commit 6359ee255f4c5ad63bbf22b5561855b1905ef855 Author: dev6-ai Date: Sun Aug 23 20:19:25 2026 -0400 PI coding agent source (initial) diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..81c1a89 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5209 @@ +# Changelog + +## [0.83.0] - 2026-07-29 + +### New Features + +- **Credential export for external clients** — `pi auth print-api-key` and `pi auth print-bearer-token` export configured credentials with automatic OAuth refresh and minimum-validity enforcement. +- **Headless OpenRouter sign-in** — Complete `/login` over SSH by pasting the redirect URL or authorization code when the loopback callback is unavailable. See [OpenRouter](docs/providers.md#openrouter). +- **Claude Opus 5 on GitHub Copilot** — Use Claude Opus 5 through GitHub Copilot with adaptive thinking and a 1M context window. See [GitHub Copilot](docs/providers.md#github-copilot). + +### Breaking Changes + +- Upgraded bundled TypeBox aliases to 1.3.7, removing deprecated APIs including `Type.Base`, `Type.Awaited`, `Type.Promise`, `Type.AsyncIterator`, `Type.Iterator`, `Type.Options`, and `Value.Mutate`, while fixing compiled validation of nullable array tool arguments. Extensions using removed APIs must migrate to supported TypeBox APIs. See [Package Dependencies](docs/packages.md#dependencies) ([#7243](https://github.com/earendil-works/pi/pull/7243) by [@petrroll](https://github.com/petrroll)). + +### Added + +- Added `pi auth print-api-key` and `pi auth print-bearer-token` commands for exporting configured credentials to external clients, including automatic OAuth refresh and configurable minimum token validity ([#7168](https://github.com/earendil-works/pi/pull/7168)). +- Exposed the session's resolved model scope as `ctx.scopedModels` to extensions. See [Extension Context](docs/extensions.md#ctxmodelregistry--ctxmodel--ctxthinkinglevel--ctxscopedmodels) ([#7191](https://github.com/earendil-works/pi/pull/7191) by [@pungggi](https://github.com/pungggi), [#7215](https://github.com/earendil-works/pi/pull/7215)). +- Added inherited per-request `fetch` injection for supported text and image provider transports. +- Added the inherited `"pending"` stop reason for partial streaming messages. See [Custom Provider Stream Pattern](docs/custom-provider.md#stream-pattern) ([#7151](https://github.com/earendil-works/pi/pull/7151) by [@lucasmeijer](https://github.com/lucasmeijer)). +- Added inherited raw provider stop reasons across Google, Anthropic, Amazon Bedrock, Mistral, and OpenAI streams; unmapped terminal reasons now surface as provider errors instead of successful stops ([#7272](https://github.com/earendil-works/pi/pull/7272)). +- Added manual redirect URL and authorization-code entry to OpenRouter login for remote and headless environments. See [OpenRouter](docs/providers.md#openrouter) ([#7114](https://github.com/earendil-works/pi/pull/7114) by [@rgarcia](https://github.com/rgarcia)). +- Added inherited Claude Opus 5 support for GitHub Copilot with adaptive thinking and a 1M context window. See [GitHub Copilot](docs/providers.md#github-copilot) ([#7158](https://github.com/earendil-works/pi/pull/7158) by [@jay-aye-see-kay](https://github.com/jay-aye-see-kay)). + +### Changed + +- Changed inherited OAuth credential resolution to refresh tokens with less than five minutes of validity remaining instead of waiting until expiration ([#7168](https://github.com/earendil-works/pi/pull/7168)). + +### Fixed + +- Added a status line when the tool output expansion is toggled ([#7180](https://github.com/earendil-works/pi/issues/7180)). +- Fixed file-backed `SYSTEM.md` and `APPEND_SYSTEM.md` prompts being omitted from the interactive startup context listing. See [System Prompt Files](docs/usage.md#system-prompt-files) ([#7096](https://github.com/earendil-works/pi/issues/7096)). +- Fixed context files loading twice when a linked Git worktree is nested under its main repository. See [Context Files](docs/usage.md#context-files) ([#7221](https://github.com/earendil-works/pi/pull/7221) by [@arajkumar](https://github.com/arajkumar)). +- Fixed llama.cpp streamed responses reporting zero token usage and leaving session context accounting empty. See [llama.cpp](docs/llama-cpp.md) ([#7258](https://github.com/earendil-works/pi/pull/7258) by [@SteveImmanuel](https://github.com/SteveImmanuel)). +- Fixed session replacement and committed tree navigation during an active response to abort and persist the outgoing turn instead of leaving dangling tool calls. See [Sessions](docs/usage.md#sessions) ([#7022](https://github.com/earendil-works/pi/pull/7022) by [@tmustier](https://github.com/tmustier)). +- Fixed failed Git package installs leaving partial directories that blocked clean retries. See [Install and Manage](docs/packages.md#install-and-manage) ([#7210](https://github.com/earendil-works/pi/pull/7210) by [@haoqixu](https://github.com/haoqixu)). +- Fixed the `/model` selector retaining a stale selection while filtering instead of highlighting the top match ([#7211](https://github.com/earendil-works/pi/pull/7211) by [@christianbasch](https://github.com/christianbasch)). +- Fixed direct RPC bash commands bypassing extension `user_bash` handlers. See [User Bash Events](docs/extensions.md#user-bash-events) ([#7214](https://github.com/earendil-works/pi/pull/7214)). +- Fixed skills, prompts, and themes losing package source metadata after extensions reload resources. See [Resource Events](docs/extensions.md#resource-events) ([#6968](https://github.com/earendil-works/pi/issues/6968)). +- Fixed cancellation of concurrently running user bash commands so every active command is aborted ([#7103](https://github.com/earendil-works/pi/pull/7103) by [@yzhg1983](https://github.com/yzhg1983)). +- Fixed duplicate messages appearing when extensions switch sessions during interactive startup ([#7110](https://github.com/earendil-works/pi/pull/7110) by [@yzhg1983](https://github.com/yzhg1983)). +- Fixed inherited Qwen Token Plan reasoning models to send their service-specific thinking controls and supported reasoning-effort levels ([#6951](https://github.com/earendil-works/pi/issues/6951), [#6998](https://github.com/earendil-works/pi/issues/6998)). +- Fixed inherited Z.AI output limits being sent through an unsupported parameter. See [Providers](docs/providers.md) ([#7174](https://github.com/earendil-works/pi/pull/7174) by [@HyeokjaeLee](https://github.com/HyeokjaeLee)). +- Fixed explicitly configured Amazon Bedrock profiles being overridden by ambient AWS access keys. See [Amazon Bedrock](docs/providers.md#amazon-bedrock) ([#7176](https://github.com/earendil-works/pi/pull/7176) by [@christianbasch](https://github.com/christianbasch)). +- Fixed inherited image fallback paths overflowing narrow terminals, shortened home-directory paths, and made absolute paths clickable when terminal hyperlinks are available ([#7262](https://github.com/earendil-works/pi/pull/7262)). +- Fixed inherited OpenAI-compatible tool calls losing their function arguments when malformed deltas also contain an empty `custom` object ([#7288](https://github.com/earendil-works/pi/pull/7288) by [@sunnyyoung](https://github.com/sunnyyoung)). + +## [0.82.1] - 2026-07-25 + +### New Features + +- **Claude Opus 5** — Available on Anthropic and Amazon Bedrock with adaptive thinking (including `xhigh`), inference profiles, and prompt caching. See [Providers](docs/providers.md#api-keys). +- **Anthropic gateway bearer auth** — `ANTHROPIC_AUTH_TOKEN` authenticates against Anthropic-compatible gateways that require `Authorization: Bearer`, including compaction and branch summaries. See [Environment Variables or Auth File](docs/providers.md#environment-variables-or-auth-file). +- **Faster, more resilient model catalogs** — pi.dev catalogs revalidate with `If-None-Match` so unchanged providers answer with an empty `304`, and llama.cpp models stay listed across restarts. See [llama.cpp](docs/llama-cpp.md). + +### Added + +- Exposed the `outputPad` setting to custom message renderers. See [Extensions](docs/extensions.md) ([#7045](https://github.com/earendil-works/pi/pull/7045) by [@xl0](https://github.com/xl0)). +- Added inherited `ANTHROPIC_AUTH_TOKEN` bearer authentication for Anthropic-compatible gateways. See [Providers](docs/providers.md#environment-variables-or-auth-file) ([#5871](https://github.com/earendil-works/pi/issues/5871)). +- Added inherited Claude Opus 5 support for Anthropic and Amazon Bedrock with adaptive thinking, inference profiles, prompt caching, and preserved AWS validation messages ([#7081](https://github.com/earendil-works/pi/pull/7081) by [@unexge](https://github.com/unexge), [#7083](https://github.com/earendil-works/pi/pull/7083) by [@davidbrai](https://github.com/davidbrai)). + +### Changed + +- Changed pi.dev model catalog refreshes to revalidate with `If-None-Match`, so unchanged provider catalogs answer with an empty `304` instead of a full download. +- Changed inherited Radius OAuth device authorization, token exchange, and refresh requests to use the configured gateway directly. +- Changed inherited model loading errors to append the underlying cause, so auth failures such as `OAuth refresh failed for openai-codex` report the provider response instead of a bare wrapper message. + +### Fixed + +- Fixed compaction and branch summaries for providers whose authentication resolves entirely to request headers ([#5871](https://github.com/earendil-works/pi/issues/5871)) +- Fixed unavailable scoped models being hidden from `/models`, allowing them to be removed without editing settings manually ([#6949](https://github.com/earendil-works/pi/issues/6949), [#7032](https://github.com/earendil-works/pi/pull/7032) by [@christianklotz](https://github.com/christianklotz)). +- Fixed startup context file discovery to skip directories that match context file names such as `AGENTS.md`, which produced `EISDIR` warnings ([#7106](https://github.com/earendil-works/pi/pull/7106) by [@mrexodia](https://github.com/mrexodia)). +- Fixed the llama.cpp extension to persist its model catalog, so llama.cpp models stay listed before the first successful refresh. See [llama.cpp](docs/llama-cpp.md) ([#7072](https://github.com/earendil-works/pi/pull/7072) by [@davidbrai](https://github.com/davidbrai)). + +## [0.82.0] - 2026-07-24 + +### New Features + +- **Constrained tool sampling** — Tools can prefer or require strict JSON Schema sampling or use OpenAI Lark/regex grammars, with model capability metadata preventing unsupported requests. See [Constrained Sampling for Tools](../ai/README.md#constrained-sampling-for-tools). +- **OpenRouter and Kimi Code sign-in** — Use `/login` to authorize OpenRouter or a Kimi Code subscription without manually configuring API keys. See [OpenRouter](docs/providers.md#openrouter). +- **Session-aware, streaming bash integrations** — Bash tools receive current session/model metadata, while direct RPC bash commands stream correlated output. See [Bash Tool Session Environment](docs/environment-variables.md#bash-tool-session-environment) and [RPC bash events](docs/rpc.md#bash_execution_update). + +### Added + +- Added inherited `Tool.constrainedSampling` with strict JSON Schema (`prefer`/`require`) and OpenAI Lark/regex grammar variants across OpenAI, Anthropic, Amazon Bedrock, Google Gemini, and Mistral. See [Constrained Sampling for Tools](../ai/README.md#constrained-sampling-for-tools). +- Added inherited `supportsGrammarTools` and `supportsStrictTools` compatibility flags, expanded `supportsStrictMode` coverage, and generated model capability metadata to gate constrained sampling. +- Added inherited Kimi Code subscription OAuth login for the Kimi For Coding provider, including device authorization and automatic token refresh ([#6935](https://github.com/earendil-works/pi/pull/6935) by [@zaycruz](https://github.com/zaycruz)). +- Added inherited OpenRouter OAuth PKCE login through `/login`, minting a user-controlled API key. See [OpenRouter](docs/providers.md#openrouter) ([#6927](https://github.com/earendil-works/pi/pull/6927) by [@rsaryev](https://github.com/rsaryev)). +- Exposed `PI_SESSION_ID`, `PI_SESSION_FILE`, `PI_PROVIDER`, `PI_MODEL`, and `PI_REASONING_LEVEL` to commands run by built-in and factory-created bash tools. See [Bash Tool Session Environment](docs/environment-variables.md#bash-tool-session-environment). +- Added streaming `bash_execution_update` events for direct RPC bash commands, correlated with request IDs. See [RPC bash events](docs/rpc.md#bash_execution_update) ([#6971](https://github.com/earendil-works/pi/pull/6971) by [@ananthakumaran](https://github.com/ananthakumaran)). + +### Changed + +- Changed inherited generated model catalogs to expose only provider-verified reasoning effort levels from models.dev ([#6928](https://github.com/earendil-works/pi/pull/6928) by [@davidbrai](https://github.com/davidbrai)). + +### Fixed + +- Fixed inherited DNS lookup failures such as `getaddrinfo`, `ENOTFOUND`, and `EAI_AGAIN` to trigger automatic assistant retries ([#6946](https://github.com/earendil-works/pi/pull/6946) by [@christianklotz](https://github.com/christianklotz)). +- Fixed inherited OpenRouter Anthropic cache breakpoints to advance through tool results and enabled cache control for `~anthropic/*-latest` aliases ([#6941](https://github.com/earendil-works/pi/pull/6941) by [@mteam88](https://github.com/mteam88)). +- Fixed inherited OpenAI Codex WebSocket sessions to retry once without a missing previous-response continuation after `previous_response_not_found` errors ([#6955](https://github.com/earendil-works/pi/pull/6955) by [@davidbrai](https://github.com/davidbrai)). +- Fixed TUI debug and crash logs to respect custom agent directories instead of always writing under `~/.pi/agent` ([#6958](https://github.com/earendil-works/pi/pull/6958) by [@davidbrai](https://github.com/davidbrai)). +- Fixed slow Ctrl+G external-editor startup when the system temporary directory contains many entries ([#6903](https://github.com/earendil-works/pi/pull/6903) by [@christianklotz](https://github.com/christianklotz)). +- Fixed startup resource display to preserve relative paths for sibling npm extensions loaded by a package ([#6964](https://github.com/earendil-works/pi/pull/6964) by [@davidbrai](https://github.com/davidbrai)). +- Fixed compaction and branch-summary requests to use fresh routing session IDs with prompt caching disabled where supported ([#6618](https://github.com/earendil-works/pi/pull/6618) by [@tmustier](https://github.com/tmustier)). +- Fixed explicit self-updates when `PI_SKIP_VERSION_CHECK` is set ([#6977](https://github.com/earendil-works/pi/issues/6977)). +- Fixed scoped model IDs containing brackets to resolve as literal exact matches before glob matching ([#6210](https://github.com/earendil-works/pi/issues/6210)). +- Fixed inherited OpenAI and Anthropic provider retry waits to honor abort signals and configured delay limits ([#6980](https://github.com/earendil-works/pi/pull/6980) by [@petrroll](https://github.com/petrroll)). +- Fixed fresh installs from preferring bundled model catalogs over newer remote catalogs because package file mtimes were newer ([#7016](https://github.com/earendil-works/pi/pull/7016) by [@davidbrai](https://github.com/davidbrai)). +- Fixed inherited editor scroll indicators overflowing narrow terminals ([#7015](https://github.com/earendil-works/pi/pull/7015) by [@christianklotz](https://github.com/christianklotz)). +- Fixed llama.cpp models to use the loaded context window as their output token limit instead of capping it at 16K ([#7034](https://github.com/earendil-works/pi/pull/7034) by [@christianklotz](https://github.com/christianklotz)). +- Fixed release source archives to include the generated provider model data used to build standalone binaries. +- Updated the packaged `protobufjs` dependency to 7.6.5 to address GHSA-j3f2-48v5-ccww ([#7005](https://github.com/earendil-works/pi/issues/7005)). +- Fixed `/copy` on Wayland to fall back to X11 or OSC 52 when `wl-copy` fails ([#7009](https://github.com/earendil-works/pi/pull/7009) by [@rkfshakti](https://github.com/rkfshakti)). +- Fixed `/model` to reload updated `models.json` configuration when opening the model picker ([#6999](https://github.com/earendil-works/pi/issues/6999)). + +## [0.81.1] - 2026-07-21 + +### New Features + +- **Verifiable release source archives** — GitHub releases now include deterministic, checksummed source archives with instructions for rebuilding standalone binaries. See [Building standalone binaries from release source](../../README.md#building-standalone-binaries-from-release-source). +- **Resilient compaction and branch summaries** — Transient provider failures now follow the configured retry policy, with retry lifecycle events available to interactive, JSON, RPC, and SDK consumers. See [Compaction & Branch Summarization](docs/compaction.md) and [RPC retry events](docs/rpc.md#summarization_retry_scheduled--summarization_retry_attempt_start--summarization_retry_finished). + +### Added + +- Added deterministic, checksummed source archives to GitHub releases with documented standalone binary rebuild instructions ([#6913](https://github.com/earendil-works/pi/pull/6913) by [@christianklotz](https://github.com/christianklotz)). + +### Fixed + +- Fixed compaction and branch summarization to retry transient provider failures using the configured retry policy, with retry lifecycle events exposed to interactive, JSON, RPC, and SDK consumers ([#6901](https://github.com/earendil-works/pi/pull/6901) by [@davidbrai](https://github.com/davidbrai)). +- Fixed interactive startup waiting for background model catalog refresh while computing the footer provider count. +- Restored the default stream fallback for extensions using the pre-0.81 agent-core API ([#6915](https://github.com/earendil-works/pi/issues/6915)). +- Fixed inherited Kimi K3 models from Moonshot AI and Moonshot AI China to use the OpenAI thinking format and expose reasoning effort support. + +## [0.81.0] - 2026-07-21 + +### New Features + +- **Local llama.cpp model management** — Connect to a llama.cpp router, search and download Hugging Face models, and explicitly load or unload models with live progress. See [llama.cpp](docs/llama-cpp.md). +- **Full provider extensions** — Extensions can register complete pi-ai providers with authentication, model refresh, filtering, and custom streaming. See [Register New Provider](docs/custom-provider.md#register-new-provider). +- **Qwen Token Plan providers** — Use the built-in international and China subscription providers with regional endpoints and API-key authentication. See [API Keys](docs/providers.md#api-keys). +- **Expanded usage accounting** — Tool, compaction, and branch-summary usage is persisted and included in session totals. See [Compaction & Branch Summarization](docs/compaction.md). + +### Added + +- Added Qwen Token Plan and Qwen Token Plan China to built-in provider setup, default model resolution, and provider documentation ([#6858](https://github.com/earendil-works/pi/pull/6858) by [@QuintinShaw](https://github.com/QuintinShaw)). +- Added the `get_available_thinking_levels` RPC command and `RpcClient.getAvailableThinkingLevels()` method ([#6865](https://github.com/earendil-works/pi/pull/6865) by [@cristinaponcela](https://github.com/cristinaponcela)). +- Exported message and tool execution lifecycle event types from the package root ([#6772](https://github.com/earendil-works/pi/pull/6772) by [@davidbrai](https://github.com/davidbrai)). +- Added built-in llama.cpp router support with `/login` connection setup and `/llama` Hugging Face model search and downloads, explicit loading, unloading, and live progress. See [llama.cpp](docs/llama-cpp.md). +- Added extension registration for complete pi-ai providers, including native authentication, model refresh, filtering, and streaming behavior. +- Added usage accounting for tools, compaction, and branch summaries in persisted sessions, footer totals, and session statistics ([#6671](https://github.com/earendil-works/pi/pull/6671) by [@davidbrai](https://github.com/davidbrai)). + +### Fixed + +- Updated the packaged `brace-expansion` dependency to 5.0.7 ([#6896](https://github.com/earendil-works/pi/pull/6896) by [@davidbrai](https://github.com/davidbrai)). +- Fixed persisted remote model catalogs from overriding newer bundled catalogs after an upgrade. +- Fixed inherited stored API-key credentials to apply their provider-scoped `env` values, including Amazon Bedrock profiles ([#6864](https://github.com/earendil-works/pi/pull/6864) by [@cristinaponcela](https://github.com/cristinaponcela)). +- Fixed inherited OpenAI-compatible cross-provider replay to keep tool call IDs unique when multiple calls share a provider call ID ([#6854](https://github.com/earendil-works/pi/pull/6854) by [@cristinaponcela](https://github.com/cristinaponcela)). +- Fixed inherited Kimi K3 thinking levels to expose low, high, and max, and normalized the `k2p7` alias to `kimi-for-coding`. +- Fixed inherited OpenCode Go models routed through the OpenAI Responses API. +- Fixed inherited `pi-ai` package metadata to avoid repeated consumer lockfile changes ([#6812](https://github.com/earendil-works/pi/pull/6812) by [@jmfederico](https://github.com/jmfederico)). +- Fixed inherited terminal shutdown to clear the editor's inverted software cursor before restoring the hardware cursor ([#6790](https://github.com/earendil-works/pi/pull/6790) by [@dam9000](https://github.com/dam9000)). +- Fixed inherited ANSI-aware text wrapping to recognize CRLF and CR line endings while preserving styles ([#6764](https://github.com/earendil-works/pi/pull/6764) by [@xz-dev](https://github.com/xz-dev)). +- Fixed inherited editor paste registry corruption after deleting and undoing paste markers, preventing literal or mismatched paste markers in submitted prompts ([#6844](https://github.com/earendil-works/pi/issues/6844)). +- Fixed sessionless OpenAI Codex WebSocket requests to use UUIDv7 request IDs ([#6834](https://github.com/earendil-works/pi/pull/6834) by [@xl0](https://github.com/xl0)). +- Fixed inherited GPT-5.6 Codex models to default to the 272K context window, avoiding automatic long-context pricing ([#6853](https://github.com/earendil-works/pi/pull/6853) by [@aadishv](https://github.com/aadishv)). +- Fixed messages queued during compaction to preserve steering and follow-up delivery behavior ([#6730](https://github.com/earendil-works/pi/pull/6730) by [@dannote](https://github.com/dannote)). +- Fixed read tool errors being syntax-highlighted as if they were file contents ([#6731](https://github.com/earendil-works/pi/pull/6731) by [@dannote](https://github.com/dannote)). +- Fixed llama.cpp router download progress updates and removed redundant wording from model action confirmations. +- Moved automatic model catalog network refresh out of startup initialization and into the running interactive and RPC modes. +- Fixed persisted sessions being read and parsed twice when opened, reducing startup latency for large sessions ([#6793](https://github.com/earendil-works/pi/issues/6793)). +- Fixed prompt-template defaults for all arguments (`${@:-default}` and `${ARGUMENTS:-default}`) ([#6695](https://github.com/earendil-works/pi/issues/6695)). +- Fixed obsolete custom UI, custom tool, and custom editor examples in the extension documentation ([#6735](https://github.com/earendil-works/pi/issues/6735)). +- Fixed Kimi Coding sessions to show API-equivalent implied costs with the subscription indicator. +- Fixed OpenAI Responses early stream endings to trigger automatic retry instead of ending the agent run ([#6727](https://github.com/earendil-works/pi/issues/6727)). + +## [0.80.10] - 2026-07-16 + +### New Features + +- **Kimi Coding thinking compatibility** — Kimi Coding models now use adaptive thinking correctly; K3 exposes its supported `max` level and supports replaying empty-signature thinking blocks. See [Kimi For Coding setup](docs/providers.md#api-keys) and [Model Options](docs/usage.md#model-options). + +### Fixed + +- Fixed inherited Kimi Coding requests to use Anthropic adaptive thinking effort without token budgets, and enabled empty thinking signatures for K3 and `kimi-for-coding`. +- Fixed inherited Kimi K3 pricing metadata for Moonshot AI and Moonshot AI China. +- Fixed inherited Kimi Coding K3 thinking-level metadata to expose only the supported `max` level ([#6737](https://github.com/earendil-works/pi/issues/6737)). +- Fixed inherited catalog generation restoring xAI models removed in 0.80.9 ([#6736](https://github.com/earendil-works/pi/issues/6736)). + +## [0.80.9] - 2026-07-16 + +### New Features + +- **Kimi K3 and deferred tool loading** — Use Kimi K3 across built-in providers, including progressive extension tool activation through Kimi’s native protocol. See [Dynamic Tool Loading](docs/extensions.md#dynamic-tool-loading), [OpenAI Compatibility](docs/models.md#openai-compatibility), and the [`kimi-deferred-tools.ts`](examples/extensions/kimi-deferred-tools.ts) example. + +### Added + +- Added inherited Kimi K3 support for Kimi Coding, Moonshot AI, Moonshot AI China, OpenRouter, and Vercel AI Gateway. +- Added Kimi deferred tool loading for extension-driven tool activation. See [Dynamic Tool Loading](docs/extensions.md#dynamic-tool-loading), [OpenAI Compatibility](docs/models.md#openai-compatibility), and the [`kimi-deferred-tools.ts`](examples/extensions/kimi-deferred-tools.ts) example. + +### Changed + +- Changed xAI login to use a prefilled device-authorization link labeled “Sign in with SuperGrok or X Premium,” and changed the default xAI model to Grok 4.5 ([#6734](https://github.com/earendil-works/pi-mono/pull/6734) by [@Jaaneek](https://github.com/Jaaneek)). + +### Fixed + +- Fixed inherited Kimi K3 output limits for Vercel AI Gateway and OpenRouter models. +- Fixed cloning or forking a session before its first assistant response to explain that the session must be saved first. + +### Removed + +- Removed Grok 3, Grok 3 Fast, Grok 4.20 variants, and Grok Code Fast 1 from the built-in xAI model catalog ([#6734](https://github.com/earendil-works/pi-mono/pull/6734) by [@Jaaneek](https://github.com/Jaaneek)). + +## [0.80.8] - 2026-07-16 + +### New Features + +- **Unified model runtime and provider authentication** — `ModelRuntime` centralizes model configuration, provider-owned `/login`, and dynamic provider catalogs. See [Providers](docs/providers.md). +- **Live model catalog refresh** — `/model` refreshes configured providers in the background, and `pi update --models` forces an immediate refresh. See [Install and Manage](docs/packages.md#install-and-manage). +- **xAI device-code OAuth and Grok 4.5 Responses support** — Sign in to xAI with a device code and use Grok 4.5 with low, medium, or high thinking. See [xAI](docs/providers.md#xai-grokx-subscription). + +### Breaking Changes + +- Replaced the SDK's `CreateAgentSessionOptions.authStorage` and `modelRegistry` options with the async `modelRuntime` option. `AuthStorage` and its storage backends are no longer exported; use `ModelRuntime` (or a custom pi-ai `CredentialStore`), or `readStoredCredential()` for one-off reads of auth.json. +- Removed redundant `ModelRuntime.getAll()`, `find()`, `getSnapshot()`, and `getAuthOptions()` projections. Use the pi-ai `Models` methods `getModels()`, `getModel()`, `getProviders()`, and `checkAuth()` directly. +- Replaced SDK request-auth assembly through `ModelRegistry.getApiKeyAndHeaders()` with `ModelRuntime.getAuth()`. Passing a provider ID returns provider-scoped auth; passing a model also resolves built-in, `models.json`, and extension model headers. +- Changed extension-facing `ModelRegistry.refresh()` from synchronous `void` to `Promise` because `models.json` loading is asynchronous. Extensions must await it before making synchronous registry reads. +- Moved canonical dynamic catalog refresh to async `ModelRuntime.refresh()`/pi-ai `Models.refresh()`. Legacy extension OAuth `modifyModels` remains supported as a synchronous compatibility projection after credential initialization. + +### Added + +- Added `ModelRuntime` as the canonical async SDK and internal model/auth facade while preserving the synchronous extension-facing `ModelRegistry` API. `ModelRuntime.create()` accepts any pi-ai `CredentialStore` through its `credentials` option. +- Added provider-owned `/login` discovery directly from registered pi-ai providers, including ambient auth status and informational links. +- Added file-backed dynamic catalogs in `models-store.json`, per-provider pi.dev catalog overlays, and Radius gateway support including offline migration from legacy credential-cached catalogs. +- Added extension provider `refreshModels(context)` support for dynamic model discovery with optional provider-controlled persistence. +- Added `pi update --models` to force an immediate model catalog refresh without updating pi or extensions. +- Added inherited xAI device-code OAuth login and Grok 4.5 OpenAI Responses support, with low, medium, and high thinking levels ([#6651](https://github.com/earendil-works/pi-mono/pull/6651) by [@Jaaneek](https://github.com/Jaaneek)). + +### Changed + +- Changed `ModelRuntime` to compose built-in providers, immutable `models.json` configuration, and extension overlays through ad-hoc pi-ai provider methods. +- Changed `ModelRuntime` to own final request assembly: `getAuth(model)` includes configured model headers, stream methods resolve auth once, and `before_provider_headers` runs as the Models-only header transform before provider dispatch. +- Changed `/model` to render the current model snapshot immediately, refresh configured providers in the background, and update the open selector with partial results or timeout errors. + +### Fixed + +- Fixed configured-provider catalog refresh to parse pi.dev's model-ID keyed responses, throttle checks to once per four hours, send the versioned pi user agent, treat unimplemented routes as unavailable overlays, and show concise refresh status in `/model`. +- Fixed adjacent assistant thinking blocks to render as one thinking section. +- Fixed inherited OpenAI Codex session IDs longer than 64 characters to meet the API limit ([#6630](https://github.com/earendil-works/pi-mono/issues/6630)). +- Fixed inherited terminal output to normalize tab characters consistently ([#6697](https://github.com/earendil-works/pi-mono/pull/6697) by [@xz-dev](https://github.com/xz-dev)). +- Fixed the Windows terminal title after checking npm packages ([#6629](https://github.com/earendil-works/pi-mono/issues/6629)). +- Fixed Bun standalone binaries to bundle OAuth adapters for interactive logins. + +## [0.80.7] - 2026-07-14 + +### Breaking Changes + +- Removed the `openai-responses` `compat.sendSessionIdHeader` flag from `models.json`. Session-affinity behavior is now controlled by `compat.sessionAffinityFormat` (`"openai"`, `"openai-nosession"`, or `"openrouter"`). Replace `sendSessionIdHeader: false` with `sessionAffinityFormat: "openai-nosession"` ([#6496](https://github.com/earendil-works/pi-mono/pull/6496) by [@petrroll](https://github.com/petrroll)). + +### New Features + +- **Cache-friendly dynamic tool loading** - Extensions can add tools during execution while supported Anthropic and OpenAI Responses models preserve prompt-cache prefixes. See [Dynamic Tool Loading](docs/extensions.md#dynamic-tool-loading). +- **Message copy shortcut** - `Ctrl+X` copies the last assistant message in the transcript or the selected message in `/tree`, making older and branched messages directly copyable. See [Display and Message Queue](docs/keybindings.md#display-and-message-queue). +- **Fable 5 `xhigh` and `max` thinking** - Native `xhigh` and `max` thinking levels are available across generated provider catalogs. See [Model Options](docs/usage.md#model-options). + +### Added + +- Added cache-friendly dynamic tool loading for extension tools activated by tool results. Supported Anthropic and OpenAI Responses models load definitions where they become available, preserving the cached prompt prefix. See [Dynamic Tool Loading](docs/extensions.md#dynamic-tool-loading) ([#6474](https://github.com/earendil-works/pi-mono/pull/6474)). +- Added inherited native `xhigh` and `max` thinking levels for Claude Fable 5 across all generated provider catalogs ([#6490](https://github.com/earendil-works/pi-mono/pull/6490) by [@davidbrai](https://github.com/davidbrai)). +- Added `Ctrl+X` to copy the last assistant message, or the selected message in `/tree`. +- Added inherited `toolChoice` support for OpenAI and Codex Responses, including required and named tool selection ([#6588](https://github.com/earendil-works/pi-mono/pull/6588) by [@xl0](https://github.com/xl0)). + +### Fixed + +- Fixed inherited OpenRouter model context windows to use the top provider's actual context length ([#6481](https://github.com/earendil-works/pi-mono/pull/6481) by [@davidbrai](https://github.com/davidbrai)). +- Fixed inherited OpenRouter OpenAI-compatible session IDs to use the `x-session-id` header instead of OpenAI-specific session-affinity fields ([#6496](https://github.com/earendil-works/pi-mono/pull/6496) by [@petrroll](https://github.com/petrroll)). +- Fixed `Ctrl+V` to paste clipboard text when the pasteboard does not contain an image. +- Fixed `/login amazon-bedrock` to prompt for and save a Bedrock API key instead of only displaying ambient AWS credential setup instructions. +- Fixed inherited Amazon Bedrock ambient AWS credentials to keep using SigV4 authentication, including for custom model IDs ([#6532](https://github.com/earendil-works/pi-mono/pull/6532) by [@ribelo](https://github.com/ribelo)). +- Fixed inherited Cloudflare Workers AI and AI Gateway authentication to use ambient account and gateway IDs when stored credentials contain only an API key ([#6292](https://github.com/earendil-works/pi-mono/pull/6292) by [@markphelps](https://github.com/markphelps)). +- Fixed inherited legacy terminal decoding for Alt+symbol key combinations such as `Alt+,` and `Alt+.` ([#6523](https://github.com/earendil-works/pi-mono/pull/6523) by [@ribelo](https://github.com/ribelo)). +- Fixed the GitHub Copilot `mai-code-1-flash-picker` model to route through the `/responses` endpoint ([#6544](https://github.com/earendil-works/pi-mono/pull/6544) by [@petrroll](https://github.com/petrroll)). +- Fixed branch summaries to work with providers that use ambient authentication instead of API keys ([#6595](https://github.com/earendil-works/pi-mono/pull/6595) by [@davidbrai](https://github.com/davidbrai)). +- Fixed inherited Amazon Bedrock errors to report unhandled provider stop reasons instead of only `An unknown error occurred` ([#6598](https://github.com/earendil-works/pi-mono/pull/6598) by [@davidbrai](https://github.com/davidbrai)). +- Fixed npm package removal when installed packages have conflicting peer dependencies ([#6604](https://github.com/earendil-works/pi-mono/pull/6604) by [@davidbrai](https://github.com/davidbrai)). +- Fixed inherited Azure OpenAI Responses reasoning replay when `encrypted_content` appears only in the terminal response event ([#6608](https://github.com/earendil-works/pi-mono/pull/6608) by [@davidbrai](https://github.com/davidbrai)). +- Fixed inherited Anthropic-compatible proxies that omit `usage` from `message_delta` events ([#6611](https://github.com/earendil-works/pi-mono/pull/6611) by [@davidbrai](https://github.com/davidbrai)). +- Fixed inherited OpenCode OpenAI Responses models to omit the unsupported `session-id` header while preserving other cache-affinity data ([#6645](https://github.com/earendil-works/pi-mono/pull/6645) by [@davidbrai](https://github.com/davidbrai)). +- Fixed system prompt cache invalidation across dates by removing the current date from the default prompt ([#6621](https://github.com/earendil-works/pi/issues/6621)). + +## [0.80.6] - 2026-07-09 + +### New Features + +- **`max` thinking level** - New opt-in thinking level above `xhigh`, natively supported on GPT-5.6 and adaptive Claude models, available across CLI (`--thinking max`), SDK, RPC, and model selection. Custom themes can define `thinkingMax`. See [CLI Reference](docs/usage.md#cli-reference). +- **Input-based pricing tiers** - Request-wide input-token pricing tiers for accurate long-context cost accounting (e.g. GPT-5.4/5.5/5.6 long-context rates), also configurable for custom models in `models.json` and `modelOverrides`. See [Model Configuration](docs/models.md#model-configuration). + +### Added + +- Added the opt-in `max` thinking level across CLI, SDK, RPC, model selection, and themes. Custom themes can define `thinkingMax`; existing themes fall back to `thinkingXhigh`. +- Added request-wide input-token pricing tiers to custom model costs in `models.json`, `modelOverrides`, and extension-registered providers. +- Added `~` (home directory) expansion for the `shellPath` setting ([#6470](https://github.com/earendil-works/pi/pull/6470) by [@aaronkyriesenbach](https://github.com/aaronkyriesenbach)). + +### Fixed + +- Fixed inherited post-compaction output-token budgeting to ignore stale assistant usage from before the compaction boundary ([#6464](https://github.com/earendil-works/pi/issues/6464)). +- Fixed inherited GPT-5.4 and GPT-5.5 long-context cost accounting while retaining the intentional 272K default context limit for models that require an explicit override. +- Fixed inherited GPT-5.6 metadata to keep direct OpenAI requests in the 272K short-context tier while exposing the Codex backend's 372K context window with long-context pricing, and removed the nonexistent bare `gpt-5.6` alias. +- Fixed inherited Anthropic message conversion to preserve thinking blocks with empty thinking text but a valid signature instead of dropping them, avoiding thinking-block errors on newer Claude models ([#6457](https://github.com/earendil-works/pi/pull/6457) by [@davidbrai](https://github.com/davidbrai)). + +## [0.80.5] - 2026-07-09 + +## [0.80.4] - 2026-07-09 + +### New Features + +- **Prompt cache miss visibility** - Significant cache misses can be shown in transcripts via `showCacheMissNotices`. See [Model & Thinking](docs/settings.md#model--thinking). +- **Project-local resource configuration** - `pi config -l` and Tab switching manage global vs project-local package resources. See [Enable and Disable Resources](docs/packages.md#enable-and-disable-resources). +- **Extension lifecycle and provider hooks** - Extensions get `agent_settled`, `before_provider_headers`, entry renderers, and `InlineExtension`. See [agent_start / agent_end / agent_settled](docs/extensions.md#agent_start--agent_end--agent_settled), [before_provider_headers](docs/extensions.md#before_provider_headers), and [InlineExtension](docs/sdk.md#inlineextension). +- **New inherited model and transport support** - GPT-5.6 metadata, Copilot Claude Sonnet 5, and zstd Codex SSE transport are available through inherited provider support. See [Providers](docs/providers.md) and [Model Options](docs/usage.md#model-options). + +### Added + +- Added inherited OpenAI GPT-5.6 model metadata for `gpt-5.6`, `gpt-5.6-sol`, `gpt-5.6-terra`, and `gpt-5.6-luna`, plus verified `openai-codex` support for `gpt-5.6-sol`, `gpt-5.6-terra`, and `gpt-5.6-luna`. +- Added inherited Claude Sonnet 5 to the GitHub Copilot model catalog ([#6200](https://github.com/earendil-works/pi/issues/6200)). +- Added inherited zstd request-body compression for the OpenAI Codex Responses SSE transport. +- Added `/login ` support with provider autocomplete. +- Added public SDK exports for CLI-equivalent model and scoped-model resolution ([#6201](https://github.com/earendil-works/pi/issues/6201)). +- Added extension and RPC `agent_settled` events plus session-level idle waiting for fully settled agent runs ([#6363](https://github.com/earendil-works/pi/issues/6363)). +- Added `before_provider_headers` extension hook support for injecting provider request headers ([#6350](https://github.com/earendil-works/pi/pull/6350) by [@pmateusz](https://github.com/pmateusz)). +- Added an `InlineExtension` type for named inline extension factories ([#6267](https://github.com/earendil-works/pi/pull/6267) by [@any-victor](https://github.com/any-victor)). +- Added extension entry renderers for persisted display-only session entries that are rendered in interactive mode without being sent to the model context. +- Added project-local resource override management to `pi config`, including project mode startup with `pi config -l` and Tab switching between global and project scopes ([#6309](https://github.com/earendil-works/pi/pull/6309)). +- Added inherited `InMemorySessionStorage` and `JsonlSessionStorage` exports from the agent harness ([#6435](https://github.com/earendil-works/pi/issues/6435)). +- Added inherited custom metadata support in JSONL session headers ([#6417](https://github.com/earendil-works/pi/pull/6417) by [@ArcadiaLin](https://github.com/ArcadiaLin)). +- Added a `showCacheMissNotices` setting and `/settings` toggle for significant prompt-cache miss transcript notices. + +### Fixed + +- Fixed inherited retry classification for gRPC `ResourceExhausted` provider errors such as NVIDIA NIM transient exhaustion responses ([#6449](https://github.com/earendil-works/pi/pull/6449) by [@davidbrai](https://github.com/davidbrai)). +- Fixed inherited retry classification for Cloudflare 524 timeout responses ([#6239](https://github.com/earendil-works/pi/issues/6239)). +- Fixed inherited GitHub Copilot device-code login polling to wait before the first token poll and to honor server-provided `slow_down` intervals, avoiding incorrect failures or apparent hangs after browser authorization ([#6187](https://github.com/earendil-works/pi/issues/6187)). +- Fixed inherited OpenAI Codex WebSocket sessions to rotate cached connections before the backend's 60-minute limit, avoiding connection-limit failures on long sessions ([#6268](https://github.com/earendil-works/pi/issues/6268)). +- Fixed inherited DS4 server context overflow detection for `Prompt has ... tokens, but the configured context size is ... tokens` errors ([#6262](https://github.com/earendil-works/pi/issues/6262)). +- Fixed inherited Fireworks GLM 5.2 Fast to use the OpenAI-compatible endpoint and `thinkingLevelMap`, aligning it with GLM 5.2 ([#6195](https://github.com/earendil-works/pi/issues/6195)). +- Fixed the fork menu to ignore duplicate selection of the same entry ([#6430](https://github.com/earendil-works/pi/pull/6430) by [@davidbrai](https://github.com/davidbrai)). +- Fixed native clipboard support in Bun standalone releases ([#6418](https://github.com/earendil-works/pi/pull/6418) by [@davidbrai](https://github.com/davidbrai)). +- Fixed inherited GitHub Copilot extended context window models to use `contextWindow: 1000000`, preventing premature compaction and under-budgeting ([#6439](https://github.com/earendil-works/pi/issues/6439)). +- Fixed inherited editor paste marker accounting when paste markers are deleted or terminal state is cleared ([#6397](https://github.com/earendil-works/pi/pull/6397) by [@affanali2k3](https://github.com/affanali2k3)). +- Fixed `null` message content from imported transcripts or custom clients to normalize at ingestion boundaries instead of failing during context construction ([#6343](https://github.com/earendil-works/pi/pull/6343)). +- Fixed inherited tool calls from length-truncated assistant messages to fail instead of waiting for missing tool results ([#6285](https://github.com/earendil-works/pi/pull/6285)). +- Fixed inherited OpenAI Completions and Responses providers to send `(no tool output)` instead of `(see attached image)` when a tool result has empty text and no image content. +- Fixed inherited OpenAI Responses and Azure OpenAI Responses requests to avoid sending `max_output_tokens` values below the provider minimum ([#6265](https://github.com/earendil-works/pi/issues/6265)). +- Fixed inherited Amazon Bedrock prompt-cache points for Claude Fable 5 and Claude Sonnet 5 ([#6235](https://github.com/earendil-works/pi/issues/6235)). +- Fixed inherited Amazon Bedrock Claude 5 prompt-cache pricing metadata by removing stale fallback overrides. +- Fixed inherited OpenAI Codex user-agent construction to synchronously load Node OS metadata, avoiding a startup race that could report `pi (browser)` in Node/Bun. +- Fixed `pi update` for pnpm installations to suggest pruning pnpm's self-update cache when the executable points at a removed cached version ([#6279](https://github.com/earendil-works/pi/pull/6279) by [@rajp152k](https://github.com/rajp152k)). +- Fixed Xiaomi Token Plan model metadata to follow the upstream models.dev token-plan catalogs, removing unsupported `mimo-v2-omni` variants ([#6204](https://github.com/earendil-works/pi/issues/6204)). +- Fixed startup model selection to skip unauthenticated saved defaults so configured local custom models can be selected instead ([#6231](https://github.com/earendil-works/pi/issues/6231)). +- Fixed the question extension example to run question tool calls sequentially so multiple questions in one assistant turn remain answerable ([#6189](https://github.com/earendil-works/pi/issues/6189)). +- Fixed `/login` to report auth storage persistence failures instead of claiming credentials were saved when `auth.json` is locked ([#6223](https://github.com/earendil-works/pi/issues/6223)). +- Fixed split-turn compaction to serialize summary requests so single-concurrency local providers do not fail with 429 errors ([#5536](https://github.com/earendil-works/pi/issues/5536)). +- Fixed compaction retained-token budgeting to count context-visible custom messages ([#6326](https://github.com/earendil-works/pi/issues/6326)). +- Fixed custom session entries appended during assistant streaming to render before the live assistant message, matching persisted session order. +- Fixed non-positive or oversized bash tool timeouts to fail with a clear validation error instead of being clamped to an immediate timeout ([#6181](https://github.com/earendil-works/pi/issues/6181)). +- Fixed the edit tool schema to allow model-invented extra replacement fields instead of rejecting otherwise valid edits ([#6278](https://github.com/earendil-works/pi/issues/6278)). +- Fixed new session resets to clear cached label timestamps ([#6354](https://github.com/earendil-works/pi/issues/6354)). +- Fixed auto-retry for Bun fetch socket-drop errors reported as `socket connection was closed`, so transient provider disconnects do not end headless runs without retrying ([#6431](https://github.com/earendil-works/pi/issues/6431)). +- Fixed `models.json` `modelOverrides` to apply to extension-registered provider models ([#6367](https://github.com/earendil-works/pi/issues/6367)). +- Fixed project context file discovery to use stable parent traversal on Windows so startup no longer hangs while loading AGENTS.md or CLAUDE.md ([#6369](https://github.com/earendil-works/pi/issues/6369)). +- Fixed `--session-id` startup to warn when no existing project session has that id and pi creates a new session ([#6407](https://github.com/earendil-works/pi/issues/6407)). +- Fixed `/reload` help text and docs to consistently mention themes and context files ([#6395](https://github.com/earendil-works/pi/issues/6395)). + +### Removed + +- Removed default attribution headers from Vercel AI Gateway requests. + +## [0.80.3] - 2026-06-30 + +### New Features + +- **Anthropic Claude Sonnet 5 support** - Claude Sonnet 5 is available through inherited Anthropic-compatible and Bedrock provider catalogs with adaptive thinking enabled. See [Providers](docs/providers.md) and [Model Options](docs/usage.md#model-options). +- **Configurable output spacing** - `outputPad` controls horizontal padding for user messages, assistant messages, and thinking blocks. See [Settings](docs/settings.md#ui--display). +- **External editor configuration** - `externalEditor` lets Ctrl+G use a configured editor before `$VISUAL`/`$EDITOR` fallbacks. See [Settings](docs/settings.md#ui--display) and [Keybindings](docs/keybindings.md). +- **Richer RPC session tree access** - RPC clients can inspect session entries and tree snapshots with `get_entries` and `get_tree`. See [get_entries](docs/rpc.md#get_entries) and [get_tree](docs/rpc.md#get_tree). +- **Extension session metadata updates** - Extensions can observe session name changes through `session_info_changed`. See [session_info_changed](docs/extensions.md#session_info_changed). +- **Modern Azure Foundry endpoint support** - Azure OpenAI Responses provider setup supports current Microsoft Foundry endpoint URLs. See [Azure OpenAI](docs/providers.md#azure-openai). + +### Added + +- Added inherited Anthropic Claude Sonnet 5 model support. +- Added `get_entries` and `get_tree` RPC commands for reading session entries and tree snapshots over RPC ([#6078](https://github.com/earendil-works/pi/pull/6078) by [@geraschenko](https://github.com/geraschenko)). +- Added a package `./rpc-entry` export for launching Pi directly in RPC mode. +- Added session-name change events for extensions ([#6175](https://github.com/earendil-works/pi/pull/6175) by [@xl0](https://github.com/xl0)). +- Added inherited Azure OpenAI Responses support for modern Microsoft Foundry endpoint URLs ([#6004](https://github.com/earendil-works/pi/pull/6004) by [@gukoff](https://github.com/gukoff)). +- Added inherited `Usage.reasoning` token counts for providers that report reasoning/thinking token usage ([#6057](https://github.com/earendil-works/pi/issues/6057)). +- Added an `externalEditor` settings.json override for Ctrl+G external editor commands, with default fallbacks to Notepad on Windows and `nano` elsewhere ([#6122](https://github.com/earendil-works/pi/issues/6122)). +- Added an `outputPad` setting for user message, assistant message, and thinking horizontal padding ([#6168](https://github.com/earendil-works/pi/issues/6168)). + +### Changed + +- Changed the default OpenAI model to `gpt-5.5`. +- Changed inherited OpenAI Codex Responses SSE response-header waits to use the configured HTTP timeout instead of the previous fixed 20 second timeout, reducing false timeouts on slow connections ([#4945](https://github.com/earendil-works/pi/issues/4945)). + +### Fixed + +- Fixed inherited Claude Sonnet 5 metadata to use adaptive thinking payloads for Anthropic-compatible and Bedrock requests. +- Fixed inherited generated Xiaomi MiMo model pricing to match current pay-as-you-go pricing from models.dev ([#6138](https://github.com/earendil-works/pi/issues/6138)). +- Fixed inherited provider HTTP errors to include response bodies instead of opaque SDK messages ([#5832](https://github.com/earendil-works/pi/pull/5832) by [@stephanmck](https://github.com/stephanmck)). +- Fixed inherited `streamSimple()` max-token caps so providers that count input and output against one context window do not reject long requests ([#5595](https://github.com/earendil-works/pi/issues/5595)). +- Fixed inherited OpenAI Responses streams to preserve reasoning replay state when output items finish out of order ([#6009](https://github.com/earendil-works/pi/issues/6009)). +- Fixed inherited Z.AI preserved thinking requests to send `thinking.clear_thinking: false` when thinking is enabled, allowing replayed `reasoning_content` to participate in provider caching ([#6083](https://github.com/earendil-works/pi/issues/6083)). +- Fixed pre-prompt compaction to stop after compaction instead of continuing immediately ([#6074](https://github.com/earendil-works/pi/pull/6074) by [@yzhg1983](https://github.com/yzhg1983)). +- Fixed resource notifications to stay before messages when resuming sessions ([#6048](https://github.com/earendil-works/pi/pull/6048) by [@haoqixu](https://github.com/haoqixu)). +- Fixed startup benchmark timing output to print after TUI shutdown, preserve extension timings, and drain terminal-query replies before stopping benchmark mode ([#6030](https://github.com/earendil-works/pi/pull/6030) by [@xl0](https://github.com/xl0), [#6063](https://github.com/earendil-works/pi/pull/6063) by [@xl0](https://github.com/xl0)). +- Fixed extension tool changes to apply before the next provider request in the same agent run without dropping `before_agent_start` system-prompt overrides ([#6162](https://github.com/earendil-works/pi/issues/6162)). +- Fixed a crash when undici emits an internal client error while terminating a mid-stream HTTP response ([#6133](https://github.com/earendil-works/pi/issues/6133)). +- Fixed the compaction event regression test to cover status indicator cleanup and keep CI passing. +- Fixed interactive status indicators so ending work, retry, compaction, or branch-summary indicators no longer shrink the TUI when clear-on-shrink is enabled ([#6026](https://github.com/earendil-works/pi/pull/6026)). +- Fixed `--session` and `SessionManager.open()` to reject non-empty invalid session files without overwriting them ([#6002](https://github.com/earendil-works/pi/issues/6002)). +- Fixed user-message transcript rendering to keep visible backslashes in Markdown escape sequences such as `\"` ([#6105](https://github.com/earendil-works/pi/issues/6105)). +- Fixed assistant messages stopped by output length to show a visible incomplete-response error ([#4290](https://github.com/earendil-works/pi/issues/4290)). +- Fixed `--no-session --session-id` so ephemeral CLI runs can use deterministic session IDs for provider cache affinity ([#6070](https://github.com/earendil-works/pi/issues/6070)). +- Fixed disk BMP image files to be detected, converted to PNG, and attached through `read` and CLI `@file` inputs ([#6047](https://github.com/earendil-works/pi/issues/6047)). +- Fixed auto-retry for provider stream errors that explicitly tell callers to retry the request ([#6019](https://github.com/earendil-works/pi/issues/6019)). + +## [0.80.2] - 2026-06-23 + +### Changed + +- Changed inherited pi-ai `ApiKeyCredential` to use the `auth.json`-compatible discriminator `type: "api_key"` and provider-scoped `env` values instead of `type: "api-key"` and metadata. +- Renamed the inherited agent-core public harness shell execution options type from `ExecutionEnvExecOptions` to `ShellExecOptions`. + +### Fixed + +- Fixed inherited Anthropic-compatible custom models to use explicit compatibility metadata instead of provider-name heuristics for session-affinity headers and unsupported tool-field omissions. +- Fixed inherited request-scoped `apiKey` and `env` values to participate in provider auth resolution, so providers such as Cloudflare can derive request-specific base URLs from explicit call options ([#6021](https://github.com/earendil-works/pi/issues/6021)). +- Restored inherited temporary legacy per-API stream aliases such as `streamSimpleOpenAICompletions` on the pi-ai compat entrypoint ([#6016](https://github.com/earendil-works/pi/issues/6016), [#6017](https://github.com/earendil-works/pi/issues/6017)). +- Restored inherited runtime `detectCompat` fallback in `openai-completions` for models without explicit compat metadata ([#6020](https://github.com/earendil-works/pi/issues/6020)). + +## [0.80.1] - 2026-06-23 + +### Fixed + +- Fixed inherited Amazon Bedrock scoped `AWS_PROFILE` endpoint resolution for built-in inference profile endpoints. +- Fixed inherited Fireworks Anthropic-compatible requests to apply session-affinity and unsupported tool-field defaults for custom Fireworks models. +- Fixed inherited Together MiniMax M2.7 metadata to avoid unsupported Together reasoning toggles. + +## [0.80.0] - 2026-06-23 + +### Changed + +- Added `Ctrl+J` as a default newline keybinding alongside `Shift+Enter`. +- Renamed the displayed `zai` provider label to ZAI Coding Plan (Global) for clarity ([#5965](https://github.com/earendil-works/pi/issues/5965)). +- pi-ai's old global API (`stream`/`complete`/`completeSimple`, `getModel`/`getModels`/`getProviders`, `registerApiProvider`, `getEnvApiKey`, ...) moved off the `@earendil-works/pi-ai` root entrypoint to `@earendil-works/pi-ai/compat`. Extensions are not affected at runtime: the extension loader resolves the pi-ai root to the compat entrypoint (a strict superset), so existing extensions keep working unchanged. Extension sources that typecheck against pi-ai's published types should switch those imports to `@earendil-works/pi-ai/compat` (or migrate to the new `createModels()`/provider-factory API). The compat entrypoint and the loader alias will be removed in a future release with a migration guide. + +### Fixed + +- Fixed session names to normalize newline characters before storing or displaying labels ([#5999](https://github.com/earendil-works/pi/pull/5999) by [@haoqixu](https://github.com/haoqixu)). +- Fixed the session selector to order threaded session trees by the latest activity anywhere in each subtree ([#5784](https://github.com/earendil-works/pi/pull/5784) by [@Perlence](https://github.com/Perlence)). +- Fixed extension-related crash and startup-failure reporting to suggest restarting with `pi -ne`. +- Fixed inherited OpenAI Responses streams to fail before missing terminal events and fixed context usage and compaction estimates to ignore malformed all-zero assistant usage after truncated responses ([#5526](https://github.com/earendil-works/pi/pull/5526) by [@dmmulroy](https://github.com/dmmulroy)). +- Fixed inherited OpenAI Codex Responses WebSocket sessions to reconnect once when OpenAI's connection limit is reached before output starts ([#5973](https://github.com/earendil-works/pi/issues/5973)). +- Fixed inherited Amazon Bedrock endpoint resolution to honor scoped `AWS_PROFILE` values. +- Fixed inherited Cloudflare providers to require account/gateway configuration and route built-in compat calls through provider auth. +- Fixed provider-scoped auth environment values to reach inherited `Models`/`ImagesModels` API calls and compat API-key injection. +- Fixed inherited OpenCode Go GLM-5.2 metadata to expose `xhigh` reasoning and send the provider's max reasoning effort ([#5967](https://github.com/earendil-works/pi/issues/5967)). +- Fixed `pi --resume` to load user package themes and resolve automatic light/dark theme settings. +- Fixed `models.json` custom providers so stored credentials can satisfy auth without a redundant provider-level `apiKey` ([#5953](https://github.com/earendil-works/pi/issues/5953)). + +### Removed + +- Removed inherited selective-provider `@earendil-works/pi-ai/base` and `@earendil-works/pi-agent-core/base` entrypoints; use the root packages with explicit `Models` provider factories instead. + +## [0.79.10] - 2026-06-22 + +### New Features + +- **Extension compaction event context** - Extension `session_before_compact` and `session_compact` events now include `reason` and `willRetry`, so extensions can distinguish manual `/compact`, threshold auto-compaction, and overflow retry flows. See [session_before_compact / session_compact](docs/extensions.md#session_before_compact--session_compact) and [Custom Summarization via Extensions](docs/compaction.md#custom-summarization-via-extensions). +- **Safer update flow** - `pi update` installs the exact checked Pi version, and update notices show the changelog URL, making upgrades more predictable. See [Install and Manage](docs/packages.md#install-and-manage). + +### Added + +- Added `reason` and `willRetry` metadata to extension `session_before_compact` and `session_compact` events so extensions can distinguish manual, threshold, and overflow compaction flows ([#5962](https://github.com/earendil-works/pi/pull/5962) by [@PizzaMarinara](https://github.com/PizzaMarinara)). + +### Fixed + +- Fixed the `find` tool to respect nested git repository boundaries when parent `.gitignore` rules ignore the nested repo ([#5960](https://github.com/earendil-works/pi/issues/5960)). +- Fixed the usage docs slash command table to include `/trust` and `/import` ([#5959](https://github.com/earendil-works/pi/issues/5959)). +- Fixed inherited OpenAI-compatible streaming to preserve encrypted `reasoning_details` that arrive before matching tool call deltas ([#5114](https://github.com/earendil-works/pi/issues/5114)). +- Fixed broken TUI documentation links to the plan-mode extension example ([#5957](https://github.com/earendil-works/pi/issues/5957)). +- Fixed transient extension UI and session-start messages emitted during session replacement or reload so they remain visible, and kept reload input blocked until reload completes ([#5943](https://github.com/earendil-works/pi/issues/5943)). +- Fixed the plan-mode example to preserve active custom tools, skip the action prompt when no plan is found, and queue refinement/execution follow-ups correctly from `agent_end` ([#5940](https://github.com/earendil-works/pi/issues/5940)). +- Fixed `pi update` to install the exact version returned by the Pi update check, make `--force` reinstall that checked version, fail instead of falling back to an unversioned reinstall when no version is available, and report both the old and updated versions. +- Fixed update notifications to display the actual changelog URL as the hyperlink text. + +## [0.79.9] - 2026-06-20 + +### New Features + +- **Chat-template thinking compatibility** - OpenAI-compatible custom providers can map Pi thinking levels into `chat_template_kwargs`, enabling vLLM/Hugging Face chat-template models such as DeepSeek to use provider-native thinking controls. See [Custom Provider API Types](docs/custom-provider.md#api-types) and [OpenAI Compatibility](docs/models.md#openai-compatibility). +- **GLM-5.2 provider improvements** - GLM-5.2 now has corrected Fireworks OpenAI-compatible routing and OpenRouter `xhigh` thinking support, improving `/model` behavior and high-effort reasoning for GLM-5.2 users. See [Model Options](docs/usage.md#model-options). + +### Added + +- Added inherited configurable `chat-template` thinking support for OpenAI-compatible providers that use `chat_template_kwargs`, such as DeepSeek models behind vLLM ([#5673](https://github.com/earendil-works/pi/issues/5673)). + +### Fixed + +- Fixed inherited Fireworks GLM-5.2 metadata to use the OpenAI-compatible Chat Completions endpoint with `reasoning_effort` support ([#5923](https://github.com/earendil-works/pi/issues/5923)). +- Fixed same-directory session switches to reuse imported extension modules while preserving fresh extension instances and lifecycle events ([#5905](https://github.com/earendil-works/pi/issues/5905)). +- Fixed deep session branches taking quadratic time to build context or branch paths ([#5909](https://github.com/earendil-works/pi/issues/5909)). +- Fixed inherited OpenRouter GLM-5.2 metadata to expose `xhigh` reasoning and send OpenRouter's native `xhigh` effort ([#5770](https://github.com/earendil-works/pi/issues/5770)). +- Fixed inherited Markdown streaming code fence rendering so partial closing fences no longer make code blocks shrink or flicker while content streams ([#5846](https://github.com/earendil-works/pi/pull/5846) by [@xl0](https://github.com/xl0)). +- Fixed fuzzy `edit` matches to preserve untouched line blocks instead of rewriting the whole file through normalized content ([#5899](https://github.com/earendil-works/pi/issues/5899)). +- Fixed bash commands through legacy WSL `bash.exe` to pass scripts over stdin so shell variables expand in the target bash ([#5893](https://github.com/earendil-works/pi/issues/5893)). +- Fixed `/model` to hide GitHub Copilot models that are unavailable to the authenticated account ([#5897](https://github.com/earendil-works/pi/issues/5897)). +- Fixed `/model` selector search to rank exact provider-prefixed matches before proxy-provider model ID matches ([#5892](https://github.com/earendil-works/pi/issues/5892)). + +## [0.79.8] - 2026-06-19 + +### New Features + +- **Selective provider base entry points** - SDK users can pair `@earendil-works/pi-ai/base` and `@earendil-works/pi-agent-core/base` with explicit provider registration to keep bundled applications from including unused provider transports. See [`pi-ai` Base Entry Point](../ai/README.md#base-entry-point) and [`pi-agent-core` Base Entry Point](../agent/README.md#base-entry-point). +- **Mistral prompt caching** - Mistral sessions now use provider-side prompt caching with session affinity and cached-token usage/cost accounting. See [API Keys](docs/providers.md#api-keys) and [Environment Variables](docs/usage.md#environment-variables). +- **Post-compaction token estimates** - Compact results and compaction events now include estimated post-compaction token counts so clients can show the approximate context reduction. See [RPC compact](docs/rpc.md#compact) and [compaction events](docs/rpc.md#compaction_start--compaction_end). +- **OpenRouter Fusion alias** - `openrouter/fusion` is available as a built-in OpenRouter model alias. See [API Keys](docs/providers.md#api-keys). + +### Added + +- Added inherited `@earendil-works/pi-ai/base` and `@earendil-works/pi-agent-core/base` entry points for selective provider registration in bundled applications ([#5348](https://github.com/earendil-works/pi/pull/5348) by [@FredKSchott](https://github.com/FredKSchott)). +- Added inherited Mistral prompt caching using the pi session ID as `prompt_cache_key`, including cached-token usage and cost accounting ([#5854](https://github.com/earendil-works/pi/issues/5854)). +- Added estimated post-compaction token counts to compact results and compaction events ([#5877](https://github.com/earendil-works/pi/issues/5877)). +- Added the inherited OpenRouter Fusion alias as `openrouter/fusion` ([#5866](https://github.com/earendil-works/pi/pull/5866) by [@dannote](https://github.com/dannote)). + +### Fixed + +- Updated vulnerable runtime dependencies, including `undici` and the packaged `protobufjs` transitive dependency. +- Fixed compaction to refuse sessions with no eligible messages instead of producing empty summaries ([#4811](https://github.com/earendil-works/pi/issues/4811)). +- Fixed successful overflow-triggered auto-compaction to avoid retrying completed assistant responses ([#5720](https://github.com/earendil-works/pi/issues/5720)). + +## [0.79.7] - 2026-06-18 + +### New Features + +- **Automatic theme mode** - `/settings` can choose separate light and dark themes and follow terminal color-scheme changes. See [Selecting a Theme](docs/themes.md#selecting-a-theme). +- **Self-only updates by default** - `pi update` now updates pi only, with `pi update --all` for updating pi and packages together. See [Install and Manage](docs/packages.md#install-and-manage). +- **Extension API helpers** - extensions can use `CONFIG_DIR_NAME` for project config paths and import edit diff helpers for edit-style diffs. See [`ctx.cwd`](docs/extensions.md#ctxcwd) and [SDK Exports](docs/sdk.md#exports). +- **Warp inline images** - Warp terminals now get inline image rendering through Kitty graphics detection. See [Image](docs/tui.md#image). + +### Added + +- Added automatic theme mode so `/settings` can use separate light and dark themes and follow terminal color-scheme changes ([#5874](https://github.com/earendil-works/pi/pull/5874)). +- Added inherited Warp terminal image capability detection so inline images render through Warp's Kitty graphics support ([#5841](https://github.com/earendil-works/pi/pull/5841) by [@dodiego](https://github.com/dodiego)). +- Exported `CONFIG_DIR_NAME` from the coding-agent public API so extensions can resolve project config paths without hardcoding `.pi` ([#5869](https://github.com/earendil-works/pi/pull/5869) by [@xl0](https://github.com/xl0)). +- Exported edit diff helpers (`generateDiffString`, `generateUnifiedPatch`, and `EditDiffResult`) from the public API for extensions that need edit-style diffs ([#5756](https://github.com/earendil-works/pi/pull/5756) by [@xl0](https://github.com/xl0)). + +### Changed + +- Changed bare `pi update` to update only pi, added `pi update --all` for updating pi and extensions together, and clarified extension update prompts. +- Reserved `/` in theme names for automatic light/dark theme settings. +- Updated extension docs, examples, runtime help, trust prompts, and config labels to use the configured project config directory instead of hardcoded `.pi` paths. + +### Fixed + +- Fixed RPC unknown-command errors to include the request id so clients do not hang waiting for a response ([#5868](https://github.com/earendil-works/pi/issues/5868)). +- Fixed `/model` autocomplete and model selection searches to match provider/model queries regardless of whether the provider or model token is typed first. +- Fixed the tree navigator to horizontally pan deep entries so the selected item remains readable ([#5830](https://github.com/earendil-works/pi/issues/5830)). + +## [0.79.6] - 2026-06-16 + +### Fixed + +- Fixed HTTP dispatcher configuration to preserve a caller's deliberate `fetch` override instead of reinstalling the undici global fetch over it. +- Fixed inherited OpenCode Go DeepSeek V4 thinking-off requests to send the provider's `thinking: { type: "disabled" }` compatibility parameter. + +## [0.79.5] - 2026-06-16 + +### New Features + +- **Provider-scoped API key environments** - `auth.json` API key entries can now include `env` overrides for provider-specific Cloudflare, Azure OpenAI, Google Vertex, Amazon Bedrock, cache retention, and proxy settings without changing the project shell. See [Auth File](docs/providers.md#auth-file). +- **Global HTTP proxy setting** - Configure `httpProxy` once in global settings to apply `HTTP_PROXY` and `HTTPS_PROXY` to Pi-managed HTTP clients. See [Network](docs/settings.md#network). +- **Vercel AI Gateway attribution** - Vercel AI Gateway requests now include Pi attribution headers by default. See [API Keys](docs/providers.md#api-keys). + +### Added + +- Added Vercel AI Gateway request attribution headers (`http-referer` and `x-title`) for Vercel AI Gateway models ([#5798](https://github.com/earendil-works/pi/pull/5798) by [@rwachtler](https://github.com/rwachtler)). +- Added an `xp` footer marker when experimental features are enabled. +- Added a global `httpProxy` setting that applies as `HTTP_PROXY` and `HTTPS_PROXY` for Pi-managed HTTP clients ([#5790](https://github.com/earendil-works/pi/issues/5790)). +- Added `auth.json` API key `env` values so provider-specific environment overrides can be scoped to Pi and propagated to inherited provider configuration ([#5728](https://github.com/earendil-works/pi/issues/5728)). + +### Changed + +- Updated the vendored Markdown parser used by HTML session exports to `marked` 18.0.5. + +### Fixed + +- Fixed inherited OpenAI Responses streaming to tolerate null message content from OpenAI-compatible servers before tool calls ([#5819](https://github.com/earendil-works/pi/issues/5819)). +- Fixed inherited OpenCode DeepSeek V4 thinking requests to avoid sending both `thinking` and `reasoning_effort` ([#5818](https://github.com/earendil-works/pi/issues/5818)). +- Fixed device-code login to stop opening the browser automatically. +- Fixed inherited editor Cursor Up handling so non-empty drafts jump to the start of the line before browsing input history ([#5789](https://github.com/earendil-works/pi/pull/5789) by [@4h9fbZ](https://github.com/4h9fbZ)). +- Fixed inherited Z.AI GLM-5.2 thinking requests to send `reasoning_effort` with the provider's `high`/`max` effort mapping ([#5770](https://github.com/earendil-works/pi/issues/5770)). +- Fixed successful `pi update` on Windows to exit naturally instead of calling `process.exit(0)`, avoiding a Node.js/libuv assertion after version-check network requests ([#5805](https://github.com/earendil-works/pi/issues/5805)). +- Fixed inherited Google and `google-vertex` Gemini model metadata to map `latest` aliases to the current models, add Gemini 3.5 Flash for Vertex, correct Gemini 2.5 Flash Vertex cache pricing, and remove shut-down Vertex preview models ([#5761](https://github.com/earendil-works/pi/issues/5761)). +- Fixed the session selector to stay open and show the all-sessions empty state when both current-folder and all-scope session lists are empty ([#5747](https://github.com/earendil-works/pi/issues/5747)). +- Fixed inherited Moonshot AI China model metadata to include Kimi K2.7 Code, and omitted unsupported thinking-off payloads for Kimi K2.7 Code models ([#5760](https://github.com/earendil-works/pi/issues/5760)). + +## [0.79.4] - 2026-06-15 + +### New Features + +- **Automatic first-run theme selection** - pi detects the terminal background on first run and defaults to the `dark` or `light` theme. See [Selecting a Theme](docs/themes.md#selecting-a-theme). +- **Standalone binary integrity checksums** - GitHub release assets now include `SHA256SUMS` files for verifying standalone binary downloads. See [Quickstart Install](docs/quickstart.md#install). + +### Added + +- Added `SHA256SUMS` integrity files to standalone binary GitHub release assets ([#5739](https://github.com/earendil-works/pi/issues/5739)). +- Added first-run interactive theme detection from the terminal background ([#5385](https://github.com/earendil-works/pi/pull/5385) by [@vegarsti](https://github.com/vegarsti)). + +### Fixed + +- Fixed bash tool output collection to keep draining stdout/stderr after the child exits while descendants still write, avoiding truncated late output ([#5753](https://github.com/earendil-works/pi/pull/5753) by [@Mearman](https://github.com/Mearman)). +- Fixed `/tree` help rendering to show compact wrapped controls instead of truncating them on narrow terminals ([#5055](https://github.com/earendil-works/pi/issues/5055)). +- Fixed SIGTERM/SIGHUP interactive shutdown to keep signal handlers installed until terminal cleanup completes, preventing `signal-exit` from re-sending the signal and leaving the terminal in raw/Kitty keyboard mode ([#5724](https://github.com/earendil-works/pi/issues/5724)). +- Fixed extensions documentation to clarify that `pi.getActiveTools()` returns active tool names while `pi.getAllTools()` returns tool metadata ([#5729](https://github.com/earendil-works/pi/issues/5729)). +- Fixed question and questionnaire extension examples to wrap long prompt, option, and help text instead of truncating it ([#5708](https://github.com/earendil-works/pi/pull/5708) by [@xl0](https://github.com/xl0)). +- Fixed package commands such as `pi list`, `pi install`, and `pi update` to terminate after completing even if an extension leaves background handles open ([#5687](https://github.com/earendil-works/pi/issues/5687)). +- Fixed `pi update` for pnpm global installs whose configured `global-bin-dir` no longer matches the active pnpm home ([#5689](https://github.com/earendil-works/pi/issues/5689)). +- Fixed npm package specs that use ranges or tags (for example `@^1.2.7`) so installed package resources still load instead of being treated as mismatched exact pins ([#5695](https://github.com/earendil-works/pi/issues/5695)). +- Fixed inherited Anthropic 1-hour prompt-cache write cost accounting to price 1-hour cache writes at 2x input instead of the 5-minute cache-write rate ([#5738](https://github.com/earendil-works/pi/pull/5738) by [@theBucky](https://github.com/theBucky)). +- Fixed inherited GitHub Copilot Claude adaptive-thinking effort metadata to match manually checked Copilot model capabilities ([#4637](https://github.com/earendil-works/pi/issues/4637)). +- Fixed inherited OpenCode/OpenCode Go completion model metadata to omit long-retention cache fields for routes that reject `prompt_cache_retention` ([#5702](https://github.com/earendil-works/pi/issues/5702)). +- Fixed inherited overlay compositing over CJK wide characters so borders stay aligned when an overlay starts inside a full-width cell ([#5297](https://github.com/earendil-works/pi/issues/5297)). +- Fixed inherited WezTerm inline Kitty image rendering during full redraw fallbacks so image padding rows are reserved before the placement is drawn without regressing tall-image placement ([#5618](https://github.com/earendil-works/pi/issues/5618), [#4415](https://github.com/earendil-works/pi/issues/4415)). +- Fixed custom provider config so plain uppercase API key and header values remain literals instead of being treated as legacy environment references; use explicit `$ENV_VAR` syntax for environment variables ([#5661](https://github.com/earendil-works/pi/issues/5661)). + +## [0.79.3] - 2026-06-13 + +### Fixed + +- Fixed inherited OpenAI GPT-5.4/GPT-5.5 and OpenAI Codex GPT-5.4/GPT-5.4 mini/GPT-5.5 context window metadata to use the observed 272k-token Codex backend limit, avoiding a billing hazard from prompts above Codex's accepted limit (reported by [@trethore](https://github.com/trethore)). + +## [0.79.2] - 2026-06-12 + +### New Features + +- **Clearer Bedrock validation guidance** - Amazon Bedrock data retention validation errors now link to AWS data retention documentation. See [Amazon Bedrock](docs/providers.md#amazon-bedrock). + +### Added + +- Added an experimental first-time setup flow behind `PI_EXPERIMENTAL=1` that asks for a dark/light theme choice (preselecting the detected appearance) and opt-in analytics data sharing on first launch with the default agent directory; opting in stores a `trackingId` in `settings.json` ([#5587](https://github.com/earendil-works/pi/pull/5587) by [@vegarsti](https://github.com/vegarsti)). +- Added AWS data retention documentation links to inherited Amazon Bedrock unsupported data retention mode validation errors ([#5561](https://github.com/earendil-works/pi/pull/5561) by [@unexge](https://github.com/unexge)). + +### Fixed + +- Fixed project trust detection to ignore global `~/.pi/agent` state when running from `$HOME`, and made `pi update` use only saved or explicit project trust without prompting ([#5619](https://github.com/earendil-works/pi/issues/5619)). +- Fixed experimental first-time setup to skip forked sessions instead of rerunning the setup prompts ([#5627](https://github.com/earendil-works/pi/pull/5627) by [@vegarsti](https://github.com/vegarsti)). +- Fixed inherited OpenAI-compatible context overflow detection for parenthesized `maximum context length (N)` errors ([#5677](https://github.com/earendil-works/pi/issues/5677)). +- Fixed inherited OpenAI GPT-5.4/GPT-5.5 and OpenAI Codex GPT-5.4/GPT-5.4 mini/GPT-5.5 context window metadata to match current OpenAI limits ([#5644](https://github.com/earendil-works/pi/issues/5644)). +- Fixed inherited Anthropic refusal stops to preserve provider `stop_details` explanations in error messages ([#5666](https://github.com/earendil-works/pi/pull/5666) by [@rwachtler](https://github.com/rwachtler)). +- Increased the inherited OpenAI Codex Responses SSE response-header timeout to 20 seconds to reduce false-positive stalls while retaining the bounded wait introduced for zero-event hangs ([#4945](https://github.com/earendil-works/pi/issues/4945)). +- Fixed inherited Claude Fable 5 thinking-off requests to omit Anthropic's unsupported `thinking.type: "disabled"` payload ([#5567](https://github.com/earendil-works/pi/pull/5567) by [@tmustier](https://github.com/tmustier)). +- Fixed inherited late tool progress callbacks after tool settlement to be ignored instead of emitting stale `tool_execution_update` events ([#5573](https://github.com/earendil-works/pi/issues/5573)). +- Fixed inherited user-message transcript rendering so standalone `+` messages no longer render as `-` ([#5657](https://github.com/earendil-works/pi/issues/5657)). +- Fixed inherited slash-separated fuzzy queries so provider/model completions remain matchable after insertion. +- Fixed inherited WezTerm inline Kitty image rendering so reserved row clears do not erase all but the top strip of tool image previews ([#5618](https://github.com/earendil-works/pi/issues/5618)). +- Fixed inherited editor wrapping for CJK text to break at character boundaries instead of leaving large trailing gaps ([#5585](https://github.com/earendil-works/pi/pull/5585) by [@haoqixu](https://github.com/haoqixu)). +- Fixed inherited loose Markdown list rendering to preserve blank-line separation between list items ([#5562](https://github.com/earendil-works/pi/pull/5562) by [@Perlence](https://github.com/Perlence)). +- Fixed `--model` resolution for authenticated custom model IDs whose slash prefix matches an unauthenticated built-in provider ([#5643](https://github.com/earendil-works/pi/issues/5643)). +- Fixed `/fork` to keep session parent chains connected when the forked path contains labels ([#5669](https://github.com/earendil-works/pi/issues/5669)). +- Fixed `/share` and `/export` HTML exports to use the active fallback theme when the configured custom theme no longer exists ([#5596](https://github.com/earendil-works/pi/issues/5596)). +- Fixed custom fallback model IDs with `:` suffixes to preserve the requested thinking level when the provider template model does not advertise reasoning ([#5560](https://github.com/earendil-works/pi/pull/5560) by [@haoqixu](https://github.com/haoqixu)). + +## [0.79.1] - 2026-06-09 + +### New Features + +- **Claude Fable 5** - Claude Fable 5 is now available on the Anthropic and Amazon Bedrock providers, with adaptive thinking and `xhigh` effort support. +- **Prompt template defaults** - Prompt templates can use default positional arguments such as `${1:-7}` for optional values. See [Prompt Template Arguments](docs/prompt-templates.md#arguments). +- **Configurable project trust defaults** - `defaultProjectTrust` lets users choose whether unresolved project trust asks, always trusts, or never trusts by default, and extensions can inspect effective trust decisions. See [Project Trust](docs/security.md#project-trust) and [`ctx.isProjectTrusted()`](docs/extensions.md#ctxisprojecttrusted). +- **Natural extension autocomplete triggers** - Extension autocomplete providers can declare trigger characters such as `#` or `$` so suggestions open without slash-command prefixes. See [Autocomplete Providers](docs/extensions.md#autocomplete-providers). + +### Added + +- Added default-value expansion for prompt template positional arguments, e.g. `${1:-7}` ([#5553](https://github.com/earendil-works/pi/pull/5553) by [@dannote](https://github.com/dannote)). +- Added `areExperimentalFeaturesEnabled` feature guard to allow users to opt in to early features ([#5547](https://github.com/earendil-works/pi/pull/5547) by [@vegarsti](https://github.com/vegarsti)). +- Added `ctx.isProjectTrusted()` for extensions to observe the effective project trust decision, including temporary trust decisions ([#5523](https://github.com/earendil-works/pi/issues/5523)). +- Added a global `defaultProjectTrust` setting to choose whether unresolved project trust asks, always trusts, or never trusts by default. +- Added extension autocomplete trigger character support for `ctx.ui.addAutocompleteProvider()` wrappers ([#4703](https://github.com/earendil-works/pi/issues/4703)). +- Added Claude Fable 5 model support inherited from `@earendil-works/pi-ai` for the Anthropic and Amazon Bedrock providers, with adaptive thinking and `xhigh` effort support. + +### Fixed + +- Fixed inherited Amazon Bedrock inference profile ARN region resolution to prefer the ARN's embedded region over `AWS_REGION` ([#5527](https://github.com/earendil-works/pi/pull/5527) by [@AJM10565](https://github.com/AJM10565)). +- Fixed inherited IME hardware cursor positioning while slash-command autocomplete is visible ([#5283](https://github.com/earendil-works/pi/pull/5283) by [@smoosex](https://github.com/smoosex)). +- Fixed inherited z.ai thinking-off requests to send the provider's `thinking: { type: "disabled" }` compatibility parameter ([#5330](https://github.com/earendil-works/pi/issues/5330)). +- Fixed inherited OpenCode completions model metadata to send explicit `maxTokens` as `max_tokens` ([#5331](https://github.com/earendil-works/pi/issues/5331)). +- Fixed inherited Moonshot Kimi thinking-off requests to send the provider's `thinking: { type: "disabled" }` compatibility parameter ([#5531](https://github.com/earendil-works/pi/issues/5531)). +- Fixed inherited Azure OpenAI Responses requests to disable server-side response storage ([#5530](https://github.com/earendil-works/pi/issues/5530)). +- Fixed inherited Azure GPT-5.4 and GPT-5.5 context window metadata to 1,050,000 tokens, matching Azure Foundry deployments instead of OpenAI's 272k limit ([#5559](https://github.com/earendil-works/pi/issues/5559)). +- Fixed inherited OpenAI and Azure GPT-5 Pro `maxTokens` metadata to 128,000, correcting an upstream value that duplicated the input sub-limit as the output limit ([#5559](https://github.com/earendil-works/pi/issues/5559)). +- Fixed inherited prompt history navigation to restore the current draft when returning from history browsing ([#5494](https://github.com/earendil-works/pi/issues/5494)). +- Fixed inherited wrapping for mixed Latin and CJK text so unspaced CJK runs can break at grapheme boundaries without leaving large trailing gaps ([#5495](https://github.com/earendil-works/pi/issues/5495)). +- Fixed extension OAuth login prompts to keep previous submitted prompt rows stable instead of mirroring the active input value ([#5433](https://github.com/earendil-works/pi/issues/5433)). +- Fixed `/reload` to apply updated `steeringMode` and `followUpMode` settings to the current session ([#5377](https://github.com/earendil-works/pi/issues/5377)). +- Fixed invalid `models.json` syntax to skip startup config migrations and report the normal file-path-aware models error instead of a raw JSON parse stack trace ([#5418](https://github.com/earendil-works/pi/issues/5418)). +- Fixed GitHub release notes and interactive changelog links to resolve package-relative documentation URLs correctly ([#5516](https://github.com/earendil-works/pi/issues/5516)). +- Fixed CLI help and version output, including plain redirected `--help`/`--version` output and simplified `list`/`config` help text. +- Fixed `/new` from ephemeral sessions to keep the new session ephemeral instead of persisting it by default ([#5045](https://github.com/earendil-works/pi/issues/5045)). +- Clarified custom model docs that `name` and `modelOverrides.name` do not replace model IDs in the footer or primary model lists ([#4841](https://github.com/earendil-works/pi/issues/4841)). + +## [0.79.0] - 2026-06-08 + +### New Features + +- **Project trust for local inputs** - Pi now asks before loading project-local settings, resources, instructions, and packages, with saved decisions and `--approve` / `--no-approve` controls for non-interactive modes. See [Project Trust](README.md#project-trust). +- **Extension-controlled trust decisions** - Global and CLI extensions can handle `project_trust`, decide, remember, or defer project trust before project-local resources load. See [`project_trust`](docs/extensions.md#project_trust). +- **Cache-hit visibility in the footer** - The interactive footer now shows the latest prompt cache hit rate (`CH`). See [Interactive Mode](README.md#interactive-mode). +- **Richer SDK and RPC extension surfaces** - Public exports now include RPC extension UI request/response types and package asset path helpers. See [Extension UI Protocol](docs/rpc.md#extension-ui-protocol) and [SDK Exports](docs/sdk.md#exports). + +### Added + +- Added a `project_trust` extension event so global and CLI extensions can decide or defer project trust during startup and runtime cwd switches. +- Added project trust gating for project-local settings, resources, instructions, and packages ([#5332](https://github.com/earendil-works/pi/pull/5332)). +- Added the latest prompt cache hit rate to the interactive footer. +- Exported RPC extension UI request and response types from the public API ([#5455](https://github.com/earendil-works/pi/issues/5455)). +- Exported coding-agent package asset path helpers from the public API ([#5415](https://github.com/earendil-works/pi/issues/5415)). + +### Fixed + +- Fixed package exports by removing the stale `./hooks` subpath that pointed at non-existent build output. +- Fixed inherited TUI rendering to clear stale lines when content shrinks to zero. +- Fixed inherited autocomplete suggestions to refresh after editor cursor movement ([#5499](https://github.com/earendil-works/pi/pull/5499) by [@Roman-Galeev](https://github.com/Roman-Galeev)). +- Fixed `/reload` to persist project trust when an implicitly trusted session creates a project `.pi` directory. +- Fixed project trust input discovery to traverse parent directories portably. +- Fixed inherited intermittent Shift+Enter handling by making Kitty keyboard protocol fallback response-driven instead of timeout-driven ([#5188](https://github.com/earendil-works/pi/issues/5188)). +- Fixed the compaction summarization system prompt to use neutral AI assistant wording for non-coding agents ([#5401](https://github.com/earendil-works/pi/issues/5401)). +- Fixed `models.json` schema support and inherited OpenAI Responses custom-provider handling for `compat.supportsDeveloperRole: false` ([#5456](https://github.com/earendil-works/pi/issues/5456)). +- Fixed inherited prompt history navigation to place the cursor at the start when browsing upward and at the end when browsing downward ([#5454](https://github.com/earendil-works/pi/issues/5454)). +- Fixed tmux setup documentation to require tmux 3.5 for `extended-keys-format csi-u` and document the tmux 3.2-3.4 fallback ([#5432](https://github.com/earendil-works/pi/issues/5432)). +- Fixed inherited OpenRouter routing preferences on OpenAI-compatible custom providers to work when the custom provider base URL does not point directly at OpenRouter ([#5347](https://github.com/earendil-works/pi/issues/5347)). +- Fixed built-in tool expand hints to style closing parentheses consistently ([#5359](https://github.com/earendil-works/pi/issues/5359)). +- Fixed skill-wrapped prompts to insert spacing between skill instructions and the user message ([#5371](https://github.com/earendil-works/pi/pull/5371) by [@Perlence](https://github.com/Perlence)). + +## [0.78.1] - 2026-06-04 + +### New Features + +- **More built-in provider coverage** - Added Ant Ling and NVIDIA NIM provider setup, plus MiniMax-M3 support for the direct MiniMax providers. See [Providers](docs/providers.md). +- **Richer extension context** - Extensions can use `ctx.mode` and `ctx.getSystemPromptOptions()` to adapt behavior across TUI, RPC, JSON, and print modes and inspect base system prompt inputs. See [Extensions](docs/extensions.md). + +### Added + +- Added containerization documentation and a Gondolin extension example for routing built-in tools into a local micro-VM. +- Added Ant Ling provider selection and setup documentation. +- Added MiniMax-M3 model support inherited from `@earendil-works/pi-ai` for the `minimax` and `minimax-cn` direct providers ([#5313](https://github.com/earendil-works/pi/issues/5313)). +- Added NVIDIA NIM provider selection, setup documentation, and direct NIM request attribution headers. +- Added `ctx.mode` to extension contexts so extensions can distinguish TUI, RPC, JSON, and print mode. +- Added `ctx.getSystemPromptOptions()` for extension commands to inspect the current base system prompt inputs ([#5306](https://github.com/earendil-works/pi/pull/5306) by [@xl0](https://github.com/xl0)). + +### Fixed + +- Fixed temporary extension package installs to use a private `~/.pi/agent/tmp/extensions` directory with `0700` permissions instead of `os.tmpdir()/pi-extensions`. +- Fixed git package source handling to reject unsafe host/path components and keep managed clone paths inside install roots. +- Fixed stored XSS in HTML session exports by sanitizing Markdown link and image URLs with a scheme allow-list after stripping control characters. +- Fixed SDK embedding in bundled Node apps failing with `ENOENT` when `package.json` is not present next to the bundle entrypoint. The package metadata reader now gracefully handles missing `package.json` by using defaults, enabling `createAgentSession()` without requiring package-adjacent files at runtime ([#5226](https://github.com/earendil-works/pi/issues/5226)). +- Fixed HTTP timeout setting not being respected for non-Codex providers (e.g., llama.cpp via OpenAI-compatible API). The `httpIdleTimeoutMs` setting (set via `/settings` HTTP timeout) now applies as the default SDK request timeout for all providers that support it, not just OpenAI Codex Responses. Disabling the timeout (HTTP timeout = false) now correctly disables SDK timeouts for all supported providers by sending a maximum int32 value (effectively infinite) instead of 0, since SDKs treat timeout=0 as an immediate timeout ([#5294](https://github.com/earendil-works/pi/issues/5294)). +- Fixed inherited Amazon Bedrock requests to replace blank required user/tool-result text with a placeholder and skip blank replay text blocks ([#4975](https://github.com/earendil-works/pi/issues/4975)). +- Fixed inherited Anthropic Claude Opus 4.7+ requests to suppress deprecated temperature parameters ([#5251](https://github.com/earendil-works/pi/pull/5251) by [@yzhg1983](https://github.com/yzhg1983)). +- Fixed inherited OpenAI GPT-5.5 generated metadata to omit unsupported minimal thinking ([#5243](https://github.com/earendil-works/pi/issues/5243)). +- Fixed inherited OpenRouter Kimi K2.6 thinking replay and developer-role instruction handling ([#5309](https://github.com/earendil-works/pi/issues/5309)). +- Fixed inherited OpenRouter reasoning instruction requests to preserve the system role when required ([#5221](https://github.com/earendil-works/pi/pull/5221) by [@PriNova](https://github.com/PriNova)). +- Fixed inherited overlay focus restoration so non-capturing overlays remain interactive after UI rerenders and explicit focus release ([#5235](https://github.com/earendil-works/pi/pull/5235) by [@nicobailon](https://github.com/nicobailon)). +- Fixed inherited tab width accounting in column slicing and overlay compositing so tab-containing output cannot exceed the terminal width ([#5218](https://github.com/earendil-works/pi/issues/5218)). +- Fixed opening and listing very large JSONL session files by reading session entries line-by-line instead of materializing the full file as one string ([#5231](https://github.com/earendil-works/pi/issues/5231)). +- Fixed the footer branch display in WSL `/mnt/...` repositories to refresh after branch changes ([#5264](https://github.com/earendil-works/pi/pull/5264) by [@psoukie](https://github.com/psoukie)). +- Fixed `renderShell: "self"` tool renderers that emit no component lines leaving a blank chat row ([#5299](https://github.com/earendil-works/pi/issues/5299)). +- Restored inherited NVIDIA Qwen 3.5 122B NIM model support. + +## [0.78.0] - 2026-05-29 + +### New Features + +- **Named startup sessions** - `--name` / `-n` sets the session display name before startup across interactive, print, JSON, and RPC modes. See [Naming Sessions](docs/sessions.md#naming-sessions) and [Session Options](docs/usage.md#session-options). +- **Clickable file tool paths** - built-in file tool titles render OSC 8 `file://` hyperlinks when the terminal supports them, including supported tmux clients. + +### Added + +- Exported `convertToPng` for extension authors ([#5167](https://github.com/earendil-works/pi-mono/pull/5167) by [@xl0](https://github.com/xl0)). +- Exported `parseArgs` and type `Args` for extension authors ([#5202](https://github.com/earendil-works/pi-mono/pull/5202) by [@xl0](https://github.com/xl0)). +- Added `--name` / `-n` to set the session display name at startup ([#5153](https://github.com/earendil-works/pi-mono/issues/5153)). +- Added a resume command hint when exiting interactive sessions ([#5176](https://github.com/earendil-works/pi-mono/pull/5176) by [@yzhg1983](https://github.com/yzhg1983)). +- Added OSC 8 `file://` hyperlinks to file paths shown in built-in file tool titles ([#5189](https://github.com/earendil-works/pi-mono/pull/5189) by [@mpazik](https://github.com/mpazik)). +- Added custom Amazon Bedrock request header support inherited from `@earendil-works/pi-ai` ([#5178](https://github.com/earendil-works/pi-mono/pull/5178) by [@stephanmck](https://github.com/stephanmck)). + +### Fixed + +- Clarified the WezTerm/WSL IME hardware cursor docs to state that cursor visibility remains opt-in ([#5200](https://github.com/earendil-works/pi-mono/issues/5200)). +- Fixed the GitLab Duo custom provider example to use adaptive thinking for Claude models, expose xhigh thinking, and include newer verified model IDs ([#5201](https://github.com/earendil-works/pi-mono/issues/5201)). +- Fixed Bun release archive creation to install and copy the matching `@mariozechner/clipboard` base package and native sidecars ([#5184](https://github.com/earendil-works/pi-mono/issues/5184)). +- Fixed early interactive input typed before the prompt loop starts so it is buffered instead of dropped ([#5195](https://github.com/earendil-works/pi-mono/pull/5195) by [@yzhg1983](https://github.com/yzhg1983)). +- Fixed OpenRouter Moonshot Kimi K2.6 requests to use `system` instead of unsupported `developer` messages ([#5159](https://github.com/earendil-works/pi-mono/issues/5159)). +- Fixed OpenCode Go Kimi K2.6 thinking requests to send `thinking` objects instead of invalid string values, and fixed OpenCode Zen Grok Build thinking requests to omit unsupported `reasoning_effort` ([#5169](https://github.com/earendil-works/pi-mono/issues/5169)). +- Fixed OpenAI Codex Responses SSE streams to abort response body reads after terminal events. +- Fixed OpenCode Kimi K2.6 generated metadata to use Anthropic-style thinking metadata instead of invalid reasoning-effort parameters. +- Fixed OSC 8 hyperlinks to pass through tmux when the client supports them ([#5189](https://github.com/earendil-works/pi-mono/pull/5189) by [@mpazik](https://github.com/mpazik)). +- Fixed ANSI text wrapping to avoid stack overflows on very long wrapped lines ([#5185](https://github.com/earendil-works/pi-mono/issues/5185)). + +## [0.77.0] - 2026-05-28 + +### New Features + +- **Claude Opus 4.8 support** - Adds Anthropic Claude Opus 4.8 metadata and updates Opus adaptive-thinking coverage. +- **Selective tool disablement** - `--exclude-tools` / `-xt` disables specific built-in, extension, or custom tools while leaving the rest available. See [Tool Options](docs/usage.md#tool-options). +- **Headless Codex subscription login** - `/login` can use device-code auth for ChatGPT Plus/Pro Codex subscriptions. See [Subscriptions](docs/providers.md#subscriptions) and [OpenAI Codex](docs/providers.md#openai-codex). +- **Streaming-aware extension input** - extensions can distinguish idle prompts, mid-stream steers, and queued follow-ups with `InputEvent.streamingBehavior`. See [Input Events](docs/extensions.md#input-events). + +### Added + +- Added `--exclude-tools` / `-xt` to disable specific built-in, extension, or custom tools while leaving the rest available ([#5109](https://github.com/earendil-works/pi/issues/5109)). +- Added OpenAI Codex subscription device-code login as a selectable headless alternative while keeping browser login as the default ([#4911](https://github.com/earendil-works/pi/pull/4911) by [@vegarsti](https://github.com/vegarsti)). +- Added `streamingBehavior` to extension input events so extensions can distinguish idle prompts from mid-stream steers and queued follow-ups ([#5107](https://github.com/earendil-works/pi/pull/5107) by [@DanielThomas](https://github.com/DanielThomas)). +- Added Claude Opus 4.8 model metadata for Anthropic and updated Opus adaptive-thinking coverage to use it. + +### Fixed + +- Fixed startup timing output so `readPipedStdin` no longer includes `createAgentSessionRuntime` work ([#4829](https://github.com/earendil-works/pi/issues/4829)). +- Fixed OpenRouter DeepSeek V4 `xhigh` reasoning metadata to preserve OpenRouter's native effort instead of sending DeepSeek's `max` effort ([#4801](https://github.com/earendil-works/pi/issues/4801)). +- Fixed custom session directories so current-folder resume/continue lookups stay scoped to the active cwd while all-session listings cover the custom directory. +- Fixed SIGTERM/SIGHUP exits to run extension `session_shutdown` cleanup and restore the terminal: signal-triggered shutdown now emits `session_shutdown` before any terminal writes, and SIGHUP no longer hard-exits, so extension resources (e.g. sockets) are released even when the terminal is gone ([#5080](https://github.com/earendil-works/pi/issues/5080)). +- Fixed keyboard protocol negotiation to ignore mismatched or delayed terminal responses, avoiding false Kitty keyboard protocol detection ([#5091](https://github.com/earendil-works/pi/pull/5091) by [@mitsuhiko](https://github.com/mitsuhiko)). +- Fixed Windows startup crashes under MSYS2 ucrt64 Node.js by updating the native clipboard addon to napi-rs 3.x ([#5028](https://github.com/earendil-works/pi/issues/5028)). +- Fixed API key and header config resolution to treat plain strings as literals, support `$ENV_VAR` / `${ENV_VAR}` interpolation and `$!` bang escaping, and require explicit env syntax for config files, avoiding Windows case-insensitive env matches corrupting literal keys ([#5095](https://github.com/earendil-works/pi/issues/5095)). +- Fixed session disposal to abort in-flight agent, compaction, branch summary, retry, and bash work ([#5029](https://github.com/earendil-works/pi/pull/5029) by [@TerminallyChilI](https://github.com/TerminallyChilI)). +- Fixed `pi.getAllTools()` to expose each tool's `promptGuidelines` for extensions that need per-tool guideline attribution ([#4879](https://github.com/earendil-works/pi/issues/4879)). +- Fixed OpenAI Codex Responses replay after switching from Anthropic extended-thinking sessions by generating unique fallback message item IDs for converted thinking/text blocks ([#5148](https://github.com/earendil-works/pi/issues/5148)). +- Fixed Anthropic-compatible replay for providers that return empty thinking signatures by adding an opt-in `allowEmptySignature` compatibility flag ([#4464](https://github.com/earendil-works/pi/issues/4464)). +- Fixed OpenAI and OpenRouter GPT-5.5 Pro thinking level metadata to expose only supported medium, high, and xhigh efforts. +- Fixed OpenCode Go Kimi K2.6 thinking-off requests to send `thinking: "none"` ([#5078](https://github.com/earendil-works/pi/issues/5078)). +- Fixed Xiaomi Token Plan model metadata to omit unsupported `mimo-v2-flash` variants ([#5075](https://github.com/earendil-works/pi/issues/5075)). +- Fixed follow-up messages queued by `agent_end` extension handlers to drain before the agent becomes idle ([#5115](https://github.com/earendil-works/pi/pull/5115) by [@DanielThomas](https://github.com/DanielThomas)). +- Fixed extension input events to report `streamingBehavior` only for prompts actually queued during streaming ([#5107](https://github.com/earendil-works/pi/pull/5107) by [@DanielThomas](https://github.com/DanielThomas)). +- Fixed system prompt tool-selection guidance to avoid preferring unavailable file exploration tools ([#5132](https://github.com/earendil-works/pi/issues/5132)). +- Fixed fenced `diff` code blocks and other highlight.js scopes to keep theme-aware syntax colors after the `cli-highlight` replacement ([#5092](https://github.com/earendil-works/pi/issues/5092)). + +## [0.76.0] - 2026-05-27 + +### New Features + +- **Explicit session IDs for automation** - `--session-id ` lets scripts create or resume an exact project-local session. See [Sessions](docs/usage.md#sessions). +- **RPC bash output can stay out of model context** - RPC clients can pass `excludeFromContext` to `bash` for commands whose output should not be sent with the next prompt. See [RPC mode](docs/rpc.md#bash). +- **More predictable provider retries and timeouts** - Codex WebSocket/SSE waits are bounded, and `retry.provider.maxRetries` controls provider retries instead of hidden SDK defaults. See [Retry settings](docs/settings.md#retry). +- **Better terminal editing across environments** - Apple Terminal Shift+Enter, Windows/JetBrains capability detection, and Unicode-aware word navigation improve interactive editing. See [Terminal setup](docs/terminal-setup.md) and [Keybindings](docs/keybindings.md). + +### Added + +- Added `--session-id` to let CLI callers use an exact project-local session ID, creating it if missing ([#4874](https://github.com/earendil-works/pi/issues/4874)). +- Added `excludeFromContext` flag to the `bash` RPC command for parity with the internal `executeBash` API ([#5039](https://github.com/earendil-works/pi/issues/5039)). + +### Fixed + +- Fixed user message transcript rendering to preserve user-authored ordered-list markers ([#5013](https://github.com/earendil-works/pi/issues/5013)). +- Fixed self-update commands to bypass npm, pnpm, and Bun minimum release age gates for explicit `pi update` runs ([#4929](https://github.com/earendil-works/pi/issues/4929)). +- Fixed context token estimates to count user image attachments consistently with tool result images ([#4983](https://github.com/earendil-works/pi/issues/4983)). +- Fixed `httpIdleTimeoutMs` to apply to OpenAI Codex Responses WebSocket idle waits, added `websocketConnectTimeoutMs` for bounded WebSocket connect waits, and added a 10s Codex SSE response-header timeout ([#4945](https://github.com/earendil-works/pi/issues/4945)). +- Fixed `RpcClient` to reject pending requests and consume stdin pipe errors when the child process exits unexpectedly ([#4764](https://github.com/earendil-works/pi/issues/4764)). +- Fixed managed npm extension updates to avoid package managers installing or resolving pi host packages as peer dependencies ([#4907](https://github.com/earendil-works/pi/issues/4907)). +- Fixed RPC mode raw stdout writes to retry transient backpressure errors and flush queued protocol output during shutdown ([#4897](https://github.com/earendil-works/pi/issues/4897)). +- Fixed OpenAI Codex Responses cache-affinity headers to send `session-id` instead of proxy-incompatible `session_id` ([#4967](https://github.com/earendil-works/pi/issues/4967)). +- Fixed `openai-codex/gpt-5.3-codex-spark` model metadata to use its 128k context window ([#4969](https://github.com/earendil-works/pi/issues/4969)). +- Fixed OpenRouter/Poolside context overflow detection for `maximum allowed input length` errors ([#4943](https://github.com/earendil-works/pi/issues/4943)). +- Fixed provider retry controls so `retry.provider.maxRetries` is honored, SDK retries default to `0`, and quota/billing 429s are not retried behind Pi's retry handling ([#4991](https://github.com/earendil-works/pi-mono/pull/4991) by [@mitsuhiko](https://github.com/mitsuhiko)). +- Fixed Apple Terminal `Shift+Enter` by detecting local macOS modifier state when Terminal.app sends plain Return. +- Fixed Windows Terminal capability detection to enable OSC 8 hyperlinks, preserving clickable long URLs across wrapped lines ([#4923](https://github.com/earendil-works/pi/issues/4923)). +- Fixed JetBrains terminal capability detection to enable truecolor while disabling unsupported OSC 8 hyperlinks ([#5037](https://github.com/earendil-works/pi-mono/pull/5037) by [@Perlence](https://github.com/Perlence)). +- Fixed editor and input word navigation/deletion to use Unicode word boundaries while preserving ASCII punctuation boundaries ([#5022](https://github.com/earendil-works/pi-mono/pull/5022) by [@haoqixu](https://github.com/haoqixu), [#5067](https://github.com/earendil-works/pi-mono/pull/5067) by [@haoqixu](https://github.com/haoqixu), [#5068](https://github.com/earendil-works/pi-mono/pull/5068) by [@haoqixu](https://github.com/haoqixu)). +- Fixed the development docs `AGENTS.md` link to point at the pi-mono guidelines ([#5041](https://github.com/earendil-works/pi/issues/5041)). + +## [0.75.5] - 2026-05-23 + +### New Features + +- **Cleaner read tool output** - Collapsed `read` tool cards now show only the read line by default, while `Ctrl+O` still expands the full file content. +- **Faster file tools on Windows** - Built-in file tools now use async filesystem operations during streaming, and image resizes run off the main TUI thread in a worker. +- **More reliable package updates** - `pi update` and git package installs now reconcile pinned git refs and keep package settings intact. See [Packages](docs/packages.md). +- **Custom Anthropic-compatible adaptive thinking** - Custom provider model configs can opt into adaptive-thinking Claude behavior with `compat.forceAdaptiveThinking`. See [Custom providers](docs/custom-provider.md) and [Models](docs/models.md). + +### Added + +- Added `compat.forceAdaptiveThinking` support to custom Anthropic-compatible model configuration docs and validation ([#4797](https://github.com/earendil-works/pi-mono/pull/4797) by [@mbazso](https://github.com/mbazso)). +- Added a standard unified patch to edit tool result details for SDK consumers ([#4821](https://github.com/earendil-works/pi/issues/4821)). +- Added a Codex subscription login method selector with device-code auth for headless environments. + +### Changed + +- Changed collapsed read tool cards to show only the read line until expanded ([#4916](https://github.com/earendil-works/pi/issues/4916)). +- Replaced the inherited optional `koffi` dependency for Windows VT input with a tiny vendored native helper, reducing install size while preserving Shift+Tab handling ([#4480](https://github.com/earendil-works/pi/issues/4480)). +- Changed the root development install documentation to use `npm install --ignore-scripts` ([#4868](https://github.com/earendil-works/pi/issues/4868)). + +### Fixed + +- Fixed `pi update` to reconcile git-pinned packages to their configured ref ([#4869](https://github.com/earendil-works/pi/issues/4869)). +- Fixed package/resource path handling for Windows and glob/pattern resolution ([#4873](https://github.com/earendil-works/pi-mono/pull/4873) by [@mitsuhiko](https://github.com/mitsuhiko)). +- Fixed config pattern matching to resolve patterns from the correct base directory ([#4898](https://github.com/earendil-works/pi-mono/pull/4898) by [@haoqixu](https://github.com/haoqixu)). +- Fixed theme pickers to list themes by their content name instead of file stem ([#4830](https://github.com/earendil-works/pi-mono/pull/4830) by [@Perlence](https://github.com/Perlence)). +- Fixed OpenCode Zen/Go requests to send per-session OpenCode routing headers ([#4847](https://github.com/earendil-works/pi/issues/4847)). +- Fixed Amazon Bedrock provider loading under strict package managers by inheriting the declared `@smithy/node-http-handler` dependency from `@earendil-works/pi-ai` ([#4842](https://github.com/earendil-works/pi/issues/4842)). +- Fixed inherited Amazon Bedrock Claude requests to send the model output token cap by default, avoiding Bedrock's 4096-token default truncation ([#4848](https://github.com/earendil-works/pi/issues/4848)). +- Fixed exported session HTML to escape quote characters in attribute values ([#4832](https://github.com/earendil-works/pi/issues/4832)). +- Fixed GitHub Copilot device-code login to keep opening the verification URL in browser-capable environments while ignoring browser launch failures for headless use ([#4788](https://github.com/earendil-works/pi-mono/pull/4788) by [@vegarsti](https://github.com/vegarsti)). +- Fixed git package installs to reconcile existing checkouts to the requested ref and update package settings without losing filters ([#4870](https://github.com/earendil-works/pi/issues/4870)). +- Published a 0.74.2 rescue release that tells Node 20 users to upgrade Node before updating to newer Pi versions ([#4876](https://github.com/earendil-works/pi/issues/4876)). +- Fixed final bash tool cards to avoid rendering duplicate full-output truncation paths ([#4819](https://github.com/earendil-works/pi/issues/4819)). +- Fixed bash tool truncation line counts to ignore the trailing newline as an extra output line ([#4818](https://github.com/earendil-works/pi/issues/4818)). +- Fixed footer home-directory abbreviation to avoid shortening sibling paths that only share the same prefix ([#4878](https://github.com/earendil-works/pi/issues/4878)). +- Fixed macOS Bun release binaries to resolve the native clipboard sidecar so Ctrl+V image paste can load `@mariozechner/clipboard` ([#4307](https://github.com/earendil-works/pi/issues/4307)). +- Fixed coding-agent tools to avoid synchronous filesystem operations during streaming and moved image resizing off the main TUI thread ([#4756](https://github.com/earendil-works/pi-mono/pull/4756) by [@mitsuhiko](https://github.com/mitsuhiko)). + +## [0.75.4] - 2026-05-20 + +### New Features + +- **Hardened npm install and release path** - Pi now ships the CLI with a generated shrinkwrap for transitive dependencies, blocks accidental lockfile changes, verifies dependency pinning and lifecycle-script allowlists in checks, disables lifecycle scripts for self-update and local release installs where supported, and smoke-tests isolated npm and Bun installs before release. See [Supply-chain hardening](../../README.md#supply-chain-hardening). + +### Added + +- Added interactive update notes after `pi update` runs, so users can see the installed version's changelog before continuing ([#4724](https://github.com/earendil-works/pi-mono/pull/4724) by [@mitsuhiko](https://github.com/mitsuhiko)). +- Exported image resize utilities from the package root for SDK consumers ([#4775](https://github.com/earendil-works/pi-mono/pull/4775) by [@xl0](https://github.com/xl0)). + +### Changed + +- Changed source syntax to avoid TypeScript constructs that require JavaScript emit, keeping core sources compatible with Node.js strip-only TypeScript checks. +- Removed web UI workspace references from the CLI package and dropped the package-level development watch script. +- Published npm installs now include an `npm-shrinkwrap.json` to lock transitive dependencies for the CLI package. +- Improved terminal theme detection for light/dark and truecolor handling. +- Changed self-update package-manager commands to disable lifecycle scripts during reinstall. + +### Fixed + +- Fixed the system prompt to tell models to resolve pi docs and examples under the absolute package paths before reading topic-specific relative references ([#4752](https://github.com/earendil-works/pi/issues/4752)). +- Fixed extension `ctx.abort()` during tool-call preflight to stop later confirmations and restore queued interactive input like Escape ([#4276](https://github.com/earendil-works/pi/issues/4276)). +- Fixed AgentSession retry, compaction, and event settlement to use the awaited agent lifecycle instead of a separate event queue, and added `willRetry` to `agent_end` session events. +- Fixed forked session runtime state to keep the active session id aligned with the fork target ([#4799](https://github.com/earendil-works/pi-mono/pull/4799) by [@Perlence](https://github.com/Perlence)). +- Fixed the subagent extension's parallel mode to return useful per-task output and failed-task diagnostics to the parent model instead of 100-character previews ([#4710](https://github.com/earendil-works/pi/issues/4710)). +- Fixed Windows local bash execution to hide helper console windows when launched from background SDK processes ([#4699](https://github.com/earendil-works/pi/issues/4699)). +- Fixed managed npm extension folders to set cloud-sync ignore metadata where supported ([#4763](https://github.com/earendil-works/pi/issues/4763)). +- Fixed HTTP idle timeout configuration so long-running provider streams can avoid premature idle disconnects ([#4759](https://github.com/earendil-works/pi-mono/pull/4759) by [@mitsuhiko](https://github.com/mitsuhiko)). +- Fixed default system prompt boundaries to use explicit XML tags for clearer file separation ([#4709](https://github.com/earendil-works/pi-mono/pull/4709) by [@herrnel](https://github.com/herrnel)). +- Fixed HTML share/export sidebar clicks for shared tool entries to scroll to the rendered tool call ([#4664](https://github.com/earendil-works/pi-mono/pull/4664) by [@yzhg1983](https://github.com/yzhg1983)). +- Fixed theme palettes to set explicit text colors and avoid terminal-default color drift. +- Fixed truecolor detection to align terminal image rendering and interactive theme decisions. +- Fixed loader indicator startup inherited from `@earendil-works/pi-tui` so initialization cannot run before frames are available. +- Fixed OpenAI-compatible default output token requests inherited from `@earendil-works/pi-ai` to avoid reserving impossible context windows on servers such as vLLM ([#4675](https://github.com/earendil-works/pi/issues/4675)). +- Fixed OpenAI prompt cache keys inherited from `@earendil-works/pi-ai` to stay within the 64-character provider limit ([#4720](https://github.com/earendil-works/pi/issues/4720)). +- Fixed Windows npm-family package commands for fnm-managed Node.js installs that expose both extensionless Unix scripts and `.cmd` shims ([#4793](https://github.com/earendil-works/pi/issues/4793)). + +## [0.75.3] - 2026-05-18 + +### Fixed + +- Fixed undici 8 HTTP/2 destroyed-session races crashing the Node CLI by preserving the previous HTTP/1.1-only fetch dispatcher behavior ([#4681](https://github.com/earendil-works/pi/issues/4681)). + +## [0.75.2] - 2026-05-18 + +### Fixed + +- Fixed Bun-compiled release binaries failing to start when Bun's built-in undici shim lacks npm undici's `install` export ([#4661](https://github.com/earendil-works/pi-mono/pull/4661) by [@dmasiero](https://github.com/dmasiero)). +- Fixed Xiaomi MiMo generated model metadata to replay assistant tool-call messages with `reasoning_content` for thinking-mode multi-turn requests, inherited from `@earendil-works/pi-ai` ([#4678](https://github.com/earendil-works/pi/issues/4678)). +- Fixed Windows external editor handoff so vim/nvim can receive input after opening from the TUI ([#4612](https://github.com/earendil-works/pi/issues/4612)). +- Fixed Windows npm self-updates to move loaded native dependency packages out of the active install before reinstalling pi ([#4157](https://github.com/earendil-works/pi/issues/4157)). +- Fixed `pi update --self` detection for pnpm v11 global installs whose package path resolves through the pnpm store ([#4647](https://github.com/earendil-works/pi/issues/4647)). +- Fixed Windows pnpm self-updates to resolve pnpm command shims and run through pnpm instead of requiring manual updates ([#4157](https://github.com/earendil-works/pi/issues/4157)). +- Fixed Windows npm-family command execution to use cross-spawn instead of parsing `.cmd` shim internals ([#4665](https://github.com/earendil-works/pi/issues/4665)). + +## [0.75.1] - 2026-05-18 + +### Fixed + +- Fixed config selectors to scale their visible row count to terminal height ([#4243](https://github.com/earendil-works/pi-mono/pull/4243) by [@samjonester](https://github.com/samjonester)). +- Fixed Anthropic-compatible API-key requests to ignore unrelated `ANTHROPIC_AUTH_TOKEN` environment values, avoiding invalid bearer credentials for providers such as Xiaomi MiMo inherited from `@earendil-works/pi-ai` ([#4342](https://github.com/earendil-works/pi/issues/4342)). +- Fixed Amazon Bedrock message conversion to skip unknown content blocks instead of failing the stream, inherited from `@earendil-works/pi-ai` ([#4223](https://github.com/earendil-works/pi/issues/4223)). +- Fixed Azure OpenAI Responses and OpenAI Responses error formatting to prefix HTTP status codes onto `errorMessage`, so transient 5xx and 429 errors are correctly matched by the agent-level auto-retry classifier inherited from `@earendil-works/pi-ai` ([#4232](https://github.com/earendil-works/pi/issues/4232)). +- Fixed OpenCode Go Kimi reasoning replay by normalizing streamed `reasoning` fields back to `reasoning_content` for OpenCode Go only, inherited from `@earendil-works/pi-ai` ([#4251](https://github.com/earendil-works/pi/issues/4251)). +- Fixed Xiaomi MiMo model metadata to use the OpenAI-compatible endpoints and `openai-completions` API, restoring multi-turn thinking/tool-call sessions inherited from `@earendil-works/pi-ai` ([#4505](https://github.com/earendil-works/pi/issues/4505)). +- Fixed JSON parse failures for compressed fetch responses under Node 26.0 by installing undici fetch globals alongside pi's global dispatcher ([#4650](https://github.com/earendil-works/pi/issues/4650), [#4652](https://github.com/earendil-works/pi/issues/4652), [#4653](https://github.com/earendil-works/pi/issues/4653)). +- Fixed npm-family package commands on Windows to avoid shell argument splitting when install prefixes contain spaces ([#4623](https://github.com/earendil-works/pi/issues/4623)). + +### Removed + +- Removed non-working OpenAI Codex fast model variants inherited from `@earendil-works/pi-ai`. + +## [0.75.0] - 2026-05-17 + +### Breaking Changes + +- Raised the minimum supported Node.js version to 22.19.0. + +### Fixed + +- Fixed compaction summary calls to use custom agent stream functions, preserving proxy-backed LLM routing ([#4484](https://github.com/earendil-works/pi/issues/4484)). +- Fixed system prompt and context file boundaries to use explicit XML tags instead of Markdown headings, reducing inconsistent boundary ingestion by models ([#4541](https://github.com/earendil-works/pi-mono/pull/4541) by [@herrnel](https://github.com/herrnel)). +- Fixed OpenAI Codex generated model metadata to use the current upstream model list inherited from `@earendil-works/pi-ai` ([#4603](https://github.com/earendil-works/pi-mono/pull/4603) by [@mattiacerutti](https://github.com/mattiacerutti)). +- Fixed GitHub Copilot GPT model thinking metadata inherited from `@earendil-works/pi-ai` to map unsupported minimal thinking to low ([#4622](https://github.com/earendil-works/pi-mono/pull/4622) by [@mattiacerutti](https://github.com/mattiacerutti)). +- Fixed user-scoped npm pi packages to install under `~/.pi/agent/npm/` instead of npm's global package root, avoiding permission errors with system-managed Node installs ([#4587](https://github.com/earendil-works/pi/issues/4587)). +- Fixed Mistral requests failing after the global fetch proxy/timeout workaround by removing the custom fetch override and using undici 8 dispatcher support instead ([#4619](https://github.com/earendil-works/pi/issues/4619)). +- Fixed default output token requests for models whose advertised output limit is effectively their full context window, avoiding impossible provider requests inherited from `@earendil-works/pi-ai` ([#4614](https://github.com/earendil-works/pi/issues/4614)). + +## [0.74.1] - 2026-05-16 + +### New Features + +- **Image generation support** - Added image generation APIs, generated image model metadata, and built-in OpenRouter image generation support inherited from `@earendil-works/pi-ai`. +- **Together AI provider** - Added Together AI as a built-in provider with `/login` API-key auth, default model resolution, and setup docs. See [README.md#providers--models](README.md#providers--models) and [docs/providers.md](docs/providers.md). +- **Windows ARM64 standalone binaries** - Added standalone release artifacts for Windows ARM64. +- **Improved terminal and markdown rendering** - Added markdown list indentation, task-list checkbox rendering, large markdown robustness, and inline image placement fixes inherited from `@earendil-works/pi-tui`. + +### Added + +- Added image generation support from `@earendil-works/pi-ai`, including image generation APIs, image model metadata, and built-in OpenRouter image generation support ([#3887](https://github.com/earendil-works/pi-mono/pull/3887) by [@cristinaponcela](https://github.com/cristinaponcela)). +- Added Together AI to built-in provider setup, `/login` API-key auth, and default model resolution ([#3624](https://github.com/earendil-works/pi-mono/pull/3624) by [@Nutlope](https://github.com/Nutlope)). +- Added Windows ARM64 standalone binary release artifacts ([#4458](https://github.com/earendil-works/pi/pull/4458) by [@brianmichel](https://github.com/brianmichel)). + +### Fixed + +- Fixed Node 26 OpenAI-compatible streams timing out after five idle minutes by routing global fetch through pi's undici dispatcher ([#4519](https://github.com/earendil-works/pi/issues/4519)). +- Fixed pnpm global package installs by resolving the global package root from pnpm's layout. +- Fixed macOS clipboard access errors under sandboxed pasteboard denial so they do not abort the process ([#4492](https://github.com/earendil-works/pi/issues/4492)). +- Fixed the scoped model startup hint to show the configured model-cycle keybinding ([#4508](https://github.com/earendil-works/pi/issues/4508)). +- Fixed resource path display to disambiguate package/resource names that collide across package locations. +- Fixed `fd` auto-download on macOS x86_64 by pinning the last release that ships an Intel macOS binary ([#4559](https://github.com/earendil-works/pi/issues/4559)). +- Fixed skill diagnostics to stop warning when a skill name differs from its parent directory ([#4534](https://github.com/earendil-works/pi/issues/4534)). +- Fixed prompt template argument parsing to split unquoted multiline input on newlines ([#4553](https://github.com/earendil-works/pi/issues/4553)). +- Fixed `--resume` session listing to cap in-flight session metadata loads and avoid OOM on large session histories ([#4583](https://github.com/earendil-works/pi/issues/4583)). +- Fixed interactive error messages to render with trailing spacing so reload errors do not run into resource listings ([#4510](https://github.com/earendil-works/pi/issues/4510)). +- Fixed `.agents` package provenance metadata to survive package-manager scans. +- Fixed nested code fences in the Termux setup documentation so the example AGENTS.md renders correctly ([#4503](https://github.com/earendil-works/pi/issues/4503)). +- Fixed tool output expansion while extension confirmation dialogs are focused ([#4429](https://github.com/earendil-works/pi/issues/4429)). +- Fixed auto-retry for Anthropic streams that end before `message_stop` ([#4433](https://github.com/earendil-works/pi/issues/4433)). +- Fixed compaction summary calls to clamp requested output tokens to model limits. +- Fixed uncaught interactive-mode exceptions to restore the terminal before exiting ([#4426](https://github.com/earendil-works/pi-mono/pull/4426) by [@ofa1](https://github.com/ofa1)). +- Fixed ANSI stripping to match `strip-ansi` behavior after dependency removal. +- Fixed UUIDv7 sequence generation shared by session IDs after dependency removal. +- Fixed OpenRouter cached-token usage accounting, Fireworks caching compatibility, and OpenAI Codex WebSocket proxy handling inherited from `@earendil-works/pi-ai`. +- Fixed markdown list wrapping, task-list checkboxes, large markdown rendering, WezTerm Kitty keyboard escape handling, and short-viewport inline image placement inherited from `@earendil-works/pi-tui`. +- Fixed theme sharing across package scopes so extensions do not crash with `Theme not initialized` ([#4333](https://github.com/earendil-works/pi/issues/4333)). +- Fixed keybinding hints to show Option instead of Alt on macOS ([#4289](https://github.com/earendil-works/pi/issues/4289)). +- Fixed the interactive update notification to render the changelog as an OSC 8 hyperlink when the terminal supports hyperlinks ([#4280](https://github.com/earendil-works/pi/issues/4280)). + +## [0.74.0] - 2026-05-07 + +### Changed + +- Updated repository links and package references for the move to `earendil-works/pi-mono` and `@earendil-works/*` package scopes. + +## [0.73.1] - 2026-05-07 + +### New Features + +- **Self-update support for the npm scope migration**: `pi update --self` now supports the upcoming package rename from `@mariozechner/pi-coding-agent` to `@earendil-works/pi-coding-agent`. After the new package is published, existing global installs can update through the normal self-update flow; pi will uninstall the old global package and install the package name returned by the version check endpoint. +- **Interactive OAuth login selection**: OAuth providers can now present multiple login choices in `/login`, enabling provider-specific interactive authentication flows. See [Providers](docs/providers.md). +- **JSONC-style `models.json` parsing**: `models.json` now allows comments and trailing commas, making custom provider and model configuration easier to maintain. See [Providers](docs/providers.md) and [Custom Providers](docs/custom-provider.md). + +### Added + +- Added interactive login selection support so OAuth providers can present multiple login choices ([#4190](https://github.com/earendil-works/pi-mono/pull/4190) by [@mitsuhiko](https://github.com/mitsuhiko)). + +### Changed + +- Changed `pi update --self` to honor the active package name returned by the Pi version check endpoint, defaulting to the current package when omitted and uninstalling the old global package before installing a renamed package. +- Changed extension loading to use upstream `jiti` 2.7 instead of the `@mariozechner/jiti` fork ([#4244](https://github.com/earendil-works/pi-mono/pull/4244) by [@pi0](https://github.com/pi0)). +- Changed `models.json` parsing to allow comments and trailing commas ([#4162](https://github.com/earendil-works/pi-mono/pull/4162) by [@julien-c](https://github.com/julien-c)). + +### Fixed + +- Fixed `pi -p` treating prompts that start with YAML frontmatter as extension flags instead of user messages ([#4163](https://github.com/badlogic/pi-mono/issues/4163)). +- Fixed pending tool results not updating in the live TUI after toggling thinking block visibility while the tool is running ([#4167](https://github.com/badlogic/pi-mono/issues/4167)). +- Fixed `/copy` reporting success on Linux without writing the clipboard on Wayland-only compositors (Hyprland, Niri, ...) by skipping the X11-only native addon on Linux and routing through `wl-copy`/`xclip`/`xsel` instead ([#4177](https://github.com/badlogic/pi-mono/issues/4177)). +- Fixed HTML session exports to strip skill wrapper XML from rendered user messages ([#4234](https://github.com/earendil-works/pi-mono/pull/4234) by [@aliou](https://github.com/aliou)). +- Fixed OpenAI-compatible chat completion streams that interleave content and tool-call deltas in the same choice. +- Fixed OpenAI Codex OAuth refresh failures writing directly to stderr while the TUI is active ([#4141](https://github.com/badlogic/pi-mono/issues/4141)). +- Fixed OpenAI Codex Responses requests to send a non-empty system prompt ([#4184](https://github.com/earendil-works/pi-mono/issues/4184)). +- Fixed Kimi For Coding model resolution for the Kimi K2 P6 alias ([#4218](https://github.com/earendil-works/pi-mono/issues/4218)). +- Fixed Kitty inline image redraws to stay within TUI-owned terminal regions and avoid writing below the active viewport. +- Fixed Kitty inline image rendering by letting the terminal allocate image ids and bounding parsed image ids to valid values. +- Fixed inline image capability detection to disable inline images in cmux terminals. + +## [0.73.0] - 2026-05-04 + +### New Features + +- **Xiaomi MiMo API billing and regional Token Plan providers** - `xiaomi` now uses API billing, with separate `xiaomi-token-plan-{cn,ams,sgp}` providers. See [docs/providers.md#api-keys](docs/providers.md#api-keys) and [README.md#providers--models](README.md#providers--models). ([#4112](https://github.com/badlogic/pi-mono/pull/4112) by [@Phoen1xCode](https://github.com/Phoen1xCode)) +- **Incremental bash output streaming** - Bash tool output now appears while commands run instead of only after completion. ([#4145](https://github.com/badlogic/pi-mono/issues/4145)) +- **Compact read rendering** - Interactive `read` output for Pi docs, context files, and skills is collapsed by default and shows selected line ranges. + +### Breaking Changes + +- Switched the built-in `xiaomi` provider from Token Plan AMS to Xiaomi's API billing endpoint, and renamed its `/login` display from "Xiaomi MiMo Token Plan" to "Xiaomi MiMo". `XIAOMI_API_KEY` now refers to the API billing key from [platform.xiaomimimo.com](https://platform.xiaomimimo.com). Users on Token Plan should switch to the appropriate `xiaomi-token-plan-*` provider and set the corresponding env var ([#4112](https://github.com/badlogic/pi-mono/pull/4112) by [@Phoen1xCode](https://github.com/Phoen1xCode)). + +### Added + +- Added three Xiaomi MiMo Token Plan regional providers visible in `/login`: `xiaomi-token-plan-cn` (`XIAOMI_TOKEN_PLAN_CN_API_KEY`), `xiaomi-token-plan-ams` (`XIAOMI_TOKEN_PLAN_AMS_API_KEY`), `xiaomi-token-plan-sgp` (`XIAOMI_TOKEN_PLAN_SGP_API_KEY`). Each defaults to `mimo-v2.5-pro` ([#4112](https://github.com/badlogic/pi-mono/pull/4112) by [@Phoen1xCode](https://github.com/Phoen1xCode)). + +### Changed + +- Changed `read` tool rendering to collapse Pi documentation, AGENTS/CLAUDE context files, and `SKILL.md` contents by default in interactive output. + +### Fixed + +- Fixed generated OpenAI-compatible model metadata for Qwen 3.5/3.6 and MiniMax M2.7, so those models work through the built-in provider catalog ([#4110](https://github.com/badlogic/pi-mono/pull/4110) by [@jsynowiec](https://github.com/jsynowiec)). +- Fixed Bedrock Claude Opus 4.7 `xhigh` thinking requests by preserving the provider's native effort value. +- Fixed OpenAI Codex WebSocket transport to fall back to SSE when setup fails before streaming starts, and surface transport diagnostics in the assistant message ([#4133](https://github.com/badlogic/pi-mono/issues/4133)). +- Fixed OpenAI Codex WebSocket transport keeping `--print` and JSON mode processes alive after the response by closing cached WebSocket sessions during session shutdown ([#4103](https://github.com/badlogic/pi-mono/issues/4103)). +- Fixed compact `read` tool calls to render directly and include selected line ranges in interactive output. +- Fixed interactive sessions to exit when terminal input is lost instead of continuing in a broken state. +- Fixed bash tool output to stream incrementally while commands run instead of waiting for command completion ([#4145](https://github.com/badlogic/pi-mono/issues/4145)). +- Fixed selector and autocomplete fuzzy ranking to prioritize exact matches. + +## [0.72.1] - 2026-05-02 + +## [0.72.0] - 2026-05-01 + +### New Features + +- **Xiaomi MiMo Token Plan provider** - New Anthropic-compatible provider with `XIAOMI_API_KEY` auth, default model (`mimo-v2.5-pro`), and `/login` display. See [docs/providers.md](docs/providers.md). ([#4005](https://github.com/badlogic/pi-mono/pull/4005) by [@Phoen1xCode](https://github.com/Phoen1xCode)). +- **Model thinking level metadata** - Models can now declare which thinking levels they support via `thinkingLevelMap`, replacing the old `reasoningEffortMap`. See [docs/models.md#thinking-level-map](docs/models.md#thinking-level-map) and [docs/custom-provider.md](docs/custom-provider.md). ([#3208](https://github.com/badlogic/pi-mono/issues/3208)). +- **Custom provider base URL overrides** - `pi.registerProvider()` now respects per-model `baseUrl` settings. See [docs/custom-provider.md](docs/custom-provider.md). ([#4063](https://github.com/badlogic/pi-mono/issues/4063)). +- **Post-turn stop callback** - Agent loop can now exit gracefully after a completed turn via `shouldStopAfterTurn`. See [`packages/agent/README.md`](https://github.com/badlogic/pi-mono/blob/main/packages/agent/README.md). +- **Self-update detection fix** - `pi` now correctly identifies and applies available updates. ([#3942](https://github.com/badlogic/pi-mono/issues/3942), [#3980](https://github.com/badlogic/pi-mono/issues/3980), [#3922](https://github.com/badlogic/pi-mono/issues/3922)). + +### Breaking Changes + +- Replaced `compat.reasoningEffortMap` in `models.json` and `pi.registerProvider()` model definitions with model-level `thinkingLevelMap` ([#3208](https://github.com/badlogic/pi-mono/issues/3208)). Migration: move old mappings from `compat.reasoningEffortMap` to `thinkingLevelMap`. Use string values for provider-specific thinking values and `null` for unsupported pi levels that should be hidden and skipped by cycling. See `docs/models.md#thinking-level-map` and `docs/custom-provider.md`. + +### Added + +- Added Xiaomi MiMo Token Plan provider support with `XIAOMI_API_KEY`, default model resolution, `/login` display support, and provider documentation ([#4005](https://github.com/badlogic/pi-mono/pull/4005) by [@Phoen1xCode](https://github.com/Phoen1xCode)). +- Added model-level `thinkingLevelMap` support in `models.json` and `pi.registerProvider()`, allowing models to expose only the thinking levels they actually support ([#3208](https://github.com/badlogic/pi-mono/issues/3208)). +- Added `shouldStopAfterTurn` agent loop callback for post-turn stop control, inherited from `@mariozechner/pi-agent-core`. See [`packages/agent/README.md`](https://github.com/badlogic/pi-mono/blob/main/packages/agent/README.md). + +### Fixed + +- Fixed the default transport setting to use `auto`, allowing OpenAI Codex to use cached WebSocket context when available ([#4083](https://github.com/badlogic/pi-mono/issues/4083)). +- Fixed `pi.registerProvider()` to honor per-model `baseUrl` overrides ([#4063](https://github.com/badlogic/pi-mono/issues/4063)). +- Fixed self-update detection so `pi` correctly identifies when a newer version is available and applies updates ([#3942](https://github.com/badlogic/pi-mono/issues/3942), [#3980](https://github.com/badlogic/pi-mono/issues/3980), [#3922](https://github.com/badlogic/pi-mono/issues/3922)). + +## [0.71.1] - 2026-05-01 + +### Added + +- Added `websocket-cached` to the transport setting options for the OpenAI Codex provider used with ChatGPT subscription auth. This keeps the same WebSocket open for a session and, after the first request, sends only the new conversation items instead of resending the full chat history when possible. + +## [0.71.0] - 2026-04-30 + +### Breaking Changes + +- Removed built-in Google Gemini CLI and Google Antigravity support. Existing configurations using those providers must switch to another supported provider. + +### New Features + +- Cloudflare AI Gateway provider support with `CLOUDFLARE_API_KEY`/`CLOUDFLARE_ACCOUNT_ID`/`CLOUDFLARE_GATEWAY_ID`, default model resolution, and `/login` display. See [docs/providers.md#cloudflare-ai-gateway](docs/providers.md#cloudflare-ai-gateway). ([#3856](https://github.com/badlogic/pi-mono/pull/3856) by [@mchenco](https://github.com/mchenco)). +- Moonshot AI provider support with `MOONSHOT_API_KEY`, default model resolution, and `/login` display. +- Mistral Medium 3.5 built-in model support. See [docs/providers.md#api-keys](docs/providers.md#api-keys). ([#4009](https://github.com/badlogic/pi-mono/pull/4009) by [@technocidal](https://github.com/technocidal)). +- Extension APIs can replace finalized `message_end` messages, wrap custom editor factories via `ctx.ui.getEditorComponent()`, and observe thinking level changes. See [docs/extensions.md#message_start--message_update--message_end](docs/extensions.md#message_start--message_update--message_end), [docs/extensions.md#widgets-status-and-footer](docs/extensions.md#widgets-status-and-footer), and [docs/extensions.md#thinking_level_select](docs/extensions.md#thinking_level_select). +- `PI_CODING_AGENT_SESSION_DIR` configures session storage from the environment. See [docs/usage.md#environment-variables](docs/usage.md#environment-variables). + +### Added + +- Added Cloudflare AI Gateway as a built-in provider with `CLOUDFLARE_API_KEY`/`CLOUDFLARE_ACCOUNT_ID`/`CLOUDFLARE_GATEWAY_ID` setup, default model resolution, `/login` display support, and provider documentation ([#3856](https://github.com/badlogic/pi-mono/pull/3856) by [@mchenco](https://github.com/mchenco)). +- Added Moonshot AI as a built-in provider with `MOONSHOT_API_KEY` setup, default model resolution, and `/login` display support. +- Added Mistral Medium 3.5 built-in model support via `@mariozechner/pi-ai` ([#4009](https://github.com/badlogic/pi-mono/pull/4009) by [@technocidal](https://github.com/technocidal)). +- Added routed OpenAI-compatible response model metadata in assistant messages, so providers such as OpenRouter can expose the concrete model used ([#3968](https://github.com/badlogic/pi-mono/pull/3968) by [@purrgrammer](https://github.com/purrgrammer)). +- Added `PI_CODING_AGENT_SESSION_DIR` as an environment equivalent to `--session-dir` ([#4027](https://github.com/badlogic/pi-mono/issues/4027)). +- Added `message_end` extension result support for replacing finalized messages, enabling extensions to override assistant usage cost ([#3982](https://github.com/badlogic/pi-mono/issues/3982)). +- Added top-level `name` support to `pi.registerProvider()` so extension-registered providers can show a friendly name in `/login` ([#3956](https://github.com/badlogic/pi-mono/issues/3956)). +- Added `ctx.ui.getEditorComponent()` so extensions can wrap the currently configured custom editor factory ([#3935](https://github.com/badlogic/pi-mono/issues/3935)). +- Added a `thinking_level_select` extension event for observing thinking level changes ([#3888](https://github.com/badlogic/pi-mono/issues/3888)). + +### Fixed + +- Fixed WSL clipboard image paste by passing the PowerShell save path directly instead of through a custom environment variable ([#2469](https://github.com/badlogic/pi-mono/issues/2469)). +- Fixed Google Vertex Gemini 3 tool call replay for unsigned tool calls ([#4032](https://github.com/badlogic/pi-mono/issues/4032)). +- Fixed blocked `edit` tool results rendering the rejection reason twice after interactive extension confirmation ([#3830](https://github.com/badlogic/pi-mono/issues/3830)). +- Fixed extension-triggered thinking level changes refreshing the interactive editor border immediately ([#3888](https://github.com/badlogic/pi-mono/issues/3888)). +- Fixed the coding-agent README See Also link to point at `@mariozechner/pi-agent-core` ([#4023](https://github.com/badlogic/pi-mono/issues/4023)). +- Fixed `grep` and `find` tool argument injection for flag-like search patterns ([#4018](https://github.com/badlogic/pi-mono/issues/4018)). +- Fixed PowerShell shell command output on Windows by only spawning detached processes on Unix ([#4013](https://github.com/badlogic/pi-mono/pull/4013) by [@picasso250](https://github.com/picasso250)). +- Fixed Bun package manager `node_modules` discovery when `npmCommand` is configured to use Bun ([#3998](https://github.com/badlogic/pi-mono/pull/3998) by [@thirtythreeforty](https://github.com/thirtythreeforty)). +- Fixed edit and edit-preview access failures to report filesystem errors correctly ([#3955](https://github.com/badlogic/pi-mono/pull/3955) by [@rwachtler](https://github.com/rwachtler)). +- Fixed `ProcessTerminal` sizing to use `COLUMNS` and `LINES` before falling back to 80x24 ([#4004](https://github.com/badlogic/pi-mono/issues/4004)). +- Updated `@anthropic-ai/sdk` to clear GHSA-p7fg-763f-g4gf audit findings ([#3992](https://github.com/badlogic/pi-mono/issues/3992)). +- Updated `@mariozechner/clipboard` to an attested release so package managers with trust policies do not reject installs ([#3946](https://github.com/badlogic/pi-mono/issues/3946)). +- Fixed project context discovery to load `AGENTS.MD` files in addition to `AGENTS.md` ([#3949](https://github.com/badlogic/pi-mono/issues/3949)). +- Fixed `/handoff` to use compacted session context instead of pre-compaction raw messages ([#3945](https://github.com/badlogic/pi-mono/issues/3945)). +- Fixed DeepSeek V4 Flash `xhigh` thinking support so requests map to DeepSeek's `max` reasoning effort ([#3944](https://github.com/badlogic/pi-mono/issues/3944)). +- Fixed Anthropic streams that end before `message_stop` to be treated as errors instead of successful partial responses ([#3936](https://github.com/badlogic/pi-mono/issues/3936)). +- Fixed generated OpenAI-compatible DeepSeek V4 reasoning compatibility outside the direct DeepSeek provider ([#3940](https://github.com/badlogic/pi-mono/issues/3940)). +- Fixed idle follow-up submission to clear the editor like normal message submission ([#3926](https://github.com/badlogic/pi-mono/issues/3926)). +- Fixed editor rendering artifacts for Thai Sara Am and Lao AM vowel characters ([#3904](https://github.com/badlogic/pi-mono/issues/3904)). +- Fixed DeepSeek V4 Flash and V4 Pro pricing metadata to match current official rates ([#3910](https://github.com/badlogic/pi-mono/issues/3910)). +- Updated the sandbox extension example lockfile to resolve the vulnerable `lodash-es` transitive dependency ([#3901](https://github.com/badlogic/pi-mono/issues/3901)). +- Fixed DeepSeek prompt cache hits to be tracked from OpenAI-compatible usage responses ([#3880](https://github.com/badlogic/pi-mono/issues/3880)). + +### Removed + +- Removed the discontinued Qwen CLI OAuth custom provider extension example ([#3832](https://github.com/badlogic/pi-mono/pull/3832) by [@4h9fbZ](https://github.com/4h9fbZ)). +- Removed Google Gemini CLI and Google Antigravity built-in login, default model, documentation, and example extension support. + +## [0.70.6] - 2026-04-28 + +### New Features + +- Cloudflare Workers AI provider support with `CLOUDFLARE_API_KEY`/`CLOUDFLARE_ACCOUNT_ID` setup. See [docs/providers.md#api-keys](docs/providers.md#api-keys). ([#3851](https://github.com/badlogic/pi-mono/pull/3851) by [@mchenco](https://github.com/mchenco)) +- Pi update checks now use `pi.dev` and identify Pi with a `pi/` user agent. See [docs/packages.md](docs/packages.md). ([#3877](https://github.com/badlogic/pi-mono/pull/3877) by [@mitsuhiko](https://github.com/mitsuhiko)) + +### Added + +- Added Cloudflare Workers AI as a built-in provider with `CLOUDFLARE_API_KEY`/`CLOUDFLARE_ACCOUNT_ID` setup, default model resolution, `/login` support, and provider documentation ([#3851](https://github.com/badlogic/pi-mono/pull/3851) by [@mchenco](https://github.com/mchenco)). + +### Changed + +- Changed Pi version checks to identify Pi with a `pi/` user agent ([#3877](https://github.com/badlogic/pi-mono/pull/3877) by [@mitsuhiko](https://github.com/mitsuhiko)). + +### Fixed + +- Fixed config selector scroll indicators to show item counts instead of line counts ([#3820](https://github.com/badlogic/pi-mono/pull/3820) by [@aliou](https://github.com/aliou)). +- Fixed exported HTML to escape embedded image data and session metadata, preventing crafted session content from injecting markup ([#3819](https://github.com/badlogic/pi-mono/pull/3819) by [@justinpbarnett](https://github.com/justinpbarnett), [#3883](https://github.com/badlogic/pi-mono/pull/3883) by [@justinpbarnett](https://github.com/justinpbarnett)). +- Fixed Bun-based package manager startup by locating global `node_modules` relative to Bun's install layout ([#3861](https://github.com/badlogic/pi-mono/pull/3861) by [@thirtythreeforty](https://github.com/thirtythreeforty)). +- Fixed Bedrock inference profile capability checks by normalizing profile ARNs to the underlying model name. +- Fixed file discovery to fall back to `fdfind` when `fd` is unavailable. +- Fixed `pi update` to skip self-update reinstalls when the installed version is already current ([#3853](https://github.com/badlogic/pi-mono/issues/3853)). +- Fixed Cloudflare Workers AI attribution headers to honor the install telemetry setting. +- Fixed `pi update --self` detection and execution for Windows package-manager shim installs, including symlinked global package roots, and print the manual fallback command when self-update fails ([#3857](https://github.com/badlogic/pi-mono/issues/3857)). + +## [0.70.5] - 2026-04-27 + +### Fixed + +- Fixed HTML export preserving ANSI-renderer trailing padding as extra blank wrapped lines. + +## [0.70.4] - 2026-04-27 + +### Fixed + +- Fixed packaged `pi` startup failing because the session selector imported a source-only utility path. + +## [0.70.3] - 2026-04-27 + +### New Features + +- `pi update` can now update pi itself in addition to installed pi packages. See [docs/packages.md](docs/packages.md). ([#3680](https://github.com/badlogic/pi-mono/pull/3680) by [@mitsuhiko](https://github.com/mitsuhiko)) +- Azure Cognitive Services endpoint support for Azure OpenAI Responses deployments. See [docs/providers.md#api-keys](docs/providers.md#api-keys). ([#3799](https://github.com/badlogic/pi-mono/pull/3799) by [@marcbloech](https://github.com/marcbloech)) +- Suppressible Anthropic extra-usage billing warning via `warnings.anthropicExtraUsage` in `/settings`. See [docs/settings.md](docs/settings.md). ([#3808](https://github.com/badlogic/pi-mono/issues/3808)) +- Extension-controlled working row visibility via `ctx.ui.setWorkingVisible()`, allowing extensions to hide the built-in loader row and render custom working state. See [docs/extensions.md](docs/extensions.md) and [examples/extensions/border-status-editor.ts](examples/extensions/border-status-editor.ts). ([#3674](https://github.com/badlogic/pi-mono/issues/3674)) + +### Added + +- Added `pi update` support for updating pi itself in addition to installed pi packages ([#3680](https://github.com/badlogic/pi-mono/pull/3680) by [@mitsuhiko](https://github.com/mitsuhiko)). +- Added Azure Cognitive Services endpoint support for Azure OpenAI Responses base URLs ([#3799](https://github.com/badlogic/pi-mono/pull/3799) by [@marcbloech](https://github.com/marcbloech)). +- Added `warnings.anthropicExtraUsage` and a `/settings` warnings submenu to suppress the Anthropic extra usage billing warning ([#3808](https://github.com/badlogic/pi-mono/issues/3808)) +- Added `ctx.ui.setWorkingVisible()` so extensions can hide the built-in interactive working loader row without reserving layout space, plus a border-status editor example that moves working state into a custom editor border ([#3674](https://github.com/badlogic/pi-mono/issues/3674)) + +### Fixed + +- Fixed duplicate printable characters from Kitty keyboard protocol CSI-u plus raw character input on layouts such as Italian ([#3780](https://github.com/badlogic/pi-mono/issues/3780)). +- Fixed API-key environment discovery and Bun startup to fall back to `/proc/self/environ` when Bun's sandbox leaves `process.env` empty ([#3801](https://github.com/badlogic/pi-mono/pull/3801) by [@mdsjip](https://github.com/mdsjip)). +- Fixed Bun sandboxed package-manager commands when `process.env` is empty ([#3807](https://github.com/badlogic/pi-mono/pull/3807) by [@mdsjip](https://github.com/mdsjip)). +- Fixed symlinked packages, resources, skills, and sessions being duplicated in selectors and loaders ([#3818](https://github.com/badlogic/pi-mono/pull/3818) by [@aliou](https://github.com/aliou)). +- Fixed Bedrock prompt-caching and adaptive-thinking capability checks for inference profile ARNs ([#3527](https://github.com/badlogic/pi-mono/pull/3527) by [@anirudhmarc](https://github.com/anirudhmarc)). +- Fixed OpenAI Codex Responses default verbosity to `low` when no verbosity is specified. +- Stopped sending empty `tools` arrays to providers that reject them when tools are disabled ([#3650](https://github.com/badlogic/pi-mono/pull/3650) by [@HQidea](https://github.com/HQidea)). +- Fixed Anthropic SSE parsing to ignore unknown proxy events such as OpenAI-style `done` terminators ([#3708](https://github.com/badlogic/pi-mono/issues/3708)). +- Fixed provider registration with override-only `models.json` entries to preserve built-in model lists ([#3651](https://github.com/badlogic/pi-mono/issues/3651)). +- Fixed `/login` to show auth supplied by `models.json` provider definitions. +- Fixed HTML export whitespace around extension-rendered tool output and expandable output hints. +- Fixed bash executor temp output streams leaking file descriptors when output was truncated by line count ([#3786](https://github.com/badlogic/pi-mono/issues/3786)) +- Fixed extension `pi.setSessionName()` updates to refresh the interactive terminal title immediately ([#3686](https://github.com/badlogic/pi-mono/issues/3686)) +- Fixed `/tree` cancellation via `session_before_tree` leaving the session stuck in compaction state ([#3688](https://github.com/badlogic/pi-mono/issues/3688)) +- Fixed Escape interrupt handling when extensions hide the built-in working loader row ([#3674](https://github.com/badlogic/pi-mono/issues/3674)) +- Fixed coding-agent test expectations for current default models and missing-auth guidance. +- Fixed long local-LLM SSE streams aborting at 5 minutes with `UND_ERR_BODY_TIMEOUT` by disabling undici `bodyTimeout`/`headersTimeout` on the global dispatcher; provider SDKs continue to enforce their own deadlines via `retry.provider.timeoutMs` ([#3715](https://github.com/badlogic/pi-mono/issues/3715)) + +## [0.70.2] - 2026-04-24 + +### Fixed + +- Fixed provider retry/timeout forwarding to omit undefined provider request controls, avoiding downstream SDK validation errors such as `timeout must be an integer` when `retry.provider.timeoutMs` is not configured ([#3627](https://github.com/badlogic/pi-mono/issues/3627)) + +## [0.70.1] - 2026-04-24 + +### New Features + +- DeepSeek provider support with V4 Flash/Pro models and `DEEPSEEK_API_KEY` authentication. See [README.md#providers--models](README.md#providers--models) and [docs/providers.md#api-keys](docs/providers.md#api-keys). +- Provider request timeout/retry controls via `retry.provider.{timeoutMs,maxRetries,maxRetryDelayMs}`, useful for long-running local inference and provider SDK retry behavior. See [docs/settings.md#retry](docs/settings.md#retry). ([#3627](https://github.com/badlogic/pi-mono/issues/3627)) + +### Added + +- Added DeepSeek to built-in provider setup, default model resolution, and provider documentation. + +### Fixed + +- Fixed `/copy` to avoid unbounded OSC 52 writes and clipboard races that could break terminal rendering or panic the native clipboard addon ([#3639](https://github.com/badlogic/pi-mono/issues/3639)) +- Fixed extension flag docs to show `pi.getFlag()` using registered flag names without the CLI `--` prefix ([#3614](https://github.com/badlogic/pi-mono/issues/3614)) +- Fixed provider retry/timeout settings wiring by adding `retry.provider.{timeoutMs,maxRetries,maxRetryDelayMs}`, migrating legacy `retry.maxDelayMs`, and forwarding provider controls into `streamSimple` request options ([#3627](https://github.com/badlogic/pi-mono/issues/3627)) +- Fixed Windows git package installs to bypass `cmd.exe` for native git commands, so install paths containing spaces no longer break `pi install git:...` with `fatal: Too many arguments` ([#3642](https://github.com/badlogic/pi-mono/issues/3642)) +- Fixed DeepSeek V4 session replay 400 errors by sending DeepSeek-compatible thinking controls and replayed assistant `reasoning_content` fields ([#3636](https://github.com/badlogic/pi-mono/issues/3636)) +- Fixed GPT-5.5 generated context window metadata to use the observed 272k limit. +- Fixed CSI-u Ctrl+letter decoding inside bracketed paste, so pasted modified-key escape sequences no longer become literal editor text ([#3623](https://github.com/badlogic/pi-mono/pull/3623) by [@Exrun94](https://github.com/Exrun94)) + +## [0.70.0] - 2026-04-23 + +### New Features + +- Searchable auth provider login flow: the `/login` provider selector now supports fuzzy search/filtering, making it faster to find providers when many are configured. See [docs/providers.md](docs/providers.md). ([#3572](https://github.com/badlogic/pi-mono/pull/3572) by [@mitsuhiko](https://github.com/mitsuhiko)) +- GPT-5.5 Codex support: `openai-codex/gpt-5.5` is available as a model option, including `xhigh` reasoning support and corrected priority-tier pricing. +- Terminal progress indicators are now opt-in: OSC 9;4 progress reporting during streaming/compaction is off by default and can be toggled via `terminal.showTerminalProgress` in `/settings` ([#3588](https://github.com/badlogic/pi-mono/issues/3588)) +- `--no-builtin-tools` / `createAgentSession({ noTools: "builtin" })` now correctly disables only built-in tools while keeping extension tools active. See [docs/extensions.md](docs/extensions.md) and [README.md](README.md) ([#3592](https://github.com/badlogic/pi-mono/issues/3592)) + +### Breaking Changes + +- Disabled OSC 9;4 terminal progress indicators by default. Set `terminal.showTerminalProgress` to `true` in `/settings` to re-enable ([#3588](https://github.com/badlogic/pi-mono/issues/3588)) + +### Added + +- Added searchable auth provider login flow with fuzzy filtering in the provider selector ([#3572](https://github.com/badlogic/pi-mono/pull/3572) by [@mitsuhiko](https://github.com/mitsuhiko)) +- Added GPT-5.5 Codex model +- Added auth source labels in `/login` so provider entries can show when auth comes from `--api-key`, an environment variable, or custom provider fallback without exposing secrets. + +### Changed + +- Updated default model selection across providers to current recommended models. +- Improved stale extension context errors after session replacement or reload to tell extension authors to avoid captured `pi`/command `ctx` and use `withSession` for post-replacement work. + +### Fixed + +- Fixed `/model` selector cancellation to request render instead of incorrectly triggering login selector. +- Changed login, OAuth, and extension selectors for more consistent styling. +- Added Amazon Bedrock setup guidance to `/login` and updated `/model` copy to refer to configured providers instead of only API keys. +- Improved no-model and missing-auth warnings to point users to `/login` for OAuth or API key setup. +- Fixed `/quit` shutdown ordering to stop the TUI before extension UI teardown can repaint, preserving the final rendered frame while still emitting `session_shutdown` before process exit. +- Fixed `SettingsManager.inMemory()` initial settings being lost after reloads triggered by SDK resource loading ([#3616](https://github.com/badlogic/pi-mono/issues/3616)) +- Fixed `models.json` provider compatibility to accept `compat.supportsLongCacheRetention`, allowing proxies to opt out of long-retention cache fields when needed while long retention is enabled by default when requested ([#3543](https://github.com/badlogic/pi-mono/issues/3543)) +- Fixed `--thinking xhigh` for `openai-codex` `gpt-5.5` so it is no longer downgraded to `high`. +- Fixed git package installs with custom `npmCommand` values such as `pnpm` by avoiding npm-specific production flags in that compatibility path ([#3604](https://github.com/badlogic/pi-mono/issues/3604)) +- Fixed first user messages rendering without spacing after existing notices such as compaction summaries or status messages ([#3613](https://github.com/badlogic/pi-mono/issues/3613)) +- Fixed the handoff extension example to use the replacement-session context after creating a new session, avoiding stale `ctx` errors when it installs the generated prompt ([#3606](https://github.com/badlogic/pi-mono/issues/3606)) +- Fixed session replacement and `/quit` teardown ordering to run host-owned extension UI cleanup synchronously after `session_shutdown` handlers complete but before invalidating the old extension context, preventing stale extension UI from rendering against a disposed session ([#3597](https://github.com/badlogic/pi-mono/pull/3597) by [@vegarsti](https://github.com/vegarsti)) +- Fixed crash on `/quit` when an extension registers a custom footer whose `render()` accesses `ctx`, by tearing down extension-provided UI before invalidating the extension runner during shutdown ([#3595](https://github.com/badlogic/pi-mono/issues/3595)) +- Fixed auto-retry to treat Bedrock/Smithy HTTP/2 transport failures like `http2 request did not get a response` as transient errors, so the agent retries automatically instead of waiting for a manual nudge ([#3594](https://github.com/badlogic/pi-mono/issues/3594)) +- Fixed the CLI/SDK tool-selection split so `--no-builtin-tools` and `createAgentSession({ noTools: "builtin" })` disable only built-in default tools while keeping extension/custom tools enabled, instead of falling through to the same "disable everything" path as `--no-tools` ([#3592](https://github.com/badlogic/pi-mono/issues/3592)) +- Fixed remaining hardcoded `pi` / `.pi` branding to route through `APP_NAME` and `CONFIG_DIR_NAME` extension points, so SDK rebrands get consistent naming in `/quit` description, `process.title`, and the project-local extensions directory ([#3583](https://github.com/badlogic/pi-mono/pull/3583) by [@jlaneve](https://github.com/jlaneve)) +- Fixed `pi-coding-agent` shipping `uuid@11`, which triggered `npm audit` moderate vulnerability reports for downstream installs; the package now depends on `uuid@14` ([#3577](https://github.com/badlogic/pi-mono/issues/3577)) +- Fixed `openai-completions` streamed tool-call assembly to coalesce deltas by stable tool index when OpenAI-compatible gateways mutate tool call IDs mid-stream, preventing malformed Kimi K2.6/OpenCode tool streams from splitting one call into multiple bogus tool calls ([#3576](https://github.com/badlogic/pi-mono/issues/3576)) +- Fixed `ctx.ui.setWorkingMessage()` to persist across loader recreation, matching the behavior of `ctx.ui.setWorkingIndicator()` ([#3566](https://github.com/badlogic/pi-mono/issues/3566)) +- Fixed coding-agent `fs.watch` error handling for theme and git-footer watchers to retry after transient watcher failures such as `EMFILE`, avoiding startup crashes in large repos ([#3564](https://github.com/badlogic/pi-mono/issues/3564)) +- Fixed built-in `kimi-coding` model generation to attach the expected `User-Agent` header so direct Kimi Coding requests use the provider's expected client identity ([#3586](https://github.com/badlogic/pi-mono/issues/3586)) +- Fixed extension shortcut conflict diagnostics to display at startup instead of only on reload, so extension authors discover reserved keybinding conflicts immediately rather than discovering them later through user feedback ([#3617](https://github.com/badlogic/pi-mono/issues/3617)) +- Fixed `models.json` Anthropic-compatible provider configuration to accept `compat.supportsEagerToolInputStreaming`, allowing proxies that reject per-tool `eager_input_streaming` to use the legacy fine-grained tool streaming beta header instead ([#3575](https://github.com/badlogic/pi-mono/issues/3575)) +- Fixed startup banner extension labels to strip trailing `index.js`/`index.ts` suffixes ([#3596](https://github.com/badlogic/pi-mono/pull/3596) by [@aliou](https://github.com/aliou)) +- Fixed OSC 9;4 terminal progress updates to stay alive in terminals such as Ghostty during long-running agent work ([#3610](https://github.com/badlogic/pi-mono/issues/3610)) +- Fixed OpenAI-compatible completion usage parsing to avoid double-counting reasoning tokens already included in `completion_tokens` ([#3581](https://github.com/badlogic/pi-mono/issues/3581)) +- Fixed `openai-responses` compatibility for strict OpenAI-compatible proxies by allowing `models.json` to disable the underscore-containing `session_id` header with `compat.sendSessionIdHeader: false` ([#3579](https://github.com/badlogic/pi-mono/issues/3579)) +- Fixed GPT-5.5 Codex capability handling to clamp unsupported minimal reasoning to `low` and apply the model's 2.5x priority service-tier pricing multiplier ([#3618](https://github.com/badlogic/pi-mono/pull/3618) by [@markusylisiurunen](https://github.com/markusylisiurunen)) + +## [0.69.0] - 2026-04-22 + +### New Features + +- TypeBox 1.x migration for extensions and SDK integrations, including TypeBox-native tool argument validation that now works in eval-restricted runtimes such as Cloudflare Workers. See [docs/extensions.md](docs/extensions.md) and [docs/sdk.md](docs/sdk.md). +- Stacked extension autocomplete providers via `ctx.ui.addAutocompleteProvider(...)`, allowing extensions to layer custom completion logic on top of built-in slash and path completion. See [docs/extensions.md#autocomplete-providers](docs/extensions.md#autocomplete-providers) and [examples/extensions/github-issue-autocomplete.ts](examples/extensions/github-issue-autocomplete.ts). +- Terminating tool results via `terminate: true`, allowing custom tools to end on a final tool call without paying for an automatic follow-up LLM turn. See [docs/extensions.md](docs/extensions.md) and [examples/extensions/structured-output.ts](examples/extensions/structured-output.ts). +- OSC 9;4 terminal progress indicators during agent streaming and compaction for supporting terminals. + +### Breaking Changes + +- Migrated first-party coding-agent code, SDK/examples/docs, and package metadata from `@sinclair/typebox` 0.34.x to `typebox` 1.x. New extensions, SDK integrations, and pi packages should depend on and import from `typebox`. Legacy extension loading still aliases the root `@sinclair/typebox` package, but `@sinclair/typebox/compiler` is no longer shimmed. This migration also picks up the new `@mariozechner/pi-ai` TypeBox-native validator path, so tool argument validation now works in eval-restricted runtimes such as Cloudflare Workers instead of being skipped ([#3112](https://github.com/badlogic/pi-mono/issues/3112)) +- Session-replacement commands now invalidate captured pre-replacement session-bound extension objects after `ctx.newSession()`, `ctx.fork()`, and `ctx.switchSession()`. Old `pi` and command `ctx` references now throw instead of silently targeting the replaced session. Migration: if code needs to keep working in the replacement session after one of those calls, pass `withSession` to that same method and do the post-switch work there. In practice, move post-switch `pi.sendUserMessage()`, `pi.sendMessage()`, and command-ctx/session-manager access into `withSession`, and use only the `ReplacedSessionContext` passed to that callback for session-bound operations. Footguns: `withSession` runs after the old extension instance has already received `session_shutdown`, old cleanup may already have invalidated captured state, captured old `pi` / old command `ctx` are stale, and previously extracted raw objects such as `const sm = ctx.sessionManager` remain the caller's responsibility and must not be reused after the switch. + +### Added + +- Added support for terminating tool results via `terminate: true`, allowing custom tools to end the current tool batch without an automatic follow-up LLM call, plus a `structured-output.ts` extension example and extension docs showing the pattern ([#3525](https://github.com/badlogic/pi-mono/issues/3525)) +- Added OSC 9;4 terminal progress indicators during agent streaming and compaction, so terminals like iTerm2, WezTerm, Windows Terminal, and Kitty show activity in their tab bar +- Added `ctx.ui.addAutocompleteProvider(...)` for stacking extension autocomplete providers on top of the built-in slash/path provider, plus a `github-issue-autocomplete.ts` example and extension docs ([#2983](https://github.com/badlogic/pi-mono/issues/2983)) + +### Fixed + +- Fixed exported session HTML to sanitize markdown link URLs before rendering them into anchor tags, blocking `javascript:`-style payloads while preserving safe links in shared/exported sessions ([#3532](https://github.com/badlogic/pi-mono/issues/3532)) +- Fixed `ctx.getSystemPrompt()` inside `before_agent_start` to reflect chained system-prompt changes made by earlier `before_agent_start` handlers, and clarified the extension docs around provider-payload rewrites and what `ctx.getSystemPrompt()` does and does not report ([#3539](https://github.com/badlogic/pi-mono/issues/3539)) +- Fixed built-in `google-gemini-cli` model lists and selector entries to include `gemini-3.1-flash-lite-preview`, so Cloud Code Assist users no longer need manual `--model` fallback selection to use it ([#3545](https://github.com/badlogic/pi-mono/issues/3545)) +- Fixed extension session-replacement flows so `ctx.newSession()`, `ctx.fork()`, `ctx.switchSession()`, and imported-session replacements fully rebind before post-switch work runs, added `withSession` replacement callbacks with fresh `ReplacedSessionContext` helpers, and make stale pre-replacement `pi` / `ctx` session-bound accesses throw instead of silently targeting the wrong session ([#2860](https://github.com/badlogic/pi-mono/issues/2860)) +- Fixed `models.json` built-in provider overrides to accept `headers` without requiring `baseUrl`, so request-header-only overrides now load and apply correctly ([#3538](https://github.com/badlogic/pi-mono/issues/3538)) + +## [0.68.1] - 2026-04-22 + +### New Features + +- Fireworks provider support with built-in models and `FIREWORKS_API_KEY` auth. See [README.md#providers--models](README.md#providers--models) and [docs/providers.md](docs/providers.md). +- Configurable inline tool image width via `terminal.imageWidthCells` in `/settings`. See [docs/settings.md#terminal--images](docs/settings.md#terminal--images). + +### Added + +- Added built-in Fireworks provider support, including `FIREWORKS_API_KEY` setup/docs and the default Fireworks model `accounts/fireworks/models/kimi-k2p6` ([#3519](https://github.com/badlogic/pi-mono/issues/3519)) + +### Fixed + +- Fixed interactive inline tool images to honor configurable `terminal.imageWidthCells` via `/settings`, so tool-output images are no longer hard-capped to 60 terminal cells ([#3508](https://github.com/badlogic/pi-mono/issues/3508)) +- Fixed `sessionDir` in `settings.json` to expand `~`, so portable session-directory settings no longer require a shell wrapper ([#3514](https://github.com/badlogic/pi-mono/issues/3514)) +- Fixed parallel tool-call rows to leave the pending state as soon as each tool is finalized, while still appending persisted tool results in assistant source order ([#3503](https://github.com/badlogic/pi-mono/issues/3503)) +- Fixed exported session markdown to render Markdown while showing HTML-like message content such as `...` verbatim, so shared sessions match the TUI instead of letting the browser interpret message text ([#3484](https://github.com/badlogic/pi-mono/issues/3484)) +- Fixed exported session HTML to render `grep` and `find` output through their existing TUI renderers and `ls` output through a native template renderer, avoiding missing formatting and spacing artifacts in shared sessions ([#3491](https://github.com/badlogic/pi-mono/pull/3491) by [@aliou](https://github.com/aliou)) +- Fixed `@` autocomplete fuzzy search to follow symlinked directories and include symlinked paths in results ([#3507](https://github.com/badlogic/pi-mono/issues/3507)) +- Fixed proxied agent streams to preserve the proxy-safe serializable subset of stream options, including session, transport, retry-delay, metadata, header, cache-retention, and thinking-budget settings ([#3512](https://github.com/badlogic/pi-mono/issues/3512)) +- Hardened Anthropic streaming against malformed tool-call JSON by owning SSE parsing with defensive JSON repair, replacing the deprecated `fine-grained-tool-streaming` beta header with per-tool `eager_input_streaming`, and updating stale test model references ([#3175](https://github.com/badlogic/pi-mono/issues/3175)) +- Fixed Bedrock runtime endpoint resolution to stop pinning built-in regional endpoints over `AWS_REGION` / `AWS_PROFILE`, restoring `us.*` and `eu.*` inference profile support after v0.68.0 while preserving custom VPC/proxy endpoint overrides ([#3481](https://github.com/badlogic/pi-mono/issues/3481), [#3485](https://github.com/badlogic/pi-mono/issues/3485), [#3486](https://github.com/badlogic/pi-mono/issues/3486), [#3487](https://github.com/badlogic/pi-mono/issues/3487), [#3488](https://github.com/badlogic/pi-mono/issues/3488)) + +## [0.68.0] - 2026-04-20 + +### New Features + +- Configurable streaming working indicator for extensions via `ctx.ui.setWorkingIndicator()`, including animated, static, and hidden indicators. See [docs/tui.md#working-indicator](docs/tui.md#working-indicator), [docs/extensions.md](docs/extensions.md), and [examples/extensions/working-indicator.ts](examples/extensions/working-indicator.ts). +- `before_agent_start` now exposes `systemPromptOptions` (`BuildSystemPromptOptions`) so extensions can inspect the structured system-prompt inputs without re-discovering resources. See [docs/extensions.md#before_agent_start](docs/extensions.md#before_agent_start) and [examples/extensions/prompt-customizer.ts](examples/extensions/prompt-customizer.ts). +- Configurable keybindings for scoped model selector actions and session-tree filter actions. See [docs/keybindings.md](docs/keybindings.md). +- `/clone` duplicates the current active branch into a new session, while extensions can choose whether to fork `before` or `at` an entry via `ctx.fork(..., { position })`. See [README.md](README.md), [docs/extensions.md](docs/extensions.md), and [docs/session.md](docs/session.md). + +### Breaking Changes + +- Changed SDK and CLI tool selection from cwd-bound built-in tool instances to tool-name allowlists. `createAgentSession({ tools })` now expects `string[]` names such as `"read"` and `"bash"` instead of `Tool[]`, `--tools` now allowlists built-in, extension, and custom tools by name, and `--no-tools` now disables all tools by default rather than only built-ins. Migrate SDK code from `tools: [readTool, bashTool]` to `tools: ["read", "bash"]` ([#2835](https://github.com/badlogic/pi-mono/issues/2835), [#3452](https://github.com/badlogic/pi-mono/issues/3452)) +- Removed prebuilt cwd-bound tool and tool-definition exports from `@mariozechner/pi-coding-agent`, including `readTool`, `bashTool`, `editTool`, `writeTool`, `grepTool`, `findTool`, `lsTool`, `readOnlyTools`, `codingTools`, and the corresponding `*ToolDefinition` values. Use the explicit factory exports instead, for example `createReadTool(cwd)`, `createBashTool(cwd)`, `createCodingTools(cwd)`, and `createReadToolDefinition(cwd)` ([#3452](https://github.com/badlogic/pi-mono/issues/3452)) +- Removed ambient `process.cwd()` / default agent-dir fallback behavior from public resource helpers. `DefaultResourceLoader`, `loadProjectContextFiles()`, and `loadSkills()` now require explicit cwd/agent-dir style inputs, and exported system-prompt option types now require an explicit `cwd`. Pass the session or project cwd explicitly instead of relying on process-global defaults ([#3452](https://github.com/badlogic/pi-mono/issues/3452)) + +### Added + +- Added extension support for customizing the interactive streaming working indicator via `ctx.ui.setWorkingIndicator()`, including custom animated frames, static indicators, hidden indicators, a new `working-indicator.ts` example extension, and updated extension/TUI/RPC docs ([#3413](https://github.com/badlogic/pi-mono/issues/3413)) +- Added `systemPromptOptions` (`BuildSystemPromptOptions`) to `before_agent_start` extension events, so extensions can inspect the structured inputs used to build the current system prompt ([#3473](https://github.com/badlogic/pi-mono/pull/3473) by [@dljsjr](https://github.com/dljsjr)) +- Added `/clone` to duplicate the current active branch into a new session, while keeping `/fork` focused on forking from a previous user message ([#2962](https://github.com/badlogic/pi-mono/issues/2962)) +- Added `ctx.fork()` support for `position: "before" | "at"` so extensions and integrations can branch before a user message or duplicate the current point in the conversation; the interactive clone/fork UX builds on that runtime support ([#3431](https://github.com/badlogic/pi-mono/pull/3431) by [@mitsuhiko](https://github.com/mitsuhiko)) +- Added configurable keybinding ids for scoped model selector actions and tree filter actions, so those interactive shortcuts can be remapped in `keybindings.json` ([#3343](https://github.com/badlogic/pi-mono/pull/3343) by [@mpazik](https://github.com/mpazik)) +- Added `PI_OAUTH_CALLBACK_HOST` support for built-in OAuth login flows, allowing local callback servers used by `pi auth` to bind to a custom interface instead of hardcoded `127.0.0.1` ([#3409](https://github.com/badlogic/pi-mono/pull/3409) by [@Michaelliv](https://github.com/Michaelliv)) +- Added `reason` and `targetSessionFile` metadata to `session_shutdown` extension events, so extensions can distinguish quit, reload, new-session, resume, and fork teardown paths ([#2863](https://github.com/badlogic/pi-mono/issues/2863)) + +### Changed + +- Changed `pi update` to batch npm package updates per scope and run git package updates with bounded parallelism, reducing multi-package update time while preserving skip behavior for pinned and already-current packages ([#2980](https://github.com/badlogic/pi-mono/issues/2980)) +- Changed Bedrock session requests to omit `maxTokens` when model token limits are unknown and to omit `temperature` when unset, letting Bedrock use provider defaults and avoid unnecessary TPM quota reservation ([#3400](https://github.com/badlogic/pi-mono/pull/3400) by [@wirjo](https://github.com/wirjo)) + +### Fixed + +- Fixed `AgentSession` system-prompt option initialization to avoid constructing an invalid empty `BuildSystemPromptOptions`, so `npm run check` passes after `cwd` became mandatory. +- Fixed shell-path resolution to stop consulting ambient `process.cwd()` state during bash execution, so session/project-specific `shellPath` settings now follow the active coding-agent session cwd instead of the launcher cwd ([#3452](https://github.com/badlogic/pi-mono/issues/3452)) +- Fixed `ctx.ui.setWorkingIndicator()` custom frames to render verbatim instead of forcing the theme accent color, so extensions now own working-indicator coloring when they customize it ([#3467](https://github.com/badlogic/pi-mono/issues/3467)) +- Fixed `pi update` reinstalling npm packages that are already at the latest published version by checking the installed package version before running `npm install @latest` ([#3000](https://github.com/badlogic/pi-mono/issues/3000)) +- Fixed `@` autocomplete plain queries to stop matching against the full cwd/base path, so path fragments in worktree names no longer crowd out intended results such as `@plan` ([#2778](https://github.com/badlogic/pi-mono/issues/2778)) +- Fixed built-in tool wrapping to use the same extension-runner context path as extension tools, so built-in tools receive execution context and `read` can warn when the current model does not support images ([#3429](https://github.com/badlogic/pi-mono/issues/3429)) +- Fixed `openai-completions` assistant replay to preserve `compat.requiresThinkingAsText` text-part serialization, avoiding same-model follow-up crashes when previous assistant messages mix thinking and text ([#3387](https://github.com/badlogic/pi-mono/issues/3387)) +- Fixed direct OpenAI Chat Completions sessions to map `sessionId` and `cacheRetention` to prompt caching fields, sending `prompt_cache_key` when caching is enabled and `prompt_cache_retention: "24h"` for direct `api.openai.com` requests with long retention ([#3426](https://github.com/badlogic/pi-mono/issues/3426)) +- Fixed OpenAI-compatible Chat Completions sessions to optionally send aligned `session_id`, `x-client-request-id`, and `x-session-affinity` headers from `sessionId` via `compat.sendSessionAffinityHeaders`, improving cache-affinity routing for backends such as Fireworks ([#3430](https://github.com/badlogic/pi-mono/issues/3430)) +- Fixed threaded `/resume` session relationships and current-session detection to canonicalize symlinked session paths during selector comparisons, so shared session directories no longer break parent-child matching or active-session delete protection ([#3364](https://github.com/badlogic/pi-mono/issues/3364)) +- Fixed `/session`, Sessions docs, and CLI help to consistently document that session reuse supports both file paths and session IDs, and that `/session` shows the current session ID ([#3390](https://github.com/badlogic/pi-mono/issues/3390)) +- Fixed Windows pnpm global install detection to recognize `\\.pnpm\\` store paths, so update notices now suggest `pnpm install -g @mariozechner/pi-coding-agent` instead of falling back to npm ([#3378](https://github.com/badlogic/pi-mono/issues/3378)) +- Fixed missing `@sinclair/typebox` runtime dependency in `@mariozechner/pi-coding-agent`, so strict pnpm installs no longer fail with `ERR_MODULE_NOT_FOUND` when starting `pi` ([#3434](https://github.com/badlogic/pi-mono/issues/3434)) +- Fixed xterm uppercase typing in the interactive editor by decoding printable `modifyOtherKeys` input and normalizing shifted letter matching, so `Shift+letter` no longer disappears in `pi` ([#3436](https://github.com/badlogic/pi-mono/issues/3436)) +- Fixed `/compact` to reuse the session thinking level for compaction summaries instead of forcing `high`, avoiding invalid reasoning-effort errors on `github-copilot/claude-opus-4.7` sessions configured for `medium` thinking ([#3438](https://github.com/badlogic/pi-mono/issues/3438)) +- Fixed shared/exported plain-text tool output to preserve indentation instead of collapsing leading whitespace in the web share page ([#3440](https://github.com/badlogic/pi-mono/issues/3440)) +- Fixed exported share pages to use browser-safe `T` and `O` shortcuts with clickable header toggles for thinking and tool visibility instead of browser-reserved `Ctrl+T` / `Ctrl+O` bindings ([#3374](https://github.com/badlogic/pi-mono/pull/3374) by [@vekexasia](https://github.com/vekexasia)) +- Fixed skill resolution to dedupe symlinked aliases by canonical path, so `pi config` no longer shows duplicate skill entries when `~/.pi/agent/skills` points to `~/.agents/skills` ([#3417](https://github.com/badlogic/pi-mono/pull/3417) by [@rwachtler](https://github.com/rwachtler)) +- Fixed OpenRouter request attribution to include Pi app headers (`HTTP-Referer: https://pi.dev`, `X-OpenRouter-Title: pi`, `X-OpenRouter-Categories: cli-agent`) when sessions are created through the coding-agent SDK and install telemetry is enabled ([#3414](https://github.com/badlogic/pi-mono/issues/3414)) +- Fixed custom-model `compat` schema/docs to support `cacheControlFormat: "anthropic"` for OpenAI-compatible providers that expose Anthropic-style prompt caching via `cache_control` markers ([#3392](https://github.com/badlogic/pi-mono/issues/3392)) +- Fixed Cloud Code Assist tool schemas to strip JSON Schema meta-declaration keys before provider translation, avoiding validation failures for tool-enabled sessions that use `$schema`, `$defs`, and related metadata ([#3412](https://github.com/badlogic/pi-mono/pull/3412) by [@vladlearns](https://github.com/vladlearns)) +- Fixed direct Bedrock sessions to honor `model.baseUrl` as the runtime client endpoint, restoring support for custom Bedrock VPC or proxy routes ([#3402](https://github.com/badlogic/pi-mono/pull/3402) by [@wirjo](https://github.com/wirjo)) +- Fixed the `edit` tool to coerce stringified `edits` JSON before validation, so models that send the array payload as a JSON string no longer fall back to ad-hoc shell edits ([#3370](https://github.com/badlogic/pi-mono/pull/3370) by [@dannote](https://github.com/dannote)) +- Fixed package manifest positive glob entries to expand before loading packaged resources, restoring manifest patterns such as `skills/**/*.md` ([#3350](https://github.com/badlogic/pi-mono/pull/3350) by [@neonspectra](https://github.com/neonspectra)) + +## [0.67.68] - 2026-04-17 + +## [0.67.67] - 2026-04-17 + +### New Features + +- Bedrock sessions can now authenticate with `AWS_BEARER_TOKEN_BEDROCK`, enabling Converse API access without local SigV4 credentials. See [docs/providers.md#amazon-bedrock](docs/providers.md#amazon-bedrock). + +### Added + +- Added Bedrock bearer-token authentication support via `AWS_BEARER_TOKEN_BEDROCK`, enabling coding-agent sessions to use Bedrock Converse without local SigV4 credentials ([#3125](https://github.com/badlogic/pi-mono/pull/3125) by [@wirjo](https://github.com/wirjo)) + +### Fixed + +- Fixed `/scoped-models` Alt+Up/Down to stay a no-op in the implicit `all enabled` state instead of materializing a full explicit enabled-model list and marking the selector dirty ([#3331](https://github.com/badlogic/pi-mono/issues/3331)) +- Fixed Mistral Small 4 default thinking requests to use the model's supported reasoning control, avoiding `400` errors when starting sessions on `mistral-small-2603` and `mistral-small-latest` ([#3338](https://github.com/badlogic/pi-mono/issues/3338)) +- Fixed Qwen chat-template thinking replay to preserve prior thinking across turns, so affected OpenAI-compatible models keep multi-turn tool-call arguments instead of degrading to empty `{}` payloads ([#3325](https://github.com/badlogic/pi-mono/issues/3325)) +- Fixed exported HTML transcripts so text selection no longer triggers click-based expand/collapse toggles ([#3332](https://github.com/badlogic/pi-mono/pull/3332) by [@xu0o0](https://github.com/xu0o0)) +- Fixed flaky git package update notifications by waiting for captured git command stdio to fully drain before comparing local and remote commit SHAs ([#3027](https://github.com/badlogic/pi-mono/issues/3027)) +- Fixed system prompt dates to use a stable `YYYY-MM-DD` format instead of locale-dependent output, keeping prompts deterministic across runtimes and locales ([#2814](https://github.com/badlogic/pi-mono/issues/2814)) +- Fixed auto-retry transient error detection to treat `Network connection lost.` as retryable, so dropped provider connections retry instead of terminating the agent ([#3317](https://github.com/badlogic/pi-mono/issues/3317)) +- Fixed compact interactive extension startup summaries to disambiguate package extensions and repeated local `index.ts` entries by using package-aware labels and the minimal parent path needed to make local entries unique ([#3308](https://github.com/badlogic/pi-mono/issues/3308)) +- Fixed git package dependency installation to use production installs (`npm install --omit=dev`) during both install and update flows, so extension runtime dependencies must come from `dependencies` and not `devDependencies` ([#3009](https://github.com/badlogic/pi-mono/issues/3009)) +- Fixed `tool_result` / `afterToolCall` extension handling for error results by forwarding `details` and `isError` overrides through `AgentSession` instead of dropping them when `isError` was already true ([#3051](https://github.com/badlogic/pi-mono/issues/3051)) +- Fixed missing root exports for `RpcClient` and RPC protocol types from `@mariozechner/pi-coding-agent`, so ESM consumers can import them from the main package entrypoint ([#3275](https://github.com/badlogic/pi-mono/issues/3275)) +- Fixed OpenAI Codex service-tier cost accounting to trust the explicitly requested tier when the API echoes the default tier in responses, keeping session cost displays aligned with the selected tier ([#3307](https://github.com/badlogic/pi-mono/pull/3307) by [@markusylisiurunen](https://github.com/markusylisiurunen)) +- Fixed parallel tool-call finalization to convert `afterToolCall` hook throws into error tool results instead of aborting the remaining tool batch ([#3084](https://github.com/badlogic/pi-mono/issues/3084)) +- Fixed Bun binary asset path resolution to honor `PI_PACKAGE_DIR` for built-in themes, HTML export templates, and interactive bundled assets ([#3074](https://github.com/badlogic/pi-mono/issues/3074)) +- Fixed user-message turn spacing in interactive mode by restoring an inter-message spacer before user turns (except the first user message), preventing assistant and user blocks from rendering flush together. +- Fixed interactive `/import` handling to support quoted JSONL paths with spaces, route missing JSONL files through the non-fatal `SessionImportFileNotFoundError` path, and document the `importFromJsonl()` exceptions (`SessionImportFileNotFoundError`, `MissingSessionCwdError`). + +## [0.67.6] - 2026-04-16 + +### New Features + +- Prompt templates support an `argument-hint` frontmatter field that renders before the description in the `/` autocomplete dropdown, using `` for required and `[square]` for optional arguments. See [docs/prompt-templates.md#argument-hints](docs/prompt-templates.md#argument-hints). +- New `after_provider_response` extension hook lets extensions inspect provider HTTP status codes and headers immediately after each response is received and before stream consumption begins. See [docs/extensions.md](docs/extensions.md). +- Compact interactive startup header with a comma-separated view of loaded AGENTS.md files, prompt templates, skills, and extensions. Press `Ctrl+O` to toggle the expanded listing. +- Markdown links in assistant output now render as OSC 8 hyperlinks on terminals that advertise support; unknown terminals and tmux/screen default to plain text so URLs are never silently dropped. + +### Added + +- Added `argument-hint` frontmatter field for prompt templates, displayed before the description in the autocomplete dropdown ([#2780](https://github.com/badlogic/pi-mono/pull/2780) by [@andresvi94](https://github.com/andresvi94)) +- Added `after_provider_response` extension hook so extensions can inspect provider HTTP status codes and headers after each provider response is received and before stream consumption begins ([#3128](https://github.com/badlogic/pi-mono/issues/3128)) +- Added OSC 8 hyperlink rendering for markdown links when the terminal advertises support ([#3248](https://github.com/badlogic/pi-mono/pull/3248) by [@ofa1](https://github.com/ofa1)) + +### Changed + +- Changed interactive startup header to a compact, comma-separated view of loaded AGENTS.md files, prompt templates, skills, and extensions, with `Ctrl+O` to toggle the expanded listing ([#3267](https://github.com/badlogic/pi-mono/pull/3267)) +- Tightened hyperlink capability detection to default `hyperlinks: false` for unknown terminals and force it off under tmux/screen (including nested sessions), preventing markdown link URLs from disappearing on terminals that silently swallow OSC 8 sequences ([#3248](https://github.com/badlogic/pi-mono/pull/3248)) + +### Fixed + +- Fixed interactive user message rendering to keep bottom padding visible in terminals affected by OSC 133 prompt markers without adding an extra blank line before the following assistant message ([#3090](https://github.com/badlogic/pi-mono/issues/3090)) +- Fixed `--verbose` startup output to begin with expanded startup help and loaded resource listings after the compact startup header change ([#3147](https://github.com/badlogic/pi-mono/issues/3147)) +- Fixed `find` tool returning no results for path-based glob patterns such as `src/**/*.spec.ts` or `some/parent/child/**` by switching fd into full-path mode and normalizing the pattern when it contains a `/` ([#3302](https://github.com/badlogic/pi-mono/issues/3302)) +- Fixed `find` tool applying nested `.gitignore` rules across sibling directories (e.g. rules from `a/.gitignore` hiding matching files under `b/`) by dropping the manual `--ignore-file` collection and delegating to fd's hierarchical `.gitignore` handling via `--no-require-git` ([#3303](https://github.com/badlogic/pi-mono/issues/3303)) +- Fixed OpenAI Responses prompt caching for non-`api.openai.com` base URLs (OpenAI-compatible proxies such as litellm, theclawbay) by sending the `session_id` and `x-client-request-id` cache-affinity headers unconditionally when a `sessionId` is provided, matching the official Codex CLI behavior ([#3264](https://github.com/badlogic/pi-mono/pull/3264) by [@vegarsti](https://github.com/vegarsti)) +- Fixed the `preset` example extension to snapshot the active model, thinking level, and tool set on the first preset application and restore that state when cycling back to `(none)`, instead of falling back to a hardcoded default tool list ([#3272](https://github.com/badlogic/pi-mono/pull/3272) by [@stembi](https://github.com/stembi)) + +## [0.67.5] - 2026-04-16 + +### Fixed + +- Fixed Opus 4.7 adaptive thinking configuration across Anthropic and Bedrock providers by recognizing Opus 4.7 adaptive-thinking support and mapping `xhigh` reasoning to provider-supported effort values ([#3286](https://github.com/badlogic/pi-mono/pull/3286) by [@markusylisiurunen](https://github.com/markusylisiurunen)) +- Fixed Zellij `Shift+Enter` regressions by reverting the Zellij-specific Kitty keyboard query bypass and restoring the previous keyboard negotiation behavior ([#3259](https://github.com/badlogic/pi-mono/issues/3259)) + +## [0.67.4] - 2026-04-16 + +### New Features + +- `--no-context-files` (`-nc`) disables automatic `AGENTS.md` / `CLAUDE.md` discovery when you need a clean run without project context injection. See [README.md#context-files](README.md#context-files). +- `loadProjectContextFiles()` is now exported as a standalone utility for extensions and SDK-style integrations that need to inspect the same context-file resolution order used by the CLI. See [README.md#context-files](README.md#context-files). +- New `after_provider_response` extension hook lets extensions inspect provider HTTP status codes and headers immediately after response creation and before stream consumption. See [docs/extensions.md](docs/extensions.md). + +### Added + +- Added `--no-context-files` (`-nc`) to disable `AGENTS.md` and `CLAUDE.md` context file discovery and loading ([#3253](https://github.com/badlogic/pi-mono/issues/3253)) +- Exported `loadProjectContextFiles()` as a standalone utility so extensions can discover project context files without instantiating a full `DefaultResourceLoader` ([#3142](https://github.com/badlogic/pi-mono/issues/3142)) +- Added `after_provider_response` extension hook so extensions can inspect provider HTTP status codes and headers after each provider response is received and before stream consumption begins ([#3128](https://github.com/badlogic/pi-mono/issues/3128)) + +### Changed + +- Added `claude-opus-4-7` model for Anthropic. +- Changed Anthropic prompt caching to add a `cache_control` breakpoint on the last tool definition, so tool schemas can be cached independently from transcript updates while preserving existing cache retention behavior ([#3260](https://github.com/badlogic/pi-mono/issues/3260)) + +### Fixed + +- Fixed markdown strikethrough parsing in interactive rendering and HTML export to require strict double-tilde delimiters (`~~text~~`) with non-whitespace boundaries. +- Fixed shutdown handling to kill tracked detached `bash` tool child processes on exit signals, preventing orphaned background processes. +- Fixed flaky `edit-tool-no-full-redraw` TUI tests by waiting for asynchronous preview and preflight error rendering instead of relying on fixed render ticks. +- Fixed `kimi-coding` default model selection to use `kimi-for-coding` instead of `kimi-k2-thinking` ([#3242](https://github.com/badlogic/pi-mono/issues/3242)) +- Fixed `ctrl+z` on native Windows to avoid crashing interactive mode, disable the default suspend binding there, and show a status message when suspend is invoked manually ([#3191](https://github.com/badlogic/pi-mono/issues/3191)) +- Fixed `find` tool cancellation and responsiveness on broad searches by making `.gitignore` discovery and `fd` execution fully abort-aware and non-blocking ([#3148](https://github.com/badlogic/pi-mono/issues/3148)) +- Fixed `grep` broad-search stalls when `context=0` by formatting match lines from ripgrep JSON output instead of doing synchronous per-match file reads ([#3205](https://github.com/badlogic/pi-mono/issues/3205)) + +## [0.67.3] - 2026-04-15 + +### New Features + +- `renderShell: "self"` for custom and built-in tool renderers so tools can own their outer shell instead of the default boxed shell. Useful for stable large previews such as edit diffs. See [docs/extensions.md#custom-rendering](docs/extensions.md#custom-rendering). +- Interactive auto-retry status now shows a live countdown during backoff instead of a static retry delay message. + +### Added + +- Added `renderShell: "self"` for custom and built-in tool renderers so tools can own their outer shell instead of using the default boxed shell. This is useful for stable large previews such as edit diffs ([#3134](https://github.com/badlogic/pi-mono/issues/3134)) + +### Fixed + +- Fixed edit diff previews to stay visible during edit permission dialogs and session replay without reintroducing large-result redraw flicker ([#3134](https://github.com/badlogic/pi-mono/issues/3134)) +- Fixed `/reload` to render a static reload status box instead of an animated spinner, avoiding redraw instability during interactive reloads. +- Fixed the `plan-mode` example extension to allow `eza` in the read-only bash allowlist instead of the deprecated `exa` command ([#3240](https://github.com/badlogic/pi-mono/pull/3240) by [@rwachtler](https://github.com/rwachtler)) +- Fixed `google-vertex` API key resolution to treat `gcp-vertex-credentials` as an Application Default Credentials marker instead of a literal API key, so marker-based setups correctly fall back to ADC ([#3221](https://github.com/badlogic/pi-mono/pull/3221) by [@deepkilo](https://github.com/deepkilo)) +- Fixed RPC `prompt` to wait for prompt preflight success before emitting its single authoritative response, while still treating handled and queued prompts as success ([#3049](https://github.com/badlogic/pi-mono/issues/3049)) +- Fixed `/scoped-models` reordering to propagate into the `/model` scoped tab, preserving the user-defined scoped model order instead of re-sorting it ([#3217](https://github.com/badlogic/pi-mono/issues/3217)) +- Fixed `session_shutdown` to fire on `SIGHUP` and `SIGTERM` in interactive, print, and RPC modes so extensions can run shutdown cleanup on those signal-driven exits ([#3212](https://github.com/badlogic/pi-mono/issues/3212)) +- Fixed screenshot path parsing to handle lower case am/pm in macOS screenshot filenames ([#3194](https://github.com/badlogic/pi-mono/pull/3194) by [@jay-aye-see-kay](https://github.com/jay-aye-see-kay)) +- Fixed interactive auto-retry status updates to show a live countdown during backoff instead of a static retry delay message ([#3187](https://github.com/badlogic/pi-mono/issues/3187)) + +## [0.67.2] - 2026-04-14 + +### New Features + +- Support for multiple `--append-system-prompt` flags, each value is appended to the system prompt separated by double newlines. See [README.md#other-options](README.md#other-options). +- Support for passing inline extension factories to `main()` for embedded integrations and custom entrypoints. +- Interactive keybinding support for Kitty `super`-modified shortcuts such as `super+k`, `super+enter`, and `ctrl+super+k`. See [docs/keybindings.md](docs/keybindings.md). + +### Added + +- Added support for multiple `--append-system-prompt` flags, each value is appended to the system prompt separated by double newlines ([#3171](https://github.com/badlogic/pi-mono/pull/3171) by [@aliou](https://github.com/aliou)) +- Added interactive keybinding support for Kitty `super`-modified shortcuts such as `super+k`, `super+enter`, and `ctrl+super+k` ([#3111](https://github.com/badlogic/pi-mono/pull/3111) by [@sudosubin](https://github.com/sudosubin)) +- Added support for passing inline extension factories to `main()` for embedded integrations and custom entrypoints ([#3099](https://github.com/badlogic/pi-mono/pull/3099) by [@pmateusz](https://github.com/pmateusz)) + +### Fixed + +- Fixed direct OpenAI Responses and Codex SSE requests to align `prompt_cache_key`, `session_id`, and `x-client-request-id` values with the same session-derived identifier, improving prompt cache affinity for append-only sessions ([#3018](https://github.com/badlogic/pi-mono/pull/3018) by [@steipete](https://github.com/steipete)) +- Fixed streaming-only `partialJson` scratch buffers leaking into persisted OpenAI Responses tool calls, which could corrupt follow-up payloads on resumed conversations. +- Fixed Ctrl+Alt letter key matching in tmux by falling through from legacy ESC-prefixed handling to CSI-u and xterm `modifyOtherKeys` parsing when the legacy form does not match ([#2989](https://github.com/badlogic/pi-mono/pull/2989) by [@kaofelix](https://github.com/kaofelix)) +- Fixed the shipped `subagent` example to avoid leaking Bun virtual filesystem script paths into subagent prompts ([#3002](https://github.com/badlogic/pi-mono/pull/3002) by [@nathyong](https://github.com/nathyong)) +- Fixed bordered loaders to stop their animation timer when disposed, preventing stale loader updates after teardown. + +## [0.67.1] - 2026-04-13 + +### Telemetry + +Interactive mode now sends a lightweight anonymous install/update telemetry ping to `https://pi.dev/install?version=x.y.z` after it writes `lastChangelogVersion` in `settings.json`. + +Why this exists: +- Pi needs a reliable per-version usage signal to understand whether releases are being adopted and to help justify funding continued development. +- npm download counts are not a reliable proxy for actual Pi usage. + +How it works: +- It only runs in interactive mode. +- It does not run in RPC mode, print mode, JSON mode, or SDK mode. +- On a fresh interactive install, Pi writes `lastChangelogVersion`, then sends the ping. +- On later interactive startups, if the local changelog contains entries newer than the previously stored `lastChangelogVersion`, Pi writes the new `lastChangelogVersion`, then sends the ping. +- The request is fire-and-forget. Startup does not wait for it, and any errors are ignored. + +What data is collected: +- Only the Pi version in the request path, for example `https://pi.dev/install?version=0.67.1`. +- The server stores only aggregate per-version counters such as `{ "0.67.1": 3 }`. +- It does not store IP addresses, client identifiers, prompts, paths, models, auth state, or any other per-user data. It literally only increments a counter for that version. + +How to disable it: +- `/settings` → disable `Install telemetry` +- `settings.json` → set `enableInstallTelemetry` to `false` +- `PI_OFFLINE=1` +- `PI_TELEMETRY=0` + +### New Features + +- Full `openRouterRouting` support in `models.json`, including fallbacks, parameter requirements, data collection, ZDR, ignore lists, quantizations, provider sorting, max price, and preferred throughput and latency constraints. See [docs/models.md](docs/models.md). +- `PI_CODING_AGENT=true` environment variable set at startup so subprocesses can detect they are running inside the coding agent. +- Updated `antigravity-image-gen.ts` example extension to use User-Agent version `1.21.9` ([#2901](https://github.com/badlogic/pi-mono/pull/2901) by [@aadishv](https://github.com/aadishv)) +- Fixed `--list-models` silently swallowing `models.json` load errors; errors are now printed to stderr ([#3072](https://github.com/badlogic/pi-mono/issues/3072)) +- Fixed custom models for built-in providers (e.g. `openrouter`) being silently dropped from `--list-models` by inheriting `api`/`baseUrl` from built-in model definitions and no longer requiring `apiKey` for providers with existing auth ([#2921](https://github.com/badlogic/pi-mono/issues/2921) and [#3072](https://github.com/badlogic/pi-mono/issues/3072)) +### Added + +- Added full `openRouterRouting` field support in `models.json`, including fallbacks, parameter requirements, data collection, ZDR, ignore lists, quantizations, provider sorting, max price, and preferred throughput and latency constraints ([#2904](https://github.com/badlogic/pi-mono/pull/2904) by [@zmberber](https://github.com/zmberber)) +- Set `PI_CODING_AGENT=true` environment variable at startup so sub-processes can detect they are running inside the coding agent ([#2868](https://github.com/badlogic/pi-mono/issues/2868)) + +### Fixed + +- Fixed interactive changelog rendering for the telemetry notes by moving the section under a `### Telemetry` heading, so startup shows the full release notes instead of only the version header. +- Updated `antigravity-image-gen.ts` example extension to use User-Agent version `1.21.9` ([#2901](https://github.com/badlogic/pi-mono/pull/2901) by [@aadishv](https://github.com/aadishv)) +- Bumped default Antigravity User-Agent version to `1.21.9` ([#2901](https://github.com/badlogic/pi-mono/pull/2901) by [@aadishv](https://github.com/aadishv)) +- Fixed Gemma 4 thinking level mapping to route between `MINIMAL` and `HIGH`, and map Pi reasoning levels to the model's supported thinking levels ([#2903](https://github.com/badlogic/pi-mono/pull/2903) by [@aadishv](https://github.com/aadishv)) +- Fixed Gemini 2.5 Flash Lite minimal thinking budget to use the model's supported 512-token minimum instead of the regular Flash 128-token minimum, avoiding invalid thinking budget errors ([#2861](https://github.com/badlogic/pi-mono/pull/2861) by [@JasonOA888](https://github.com/JasonOA888)) +- Fixed OpenAI Codex Responses requests to forward configured `serviceTier` values, restoring service-tier selection for Codex sessions ([#2996](https://github.com/badlogic/pi-mono/pull/2996) by [@markusylisiurunen](https://github.com/markusylisiurunen)) +- Fixed newly generated session IDs to use UUIDv7, improving time locality for session-based request routing ([#3018](https://github.com/badlogic/pi-mono/pull/3018) by [@steipete](https://github.com/steipete)) +- Fixed `Container.render()` stack overflow on long sessions by replacing `Array.push(...spread)` with a loop-based push, preventing `RangeError: Maximum call stack size exceeded` when child output exceeds the V8 call stack argument limit ([#2651](https://github.com/badlogic/pi-mono/issues/2651)) +- Fixed editor sticky-column tracking around paste markers so vertical cursor navigation restores the column from before the cursor entered a paste marker instead of jumping inside or past pasted content ([#3092](https://github.com/badlogic/pi-mono/pull/3092) by [@Perlence](https://github.com/Perlence)) +- Fixed queued messages typed during `/tree` branch summarization to flush automatically after navigation completes, so they no longer remain stuck in the steering queue ([#3091](https://github.com/badlogic/pi-mono/pull/3091) by [@Perlence](https://github.com/Perlence)) +- Fixed npm package update check to work with packages on non-default registries by using `npm view` instead of hardcoded `registry.npmjs.org` fetch ([#3164](https://github.com/badlogic/pi-mono/pull/3164) by [@aliou](https://github.com/aliou)) + +## [0.67.0] - 2026-04-13 + +See [0.67.1]. Version 0.67.0 shipped with a changelog formatting error that caused interactive startup to show only the version header instead of the full release notes. + +## [0.66.1] - 2026-04-08 + +### Changed + +- Changed the Earendil announcement from an automatic startup notice to the hidden `/dementedelves` slash command. + +## [0.66.0] - 2026-04-08 + +### New Features + +- Earendil startup announcement with bundled inline image rendering and a linked blog post for April 8 and 9, 2026. +- Interactive Anthropic subscription auth warning when Anthropic subscription auth is active, clarifying that Anthropic third-party usage draws from extra usage and is billed per token. + +### Fixed + +- Fixed bare `readline` import to use `node:readline` prefix for Deno compatibility ([#2885](https://github.com/badlogic/pi-mono/issues/2885) by [@milosv-vtool](https://github.com/milosv-vtool)) +- Fixed auto-retry to treat stream failures like `request ended without sending any chunks` as transient errors ([#2892](https://github.com/badlogic/pi-mono/issues/2892)) +- Fixed interactive startup notices to render after the initial resource listing, and added a bundled Earendil startup announcement with inline image rendering for April 8 and 9, 2026. Moved the blog link above the image to avoid overlap with terminal image rendering. +- Fixed interactive mode to warn when Anthropic subscription auth is active, so users know Anthropic third-party usage draws from extra usage and is billed per token. + +## [0.65.2] - 2026-04-06 + +## [0.65.1] - 2026-04-05 + +### Fixed + +- Fixed bash output truncation by line count to always persist full output to a temp file, preventing data loss when output exceeds 2000 lines but stays under the byte threshold ([#2852](https://github.com/badlogic/pi-mono/issues/2852)) +- RpcClient now forwards subprocess stderr to parent process in real-time ([#2805](https://github.com/badlogic/pi-mono/issues/2805)) +- Theme file watcher now handles async `fs.watch` error events instead of crashing the process ([#2791](https://github.com/badlogic/pi-mono/issues/2791)) +- Fixed stored session cwd handling so resuming or importing a session whose original working directory no longer exists now prompts interactive users to continue in the current cwd, while non-interactive modes fail with a clear error. +- Fixed resource collision precedence so project and user skills, prompt templates, and themes override package resources consistently, and CLI-provided paths take precedence over discovered resources ([#2781](https://github.com/badlogic/pi-mono/issues/2781)) +- Fixed OpenAI-compatible completions streaming usage accounting to preserve `prompt_tokens_details.cache_write_tokens` and normalize OpenRouter `cached_tokens`, preventing incorrect cache read/write token and cost reporting in pi ([#2802](https://github.com/badlogic/pi-mono/issues/2802)) +- Fixed CLI extension paths like `git:gist.github.com/...` being incorrectly resolved against cwd instead of being passed through to the package manager ([#2845](https://github.com/badlogic/pi-mono/pull/2845) by [@aliou](https://github.com/aliou)) +- Fixed piped stdin runs with `--mode json` to preserve JSONL output instead of falling back to plain text ([#2848](https://github.com/badlogic/pi-mono/pull/2848) by [@aliou](https://github.com/aliou)) +- Fixed interactive command docs to stop listing removed `/exit` as a supported quit command ([#2850](https://github.com/badlogic/pi-mono/issues/2850)) + +## [0.65.0] - 2026-04-03 + +### New Features + +- **Session runtime API**: `createAgentSessionRuntime()` and `AgentSessionRuntime` provide a closure-based runtime that recreates cwd-bound services and session config on every session switch. Startup, `/new`, `/resume`, `/fork`, and import all use the same creation path. See [docs/sdk.md](docs/sdk.md) and [examples/sdk/13-session-runtime.ts](examples/sdk/13-session-runtime.ts). +- **Label timestamps in `/tree`**: Toggle timestamps on tree entries with `Shift+T`, with smart date formatting and timestamp preservation through branching ([#2691](https://github.com/badlogic/pi-mono/pull/2691) by [@w-winter](https://github.com/w-winter)) +- **`defineTool()` helper**: Create standalone custom tool definitions with full TypeScript parameter type inference, no manual casts needed ([#2746](https://github.com/badlogic/pi-mono/issues/2746)). See [docs/extensions.md](docs/extensions.md). +- **Unified diagnostics**: Arg parsing, service creation, session option resolution, and resource loading all return structured diagnostics (`info`/`warning`/`error`) instead of logging or exiting. The app layer decides presentation and exit behavior. + +### Breaking Changes + +- Removed extension post-transition events `session_switch` and `session_fork`. Use `session_start` with `event.reason` (`"startup" | "reload" | "new" | "resume" | "fork"`). For `"new"`, `"resume"`, and `"fork"`, `session_start` includes `previousSessionFile`. +- Removed session-replacement methods from `AgentSession`. Use `AgentSessionRuntime` for `newSession()`, `switchSession()`, `fork()`, and `importFromJsonl()`. Cross-cwd session replacement rebuilds all cwd-bound runtime state and replaces the live `AgentSession` instance. +- Removed `session_directory` from extension and settings APIs. +- Unknown single-dash CLI flags (e.g. `-s`) now produce an error instead of being silently ignored. + +#### Migration: Extensions + +Before: + +```ts +pi.on("session_switch", async (event, ctx) => { ... }); +pi.on("session_fork", async (_event, ctx) => { ... }); +``` + +After: + +```ts +pi.on("session_start", async (event, ctx) => { + // event.reason: "startup" | "reload" | "new" | "resume" | "fork" + // event.previousSessionFile: set for "new", "resume", "fork" +}); +``` + +#### Migration: SDK session replacement + +Before: + +```ts +await session.newSession(); +await session.switchSession("/path/to/session.jsonl"); +``` + +After: + +```ts +import { + type CreateAgentSessionRuntimeFactory, + createAgentSessionFromServices, + createAgentSessionRuntime, + createAgentSessionServices, + getAgentDir, + SessionManager, +} from "@mariozechner/pi-coding-agent"; + +const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => { + const services = await createAgentSessionServices({ cwd }); + return { + ...(await createAgentSessionFromServices({ services, sessionManager, sessionStartEvent })), + services, + diagnostics: services.diagnostics, + }; +}; + +const runtime = await createAgentSessionRuntime(createRuntime, { + cwd: process.cwd(), + agentDir: getAgentDir(), + sessionManager: SessionManager.create(process.cwd()), +}); + +await runtime.newSession(); +await runtime.switchSession("/path/to/session.jsonl"); +await runtime.fork("entry-id"); + +// After replacement, runtime.session is the new live session. +// Rebind any session-local subscriptions or extension bindings. +``` + +### Added + +- Added `createAgentSessionRuntime()` and `AgentSessionRuntime` for runtime-backed session replacement. The runtime takes a `CreateAgentSessionRuntimeFactory` closure that closes over process-global fixed inputs and recreates cwd-bound services and session config for each effective cwd. Startup and later `/new`, `/resume`, `/fork`, import all use the same factory. +- Added unified diagnostics model (`info`/`warning`/`error`) for arg parsing, service creation, session option resolution, and resource loading. Creation logic no longer logs or exits. The app layer decides presentation and exit behavior. +- Added error diagnostics for missing explicit CLI resource paths (`-e`, `--skill`, `--prompt-template`, `--theme`) + +- Added `defineTool()` so standalone and array-based custom tool definitions keep inferred parameter types without manual casts ([#2746](https://github.com/badlogic/pi-mono/issues/2746)) + +- Added label timestamps to the session tree with a `Shift+T` toggle in `/tree`, smart date formatting, and timestamp preservation through branching ([#2691](https://github.com/badlogic/pi-mono/pull/2691) by [@w-winter](https://github.com/w-winter)) + +### Fixed + +- Fixed startup resource loading to reuse the initial `ResourceLoader` for the first runtime, so extensions are not loaded twice before session startup and `session_start` handlers still fire for singleton-style extensions ([#2766](https://github.com/badlogic/pi-mono/issues/2766)) +- Fixed retry settlement so retried agent runs wait for the full retry cycle to complete before declaring idle, preventing stale state after transient errors +- Fixed theme `export` colors to resolve theme variables the same way as `colors`, so `/export` HTML backgrounds now honor entries like `pageBg: "base"` instead of requiring inline hex values ([#2707](https://github.com/badlogic/pi-mono/issues/2707)) +- Fixed Bedrock throttling errors being misidentified as context overflow, causing unnecessary compaction instead of retry ([#2699](https://github.com/badlogic/pi-mono/pull/2699) by [@xu0o0](https://github.com/xu0o0)) +- Added tool streaming support for newer Z.ai models ([#2732](https://github.com/badlogic/pi-mono/pull/2732) by [@kaofelix](https://github.com/kaofelix)) + +## [0.64.0] - 2026-03-29 + +### New Features + +- Extensions and SDK callers can attach a `prepareArguments` hook to any tool definition, letting them normalize or migrate raw model arguments before schema validation. The built-in `edit` tool uses this to transparently support sessions created with the old single-edit schema. See [docs/extensions.md](docs/extensions.md) +- Extensions can customize the collapsed thinking block label via `ctx.ui.setHiddenThinkingLabel()`. See [examples/extensions/hidden-thinking-label.ts](examples/extensions/hidden-thinking-label.ts) ([#2673](https://github.com/badlogic/pi-mono/issues/2673)) + +### Breaking Changes + +- `ModelRegistry` no longer has a public constructor. SDK callers and tests must use `ModelRegistry.create(authStorage, modelsJsonPath?)` for file-backed registries or `ModelRegistry.inMemory(authStorage)` for built-in-only registries. Direct `new ModelRegistry(...)` calls no longer compile. + +### Added + +- Added `ToolDefinition.prepareArguments` hook to prepare raw tool call arguments before schema validation, enabling compatibility shims for resumed sessions with outdated tool schemas +- Built-in `edit` tool now uses `prepareArguments` to silently fold legacy top-level `oldText`/`newText` into `edits[]` when resuming old sessions +- Added `ctx.ui.setHiddenThinkingLabel()` so extensions can customize the collapsed thinking label in interactive mode, with a no-op in RPC mode and a runnable example extension in `examples/extensions/hidden-thinking-label.ts` ([#2673](https://github.com/badlogic/pi-mono/issues/2673)) + +### Fixed + +- Fixed extension-queued user messages to refresh the interactive pending-message list so messages submitted while a turn is active are no longer silently dropped ([#2674](https://github.com/badlogic/pi-mono/pull/2674) by [@mrexodia](https://github.com/mrexodia)) +- Fixed monorepo `tsconfig.json` path mappings to resolve `@mariozechner/pi-ai` subpath exports to source files in development checkouts ([#2625](https://github.com/badlogic/pi-mono/pull/2625) by [@ferologics](https://github.com/ferologics)) +- Fixed TUI cell size response handling to consume only exact `CSI 6 ; height ; width t` replies, so bare `Escape` is no longer swallowed while waiting for terminal image metadata ([#2661](https://github.com/badlogic/pi-mono/issues/2661)) +- Fixed Kitty keyboard protocol keypad functional keys to normalize to logical digits, symbols, and navigation keys, so numpad input in terminals such as iTerm2 no longer inserts Private Use Area gibberish or gets ignored ([#2650](https://github.com/badlogic/pi-mono/issues/2650)) + +## [0.63.2] - 2026-03-29 + +### New Features + +- Extension handlers can now use `ctx.signal` to forward cancellation into nested model calls, `fetch()`, and other abort-aware work. See [docs/extensions.md#ctxsignal](docs/extensions.md#ctxsignal) ([#2660](https://github.com/badlogic/pi-mono/issues/2660)) +- Built-in `edit` tool input now uses `edits[]` as the only replacement shape, reducing invalid tool calls caused by mixed single-edit and multi-edit schemas ([#2639](https://github.com/badlogic/pi-mono/issues/2639)) +- Large multi-edit results no longer trigger full-screen redraws in the interactive TUI when the final diff is rendered ([#2664](https://github.com/badlogic/pi-mono/issues/2664)) + +### Added + +- Added `ctx.signal` to `ExtensionContext` and wired it to the active agent turn so extension handlers can forward cancellation into nested model calls, `fetch()`, and other abort-aware work ([#2660](https://github.com/badlogic/pi-mono/issues/2660)) + +### Fixed + +- Fixed built-in `edit` tool input to use `edits[]` as the only replacement shape, eliminating the mixed single-edit and multi-edit modes that caused repeated invalid tool calls and retries ([#2639](https://github.com/badlogic/pi-mono/issues/2639)) +- Fixed edit tool TUI rendering to defer large multi-edit diffs to the settled result, avoiding full-screen redraws when the tool completes ([#2664](https://github.com/badlogic/pi-mono/issues/2664)) + +## [0.63.1] - 2026-03-27 + +### Added + +- Added `gemini-3.1-pro-preview-customtools` model availability for the `google-vertex` provider ([#2610](https://github.com/badlogic/pi-mono/pull/2610) by [@gordonhwc](https://github.com/gordonhwc)) + +### Fixed + +- Documented `tool_call` input mutation as supported extension API behavior, clarified that post-mutation inputs are not re-validated, and added regression coverage for executing mutated tool arguments ([#2611](https://github.com/badlogic/pi-mono/issues/2611)) +- Fixed repeated compactions dropping messages that were kept by an earlier compaction by re-summarizing from the previous kept boundary and recalculating `tokensBefore` from the rebuilt session context ([#2608](https://github.com/badlogic/pi-mono/issues/2608)) +- Fixed interactive compaction UI updates so `ctx.compact()` rebuilds the chat through unified compaction events, manual compaction no longer duplicates the summary block, and the `trigger-compact` example only fires when context usage crosses its threshold ([#2617](https://github.com/badlogic/pi-mono/issues/2617)) +- Fixed interactive compaction completion to append a synthetic compaction summary after rebuilding the chat so the latest compaction remains visible at the bottom +- Fixed skill discovery to stop recursing once a directory contains `SKILL.md`, and to ignore root `*.md` files in `.agents/skills` while keeping root markdown skill files supported in `~/.pi/agent/skills`, `.pi/skills`, and package `skills/` directories ([#2603](https://github.com/badlogic/pi-mono/issues/2603)) +- Fixed edit tool diff rendering for multi-edit operations with large unchanged gaps so distant edits collapse intermediate context instead of dumping the full unchanged middle block +- Fixed edit tool error rendering to avoid repeating the same exact-match failure in both the preview and result blocks +- Fixed auto-compaction overflow recovery for Ollama models when the backend returns explicit `prompt too long; exceeded max context length ...` errors instead of silently truncating input ([#2626](https://github.com/badlogic/pi-mono/issues/2626)) +- Fixed built-in tool overrides that reuse built-in parameter schemas to still honor custom `renderCall` and `renderResult` renderers in the interactive TUI, restoring the `minimal-mode` example ([#2595](https://github.com/badlogic/pi-mono/issues/2595)) + +## [0.63.0] - 2026-03-27 + +### Breaking Changes + +- `ModelRegistry.getApiKey(model)` has been replaced by `getApiKeyAndHeaders(model)` because `models.json` auth and header values can now resolve dynamically on every request. Extensions and SDK integrations that previously fetched only an API key must now fetch request auth per call and forward both `apiKey` and `headers`. Use `getApiKeyForProvider(provider)` only when you explicitly want provider-level API key lookup without model headers or `authHeader` handling ([#1835](https://github.com/badlogic/pi-mono/issues/1835)) +- Removed deprecated direct `minimax` and `minimax-cn` model IDs, keeping only `MiniMax-M2.7` and `MiniMax-M2.7-highspeed`. Update pinned model IDs to one of those supported direct MiniMax models, or use another provider route that still exposes the older IDs ([#2596](https://github.com/badlogic/pi-mono/pull/2596) by [@liyuan97](https://github.com/liyuan97)) + +#### Migration Notes + +Before: + +```ts +const apiKey = await ctx.modelRegistry.getApiKey(model); +return streamSimple(model, messages, { apiKey }); +``` + +After: + +```ts +const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model); +if (!auth.ok) throw new Error(auth.error); +return streamSimple(model, messages, { + apiKey: auth.apiKey, + headers: auth.headers, +}); +``` + +### Added + +- Added `sessionDir` setting support in global and project `settings.json` so session storage can be configured without passing `--session-dir` on every invocation ([#2598](https://github.com/badlogic/pi-mono/pull/2598) by [@smcllns](https://github.com/smcllns)) +- Added a startup onboarding hint in the interactive header telling users pi can explain its own features and documentation ([#2620](https://github.com/badlogic/pi-mono/pull/2620) by [@ferologics](https://github.com/ferologics)) +- Added `edit` tool multi-edit support so one call can update multiple separate, disjoint regions in the same file while matching all replacements against the original file content +- Added support for `PI_TUI_WRITE_LOG` directory paths, creating a unique log file (`tui--.log`) per instance for easier debugging of multiple pi sessions ([#2508](https://github.com/badlogic/pi-mono/pull/2508) by [@mrexodia](https://github.com/mrexodia)) + +### Changed + +### Fixed + +- Fixed file mutation queue ordering so concurrent `edit` and `write` operations targeting the same file stay serialized in request order instead of being reordered during queue-key resolution +- Fixed `models.json` shell-command auth and headers to resolve at request time instead of being cached into long-lived model state. pi now leaves TTL, caching, and recovery policy to user-provided wrapper commands because arbitrary shell commands need provider-specific strategies ([#1835](https://github.com/badlogic/pi-mono/issues/1835)) +- Fixed Google and Vertex cost calculation to subtract cached prompt tokens from billable input tokens instead of double-counting them when providers report `cachedContentTokenCount` ([#2588](https://github.com/badlogic/pi-mono/pull/2588) by [@sparkleMing](https://github.com/sparkleMing)) +- Added missing `ajv` direct dependency; previously relied on transitive install via `@mariozechner/pi-ai` which broke standalone installs ([#2252](https://github.com/badlogic/pi-mono/issues/2252)) +- Fixed `/export` HTML backgrounds to honor `theme.export.pageBg`, `cardBg`, and `infoBg` instead of always deriving them from `userMessageBg` ([#2565](https://github.com/badlogic/pi-mono/issues/2565)) +- Fixed interactive bash execution collapsed previews to recompute visual line wrapping at render time, so previews respect the current terminal width after resizes and split-pane width changes ([#2569](https://github.com/badlogic/pi-mono/issues/2569)) +- Fixed RPC `get_session_stats` to expose `contextUsage`, so headless clients can read actual current context-window usage instead of deriving it from token totals ([#2550](https://github.com/badlogic/pi-mono/issues/2550)) +- Fixed `pi update` for git packages to fetch only the tracked target branch with `--no-tags`, reducing unrelated branch and tag noise while preserving force-push-safe updates ([#2548](https://github.com/badlogic/pi-mono/issues/2548)) +- Fixed print and JSON modes to emit `session_shutdown` before exit, so extensions can release long-lived resources and non-interactive runs terminate cleanly ([#2576](https://github.com/badlogic/pi-mono/issues/2576)) +- Fixed GitHub Copilot OpenAI Responses requests to omit the `reasoning` field entirely when no reasoning effort is requested, avoiding `400` errors from Copilot `gpt-5-mini` rejecting `reasoning: { effort: "none" }` during internal summary calls ([#2567](https://github.com/badlogic/pi-mono/issues/2567)) +- Fixed blockquote text color breaking after inline links (and other inline elements) due to missing style restoration prefix +- Fixed slash-command Tab completion from immediately chaining into argument autocomplete after completing the command name, restoring flows like `/model` that submit into a selector dialog ([#2577](https://github.com/badlogic/pi-mono/issues/2577)) +- Fixed stale content and incorrect viewport tracking after TUI content shrinks or transient components inflate the working area ([#2126](https://github.com/badlogic/pi-mono/pull/2126) by [@Perlence](https://github.com/Perlence)) +- Fixed `@` autocomplete to debounce editor-triggered searches, cancel in-flight `fd` lookups cleanly, and keep suggestions visible while results refresh ([#1278](https://github.com/badlogic/pi-mono/issues/1278)) + +## [0.62.0] - 2026-03-23 + +### New Features + +- Built-in tools as extensible ToolDefinitions. Extension authors can now override rendering of built-in read/write/edit/bash/grep/find/ls tools with custom `renderCall`/`renderResult` components. See [docs/extensions.md](docs/extensions.md). +- Unified source provenance via `sourceInfo`. All resources, commands, tools, skills, and prompt templates now carry structured `sourceInfo` with path, scope, and source metadata. Visible in autocomplete, RPC discovery, and SDK introspection. See [docs/extensions.md](docs/extensions.md). +- AWS Bedrock cost allocation tagging. New `requestMetadata` option on `BedrockOptions` forwards key-value pairs to the Bedrock Converse API for AWS Cost Explorer split cost allocation. + +### Breaking Changes + +- Changed `ToolDefinition.renderCall` and `renderResult` semantics. Fallback rendering now happens only when a renderer is not defined for that slot. If `renderCall` or `renderResult` is defined, it must return a `Component`. +- Changed slash command provenance to use `sourceInfo` consistently. RPC `get_commands`, `RpcSlashCommand`, and SDK `SlashCommandInfo` no longer expose `location` or `path`. Use `sourceInfo` instead ([#1734](https://github.com/badlogic/pi-mono/issues/1734)) +- Removed legacy `source` fields from `Skill` and `PromptTemplate`. Use `sourceInfo.source` for provenance instead ([#1734](https://github.com/badlogic/pi-mono/issues/1734)) +- Removed `ResourceLoader.getPathMetadata()`. Resource provenance is now attached directly to loaded resources via `sourceInfo` ([#1734](https://github.com/badlogic/pi-mono/issues/1734)) +- Removed `extensionPath` from `RegisteredCommand` and `RegisteredTool`. Use `sourceInfo.path` for provenance instead ([#1734](https://github.com/badlogic/pi-mono/issues/1734)) + +#### Migration Notes + +Resource, command, and tool provenance now use `sourceInfo` consistently. + +Common updates: +- RPC `get_commands`: replace `path` and `location` with `sourceInfo.path`, `sourceInfo.scope`, and `sourceInfo.source` +- `SlashCommandInfo`: replace `command.path` and `command.location` with `command.sourceInfo` +- `Skill` and `PromptTemplate`: replace `.source` with `.sourceInfo.source` +- `RegisteredCommand` and `RegisteredTool`: replace `.extensionPath` with `.sourceInfo.path` +- Custom `ResourceLoader` implementations: remove `getPathMetadata()` and read provenance from loaded resources directly + +Examples: +- `command.path` -> `command.sourceInfo.path` +- `command.location === "user"` -> `command.sourceInfo.scope === "user"` +- `skill.source` -> `skill.sourceInfo.source` +- `tool.extensionPath` -> `tool.sourceInfo.path` + +### Changed + +- Built-in tools now work like custom tools in extensions. To get built-in tool definitions, import `readToolDefinition` / `createReadToolDefinition()` and the equivalent `bash`, `edit`, `write`, `grep`, `find`, and `ls` exports from `@mariozechner/pi-coding-agent`. +- Cleaned up `buildSystemPrompt()` so built-in tool snippets and tool-local guidelines come from built-in `ToolDefinition` metadata, while cross-tool and global prompt rules stay in system prompt construction. +- Added structured `sourceInfo` to `pi.getAllTools()` results for built-in, SDK, and extension tools ([#1734](https://github.com/badlogic/pi-mono/issues/1734)) + +### Fixed + +- Fixed extension command name conflicts so extensions with duplicate command names can load together. Conflicting extension commands now get numeric invocation suffixes in load order, for example `/review:1` and `/review:2` ([#1061](https://github.com/badlogic/pi-mono/issues/1061)) +- Fixed slash command source attribution for extension commands, prompt templates, and skills in autocomplete and command discovery ([#1734](https://github.com/badlogic/pi-mono/issues/1734)) +- Fixed auto-resized image handling to enforce the inline image size limit on the final base64 payload, return text-only fallbacks when resizing cannot produce a safe image, and avoid falling back to the original image in `read` and `@file` auto-resize paths ([#2055](https://github.com/badlogic/pi-mono/issues/2055)) +- Fixed `pi update` for git packages to skip destructive reset, clean, and reinstall steps when the fetched target already matches the local checkout ([#2503](https://github.com/badlogic/pi-mono/issues/2503)) +- Fixed print and JSON mode to take over stdout during non-interactive startup, keeping package-manager and other incidental chatter off protocol/output stdout ([#2482](https://github.com/badlogic/pi-mono/issues/2482)) +- Fixed cli-highlight auto-detection for languageless code blocks that misidentified prose as programming languages and colored random English words as keywords +- Fixed Anthropic thinking disable handling to send `thinking: { type: "disabled" }` for reasoning-capable models when thinking is explicitly off ([#2022](https://github.com/badlogic/pi-mono/issues/2022)) +- Fixed explicit thinking disable handling across Google, Google Vertex, Gemini CLI, OpenAI Responses, Azure OpenAI Responses, and OpenRouter-backed OpenAI-compatible completions ([#2490](https://github.com/badlogic/pi-mono/issues/2490)) +- Fixed OpenAI Responses replay for foreign tool-call item IDs by hashing foreign IDs into bounded `fc_` IDs +- Fixed OpenAI-compatible completions streams to ignore null chunks instead of crashing ([#2466](https://github.com/badlogic/pi-mono/pull/2466) by [@Cheng-Zi-Qing](https://github.com/Cheng-Zi-Qing)) +- Fixed `truncateToWidth()` performance for very large strings by streaming truncation ([#2447](https://github.com/badlogic/pi-mono/issues/2447)) +- Fixed markdown heading styling being lost after inline code spans within headings + +## [0.61.1] - 2026-03-20 + +### New Features + +- Typed `tool_call` handler return values via `ToolCallEventResult` exports from the top-level package and core extension entry. See [docs/extensions.md](docs/extensions.md). +- Updated default models for `zai`, `cerebras`, `minimax`, and `minimax-cn`, and aligned MiniMax catalog coverage and limits with the current provider lineup. See [docs/models.md](docs/models.md) and [docs/providers.md](docs/providers.md). + +### Added + +- Added `ToolCallEventResult` to the `@mariozechner/pi-coding-agent` top-level and core extension exports so extension authors can type explicit `tool_call` handler return values ([#2458](https://github.com/badlogic/pi-mono/issues/2458)) + +### Changed + +- Changed the default models for `zai`, `cerebras`, `minimax`, and `minimax-cn` to match the current provider lineup, and added missing `MiniMax-M2.1-highspeed` model entries with normalized MiniMax context limits ([#2445](https://github.com/badlogic/pi-mono/pull/2445) by [@1500256797](https://github.com/1500256797)) + +### Fixed + +- Fixed `ctrl+z` suspend and `fg` resume reliability by keeping the process alive until the `SIGCONT` handler restores the TUI, avoiding immediate process exit in environments with no other live event-loop handles ([#2454](https://github.com/badlogic/pi-mono/issues/2454)) +- Fixed `createAgentSession({ agentDir })` to derive the default persisted session path from the provided `agentDir`, keeping session storage aligned with settings, auth, models, and resource loading ([#2457](https://github.com/badlogic/pi-mono/issues/2457)) +- Fixed shared keybinding resolution to stop user overrides from evicting unrelated default shortcuts such as selector confirm and editor cursor keys ([#2455](https://github.com/badlogic/pi-mono/issues/2455)) +- Fixed Termux software keyboard height changes from forcing full-screen redraws and replaying TUI history on every toggle ([#2467](https://github.com/badlogic/pi-mono/issues/2467)) +- Fixed project-local npm package updates to install npm `latest` instead of reusing stale saved dependency ranges, and added `Did you mean ...?` suggestions when `pi update ` omits the configured npm or git source prefix ([#2459](https://github.com/badlogic/pi-mono/issues/2459)) + +## [0.61.0] - 2026-03-20 + +### New Features + +- Namespaced keybinding ids and a unified keybinding manager across the app and TUI. See [docs/keybindings.md](docs/keybindings.md) and [docs/extensions.md](docs/extensions.md). +- JSONL session export and import via `/export ` and `/import `. See [README.md](README.md) and [docs/session.md](docs/session.md). +- Resizable sidebar in HTML share and export views. See [README.md](README.md). + +### Breaking Changes + +- Interactive keybinding ids are now namespaced, and `keybindings.json` now uses those same canonical namespaced ids. Older config files are migrated automatically on startup. Custom editors and extension UI components still receive an injected `keybindings: KeybindingsManager`. They do not call `getKeybindings()` or `setKeybindings()` themselves. Declaration merging applies to that injected type ([#2391](https://github.com/badlogic/pi-mono/issues/2391)) +- Extension author migration: update `keyHint()`, `keyText()`, and injected `keybindings.matches(...)` calls from old built-in names like `"expandTools"`, `"selectConfirm"`, and `"interrupt"` to namespaced ids like `"app.tools.expand"`, `"tui.select.confirm"`, and `"app.interrupt"`. See [docs/keybindings.md](docs/keybindings.md) for the full list. `pi.registerShortcut("ctrl+shift+p", ...)` is unchanged because extension shortcuts still use raw key combos, not keybinding ids. + +### Added + +- Added `gpt-5.4-mini` to the `openai-codex` model catalog ([#2334](https://github.com/badlogic/pi-mono/pull/2334) by [@justram](https://github.com/justram)) +- Added JSONL session export and import via `/export ` and `/import ` ([#2356](https://github.com/badlogic/pi-mono/pull/2356) by [@hjanuschka](https://github.com/hjanuschka)) +- Added a resizable sidebar to HTML share and export views ([#2435](https://github.com/badlogic/pi-mono/pull/2435) by [@dmmulroy](https://github.com/dmmulroy)) + +### Fixed + +- Tests for session-selector-rename and tree-selector are now keybinding-agnostic, resetting editor keybindings to defaults before each test so user `keybindings.json` cannot cause failures ([#2360](https://github.com/badlogic/pi-mono/issues/2360)) +- Fixed custom `keybindings.json` overrides to shadow conflicting default shortcuts globally, so bindings such as `cursorUp: ["up", "ctrl+p"]` no longer leave default actions like model cycling active ([#2391](https://github.com/badlogic/pi-mono/issues/2391)) +- Fixed concurrent `edit` and `write` mutations targeting the same file to run serially, preventing interleaved file writes from overwriting each other ([#2327](https://github.com/badlogic/pi-mono/issues/2327)) +- Fixed RPC mode to redirect unexpected stdout writes to stderr so JSONL responses remain parseable ([#2388](https://github.com/badlogic/pi-mono/issues/2388)) +- Fixed auto-retry with tool-using retry responses so `session.prompt()` waits for the full retry loop, including tool execution, before returning ([#2440](https://github.com/badlogic/pi-mono/pull/2440) by [@pasky](https://github.com/pasky)) +- Fixed `/model` to refresh scoped model lists after `models.json` changes, avoiding stale selector contents ([#2408](https://github.com/badlogic/pi-mono/pull/2408) by [@Perlence](https://github.com/Perlence)) +- Fixed `validateToolArguments()` to fall back gracefully when AJV schema compilation is blocked in restricted runtimes such as Cloudflare Workers, allowing tool execution to proceed without schema validation ([#2395](https://github.com/badlogic/pi-mono/issues/2395)) +- Fixed CLI startup to suppress process warnings from leaking into terminal, print, and RPC output ([#2404](https://github.com/badlogic/pi-mono/issues/2404)) +- Fixed bash tool rendering to show elapsed time at the bottom of the tool block ([#2406](https://github.com/badlogic/pi-mono/issues/2406)) +- Fixed custom theme file watching to reload updated theme contents from disk instead of keeping stale cached theme data ([#2417](https://github.com/badlogic/pi-mono/issues/2417), [#2003](https://github.com/badlogic/pi-mono/issues/2003)) +- Fixed footer Git branch refreshes to run asynchronously so branch watcher updates do not block the UI ([#2418](https://github.com/badlogic/pi-mono/issues/2418)) +- Fixed invalid extension provider registrations to surface an extension error without preventing other providers from loading ([#2431](https://github.com/badlogic/pi-mono/issues/2431)) +- Fixed Windows bash execution hanging for commands that spawn detached descendants inheriting stdout/stderr handles, which caused `agent-browser` and similar commands to spin forever ([#2389](https://github.com/badlogic/pi-mono/pull/2389) by [@mrexodia](https://github.com/mrexodia)) +- Fixed `google-vertex` API key resolution to ignore placeholder auth markers like `` and fall back to ADC instead of sending them as literal API keys ([#2335](https://github.com/badlogic/pi-mono/issues/2335)) +- Fixed desktop clipboard text copy to prefer native OS clipboard integration before shell fallbacks, improving reliability on macOS and Windows ([#2347](https://github.com/badlogic/pi-mono/issues/2347)) +- Fixed Bun Bedrock provider registration to survive provider resets and session reloads in compiled binaries ([#2350](https://github.com/badlogic/pi-mono/pull/2350) by [@unexge](https://github.com/unexge)) +- Fixed OpenRouter reasoning requests to use the provider's nested reasoning payload, restoring thinking level support for OpenRouter models and custom compat settings ([#2298](https://github.com/badlogic/pi-mono/pull/2298) by [@PriNova](https://github.com/PriNova)) +- Fixed Bedrock application inference profiles to support prompt caching when `AWS_BEDROCK_FORCE_CACHE=1` is set, covering profile ARNs that do not expose the underlying Claude model name ([#2346](https://github.com/badlogic/pi-mono/pull/2346) by [@haoqixu](https://github.com/haoqixu)) + +## [0.60.0] - 2026-03-18 + +### New Features + +- Fork existing sessions directly from the CLI with `--fork `, which copies a source session into a new session in the current project. See [README.md](README.md). +- Extensions and SDK callers can reuse pi's built-in local bash backend via `createLocalBashOperations()` for `user_bash` interception and custom bash integrations. See [docs/extensions.md#user_bash](docs/extensions.md#user_bash). +- Startup no longer updates unpinned npm and git packages automatically. Use `pi update` explicitly, while interactive mode checks for updates in the background and notifies you when newer packages are available. See [README.md](README.md). + +### Breaking Changes + +- Changed package startup behavior so installed unpinned packages are no longer checked or updated during startup. Use `pi update` to apply npm/git package updates, while interactive mode now checks for available package updates in the background and notifies you when updates are available ([#1963](https://github.com/badlogic/pi-mono/issues/1963)) + +### Added + +- Added `--fork ` CLI flag to fork an existing session file or partial session UUID directly into a new session ([#2290](https://github.com/badlogic/pi-mono/issues/2290)) +- Added `createLocalBashOperations()` export so extensions and SDK callers can wrap pi's built-in local bash backend for `user_bash` handling and other custom bash integrations ([#2299](https://github.com/badlogic/pi-mono/issues/2299)) + +### Fixed + +- Fixed active model selection to refresh immediately after dynamic provider registrations or updates change the available model set ([#2291](https://github.com/badlogic/pi-mono/issues/2291)) +- Fixed tmux xterm `modifyOtherKeys` matching for `Backspace`, `Escape`, and `Space`, and resolved raw `\x08` backspace ambiguity by treating Windows Terminal sessions differently from legacy terminals ([#2293](https://github.com/badlogic/pi-mono/issues/2293)) +- Fixed Gemini 3 and Antigravity image tool results to stay inline as multimodal tool responses instead of being rerouted through separate follow-up messages ([#2052](https://github.com/badlogic/pi-mono/issues/2052)) +- Fixed bundled Bedrock Claude 4.6 model metadata to use the correct 200K context window instead of 1M ([#2305](https://github.com/badlogic/pi-mono/issues/2305)) +- Fixed `/reload` to reload keybindings from disk so changes in `keybindings.json` apply immediately ([#2309](https://github.com/badlogic/pi-mono/issues/2309)) +- Fixed lazy built-in provider registration so compiled Bun binaries can still load providers on first use without eagerly bundling provider SDKs ([#2314](https://github.com/badlogic/pi-mono/issues/2314)) +- Fixed built-in OAuth login flows to use aligned callback handling across Anthropic, Gemini CLI, Antigravity, and OpenAI Codex, and fixed OpenAI Codex login to complete immediately once the browser callback succeeds ([#2316](https://github.com/badlogic/pi-mono/issues/2316)) +- Fixed OpenAI-compatible z.ai `network_error` responses to trigger error handling and retries instead of being treated as successful assistant output ([#2313](https://github.com/badlogic/pi-mono/issues/2313)) +- Fixed print mode to merge piped stdin into the initial prompt when both stdin and an explicit prompt are provided ([#2315](https://github.com/badlogic/pi-mono/issues/2315)) +- Fixed OpenAI Responses replay in coding-agent to normalize oversized resumed tool call IDs before sending them back to OpenAI Codex and other Responses-compatible targets ([#2328](https://github.com/badlogic/pi-mono/issues/2328)) +- Fixed tmux extended-keys warning to stay hidden when the tmux server is unreachable, avoiding false startup warnings in sandboxed environments ([#2311](https://github.com/badlogic/pi-mono/pull/2311) by [@kaffarell](https://github.com/kaffarell)) + +## [0.59.0] - 2026-03-17 + +### New Features + +- Faster startup by lazy-loading `@mariozechner/pi-ai` provider SDKs on first use instead of import time ([#2297](https://github.com/badlogic/pi-mono/issues/2297)) +- Better provider retry behavior when providers return error messages as responses ([#2264](https://github.com/badlogic/pi-mono/issues/2264)) +- Better terminal integration via OSC 133 command-executed markers ([#2242](https://github.com/badlogic/pi-mono/issues/2242)) +- Better Git footer branch detection for repositories using reftable storage ([#2300](https://github.com/badlogic/pi-mono/issues/2300)) + +### Breaking Changes + +- Changed custom tool system prompt behavior so extension and SDK tools are included in the default `Available tools` section only when they provide `promptSnippet`. Omitting `promptSnippet` now leaves the tool out of that section instead of falling back to `description` ([#2285](https://github.com/badlogic/pi-mono/issues/2285)) + +### Changed + +- Lazy-load built-in `@mariozechner/pi-ai` provider modules and root provider wrappers so coding-agent startup no longer eagerly loads provider SDKs before first use ([#2297](https://github.com/badlogic/pi-mono/issues/2297)) + +### Fixed + +- Fixed session title handling in `/tree`, compaction, and branch summarization so empty title clears render correctly and `session_info` entries stay out of summaries ([#2304](https://github.com/badlogic/pi-mono/pull/2304) by [@aliou](https://github.com/aliou)) +- Fixed footer branch detection for Git repositories using reftable storage so branch names still appear correctly in the footer ([#2300](https://github.com/badlogic/pi-mono/issues/2300)) +- Fixed rendered user messages to emit an OSC 133 command-executed marker after command output, improving terminal prompt integration ([#2242](https://github.com/badlogic/pi-mono/issues/2242)) +- Fixed provider retry handling to treat provider-returned error messages as retryable failures instead of successful responses ([#2264](https://github.com/badlogic/pi-mono/issues/2264)) +- Fixed Claude 4.6 context window overrides in bundled model metadata so coding-agent sees the intended model limits after generated catalogs are rebuilt ([#2286](https://github.com/badlogic/pi-mono/issues/2286)) + +## [0.58.4] - 2026-03-16 + +### Fixed + +- Fixed steering messages to wait until the current assistant message's tool-call batch fully finishes instead of skipping pending tool calls. + +## [0.58.3] - 2026-03-15 + +## [0.58.2] - 2026-03-15 + +### Added + +- Improved settings, theme, thinking, and show-images selector layouts by using configurable select-list primary column sizing ([#2154](https://github.com/badlogic/pi-mono/pull/2154) by [@markusylisiurunen](https://github.com/markusylisiurunen)) + +### Fixed + +- Fixed fuzzy `edit` matching to normalize Unicode compatibility variants before comparison, reducing false "oldText not found" failures for text such as CJK and full-width characters ([#2044](https://github.com/badlogic/pi-mono/issues/2044)) +- Fixed `/model ` exact matching and picker search to recognize canonical `provider/model` references when model IDs themselves contain `/`, such as LM Studio models like `unsloth/qwen3.5-35b-a3b` ([#2174](https://github.com/badlogic/pi-mono/issues/2174)) +- Fixed Anthropic OAuth manual login and token refresh by using the localhost callback URI for pasted redirect/code flows and omitting `scope` from refresh-token requests ([#2169](https://github.com/badlogic/pi-mono/issues/2169)) +- Fixed stale scrollback remaining after session switches by clearing the screen before wiping scrollback ([#2155](https://github.com/badlogic/pi-mono/pull/2155) by [@Perlence](https://github.com/Perlence)) +- Fixed extra blank lines after markdown block elements in rendered output ([#2152](https://github.com/badlogic/pi-mono/pull/2152) by [@markusylisiurunen](https://github.com/markusylisiurunen)) + +## [0.58.1] - 2026-03-14 + +### Added + +- Added `pi uninstall` alias for `pi install --uninstall` convenience + +### Fixed + +- Fixed OpenAI Codex websocket protocol to include required headers and properly terminate SSE streams on connection close ([#1961](https://github.com/badlogic/pi-mono/issues/1961)) +- Fixed WSL clipboard image fallback to properly handle missing clipboard utilities and permission errors ([#1722](https://github.com/badlogic/pi-mono/issues/1722)) +- Fixed extension `session_start` hook firing before TUI was ready, causing UI operations in `session_start` handlers to fail ([#2035](https://github.com/badlogic/pi-mono/issues/2035)) +- Fixed Windows shell and path handling for package manager operations and autocomplete to properly handle drive letters and mixed path separators +- Fixed Bedrock prompt caching being enabled for non-Claude models, causing API errors ([#2053](https://github.com/badlogic/pi-mono/issues/2053)) +- Fixed Qwen models via OpenAI-compatible providers by adding `qwen-chat-template` compat mode that uses Qwen's native chat template format ([#2020](https://github.com/badlogic/pi-mono/issues/2020)) +- Fixed Bedrock unsigned thinking replay to handle edge cases with empty or malformed thinking blocks ([#2063](https://github.com/badlogic/pi-mono/issues/2063)) +- Fixed headless clipboard fallback logging spurious errors in non-interactive environments ([#2056](https://github.com/badlogic/pi-mono/issues/2056)) +- Fixed `models.json` provider compat flags not being honored when loading custom model definitions ([#2062](https://github.com/badlogic/pi-mono/issues/2062)) +- Fixed xhigh reasoning effort detection for Claude Opus 4.6 to match by model ID instead of requiring explicit capability flag ([#2040](https://github.com/badlogic/pi-mono/issues/2040)) +- Fixed prompt cwd containing Windows backslashes breaking bash tool execution by normalizing to forward slashes ([#2080](https://github.com/badlogic/pi-mono/issues/2080)) +- Fixed editor paste to preserve literal content instead of normalizing newlines, preventing content corruption for text with embedded escape sequences ([#2064](https://github.com/badlogic/pi-mono/issues/2064)) +- Fixed skill discovery recursing past skill root directories when nested SKILL.md files exist ([#2075](https://github.com/badlogic/pi-mono/issues/2075)) +- Fixed tab completion to preserve `./` prefix when completing relative paths ([#2087](https://github.com/badlogic/pi-mono/issues/2087)) +- Fixed npm package installs and lookups being tied to the active repository Node version by adding `npmCommand` as an argv-style settings override for package manager operations ([#2072](https://github.com/badlogic/pi-mono/issues/2072)) +- Fixed `ctx.ui.getEditorText()` in the extension API returning paste markers (e.g., `[paste #1 +24 lines]`) instead of the actual pasted content ([#2084](https://github.com/badlogic/pi-mono/issues/2084)) +- Fixed startup crash when downloading `fd`/`ripgrep` on first run by using `pipeline()` instead of `finished(readable.pipe(writable))` so stream errors from timeouts are caught properly, and increased the download timeout from 10s to 120s ([#2066](https://github.com/badlogic/pi-mono/issues/2066)) + +## [0.58.0] - 2026-03-14 + +### New Features + +- Claude Opus 4.6, Sonnet 4.6, and related Bedrock models now use a 1M token context window (up from 200K) ([#2135](https://github.com/badlogic/pi-mono/pull/2135) by [@mitsuhiko](https://github.com/mitsuhiko)). +- Extension tool calls now execute in parallel by default, with sequential `tool_call` preflight preserved for extension interception. +- `GOOGLE_CLOUD_API_KEY` environment variable support for the `google-vertex` provider as an alternative to Application Default Credentials ([#1976](https://github.com/badlogic/pi-mono/pull/1976) by [@gordonhwc](https://github.com/gordonhwc)). +- Extensions can supply deterministic session IDs via `newSession()` ([#2130](https://github.com/badlogic/pi-mono/pull/2130) by [@zhahaoyu](https://github.com/zhahaoyu)). + +### Added + +- Added `GOOGLE_CLOUD_API_KEY` environment variable support for the `google-vertex` provider as an alternative to Application Default Credentials ([#1976](https://github.com/badlogic/pi-mono/pull/1976) by [@gordonhwc](https://github.com/gordonhwc)) +- Added custom session ID support in `newSession()` for extensions that need deterministic session paths ([#2130](https://github.com/badlogic/pi-mono/pull/2130) by [@zhahaoyu](https://github.com/zhahaoyu)) + +### Changed + +- Changed extension tool interception to use agent-core `beforeToolCall` and `afterToolCall` hooks instead of wrapper-based interception. Tool calls now execute in parallel by default, extension `tool_call` preflight still runs sequentially, and final tool results are emitted in assistant source order. +- Raised Claude Opus 4.6, Sonnet 4.6, and related Bedrock model context windows from 200K to 1M tokens ([#2135](https://github.com/badlogic/pi-mono/pull/2135) by [@mitsuhiko](https://github.com/mitsuhiko)) + +### Fixed + +- Fixed `tool_call` extension handlers observing stale `sessionManager` state during multi-tool turns by draining queued agent events before each `tool_call` preflight. In parallel tool mode this guarantees state through the current assistant tool-calling message, but not sibling tool results from the same assistant message. +- Fixed interactive input fields backed by the TUI `Input` component to scroll by visual column width for wide Unicode text (CJK, fullwidth characters), preventing rendered line overflow and TUI crashes in places like search and filter inputs ([#1982](https://github.com/badlogic/pi-mono/issues/1982)) +- Fixed `shift+tab` and other modified Tab bindings in tmux when `extended-keys-format` is left at the default `xterm` +- Fixed EXIF orientation not being applied during image convert and resize, causing JPEG and WebP images from phone cameras to display rotated or mirrored ([#2105](https://github.com/badlogic/pi-mono/pull/2105) by [@melihmucuk](https://github.com/melihmucuk)) +- Fixed the default coding-agent system prompt to include only the current date in ISO format, not the current time, so prompt prefixes stay cacheable across reloads and resumed sessions ([#2131](https://github.com/badlogic/pi-mono/issues/2131)) +- Fixed retry regex to match `server_error` and `internal_error` error types from providers, improving automatic retry coverage ([#2117](https://github.com/badlogic/pi-mono/pull/2117) by [@MadKangYu](https://github.com/MadKangYu)) +- Fixed example extensions to support `PI_CODING_AGENT_DIR` environment variable for custom agent directory paths ([#2009](https://github.com/badlogic/pi-mono/pull/2009) by [@smithbm2316](https://github.com/smithbm2316)) +- Fixed tool result images not being sent in `function_call_output` items for OpenAI Responses API providers, causing image data to be silently dropped in tool results ([#2104](https://github.com/badlogic/pi-mono/issues/2104)) +- Fixed assistant content being sent as structured content blocks instead of plain strings in the `openai-completions` provider, causing errors with some OpenAI-compatible backends ([#2008](https://github.com/badlogic/pi-mono/pull/2008) by [@geraldoaax](https://github.com/geraldoaax)) +- Fixed error details in OpenAI Responses `response.failed` handler to include status code, error code, and message instead of a generic failure ([#1956](https://github.com/badlogic/pi-mono/pull/1956) by [@drewburr](https://github.com/drewburr)) +- Fixed GitHub Copilot device-code login polling to respect OAuth slow-down intervals, wait before the first token poll, and include a clearer clock-drift hint in WSL/VM environments when repeated slow-downs lead to timeout +- Fixed usage statistics not being captured for OpenAI-compatible providers that return usage in `choice.usage` instead of the standard `chunk.usage` (e.g., Moonshot/Kimi) ([#2017](https://github.com/badlogic/pi-mono/issues/2017)) +- Fixed editor scroll indicator rendering crash in narrow terminal widths ([#2103](https://github.com/badlogic/pi-mono/pull/2103) by [@haoqixu](https://github.com/haoqixu)) +- Fixed tab characters in editor and input paste not being normalized to spaces ([#2027](https://github.com/badlogic/pi-mono/pull/2027), [#1975](https://github.com/badlogic/pi-mono/pull/1975) by [@haoqixu](https://github.com/haoqixu)) +- Fixed `wordWrapLine` overflow when wide characters (CJK, fullwidth) fall exactly at the wrap boundary ([#2082](https://github.com/badlogic/pi-mono/pull/2082) by [@haoqixu](https://github.com/haoqixu)) +- Fixed paste markers not being treated as atomic segments in editor word wrapping and cursor navigation ([#2111](https://github.com/badlogic/pi-mono/pull/2111) by [@haoqixu](https://github.com/haoqixu)) + +## [0.57.1] - 2026-03-07 + +### New Features +- Tree branch folding and segment-jump navigation in `/tree`, with `Ctrl+←`/`Ctrl+→` and `Alt+←`/`Alt+→` shortcuts while `←`/`→` and `Page Up`/`Page Down` remain available for paging. See [docs/tree.md](docs/tree.md) and [docs/keybindings.md](docs/keybindings.md). +- `session_directory` extension event for customizing session directory paths before session manager creation. See [docs/extensions.md](docs/extensions.md). +- Digit keybindings (`0-9`) in the TUI keybinding system, including modified combos like `ctrl+1`. See [docs/keybindings.md](docs/keybindings.md). + +### Added +- Added `/tree` branch folding and segment-jump navigation with `Ctrl+←`/`Ctrl+→` and `Alt+←`/`Alt+→`, while keeping `←`/`→` and `Page Up`/`Page Down` for paging ([#1724](https://github.com/badlogic/pi-mono/pull/1724) by [@Perlence](https://github.com/Perlence)) +- Added `session_directory` extension event that fires before session manager creation, allowing extensions to customize the session directory path based on cwd and other factors. CLI `--session-dir` flag takes precedence over extension-provided paths ([#1730](https://github.com/badlogic/pi-mono/pull/1730) by [@hjanuschka](https://github.com/hjanuschka)). +- Added digit keys (`0-9`) to the keybinding system, including Kitty CSI-u and xterm `modifyOtherKeys` support for bindings like `ctrl+1` ([#1905](https://github.com/badlogic/pi-mono/issues/1905)) + +### Fixed +- Fixed custom tool collapsed/expanded rendering in HTML exports. Custom tools that define different collapsed vs expanded displays now render correctly in exported HTML, with expandable sections when both states differ and direct display when only expanded exists ([#1934](https://github.com/badlogic/pi-mono/pull/1934) by [@aliou](https://github.com/aliou)) +- Fixed tmux startup guidance and keyboard setup warnings for modified key handling, including Ghostty `shift+enter=text:\n` remap guidance and tmux `extended-keys-format` detection ([#1872](https://github.com/badlogic/pi-mono/issues/1872)) +- Fixed z.ai context overflow recovery so `model_context_window_exceeded` errors trigger auto-compaction instead of surfacing as unhandled stop reason failures ([#1937](https://github.com/badlogic/pi-mono/issues/1937)) +- Fixed autocomplete selection ignoring typed text: highlight now follows the first prefix match as the user types, and exact matches are always selected on Enter ([#1931](https://github.com/badlogic/pi-mono/pull/1931) by [@aliou](https://github.com/aliou)) +- Fixed slash-command Tab completion to immediately open argument completions when available ([#1481](https://github.com/badlogic/pi-mono/pull/1481) by [@barapa](https://github.com/barapa)) +- Fixed explicit `pi -e ` extensions losing command and tool conflicts to discovered extensions by giving CLI-loaded extensions higher precedence ([#1896](https://github.com/badlogic/pi-mono/issues/1896)) +- Fixed Windows external editor launch for `Ctrl+G` and `ctx.ui.editor()` so shell-based commands like `EDITOR="code --wait"` work correctly ([#1925](https://github.com/badlogic/pi-mono/issues/1925)) + +## [0.57.0] - 2026-03-07 + +### New Features + +- Extensions can intercept and modify provider request payloads via `before_provider_request`. See [docs/extensions.md#before_provider_request](docs/extensions.md#before_provider_request). +- Extension UIs can use non-capturing overlays with explicit focus control via `OverlayOptions.nonCapturing` and `OverlayHandle.focus()` / `unfocus()` / `isFocused()`. See [docs/extensions.md](docs/extensions.md) and [../tui/README.md](../tui/README.md). +- RPC mode now uses strict LF-only JSONL framing for robust payload handling. See [docs/rpc.md](docs/rpc.md). + +### Breaking Changes + +- RPC mode now uses strict LF-delimited JSONL framing. Clients must split records on `\n` only instead of using generic line readers such as Node `readline`, which also split on Unicode separators inside JSON payloads ([#1911](https://github.com/badlogic/pi-mono/issues/1911)) + +### Added + +- Added `before_provider_request` extension hook so extensions can inspect or replace provider payloads before requests are sent, with an example in `examples/extensions/provider-payload.ts` +- Added non-capturing overlay focus control for extension UIs via `OverlayOptions.nonCapturing` and `OverlayHandle.focus()` / `unfocus()` / `isFocused()` ([#1916](https://github.com/badlogic/pi-mono/pull/1916) by [@nicobailon](https://github.com/nicobailon)) + +### Changed + +- Overlay compositing in extension UIs now uses focus order so focused overlays render on top while preserving stack semantics for show/hide behavior ([#1916](https://github.com/badlogic/pi-mono/pull/1916) by [@nicobailon](https://github.com/nicobailon)) + +### Fixed + +- Fixed RPC mode stdin/stdout framing to use strict LF-delimited JSONL instead of `readline`, so payloads containing `U+2028` or `U+2029` no longer corrupt command or event streams ([#1911](https://github.com/badlogic/pi-mono/issues/1911)) +- Fixed automatic overlay focus restoration in extension UIs to skip non-capturing overlays, and fixed overlay hide behavior to only reassign focus when the hidden overlay had focus ([#1916](https://github.com/badlogic/pi-mono/pull/1916) by [@nicobailon](https://github.com/nicobailon)) +- Fixed `pi config` misclassifying `~/.agents/skills` as project-scoped in non-git directories under `$HOME`, so toggling those skills no longer writes project overrides to `.pi/settings.json` ([#1915](https://github.com/badlogic/pi-mono/issues/1915)) + +## [0.56.3] - 2026-03-06 + +### New Features + +- `claude-sonnet-4-6` model available via the `google-antigravity` provider ([#1859](https://github.com/badlogic/pi-mono/issues/1859)) +- Custom editors can now define their own `onEscape`/`onCtrlD` handlers without being overwritten by app defaults, enabling vim-mode extensions ([#1838](https://github.com/badlogic/pi-mono/issues/1838)) +- Shift+Enter and Ctrl+Enter now work inside tmux via xterm modifyOtherKeys fallback ([docs/tmux.md](docs/tmux.md), [#1872](https://github.com/badlogic/pi-mono/issues/1872)) +- Auto-compaction is now resilient to persistent API errors (e.g. 529 overloaded) and no longer retriggers spuriously after compaction ([#1834](https://github.com/badlogic/pi-mono/issues/1834), [#1860](https://github.com/badlogic/pi-mono/issues/1860)) + +### Added + +- Added `claude-sonnet-4-6` model for the `google-antigravity` provider ([#1859](https://github.com/badlogic/pi-mono/issues/1859)). +- Added [tmux setup documentation](docs/tmux.md) for modified enter key support ([#1872](https://github.com/badlogic/pi-mono/issues/1872)) + +### Fixed + +- Fixed custom editors having their `onEscape`/`onCtrlD` handlers unconditionally overwritten by app-level defaults, making vim-style escape handling impossible ([#1838](https://github.com/badlogic/pi-mono/issues/1838)) +- Fixed auto-compaction retriggering on the first prompt after compaction due to stale pre-compaction assistant usage ([#1860](https://github.com/badlogic/pi-mono/issues/1860) by [@joelhooks](https://github.com/joelhooks)) +- Fixed sessions never auto-compacting when hitting persistent API errors (e.g. 529 overloaded) by estimating context size from the last successful response ([#1834](https://github.com/badlogic/pi-mono/issues/1834)) +- Fixed compaction summarization requests exceeding context limits by truncating tool results to 2k chars ([#1796](https://github.com/badlogic/pi-mono/issues/1796)) +- Fixed `/new` leaving startup header content, including the changelog, visible after starting a fresh session ([#1880](https://github.com/badlogic/pi-mono/issues/1880)) +- Fixed misleading docs and example implying that returning `{ isError: true }` from a tool's `execute` function marks the execution as failed; errors must be signaled by throwing ([#1881](https://github.com/badlogic/pi-mono/issues/1881)) +- Fixed model switches through non-reasoning models to preserve the saved default thinking level instead of persisting a capability-forced `off` clamp ([#1864](https://github.com/badlogic/pi-mono/issues/1864)) +- Fixed parallel pi processes failing with false "No API key found" errors due to immediate lockfile contention on `auth.json` and `settings.json` ([#1871](https://github.com/badlogic/pi-mono/issues/1871)) +- Fixed OpenAI Responses reasoning replay regression that broke multi-turn reasoning continuity ([#1878](https://github.com/badlogic/pi-mono/issues/1878)) + +## [0.56.2] - 2026-03-05 + +### New Features + +- GPT-5.4 support across `openai`, `openai-codex`, `azure-openai-responses`, and `opencode`, with `gpt-5.4` now the default for `openai` and `openai-codex` ([README.md](README.md), [docs/providers.md](docs/providers.md)). +- `treeFilterMode` setting to choose the default `/tree` filter mode (`default`, `no-tools`, `user-only`, `labeled-only`, `all`) ([docs/settings.md](docs/settings.md), [#1852](https://github.com/badlogic/pi-mono/pull/1852) by [@lajarre](https://github.com/lajarre)). +- Mistral native conversations integration with SDK-backed provider behavior, preserving Mistral-specific thinking and replay semantics ([README.md](README.md), [docs/providers.md](docs/providers.md), [#1716](https://github.com/badlogic/pi-mono/issues/1716)). + +### Added + +- Added `gpt-5.4` model availability for `openai`, `openai-codex`, `azure-openai-responses`, and `opencode` providers. +- Added `gpt-5.3-codex` fallback model availability for `github-copilot` until upstream model catalogs include it ([#1853](https://github.com/badlogic/pi-mono/issues/1853)). +- Added `treeFilterMode` setting to choose the default `/tree` filter mode (`default`, `no-tools`, `user-only`, `labeled-only`, `all`) ([#1852](https://github.com/badlogic/pi-mono/pull/1852) by [@lajarre](https://github.com/lajarre)). + +### Changed + +- Updated the default models for the `openai` and `openai-codex` providers to `gpt-5.4`. + +### Fixed + +- Fixed GPT-5.3 Codex follow-up turns dropping OpenAI Responses assistant `phase` metadata by preserving replayable signatures in session history and forwarding `phase` back to the Responses API ([#1819](https://github.com/badlogic/pi-mono/issues/1819)). +- Fixed OpenAI Responses replay to omit empty thinking blocks, avoiding invalid no-op reasoning items in follow-up turns. +- Updated Mistral integration to use the native SDK-backed provider and conversations API, including coding-agent model/provider wiring and Mistral setup documentation ([#1716](https://github.com/badlogic/pi-mono/issues/1716)). +- Fixed Antigravity reliability: endpoint cascade on 403/404, added autopush sandbox fallback, removed extra fingerprint headers ([#1830](https://github.com/badlogic/pi-mono/issues/1830)). +- Fixed `@mariozechner/pi-ai/oauth` extension imports in published installs by resolving the subpath directly from built `dist` files instead of package-root wrapper shims ([#1856](https://github.com/badlogic/pi-mono/issues/1856)). +- Fixed Gemini 3 multi-turn tool use losing structured context by using `skip_thought_signature_validator` sentinel for unsigned function calls instead of text fallback ([#1829](https://github.com/badlogic/pi-mono/issues/1829)). +- Fixed model selector filter not accepting typed characters in VS Code 1.110+ due to missing Kitty CSI-u printable decoding in the `Input` component ([#1857](https://github.com/badlogic/pi-mono/issues/1857)) +- Fixed editor/footer visibility drift during terminal resize by forcing full redraws when terminal width or height changes ([#1844](https://github.com/badlogic/pi-mono/pull/1844) by [@ghoulr](https://github.com/ghoulr)). +- Fixed footer width truncation for wide Unicode text (session name, model, provider) to prevent TUI crashes from rendered lines exceeding terminal width ([#1833](https://github.com/badlogic/pi-mono/issues/1833)). +- Fixed Windows write preview background artifacts by normalizing CRLF content (`\r\n`) to LF for display rendering in tool output previews ([#1854](https://github.com/badlogic/pi-mono/issues/1854)). + +## [0.56.1] - 2026-03-05 + +### Fixed + +- Fixed extension alias fallback resolution to use ESM-aware resolution for `jiti` aliases in global installs ([#1821](https://github.com/badlogic/pi-mono/pull/1821) by [@Perlence](https://github.com/Perlence)) +- Fixed markdown blockquote rendering to isolate blockquote styling from default text style, preventing style leakage. + +## [0.56.0] - 2026-03-04 + +### New Features + +- Added OpenCode Go provider support with `opencode-go` model defaults and `OPENCODE_API_KEY` environment variable support ([docs/providers.md](docs/providers.md), [#1757](https://github.com/badlogic/pi-mono/issues/1757)). +- Added `branchSummary.skipPrompt` setting to skip branch summarization prompts during tree navigation ([docs/settings.md](docs/settings.md), [#1792](https://github.com/badlogic/pi-mono/issues/1792)). +- Added `gemini-3.1-flash-lite-preview` fallback model availability for Google provider catalogs when upstream model metadata lags ([README.md](README.md), [#1785](https://github.com/badlogic/pi-mono/issues/1785)). + +### Breaking Changes + +- Changed scoped model thinking semantics. Scoped entries without an explicit `:` suffix now inherit the current session thinking level when selected, instead of applying a startup-captured default. +- Moved Node OAuth runtime exports off the top-level `@mariozechner/pi-ai` entry. OAuth login and refresh must be imported from `@mariozechner/pi-ai/oauth` ([#1814](https://github.com/badlogic/pi-mono/issues/1814)). + +### Added + +- Added `branchSummary.skipPrompt` setting to skip the summary prompt when navigating branches ([#1792](https://github.com/badlogic/pi-mono/issues/1792)). +- Added OpenCode Go provider support with `opencode-go` model defaults and `OPENCODE_API_KEY` environment variable support ([#1757](https://github.com/badlogic/pi-mono/issues/1757)). +- Added `gemini-3.1-flash-lite-preview` fallback model availability in provider catalogs when upstream catalogs lag ([#1785](https://github.com/badlogic/pi-mono/issues/1785)). + +### Changed + +- Updated Antigravity Gemini 3.1 model metadata and request headers to match upstream behavior. + +### Fixed + +- Fixed IME hardware cursor positioning in the custom extension editor (`ctx.ui.editor()` / extension editor dialog) by propagating focus to the internal `Editor`, preventing the terminal cursor from getting stuck at the bottom-right during composition. +- Added OSC 133 semantic zone markers around rendered user messages to support terminal navigation between prompts in iTerm2, WezTerm, Kitty, Ghostty, and other compatible terminals ([#1805](https://github.com/badlogic/pi-mono/issues/1805)). +- Fixed markdown blockquotes dropping nested list content in the TUI renderer ([#1787](https://github.com/badlogic/pi-mono/issues/1787)). +- Fixed TUI width handling for regional indicator symbols to prevent wrap drift and stale characters during streaming ([#1783](https://github.com/badlogic/pi-mono/issues/1783)). +- Fixed Kitty CSI-u handling to ignore unsupported modifiers so modifier-only events do not insert printable characters ([#1807](https://github.com/badlogic/pi-mono/issues/1807)). +- Fixed single-line paste handling to insert text atomically and avoid repeated `@` autocomplete scans on large pastes ([#1812](https://github.com/badlogic/pi-mono/issues/1812)). +- Fixed extension loading with the new `@mariozechner/pi-ai/oauth` export path by aliasing the oauth subpath in the extension loader and development path mapping ([#1814](https://github.com/badlogic/pi-mono/issues/1814)). +- Fixed browser-safe provider loading regressions by preloading the Bedrock provider module in compiled Bun binaries and rebuilding binaries against fresh workspace dependencies ([#1814](https://github.com/badlogic/pi-mono/issues/1814)). +- Fixed GNU screen terminal detection by downgrading theme output to 256-color mode for `screen*` TERM values ([#1809](https://github.com/badlogic/pi-mono/issues/1809)). +- Fixed branch summarization queue handling so messages typed while summaries are generated are processed correctly ([#1803](https://github.com/badlogic/pi-mono/issues/1803)). +- Fixed compaction summary requests to avoid reasoning output for non-reasoning models ([#1793](https://github.com/badlogic/pi-mono/issues/1793)). +- Fixed overflow auto-compaction cascades so a single overflow does not trigger repeated compaction loops. +- Fixed `models.json` to allow provider-scoped custom model ids and model-level `baseUrl` overrides ([#1759](https://github.com/badlogic/pi-mono/issues/1759), [#1777](https://github.com/badlogic/pi-mono/issues/1777)). +- Fixed session selector display sanitization by stripping control characters from session display text ([#1747](https://github.com/badlogic/pi-mono/issues/1747)). +- Fixed Groq Qwen3 reasoning effort mapping for OpenAI-compatible models ([#1745](https://github.com/badlogic/pi-mono/issues/1745)). +- Fixed Bedrock `AWS_PROFILE` region resolution by honoring profile `region` values ([#1800](https://github.com/badlogic/pi-mono/issues/1800)). +- Fixed Gemini 3.1 thinking-level detection for `google` and `google-vertex` providers ([#1785](https://github.com/badlogic/pi-mono/issues/1785)). +- Fixed browser bundling compatibility for `@mariozechner/pi-ai` by removing Node-only side effects from default browser import paths ([#1814](https://github.com/badlogic/pi-mono/issues/1814)). +## [0.55.4] - 2026-03-02 + +### New Features + +- Runtime tool registration now applies immediately in active sessions. Tools registered via `pi.registerTool()` after startup are available to `pi.getAllTools()` and the LLM without `/reload` ([docs/extensions.md](docs/extensions.md), [examples/extensions/dynamic-tools.ts](examples/extensions/dynamic-tools.ts), [#1720](https://github.com/badlogic/pi-mono/issues/1720)). +- Tool definitions can customize the default system prompt with `promptSnippet` (`Available tools`) and `promptGuidelines` (`Guidelines`) while the tool is active ([docs/extensions.md](docs/extensions.md), [#1720](https://github.com/badlogic/pi-mono/issues/1720)). +- Custom tool renderers can suppress transcript output without leaving extra spacing or empty transcript footprint in interactive rendering ([docs/extensions.md](docs/extensions.md), [#1719](https://github.com/badlogic/pi-mono/pull/1719)). + +### Added + +- Added optional `promptSnippet` to `ToolDefinition` for one-line entries in the default system prompt's `Available tools` section. Active extension tools appear there when registered and active ([#1237](https://github.com/badlogic/pi-mono/pull/1237) by [@semtexzv](https://github.com/semtexzv)). +- Added optional `promptGuidelines` to `ToolDefinition` so active tools can append tool-specific bullets to the default system prompt `Guidelines` section ([#1720](https://github.com/badlogic/pi-mono/issues/1720)). + +### Fixed + +- Fixed `pi.registerTool()` dynamic registration after session initialization. Tools registered in `session_start` and later handlers now refresh immediately, become active, and are visible to the LLM without `/reload` ([#1720](https://github.com/badlogic/pi-mono/issues/1720)) +- Fixed session message persistence ordering by serializing `AgentSession` event processing, preventing `toolResult` entries from being written before their corresponding assistant tool-call messages when extension handlers are asynchronous ([#1717](https://github.com/badlogic/pi-mono/issues/1717)) +- Fixed spacing artifacts when custom tool renderers intentionally suppress per-call transcript output, including extra blank rows in interactive streaming and non-zero transcript footprint for empty custom renders ([#1719](https://github.com/badlogic/pi-mono/pull/1719) by [@alasano](https://github.com/alasano)) +- Fixed `session.prompt()` returning before retry completion by creating the retry promise synchronously at `agent_end` dispatch, which closes a race when earlier queued event handlers are async ([#1726](https://github.com/badlogic/pi-mono/pull/1726) by [@pasky](https://github.com/pasky)) + +## [0.55.3] - 2026-02-27 + +### Fixed + +- Changed the default image paste keybinding on Windows to `alt+v` to avoid `ctrl+v` conflicts with terminal paste behavior ([#1682](https://github.com/badlogic/pi-mono/pull/1682) by [@mrexodia](https://github.com/mrexodia)). + +## [0.55.2] - 2026-02-27 + +### New Features + +- Extensions can dynamically remove custom providers via `pi.unregisterProvider(name)`, restoring any built-in models that were overridden, without requiring `/reload` ([docs](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/custom-provider.md)). +- `pi.registerProvider()` now takes effect immediately when called outside the initial extension load phase (e.g. from a command handler), removing the need for `/reload` after late registrations. + +### Added + +- `pi.unregisterProvider(name)` removes a dynamically registered provider and its models from the registry without requiring `/reload`. Built-in models that were overridden by the provider are restored ([#1669](https://github.com/badlogic/pi-mono/pull/1669) by [@aliou](https://github.com/aliou)). + +### Fixed + +- `pi.registerProvider()` now takes effect immediately when called after the initial extension load phase (e.g. from a command handler). Previously the registration sat in a pending queue that was never flushed until the next `/reload` ([#1669](https://github.com/badlogic/pi-mono/pull/1669) by [@aliou](https://github.com/aliou)). +- Fixed duplicate session headers when forking from a point before any assistant message. `createBranchedSession` now defers file creation to `_persist()` when the branched path has no assistant message, matching the `newSession()` contract ([#1672](https://github.com/badlogic/pi-mono/pull/1672) by [@w-winter](https://github.com/w-winter)). +- Fixed SIGINT being delivered to pi while the process is suspended (e.g. via `ctrl+z`), which could corrupt terminal state on resume ([#1668](https://github.com/badlogic/pi-mono/pull/1668) by [@aliou](https://github.com/aliou)). +- Fixed Z.ai thinking control using wrong parameter name, causing thinking to always be enabled and wasting tokens/latency ([#1674](https://github.com/badlogic/pi-mono/pull/1674) by [@okuyam2y](https://github.com/okuyam2y)) +- Fixed `redacted_thinking` blocks being silently dropped during Anthropic streaming, and related issues with interleaved-thinking beta headers and temperature being sent alongside extended thinking ([#1665](https://github.com/badlogic/pi-mono/pull/1665) by [@tctev](https://github.com/tctev)) +- Fixed `(external, cli)` user-agent flag causing 401 errors on Anthropic setup-token endpoint ([#1677](https://github.com/badlogic/pi-mono/pull/1677) by [@LazerLance777](https://github.com/LazerLance777)) +- Fixed crash when OpenAI-compatible provider returns a chunk with no `choices` array ([#1671](https://github.com/badlogic/pi-mono/issues/1671)) + +## [0.55.1] - 2026-02-26 + +### New Features + +- Added offline startup mode via `--offline` (or `PI_OFFLINE`) to disable startup network operations, with startup network timeouts to avoid hangs in restricted or offline environments. +- Added `gemini-3.1-pro-preview` model support to the `google-gemini-cli` provider ([#1599](https://github.com/badlogic/pi-mono/pull/1599) by [@audichuang](https://github.com/audichuang)). + +### Fixed + +- Fixed offline startup hangs by adding offline startup behavior and network timeouts during managed tool setup ([#1631](https://github.com/badlogic/pi-mono/pull/1631) by [@mcollina](https://github.com/mcollina)) +- Fixed Windows VT input initialization in ESM by loading koffi via createRequire, avoiding runtime and bundling issues in end-user environments ([#1627](https://github.com/badlogic/pi-mono/pull/1627) by [@kaste](https://github.com/kaste)) +- Fixed managed `fd`/`rg` bootstrap on Windows in Git Bash by using `extract-zip` for `.zip` archives, searching extracted layouts more robustly, and isolating extraction temp directories to avoid concurrent download races ([#1348](https://github.com/badlogic/pi-mono/issues/1348)) +- Fixed extension loading on Windows when resolving `@sinclair/typebox` aliases so subpath imports like `@sinclair/typebox/compiler` resolve correctly. +- Fixed adaptive thinking for Claude Sonnet 4.6 in Anthropic and Bedrock providers, and clamped unsupported `xhigh` effort values to supported levels ([#1548](https://github.com/badlogic/pi-mono/pull/1548) by [@tctev](https://github.com/tctev)) +- Fixed Vertex ADC credential detection race by avoiding caching a false negative during async import initialization ([#1550](https://github.com/badlogic/pi-mono/pull/1550) by [@jeremiahgaylord-web](https://github.com/jeremiahgaylord-web)) +- Fixed subagent extension example to resolve user agents from the configured agent directory instead of hardcoded paths ([#1559](https://github.com/badlogic/pi-mono/pull/1559) by [@tianshuwang](https://github.com/tianshuwang)) + +## [0.55.0] - 2026-02-24 + +### Breaking Changes + +- Resource precedence for extensions, skills, prompts, themes, and slash-command name collisions is now project-first (`cwd/.pi`) before user-global (`~/.pi/agent`). If you relied on global resources overriding project resources with the same names, rename or reorder your resources. +- Extension registration conflicts no longer unload the entire later extension. All extensions stay loaded, and conflicting command/tool/flag names are resolved by first registration in load order. + +## [0.54.2] - 2026-02-23 + +### Fixed + +- Fixed `.pi` folder being created unnecessarily when only reading settings. The folder is now only created when writing project-specific settings. +- Fixed extension-driven runtime theme changes to persist in settings so `/settings` reflects the active `currentTheme` after `ctx.ui.setTheme(...)` ([#1483](https://github.com/badlogic/pi-mono/pull/1483) by [@ferologics](https://github.com/ferologics)) +- Fixed interactive mode freezes during large streaming `write` tool calls by using incremental syntax highlighting while partial arguments stream, with a final full re-highlight after tool-call arguments complete. + +## [0.54.1] - 2026-02-22 + +### Fixed + +- Externalized koffi from bun binary builds, reducing archive sizes by ~15MB per platform (e.g. darwin-arm64: 43MB -> 28MB). Koffi's Windows-only `.node` file is now shipped alongside the Windows binary only. + +## [0.54.0] - 2026-02-19 + +### Added + +- Added default skill auto-discovery for `.agents/skills` locations. Pi now discovers project skills from `.agents/skills` in `cwd` and ancestor directories (up to git repo root, or filesystem root when not in a repo), and global skills from `~/.agents/skills`, in addition to existing `.pi` skill paths. + +## [0.53.1] - 2026-02-19 + +### Changed + +- Added Gemini 3.1 model catalog entries for all built-in providers that currently expose it: `google`, `google-vertex`, `opencode`, `openrouter`, and `vercel-ai-gateway`. +- Added Claude Opus 4.6 Thinking to the `google-antigravity` model catalog. + +## [0.53.0] - 2026-02-17 + +### Breaking Changes + +- `SettingsManager` persistence semantics changed for SDK consumers. Setters now update in-memory state immediately and queue disk writes. Code that requires durable on-disk settings must call `await settingsManager.flush()`. +- `AuthStorage` constructor is no longer public. Use static factories (`AuthStorage.create(...)`, `AuthStorage.fromStorage(...)`, `AuthStorage.inMemory(...)`). This breaks code that used `new AuthStorage(...)` directly. + +### Added + +- Added `SettingsManager.drainErrors()` for caller-controlled settings I/O error handling without manager-side console output. +- Added auth storage backends (`FileAuthStorageBackend`, `InMemoryAuthStorageBackend`) and `AuthStorage.fromStorage(...)` for storage-first auth persistence wiring. +- Added Anthropic `claude-sonnet-4-6` model fallback entry to generated model definitions. + +### Changed + +- `SettingsManager` now uses scoped storage abstraction with per-scope locked read/merge/write persistence for global and project settings. + +### Fixed + +- Fixed project settings persistence to preserve unrelated external edits via merge-on-write, while still applying in-memory changes for modified keys. +- Fixed auth credential persistence to preserve unrelated external edits to `auth.json` via locked read/merge/write updates. +- Fixed auth load/persist error surfacing by buffering errors and exposing them via `AuthStorage.drainErrors()`. + +## [0.52.12] - 2026-02-13 + +### Added + +- Added `transport` setting (`"sse"`, `"websocket"`, `"auto"`) to `/settings` and `settings.json` for providers that support multiple transports (currently `openai-codex` via OpenAI Codex Responses). + +### Changed + +- Interactive mode now applies transport changes immediately to the active agent session. +- Settings migration now maps legacy `websockets: boolean` to the new `transport` setting. + +## [0.52.11] - 2026-02-13 + +### Added + +- Added MiniMax M2.5 model entries for `minimax`, `minimax-cn`, `openrouter`, and `vercel-ai-gateway` providers, plus `minimax-m2.5-free` for `opencode`. + +## [0.52.10] - 2026-02-12 + +### New Features + +- Extension terminal input interception via `terminal_input`, allowing extensions to consume or transform raw input before normal TUI handling. See [docs/extensions.md](docs/extensions.md). +- Expanded CLI model selection: `--model` now supports `provider/id`, fuzzy matching, and `:` suffixes. See [README.md](README.md) and [docs/models.md](docs/models.md). +- Safer package source handling with stricter git source parsing and improved local path normalization. See [docs/packages.md](docs/packages.md). +- New built-in model definition `gpt-5.3-codex-spark` for OpenAI and OpenAI Codex providers. +- Improved OpenAI stream robustness for malformed trailing tool-call JSON in partial chunks. +- Added built-in GLM-5 model support via z.ai and OpenRouter provider catalogs. + +### Breaking Changes + +- `ContextUsage.tokens` and `ContextUsage.percent` are now `number | null`. After compaction, context token count is unknown until the next LLM response, so these fields return `null`. Extensions that read `ContextUsage` must handle the `null` case. Removed `usageTokens`, `trailingTokens`, and `lastUsageIndex` fields from `ContextUsage` (implementation details that should not have been public) ([#1382](https://github.com/badlogic/pi-mono/pull/1382) by [@ferologics](https://github.com/ferologics)) +- Git source parsing is now strict without `git:` prefix: only protocol URLs are treated as git (`https://`, `http://`, `ssh://`, `git://`). Shorthand sources like `github.com/org/repo` and `git@github.com:org/repo` now require the `git:` prefix. ([#1426](https://github.com/badlogic/pi-mono/issues/1426)) + +### Added + +- Added extension event forwarding for message and tool execution lifecycles (`message_start`, `message_update`, `message_end`, `tool_execution_start`, `tool_execution_update`, `tool_execution_end`) ([#1375](https://github.com/badlogic/pi-mono/pull/1375) by [@sumeet](https://github.com/sumeet)) +- Added `terminal_input` extension event to intercept, consume, or transform raw terminal input before normal TUI handling. +- Added `gpt-5.3-codex-spark` model definition for OpenAI and OpenAI Codex providers (research preview). + +### Changed + +- Routed GitHub Copilot Claude 4.x models through Anthropic Messages API, with updated Copilot header handling for Claude model requests. + +### Fixed + +- Fixed context usage percentage in footer showing stale pre-compaction values. After compaction the footer now shows `?/200k` until the next LLM response provides accurate usage ([#1382](https://github.com/badlogic/pi-mono/pull/1382) by [@ferologics](https://github.com/ferologics)) +- Fixed `_checkCompaction()` using the first compaction entry instead of the latest, which could cause incorrect overflow detection with multiple compactions ([#1382](https://github.com/badlogic/pi-mono/pull/1382) by [@ferologics](https://github.com/ferologics)) +- `--model` now works without `--provider`, supports `provider/id` syntax, fuzzy matching, and `:` suffix (e.g., `--model sonnet:high`, `--model openai/gpt-4o`) ([#1350](https://github.com/badlogic/pi-mono/pull/1350) by [@mitsuhiko](https://github.com/mitsuhiko)) +- Fixed local package path normalization for extension sources while tightening git source parsing rules ([#1426](https://github.com/badlogic/pi-mono/issues/1426)) +- Fixed extension terminal input listeners not being cleared during session resets, which could leave stale handlers active. +- Fixed Termux bootstrap package name for `fd` installation ([#1433](https://github.com/badlogic/pi-mono/pull/1433)) +- Fixed `@` file autocomplete fuzzy matching to prioritize path-prefix and segment matches for nested paths ([#1423](https://github.com/badlogic/pi-mono/issues/1423)) +- Fixed OpenAI streaming tool-call parsing to tolerate malformed trailing JSON in partial chunks ([#1424](https://github.com/badlogic/pi-mono/issues/1424)) + +## [0.52.9] - 2026-02-08 + +### New Features + +- Extensions can trigger a full runtime reload via `ctx.reload()`, useful for hot-reloading configuration or restarting the agent. See [docs/extensions.md](docs/extensions.md) and the [`reload-runtime` example](examples/extensions/reload-runtime.ts) ([#1371](https://github.com/badlogic/pi-mono/issues/1371)) +- Short CLI disable aliases: `-ne` (`--no-extensions`), `-ns` (`--no-skills`), and `-np` (`--no-prompt-templates`) for faster interactive usage and scripting. +- `/export` HTML now includes collapsible tool input schemas (parameter names, types, and descriptions), improving session review and sharing workflows ([#1416](https://github.com/badlogic/pi-mono/pull/1416) by [@marchellodev](https://github.com/marchellodev)). +- `pi.getAllTools()` now exposes tool parameters in addition to name and description, enabling richer extension integrations ([#1416](https://github.com/badlogic/pi-mono/pull/1416) by [@marchellodev](https://github.com/marchellodev)). + +### Added + +- Added `ctx.reload()` to the extension API for programmatic runtime reload ([#1371](https://github.com/badlogic/pi-mono/issues/1371)) +- Added short aliases for disable flags: `-ne` for `--no-extensions`, `-ns` for `--no-skills`, `-np` for `--no-prompt-templates` +- `/export` HTML now includes tool input schema (parameter names, types, descriptions) in a collapsible section under each tool ([#1416](https://github.com/badlogic/pi-mono/pull/1416) by [@marchellodev](https://github.com/marchellodev)) +- `pi.getAllTools()` now returns tool parameters in addition to name and description ([#1416](https://github.com/badlogic/pi-mono/pull/1416) by [@marchellodev](https://github.com/marchellodev)) + +### Fixed + +- Fixed extension source parsing so dot-prefixed local paths (for example `.pi/extensions/foo.ts`) are treated as local paths instead of git URLs +- Fixed fd/rg download failing on Windows due to `unzip` not being available; now uses `tar` for both `.tar.gz` and `.zip` extraction, with proper error reporting ([#1348](https://github.com/badlogic/pi-mono/issues/1348)) +- Fixed RPC mode documentation incorrectly stating `ctx.hasUI` is `false`; it is `true` because dialog and fire-and-forget UI methods work via the RPC sub-protocol. Also documented missing unsupported/degraded methods (`pasteToEditor`, `getAllThemes`, `getTheme`, `setTheme`) ([#1411](https://github.com/badlogic/pi-mono/pull/1411) by [@aliou](https://github.com/aliou)) +- Fixed `rg` not available in bash tool by downloading it at startup alongside `fd` ([#1348](https://github.com/badlogic/pi-mono/issues/1348)) +- Fixed `custom-compaction` example to use `ModelRegistry` ([#1387](https://github.com/badlogic/pi-mono/issues/1387)) +- Google providers now support full JSON Schema in tool declarations (anyOf, oneOf, const, etc.) ([#1398](https://github.com/badlogic/pi-mono/issues/1398) by [@jarib](https://github.com/jarib)) +- Reverted incorrect Antigravity model change: `claude-opus-4-6-thinking` back to `claude-opus-4-5-thinking` (model does not exist on Antigravity endpoint) +- Updated the Antigravity system instruction to a more compact version for Google Gemini CLI compatibility +- Corrected opencode context windows for Claude Sonnet 4 and 4.5 ([#1383](https://github.com/badlogic/pi-mono/issues/1383)) +- Fixed subagent example unknown-agent errors to include available agent names ([#1414](https://github.com/badlogic/pi-mono/pull/1414) by [@dnouri](https://github.com/dnouri)) + +## [0.52.8] - 2026-02-07 + +### New Features + +- Emacs-style kill ring (`ctrl+k`/`ctrl+y`/`alt+y`) and undo (`ctrl+z`) in the editor input ([#1373](https://github.com/badlogic/pi-mono/pull/1373) by [@Perlence](https://github.com/Perlence)) +- OpenRouter `auto` model alias (`openrouter:auto`) for automatic model routing ([#1361](https://github.com/badlogic/pi-mono/pull/1361) by [@yogasanas](https://github.com/yogasanas)) +- Extensions can programmatically paste content into the editor via `pasteToEditor` in the extension UI context. See [docs/extensions.md](docs/extensions.md) ([#1351](https://github.com/badlogic/pi-mono/pull/1351) by [@kaofelix](https://github.com/kaofelix)) +- `pi --help` and invalid subcommands now show helpful output instead of failing silently ([#1347](https://github.com/badlogic/pi-mono/pull/1347) by [@ferologics](https://github.com/ferologics)) + +### Added + +- Added `pasteToEditor` to extension UI context for programmatic editor paste ([#1351](https://github.com/badlogic/pi-mono/pull/1351) by [@kaofelix](https://github.com/kaofelix)) +- Added package subcommand help and friendly error messages for invalid commands ([#1347](https://github.com/badlogic/pi-mono/pull/1347) by [@ferologics](https://github.com/ferologics)) +- Added OpenRouter `auto` model alias for automatic model routing ([#1361](https://github.com/badlogic/pi-mono/pull/1361) by [@yogasanas](https://github.com/yogasanas)) +- Added kill ring (ctrl+k/ctrl+y/alt+y) and undo (ctrl+z) support to the editor input ([#1373](https://github.com/badlogic/pi-mono/pull/1373) by [@Perlence](https://github.com/Perlence)) + +### Changed + +- Replaced Claude Opus 4.5 with Opus 4.6 as default model ([#1345](https://github.com/badlogic/pi-mono/pull/1345) by [@calvin-hpnet](https://github.com/calvin-hpnet)) + +### Fixed + +- Fixed temporary git package caches (`-e `) to refresh on cache hits for unpinned sources, including detached/no-upstream checkouts +- Fixed aborting retries when an extension customizes the editor ([#1364](https://github.com/badlogic/pi-mono/pull/1364) by [@Perlence](https://github.com/Perlence)) +- Fixed autocomplete not propagating to custom editors created by extensions ([#1372](https://github.com/badlogic/pi-mono/pull/1372) by [@Perlence](https://github.com/Perlence)) +- Fixed extension shutdown to use clean TUI shutdown path, preventing orphaned processes + +## [0.52.7] - 2026-02-06 + +### New Features + +- Per-model overrides in `models.json` via `modelOverrides`, allowing customization of built-in provider models without replacing provider model lists. See [docs/models.md#per-model-overrides](docs/models.md#per-model-overrides). +- `models.json` provider `models` now merge with built-in models by `id`, so custom models can be added or replace matching built-ins without full provider replacement. See [docs/models.md#overriding-built-in-providers](docs/models.md#overriding-built-in-providers). +- Bedrock proxy support for unauthenticated endpoints via `AWS_BEDROCK_SKIP_AUTH` and `AWS_BEDROCK_FORCE_HTTP1`. See [docs/providers.md](docs/providers.md). + +### Breaking Changes + +- Changed `models.json` provider `models` behavior from full replacement to merge-by-id with built-in models. Built-in models are now kept by default, and custom models upsert by `id`. + +### Added + +- Added `modelOverrides` in `models.json` to customize individual built-in models per provider without full provider replacement ([#1332](https://github.com/badlogic/pi-mono/pull/1332) by [@charles-cooper](https://github.com/charles-cooper)) +- Added `AWS_BEDROCK_SKIP_AUTH` and `AWS_BEDROCK_FORCE_HTTP1` environment variables for connecting to unauthenticated Bedrock proxies ([#1320](https://github.com/badlogic/pi-mono/pull/1320) by [@virtuald](https://github.com/virtuald)) + +### Fixed + +- Fixed extra spacing between thinking-only assistant content and subsequent tool execution blocks when assistant messages contain no text +- Fixed queued steering/follow-up/custom messages remaining stuck after threshold auto-compaction by resuming the agent loop when Agent-level queues still contain pending messages ([#1312](https://github.com/badlogic/pi-mono/pull/1312) by [@ferologics](https://github.com/ferologics)) +- Fixed `tool_result` extension handlers to chain result patches across handlers instead of last-handler-wins behavior ([#1280](https://github.com/badlogic/pi-mono/issues/1280)) +- Fixed compromised auth lock files being handled gracefully instead of crashing auth storage initialization ([#1322](https://github.com/badlogic/pi-mono/issues/1322)) +- Fixed Bedrock adaptive thinking handling for Claude Opus 4.6 with interleaved thinking beta responses ([#1323](https://github.com/badlogic/pi-mono/pull/1323) by [@markusylisiurunen](https://github.com/markusylisiurunen)) +- Fixed OpenAI Responses API requests to use `store: false` by default to avoid server-side history logging ([#1308](https://github.com/badlogic/pi-mono/issues/1308)) +- Fixed interactive mode startup by initializing autocomplete after resources are loaded ([#1328](https://github.com/badlogic/pi-mono/issues/1328)) +- Fixed `modelOverrides` merge behavior for nested objects and documented usage details ([#1062](https://github.com/badlogic/pi-mono/issues/1062)) + +## [0.52.6] - 2026-02-05 + +### Breaking Changes + +- Removed `/exit` command handling. Use `/quit` to exit ([#1303](https://github.com/badlogic/pi-mono/issues/1303)) + +### Fixed + +- Fixed `/quit` being shadowed by fuzzy slash command autocomplete matches from skills by adding `/quit` to built-in command autocomplete ([#1303](https://github.com/badlogic/pi-mono/issues/1303)) +- Fixed local package source parsing and settings normalization regression that misclassified relative paths as git URLs and prevented globally installed local packages from loading after restart ([#1304](https://github.com/badlogic/pi-mono/issues/1304)) + +## [0.52.5] - 2026-02-05 + +### Fixed + +- Fixed thinking level capability detection so Anthropic Opus 4.6 models expose `xhigh` in selectors and cycling + +## [0.52.4] - 2026-02-05 + +### Fixed + +- Fixed extensions setting not respecting `package.json` `pi.extensions` manifest when directory is specified directly ([#1302](https://github.com/badlogic/pi-mono/pull/1302) by [@hjanuschka](https://github.com/hjanuschka)) + +## [0.52.3] - 2026-02-05 + +### Fixed + +- Fixed git package parsing fallback for unknown hosts so enterprise git sources like `git:github.tools.sap/org/repo` are treated as git packages instead of local paths +- Fixed git package `@ref` parsing for shorthand, HTTPS, and SSH source formats, including branch refs with slashes +- Fixed Bedrock default model ID from `us.anthropic.claude-opus-4-6-v1:0` to `us.anthropic.claude-opus-4-6-v1` +- Fixed Bedrock Opus 4.6 model metadata (IDs, cache pricing) and added missing EU profile +- Fixed Claude Opus 4.6 context window metadata to 200000 for Anthropic and OpenCode providers + +## [0.52.2] - 2026-02-05 + +### Changed + +- Updated default model for `anthropic` provider to `claude-opus-4-6` +- Updated default model for `openai-codex` provider to `gpt-5.3-codex` +- Updated default model for `amazon-bedrock` provider to `us.anthropic.claude-opus-4-6-v1:0` +- Updated default model for `vercel-ai-gateway` provider to `anthropic/claude-opus-4-6` +- Updated default model for `opencode` provider to `claude-opus-4-6` + +## [0.52.1] - 2026-02-05 + +## [0.52.0] - 2026-02-05 + +### New Features + +- Claude Opus 4.6 model support. +- GPT-5.3 Codex model support (OpenAI Codex provider only). +- SSH URL support for git packages. See [docs/packages.md](docs/packages.md). +- `auth.json` API keys now support shell command resolution (`!command`) and environment variable lookup. See [docs/providers.md](docs/providers.md). +- Model selectors now display the selected model name. + +### Added + +- API keys in `auth.json` now support shell command resolution (`!command`) and environment variable lookup, matching the behavior in `models.json` +- Added `minimal-mode.ts` example extension demonstrating how to override built-in tool rendering for a minimal display mode +- Added Claude Opus 4.6 model to the model catalog +- Added GPT-5.3 Codex model to the model catalog (OpenAI Codex provider only) +- Added SSH URL support for git packages ([#1287](https://github.com/badlogic/pi-mono/pull/1287) by [@markusn](https://github.com/markusn)) +- Model selectors now display the selected model name ([#1275](https://github.com/badlogic/pi-mono/pull/1275) by [@haoqixu](https://github.com/haoqixu)) + +### Fixed + +- Fixed HTML export losing indentation in ANSI-rendered tool output (e.g. JSON code blocks in custom tool results) ([#1269](https://github.com/badlogic/pi-mono/pull/1269) by [@aliou](https://github.com/aliou)) +- Fixed images being silently dropped when `prompt()` is called with both `images` and `streamingBehavior` during streaming. `steer()`, `followUp()`, and the corresponding RPC commands now accept optional images. ([#1271](https://github.com/badlogic/pi-mono/pull/1271) by [@aliou](https://github.com/aliou)) +- CLI `--help`, `--version`, `--list-models`, and `--export` now exit even if extensions keep the event loop alive ([#1285](https://github.com/badlogic/pi-mono/pull/1285) by [@ferologics](https://github.com/ferologics)) +- Fixed crash when models send malformed tool arguments (objects instead of strings) ([#1259](https://github.com/badlogic/pi-mono/issues/1259)) +- Fixed custom message expand state not being respected ([#1258](https://github.com/badlogic/pi-mono/pull/1258) by [@Gurpartap](https://github.com/Gurpartap)) +- Fixed skill loader to respect .gitignore, .ignore, and .fdignore when scanning directories + +## [0.51.6] - 2026-02-04 + +### New Features + +- Configurable resume keybinding action for opening the session resume selector. See [docs/keybindings.md](docs/keybindings.md). ([#1249](https://github.com/badlogic/pi-mono/pull/1249) by [@juanibiapina](https://github.com/juanibiapina)) + +### Added + +- Added `resume` as a configurable keybinding action, allowing users to bind a key to open the session resume selector (like `newSession`, `tree`, and `fork`) ([#1249](https://github.com/badlogic/pi-mono/pull/1249) by [@juanibiapina](https://github.com/juanibiapina)) + +### Changed + +- Slash command menu now triggers on the first line even when other lines have content, allowing commands to be prepended to existing text ([#1227](https://github.com/badlogic/pi-mono/pull/1227) by [@aliou](https://github.com/aliou)) + +### Fixed + +- Ignored unknown skill frontmatter fields when loading skills +- Fixed `/reload` not picking up changes in global settings.json ([#1241](https://github.com/badlogic/pi-mono/issues/1241)) +- Fixed forked sessions to persist the user message after forking +- Fixed forked sessions to write to new session files instead of the parent ([#1242](https://github.com/badlogic/pi-mono/issues/1242)) +- Fixed local package removal to normalize paths before comparison ([#1243](https://github.com/badlogic/pi-mono/issues/1243)) +- Fixed OpenAI Codex Responses provider to respect configured baseUrl ([#1244](https://github.com/badlogic/pi-mono/issues/1244)) +- Fixed `/settings` crashing in narrow terminals by handling small widths in the settings list ([#1246](https://github.com/badlogic/pi-mono/pull/1246) by [@haoqixu](https://github.com/haoqixu)) +- Fixed Unix bash detection to fall back to PATH lookup when `/bin/bash` is unavailable, including Termux setups ([#1230](https://github.com/badlogic/pi-mono/pull/1230) by [@VaclavSynacek](https://github.com/VaclavSynacek)) + +## [0.51.5] - 2026-02-04 + +### Changed + +- Changed Bedrock model generation to drop legacy workarounds now handled upstream ([#1239](https://github.com/badlogic/pi-mono/pull/1239) by [@unexge](https://github.com/unexge)) + +### Fixed + +- Fixed Windows package installs regression by using shell execution instead of `.cmd` resolution ([#1220](https://github.com/badlogic/pi-mono/issues/1220)) + +## [0.51.4] - 2026-02-03 + +### New Features + +- Share URLs now default to pi.dev, graciously donated by exe.dev. + +### Changed + +- Share URLs now use pi.dev by default while pi.dev and buildwithpi.ai continue to work. + +### Fixed + +- Fixed input scrolling to avoid splitting emoji sequences ([#1228](https://github.com/badlogic/pi-mono/pull/1228) by [@haoqixu](https://github.com/haoqixu)) + +## [0.51.3] - 2026-02-03 + +### New Features + +- Command discovery for extensions via `ExtensionAPI.getCommands()`, with `commands.ts` example for invocation patterns. See [docs/extensions.md#pigetcommands](docs/extensions.md#pigetcommands) and [examples/extensions/commands.ts](examples/extensions/commands.ts). +- Local path support for `pi install` and `pi remove`, with relative path resolution against the settings file. See [docs/packages.md#local-paths](docs/packages.md#local-paths). + +### Breaking Changes + +- RPC `get_commands` response and `SlashCommandSource` type: renamed `"template"` to `"prompt"` for consistency with the rest of the codebase + +### Added + +- Added `ExtensionAPI.getCommands()` to let extensions list available slash commands (extensions, prompt templates, skills) for invocation via `prompt` ([#1210](https://github.com/badlogic/pi-mono/pull/1210) by [@w-winter](https://github.com/w-winter)) +- Added `commands.ts` example extension and exported `SlashCommandInfo` types for command discovery integrations ([#1210](https://github.com/badlogic/pi-mono/pull/1210) by [@w-winter](https://github.com/w-winter)) +- Added local path support for `pi install` and `pi remove` with relative paths stored against the target settings file ([#1216](https://github.com/badlogic/pi-mono/issues/1216)) + +### Fixed + +- Fixed default thinking level persistence so settings-derived defaults are saved and restored correctly +- Fixed Windows package installs by resolving `npm.cmd` when `npm` is not directly executable ([#1220](https://github.com/badlogic/pi-mono/issues/1220)) +- Fixed xhigh thinking level support check to accept gpt-5.2 model IDs ([#1209](https://github.com/badlogic/pi-mono/issues/1209)) + +## [0.51.2] - 2026-02-03 + +### New Features + +- Extension tool output expansion controls via ExtensionUIContext getToolsExpanded and setToolsExpanded. See [docs/extensions.md](docs/extensions.md) and [docs/rpc.md](docs/rpc.md). + +### Added + +- Added ExtensionUIContext getToolsExpanded and setToolsExpanded for controlling tool output expansion ([#1199](https://github.com/badlogic/pi-mono/pull/1199) by [@academo](https://github.com/academo)) +- Added install method detection to show package manager specific update instructions ([#1203](https://github.com/badlogic/pi-mono/pull/1203) by [@Itsnotaka](https://github.com/Itsnotaka)) + +### Fixed + +- Fixed Kitty key release events leaking to parent shell over slow SSH connections by draining stdin for up to 1s on exit ([#1204](https://github.com/badlogic/pi-mono/issues/1204)) +- Fixed legacy newline handling in the editor to preserve previous newline behavior +- Fixed @ autocomplete to include hidden paths +- Fixed submit fallback to honor configured keybindings +- Fixed extension commands conflicting with built-in commands by skipping them ([#1196](https://github.com/badlogic/pi-mono/pull/1196) by [@haoqixu](https://github.com/haoqixu)) +- Fixed @-prefixed tool paths failing to resolve by stripping the prefix ([#1206](https://github.com/badlogic/pi-mono/issues/1206)) +- Fixed install method detection to avoid stale cached results + +## [0.51.1] - 2026-02-02 + +### New Features + +- **Extension API switchSession**: Extensions can now programmatically switch sessions via `ctx.switchSession(sessionPath)`. See [docs/extensions.md](docs/extensions.md). ([#1187](https://github.com/badlogic/pi-mono/issues/1187)) +- **Clear on shrink setting**: New `terminal.clearOnShrink` setting keeps the editor and footer pinned to the bottom of the terminal when content shrinks. May cause some flicker due to redraws. Disabled by default. Enable via `/settings` or `PI_CLEAR_ON_SHRINK=1` env var. + +### Fixed + +- Fixed scoped models not finding valid credentials after logout ([#1194](https://github.com/badlogic/pi-mono/pull/1194) by [@terrorobe](https://github.com/terrorobe)) +- Fixed Ctrl+D exit closing the parent SSH session due to stdin buffer race condition ([#1185](https://github.com/badlogic/pi-mono/issues/1185)) +- Fixed emoji cursor positioning in editor input ([#1183](https://github.com/badlogic/pi-mono/pull/1183) by [@haoqixu](https://github.com/haoqixu)) + +## [0.51.0] - 2026-02-01 + +### Breaking Changes + +- **Extension tool signature change**: `ToolDefinition.execute` now uses `(toolCallId, params, signal, onUpdate, ctx)` parameter order to match `AgentTool.execute`. Previously it was `(toolCallId, params, onUpdate, ctx, signal)`. This makes wrapping built-in tools trivial since the first four parameters now align. Update your extensions by swapping the `signal` and `onUpdate` parameters: + ```ts + // Before + async execute(toolCallId, params, onUpdate, ctx, signal) { ... } + + // After + async execute(toolCallId, params, signal, onUpdate, ctx) { ... } + ``` + +### New Features + +- **Android/Termux support**: Pi now runs on Android via Termux. Install with: + ```bash + pkg install nodejs termux-api git + npm install -g @mariozechner/pi-coding-agent + mkdir -p ~/.pi/agent + echo "You are running on Android in Termux." > ~/.pi/agent/AGENTS.md + ``` + Clipboard operations fall back gracefully when `termux-api` is unavailable. ([#1164](https://github.com/badlogic/pi-mono/issues/1164)) +- **Bash spawn hook**: Extensions can now intercept and modify bash commands before execution via `pi.setBashSpawnHook()`. Adjust the command string, working directory, or environment variables. See [docs/extensions.md](docs/extensions.md). ([#1160](https://github.com/badlogic/pi-mono/pull/1160) by [@mitsuhiko](https://github.com/mitsuhiko)) +- **Linux ARM64 musl support**: Pi now runs on Alpine Linux ARM64 (linux-arm64-musl) via updated clipboard dependency. +- **Nix/Guix support**: `PI_PACKAGE_DIR` environment variable overrides the package path for content-addressed package managers where store paths tokenize poorly. See [README.md#environment-variables](README.md#environment-variables). ([#1153](https://github.com/badlogic/pi-mono/pull/1153) by [@odysseus0](https://github.com/odysseus0)) +- **Named session filter**: `/resume` picker now supports filtering to show only named sessions via Ctrl+N. Configurable via `toggleSessionNamedFilter` keybinding. See [docs/keybindings.md](docs/keybindings.md). ([#1128](https://github.com/badlogic/pi-mono/pull/1128) by [@w-winter](https://github.com/w-winter)) +- **Typed tool call events**: Extension developers can narrow `ToolCallEvent` types using `isToolCallEventType()` for better TypeScript support. See [docs/extensions.md#tool-call-events](docs/extensions.md#tool-call-events). ([#1147](https://github.com/badlogic/pi-mono/pull/1147) by [@giuseppeg](https://github.com/giuseppeg)) +- **Extension UI Protocol**: Full RPC documentation and examples for extension dialogs and notifications, enabling headless clients to support interactive extensions. See [docs/rpc.md#extension-ui-protocol](docs/rpc.md#extension-ui-protocol). ([#1144](https://github.com/badlogic/pi-mono/pull/1144) by [@aliou](https://github.com/aliou)) + +### Added + +- Added Linux ARM64 musl (Alpine Linux) support via clipboard dependency update +- Added Android/Termux support with graceful clipboard fallback ([#1164](https://github.com/badlogic/pi-mono/issues/1164)) +- Added bash tool spawn hook support for adjusting command, cwd, and env before execution ([#1160](https://github.com/badlogic/pi-mono/pull/1160) by [@mitsuhiko](https://github.com/mitsuhiko)) +- Added typed `ToolCallEvent.input` per tool with `isToolCallEventType()` type guard for narrowing built-in tool events ([#1147](https://github.com/badlogic/pi-mono/pull/1147) by [@giuseppeg](https://github.com/giuseppeg)) +- Exported `discoverAndLoadExtensions` from package to enable extension testing without a local repo clone ([#1148](https://github.com/badlogic/pi-mono/issues/1148)) +- Added Extension UI Protocol documentation to RPC docs covering all request/response types for extension dialogs and notifications ([#1144](https://github.com/badlogic/pi-mono/pull/1144) by [@aliou](https://github.com/aliou)) +- Added `rpc-demo.ts` example extension exercising all RPC-supported extension UI methods ([#1144](https://github.com/badlogic/pi-mono/pull/1144) by [@aliou](https://github.com/aliou)) +- Added `rpc-extension-ui.ts` TUI example client demonstrating the extension UI protocol with interactive dialogs ([#1144](https://github.com/badlogic/pi-mono/pull/1144) by [@aliou](https://github.com/aliou)) +- Added `PI_PACKAGE_DIR` environment variable to override package path for content-addressed package managers (Nix, Guix) where store paths tokenize poorly ([#1153](https://github.com/badlogic/pi-mono/pull/1153) by [@odysseus0](https://github.com/odysseus0)) +- `/resume` session picker now supports named-only filter toggle (default Ctrl+N, configurable via `toggleSessionNamedFilter`) to show only named sessions ([#1128](https://github.com/badlogic/pi-mono/pull/1128) by [@w-winter](https://github.com/w-winter)) + +### Fixed + +- Fixed `pi update` not updating npm/git packages when called without arguments ([#1151](https://github.com/badlogic/pi-mono/issues/1151)) +- Fixed `models.json` validation requiring fields documented as optional. Model definitions now only require `id`; all other fields (`name`, `reasoning`, `input`, `cost`, `contextWindow`, `maxTokens`) have sensible defaults. ([#1146](https://github.com/badlogic/pi-mono/issues/1146)) +- Fixed models resolving relative paths in skill files from cwd instead of skill directory by adding explicit guidance to skills preamble ([#1136](https://github.com/badlogic/pi-mono/issues/1136)) +- Fixed tree selector losing focus state when navigating entries ([#1142](https://github.com/badlogic/pi-mono/pull/1142) by [@Perlence](https://github.com/Perlence)) +- Fixed `cacheRetention` option not being passed through in `buildBaseOptions` ([#1154](https://github.com/badlogic/pi-mono/issues/1154)) +- Fixed OAuth login/refresh not using HTTP proxy settings (`HTTP_PROXY`, `HTTPS_PROXY` env vars) ([#1132](https://github.com/badlogic/pi-mono/issues/1132)) +- Fixed `pi update ` installing packages locally when the source is only registered globally ([#1163](https://github.com/badlogic/pi-mono/pull/1163) by [@aliou](https://github.com/aliou)) +- Fixed tree navigation with summarization overwriting editor content typed during the summarization wait ([#1169](https://github.com/badlogic/pi-mono/pull/1169) by [@aliou](https://github.com/aliou)) + +## [0.50.9] - 2026-02-01 + +### Added + +- Added `titlebar-spinner.ts` example extension that shows a braille spinner animation in the terminal title while the agent is working. +- Added `PI_AI_ANTIGRAVITY_VERSION` environment variable documentation to help text ([#1129](https://github.com/badlogic/pi-mono/issues/1129)) +- Added `cacheRetention` stream option with provider-specific mappings for prompt cache controls, defaulting to short retention ([#1134](https://github.com/badlogic/pi-mono/issues/1134)) + +## [0.50.8] - 2026-02-01 + +### Added + +- Added `newSession`, `tree`, and `fork` keybinding actions for `/new`, `/tree`, and `/fork` commands. All unbound by default. ([#1114](https://github.com/badlogic/pi-mono/pull/1114) by [@juanibiapina](https://github.com/juanibiapina)) +- Added `retry.maxDelayMs` setting to cap maximum server-requested retry delay. When a provider requests a longer delay (e.g., Google's "quota will reset after 5h"), the request fails immediately with an informative error instead of waiting silently. Default: 60000ms (60 seconds). ([#1123](https://github.com/badlogic/pi-mono/issues/1123)) +- `/resume` session picker: new "Threaded" sort mode (now default) displays sessions in a tree structure based on fork relationships. Compact one-line format with message count and age on the right. ([#1124](https://github.com/badlogic/pi-mono/pull/1124) by [@pasky](https://github.com/pasky)) +- Added Qwen CLI OAuth provider extension example. ([#940](https://github.com/badlogic/pi-mono/pull/940) by [@4h9fbZ](https://github.com/4h9fbZ)) +- Added OAuth `modifyModels` hook support for extension-registered providers at registration time. ([#940](https://github.com/badlogic/pi-mono/pull/940) by [@4h9fbZ](https://github.com/4h9fbZ)) +- Added Qwen thinking format support for OpenAI-compatible completions via `enable_thinking`. ([#940](https://github.com/badlogic/pi-mono/pull/940) by [@4h9fbZ](https://github.com/4h9fbZ)) +- Added sticky column tracking for vertical cursor navigation so the editor restores the preferred column when moving across short lines. ([#1120](https://github.com/badlogic/pi-mono/pull/1120) by [@Perlence](https://github.com/Perlence)) +- Added `resources_discover` extension hook to supply additional skills, prompts, and themes on startup and reload. + +### Fixed + +- Fixed `switchSession()` appending spurious `thinking_level_change` entry to session log on resume. `setThinkingLevel()` is now idempotent. ([#1118](https://github.com/badlogic/pi-mono/issues/1118)) +- Fixed clipboard image paste on WSL2/WSLg writing invalid PNG files when clipboard provides `image/bmp` format. BMP images are now converted to PNG before saving. ([#1112](https://github.com/badlogic/pi-mono/pull/1112) by [@lightningRalf](https://github.com/lightningRalf)) +- Fixed Kitty keyboard protocol base layout fallback so non-QWERTY layouts do not trigger wrong shortcuts ([#1096](https://github.com/badlogic/pi-mono/pull/1096) by [@rytswd](https://github.com/rytswd)) + +## [0.50.7] - 2026-01-31 + +### Fixed + +- Multi-file extensions in packages now work correctly. Package resolution now uses the same discovery logic as local extensions: only `index.ts` (or manifest-declared entries) are loaded from subdirectories, not helper modules. ([#1102](https://github.com/badlogic/pi-mono/issues/1102)) + +## [0.50.6] - 2026-01-30 + +### Added + +- Added `ctx.getSystemPrompt()` to extension context for accessing the current effective system prompt ([#1098](https://github.com/badlogic/pi-mono/pull/1098) by [@kaofelix](https://github.com/kaofelix)) + +### Fixed + +- Fixed empty rows appearing below footer when content shrinks (e.g., closing `/tree`, clearing multi-line editor) ([#1095](https://github.com/badlogic/pi-mono/pull/1095) by [@marckrenn](https://github.com/marckrenn)) +- Fixed terminal cursor remaining hidden after exiting TUI via `stop()` when a render was pending ([#1099](https://github.com/badlogic/pi-mono/pull/1099) by [@haoqixu](https://github.com/haoqixu)) + +## [0.50.5] - 2026-01-30 + +## [0.50.4] - 2026-01-30 + +### New Features + +- **OSC 52 clipboard support for SSH/mosh** - The `/copy` command now works over remote connections using the OSC 52 terminal escape sequence. No more clipboard frustration when using pi over SSH. ([#1069](https://github.com/badlogic/pi-mono/issues/1069) by [@gturkoglu](https://github.com/gturkoglu)) +- **Vercel AI Gateway routing** - Route requests through Vercel's AI Gateway with provider failover and load balancing. Configure via `vercelGatewayRouting` in models.json. ([#1051](https://github.com/badlogic/pi-mono/pull/1051) by [@ben-vargas](https://github.com/ben-vargas)) +- **Character jump navigation** - Bash/Readline-style character search: Ctrl+] jumps forward to the next occurrence of a character, Ctrl+Alt+] jumps backward. ([#1074](https://github.com/badlogic/pi-mono/pull/1074) by [@Perlence](https://github.com/Perlence)) +- **Emacs-style Ctrl+B/Ctrl+F navigation** - Alternative keybindings for word navigation (cursor word left/right) in the editor. ([#1053](https://github.com/badlogic/pi-mono/pull/1053) by [@ninlds](https://github.com/ninlds)) +- **Line boundary navigation** - Editor jumps to line start when pressing Up at first visual line, and line end when pressing Down at last visual line. ([#1050](https://github.com/badlogic/pi-mono/pull/1050) by [@4h9fbZ](https://github.com/4h9fbZ)) +- **Performance improvements** - Optimized image line detection and box rendering cache in the TUI for better rendering performance. ([#1084](https://github.com/badlogic/pi-mono/pull/1084) by [@can1357](https://github.com/can1357)) +- **`set_session_name` RPC command** - Headless clients can now set the session display name programmatically. ([#1075](https://github.com/badlogic/pi-mono/pull/1075) by [@dnouri](https://github.com/dnouri)) +- **Disable double-escape behavior** - New `"none"` option for `doubleEscapeAction` setting completely disables the double-escape shortcut. ([#973](https://github.com/badlogic/pi-mono/issues/973) by [@juanibiapina](https://github.com/juanibiapina)) + +### Added + +- Added "none" option to `doubleEscapeAction` setting to disable double-escape behavior entirely ([#973](https://github.com/badlogic/pi-mono/issues/973) by [@juanibiapina](https://github.com/juanibiapina)) +- Added OSC 52 clipboard support for SSH/mosh sessions. `/copy` now works over remote connections. ([#1069](https://github.com/badlogic/pi-mono/issues/1069) by [@gturkoglu](https://github.com/gturkoglu)) +- Added Vercel AI Gateway routing support via `vercelGatewayRouting` in models.json ([#1051](https://github.com/badlogic/pi-mono/pull/1051) by [@ben-vargas](https://github.com/ben-vargas)) +- Added Ctrl+B and Ctrl+F keybindings for cursor word left/right navigation in the editor ([#1053](https://github.com/badlogic/pi-mono/pull/1053) by [@ninlds](https://github.com/ninlds)) +- Added character jump navigation: Ctrl+] jumps forward to next character, Ctrl+Alt+] jumps backward ([#1074](https://github.com/badlogic/pi-mono/pull/1074) by [@Perlence](https://github.com/Perlence)) +- Editor now jumps to line start when pressing Up at first visual line, and line end when pressing Down at last visual line ([#1050](https://github.com/badlogic/pi-mono/pull/1050) by [@4h9fbZ](https://github.com/4h9fbZ)) +- Optimized image line detection and box rendering cache for better TUI performance ([#1084](https://github.com/badlogic/pi-mono/pull/1084) by [@can1357](https://github.com/can1357)) +- Added `set_session_name` RPC command for headless clients to set session display name ([#1075](https://github.com/badlogic/pi-mono/pull/1075) by [@dnouri](https://github.com/dnouri)) + +### Fixed + +- Read tool now handles macOS filenames with curly quotes (U+2019) and NFD Unicode normalization ([#1078](https://github.com/badlogic/pi-mono/issues/1078)) +- Respect .gitignore, .ignore, and .fdignore files when scanning package resources for skills, prompts, themes, and extensions ([#1072](https://github.com/badlogic/pi-mono/issues/1072)) +- Fixed tool call argument defaults when providers omit inputs ([#1065](https://github.com/badlogic/pi-mono/issues/1065)) +- Invalid JSON in settings.json no longer causes the file to be overwritten with empty settings ([#1054](https://github.com/badlogic/pi-mono/issues/1054)) +- Config selector now shows folder name for extensions with duplicate display names ([#1064](https://github.com/badlogic/pi-mono/pull/1064) by [@Graffioh](https://github.com/Graffioh)) + +## [0.50.3] - 2026-01-29 + +### New Features + +- **Kimi For Coding provider**: Access Moonshot AI's Anthropic-compatible coding API. Set `KIMI_API_KEY` environment variable. See [README.md#kimi-for-coding](README.md#kimi-for-coding). + +### Added + +- Added Kimi For Coding provider support (Moonshot AI's Anthropic-compatible coding API). Set `KIMI_API_KEY` environment variable. See [README.md#kimi-for-coding](README.md#kimi-for-coding). + +### Fixed + +- Resources now appear before messages when resuming a session, preventing loaded context from appearing at the bottom of the chat. + +## [0.50.2] - 2026-01-29 + +### New Features + +- **Hugging Face provider**: Access Hugging Face models via OpenAI-compatible Inference Router. Set `HF_TOKEN` environment variable. See [README.md#hugging-face](README.md#hugging-face). +- **Extended prompt caching**: `PI_CACHE_RETENTION=long` enables 1-hour caching for Anthropic (vs 5min default) and 24-hour for OpenAI (vs in-memory default). Only applies to direct API calls. See [README.md#prompt-caching](README.md#prompt-caching). +- **Configurable autocomplete height**: `autocompleteMaxVisible` setting (3-20 items, default 5) controls dropdown size. Adjust via `/settings` or `settings.json`. +- **Shell-style keybindings**: `alt+b`/`alt+f` for word navigation, `ctrl+d` for delete character forward. See [docs/keybindings.md](docs/keybindings.md). +- **RPC `get_commands`**: Headless clients can now list available commands programmatically. See [docs/rpc.md](docs/rpc.md). + +### Added + +- Added Hugging Face provider support via OpenAI-compatible Inference Router ([#994](https://github.com/badlogic/pi-mono/issues/994)) +- Added `PI_CACHE_RETENTION` environment variable to control cache TTL for Anthropic (5m vs 1h) and OpenAI (in-memory vs 24h). Set to `long` for extended retention. ([#967](https://github.com/badlogic/pi-mono/issues/967)) +- Added `autocompleteMaxVisible` setting for configurable autocomplete dropdown height (3-20 items, default 5) ([#972](https://github.com/badlogic/pi-mono/pull/972) by [@masonc15](https://github.com/masonc15)) +- Added `/files` command to list all file operations (read, write, edit) in the current session +- Added shell-style keybindings: `alt+b`/`alt+f` for word navigation, `ctrl+d` for delete character forward (when editor has text) ([#1043](https://github.com/badlogic/pi-mono/issues/1043) by [@jasonish](https://github.com/jasonish)) +- Added `get_commands` RPC method for headless clients to list available commands ([#995](https://github.com/badlogic/pi-mono/pull/995) by [@dnouri](https://github.com/dnouri)) + +### Changed + +- Improved `extractCursorPosition` performance in TUI: scans lines in reverse order, early-outs when cursor is above viewport ([#1004](https://github.com/badlogic/pi-mono/pull/1004) by [@can1357](https://github.com/can1357)) +- Autocomplete improvements: better handling of partial matches and edge cases ([#1024](https://github.com/badlogic/pi-mono/pull/1024) by [@Perlence](https://github.com/Perlence)) + +### Fixed + +- External edits to `settings.json` are now preserved when pi reloads or saves unrelated settings. Previously, editing settings.json directly (e.g., removing a package from `packages` array) would be silently reverted on next pi startup when automatic setters like `setLastChangelogVersion()` triggered a save. +- Fixed custom header not displaying correctly with `quietStartup` enabled ([#1039](https://github.com/badlogic/pi-mono/pull/1039) by [@tudoroancea](https://github.com/tudoroancea)) +- Empty array in package filter now disables all resources instead of falling back to manifest defaults ([#1044](https://github.com/badlogic/pi-mono/issues/1044)) +- Auto-retry counter now resets after each successful LLM response instead of accumulating across tool-use turns ([#1019](https://github.com/badlogic/pi-mono/issues/1019)) +- Fixed incorrect `.md` file names in warning messages ([#1041](https://github.com/badlogic/pi-mono/issues/1041) by [@llimllib](https://github.com/llimllib)) +- Fixed provider name hidden in footer when terminal is narrow ([#981](https://github.com/badlogic/pi-mono/pull/981) by [@Perlence](https://github.com/Perlence)) +- Fixed backslash input buffering causing delayed character display in editor ([#1037](https://github.com/badlogic/pi-mono/pull/1037) by [@Perlence](https://github.com/Perlence)) +- Fixed markdown table rendering with proper row dividers and minimum column width ([#997](https://github.com/badlogic/pi-mono/pull/997) by [@tmustier](https://github.com/tmustier)) +- Fixed OpenAI completions `toolChoice` handling ([#998](https://github.com/badlogic/pi-mono/pull/998) by [@williamtwomey](https://github.com/williamtwomey)) +- Fixed cross-provider handoff failing when switching from OpenAI Responses API providers due to pipe-separated tool call IDs ([#1022](https://github.com/badlogic/pi-mono/issues/1022)) +- Fixed 429 rate limit errors incorrectly triggering auto-compaction instead of retry with backoff ([#1038](https://github.com/badlogic/pi-mono/issues/1038)) +- Fixed Anthropic provider to handle `sensitive` stop_reason returned by API ([#978](https://github.com/badlogic/pi-mono/issues/978)) +- Fixed DeepSeek API compatibility by detecting `deepseek.com` URLs and disabling unsupported `developer` role ([#1048](https://github.com/badlogic/pi-mono/issues/1048)) +- Fixed Anthropic provider to preserve input token counts when proxies omit them in `message_delta` events ([#1045](https://github.com/badlogic/pi-mono/issues/1045)) +- Fixed `autocompleteMaxVisible` setting not persisting to `settings.json` + +## [0.50.1] - 2026-01-26 + +### Fixed + +- Git extension updates now handle force-pushed remotes gracefully instead of failing ([#961](https://github.com/badlogic/pi-mono/pull/961) by [@aliou](https://github.com/aliou)) +- Extension `ctx.newSession({ setup })` now properly syncs agent state and renders messages after setup callback runs ([#968](https://github.com/badlogic/pi-mono/issues/968)) +- Fixed extension UI bindings not initializing when starting with no extensions, which broke UI methods after `/reload` +- Fixed `/hotkeys` output to title-case extension hotkeys ([#969](https://github.com/badlogic/pi-mono/pull/969) by [@Perlence](https://github.com/Perlence)) +- Fixed model catalog generation to exclude deprecated OpenCode Zen models ([#970](https://github.com/badlogic/pi-mono/pull/970) by [@DanielTatarkin](https://github.com/DanielTatarkin)) +- Fixed git extension removal to prune empty directories + +## [0.50.0] - 2026-01-26 + +### New Features + +- Pi packages for bundling and installing extensions, skills, prompts, and themes. See [docs/packages.md](docs/packages.md). +- Hot reload (`/reload`) of resources including AGENTS.md, SYSTEM.md, APPEND_SYSTEM.md, prompt templates, skills, themes, and extensions. See [README.md#commands](README.md#commands) and [README.md#context-files](README.md#context-files). +- Custom providers via `pi.registerProvider()` for proxies, custom endpoints, OAuth or SSO flows, and non-standard streaming APIs. See [docs/custom-provider.md](docs/custom-provider.md). +- Azure OpenAI Responses provider support with deployment-aware model mapping. See [docs/providers.md#azure-openai](docs/providers.md#azure-openai). +- OpenRouter routing support for custom models via `openRouterRouting`. See [docs/providers.md#api-keys](docs/providers.md#api-keys) and [docs/models.md](docs/models.md). +- Skill invocation messages are now collapsible and skills can opt out of model invocation via `disable-model-invocation`. See [docs/skills.md#frontmatter](docs/skills.md#frontmatter). +- Session selector renaming and configurable keybindings. See [README.md#commands](README.md#commands) and [docs/keybindings.md](docs/keybindings.md). +- `models.json` headers can resolve environment variables and shell commands. See [docs/models.md#value-resolution](docs/models.md#value-resolution). +- `--verbose` CLI flag to override quiet startup. See [README.md#cli-reference](README.md#cli-reference). + +Read the fully revamped docs in `README.md`, or have your clanker read them for you. + +### SDK Migration Guide + +There are multiple SDK breaking changes since v0.49.3. For the quickest migration, point your agent at `packages/coding-agent/docs/sdk.md`, the SDK examples in `packages/coding-agent/examples/sdk`, and the SDK source in `packages/coding-agent/src/core/sdk.ts` and related modules. + +### Breaking Changes + +- Header values in `models.json` now resolve environment variables (if a header value matches an env var name, the env var value is used). This may change behavior if a literal header value accidentally matches an env var name. ([#909](https://github.com/badlogic/pi-mono/issues/909)) +- External packages (npm/git) are now configured via `packages` array in settings.json instead of `extensions`. Existing npm:/git: entries in `extensions` are auto-migrated. ([#645](https://github.com/badlogic/pi-mono/issues/645)) +- Resource loading now uses `ResourceLoader` only and settings.json uses arrays for extensions, skills, prompts, and themes ([#645](https://github.com/badlogic/pi-mono/issues/645)) +- Removed `discoverAuthStorage` and `discoverModels` from the SDK. `AuthStorage` and `ModelRegistry` now default to `~/.pi/agent` paths unless you pass an `agentDir` ([#645](https://github.com/badlogic/pi-mono/issues/645)) + +### Added + +- Session renaming in `/resume` picker via `Ctrl+R` without opening the session ([#863](https://github.com/badlogic/pi-mono/pull/863) by [@svkozak](https://github.com/svkozak)) +- Session selector keybindings are now configurable ([#948](https://github.com/badlogic/pi-mono/pull/948) by [@aos](https://github.com/aos)) +- `disable-model-invocation` frontmatter field for skills to prevent agentic invocation while still allowing explicit `/skill:name` commands ([#927](https://github.com/badlogic/pi-mono/issues/927)) +- Exposed `copyToClipboard` utility for extensions ([#926](https://github.com/badlogic/pi-mono/issues/926) by [@mitsuhiko](https://github.com/mitsuhiko)) +- Skill invocation messages are now collapsible in chat output, showing collapsed by default with skill name and expand hint ([#894](https://github.com/badlogic/pi-mono/issues/894)) +- Header values in `models.json` now support environment variables and shell commands, matching `apiKey` resolution ([#909](https://github.com/badlogic/pi-mono/issues/909)) +- Added HTTP proxy environment variable support for API requests ([#942](https://github.com/badlogic/pi-mono/pull/942) by [@haoqixu](https://github.com/haoqixu)) +- Added OpenRouter provider routing support for custom models via `openRouterRouting` compat field ([#859](https://github.com/badlogic/pi-mono/pull/859) by [@v01dpr1mr0s3](https://github.com/v01dpr1mr0s3)) +- Added `azure-openai-responses` provider support for Azure OpenAI Responses API. ([#890](https://github.com/badlogic/pi-mono/pull/890) by [@markusylisiurunen](https://github.com/markusylisiurunen)) +- Added changelog link to update notifications ([#925](https://github.com/badlogic/pi-mono/pull/925) by [@dannote](https://github.com/dannote)) +- Added `--verbose` CLI flag to override quietStartup setting ([#906](https://github.com/badlogic/pi-mono/pull/906) by [@Perlence](https://github.com/Perlence)) +- `markdown.codeBlockIndent` setting to customize code block indentation in rendered output +- Extension package management with `pi install`, `pi remove`, `pi update`, and `pi list` commands ([#645](https://github.com/badlogic/pi-mono/issues/645)) +- Package filtering: selectively load resources from packages using object form in `packages` array ([#645](https://github.com/badlogic/pi-mono/issues/645)) +- Glob pattern support with minimatch in package filters, top-level settings arrays, and pi manifest (e.g., `"!funky.json"`, `"*.ts"`) ([#645](https://github.com/badlogic/pi-mono/issues/645)) +- `/reload` command to reload extensions, skills, prompts, and themes ([#645](https://github.com/badlogic/pi-mono/issues/645)) +- `pi config` command with TUI to enable/disable package and top-level resources via patterns ([#938](https://github.com/badlogic/pi-mono/issues/938)) +- CLI flags for `--skill`, `--prompt-template`, `--theme`, `--no-prompt-templates`, and `--no-themes` ([#645](https://github.com/badlogic/pi-mono/issues/645)) +- Package deduplication: if same package appears in global and project settings, project wins ([#645](https://github.com/badlogic/pi-mono/issues/645)) +- Unified collision reporting with `ResourceDiagnostic` type for all resource types ([#645](https://github.com/badlogic/pi-mono/issues/645)) +- Show provider alongside the model in the footer if multiple providers are available +- Custom provider support via `pi.registerProvider()` with `streamSimple` for custom API implementations +- Added `custom-provider.ts` example extension demonstrating custom Anthropic provider with OAuth + +### Changed + +- `/resume` picker sort toggle moved to `Ctrl+S` to free `Ctrl+R` for rename ([#863](https://github.com/badlogic/pi-mono/pull/863) by [@svkozak](https://github.com/svkozak)) +- HTML export: clicking a sidebar message now navigates to its newest leaf and scrolls to it, instead of truncating the branch ([#853](https://github.com/badlogic/pi-mono/pull/853) by [@mitsuhiko](https://github.com/mitsuhiko)) +- HTML export: active path is now visually highlighted with dimmed off-path nodes ([#929](https://github.com/badlogic/pi-mono/pull/929) by [@hewliyang](https://github.com/hewliyang)) +- Azure OpenAI Responses provider now uses base URL configuration with deployment-aware model mapping and no longer includes service tier handling +- `/reload` now re-renders the entire scrollback so updated extension components are visible immediately ([#928](https://github.com/badlogic/pi-mono/pull/928) by [@ferologics](https://github.com/ferologics)) +- Skill, prompt template, and theme discovery now use settings and CLI path arrays instead of legacy filters ([#645](https://github.com/badlogic/pi-mono/issues/645)) + +### Fixed + +- Extension `setWorkingMessage()` calls in `agent_start` handlers now work correctly; previously the message was silently ignored because the loading animation didn't exist yet ([#935](https://github.com/badlogic/pi-mono/issues/935)) +- Fixed package auto-discovery to respect loader rules, config overrides, and force-exclude patterns +- Fixed /reload restoring the correct editor after reload ([#949](https://github.com/badlogic/pi-mono/pull/949) by [@Perlence](https://github.com/Perlence)) +- Fixed distributed themes breaking `/export` ([#946](https://github.com/badlogic/pi-mono/pull/946) by [@mitsuhiko](https://github.com/mitsuhiko)) +- Fixed startup hints to clarify thinking level selection and expanded thinking guidance +- Fixed SDK initial model resolution to use `findInitialModel` and default to Claude Opus 4.5 for Anthropic models +- Fixed no-models warning to include the `/model` instruction +- Fixed authentication error messages to point to the authentication documentation +- Fixed bash output hint lines to truncate to terminal width +- Fixed custom editors to honor the `paddingX` setting ([#936](https://github.com/badlogic/pi-mono/pull/936) by [@Perlence](https://github.com/Perlence)) +- Fixed system prompt tool list to show only built-in tools +- Fixed package manager to check npm package versions before using cached copies +- Fixed package manager to run `npm install` after cloning git repositories with a package.json +- Fixed extension provider registrations to apply before model resolution +- Fixed editor multi-line insertion handling and lastAction tracking ([#945](https://github.com/badlogic/pi-mono/pull/945) by [@Perlence](https://github.com/Perlence)) +- Fixed editor word wrapping to reserve a cursor column ([#934](https://github.com/badlogic/pi-mono/pull/934) by [@Perlence](https://github.com/Perlence)) +- Fixed editor word wrapping to use single-pass backtracking for whitespace handling ([#924](https://github.com/badlogic/pi-mono/pull/924) by [@Perlence](https://github.com/Perlence)) +- Fixed Kitty image ID allocation and cleanup to prevent image ID collisions +- Fixed overlays staying centered after terminal resizes ([#950](https://github.com/badlogic/pi-mono/pull/950) by [@nicobailon](https://github.com/nicobailon)) +- Fixed streaming dispatch to use the model api type instead of hardcoded API defaults +- Fixed Google providers to default tool call arguments to an empty object when omitted +- Fixed OpenAI Responses streaming to handle `arguments.done` events on OpenAI-compatible endpoints ([#917](https://github.com/badlogic/pi-mono/pull/917) by [@williballenthin](https://github.com/williballenthin)) +- Fixed OpenAI Codex Responses tool strictness handling after the shared responses refactor +- Fixed Azure OpenAI Responses streaming to guard deltas before content parts and correct metadata and handoff gating +- Fixed OpenAI completions tool-result image batching after consecutive tool results ([#902](https://github.com/badlogic/pi-mono/pull/902) by [@terrorobe](https://github.com/terrorobe)) +- Off-by-one error in bash output "earlier lines" count caused by counting spacing newline as hidden content ([#921](https://github.com/badlogic/pi-mono/issues/921)) +- User package filters now layer on top of manifest filters instead of replacing them ([#645](https://github.com/badlogic/pi-mono/issues/645)) +- Auto-retry now handles "terminated" errors from Codex API mid-stream failures +- Follow-up queue (Alt+Enter) now sends full paste content instead of `[paste #N ...]` markers ([#912](https://github.com/badlogic/pi-mono/issues/912)) +- Fixed Alt-Up not restoring messages queued during compaction ([#923](https://github.com/badlogic/pi-mono/pull/923) by [@aliou](https://github.com/aliou)) +- Fixed session corruption when loading empty or invalid session files via `--session` flag ([#932](https://github.com/badlogic/pi-mono/issues/932) by [@armanddp](https://github.com/armanddp)) +- Fixed extension shortcuts not firing when extension also uses `setEditorComponent()` ([#947](https://github.com/badlogic/pi-mono/pull/947) by [@Perlence](https://github.com/Perlence)) +- Session "modified" time now uses last message timestamp instead of file mtime, so renaming doesn't reorder the recent list ([#863](https://github.com/badlogic/pi-mono/pull/863) by [@svkozak](https://github.com/svkozak)) + +## [0.49.3] - 2026-01-22 + +### Added + +- `markdown.codeBlockIndent` setting to customize code block indentation in rendered output ([#855](https://github.com/badlogic/pi-mono/pull/855) by [@terrorobe](https://github.com/terrorobe)) +- Added `inline-bash.ts` example extension for expanding `!{command}` patterns in prompts ([#881](https://github.com/badlogic/pi-mono/pull/881) by [@scutifer](https://github.com/scutifer)) +- Added `antigravity-image-gen.ts` example extension for AI image generation via Google Antigravity ([#893](https://github.com/badlogic/pi-mono/pull/893) by [@ben-vargas](https://github.com/ben-vargas)) +- Added `PI_SHARE_VIEWER_URL` environment variable for custom share viewer URLs ([#889](https://github.com/badlogic/pi-mono/pull/889) by [@andresaraujo](https://github.com/andresaraujo)) +- Added Alt+Delete as hotkey for delete word forwards ([#878](https://github.com/badlogic/pi-mono/pull/878) by [@Perlence](https://github.com/Perlence)) + +### Changed + +- Tree selector: changed label filter shortcut from `l` to `Shift+L` so users can search for entries containing "l" ([#861](https://github.com/badlogic/pi-mono/pull/861) by [@mitsuhiko](https://github.com/mitsuhiko)) +- Fuzzy matching now scores consecutive matches higher for better search relevance ([#860](https://github.com/badlogic/pi-mono/pull/860) by [@mitsuhiko](https://github.com/mitsuhiko)) + +### Fixed + +- Fixed error messages showing hardcoded `~/.pi/agent/` paths instead of respecting `PI_CODING_AGENT_DIR` ([#887](https://github.com/badlogic/pi-mono/pull/887) by [@aliou](https://github.com/aliou)) +- Fixed `write` tool not displaying errors in the UI when execution fails ([#856](https://github.com/badlogic/pi-mono/issues/856)) +- Fixed HTML export using default theme instead of user's active theme ([#870](https://github.com/badlogic/pi-mono/pull/870) by [@scutifer](https://github.com/scutifer)) +- Show session name in the footer and terminal / tab title ([#876](https://github.com/badlogic/pi-mono/pull/876) by [@scutifer](https://github.com/scutifer)) +- Fixed 256color fallback in Terminal.app to prevent color rendering issues ([#869](https://github.com/badlogic/pi-mono/pull/869) by [@Perlence](https://github.com/Perlence)) +- Fixed viewport tracking and cursor positioning for overlays and content shrink scenarios +- Fixed autocomplete to allow searches with `/` characters (e.g., `folder1/folder2`) ([#882](https://github.com/badlogic/pi-mono/pull/882) by [@richardgill](https://github.com/richardgill)) +- Fixed autolinked emails displaying redundant `(mailto:...)` suffix ([#888](https://github.com/badlogic/pi-mono/pull/888) by [@terrorobe](https://github.com/terrorobe)) +- Fixed `@` file autocomplete adding space after directories, breaking continued autocomplete into subdirectories + +## [0.49.2] - 2026-01-19 + +### Added + +- Added widget placement option for extension widgets via `widgetPlacement` in `pi.addWidget()` ([#850](https://github.com/badlogic/pi-mono/pull/850) by [@marckrenn](https://github.com/marckrenn)) +- Added AWS credential detection for ECS/Kubernetes environments: `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`, `AWS_CONTAINER_CREDENTIALS_FULL_URI`, `AWS_WEB_IDENTITY_TOKEN_FILE` ([#848](https://github.com/badlogic/pi-mono/issues/848)) +- Add "quiet startup" setting to `/settings` ([#847](https://github.com/badlogic/pi-mono/pull/847) by [@unexge](https://github.com/unexge)) + +### Changed + +- HTML export now includes JSONL download button, jump-to-last-message on click, and fixed missing labels ([#853](https://github.com/badlogic/pi-mono/pull/853) by [@mitsuhiko](https://github.com/mitsuhiko)) +- Improved error message for OAuth authentication failures (expired credentials, offline) instead of generic 'No API key found' ([#849](https://github.com/badlogic/pi-mono/pull/849) by [@zedrdave](https://github.com/zedrdave)) + +### Fixed +- Fixed `/model` selector scope toggle so you can switch between all and scoped models when scoped models are saved ([#844](https://github.com/badlogic/pi-mono/issues/844)) +- Fixed OpenAI Responses 400 error "reasoning without following item" when replaying aborted turns ([#838](https://github.com/badlogic/pi-mono/pull/838)) +- Fixed pi exiting with code 0 when cancelling resume session selection + +### Removed + +- Removed `strictResponsesPairing` compat option from models.json schema (no longer needed) + +## [0.49.1] - 2026-01-18 + +### Added + +- Added `strictResponsesPairing` compat option for custom OpenAI Responses models on Azure ([#768](https://github.com/badlogic/pi-mono/pull/768) by [@prateekmedia](https://github.com/prateekmedia)) +- Session selector (`/resume`) now supports path display toggle (`Ctrl+P`) and session deletion (`Ctrl+D`) with inline confirmation ([#816](https://github.com/badlogic/pi-mono/pull/816) by [@w-winter](https://github.com/w-winter)) +- Added undo support in interactive mode with Ctrl+- hotkey. ([#831](https://github.com/badlogic/pi-mono/pull/831) by [@Perlence](https://github.com/Perlence)) + +### Changed + +- Share URLs now use hash fragments (`#`) instead of query strings (`?`) to prevent session IDs from being sent to buildwithpi.ai ([#829](https://github.com/badlogic/pi-mono/pull/829) by [@terrorobe](https://github.com/terrorobe)) +- API keys in `models.json` can now be retrieved via shell command using `!` prefix (e.g., `"apiKey": "!security find-generic-password -ws 'anthropic'"` for macOS Keychain) ([#762](https://github.com/badlogic/pi-mono/pull/762) by [@cv](https://github.com/cv)) + +### Fixed + +- Fixed IME candidate window appearing in wrong position when filtering menus with Input Method Editor (e.g., Chinese IME). Components with search inputs now properly propagate focus state for cursor positioning. ([#827](https://github.com/badlogic/pi-mono/issues/827)) +- Fixed extension shortcut conflicts to respect user keybindings when built-in actions are remapped. ([#826](https://github.com/badlogic/pi-mono/pull/826) by [@richardgill](https://github.com/richardgill)) +- Fixed photon WASM loading in standalone compiled binaries. +- Fixed tool call ID normalization for cross-provider handoffs (e.g., Codex to Antigravity Claude) ([#821](https://github.com/badlogic/pi-mono/issues/821)) + +## [0.49.0] - 2026-01-17 + +### Added + +- `pi.setLabel(entryId, label)` in ExtensionAPI for setting per-entry labels from extensions ([#806](https://github.com/badlogic/pi-mono/issues/806)) +- Export `keyHint`, `appKeyHint`, `editorKey`, `appKey`, `rawKeyHint` for extensions to format keybinding hints consistently ([#802](https://github.com/badlogic/pi-mono/pull/802) by [@dannote](https://github.com/dannote)) +- Exported `VERSION` from the package index and updated the custom-header example. ([#798](https://github.com/badlogic/pi-mono/pull/798) by [@tallshort](https://github.com/tallshort)) +- Added `showHardwareCursor` setting to control cursor visibility while still positioning it for IME support. ([#800](https://github.com/badlogic/pi-mono/pull/800) by [@ghoulr](https://github.com/ghoulr)) +- Added Emacs-style kill ring editing with yank and yank-pop keybindings, plus legacy Alt+letter handling and Alt+D delete word forward support in the interactive editor. ([#810](https://github.com/badlogic/pi-mono/pull/810) by [@Perlence](https://github.com/Perlence)) +- Added `ctx.compact()` and `ctx.getContextUsage()` to extension contexts for programmatic compaction and context usage checks. +- Added documentation for delete word forward and kill ring keybindings in interactive mode. ([#810](https://github.com/badlogic/pi-mono/pull/810) by [@Perlence](https://github.com/Perlence)) + +### Changed + +- Updated the default system prompt wording to clarify the pi harness and documentation scope. +- Simplified Codex system prompt handling to use the default system prompt directly for Codex instructions. + +### Fixed + +- Fixed photon module failing to load in ESM context with "require is not defined" error ([#795](https://github.com/badlogic/pi-mono/pull/795) by [@dannote](https://github.com/dannote)) +- Fixed compaction UI not showing when extensions trigger compaction. +- Fixed orphaned tool results after errored assistant messages causing Codex API errors. When an assistant message has `stopReason: "error"`, its tool calls are now excluded from pending tool tracking, preventing synthetic tool results from being generated for calls that will be dropped by provider-specific converters. ([#812](https://github.com/badlogic/pi-mono/issues/812)) +- Fixed Bedrock Claude max_tokens handling to always exceed thinking budget tokens, preventing compaction failures. ([#797](https://github.com/badlogic/pi-mono/pull/797) by [@pjtf93](https://github.com/pjtf93)) +- Fixed Claude Code tool name normalization to match the Claude Code tool list case-insensitively and remove invalid mappings. + +### Removed + +- Removed `pi-internal://` path resolution from the read tool. + +## [0.48.0] - 2026-01-16 + +### Added + +- Added `quietStartup` setting to silence startup output (version header, loaded context info, model scope line). Changelog notifications are still shown. ([#777](https://github.com/badlogic/pi-mono/pull/777) by [@ribelo](https://github.com/ribelo)) +- Added `editorPaddingX` setting for horizontal padding in input editor (0-3, default: 0) +- Added `shellCommandPrefix` setting to prepend commands to every bash execution, enabling alias expansion in non-interactive shells (e.g., `"shellCommandPrefix": "shopt -s expand_aliases"`) ([#790](https://github.com/badlogic/pi-mono/pull/790) by [@richardgill](https://github.com/richardgill)) +- Added bash-style argument slicing for prompt templates ([#770](https://github.com/badlogic/pi-mono/pull/770) by [@airtonix](https://github.com/airtonix)) +- Extension commands can provide argument auto-completions via `getArgumentCompletions` in `pi.registerCommand()` ([#775](https://github.com/badlogic/pi-mono/pull/775) by [@ribelo](https://github.com/ribelo)) +- Bash tool now displays the timeout value in the UI when a timeout is set ([#780](https://github.com/badlogic/pi-mono/pull/780) by [@dannote](https://github.com/dannote)) +- Export `getShellConfig` for extensions to detect user's shell environment ([#766](https://github.com/badlogic/pi-mono/pull/766) by [@dannote](https://github.com/dannote)) +- Added `thinkingText` and `selectedBg` to theme schema ([#763](https://github.com/badlogic/pi-mono/pull/763) by [@scutifer](https://github.com/scutifer)) +- `navigateTree()` now supports `replaceInstructions` option to replace the default summarization prompt entirely, and `label` option to attach a label to the branch summary entry ([#787](https://github.com/badlogic/pi-mono/pull/787) by [@mitsuhiko](https://github.com/mitsuhiko)) + +### Fixed + +- Fixed crash during auto-compaction when summarization fails (e.g., quota exceeded). Now displays error message instead of crashing ([#792](https://github.com/badlogic/pi-mono/issues/792)) +- Fixed `--session ` to search globally across projects if not found locally, with option to fork sessions from other projects ([#785](https://github.com/badlogic/pi-mono/pull/785) by [@ribelo](https://github.com/ribelo)) +- Fixed standalone binary WASM loading on Linux ([#784](https://github.com/badlogic/pi-mono/issues/784)) +- Fixed string numbers in tool arguments not being coerced to numbers during validation ([#786](https://github.com/badlogic/pi-mono/pull/786) by [@dannote](https://github.com/dannote)) +- Fixed `--no-extensions` flag not preventing extension discovery ([#776](https://github.com/badlogic/pi-mono/issues/776)) +- Fixed extension messages rendering twice on startup when `pi.sendMessage({ display: true })` is called during `session_start` ([#765](https://github.com/badlogic/pi-mono/pull/765) by [@dannote](https://github.com/dannote)) +- Fixed `PI_CODING_AGENT_DIR` env var not expanding tilde (`~`) to home directory ([#778](https://github.com/badlogic/pi-mono/pull/778) by [@aliou](https://github.com/aliou)) +- Fixed session picker hint text overflow ([#764](https://github.com/badlogic/pi-mono/issues/764)) +- Fixed Kitty keyboard protocol shifted symbol keys (e.g., `@`, `?`) not working in editor ([#779](https://github.com/badlogic/pi-mono/pull/779) by [@iamd3vil](https://github.com/iamd3vil)) +- Fixed Bedrock tool call IDs causing API errors from invalid characters ([#781](https://github.com/badlogic/pi-mono/pull/781) by [@pjtf93](https://github.com/pjtf93)) + +### Changed + +- Hardware cursor is now disabled by default for better terminal compatibility. Set `PI_HARDWARE_CURSOR=1` to enable (replaces `PI_NO_HARDWARE_CURSOR=1` which disabled it). + +## [0.47.0] - 2026-01-16 + +### Breaking Changes + +- Extensions using `Editor` directly must now pass `TUI` as the first constructor argument: `new Editor(tui, theme)`. The `tui` parameter is available in extension factory functions. ([#732](https://github.com/badlogic/pi-mono/issues/732)) + +### Added + +- **OpenAI Codex official support**: Full compatibility with OpenAI's Codex CLI models (`gpt-5.1`, `gpt-5.2`, `gpt-5.1-codex-mini`, `gpt-5.2-codex`). Features include static system prompt for OpenAI allowlisting, prompt caching via session ID, and reasoning signature retention across turns. Set `OPENAI_API_KEY` and use `--provider openai-codex` or select a Codex model. ([#737](https://github.com/badlogic/pi-mono/pull/737)) +- `pi-internal://` URL scheme in read tool for accessing internal documentation. The model can read files from the coding-agent package (README, docs, examples) to learn about extending pi. +- New `input` event in extension system for intercepting, transforming, or handling user input before the agent processes it. Supports three result types: `continue` (pass through), `transform` (modify text/images), `handled` (respond without LLM). Handlers chain transforms and short-circuit on handled. ([#761](https://github.com/badlogic/pi-mono/pull/761) by [@nicobailon](https://github.com/nicobailon)) +- Extension example: `input-transform.ts` demonstrating input interception patterns (quick mode, instant commands, source routing) ([#761](https://github.com/badlogic/pi-mono/pull/761) by [@nicobailon](https://github.com/nicobailon)) +- Custom tool HTML export: extensions with `renderCall`/`renderResult` now render in `/share` and `/export` output with ANSI-to-HTML color conversion ([#702](https://github.com/badlogic/pi-mono/pull/702) by [@aliou](https://github.com/aliou)) +- Direct filter shortcuts in Tree mode: Ctrl+D (default), Ctrl+T (no-tools), Ctrl+U (user-only), Ctrl+L (labeled-only), Ctrl+A (all) ([#747](https://github.com/badlogic/pi-mono/pull/747) by [@kaofelix](https://github.com/kaofelix)) + +### Changed + +- Skill commands (`/skill:name`) are now expanded in AgentSession instead of interactive mode. This enables skill commands in RPC and print modes, and allows the `input` event to intercept `/skill:name` before expansion. + +### Fixed + +- Editor no longer corrupts terminal display when loading large prompts via `setEditorText`. Content now scrolls vertically with indicators showing lines above/below the viewport. ([#732](https://github.com/badlogic/pi-mono/issues/732)) +- Piped stdin now works correctly: `echo foo | pi` is equivalent to `pi -p foo`. When stdin is piped, print mode is automatically enabled since interactive mode requires a TTY ([#708](https://github.com/badlogic/pi-mono/issues/708)) +- Session tree now preserves branch connectors and indentation when filters hide intermediate entries so descendants attach to the nearest visible ancestor and sibling branches align. Fixed in both TUI and HTML export ([#739](https://github.com/badlogic/pi-mono/pull/739) by [@w-winter](https://github.com/w-winter)) +- Added `upstream connect`, `connection refused`, and `reset before headers` patterns to auto-retry error detection ([#733](https://github.com/badlogic/pi-mono/issues/733)) +- Multi-line YAML frontmatter in skills and prompt templates now parses correctly. Centralized frontmatter parsing using the `yaml` library. ([#728](https://github.com/badlogic/pi-mono/pull/728) by [@richardgill](https://github.com/richardgill)) +- `ctx.shutdown()` now waits for pending UI renders to complete before exiting, ensuring notifications and final output are visible ([#756](https://github.com/badlogic/pi-mono/issues/756)) +- OpenAI Codex provider now retries on transient errors (429, 5xx, connection failures) with exponential backoff ([#733](https://github.com/badlogic/pi-mono/issues/733)) + +## [0.46.0] - 2026-01-15 + +### Fixed + +- Scoped models (`--models` or `enabledModels`) now remember the last selected model across sessions instead of always starting with the first model in the scope ([#736](https://github.com/badlogic/pi-mono/pull/736) by [@ogulcancelik](https://github.com/ogulcancelik)) +- Show `bun install` instead of `npm install` in update notification when running under Bun ([#714](https://github.com/badlogic/pi-mono/pull/714) by [@dannote](https://github.com/dannote)) +- `/skill` prompts now include the skill path ([#711](https://github.com/badlogic/pi-mono/pull/711) by [@jblwilliams](https://github.com/jblwilliams)) +- Use configurable `expandTools` keybinding instead of hardcoded Ctrl+O ([#717](https://github.com/badlogic/pi-mono/pull/717) by [@dannote](https://github.com/dannote)) +- Compaction turn prefix summaries now merge correctly ([#738](https://github.com/badlogic/pi-mono/pull/738) by [@vsabavat](https://github.com/vsabavat)) +- Avoid unsigned Gemini 3 tool calls ([#741](https://github.com/badlogic/pi-mono/pull/741) by [@roshanasingh4](https://github.com/roshanasingh4)) +- Fixed signature support for non-Anthropic models in Amazon Bedrock provider ([#727](https://github.com/badlogic/pi-mono/pull/727) by [@unexge](https://github.com/unexge)) +- Keyboard shortcuts (Ctrl+C, Ctrl+D, etc.) now work on non-Latin keyboard layouts (Russian, Ukrainian, Bulgarian, etc.) in terminals supporting Kitty keyboard protocol with alternate key reporting ([#718](https://github.com/badlogic/pi-mono/pull/718) by [@dannote](https://github.com/dannote)) + +### Added + +- Edit tool now uses fuzzy matching as fallback when exact match fails, tolerating trailing whitespace, smart quotes, Unicode dashes, and special spaces ([#713](https://github.com/badlogic/pi-mono/pull/713) by [@dannote](https://github.com/dannote)) +- Support `APPEND_SYSTEM.md` to append instructions to the system prompt ([#716](https://github.com/badlogic/pi-mono/pull/716) by [@tallshort](https://github.com/tallshort)) +- Session picker search: Ctrl+R toggles sorting between fuzzy match (default) and most recent; supports quoted phrase matching and `re:` regex mode ([#731](https://github.com/badlogic/pi-mono/pull/731) by [@ogulcancelik](https://github.com/ogulcancelik)) +- Export `getAgentDir` for extensions ([#749](https://github.com/badlogic/pi-mono/pull/749) by [@dannote](https://github.com/dannote)) +- Show loaded prompt templates on startup ([#743](https://github.com/badlogic/pi-mono/pull/743) by [@tallshort](https://github.com/tallshort)) +- MiniMax China (`minimax-cn`) provider support ([#725](https://github.com/badlogic/pi-mono/pull/725) by [@tallshort](https://github.com/tallshort)) +- `gpt-5.2-codex` models for GitHub Copilot and OpenCode Zen providers ([#734](https://github.com/badlogic/pi-mono/pull/734) by [@aadishv](https://github.com/aadishv)) + +### Changed + +- Replaced `wasm-vips` with `@silvia-odwyer/photon-node` for image processing ([#710](https://github.com/badlogic/pi-mono/pull/710) by [@can1357](https://github.com/can1357)) +- Extension example: `plan-mode/` shortcut changed from Shift+P to Ctrl+Alt+P to avoid conflict with typing capital P ([#746](https://github.com/badlogic/pi-mono/pull/746) by [@ferologics](https://github.com/ferologics)) +- UI keybinding hints now respect configured keybindings across components ([#724](https://github.com/badlogic/pi-mono/pull/724) by [@dannote](https://github.com/dannote)) +- CLI process title is now set to `pi` for easier process identification ([#742](https://github.com/badlogic/pi-mono/pull/742) by [@richardgill](https://github.com/richardgill)) + +## [0.45.7] - 2026-01-13 + +### Added + +- Exported `highlightCode` and `getLanguageFromPath` for extensions ([#703](https://github.com/badlogic/pi-mono/pull/703) by [@dannote](https://github.com/dannote)) + +## [0.45.6] - 2026-01-13 + +### Added + +- `ctx.ui.custom()` now accepts `overlayOptions` for overlay positioning and sizing (anchor, margins, offsets, percentages, absolute positioning) ([#667](https://github.com/badlogic/pi-mono/pull/667) by [@nicobailon](https://github.com/nicobailon)) +- `ctx.ui.custom()` now accepts `onHandle` callback to receive the `OverlayHandle` for controlling overlay visibility ([#667](https://github.com/badlogic/pi-mono/pull/667) by [@nicobailon](https://github.com/nicobailon)) +- Extension example: `overlay-qa-tests.ts` with 10 commands for testing overlay positioning, animation, and toggle scenarios ([#667](https://github.com/badlogic/pi-mono/pull/667) by [@nicobailon](https://github.com/nicobailon)) +- Extension example: `doom-overlay/` - DOOM game running as an overlay at 35 FPS (auto-downloads WAD on first run) ([#667](https://github.com/badlogic/pi-mono/pull/667) by [@nicobailon](https://github.com/nicobailon)) + +## [0.45.5] - 2026-01-13 + +### Fixed + +- Skip changelog display on fresh install (only show on upgrades) + +## [0.45.4] - 2026-01-13 + +### Changed + +- Light theme colors adjusted for WCAG AA compliance (4.5:1 contrast ratio against white backgrounds) +- Replaced `sharp` with `wasm-vips` for image processing (resize, PNG conversion). Eliminates native build requirements that caused installation failures on some systems. ([#696](https://github.com/badlogic/pi-mono/issues/696)) + +### Added + +- Extension example: `summarize.ts` for summarizing conversations using custom UI and an external model ([#684](https://github.com/badlogic/pi-mono/pull/684) by [@scutifer](https://github.com/scutifer)) +- Extension example: `question.ts` enhanced with custom UI for asking user questions ([#693](https://github.com/badlogic/pi-mono/pull/693) by [@ferologics](https://github.com/ferologics)) +- Extension example: `plan-mode/` enhanced with explicit step tracking and progress widget ([#694](https://github.com/badlogic/pi-mono/pull/694) by [@ferologics](https://github.com/ferologics)) +- Extension example: `questionnaire.ts` for multi-question input with tab bar navigation ([#695](https://github.com/badlogic/pi-mono/pull/695) by [@ferologics](https://github.com/ferologics)) +- Experimental Vercel AI Gateway provider support: set `AI_GATEWAY_API_KEY` and use `--provider vercel-ai-gateway`. Token usage is currently reported incorrectly by Anthropic Messages compatible endpoint. ([#689](https://github.com/badlogic/pi-mono/pull/689) by [@timolins](https://github.com/timolins)) + +### Fixed + +- Fix API key resolution after model switches by using provider argument ([#691](https://github.com/badlogic/pi-mono/pull/691) by [@joshp123](https://github.com/joshp123)) +- Fixed z.ai thinking/reasoning: thinking toggle now correctly enables/disables thinking for z.ai models ([#688](https://github.com/badlogic/pi-mono/issues/688)) +- Fixed extension loading in compiled Bun binary: extensions with local file imports now work correctly. Updated `@mariozechner/jiti` to v2.6.5 which bundles babel for Bun binary compatibility. ([#681](https://github.com/badlogic/pi-mono/issues/681)) +- Fixed theme loading when installed via mise: use wrapper directory in release tarballs for compatibility with mise's `strip_components=1` extraction. ([#681](https://github.com/badlogic/pi-mono/issues/681)) + +## [0.45.3] - 2026-01-13 + +## [0.45.2] - 2026-01-13 + +### Fixed + +- Extensions now load correctly in compiled Bun binary using `@mariozechner/jiti` fork with `virtualModules` support. Bundled packages (`@sinclair/typebox`, `@mariozechner/pi-tui`, `@mariozechner/pi-ai`, `@mariozechner/pi-coding-agent`) are accessible to extensions without filesystem node_modules. + +## [0.45.1] - 2026-01-13 + +### Changed + +- `/share` now outputs `buildwithpi.ai` session preview URLs instead of `pi.dev` + +## [0.45.0] - 2026-01-13 + +### Added + +- MiniMax provider support: set `MINIMAX_API_KEY` and use `minimax/MiniMax-M2.1` ([#656](https://github.com/badlogic/pi-mono/pull/656) by [@dannote](https://github.com/dannote)) +- `/scoped-models`: Alt+Up/Down to reorder enabled models. Order is preserved when saving with Ctrl+S and determines Ctrl+P cycling order. ([#676](https://github.com/badlogic/pi-mono/pull/676) by [@thomasmhr](https://github.com/thomasmhr)) +- Amazon Bedrock provider support (experimental, tested with Anthropic Claude models only) ([#494](https://github.com/badlogic/pi-mono/pull/494) by [@unexge](https://github.com/unexge)) +- Extension example: `sandbox/` for OS-level bash sandboxing using `@anthropic-ai/sandbox-runtime` with per-project config ([#673](https://github.com/badlogic/pi-mono/pull/673) by [@dannote](https://github.com/dannote)) +- Print mode JSON output now emits the session header as the first line. + +## [0.44.0] - 2026-01-12 + +### Breaking Changes + +- `pi.getAllTools()` now returns `ToolInfo[]` (with `name` and `description`) instead of `string[]`. Extensions that only need names can use `.map(t => t.name)`. ([#648](https://github.com/badlogic/pi-mono/pull/648) by [@carsonfarmer](https://github.com/carsonfarmer)) + +### Added + +- Session naming: `/name ` command sets a display name shown in the session selector instead of the first message. Useful for distinguishing forked sessions. Extensions can use `pi.setSessionName()` and `pi.getSessionName()`. ([#650](https://github.com/badlogic/pi-mono/pull/650) by [@scutifer](https://github.com/scutifer)) +- Extension example: `notify.ts` for desktop notifications via OSC 777 escape sequence ([#658](https://github.com/badlogic/pi-mono/pull/658) by [@ferologics](https://github.com/ferologics)) +- Inline hint for queued messages showing the `Alt+Up` restore shortcut ([#657](https://github.com/badlogic/pi-mono/pull/657) by [@tmustier](https://github.com/tmustier)) +- Page-up/down navigation in `/resume` session selector to jump by 5 items ([#662](https://github.com/badlogic/pi-mono/pull/662) by [@aliou](https://github.com/aliou)) +- Fuzzy search in `/settings` menu: type to filter settings by label ([#643](https://github.com/badlogic/pi-mono/pull/643) by [@ninlds](https://github.com/ninlds)) + +### Fixed + +- Session selector now stays open when current folder has no sessions, allowing Tab to switch to "all" scope ([#661](https://github.com/badlogic/pi-mono/pull/661) by [@aliou](https://github.com/aliou)) +- Extensions using theme utilities like `getSettingsListTheme()` now work in dev mode with tsx + +## [0.43.0] - 2026-01-11 + +### Breaking Changes + +- Extension editor (`ctx.ui.editor()`) now uses Enter to submit and Shift+Enter for newlines, matching the main editor. Previously used Ctrl+Enter to submit. Extensions with hardcoded "ctrl+enter" hints need updating. ([#642](https://github.com/badlogic/pi-mono/pull/642) by [@mitsuhiko](https://github.com/mitsuhiko)) +- Renamed `/branch` command to `/fork` ([#641](https://github.com/badlogic/pi-mono/issues/641)) + - RPC: `branch` → `fork`, `get_branch_messages` → `get_fork_messages` + - SDK: `branch()` → `fork()`, `getBranchMessages()` → `getForkMessages()` + - AgentSession: `branch()` → `fork()`, `getUserMessagesForBranching()` → `getUserMessagesForForking()` + - Extension events: `session_before_branch` → `session_before_fork`, `session_branch` → `session_fork` + - Settings: `doubleEscapeAction: "branch" | "tree"` → `"fork" | "tree"` +- `SessionManager.list()` and `SessionManager.listAll()` are now async, returning `Promise`. Callers must await them. ([#620](https://github.com/badlogic/pi-mono/pull/620) by [@tmustier](https://github.com/tmustier)) + +### Added +- `/resume` selector now toggles between current-folder and all sessions with Tab, showing the session cwd in the All view and loading progress. ([#620](https://github.com/badlogic/pi-mono/pull/620) by [@tmustier](https://github.com/tmustier)) +- `SessionManager.list()` and `SessionManager.listAll()` accept optional `onProgress` callback for progress updates +- `SessionInfo.cwd` field containing the session's working directory (empty string for old sessions) +- `SessionListProgress` type export for progress callbacks +- `/scoped-models` command to enable/disable models for Ctrl+P cycling. Changes are session-only by default; press Ctrl+S to persist to settings.json. ([#626](https://github.com/badlogic/pi-mono/pull/626) by [@CarlosGtrz](https://github.com/CarlosGtrz)) +- `model_select` extension hook fires when model changes via `/model`, model cycling, or session restore with `source` field and `previousModel` ([#628](https://github.com/badlogic/pi-mono/pull/628) by [@marckrenn](https://github.com/marckrenn)) +- `ctx.ui.setWorkingMessage()` extension API to customize the "Working..." message during streaming ([#625](https://github.com/badlogic/pi-mono/pull/625) by [@nicobailon](https://github.com/nicobailon)) +- Skill slash commands: loaded skills are registered as `/skill:name` commands for quick access. Toggle via `/settings` or `skills.enableSkillCommands` in settings.json. ([#630](https://github.com/badlogic/pi-mono/pull/630) by [@Dwsy](https://github.com/Dwsy)) +- Slash command autocomplete now uses fuzzy matching (type `/skbra` to match `/skill:brave-search`) +- `/tree` branch summarization now offers three options: "No summary", "Summarize", and "Summarize with custom prompt". Custom prompts are appended as additional focus to the default summarization instructions. ([#642](https://github.com/badlogic/pi-mono/pull/642) by [@mitsuhiko](https://github.com/mitsuhiko)) + +### Fixed + +- Missing spacer between assistant message and text editor ([#655](https://github.com/badlogic/pi-mono/issues/655)) +- Session picker respects custom keybindings when using `--resume` ([#633](https://github.com/badlogic/pi-mono/pull/633) by [@aos](https://github.com/aos)) +- Custom footer extensions now see model changes: `ctx.model` is now a getter that returns the current model instead of a snapshot from when the context was created ([#634](https://github.com/badlogic/pi-mono/pull/634) by [@ogulcancelik](https://github.com/ogulcancelik)) +- Footer git branch not updating after external branch switches. Git uses atomic writes (temp file + rename), which changes the inode and breaks `fs.watch` on the file. Now watches the directory instead. +- Extension loading errors are now displayed to the user instead of being silently ignored ([#639](https://github.com/badlogic/pi-mono/pull/639) by [@aliou](https://github.com/aliou)) + +## [0.42.5] - 2026-01-11 + +### Fixed + +- Reduced flicker by only re-rendering changed lines ([#617](https://github.com/badlogic/pi-mono/pull/617) by [@ogulcancelik](https://github.com/ogulcancelik)). No worries tho, there's still a little flicker in the VS Code Terminal. Praise the flicker. +- Cursor position tracking when content shrinks with unchanged remaining lines +- TUI renders with wrong dimensions after suspend/resume if terminal was resized while suspended ([#599](https://github.com/badlogic/pi-mono/issues/599)) +- Pasted content containing Kitty key release patterns (e.g., `:3F` in MAC addresses) was incorrectly filtered out ([#623](https://github.com/badlogic/pi-mono/pull/623) by [@ogulcancelik](https://github.com/ogulcancelik)) + +## [0.42.4] - 2026-01-10 + +### Fixed + +- Bash output expanded hint now says "(ctrl+o to collapse)" ([#610](https://github.com/badlogic/pi-mono/pull/610) by [@tallshort](https://github.com/tallshort)) +- Fixed UTF-8 text corruption in remote bash execution (SSH, containers) by using streaming TextDecoder ([#608](https://github.com/badlogic/pi-mono/issues/608)) + +## [0.42.3] - 2026-01-10 + +### Changed + +- OpenAI Codex: updated to use bundled system prompt from upstream + +## [0.42.2] - 2026-01-10 + +### Added + +- `/model ` now pre-filters the model selector or auto-selects on exact match. Use `provider/model` syntax to disambiguate (e.g., `/model openai/gpt-4`). ([#587](https://github.com/badlogic/pi-mono/pull/587) by [@zedrdave](https://github.com/zedrdave)) +- `FooterDataProvider` for custom footers: `ctx.ui.setFooter()` now receives a third `footerData` parameter providing `getGitBranch()`, `getExtensionStatuses()`, and `onBranchChange()` for reactive updates ([#600](https://github.com/badlogic/pi-mono/pull/600) by [@nicobailon](https://github.com/nicobailon)) +- `Alt+Up` hotkey to restore queued steering/follow-up messages back into the editor without aborting the current run ([#604](https://github.com/badlogic/pi-mono/pull/604) by [@tmustier](https://github.com/tmustier)) + +### Fixed + +- Fixed LM Studio compatibility for OpenAI Responses tool strict mapping in the ai provider ([#598](https://github.com/badlogic/pi-mono/pull/598) by [@gnattu](https://github.com/gnattu)) + +## [0.42.1] - 2026-01-09 + +### Fixed + +- Symlinked directories in `prompts/` folders are now followed when loading prompt templates ([#601](https://github.com/badlogic/pi-mono/pull/601) by [@aliou](https://github.com/aliou)) + +## [0.42.0] - 2026-01-09 + +### Added + +- Added OpenCode Zen provider support. Set `OPENCODE_API_KEY` env var and use `opencode/` (e.g., `opencode/claude-opus-4-5`). + +## [0.41.0] - 2026-01-09 + +### Added + +- Anthropic OAuth support is back! Use `/login` to authenticate with your Claude Pro/Max subscription. + +## [0.40.1] - 2026-01-09 + +### Removed + +- Anthropic OAuth support (`/login`). Use API keys instead. + +## [0.40.0] - 2026-01-08 + +### Added + +- Documentation on component invalidation and theme changes in `docs/tui.md` + +### Fixed + +- Components now properly rebuild their content on theme change (tool executions, assistant messages, bash executions, custom messages, branch/compaction summaries) + +## [0.39.1] - 2026-01-08 + +### Fixed + +- `setTheme()` now triggers a full rerender so previously rendered components update with the new theme colors +- `mac-system-theme.ts` example now polls every 2 seconds and uses `osascript` for real-time macOS appearance detection + +## [0.39.0] - 2026-01-08 + +### Breaking Changes + +- `before_agent_start` event now receives `systemPrompt` in the event object and returns `systemPrompt` (full replacement) instead of `systemPromptAppend`. Extensions that were appending must now use `event.systemPrompt + extra` pattern. ([#575](https://github.com/badlogic/pi-mono/issues/575)) +- `discoverSkills()` now returns `{ skills: Skill[], warnings: SkillWarning[] }` instead of `Skill[]`. This allows callers to handle skill loading warnings. ([#577](https://github.com/badlogic/pi-mono/pull/577) by [@cv](https://github.com/cv)) + +### Added + +- `ctx.ui.getAllThemes()`, `ctx.ui.getTheme(name)`, and `ctx.ui.setTheme(name | Theme)` methods for extensions to list, load, and switch themes at runtime ([#576](https://github.com/badlogic/pi-mono/pull/576)) +- `--no-tools` flag to disable all built-in tools, allowing extension-only tool setups ([#557](https://github.com/badlogic/pi-mono/pull/557) by [@cv](https://github.com/cv)) +- Pluggable operations for built-in tools enabling remote execution via SSH or other transports ([#564](https://github.com/badlogic/pi-mono/issues/564)). Interfaces: `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `LsOperations`, `GrepOperations`, `FindOperations` +- `user_bash` event for intercepting user `!`/`!!` commands, allowing extensions to redirect to remote systems ([#528](https://github.com/badlogic/pi-mono/issues/528)) +- `setActiveTools()` in ExtensionAPI for dynamic tool management +- Built-in renderers used automatically for tool overrides without custom `renderCall`/`renderResult` +- `ssh.ts` example: remote tool execution via `--ssh user@host:/path` +- `interactive-shell.ts` example: run interactive commands (vim, git rebase, htop) with full terminal access via `!i` prefix or auto-detection +- Wayland clipboard support for `/copy` command using wl-copy with xclip/xsel fallback ([#570](https://github.com/badlogic/pi-mono/pull/570) by [@OgulcanCelik](https://github.com/OgulcanCelik)) +- **Experimental:** `ctx.ui.custom()` now accepts `{ overlay: true }` option for floating modal components that composite over existing content without clearing the screen ([#558](https://github.com/badlogic/pi-mono/pull/558) by [@nicobailon](https://github.com/nicobailon)) +- `AgentSession.skills` and `AgentSession.skillWarnings` properties to access loaded skills without rediscovery ([#577](https://github.com/badlogic/pi-mono/pull/577) by [@cv](https://github.com/cv)) + +### Fixed + +- String `systemPrompt` in `createAgentSession()` now works as a full replacement instead of having context files and skills appended, matching documented behavior ([#543](https://github.com/badlogic/pi-mono/issues/543)) +- Update notification for bun binary installs now shows release download URL instead of npm command ([#567](https://github.com/badlogic/pi-mono/pull/567) by [@ferologics](https://github.com/ferologics)) +- ESC key now works during "Working..." state after auto-retry ([#568](https://github.com/badlogic/pi-mono/pull/568) by [@tmustier](https://github.com/tmustier)) +- Abort messages now show correct retry attempt count (e.g., "Aborted after 2 retry attempts") ([#568](https://github.com/badlogic/pi-mono/pull/568) by [@tmustier](https://github.com/tmustier)) +- Fixed Antigravity provider returning 429 errors despite available quota ([#571](https://github.com/badlogic/pi-mono/pull/571) by [@ben-vargas](https://github.com/ben-vargas)) +- Fixed malformed thinking text in Gemini/Antigravity responses where thinking content appeared as regular text or vice versa. Cross-model conversations now properly convert thinking blocks to plain text. ([#561](https://github.com/badlogic/pi-mono/issues/561)) +- `--no-skills` flag now correctly prevents skills from loading in interactive mode ([#577](https://github.com/badlogic/pi-mono/pull/577) by [@cv](https://github.com/cv)) + +## [0.38.0] - 2026-01-08 + +### Breaking Changes + +- `ctx.ui.custom()` factory signature changed from `(tui, theme, done)` to `(tui, theme, keybindings, done)` for keybinding access in custom components +- `LoadedExtension` type renamed to `Extension` +- `LoadExtensionsResult.setUIContext()` removed, replaced with `runtime: ExtensionRuntime` +- `ExtensionRunner` constructor now requires `runtime: ExtensionRuntime` as second parameter +- `ExtensionRunner.initialize()` signature changed from options object to positional params `(actions, contextActions, commandContextActions?, uiContext?)` +- `ExtensionRunner.getHasUI()` renamed to `hasUI()` +- OpenAI Codex model aliases removed (`gpt-5`, `gpt-5-mini`, `gpt-5-nano`, `codex-mini-latest`). Use canonical IDs: `gpt-5.1`, `gpt-5.1-codex-mini`, `gpt-5.2`, `gpt-5.2-codex`. ([#536](https://github.com/badlogic/pi-mono/pull/536) by [@ghoulr](https://github.com/ghoulr)) + +### Added + +- `--no-extensions` flag to disable extension discovery while still allowing explicit `-e` paths ([#524](https://github.com/badlogic/pi-mono/pull/524) by [@cv](https://github.com/cv)) +- SDK: `InteractiveMode`, `runPrintMode()`, `runRpcMode()` exported for building custom run modes. See `docs/sdk.md`. +- `PI_SKIP_VERSION_CHECK` environment variable to disable new version notifications at startup ([#549](https://github.com/badlogic/pi-mono/pull/549) by [@aos](https://github.com/aos)) +- `thinkingBudgets` setting to customize token budgets per thinking level for token-based providers ([#529](https://github.com/badlogic/pi-mono/pull/529) by [@melihmucuk](https://github.com/melihmucuk)) +- Extension UI dialogs (`ctx.ui.select()`, `ctx.ui.confirm()`, `ctx.ui.input()`) now support a `timeout` option with live countdown display ([#522](https://github.com/badlogic/pi-mono/pull/522) by [@nicobailon](https://github.com/nicobailon)) +- Extensions can now provide custom editor components via `ctx.ui.setEditorComponent()`. See `examples/extensions/modal-editor.ts` and `docs/tui.md` Pattern 7. +- Extension factories can now be async, enabling dynamic imports and lazy-loaded dependencies ([#513](https://github.com/badlogic/pi-mono/pull/513) by [@austinm911](https://github.com/austinm911)) +- `ctx.shutdown()` is now available in extension contexts for requesting a graceful shutdown. In interactive mode, shutdown is deferred until the agent becomes idle (after processing all queued steering and follow-up messages). In RPC mode, shutdown is deferred until after completing the current command response. In print mode, shutdown is a no-op as the process exits automatically when prompts complete. ([#542](https://github.com/badlogic/pi-mono/pull/542) by [@kaofelix](https://github.com/kaofelix)) + +### Fixed + +- Default thinking level from settings now applies correctly when `enabledModels` is configured ([#540](https://github.com/badlogic/pi-mono/pull/540) by [@ferologics](https://github.com/ferologics)) +- External edits to `settings.json` while pi is running are now preserved when pi saves settings ([#527](https://github.com/badlogic/pi-mono/pull/527) by [@ferologics](https://github.com/ferologics)) +- Overflow-based compaction now skips if error came from a different model or was already handled by a previous compaction ([#535](https://github.com/badlogic/pi-mono/pull/535) by [@mitsuhiko](https://github.com/mitsuhiko)) +- OpenAI Codex context window reduced from 400k to 272k tokens to match Codex CLI defaults and prevent 400 errors ([#536](https://github.com/badlogic/pi-mono/pull/536) by [@ghoulr](https://github.com/ghoulr)) +- Context overflow detection now recognizes `context_length_exceeded` errors. +- Key presses no longer dropped when input is batched over SSH ([#538](https://github.com/badlogic/pi-mono/issues/538)) +- Clipboard image support now works on Alpine Linux and other musl-based distros ([#533](https://github.com/badlogic/pi-mono/issues/533)) + +## [0.37.8] - 2026-01-07 + +## [0.37.7] - 2026-01-07 + +## [0.37.6] - 2026-01-06 + +### Added + +- Extension UI dialogs (`ctx.ui.select()`, `ctx.ui.confirm()`, `ctx.ui.input()`) now accept an optional `AbortSignal` to programmatically dismiss dialogs. Useful for implementing timeouts. See `examples/extensions/timed-confirm.ts`. ([#474](https://github.com/badlogic/pi-mono/issues/474)) +- HTML export now shows bridge prompts in model change messages for Codex sessions ([#510](https://github.com/badlogic/pi-mono/pull/510) by [@mitsuhiko](https://github.com/mitsuhiko)) + +## [0.37.5] - 2026-01-06 + +### Added + +- ExtensionAPI: `setModel()`, `getThinkingLevel()`, `setThinkingLevel()` methods for extensions to change model and thinking level at runtime ([#509](https://github.com/badlogic/pi-mono/issues/509)) +- Exported truncation utilities for custom tools: `truncateHead`, `truncateTail`, `truncateLine`, `formatSize`, `DEFAULT_MAX_BYTES`, `DEFAULT_MAX_LINES`, `TruncationOptions`, `TruncationResult` +- New example `truncated-tool.ts` demonstrating proper output truncation with custom rendering for extensions +- New example `preset.ts` demonstrating preset configurations with model/thinking/tools switching ([#347](https://github.com/badlogic/pi-mono/issues/347)) +- Documentation for output truncation best practices in `docs/extensions.md` +- Exported all UI components for extensions: `ArminComponent`, `AssistantMessageComponent`, `BashExecutionComponent`, `BorderedLoader`, `BranchSummaryMessageComponent`, `CompactionSummaryMessageComponent`, `CustomEditor`, `CustomMessageComponent`, `DynamicBorder`, `ExtensionEditorComponent`, `ExtensionInputComponent`, `ExtensionSelectorComponent`, `FooterComponent`, `LoginDialogComponent`, `ModelSelectorComponent`, `OAuthSelectorComponent`, `SessionSelectorComponent`, `SettingsSelectorComponent`, `ShowImagesSelectorComponent`, `ThemeSelectorComponent`, `ThinkingSelectorComponent`, `ToolExecutionComponent`, `TreeSelectorComponent`, `UserMessageComponent`, `UserMessageSelectorComponent`, plus utilities `renderDiff`, `truncateToVisualLines` +- `docs/tui.md`: Common Patterns section with copy-paste code for SelectList, BorderedLoader, SettingsList, setStatus, setWidget, setFooter +- `docs/tui.md`: Key Rules section documenting critical patterns for extension UI development +- `docs/extensions.md`: Exhaustive example links for all ExtensionAPI methods and events +- System prompt now references `docs/tui.md` for TUI component development + +## [0.37.4] - 2026-01-06 + +### Added + +- Session picker (`pi -r`) and `--session` flag now support searching/resuming by session ID (UUID prefix) ([#495](https://github.com/badlogic/pi-mono/issues/495) by [@arunsathiya](https://github.com/arunsathiya)) +- Extensions can now replace the startup header with `ctx.ui.setHeader()`, see `examples/extensions/custom-header.ts` ([#500](https://github.com/badlogic/pi-mono/pull/500) by [@tudoroancea](https://github.com/tudoroancea)) + +### Changed + +- Startup help text: fixed misleading "ctrl+k to delete line" to "ctrl+k to delete to end" +- Startup help text and `/hotkeys`: added `!!` shortcut for running bash without adding output to context + +### Fixed + +- Queued steering/follow-up messages no longer wipe unsent editor input ([#503](https://github.com/badlogic/pi-mono/pull/503) by [@tmustier](https://github.com/tmustier)) +- OAuth token refresh failure no longer crashes app at startup, allowing user to `/login` to re-authenticate ([#498](https://github.com/badlogic/pi-mono/issues/498)) + +## [0.37.3] - 2026-01-06 + +### Added + +- Extensions can now replace the footer with `ctx.ui.setFooter()`, see `examples/extensions/custom-footer.ts` ([#481](https://github.com/badlogic/pi-mono/issues/481)) +- Session ID is now forwarded to LLM providers for session-based caching (used by OpenAI Codex for prompt caching). +- Added `blockImages` setting to prevent images from being sent to LLM providers ([#492](https://github.com/badlogic/pi-mono/pull/492) by [@jsinge97](https://github.com/jsinge97)) +- Extensions can now send user messages via `pi.sendUserMessage()` ([#483](https://github.com/badlogic/pi-mono/issues/483)) + +### Fixed + +- Add `minimatch` as a direct dependency for explicit imports. +- Status bar now shows correct git branch when running in a git worktree ([#490](https://github.com/badlogic/pi-mono/pull/490) by [@kcosr](https://github.com/kcosr)) +- Interactive mode: Ctrl+V clipboard image paste now works on Wayland sessions by using `wl-paste` with `xclip` fallback ([#488](https://github.com/badlogic/pi-mono/pull/488) by [@ghoulr](https://github.com/ghoulr)) + +## [0.37.2] - 2026-01-05 + +### Fixed + +- Extension directories in `settings.json` now respect `package.json` manifests, matching global extension behavior ([#480](https://github.com/badlogic/pi-mono/pull/480) by [@prateekmedia](https://github.com/prateekmedia)) +- Share viewer: deep links now scroll to the target message when opened via `/share` +- Bash tool now handles spawn errors gracefully instead of crashing the agent (missing cwd, invalid shell path) ([#479](https://github.com/badlogic/pi-mono/pull/479) by [@robinwander](https://github.com/robinwander)) + +## [0.37.1] - 2026-01-05 + +### Fixed + +- Share viewer: copy-link buttons now generate correct URLs when session is viewed via `/share` (iframe context) + +## [0.37.0] - 2026-01-05 + +### Added + +- Share viewer: copy-link button on messages to share URLs that navigate directly to a specific message ([#477](https://github.com/badlogic/pi-mono/pull/477) by [@lockmeister](https://github.com/lockmeister)) +- Extension example: add `claude-rules` to load `.claude/rules/` entries into the system prompt ([#461](https://github.com/badlogic/pi-mono/pull/461) by [@vaayne](https://github.com/vaayne)) +- Headless OAuth login: all providers now show paste input for manual URL/code entry, works over SSH without DISPLAY ([#428](https://github.com/badlogic/pi-mono/pull/428) by [@ben-vargas](https://github.com/ben-vargas), [#468](https://github.com/badlogic/pi-mono/pull/468) by [@crcatala](https://github.com/crcatala)) + +### Changed + +- OAuth login UI now uses dedicated dialog component with consistent borders +- Assume truecolor support for all terminals except `dumb`, empty, or `linux` (fixes colors over SSH) +- OpenAI Codex clean-up: removed per-thinking-level model variants, thinking level is now set separately and the provider clamps to what each model supports internally (initial implementation in [#472](https://github.com/badlogic/pi-mono/pull/472) by [@ben-vargas](https://github.com/ben-vargas)) + +### Fixed + +- Messages submitted during compaction are queued and delivered after compaction completes, preserving steering and follow-up behavior. Extension commands execute immediately during compaction. ([#476](https://github.com/badlogic/pi-mono/pull/476) by [@tmustier](https://github.com/tmustier)) +- Managed binaries (`fd`, `rg`) now stored in `~/.pi/agent/bin/` instead of `tools/`, eliminating false deprecation warnings ([#470](https://github.com/badlogic/pi-mono/pull/470) by [@mcinteerj](https://github.com/mcinteerj)) +- Extensions defined in `settings.json` were not loaded ([#463](https://github.com/badlogic/pi-mono/pull/463) by [@melihmucuk](https://github.com/melihmucuk)) +- OAuth refresh no longer logs users out when multiple pi instances are running ([#466](https://github.com/badlogic/pi-mono/pull/466) by [@Cursivez](https://github.com/Cursivez)) +- Migration warnings now ignore `fd.exe` and `rg.exe` in `tools/` on Windows ([#458](https://github.com/badlogic/pi-mono/pull/458) by [@carlosgtrz](https://github.com/carlosgtrz)) +- CI: add `examples/extensions/with-deps` to workspaces to fix typecheck ([#467](https://github.com/badlogic/pi-mono/pull/467) by [@aliou](https://github.com/aliou)) +- SDK: passing `extensions: []` now disables extension discovery as documented ([#465](https://github.com/badlogic/pi-mono/pull/465) by [@aliou](https://github.com/aliou)) + +## [0.36.0] - 2026-01-05 + +### Added + +- Experimental: OpenAI Codex OAuth provider support: access Codex models via ChatGPT Plus/Pro subscription using `/login openai-codex` ([#451](https://github.com/badlogic/pi-mono/pull/451) by [@kim0](https://github.com/kim0)) + +## [0.35.0] - 2026-01-05 + +This release unifies hooks and custom tools into a single "extensions" system and renames "slash commands" to "prompt templates". ([#454](https://github.com/badlogic/pi-mono/issues/454)) + +**Before migrating, read:** + +- [docs/extensions.md](docs/extensions.md) - Full API reference +- [README.md](README.md) - Extensions section with examples +- [examples/extensions/](examples/extensions/) - Working examples + +### Extensions Migration + +Hooks and custom tools are now unified as **extensions**. Both were TypeScript modules exporting a factory function that receives an API object. Now there's one concept, one discovery location, one CLI flag, one settings.json entry. + +**Automatic migration:** + +- `commands/` directories are automatically renamed to `prompts/` on startup (both `~/.pi/agent/commands/` and `.pi/commands/`) + +**Manual migration required:** + +1. Move files from `hooks/` and `tools/` directories to `extensions/` (deprecation warnings shown on startup) +2. Update imports and type names in your extension code +3. Update `settings.json` if you have explicit hook and custom tool paths configured + +**Directory changes:** + +``` +# Before +~/.pi/agent/hooks/*.ts → ~/.pi/agent/extensions/*.ts +~/.pi/agent/tools/*.ts → ~/.pi/agent/extensions/*.ts +.pi/hooks/*.ts → .pi/extensions/*.ts +.pi/tools/*.ts → .pi/extensions/*.ts +``` + +**Extension discovery rules** (in `extensions/` directories): + +1. **Direct files:** `extensions/*.ts` or `*.js` → loaded directly +2. **Subdirectory with index:** `extensions/myext/index.ts` → loaded as single extension +3. **Subdirectory with package.json:** `extensions/myext/package.json` with `"pi"` field → loads declared paths + +```json +// extensions/my-package/package.json +{ + "name": "my-extension-package", + "dependencies": { "zod": "^3.0.0" }, + "pi": { + "extensions": ["./src/main.ts", "./src/tools.ts"] + } +} +``` + +No recursion beyond one level. Complex packages must use the `package.json` manifest. Dependencies are resolved via jiti, and extensions can be published to and installed from npm. + +**Type renames:** + +- `HookAPI` → `ExtensionAPI` +- `HookContext` → `ExtensionContext` +- `HookCommandContext` → `ExtensionCommandContext` +- `HookUIContext` → `ExtensionUIContext` +- `CustomToolAPI` → `ExtensionAPI` (merged) +- `CustomToolContext` → `ExtensionContext` (merged) +- `CustomToolUIContext` → `ExtensionUIContext` +- `CustomTool` → `ToolDefinition` +- `CustomToolFactory` → `ExtensionFactory` +- `HookMessage` → `CustomMessage` + +**Import changes:** + +```typescript +// Before (hook) +import type { HookAPI, HookContext } from "@mariozechner/pi-coding-agent"; +export default function (pi: HookAPI) { ... } + +// Before (custom tool) +import type { CustomToolFactory } from "@mariozechner/pi-coding-agent"; +const factory: CustomToolFactory = (pi) => ({ name: "my_tool", ... }); +export default factory; + +// After (both are now extensions) +import type { ExtensionAPI } from "@mariozechner/pi-coding-agent"; +export default function (pi: ExtensionAPI) { + pi.on("tool_call", async (event, ctx) => { ... }); + pi.registerTool({ name: "my_tool", ... }); +} +``` + +**Custom tools now have full context access.** Tools registered via `pi.registerTool()` now receive the same `ctx` object that event handlers receive. Previously, custom tools had limited context. Now all extension code shares the same capabilities: + +- `pi.registerTool()` - Register tools the LLM can call +- `pi.registerCommand()` - Register commands like `/mycommand` +- `pi.registerShortcut()` - Register keyboard shortcuts (shown in `/hotkeys`) +- `pi.registerFlag()` - Register CLI flags (shown in `--help`) +- `pi.registerMessageRenderer()` - Custom TUI rendering for message types +- `pi.on()` - Subscribe to lifecycle events (tool_call, session_start, etc.) +- `pi.sendMessage()` - Inject messages into the conversation +- `pi.appendEntry()` - Persist custom data in session (survives restart/branch) +- `pi.exec()` - Run shell commands +- `pi.getActiveTools()` / `pi.setActiveTools()` - Dynamic tool enable/disable +- `pi.getAllTools()` - List all available tools +- `pi.events` - Event bus for cross-extension communication +- `ctx.ui.confirm()` / `select()` / `input()` - User prompts +- `ctx.ui.notify()` - Toast notifications +- `ctx.ui.setStatus()` - Persistent status in footer (multiple extensions can set their own) +- `ctx.ui.setWidget()` - Widget display above editor +- `ctx.ui.setTitle()` - Set terminal window title +- `ctx.ui.custom()` - Full TUI component with keyboard handling +- `ctx.ui.editor()` - Multi-line text editor with external editor support +- `ctx.sessionManager` - Read session entries, get branch history + +**Settings changes:** + +```json +// Before +{ + "hooks": ["./my-hook.ts"], + "customTools": ["./my-tool.ts"] +} + +// After +{ + "extensions": ["./my-extension.ts"] +} +``` + +**CLI changes:** + +```bash +# Before +pi --hook ./safety.ts --tool ./todo.ts + +# After +pi --extension ./safety.ts -e ./todo.ts +``` + +### Prompt Templates Migration + +"Slash commands" (markdown files defining reusable prompts invoked via `/name`) are renamed to "prompt templates" to avoid confusion with extension-registered commands. + +**Automatic migration:** The `commands/` directory is automatically renamed to `prompts/` on startup (if `prompts/` doesn't exist). Works for both regular directories and symlinks. + +**Directory changes:** + +``` +~/.pi/agent/commands/*.md → ~/.pi/agent/prompts/*.md +.pi/commands/*.md → .pi/prompts/*.md +``` + +**SDK type renames:** + +- `FileSlashCommand` → `PromptTemplate` +- `LoadSlashCommandsOptions` → `LoadPromptTemplatesOptions` + +**SDK function renames:** + +- `discoverSlashCommands()` → `discoverPromptTemplates()` +- `loadSlashCommands()` → `loadPromptTemplates()` +- `expandSlashCommand()` → `expandPromptTemplate()` +- `getCommandsDir()` → `getPromptsDir()` + +**SDK option renames:** + +- `CreateAgentSessionOptions.slashCommands` → `.promptTemplates` +- `AgentSession.fileCommands` → `.promptTemplates` +- `PromptOptions.expandSlashCommands` → `.expandPromptTemplates` + +### SDK Migration + +**Discovery functions:** + +- `discoverAndLoadHooks()` → `discoverAndLoadExtensions()` +- `discoverAndLoadCustomTools()` → merged into `discoverAndLoadExtensions()` +- `loadHooks()` → `loadExtensions()` +- `loadCustomTools()` → merged into `loadExtensions()` + +**Runner and wrapper:** + +- `HookRunner` → `ExtensionRunner` +- `wrapToolsWithHooks()` → `wrapToolsWithExtensions()` +- `wrapToolWithHooks()` → `wrapToolWithExtensions()` + +**CreateAgentSessionOptions:** + +- `.hooks` → removed (use `.additionalExtensionPaths` for paths) +- `.additionalHookPaths` → `.additionalExtensionPaths` +- `.preloadedHooks` → `.preloadedExtensions` +- `.customTools` type changed: `Array<{ path?; tool: CustomTool }>` → `ToolDefinition[]` +- `.additionalCustomToolPaths` → merged into `.additionalExtensionPaths` +- `.slashCommands` → `.promptTemplates` + +**AgentSession:** + +- `.hookRunner` → `.extensionRunner` +- `.fileCommands` → `.promptTemplates` +- `.sendHookMessage()` → `.sendCustomMessage()` + +### Session Migration + +**Automatic.** Session version bumped from 2 to 3. Existing sessions are migrated on first load: + +- Message role `"hookMessage"` → `"custom"` + +### Breaking Changes + +- **Settings:** `hooks` and `customTools` arrays replaced with single `extensions` array +- **CLI:** `--hook` and `--tool` flags replaced with `--extension` / `-e` +- **Directories:** `hooks/`, `tools/` → `extensions/`; `commands/` → `prompts/` +- **Types:** See type renames above +- **SDK:** See SDK migration above + +### Changed + +- Extensions can have their own `package.json` with dependencies (resolved via jiti) +- Documentation: `docs/hooks.md` and `docs/custom-tools.md` merged into `docs/extensions.md` +- Examples: `examples/hooks/` and `examples/custom-tools/` merged into `examples/extensions/` +- README: Extensions section expanded with custom tools, commands, events, state persistence, shortcuts, flags, and UI examples +- SDK: `customTools` option now accepts `ToolDefinition[]` directly (simplified from `Array<{ path?, tool }>`) +- SDK: `extensions` option accepts `ExtensionFactory[]` for inline extensions +- SDK: `additionalExtensionPaths` replaces both `additionalHookPaths` and `additionalCustomToolPaths` + +## [0.34.2] - 2026-01-04 + +## [0.34.1] - 2026-01-04 + +### Added + +- Hook API: `ctx.ui.setTitle(title)` allows hooks to set the terminal window/tab title ([#446](https://github.com/badlogic/pi-mono/pull/446) by [@aliou](https://github.com/aliou)) + +### Changed + +- Expanded keybinding documentation to list all 32 supported symbol keys with notes on ctrl+symbol behavior ([#450](https://github.com/badlogic/pi-mono/pull/450) by [@kaofelix](https://github.com/kaofelix)) + +## [0.34.0] - 2026-01-04 + +### Added + +- Hook API: `pi.getActiveTools()` and `pi.setActiveTools(toolNames)` for dynamically enabling/disabling tools from hooks +- Hook API: `pi.getAllTools()` to enumerate all configured tools (built-in via --tools or default, plus custom tools) +- Hook API: `pi.registerFlag(name, options)` and `pi.getFlag(name)` for hooks to register custom CLI flags (parsed automatically) +- Hook API: `pi.registerShortcut(shortcut, options)` for hooks to register custom keyboard shortcuts using `KeyId` (e.g., `Key.shift("p")`). Conflicts with built-in shortcuts are skipped, conflicts between hooks logged as warnings. +- Hook API: `ctx.ui.setWidget(key, content)` for status displays above the editor. Accepts either a string array or a component factory function. +- Hook API: `theme.strikethrough(text)` for strikethrough text styling +- Hook API: `before_agent_start` handlers can now return `systemPromptAppend` to dynamically append text to the system prompt for that turn. Multiple hooks' appends are concatenated. +- Hook API: `before_agent_start` handlers can now return multiple messages (all are injected, not just the first) +- `/hotkeys` command now shows hook-registered shortcuts in a separate "Hooks" section +- New example hook: `plan-mode.ts` - Claude Code-style read-only exploration mode: + - Toggle via `/plan` command, `Shift+P` shortcut, or `--plan` CLI flag + - Read-only tools: `read`, `bash`, `grep`, `find`, `ls` (no `edit`/`write`) + - Bash commands restricted to non-destructive operations (blocks `rm`, `mv`, `git commit`, `npm install`, etc.) + - Interactive prompt after each response: execute plan, stay in plan mode, or refine + - Todo list widget showing progress with checkboxes and strikethrough for completed items + - Each todo has a unique ID; agent marks items done by outputting `[DONE:id]` + - Progress updates via `agent_end` hook (parses completed items from final message) + - `/todos` command to view current plan progress + - Shows `⏸ plan` indicator in footer when in plan mode, `📋 2/5` when executing + - State persists across sessions (including todo progress) +- New example hook: `tools.ts` - Interactive `/tools` command to enable/disable tools with session persistence +- New example hook: `pirate.ts` - Demonstrates `systemPromptAppend` to make the agent speak like a pirate +- Tool registry now contains all built-in tools (read, bash, edit, write, grep, find, ls) even when `--tools` limits the initially active set. Hooks can enable any tool from the registry via `pi.setActiveTools()`. +- System prompt now automatically rebuilds when tools change via `setActiveTools()`, updating tool descriptions and guidelines to match the new tool set +- Hook errors now display full stack traces for easier debugging +- Event bus (`pi.events`) for tool/hook communication: shared pub/sub between custom tools and hooks +- Custom tools now have `pi.sendMessage()` to send messages directly to the agent session without needing the event bus +- `sendMessage()` supports `deliverAs: "nextTurn"` to queue messages for the next user prompt + +### Changed + +- Removed image placeholders after copy & paste, replaced with inserting image file paths directly. ([#442](https://github.com/badlogic/pi-mono/pull/442) by [@mitsuhiko](https://github.com/mitsuhiko)) + +### Fixed + +- Fixed potential text decoding issues in bash executor by using streaming TextDecoder instead of Buffer.toString() +- External editor (Ctrl-G) now shows full pasted content instead of `[paste #N ...]` placeholders ([#444](https://github.com/badlogic/pi-mono/pull/444) by [@aliou](https://github.com/aliou)) + +## [0.33.0] - 2026-01-04 + +### Breaking Changes + +- **Key detection functions removed from `@mariozechner/pi-tui`**: All `isXxx()` key detection functions (`isEnter()`, `isEscape()`, `isCtrlC()`, etc.) have been removed. Use `matchesKey(data, keyId)` instead (e.g., `matchesKey(data, "enter")`, `matchesKey(data, "ctrl+c")`). This affects hooks and custom tools that use `ctx.ui.custom()` with keyboard input handling. ([#405](https://github.com/badlogic/pi-mono/pull/405)) + +### Added + +- Clipboard image paste support via `Ctrl+V`. Images are saved to a temp file and attached to the message. Works on macOS, Windows, and Linux (X11). ([#419](https://github.com/badlogic/pi-mono/issues/419)) +- Configurable keybindings via `~/.pi/agent/keybindings.json`. All keyboard shortcuts (editor navigation, deletion, app actions like model cycling, etc.) can now be customized. Supports multiple bindings per action. ([#405](https://github.com/badlogic/pi-mono/pull/405) by [@hjanuschka](https://github.com/hjanuschka)) +- `/quit` and `/exit` slash commands to gracefully exit the application. Unlike double Ctrl+C, these properly await hook and custom tool cleanup handlers before exiting. ([#426](https://github.com/badlogic/pi-mono/pull/426) by [@ben-vargas](https://github.com/ben-vargas)) + +### Fixed + +- Subagent example README referenced incorrect filename `subagent.ts` instead of `index.ts` ([#427](https://github.com/badlogic/pi-mono/pull/427) by [@Whamp](https://github.com/Whamp)) + +## [0.32.3] - 2026-01-03 + +### Fixed + +- `--list-models` no longer shows Google Vertex AI models without explicit authentication configured +- JPEG/GIF/WebP images not displaying in terminals using Kitty graphics protocol (Kitty, Ghostty, WezTerm). The protocol requires PNG format, so non-PNG images are now converted before display. +- Version check URL typo preventing update notifications from working ([#423](https://github.com/badlogic/pi-mono/pull/423) by [@skuridin](https://github.com/skuridin)) +- Large images exceeding Anthropic's 5MB limit now retry with progressive quality/size reduction ([#424](https://github.com/badlogic/pi-mono/pull/424) by [@mitsuhiko](https://github.com/mitsuhiko)) + +## [0.32.2] - 2026-01-03 + +### Added + +- `$ARGUMENTS` syntax for custom slash commands as alternative to `$@` for all arguments joined. Aligns with patterns used by Claude, Codex, and OpenCode. Both syntaxes remain fully supported. ([#418](https://github.com/badlogic/pi-mono/pull/418) by [@skuridin](https://github.com/skuridin)) + +### Changed + +- **Slash commands and hook commands now work during streaming**: Previously, using a slash command or hook command while the agent was streaming would crash with "Agent is already processing". Now: + - Hook commands execute immediately (they manage their own LLM interaction via `pi.sendMessage()`) + - File-based slash commands are expanded and queued via steer/followUp + - `steer()` and `followUp()` now expand file-based slash commands and error on hook commands (hook commands cannot be queued) + - `prompt()` accepts new `streamingBehavior` option (`"steer"` or `"followUp"`) to specify queueing behavior during streaming + - RPC `prompt` command now accepts optional `streamingBehavior` field + ([#420](https://github.com/badlogic/pi-mono/issues/420)) + +### Fixed + +- Slash command argument substitution now processes positional arguments (`$1`, `$2`, etc.) before all-arguments (`$@`, `$ARGUMENTS`) to prevent recursive substitution when argument values contain dollar-digit patterns like `$100`. ([#418](https://github.com/badlogic/pi-mono/pull/418) by [@skuridin](https://github.com/skuridin)) + +## [0.32.1] - 2026-01-03 + +### Added + +- Shell commands without context contribution: use `!!command` to execute a bash command that is shown in the TUI and saved to session history but excluded from LLM context. Useful for running commands you don't want the AI to see. ([#414](https://github.com/badlogic/pi-mono/issues/414)) + +### Fixed + +- Edit tool diff not displaying in TUI due to race condition between async preview computation and tool execution + +## [0.32.0] - 2026-01-03 + +### Breaking Changes + +- **Queue API replaced with steer/followUp**: The `queueMessage()` method has been split into two methods with different delivery semantics ([#403](https://github.com/badlogic/pi-mono/issues/403)): + - `steer(text)`: Interrupts the agent mid-run (Enter while streaming). Delivered after current tool execution. + - `followUp(text)`: Waits until the agent finishes (Alt+Enter while streaming). Delivered only when agent stops. +- **Settings renamed**: `queueMode` setting renamed to `steeringMode`. Added new `followUpMode` setting. Old settings.json files are migrated automatically. +- **AgentSession methods renamed**: + - `queueMessage()` → `steer()` and `followUp()` + - `queueMode` getter → `steeringMode` and `followUpMode` getters + - `setQueueMode()` → `setSteeringMode()` and `setFollowUpMode()` + - `queuedMessageCount` → `pendingMessageCount` + - `getQueuedMessages()` → `getSteeringMessages()` and `getFollowUpMessages()` + - `clearQueue()` now returns `{ steering: string[], followUp: string[] }` + - `hasQueuedMessages()` → `hasPendingMessages()` +- **Hook API signature changed**: `pi.sendMessage()` second parameter changed from `triggerTurn?: boolean` to `options?: { triggerTurn?, deliverAs? }`. Use `deliverAs: "followUp"` for follow-up delivery. Affects both hooks and internal `sendHookMessage()` method. +- **RPC API changes**: + - `queue_message` command → `steer` and `follow_up` commands + - `set_queue_mode` command → `set_steering_mode` and `set_follow_up_mode` commands + - `RpcSessionState.queueMode` → `steeringMode` and `followUpMode` +- **Settings UI**: "Queue mode" setting split into "Steering mode" and "Follow-up mode" + +### Added + +- Configurable double-escape action: choose whether double-escape with empty editor opens `/tree` (default) or `/branch`. Configure via `/settings` or `doubleEscapeAction` in settings.json ([#404](https://github.com/badlogic/pi-mono/issues/404)) +- Vertex AI provider (`google-vertex`): access Gemini models via Google Cloud Vertex AI using Application Default Credentials ([#300](https://github.com/badlogic/pi-mono/pull/300) by [@default-anton](https://github.com/default-anton)) +- Built-in provider overrides in `models.json`: override just `baseUrl` to route a built-in provider through a proxy while keeping all its models, or define `models` to fully replace the provider ([#406](https://github.com/badlogic/pi-mono/pull/406) by [@yevhen](https://github.com/yevhen)) +- Automatic image resizing: images larger than 2000x2000 are resized for better model compatibility. Original dimensions are injected into the prompt. Controlled via `/settings` or `images.autoResize` in settings.json. ([#402](https://github.com/badlogic/pi-mono/pull/402) by [@mitsuhiko](https://github.com/mitsuhiko)) +- Alt+Enter keybind to queue follow-up messages while agent is streaming +- `Theme` and `ThemeColor` types now exported for hooks using `ctx.ui.custom()` +- Terminal window title now displays "pi - dirname" to identify which project session you're in ([#407](https://github.com/badlogic/pi-mono/pull/407) by [@kaofelix](https://github.com/kaofelix)) + +### Changed + +- Editor component now uses word wrapping instead of character-level wrapping for better readability ([#382](https://github.com/badlogic/pi-mono/pull/382) by [@nickseelert](https://github.com/nickseelert)) + +### Fixed + +- `/model` selector now opens instantly instead of waiting for OAuth token refresh. Token refresh is deferred until a model is actually used. +- Shift+Space, Shift+Backspace, and Shift+Delete now work correctly in Kitty-protocol terminals (Kitty, WezTerm, etc.) instead of being silently ignored ([#411](https://github.com/badlogic/pi-mono/pull/411) by [@nathyong](https://github.com/nathyong)) +- `AgentSession.prompt()` now throws if called while the agent is already streaming, preventing race conditions. Use `steer()` or `followUp()` to queue messages during streaming. +- Ctrl+C now works like Escape in selector components, so mashing Ctrl+C will eventually close the program ([#400](https://github.com/badlogic/pi-mono/pull/400) by [@mitsuhiko](https://github.com/mitsuhiko)) + +## [0.31.1] - 2026-01-02 + +### Fixed + +- Model selector no longer allows negative index when pressing arrow keys before models finish loading ([#398](https://github.com/badlogic/pi-mono/pull/398) by [@mitsuhiko](https://github.com/mitsuhiko)) +- Type guard functions (`isBashToolResult`, etc.) now exported at runtime, not just in type declarations ([#397](https://github.com/badlogic/pi-mono/issues/397)) + +## [0.31.0] - 2026-01-02 + +This release introduces session trees for in-place branching, major API changes to hooks and custom tools, and structured compaction with file tracking. + +### Session Tree + +Sessions now use a tree structure with `id`/`parentId` fields. This enables in-place branching: navigate to any previous point with `/tree`, continue from there, and switch between branches while preserving all history in a single file. + +**Existing sessions are automatically migrated** (v1 → v2) on first load. No manual action required. + +New entry types: `BranchSummaryEntry` (context from abandoned branches), `CustomEntry` (hook state), `CustomMessageEntry` (hook-injected messages), `LabelEntry` (bookmarks). + +See [docs/session.md](docs/session.md) for the file format and `SessionManager` API. + +### Hooks Migration + +The hooks API has been restructured with more granular events and better session access. + +**Type renames:** + +- `HookEventContext` → `HookContext` +- `HookCommandContext` is now a new interface extending `HookContext` with session control methods + +**Event changes:** + +- The monolithic `session` event is now split into granular events: `session_start`, `session_before_switch`, `session_switch`, `session_before_branch`, `session_branch`, `session_before_compact`, `session_compact`, `session_shutdown` +- `session_before_switch` and `session_switch` events now include `reason: "new" | "resume"` to distinguish between `/new` and `/resume` +- New `session_before_tree` and `session_tree` events for `/tree` navigation (hook can provide custom branch summary) +- New `before_agent_start` event: inject messages before the agent loop starts +- New `context` event: modify messages non-destructively before each LLM call +- Session entries are no longer passed in events. Use `ctx.sessionManager.getEntries()` or `ctx.sessionManager.getBranch()` instead + +**API changes:** + +- `pi.send(text, attachments?)` → `pi.sendMessage(message, triggerTurn?)` (creates `CustomMessageEntry`) +- New `pi.appendEntry(customType, data?)` for hook state persistence (not in LLM context) +- New `pi.registerCommand(name, options)` for custom slash commands (handler receives `HookCommandContext`) +- New `pi.registerMessageRenderer(customType, renderer)` for custom TUI rendering +- New `ctx.isIdle()`, `ctx.abort()`, `ctx.hasQueuedMessages()` for agent state (available in all events) +- New `ctx.ui.editor(title, prefill?)` for multi-line text editing with Ctrl+G external editor support +- New `ctx.ui.custom(component)` for full TUI component rendering with keyboard focus +- New `ctx.ui.setStatus(key, text)` for persistent status text in footer (multiple hooks can set their own) +- New `ctx.ui.theme` getter for styling text with theme colors +- `ctx.exec()` moved to `pi.exec()` +- `ctx.sessionFile` → `ctx.sessionManager.getSessionFile()` +- New `ctx.modelRegistry` and `ctx.model` for API key resolution + +**HookCommandContext (slash commands only):** + +- `ctx.waitForIdle()` - wait for agent to finish streaming +- `ctx.newSession(options?)` - create new sessions with optional setup callback +- `ctx.fork(entryId) - fork from a specific entry, creating a new session file +- `ctx.navigateTree(targetId, options?)` - navigate the session tree + +These methods are only on `HookCommandContext` (not `HookContext`) because they can deadlock if called from event handlers that run inside the agent loop. + +**Removed:** + +- `hookTimeout` setting (hooks no longer have timeouts; use Ctrl+C to abort) +- `resolveApiKey` parameter (use `ctx.modelRegistry.getApiKey(model)`) + +See [docs/hooks.md](docs/hooks.md) and [examples/hooks/](examples/hooks/) for the current API. + +### Custom Tools Migration + +The custom tools API has been restructured to mirror the hooks pattern with a context object. + +**Type renames:** + +- `CustomAgentTool` → `CustomTool` +- `ToolAPI` → `CustomToolAPI` +- `ToolContext` → `CustomToolContext` +- `ToolSessionEvent` → `CustomToolSessionEvent` + +**Execute signature changed:** + +```typescript +// Before (v0.30.2) +execute(toolCallId, params, signal, onUpdate) + +// After +execute(toolCallId, params, onUpdate, ctx, signal?) +``` + +The new `ctx: CustomToolContext` provides `sessionManager`, `modelRegistry`, `model`, and agent state methods: + +- `ctx.isIdle()` - check if agent is streaming +- `ctx.hasQueuedMessages()` - check if user has queued messages (skip interactive prompts) +- `ctx.abort()` - abort current operation (fire-and-forget) + +**Session event changes:** + +- `CustomToolSessionEvent` now only has `reason` and `previousSessionFile` +- Session entries are no longer in the event. Use `ctx.sessionManager.getBranch()` or `ctx.sessionManager.getEntries()` to reconstruct state +- Reasons: `"start" | "switch" | "branch" | "tree" | "shutdown"` (no separate `"new"` reason; `/new` triggers `"switch"`) +- `dispose()` method removed. Use `onSession` with `reason: "shutdown"` for cleanup + +See [docs/custom-tools.md](docs/custom-tools.md) and [examples/custom-tools/](examples/custom-tools/) for the current API. + +### SDK Migration + +**Type changes:** + +- `CustomAgentTool` → `CustomTool` +- `AppMessage` → `AgentMessage` +- `sessionFile` returns `string | undefined` (was `string | null`) +- `model` returns `Model | undefined` (was `Model | null`) +- `Attachment` type removed. Use `ImageContent` from `@mariozechner/pi-ai` instead. Add images directly to message content arrays. + +**AgentSession API:** + +- `branch(entryIndex: number)` → `branch(entryId: string)` +- `getUserMessagesForBranching()` returns `{ entryId, text }` instead of `{ entryIndex, text }` +- `reset()` → `newSession(options?)` where options has optional `parentSession` for lineage tracking +- `newSession()` and `switchSession()` now return `Promise` (false if cancelled by hook) +- New `navigateTree(targetId, options?)` for in-place tree navigation + +**Hook integration:** + +- New `sendHookMessage(message, triggerTurn?)` for hook message injection + +**SessionManager API:** + +- Method renames: `saveXXX()` → `appendXXX()` (e.g., `appendMessage`, `appendCompaction`) +- `branchInPlace()` → `branch()` +- `reset()` → `newSession(options?)` with optional `parentSession` for lineage tracking +- `createBranchedSessionFromEntries(entries, index)` → `createBranchedSession(leafId)` +- `SessionHeader.branchedFrom` → `SessionHeader.parentSession` +- `saveCompaction(entry)` → `appendCompaction(summary, firstKeptEntryId, tokensBefore, details?)` +- `getEntries()` now excludes the session header (use `getHeader()` separately) +- `getSessionFile()` returns `string | undefined` (undefined for in-memory sessions) +- New tree methods: `getTree()`, `getBranch()`, `getLeafId()`, `getLeafEntry()`, `getEntry()`, `getChildren()`, `getLabel()` +- New append methods: `appendCustomEntry()`, `appendCustomMessageEntry()`, `appendLabelChange()` +- New branch methods: `branch(entryId)`, `branchWithSummary()` + +**ModelRegistry (new):** + +`ModelRegistry` is a new class that manages model discovery and API key resolution. It combines built-in models with custom models from `models.json` and resolves API keys via `AuthStorage`. + +```typescript +import { + discoverAuthStorage, + discoverModels, +} from "@mariozechner/pi-coding-agent"; + +const authStorage = discoverAuthStorage(); // ~/.pi/agent/auth.json +const modelRegistry = discoverModels(authStorage); // + ~/.pi/agent/models.json + +// Get all models (built-in + custom) +const allModels = modelRegistry.getAll(); + +// Get only models with valid API keys +const available = await modelRegistry.getAvailable(); + +// Find specific model +const model = modelRegistry.find("anthropic", "claude-sonnet-4-20250514"); + +// Get API key for a model +const apiKey = await modelRegistry.getApiKey(model); +``` + +This replaces the old `resolveApiKey` callback pattern. Hooks and custom tools access it via `ctx.modelRegistry`. + +**Renamed exports:** + +- `messageTransformer` → `convertToLlm` +- `SessionContext` alias `LoadedSession` removed + +See [docs/sdk.md](docs/sdk.md) and [examples/sdk/](examples/sdk/) for the current API. + +### RPC Migration + +**Session commands:** + +- `reset` command → `new_session` command with optional `parentSession` field + +**Branching commands:** + +- `branch` command: `entryIndex` → `entryId` +- `get_branch_messages` response: `entryIndex` → `entryId` + +**Type changes:** + +- Messages are now `AgentMessage` (was `AppMessage`) +- `prompt` command: `attachments` field replaced with `images` field using `ImageContent` format + +**Compaction events:** + +- `auto_compaction_start` now includes `reason` field (`"threshold"` or `"overflow"`) +- `auto_compaction_end` now includes `willRetry` field +- `compact` response includes full `CompactionResult` (`summary`, `firstKeptEntryId`, `tokensBefore`, `details`) + +See [docs/rpc.md](docs/rpc.md) for the current protocol. + +### Structured Compaction + +Compaction and branch summarization now use a structured output format: + +- Clear sections: Goal, Progress, Key Information, File Operations +- File tracking: `readFiles` and `modifiedFiles` arrays in `details`, accumulated across compactions +- Conversations are serialized to text before summarization to prevent the model from "continuing" them + +The `before_compact` and `before_tree` hook events allow custom compaction implementations. See [docs/compaction.md](docs/compaction.md). + +### Interactive Mode + +**`/tree` command:** + +- Navigate the full session tree in-place +- Search by typing, page with ←/→ +- Filter modes (Ctrl+O): default → no-tools → user-only → labeled-only → all +- Press `l` to label entries as bookmarks +- Selecting a branch switches context and optionally injects a summary of the abandoned branch + +**Entry labels:** + +- Bookmark any entry via `/tree` → select → `l` +- Labels appear in tree view and persist as `LabelEntry` + +**Theme changes (breaking for custom themes):** + +Custom themes must add these new color tokens or they will fail to load: + +- `selectedBg`: background for selected/highlighted items in tree selector and other components +- `customMessageBg`: background for hook-injected messages (`CustomMessageEntry`) +- `customMessageText`: text color for hook messages +- `customMessageLabel`: label color for hook messages (the `[customType]` prefix) + +Total color count increased from 46 to 50. See [docs/themes.md](docs/themes.md) for the full color list and copy values from the built-in dark/light themes. + +**Settings:** + +- `enabledModels`: allowlist models in `settings.json` (same format as `--models` CLI) + +### Added + +- `ctx.ui.setStatus(key, text)` for hooks to display persistent status text in the footer ([#385](https://github.com/badlogic/pi-mono/pull/385) by [@prateekmedia](https://github.com/prateekmedia)) +- `ctx.ui.theme` getter for styling status text and other output with theme colors +- `/share` command to upload session as a secret GitHub gist and get a shareable URL via pi.dev ([#380](https://github.com/badlogic/pi-mono/issues/380)) +- HTML export now includes a tree visualization sidebar for navigating session branches ([#375](https://github.com/badlogic/pi-mono/issues/375)) +- HTML export supports keyboard shortcuts: Ctrl+T to toggle thinking blocks, Ctrl+O to toggle tool outputs +- HTML export supports theme-configurable background colors via optional `export` section in theme JSON ([#387](https://github.com/badlogic/pi-mono/pull/387) by [@mitsuhiko](https://github.com/mitsuhiko)) +- HTML export syntax highlighting now uses theme colors and matches TUI rendering +- **Snake game example hook**: Demonstrates `ui.custom()`, `registerCommand()`, and session persistence. See [examples/hooks/snake.ts](examples/hooks/snake.ts). +- **`thinkingText` theme token**: Configurable color for thinking block text. ([#366](https://github.com/badlogic/pi-mono/pull/366) by [@paulbettner](https://github.com/paulbettner)) + +### Changed + +- **Entry IDs**: Session entries now use short 8-character hex IDs instead of full UUIDs +- **API key priority**: `ANTHROPIC_OAUTH_TOKEN` now takes precedence over `ANTHROPIC_API_KEY` +- HTML export template split into separate files (template.html, template.css, template.js) for easier maintenance + +### Fixed + +- HTML export now properly sanitizes user messages containing HTML tags like ` + + + + +
+ + +
+
+
+
+
+ +
+
+ + + + + + + + + + + + + diff --git a/dist/core/export-html/template.js b/dist/core/export-html/template.js new file mode 100644 index 0000000..cfdd161 --- /dev/null +++ b/dist/core/export-html/template.js @@ -0,0 +1,1864 @@ + (function() { + 'use strict'; + + // ============================================================ + // DATA LOADING + // ============================================================ + + const base64 = document.getElementById('session-data').textContent; + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + const data = JSON.parse(new TextDecoder('utf-8').decode(bytes)); + const { header, entries, leafId: defaultLeafId, systemPrompt, tools, renderedTools } = data; + + // ============================================================ + // URL PARAMETER HANDLING + // ============================================================ + + // Parse URL parameters for deep linking: leafId and targetId + // Check for injected params (when loaded in iframe via srcdoc) or use window.location + const injectedParams = document.querySelector('meta[name="pi-url-params"]'); + const searchString = injectedParams ? injectedParams.content : window.location.search.substring(1); + const urlParams = new URLSearchParams(searchString); + const urlLeafId = urlParams.get('leafId'); + const urlTargetId = urlParams.get('targetId'); + // Use URL leafId if provided, otherwise fall back to session default + const leafId = urlLeafId || defaultLeafId; + + // ============================================================ + // DATA STRUCTURES + // ============================================================ + + // Entry lookup by ID + const byId = new Map(); + for (const entry of entries) { + byId.set(entry.id, entry); + } + + // Tool call lookup (toolCallId -> {name, arguments}) + const toolCallMap = new Map(); + for (const entry of entries) { + if (entry.type === 'message' && entry.message.role === 'assistant') { + const content = entry.message.content; + if (Array.isArray(content)) { + for (const block of content) { + if (block.type === 'toolCall') { + toolCallMap.set(block.id, { name: block.name, arguments: block.arguments }); + } + } + } + } + } + + // Label lookup (entryId -> label string) + // Labels are stored in 'label' entries that reference their target via targetId + const labelMap = new Map(); + for (const entry of entries) { + if (entry.type === 'label' && entry.targetId && entry.label) { + labelMap.set(entry.targetId, entry.label); + } + } + + // ============================================================ + // TREE DATA PREPARATION (no DOM, pure data) + // ============================================================ + + /** + * Build tree structure from flat entries. + * Returns array of root nodes, each with { entry, children, label }. + */ + function buildTree() { + const nodeMap = new Map(); + const roots = []; + + // Create nodes + for (const entry of entries) { + nodeMap.set(entry.id, { + entry, + children: [], + label: labelMap.get(entry.id) + }); + } + + // Build parent-child relationships + for (const entry of entries) { + const node = nodeMap.get(entry.id); + if (entry.parentId === null || entry.parentId === undefined || entry.parentId === entry.id) { + roots.push(node); + } else { + const parent = nodeMap.get(entry.parentId); + if (parent) { + parent.children.push(node); + } else { + roots.push(node); + } + } + } + + // Sort children by timestamp + function sortChildren(node) { + node.children.sort((a, b) => + new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime() + ); + node.children.forEach(sortChildren); + } + roots.forEach(sortChildren); + + return roots; + } + + /** + * Build set of entry IDs on path from root to target. + */ + function buildActivePathIds(targetId) { + const ids = new Set(); + let current = byId.get(targetId); + while (current) { + ids.add(current.id); + // Stop if no parent or self-referencing (root) + if (!current.parentId || current.parentId === current.id) { + break; + } + current = byId.get(current.parentId); + } + return ids; + } + + /** + * Get array of entries from root to target (the conversation path). + */ + function getPath(targetId) { + const path = []; + let current = byId.get(targetId); + while (current) { + path.unshift(current); + // Stop if no parent or self-referencing (root) + if (!current.parentId || current.parentId === current.id) { + break; + } + current = byId.get(current.parentId); + } + return path; + } + + // Tree node lookup for finding leaves + let treeNodeMap = null; + + /** + * Find the newest leaf node reachable from a given node. + * This allows clicking any node in a branch to show the full branch. + * Children are sorted by timestamp, so the newest is always last. + */ + function findNewestLeaf(nodeId) { + // Build tree node map lazily + if (!treeNodeMap) { + treeNodeMap = new Map(); + const tree = buildTree(); + function mapNodes(node) { + treeNodeMap.set(node.entry.id, node); + node.children.forEach(mapNodes); + } + tree.forEach(mapNodes); + } + + const node = treeNodeMap.get(nodeId); + if (!node) return nodeId; + + // Follow the newest (last) child at each level + let current = node; + while (current.children.length > 0) { + current = current.children[current.children.length - 1]; + } + return current.entry.id; + } + + /** + * Flatten tree into list with indentation and connector info. + * Returns array of { node, indent, showConnector, isLast, gutters, isVirtualRootChild, multipleRoots }. + * Matches tree-selector.ts logic exactly. + */ + function flattenTree(roots, activePathIds) { + const result = []; + const multipleRoots = roots.length > 1; + + // Mark which subtrees contain the active leaf + const containsActive = new Map(); + function markActive(node) { + let has = activePathIds.has(node.entry.id); + for (const child of node.children) { + if (markActive(child)) has = true; + } + containsActive.set(node, has); + return has; + } + roots.forEach(markActive); + + // Stack: [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] + const stack = []; + + // Add roots (prioritize branch containing active leaf) + const orderedRoots = [...roots].sort((a, b) => + Number(containsActive.get(b)) - Number(containsActive.get(a)) + ); + for (let i = orderedRoots.length - 1; i >= 0; i--) { + const isLast = i === orderedRoots.length - 1; + stack.push([orderedRoots[i], multipleRoots ? 1 : 0, multipleRoots, multipleRoots, isLast, [], multipleRoots]); + } + + while (stack.length > 0) { + const [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] = stack.pop(); + + result.push({ node, indent, showConnector, isLast, gutters, isVirtualRootChild, multipleRoots }); + + const children = node.children; + const multipleChildren = children.length > 1; + + // Order children (active branch first) + const orderedChildren = [...children].sort((a, b) => + Number(containsActive.get(b)) - Number(containsActive.get(a)) + ); + + // Calculate child indent (matches tree-selector.ts) + let childIndent; + if (multipleChildren) { + // Parent branches: children get +1 + childIndent = indent + 1; + } else if (justBranched && indent > 0) { + // First generation after a branch: +1 for visual grouping + childIndent = indent + 1; + } else { + // Single-child chain: stay flat + childIndent = indent; + } + + // Build gutters for children + const connectorDisplayed = showConnector && !isVirtualRootChild; + const currentDisplayIndent = multipleRoots ? Math.max(0, indent - 1) : indent; + const connectorPosition = Math.max(0, currentDisplayIndent - 1); + const childGutters = connectorDisplayed + ? [...gutters, { position: connectorPosition, show: !isLast }] + : gutters; + + // Add children in reverse order for stack + for (let i = orderedChildren.length - 1; i >= 0; i--) { + const childIsLast = i === orderedChildren.length - 1; + stack.push([orderedChildren[i], childIndent, multipleChildren, multipleChildren, childIsLast, childGutters, false]); + } + } + + return result; + } + + /** + * Build ASCII prefix string for tree node. + */ + function buildTreePrefix(flatNode) { + const { indent, showConnector, isLast, gutters, isVirtualRootChild, multipleRoots } = flatNode; + const displayIndent = multipleRoots ? Math.max(0, indent - 1) : indent; + const connector = showConnector && !isVirtualRootChild ? (isLast ? '└─ ' : '├─ ') : ''; + const connectorPosition = connector ? displayIndent - 1 : -1; + + const totalChars = displayIndent * 3; + const prefixChars = []; + for (let i = 0; i < totalChars; i++) { + const level = Math.floor(i / 3); + const posInLevel = i % 3; + + const gutter = gutters.find(g => g.position === level); + if (gutter) { + prefixChars.push(posInLevel === 0 ? (gutter.show ? '│' : ' ') : ' '); + } else if (connector && level === connectorPosition) { + if (posInLevel === 0) { + prefixChars.push(isLast ? '└' : '├'); + } else if (posInLevel === 1) { + prefixChars.push('─'); + } else { + prefixChars.push(' '); + } + } else { + prefixChars.push(' '); + } + } + return prefixChars.join(''); + } + + // ============================================================ + // FILTERING (pure data) + // ============================================================ + + let filterMode = 'default'; + let searchQuery = ''; + + function hasTextContent(content) { + if (typeof content === 'string') return content.trim().length > 0; + if (Array.isArray(content)) { + for (const c of content) { + if (c.type === 'text' && c.text && c.text.trim().length > 0) return true; + } + } + return false; + } + + function extractContent(content) { + if (typeof content === 'string') return content; + if (Array.isArray(content)) { + return content + .filter(c => c.type === 'text' && c.text) + .map(c => c.text) + .join(''); + } + return ''; + } + + /** + * Parse a skill block from message text. + * Returns null if the text doesn't contain a skill block. + * Matches the format: \n...\n\n\nuser message + */ + function parseSkillBlock(text) { + const match = text.match(/^\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/); + if (!match) return null; + return { + name: match[1], + location: match[2], + content: match[3], + userMessage: match[4]?.trim() || undefined, + }; + } + + function getSearchableText(entry, label) { + const parts = []; + if (label) parts.push(label); + + switch (entry.type) { + case 'message': { + const msg = entry.message; + parts.push(msg.role); + if (msg.content) parts.push(extractContent(msg.content)); + if (msg.role === 'bashExecution' && msg.command) parts.push(msg.command); + break; + } + case 'custom_message': + parts.push(entry.customType); + parts.push(typeof entry.content === 'string' ? entry.content : extractContent(entry.content)); + break; + case 'compaction': + parts.push('compaction'); + break; + case 'branch_summary': + parts.push('branch summary', entry.summary); + break; + case 'model_change': + parts.push('model', entry.modelId); + break; + case 'thinking_level_change': + parts.push('thinking', entry.thinkingLevel); + break; + } + + return parts.join(' ').toLowerCase(); + } + + /** + * Filter flat nodes based on current filterMode and searchQuery. + */ + function filterNodes(flatNodes, currentLeafId) { + const searchTokens = searchQuery.toLowerCase().split(/\s+/).filter(Boolean); + + const filtered = flatNodes.filter(flatNode => { + const entry = flatNode.node.entry; + const label = flatNode.node.label; + const isCurrentLeaf = entry.id === currentLeafId; + + // Always show current leaf + if (isCurrentLeaf) return true; + + // Hide assistant messages with only tool calls (no text) unless error/aborted + if (entry.type === 'message' && entry.message.role === 'assistant') { + const msg = entry.message; + const hasText = hasTextContent(msg.content); + const isErrorOrAborted = msg.stopReason && msg.stopReason !== 'stop' && msg.stopReason !== 'toolUse'; + if (!hasText && !isErrorOrAborted) return false; + } + + // Apply filter mode + const isSettingsEntry = ['label', 'custom', 'model_change', 'thinking_level_change'].includes(entry.type); + let passesFilter = true; + + switch (filterMode) { + case 'user-only': + passesFilter = entry.type === 'message' && entry.message.role === 'user'; + break; + case 'no-tools': + passesFilter = !isSettingsEntry && !(entry.type === 'message' && entry.message.role === 'toolResult'); + break; + case 'labeled-only': + passesFilter = label !== undefined; + break; + case 'all': + passesFilter = true; + break; + default: // 'default' + passesFilter = !isSettingsEntry; + break; + } + + if (!passesFilter) return false; + + // Apply search filter + if (searchTokens.length > 0) { + const nodeText = getSearchableText(entry, label); + if (!searchTokens.every(t => nodeText.includes(t))) return false; + } + + return true; + }); + + // Recalculate visual structure based on visible tree + recalculateVisualStructure(filtered, flatNodes); + + return filtered; + } + + /** + * Recompute indentation/connectors for the filtered view + * + * Filtering can hide intermediate entries; descendants attach to the nearest visible ancestor. + * Keep indentation semantics aligned with flattenTree() so single-child chains don't drift right. + */ + function recalculateVisualStructure(filteredNodes, allFlatNodes) { + if (filteredNodes.length === 0) return; + + const visibleIds = new Set(filteredNodes.map(n => n.node.entry.id)); + + // Build entry map for parent lookup (using full tree) + const entryMap = new Map(); + for (const flatNode of allFlatNodes) { + entryMap.set(flatNode.node.entry.id, flatNode); + } + + // Find nearest visible ancestor for a node + function findVisibleAncestor(nodeId) { + let currentId = entryMap.get(nodeId)?.node.entry.parentId; + while (currentId != null) { + if (visibleIds.has(currentId)) { + return currentId; + } + currentId = entryMap.get(currentId)?.node.entry.parentId; + } + return null; + } + + // Build visible tree structure + const visibleParent = new Map(); + const visibleChildren = new Map(); + visibleChildren.set(null, []); // root-level nodes + + for (const flatNode of filteredNodes) { + const nodeId = flatNode.node.entry.id; + const ancestorId = findVisibleAncestor(nodeId); + visibleParent.set(nodeId, ancestorId); + + if (!visibleChildren.has(ancestorId)) { + visibleChildren.set(ancestorId, []); + } + visibleChildren.get(ancestorId).push(nodeId); + } + + // Update multipleRoots based on visible roots + const visibleRootIds = visibleChildren.get(null); + const multipleRoots = visibleRootIds.length > 1; + + // Build a map for quick lookup: nodeId → FlatNode + const filteredNodeMap = new Map(); + for (const flatNode of filteredNodes) { + filteredNodeMap.set(flatNode.node.entry.id, flatNode); + } + + // DFS traversal of visible tree, applying same indentation rules as flattenTree() + // Stack items: [nodeId, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] + const stack = []; + + // Add visible roots in reverse order (to process in forward order via stack) + for (let i = visibleRootIds.length - 1; i >= 0; i--) { + const isLast = i === visibleRootIds.length - 1; + stack.push([ + visibleRootIds[i], + multipleRoots ? 1 : 0, + multipleRoots, + multipleRoots, + isLast, + [], + multipleRoots + ]); + } + + while (stack.length > 0) { + const [nodeId, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] = stack.pop(); + + const flatNode = filteredNodeMap.get(nodeId); + if (!flatNode) continue; + + // Update this node's visual properties + flatNode.indent = indent; + flatNode.showConnector = showConnector; + flatNode.isLast = isLast; + flatNode.gutters = gutters; + flatNode.isVirtualRootChild = isVirtualRootChild; + flatNode.multipleRoots = multipleRoots; + + // Get visible children of this node + const children = visibleChildren.get(nodeId) || []; + const multipleChildren = children.length > 1; + + // Calculate child indent using same rules as flattenTree(): + // - Parent branches (multiple children): children get +1 + // - Just branched and indent > 0: children get +1 for visual grouping + // - Single-child chain: stay flat + let childIndent; + if (multipleChildren) { + childIndent = indent + 1; + } else if (justBranched && indent > 0) { + childIndent = indent + 1; + } else { + childIndent = indent; + } + + // Build gutters for children (same logic as flattenTree) + const connectorDisplayed = showConnector && !isVirtualRootChild; + const currentDisplayIndent = multipleRoots ? Math.max(0, indent - 1) : indent; + const connectorPosition = Math.max(0, currentDisplayIndent - 1); + const childGutters = connectorDisplayed + ? [...gutters, { position: connectorPosition, show: !isLast }] + : gutters; + + // Add children in reverse order (to process in forward order via stack) + for (let i = children.length - 1; i >= 0; i--) { + const childIsLast = i === children.length - 1; + stack.push([ + children[i], + childIndent, + multipleChildren, + multipleChildren, + childIsLast, + childGutters, + false + ]); + } + } + } + + // ============================================================ + // TREE DISPLAY TEXT (pure data -> string) + // ============================================================ + + function shortenPath(p) { + if (typeof p !== 'string') return ''; + if (p.startsWith('/Users/')) { + const parts = p.split('/'); + if (parts.length > 2) return '~' + p.slice(('/Users/' + parts[2]).length); + } + if (p.startsWith('/home/')) { + const parts = p.split('/'); + if (parts.length > 2) return '~' + p.slice(('/home/' + parts[2]).length); + } + return p; + } + + function formatToolCall(name, args) { + switch (name) { + case 'read': { + const path = shortenPath(String(args.path || args.file_path || '')); + const offset = args.offset; + const limit = args.limit; + let display = path; + if (offset !== undefined || limit !== undefined) { + const start = offset ?? 1; + const end = limit !== undefined ? start + limit - 1 : ''; + display += `:${start}${end ? `-${end}` : ''}`; + } + return `[read: ${display}]`; + } + case 'write': + return `[write: ${shortenPath(String(args.path || args.file_path || ''))}]`; + case 'edit': + return `[edit: ${shortenPath(String(args.path || args.file_path || ''))}]`; + case 'bash': { + const rawCmd = String(args.command || ''); + const cmd = rawCmd.replace(/[\n\t]/g, ' ').trim().slice(0, 50); + return `[bash: ${cmd}${rawCmd.length > 50 ? '...' : ''}]`; + } + case 'grep': + return `[grep: /${args.pattern || ''}/ in ${shortenPath(String(args.path || '.'))}]`; + case 'find': + return `[find: ${args.pattern || ''} in ${shortenPath(String(args.path || '.'))}]`; + case 'ls': + return `[ls: ${shortenPath(String(args.path || '.'))}]`; + default: { + const argsStr = JSON.stringify(args).slice(0, 40); + return `[${name}: ${argsStr}${JSON.stringify(args).length > 40 ? '...' : ''}]`; + } + } + } + + function escapeHtml(text) { + return String(text) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + + function sanitizeMarkdownUrl(value) { + const href = String(value || '').trim().replace(/[\x00-\x1f\x7f]/g, ''); + if (!href) return href; + + const scheme = href.match(/^([A-Za-z][A-Za-z0-9+.-]*):/); + if (scheme && !/^(https?|mailto|tel|ftp)$/i.test(scheme[1])) { + return null; + } + + return href; + } + + /** + * Truncate string to maxLen chars, append "..." if truncated. + */ + function truncate(s, maxLen = 100) { + if (s.length <= maxLen) return s; + return s.slice(0, maxLen) + '...'; + } + + /** + * Get display text for tree node (returns HTML string). + */ + function getTreeNodeDisplayHtml(entry, label) { + const normalize = s => s.replace(/[\n\t]/g, ' ').trim(); + const labelHtml = label ? `[${escapeHtml(label)}] ` : ''; + + switch (entry.type) { + case 'message': { + const msg = entry.message; + if (msg.role === 'user') { + const rawContent = extractContent(msg.content); + const skillBlock = parseSkillBlock(rawContent); + if (skillBlock) { + let treeHtml = labelHtml + `skill: ${escapeHtml(skillBlock.name)}`; + if (skillBlock.userMessage) { + treeHtml += ` · user: ${escapeHtml(truncate(normalize(skillBlock.userMessage)))}`; + } + return treeHtml; + } + const content = truncate(normalize(rawContent)); + return labelHtml + `user: ${escapeHtml(content)}`; + } + if (msg.role === 'assistant') { + const textContent = truncate(normalize(extractContent(msg.content))); + if (textContent) { + return labelHtml + `assistant: ${escapeHtml(textContent)}`; + } + if (msg.stopReason === 'aborted') { + return labelHtml + `assistant: (aborted)`; + } + if (msg.errorMessage) { + return labelHtml + `assistant: ${escapeHtml(truncate(msg.errorMessage))}`; + } + return labelHtml + `assistant: (no text)`; + } + if (msg.role === 'toolResult') { + const toolCall = msg.toolCallId ? toolCallMap.get(msg.toolCallId) : null; + if (toolCall) { + return labelHtml + `${escapeHtml(formatToolCall(toolCall.name, toolCall.arguments))}`; + } + return labelHtml + `[${escapeHtml(msg.toolName || 'tool')}]`; + } + if (msg.role === 'bashExecution') { + const cmd = truncate(normalize(msg.command || '')); + return labelHtml + `[bash]: ${escapeHtml(cmd)}`; + } + return labelHtml + `[${escapeHtml(msg.role)}]`; + } + case 'compaction': + return labelHtml + `[compaction: ${Math.round(entry.tokensBefore/1000)}k tokens]`; + case 'branch_summary': { + const summary = truncate(normalize(entry.summary || '')); + return labelHtml + `[branch summary]: ${escapeHtml(summary)}`; + } + case 'custom_message': { + const content = typeof entry.content === 'string' ? entry.content : extractContent(entry.content); + return labelHtml + `[${escapeHtml(entry.customType)}]: ${escapeHtml(truncate(normalize(content)))}`; + } + case 'model_change': + return labelHtml + `[model: ${escapeHtml(entry.modelId)}]`; + case 'thinking_level_change': + return labelHtml + `[thinking: ${escapeHtml(entry.thinkingLevel)}]`; + default: + return labelHtml + `[${escapeHtml(entry.type)}]`; + } + } + + // ============================================================ + // TREE RENDERING (DOM manipulation) + // ============================================================ + + let currentLeafId = leafId; + let currentTargetId = urlTargetId || leafId; + let treeRendered = false; + + function renderTree() { + const tree = buildTree(); + const activePathIds = buildActivePathIds(currentLeafId); + const flatNodes = flattenTree(tree, activePathIds); + const filtered = filterNodes(flatNodes, currentLeafId); + const container = document.getElementById('tree-container'); + + // Full render only on first call or when filter/search changes + if (!treeRendered) { + container.innerHTML = ''; + + for (const flatNode of filtered) { + const entry = flatNode.node.entry; + const isOnPath = activePathIds.has(entry.id); + const isTarget = entry.id === currentTargetId; + + const div = document.createElement('div'); + div.className = 'tree-node'; + if (isOnPath) div.classList.add('in-path'); + if (isTarget) div.classList.add('active'); + div.dataset.id = entry.id; + + const prefix = buildTreePrefix(flatNode); + const prefixSpan = document.createElement('span'); + prefixSpan.className = 'tree-prefix'; + prefixSpan.textContent = prefix; + + const marker = document.createElement('span'); + marker.className = 'tree-marker'; + marker.textContent = isOnPath ? '•' : ' '; + + const content = document.createElement('span'); + content.className = 'tree-content'; + content.innerHTML = getTreeNodeDisplayHtml(entry, flatNode.node.label); + + div.appendChild(prefixSpan); + div.appendChild(marker); + div.appendChild(content); + // Navigate to the newest leaf through this node, but scroll to the clicked node + div.addEventListener('click', () => { + if (window.getSelection().toString()) return; + const leafId = findNewestLeaf(entry.id); + navigateTo(leafId, 'target', entry.id); + }); + + container.appendChild(div); + } + + treeRendered = true; + } else { + // Just update markers and classes + const nodes = container.querySelectorAll('.tree-node'); + for (const node of nodes) { + const id = node.dataset.id; + const isOnPath = activePathIds.has(id); + const isTarget = id === currentTargetId; + + node.classList.toggle('in-path', isOnPath); + node.classList.toggle('active', isTarget); + + const marker = node.querySelector('.tree-marker'); + if (marker) { + marker.textContent = isOnPath ? '•' : ' '; + } + } + } + + document.getElementById('tree-status').textContent = `${filtered.length} / ${flatNodes.length} entries`; + + // Scroll active node into view after layout + setTimeout(() => { + const activeNode = container.querySelector('.tree-node.active'); + if (activeNode) { + activeNode.scrollIntoView({ block: 'nearest' }); + } + }, 0); + } + + function forceTreeRerender() { + treeRendered = false; + renderTree(); + } + + // ============================================================ + // MESSAGE RENDERING + // ============================================================ + + function formatTokens(count) { + if (count < 1000) return count.toString(); + if (count < 10000) return (count / 1000).toFixed(1) + 'k'; + if (count < 1000000) return Math.round(count / 1000) + 'k'; + return (count / 1000000).toFixed(1) + 'M'; + } + + function formatTimestamp(ts) { + if (!ts) return ''; + const date = new Date(ts); + return date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' }); + } + + function replaceTabs(text) { + return text.replace(/\t/g, ' '); + } + + /** Safely coerce value to string for display. Returns null if invalid type. */ + function str(value) { + if (typeof value === 'string') return value; + if (value == null) return ''; + return null; + } + + function getLanguageFromPath(filePath) { + const ext = filePath.split('.').pop()?.toLowerCase(); + const extToLang = { + ts: 'typescript', tsx: 'typescript', js: 'javascript', jsx: 'javascript', + py: 'python', rb: 'ruby', rs: 'rust', go: 'go', java: 'java', + c: 'c', cpp: 'cpp', h: 'c', hpp: 'cpp', cs: 'csharp', + php: 'php', sh: 'bash', bash: 'bash', zsh: 'bash', + sql: 'sql', html: 'html', css: 'css', scss: 'scss', + json: 'json', yaml: 'yaml', yml: 'yaml', xml: 'xml', + md: 'markdown', dockerfile: 'dockerfile' + }; + return extToLang[ext]; + } + + function findToolResult(toolCallId) { + for (const entry of entries) { + if (entry.type === 'message' && entry.message.role === 'toolResult') { + if (entry.message.toolCallId === toolCallId) { + return entry.message; + } + } + } + return null; + } + + function formatExpandableOutput(text, maxLines, lang) { + text = replaceTabs(text); + const lines = text.split('\n'); + const displayLines = lines.slice(0, maxLines); + const remaining = lines.length - maxLines; + + if (lang) { + let highlighted; + try { + highlighted = hljs.highlight(text, { language: lang }).value; + } catch { + highlighted = escapeHtml(text); + } + + if (remaining > 0) { + const previewCode = displayLines.join('\n'); + let previewHighlighted; + try { + previewHighlighted = hljs.highlight(previewCode, { language: lang }).value; + } catch { + previewHighlighted = escapeHtml(previewCode); + } + + return ``; + } + + return `
${highlighted}
`; + } + + // Plain text output + if (remaining > 0) { + let out = ''; + return out; + } + + let out = '
'; + for (const line of displayLines) { + out += `
${escapeHtml(replaceTabs(line))}
`; + } + out += '
'; + return out; + } + + function renderToolCall(call) { + const result = findToolResult(call.id); + const isError = result?.isError || false; + const statusClass = result ? (isError ? 'error' : 'success') : 'pending'; + + const getResultText = () => { + if (!result) return ''; + const textBlocks = result.content.filter(c => c.type === 'text'); + return textBlocks.map(c => c.text).join('\n'); + }; + + const getResultImages = () => { + if (!result) return []; + return result.content.filter(c => c.type === 'image'); + }; + + const renderResultImages = () => { + const images = getResultImages(); + if (images.length === 0) return ''; + return '
' + + images.map(img => ``).join('') + + '
'; + }; + + const toolDomId = `tool-call-${escapeHtml(call.id)}`; + let html = `
`; + const args = call.arguments || {}; + const name = call.name; + + const invalidArg = '[invalid arg]'; + + switch (name) { + case 'bash': { + const command = str(args.command); + const cmdDisplay = command === null ? invalidArg : escapeHtml(command || '...'); + html += `
$ ${cmdDisplay}
`; + if (result) { + const output = getResultText().trim(); + if (output) html += formatExpandableOutput(output, 5); + } + break; + } + case 'read': { + const filePath = str(args.file_path ?? args.path); + const offset = args.offset; + const limit = args.limit; + + let pathHtml = filePath === null ? invalidArg : escapeHtml(shortenPath(filePath || '')); + if (filePath !== null && (offset !== undefined || limit !== undefined)) { + const startLine = offset ?? 1; + const endLine = limit !== undefined ? startLine + limit - 1 : ''; + pathHtml += `:${startLine}${endLine ? '-' + endLine : ''}`; + } + + html += `
read ${pathHtml}
`; + if (result) { + html += renderResultImages(); + const output = getResultText(); + const lang = filePath ? getLanguageFromPath(filePath) : null; + if (output) html += formatExpandableOutput(output, 10, lang); + } + break; + } + case 'write': { + const filePath = str(args.file_path ?? args.path); + const content = str(args.content); + + html += `
write ${filePath === null ? invalidArg : escapeHtml(shortenPath(filePath || ''))}`; + if (content !== null && content) { + const lines = content.split('\n'); + if (lines.length > 10) html += ` (${lines.length} lines)`; + } + html += '
'; + + if (content === null) { + html += `
[invalid content arg - expected string]
`; + } else if (content) { + const lang = filePath ? getLanguageFromPath(filePath) : null; + html += formatExpandableOutput(content, 10, lang); + } + if (result) { + const output = getResultText().trim(); + if (output) html += `
${escapeHtml(output)}
`; + } + break; + } + case 'edit': { + const filePath = str(args.file_path ?? args.path); + html += `
edit ${filePath === null ? invalidArg : escapeHtml(shortenPath(filePath || ''))}
`; + + if (result?.details?.diff) { + const diffLines = result.details.diff.split('\n'); + html += '
'; + for (const line of diffLines) { + const cls = line.match(/^\+/) ? 'diff-added' : line.match(/^-/) ? 'diff-removed' : 'diff-context'; + html += `
${escapeHtml(replaceTabs(line))}
`; + } + html += '
'; + } else if (result) { + const output = getResultText().trim(); + if (output) html += `
${escapeHtml(output)}
`; + } + break; + } + case 'ls': { + const dirPath = str(args.path); + const limit = args.limit; + + let pathHtml = dirPath === null ? invalidArg : escapeHtml(shortenPath(dirPath || '.')); + if (limit !== undefined) { + pathHtml += ` (limit ${escapeHtml(String(limit))})`; + } + + html += `
ls ${pathHtml}
`; + if (result) { + const output = getResultText().trim(); + if (output) html += formatExpandableOutput(output, 20); + } + break; + } + default: { + // Check for pre-rendered custom tool HTML + const rendered = renderedTools?.[call.id]; + if (rendered?.callHtml || rendered?.resultHtmlCollapsed || rendered?.resultHtmlExpanded) { + // Custom tool with pre-rendered HTML from TUI renderer + if (rendered.callHtml) { + html += `
${rendered.callHtml}
`; + } else { + html += `
${escapeHtml(name)}
`; + } + + if (rendered.resultHtmlCollapsed && rendered.resultHtmlExpanded && rendered.resultHtmlCollapsed !== rendered.resultHtmlExpanded) { + // Both collapsed and expanded differ - render expandable section + html += ``; + } else if (rendered.resultHtmlExpanded) { + // Only expanded exists (or collapsed is identical) - show directly + html += `
${rendered.resultHtmlExpanded}
`; + } else if (result) { + // No pre-rendered result HTML - fallback to JSON + const output = getResultText(); + if (output) html += formatExpandableOutput(output, 10); + } + } else { + // Fallback to JSON display (existing behavior) + html += `
${escapeHtml(name)}
`; + html += `
${escapeHtml(JSON.stringify(args, null, 2))}
`; + if (result) { + const output = getResultText(); + if (output) html += formatExpandableOutput(output, 10); + } + } + } + } + + html += '
'; + return html; + } + + /** + * Download the session data as a JSONL file. + * Reconstructs the original format: header line + entry lines. + */ + window.downloadSessionJson = function() { + // Build JSONL content: header first, then all entries + const lines = []; + if (header) { + lines.push(JSON.stringify({ type: 'header', ...header })); + } + for (const entry of entries) { + lines.push(JSON.stringify(entry)); + } + const jsonlContent = lines.join('\n'); + + // Create download + const blob = new Blob([jsonlContent], { type: 'application/x-ndjson' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `${header?.id || 'session'}.jsonl`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + } + + /** + * Build a shareable URL for a specific message. + * URL format: base?gistId&leafId=&targetId= + */ + function buildShareUrl(entryId) { + // Check for injected base URL (used when loaded in iframe via srcdoc) + const baseUrlMeta = document.querySelector('meta[name="pi-share-base-url"]'); + const baseUrl = baseUrlMeta ? baseUrlMeta.content : window.location.href.split('?')[0]; + + const url = new URL(window.location.href); + // Find the gist ID (first query param without value, e.g., ?abc123) + const gistId = Array.from(url.searchParams.keys()).find(k => !url.searchParams.get(k)); + + // Build the share URL + const params = new URLSearchParams(); + params.set('leafId', currentLeafId); + params.set('targetId', entryId); + + // If we have an injected base URL (iframe context), use it directly + if (baseUrlMeta) { + return `${baseUrl}&${params.toString()}`; + } + + // Otherwise build from current location (direct file access) + url.search = gistId ? `?${gistId}&${params.toString()}` : `?${params.toString()}`; + return url.toString(); + } + + /** + * Copy text to clipboard with visual feedback. + * Uses navigator.clipboard with fallback to execCommand for HTTP contexts. + */ + async function copyToClipboard(text, button) { + let success = false; + try { + if (navigator.clipboard && navigator.clipboard.writeText) { + await navigator.clipboard.writeText(text); + success = true; + } + } catch (err) { + // Clipboard API failed, try fallback + } + + // Fallback for HTTP or when Clipboard API is unavailable + if (!success) { + try { + const textarea = document.createElement('textarea'); + textarea.value = text; + textarea.style.position = 'fixed'; + textarea.style.opacity = '0'; + document.body.appendChild(textarea); + textarea.select(); + success = document.execCommand('copy'); + document.body.removeChild(textarea); + } catch (err) { + console.error('Failed to copy:', err); + } + } + + if (success && button) { + const originalHtml = button.innerHTML; + button.innerHTML = '✓'; + button.classList.add('copied'); + setTimeout(() => { + button.innerHTML = originalHtml; + button.classList.remove('copied'); + }, 1500); + } + } + + /** + * Render the copy-link button HTML for a message. + */ + function renderCopyLinkButton(entryId) { + return ``; + } + + function renderEntry(entry) { + const ts = formatTimestamp(entry.timestamp); + const tsHtml = ts ? `
${ts}
` : ''; + const entryDomId = `entry-${escapeHtml(entry.id)}`; + const copyBtnHtml = renderCopyLinkButton(entry.id); + + if (entry.type === 'message') { + const msg = entry.message; + + if (msg.role === 'user') { + const content = msg.content; + const text = typeof content === 'string' ? content : + content.filter(c => c.type === 'text').map(c => c.text).join('\n'); + const skillBlock = parseSkillBlock(text); + + if (skillBlock) { + // Collect images from content array + const images = Array.isArray(content) ? content.filter(c => c.type === 'image') : []; + const hasUserContent = skillBlock.userMessage || images.length > 0; + let html = `
${copyBtnHtml}${tsHtml}`; + + // Skill invocation (collapsed by default, click to expand) + html += `
+
[skill] ${escapeHtml(skillBlock.name)}
+
${escapeHtml(skillBlock.name)} (click to expand)
+
${safeMarkedParse(skillBlock.content)}
+
`; + + // User message (separate block if present) + if (hasUserContent) { + html += '
'; + if (images.length > 0) { + html += '
'; + for (const img of images) { + html += ``; + } + html += '
'; + } + if (skillBlock.userMessage) { + html += `
${safeMarkedParse(skillBlock.userMessage)}
`; + } + html += '
'; + } + + html += '
'; + return html; + } + + // No skill block - normal user message + let html = `
${copyBtnHtml}${tsHtml}`; + + if (Array.isArray(content)) { + const images = content.filter(c => c.type === 'image'); + if (images.length > 0) { + html += '
'; + for (const img of images) { + html += ``; + } + html += '
'; + } + } + + if (text.trim()) { + html += `
${safeMarkedParse(text)}
`; + } + html += '
'; + return html; + } + + if (msg.role === 'assistant') { + let html = `
${copyBtnHtml}${tsHtml}`; + + for (const block of msg.content) { + if (block.type === 'text' && block.text.trim()) { + html += `
${safeMarkedParse(block.text)}
`; + } else if (block.type === 'thinking' && block.thinking.trim()) { + html += `
+
${escapeHtml(block.thinking)}
+
Thinking ...
+
`; + } + } + + for (const block of msg.content) { + if (block.type === 'toolCall') { + html += renderToolCall(block); + } + } + + if (msg.stopReason === 'aborted') { + html += '
Aborted
'; + } else if (msg.stopReason === 'error') { + html += `
Error: ${escapeHtml(msg.errorMessage || 'Unknown error')}
`; + } + + html += '
'; + return html; + } + + if (msg.role === 'bashExecution') { + const isError = msg.cancelled || (msg.exitCode !== 0 && msg.exitCode !== null); + let html = `
${tsHtml}`; + html += `
$ ${escapeHtml(msg.command)}
`; + if (msg.output) html += formatExpandableOutput(msg.output, 10); + if (msg.cancelled) { + html += '
(cancelled)
'; + } else if (msg.exitCode !== 0 && msg.exitCode !== null) { + html += `
(exit ${msg.exitCode})
`; + } + html += '
'; + return html; + } + + if (msg.role === 'toolResult') return ''; + } + + if (entry.type === 'model_change') { + return `
${tsHtml}Switched to model: ${escapeHtml(entry.provider)}/${escapeHtml(entry.modelId)}
`; + } + + if (entry.type === 'compaction') { + return `
+
[compaction]
+
Compacted from ${entry.tokensBefore.toLocaleString()} tokens
+
Compacted from ${entry.tokensBefore.toLocaleString()} tokens\n\n${escapeHtml(entry.summary)}
+
`; + } + + if (entry.type === 'branch_summary') { + return `
${tsHtml} +
Branch Summary
+
${safeMarkedParse(entry.summary)}
+
`; + } + + if (entry.type === 'custom_message' && entry.display) { + return `
${tsHtml} +
[${escapeHtml(entry.customType)}]
+
${safeMarkedParse(typeof entry.content === 'string' ? entry.content : JSON.stringify(entry.content))}
+
`; + } + + return ''; + } + + // ============================================================ + // HEADER / STATS + // ============================================================ + + function computeStats(entryList) { + let userMessages = 0, assistantMessages = 0, toolResults = 0; + let customMessages = 0, compactions = 0, branchSummaries = 0, toolCalls = 0; + const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }; + const cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }; + const models = new Set(); + + for (const entry of entryList) { + if (entry.type === 'message') { + const msg = entry.message; + if (msg.role === 'user') userMessages++; + if (msg.role === 'assistant') { + assistantMessages++; + if (msg.model) models.add(msg.provider ? `${msg.provider}/${msg.model}` : msg.model); + if (msg.usage) { + tokens.input += msg.usage.input || 0; + tokens.output += msg.usage.output || 0; + tokens.cacheRead += msg.usage.cacheRead || 0; + tokens.cacheWrite += msg.usage.cacheWrite || 0; + if (msg.usage.cost) { + cost.input += msg.usage.cost.input || 0; + cost.output += msg.usage.cost.output || 0; + cost.cacheRead += msg.usage.cost.cacheRead || 0; + cost.cacheWrite += msg.usage.cost.cacheWrite || 0; + } + } + toolCalls += msg.content.filter(c => c.type === 'toolCall').length; + } + if (msg.role === 'toolResult') toolResults++; + } else if (entry.type === 'compaction') { + compactions++; + } else if (entry.type === 'branch_summary') { + branchSummaries++; + } else if (entry.type === 'custom_message') { + customMessages++; + } + } + + return { userMessages, assistantMessages, toolResults, customMessages, compactions, branchSummaries, toolCalls, tokens, cost, models: Array.from(models) }; + } + + const globalStats = computeStats(entries); + + function renderHeader() { + const totalCost = globalStats.cost.input + globalStats.cost.output + globalStats.cost.cacheRead + globalStats.cost.cacheWrite; + + const tokenParts = []; + if (globalStats.tokens.input) tokenParts.push(`↑${formatTokens(globalStats.tokens.input)}`); + if (globalStats.tokens.output) tokenParts.push(`↓${formatTokens(globalStats.tokens.output)}`); + if (globalStats.tokens.cacheRead) tokenParts.push(`R${formatTokens(globalStats.tokens.cacheRead)}`); + if (globalStats.tokens.cacheWrite) tokenParts.push(`W${formatTokens(globalStats.tokens.cacheWrite)}`); + + const msgParts = []; + if (globalStats.userMessages) msgParts.push(`${globalStats.userMessages} user`); + if (globalStats.assistantMessages) msgParts.push(`${globalStats.assistantMessages} assistant`); + if (globalStats.toolResults) msgParts.push(`${globalStats.toolResults} tool results`); + if (globalStats.customMessages) msgParts.push(`${globalStats.customMessages} custom`); + if (globalStats.compactions) msgParts.push(`${globalStats.compactions} compactions`); + if (globalStats.branchSummaries) msgParts.push(`${globalStats.branchSummaries} branch summaries`); + + let html = ` +
+

Session: ${escapeHtml(header?.id || 'unknown')}

+
+ T toggle thinking · O toggle tools +
+ + + +
+
+
+
Date:${header?.timestamp ? new Date(header.timestamp).toLocaleString() : 'unknown'}
+
Models:${escapeHtml(globalStats.models.join(', ') || 'unknown')}
+
Messages:${msgParts.join(', ') || '0'}
+
Tool Calls:${globalStats.toolCalls}
+
Tokens:${tokenParts.join(' ') || '0'}
+
Cost:$${totalCost.toFixed(3)}
+
+
`; + + // Render system prompt (user's base prompt, applies to all providers) + if (systemPrompt) { + const lines = systemPrompt.split('\n'); + const previewLines = 10; + if (lines.length > previewLines) { + const preview = lines.slice(0, previewLines).join('\n'); + const remaining = lines.length - previewLines; + html += ``; + } else { + html += `
+
System Prompt
+
${escapeHtml(systemPrompt)}
+
`; + } + } + + if (tools && tools.length > 0) { + html += `
+
Available Tools
+
+ ${tools.map(t => { + const hasParams = t.parameters && typeof t.parameters === 'object' && t.parameters.properties && Object.keys(t.parameters.properties).length > 0; + if (!hasParams) { + return `
${escapeHtml(t.name)} - ${escapeHtml(t.description)}
`; + } + const params = t.parameters; + const properties = params.properties; + const required = params.required || []; + let paramsHtml = ''; + for (const [name, prop] of Object.entries(properties)) { + const isRequired = required.includes(name); + const typeStr = prop.type || 'any'; + const reqLabel = isRequired ? 'required' : 'optional'; + paramsHtml += `
${escapeHtml(name)} ${escapeHtml(typeStr)} ${reqLabel}`; + if (prop.description) { + paramsHtml += `
${escapeHtml(prop.description)}
`; + } + paramsHtml += `
`; + } + return `
${escapeHtml(t.name)} - ${escapeHtml(t.description)}
${paramsHtml}
`; + }).join('')} +
+
`; + } + + return html; + } + + // ============================================================ + // NAVIGATION + // ============================================================ + + // Cache for rendered entry DOM nodes + const entryCache = new Map(); + + function getScrollTargetElementId(entryId) { + const entry = byId.get(entryId); + if (entry?.type === 'message' && entry.message.role === 'toolResult' && entry.message.toolCallId) { + // getElementById() matches the parsed DOM id attribute, whose HTML entities + // were already resolved from the escaped id rendered by renderToolCall(). + return `tool-call-${entry.message.toolCallId}`; + } + return `entry-${entryId}`; + } + + function renderEntryToNode(entry) { + // Check cache first + if (entryCache.has(entry.id)) { + return entryCache.get(entry.id).cloneNode(true); + } + + // Render to HTML string, then parse to node + const html = renderEntry(entry); + if (!html) return null; + + const template = document.createElement('template'); + template.innerHTML = html; + const node = template.content.firstElementChild; + + // Cache the node + if (node) { + entryCache.set(entry.id, node.cloneNode(true)); + } + return node; + } + + function navigateTo(targetId, scrollMode = 'target', scrollToEntryId = null) { + currentLeafId = targetId; + currentTargetId = scrollToEntryId || targetId; + const path = getPath(targetId); + + renderTree(); + + document.getElementById('header-container').innerHTML = renderHeader(); + attachHeaderHandlers(); + + // Build messages using cached DOM nodes + const messagesEl = document.getElementById('messages'); + const fragment = document.createDocumentFragment(); + + for (const entry of path) { + const node = renderEntryToNode(entry); + if (node) { + fragment.appendChild(node); + } + } + + messagesEl.innerHTML = ''; + messagesEl.appendChild(fragment); + + // Attach click handlers for copy-link buttons + messagesEl.querySelectorAll('.copy-link-btn').forEach(btn => { + btn.addEventListener('click', (e) => { + e.stopPropagation(); + const entryId = btn.dataset.entryId; + const shareUrl = buildShareUrl(entryId); + copyToClipboard(shareUrl, btn); + }); + }); + + // Use setTimeout(0) to ensure DOM is fully laid out before scrolling + setTimeout(() => { + const content = document.getElementById('content'); + if (scrollMode === 'bottom') { + content.scrollTop = content.scrollHeight; + } else if (scrollMode === 'target') { + // If scrollToEntryId is provided, scroll to that specific entry. + // Tool result entries are rendered inside their assistant tool-call block, + // so route them to the visible tool-call element instead. + const scrollTargetId = scrollToEntryId || targetId; + const targetEl = document.getElementById(getScrollTargetElementId(scrollTargetId)) || + document.getElementById(`entry-${scrollTargetId}`); + if (targetEl) { + targetEl.scrollIntoView({ block: 'center' }); + // Briefly highlight the target message + if (scrollToEntryId) { + targetEl.classList.add('highlight'); + setTimeout(() => targetEl.classList.remove('highlight'), 2000); + } + } + } + }, 0); + } + + // ============================================================ + // INITIALIZATION + // ============================================================ + + // Configure marked with syntax highlighting and TUI-compatible HTML handling + const strictStrikethroughRegex = /^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/; + + marked.use({ + breaks: true, + gfm: true, + tokenizer: { + // Treat HTML-like input as plain text so tags are shown verbatim, + // matching the TUI markdown renderer. + html() { + return undefined; + }, + tag() { + return undefined; + }, + del(src) { + const match = strictStrikethroughRegex.exec(src); + if (!match) return undefined; + return { + type: 'del', + raw: match[0], + text: match[2], + tokens: this.lexer.inlineTokens(match[2]) + }; + } + }, + renderer: { + // Sanitize link URLs with a scheme allow-list. Browsers strip C0 + // controls from schemes, so strip them before checking and emitting. + link(token) { + const href = sanitizeMarkdownUrl(token.href); + if (href === null) { + return this.parser.parseInline(token.tokens); + } + let out = ''; + return out; + }, + // Sanitize image src URLs with the same scheme allow-list. + image(token) { + const href = sanitizeMarkdownUrl(token.href); + if (href === null) { + return escapeHtml(token.text || ''); + } + let out = '' + escapeHtml(token.text || '') + '${highlighted}`; + }, + // Inline code: escape HTML + codespan(token) { + return `${escapeHtml(token.text)}`; + } + } + }); + + // Simple marked parse (escaping handled in renderers) + function safeMarkedParse(text) { + return marked.parse(text); + } + + // Search input + const searchInput = document.getElementById('tree-search'); + searchInput.addEventListener('input', (e) => { + searchQuery = e.target.value; + forceTreeRerender(); + }); + + // Filter buttons + document.querySelectorAll('.filter-btn').forEach(btn => { + btn.addEventListener('click', () => { + document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active')); + btn.classList.add('active'); + filterMode = btn.dataset.filter; + forceTreeRerender(); + }); + }); + + // Sidebar toggle + const sidebar = document.getElementById('sidebar'); + const overlay = document.getElementById('sidebar-overlay'); + const hamburger = document.getElementById('hamburger'); + const sidebarResizer = document.getElementById('sidebar-resizer'); + const SIDEBAR_WIDTH_STORAGE_KEY = 'pi-share:v1:sidebar-width'; + const MIN_CONTENT_WIDTH = 320; + + function isMobileLayout() { + return window.matchMedia('(max-width: 900px)').matches; + } + + function getSidebarBounds() { + const rootStyles = getComputedStyle(document.documentElement); + const minWidth = parseFloat(rootStyles.getPropertyValue('--sidebar-min-width')) || 240; + const maxWidth = parseFloat(rootStyles.getPropertyValue('--sidebar-max-width')) || 720; + const viewportMaxWidth = window.innerWidth - MIN_CONTENT_WIDTH; + return { + minWidth, + maxWidth: Math.max(minWidth, Math.min(maxWidth, viewportMaxWidth)) + }; + } + + function clampSidebarWidth(width) { + const { minWidth, maxWidth } = getSidebarBounds(); + return Math.max(minWidth, Math.min(maxWidth, width)); + } + + function applySidebarWidth(width) { + document.documentElement.style.setProperty('--sidebar-width', `${Math.round(clampSidebarWidth(width))}px`); + } + + function loadSidebarWidth() { + try { + const raw = localStorage.getItem(SIDEBAR_WIDTH_STORAGE_KEY); + if (raw === null) return null; + const width = Number(raw); + return Number.isFinite(width) ? width : null; + } catch { + return null; + } + } + + function saveSidebarWidth(width) { + try { + localStorage.setItem(SIDEBAR_WIDTH_STORAGE_KEY, String(Math.round(clampSidebarWidth(width)))); + } catch { + // Ignore storage failures (e.g. private browsing restrictions) + } + } + + function setupSidebarResize() { + const savedWidth = loadSidebarWidth(); + if (savedWidth !== null) { + applySidebarWidth(savedWidth); + } + + if (!sidebarResizer) return; + + let cleanupDrag = null; + + const stopDrag = (pointerId) => { + if (cleanupDrag) { + cleanupDrag(pointerId); + cleanupDrag = null; + } + }; + + sidebarResizer.addEventListener('pointerdown', (e) => { + if (isMobileLayout()) return; + + e.preventDefault(); + const startX = e.clientX; + const startWidth = sidebar.getBoundingClientRect().width; + document.body.classList.add('sidebar-resizing'); + sidebarResizer.setPointerCapture?.(e.pointerId); + + const onPointerMove = (event) => { + applySidebarWidth(startWidth + (event.clientX - startX)); + }; + + cleanupDrag = (pointerIdToRelease) => { + document.body.classList.remove('sidebar-resizing'); + sidebarResizer.releasePointerCapture?.(pointerIdToRelease); + window.removeEventListener('pointermove', onPointerMove); + window.removeEventListener('pointerup', onPointerUp); + window.removeEventListener('pointercancel', onPointerCancel); + saveSidebarWidth(sidebar.getBoundingClientRect().width); + }; + + const onPointerUp = (event) => stopDrag(event.pointerId); + const onPointerCancel = (event) => stopDrag(event.pointerId); + + window.addEventListener('pointermove', onPointerMove); + window.addEventListener('pointerup', onPointerUp); + window.addEventListener('pointercancel', onPointerCancel); + }); + + sidebarResizer.addEventListener('dblclick', () => { + if (isMobileLayout()) return; + applySidebarWidth(400); + saveSidebarWidth(400); + }); + + window.addEventListener('resize', () => { + if (isMobileLayout()) return; + applySidebarWidth(sidebar.getBoundingClientRect().width); + }); + } + + setupSidebarResize(); + + hamburger.addEventListener('click', () => { + sidebar.classList.add('open'); + overlay.classList.add('open'); + hamburger.style.display = 'none'; + }); + + const closeSidebar = () => { + sidebar.classList.remove('open'); + overlay.classList.remove('open'); + hamburger.style.display = ''; + }; + + overlay.addEventListener('click', closeSidebar); + document.getElementById('sidebar-close').addEventListener('click', closeSidebar); + + // Toggle states + let thinkingExpanded = true; + let toolOutputsExpanded = false; + + const toggleThinking = () => { + thinkingExpanded = !thinkingExpanded; + document.querySelectorAll('.thinking-text').forEach(el => { + el.style.display = thinkingExpanded ? '' : 'none'; + }); + document.querySelectorAll('.thinking-collapsed').forEach(el => { + el.style.display = thinkingExpanded ? 'none' : 'block'; + }); + }; + + const toggleToolOutputs = () => { + toolOutputsExpanded = !toolOutputsExpanded; + document.querySelectorAll('.tool-output.expandable').forEach(el => { + el.classList.toggle('expanded', toolOutputsExpanded); + }); + document.querySelectorAll('.compaction').forEach(el => { + el.classList.toggle('expanded', toolOutputsExpanded); + }); + document.querySelectorAll('.skill-invocation').forEach(el => { + el.classList.toggle('expanded', toolOutputsExpanded); + }); + }; + + const attachHeaderHandlers = () => { + document.querySelector('[data-action="toggle-thinking"]')?.addEventListener('click', toggleThinking); + document.querySelector('[data-action="toggle-tools"]')?.addEventListener('click', toggleToolOutputs); + }; + + const isEditableTarget = (element) => { + if (!element) return false; + const tagName = element.tagName; + if (tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT' || tagName === 'BUTTON') { + return true; + } + return element.isContentEditable || Boolean(element.closest?.('[contenteditable="true"]')); + }; + + // Keyboard shortcuts + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + searchInput.value = ''; + searchQuery = ''; + navigateTo(leafId, 'bottom'); + } + + if (isEditableTarget(document.activeElement)) { + return; + } + + const key = e.key.toLowerCase(); + if (key === 't') { + e.preventDefault(); + toggleThinking(); + } else if (key === 'o') { + e.preventDefault(); + toggleToolOutputs(); + } + }); + + // Initial render + // If URL has targetId, scroll to that specific message; otherwise stay at top + if (leafId) { + if (urlTargetId && byId.has(urlTargetId)) { + // Deep link: navigate to leaf and scroll to target message + navigateTo(leafId, 'target', urlTargetId); + } else { + navigateTo(leafId, 'none'); + } + } else if (entries.length > 0) { + // Fallback: use last entry if no leafId + navigateTo(entries[entries.length - 1].id, 'none'); + } + })(); diff --git a/dist/core/export-html/tool-renderer.d.ts b/dist/core/export-html/tool-renderer.d.ts new file mode 100644 index 0000000..f4ebbbf --- /dev/null +++ b/dist/core/export-html/tool-renderer.d.ts @@ -0,0 +1,34 @@ +/** + * Tool HTML renderer for custom tools in HTML export. + * + * Renders custom tool calls and results to HTML by invoking their TUI renderers + * and converting the ANSI output to HTML. + */ +import type { Theme } from "../../modes/interactive/theme/theme.ts"; +import type { ToolDefinition } from "../extensions/types.ts"; +export interface ToolHtmlRendererDeps { + /** Function to look up tool definition by name */ + getToolDefinition: (name: string) => ToolDefinition | undefined; + /** Theme for styling */ + theme: Theme; + /** Working directory for render context */ + cwd: string; + /** Terminal width for rendering (default: 100) */ + width?: number; +} +export interface ToolHtmlRenderer { + /** Render a tool call to HTML. Returns undefined if tool has no custom renderer. */ + renderCall(toolCallId: string, toolName: string, args: unknown): string | undefined; + /** Render a tool result to collapsed/expanded HTML. Returns undefined if tool has no custom renderer. */ + renderResult(toolCallId: string, toolName: string, result: Array<{ + type: string; + text?: string; + data?: string; + mimeType?: string; + }>, details: unknown, isError: boolean): { + collapsed?: string; + expanded?: string; + } | undefined; +} +export declare function createToolHtmlRenderer(deps: ToolHtmlRendererDeps): ToolHtmlRenderer; +//# sourceMappingURL=tool-renderer.d.ts.map \ No newline at end of file diff --git a/dist/core/export-html/tool-renderer.d.ts.map b/dist/core/export-html/tool-renderer.d.ts.map new file mode 100644 index 0000000..9142c6c --- /dev/null +++ b/dist/core/export-html/tool-renderer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tool-renderer.d.ts","sourceRoot":"","sources":["../../../src/core/export-html/tool-renderer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AACpE,OAAO,KAAK,EAAE,cAAc,EAAqB,MAAM,wBAAwB,CAAC;AAGhF,MAAM,WAAW,oBAAoB;IACpC,kDAAkD;IAClD,iBAAiB,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,cAAc,GAAG,SAAS,CAAC;IAChE,wBAAwB;IACxB,KAAK,EAAE,KAAK,CAAC;IACb,2CAA2C;IAC3C,GAAG,EAAE,MAAM,CAAC;IACZ,kDAAkD;IAClD,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,gBAAgB;IAChC,oFAAoF;IACpF,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAAC;IACpF,yGAAyG;IACzG,YAAY,CACX,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,EAChF,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,OAAO,GACd;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;CACzD;AAsBD,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,oBAAoB,GAAG,gBAAgB,CAkHnF","sourcesContent":["/**\n * Tool HTML renderer for custom tools in HTML export.\n *\n * Renders custom tool calls and results to HTML by invoking their TUI renderers\n * and converting the ANSI output to HTML.\n */\n\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderContext } from \"../extensions/types.ts\";\nimport { ansiLinesToHtml } from \"./ansi-to-html.ts\";\n\nexport interface ToolHtmlRendererDeps {\n\t/** Function to look up tool definition by name */\n\tgetToolDefinition: (name: string) => ToolDefinition | undefined;\n\t/** Theme for styling */\n\ttheme: Theme;\n\t/** Working directory for render context */\n\tcwd: string;\n\t/** Terminal width for rendering (default: 100) */\n\twidth?: number;\n}\n\nexport interface ToolHtmlRenderer {\n\t/** Render a tool call to HTML. Returns undefined if tool has no custom renderer. */\n\trenderCall(toolCallId: string, toolName: string, args: unknown): string | undefined;\n\t/** Render a tool result to collapsed/expanded HTML. Returns undefined if tool has no custom renderer. */\n\trenderResult(\n\t\ttoolCallId: string,\n\t\ttoolName: string,\n\t\tresult: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,\n\t\tdetails: unknown,\n\t\tisError: boolean,\n\t): { collapsed?: string; expanded?: string } | undefined;\n}\n\n/**\n * Create a tool HTML renderer.\n *\n * The renderer looks up tool definitions and invokes their renderCall/renderResult\n * methods, converting the resulting TUI Component output (ANSI) to HTML.\n */\nconst ANSI_ESCAPE_REGEX = /\\x1b\\[[\\d;]*m/g;\n\nfunction isBlankRenderedLine(line: string): boolean {\n\treturn line.replace(ANSI_ESCAPE_REGEX, \"\").trim().length === 0;\n}\n\nfunction trimRenderedResultLines(lines: string[]): string[] {\n\tlet start = 0;\n\tlet end = lines.length;\n\twhile (start < end && isBlankRenderedLine(lines[start])) start++;\n\twhile (end > start && isBlankRenderedLine(lines[end - 1])) end--;\n\treturn lines.slice(start, end);\n}\n\nexport function createToolHtmlRenderer(deps: ToolHtmlRendererDeps): ToolHtmlRenderer {\n\tconst { getToolDefinition, theme, cwd, width = 100 } = deps;\n\n\tconst renderedCallComponents = new Map();\n\tconst renderedResultComponents = new Map();\n\tconst renderedStates = new Map();\n\tconst renderedArgs = new Map();\n\n\tconst getState = (toolCallId: string): any => {\n\t\tlet state = renderedStates.get(toolCallId);\n\t\tif (!state) {\n\t\t\tstate = {};\n\t\t\trenderedStates.set(toolCallId, state);\n\t\t}\n\t\treturn state;\n\t};\n\n\tconst createRenderContext = (\n\t\ttoolCallId: string,\n\t\tlastComponent: Component | undefined,\n\t\texpanded: boolean,\n\t\tisPartial: boolean,\n\t\tisError: boolean,\n\t): ToolRenderContext => {\n\t\treturn {\n\t\t\targs: renderedArgs.get(toolCallId),\n\t\t\ttoolCallId,\n\t\t\tinvalidate: () => {},\n\t\t\tlastComponent,\n\t\t\tstate: getState(toolCallId),\n\t\t\tcwd,\n\t\t\texecutionStarted: true,\n\t\t\targsComplete: true,\n\t\t\tisPartial,\n\t\t\texpanded,\n\t\t\tshowImages: false,\n\t\t\tisError,\n\t\t};\n\t};\n\n\treturn {\n\t\trenderCall(toolCallId: string, toolName: string, args: unknown): string | undefined {\n\t\t\ttry {\n\t\t\t\trenderedArgs.set(toolCallId, args);\n\t\t\t\tconst toolDef = getToolDefinition(toolName);\n\t\t\t\tif (!toolDef?.renderCall) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tconst component = toolDef.renderCall(\n\t\t\t\t\targs,\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedCallComponents.get(toolCallId), false, true, false),\n\t\t\t\t);\n\t\t\t\trenderedCallComponents.set(toolCallId, component);\n\t\t\t\tconst lines = component.render(width);\n\t\t\t\treturn ansiLinesToHtml(lines);\n\t\t\t} catch {\n\t\t\t\t// On error, return undefined so HTML export can fall back to structured result rendering\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\n\t\trenderResult(\n\t\t\ttoolCallId: string,\n\t\t\ttoolName: string,\n\t\t\tresult: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,\n\t\t\tdetails: unknown,\n\t\t\tisError: boolean,\n\t\t): { collapsed?: string; expanded?: string } | undefined {\n\t\t\ttry {\n\t\t\t\tconst toolDef = getToolDefinition(toolName);\n\t\t\t\tif (!toolDef?.renderResult) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\t// Build AgentToolResult from content array\n\t\t\t\t// Cast content since session storage uses generic object types\n\t\t\t\tconst agentToolResult = {\n\t\t\t\t\tcontent: result as (TextContent | ImageContent)[],\n\t\t\t\t\tdetails,\n\t\t\t\t\tisError,\n\t\t\t\t};\n\n\t\t\t\t// Render collapsed\n\t\t\t\tconst collapsedComponent = toolDef.renderResult(\n\t\t\t\t\tagentToolResult,\n\t\t\t\t\t{ expanded: false, isPartial: false },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedResultComponents.get(toolCallId), false, false, isError),\n\t\t\t\t);\n\t\t\t\trenderedResultComponents.set(toolCallId, collapsedComponent);\n\t\t\t\tconst collapsed = ansiLinesToHtml(trimRenderedResultLines(collapsedComponent.render(width)));\n\n\t\t\t\t// Render expanded\n\t\t\t\tconst expandedComponent = toolDef.renderResult(\n\t\t\t\t\tagentToolResult,\n\t\t\t\t\t{ expanded: true, isPartial: false },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedResultComponents.get(toolCallId), true, false, isError),\n\t\t\t\t);\n\t\t\t\trenderedResultComponents.set(toolCallId, expandedComponent);\n\t\t\t\tconst expanded = ansiLinesToHtml(trimRenderedResultLines(expandedComponent.render(width)));\n\n\t\t\t\treturn {\n\t\t\t\t\t...(collapsed && collapsed !== expanded ? { collapsed } : {}),\n\t\t\t\t\texpanded,\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\t// On error, return undefined so HTML export can fall back to structured result rendering\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/export-html/tool-renderer.js b/dist/core/export-html/tool-renderer.js new file mode 100644 index 0000000..9bd365b --- /dev/null +++ b/dist/core/export-html/tool-renderer.js @@ -0,0 +1,108 @@ +/** + * Tool HTML renderer for custom tools in HTML export. + * + * Renders custom tool calls and results to HTML by invoking their TUI renderers + * and converting the ANSI output to HTML. + */ +import { ansiLinesToHtml } from "./ansi-to-html.js"; +/** + * Create a tool HTML renderer. + * + * The renderer looks up tool definitions and invokes their renderCall/renderResult + * methods, converting the resulting TUI Component output (ANSI) to HTML. + */ +const ANSI_ESCAPE_REGEX = /\x1b\[[\d;]*m/g; +function isBlankRenderedLine(line) { + return line.replace(ANSI_ESCAPE_REGEX, "").trim().length === 0; +} +function trimRenderedResultLines(lines) { + let start = 0; + let end = lines.length; + while (start < end && isBlankRenderedLine(lines[start])) + start++; + while (end > start && isBlankRenderedLine(lines[end - 1])) + end--; + return lines.slice(start, end); +} +export function createToolHtmlRenderer(deps) { + const { getToolDefinition, theme, cwd, width = 100 } = deps; + const renderedCallComponents = new Map(); + const renderedResultComponents = new Map(); + const renderedStates = new Map(); + const renderedArgs = new Map(); + const getState = (toolCallId) => { + let state = renderedStates.get(toolCallId); + if (!state) { + state = {}; + renderedStates.set(toolCallId, state); + } + return state; + }; + const createRenderContext = (toolCallId, lastComponent, expanded, isPartial, isError) => { + return { + args: renderedArgs.get(toolCallId), + toolCallId, + invalidate: () => { }, + lastComponent, + state: getState(toolCallId), + cwd, + executionStarted: true, + argsComplete: true, + isPartial, + expanded, + showImages: false, + isError, + }; + }; + return { + renderCall(toolCallId, toolName, args) { + try { + renderedArgs.set(toolCallId, args); + const toolDef = getToolDefinition(toolName); + if (!toolDef?.renderCall) { + return undefined; + } + const component = toolDef.renderCall(args, theme, createRenderContext(toolCallId, renderedCallComponents.get(toolCallId), false, true, false)); + renderedCallComponents.set(toolCallId, component); + const lines = component.render(width); + return ansiLinesToHtml(lines); + } + catch { + // On error, return undefined so HTML export can fall back to structured result rendering + return undefined; + } + }, + renderResult(toolCallId, toolName, result, details, isError) { + try { + const toolDef = getToolDefinition(toolName); + if (!toolDef?.renderResult) { + return undefined; + } + // Build AgentToolResult from content array + // Cast content since session storage uses generic object types + const agentToolResult = { + content: result, + details, + isError, + }; + // Render collapsed + const collapsedComponent = toolDef.renderResult(agentToolResult, { expanded: false, isPartial: false }, theme, createRenderContext(toolCallId, renderedResultComponents.get(toolCallId), false, false, isError)); + renderedResultComponents.set(toolCallId, collapsedComponent); + const collapsed = ansiLinesToHtml(trimRenderedResultLines(collapsedComponent.render(width))); + // Render expanded + const expandedComponent = toolDef.renderResult(agentToolResult, { expanded: true, isPartial: false }, theme, createRenderContext(toolCallId, renderedResultComponents.get(toolCallId), true, false, isError)); + renderedResultComponents.set(toolCallId, expandedComponent); + const expanded = ansiLinesToHtml(trimRenderedResultLines(expandedComponent.render(width))); + return { + ...(collapsed && collapsed !== expanded ? { collapsed } : {}), + expanded, + }; + } + catch { + // On error, return undefined so HTML export can fall back to structured result rendering + return undefined; + } + }, + }; +} +//# sourceMappingURL=tool-renderer.js.map \ No newline at end of file diff --git a/dist/core/export-html/tool-renderer.js.map b/dist/core/export-html/tool-renderer.js.map new file mode 100644 index 0000000..d9fc84a --- /dev/null +++ b/dist/core/export-html/tool-renderer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tool-renderer.js","sourceRoot":"","sources":["../../../src/core/export-html/tool-renderer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AA0BpD;;;;;GAKG;AACH,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;AAE3C,SAAS,mBAAmB,CAAC,IAAY,EAAW;IACnD,OAAO,IAAI,CAAC,OAAO,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC,CAAC;AAAA,CAC/D;AAED,SAAS,uBAAuB,CAAC,KAAe,EAAY;IAC3D,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC;IACvB,OAAO,KAAK,GAAG,GAAG,IAAI,mBAAmB,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAAE,KAAK,EAAE,CAAC;IACjE,OAAO,GAAG,GAAG,KAAK,IAAI,mBAAmB,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CA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,KAAK,EACL,mBAAmB,CAAC,UAAU,EAAE,wBAAwB,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,CAChG,CAAC;gBACF,wBAAwB,CAAC,GAAG,CAAC,UAAU,EAAE,kBAAkB,CAAC,CAAC;gBAC7D,MAAM,SAAS,GAAG,eAAe,CAAC,uBAAuB,CAAC,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBAE7F,kBAAkB;gBAClB,MAAM,iBAAiB,GAAG,OAAO,CAAC,YAAY,CAC7C,eAAe,EACf,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,EACpC,KAAK,EACL,mBAAmB,CAAC,UAAU,EAAE,wBAAwB,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAC/F,CAAC;gBACF,wBAAwB,CAAC,GAAG,CAAC,UAAU,EAAE,iBAAiB,CAAC,CAAC;gBAC5D,MAAM,QAAQ,GAAG,eAAe,CAAC,uBAAuB,CAAC,iBAAiB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBAE3F,OAAO;oBACN,GAAG,CAAC,SAAS,IAAI,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBAC7D,QAAQ;iBACR,CAAC;YACH,CAAC;YAAC,MAAM,CAAC;gBACR,yFAAyF;gBACzF,OAAO,SAAS,CAAC;YAClB,CAAC;QAAA,CACD;KACD,CAAC;AAAA,CACF","sourcesContent":["/**\n * Tool HTML renderer for custom tools in HTML export.\n *\n * Renders custom tool calls and results to HTML by invoking their TUI renderers\n * and converting the ANSI output to HTML.\n */\n\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderContext } from \"../extensions/types.ts\";\nimport { ansiLinesToHtml } from \"./ansi-to-html.ts\";\n\nexport interface ToolHtmlRendererDeps {\n\t/** Function to look up tool definition by name */\n\tgetToolDefinition: (name: string) => ToolDefinition | undefined;\n\t/** Theme for styling */\n\ttheme: Theme;\n\t/** Working directory for render context */\n\tcwd: string;\n\t/** Terminal width for rendering (default: 100) */\n\twidth?: number;\n}\n\nexport interface ToolHtmlRenderer {\n\t/** Render a tool call to HTML. Returns undefined if tool has no custom renderer. */\n\trenderCall(toolCallId: string, toolName: string, args: unknown): string | undefined;\n\t/** Render a tool result to collapsed/expanded HTML. Returns undefined if tool has no custom renderer. */\n\trenderResult(\n\t\ttoolCallId: string,\n\t\ttoolName: string,\n\t\tresult: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,\n\t\tdetails: unknown,\n\t\tisError: boolean,\n\t): { collapsed?: string; expanded?: string } | undefined;\n}\n\n/**\n * Create a tool HTML renderer.\n *\n * The renderer looks up tool definitions and invokes their renderCall/renderResult\n * methods, converting the resulting TUI Component output (ANSI) to HTML.\n */\nconst ANSI_ESCAPE_REGEX = /\\x1b\\[[\\d;]*m/g;\n\nfunction isBlankRenderedLine(line: string): boolean {\n\treturn line.replace(ANSI_ESCAPE_REGEX, \"\").trim().length === 0;\n}\n\nfunction trimRenderedResultLines(lines: string[]): string[] {\n\tlet start = 0;\n\tlet end = lines.length;\n\twhile (start < end && isBlankRenderedLine(lines[start])) start++;\n\twhile (end > start && isBlankRenderedLine(lines[end - 1])) end--;\n\treturn lines.slice(start, end);\n}\n\nexport function createToolHtmlRenderer(deps: ToolHtmlRendererDeps): ToolHtmlRenderer {\n\tconst { getToolDefinition, theme, cwd, width = 100 } = deps;\n\n\tconst renderedCallComponents = new Map();\n\tconst renderedResultComponents = new Map();\n\tconst renderedStates = new Map();\n\tconst renderedArgs = new Map();\n\n\tconst getState = (toolCallId: string): any => {\n\t\tlet state = renderedStates.get(toolCallId);\n\t\tif (!state) {\n\t\t\tstate = {};\n\t\t\trenderedStates.set(toolCallId, state);\n\t\t}\n\t\treturn state;\n\t};\n\n\tconst createRenderContext = (\n\t\ttoolCallId: string,\n\t\tlastComponent: Component | undefined,\n\t\texpanded: boolean,\n\t\tisPartial: boolean,\n\t\tisError: boolean,\n\t): ToolRenderContext => {\n\t\treturn {\n\t\t\targs: renderedArgs.get(toolCallId),\n\t\t\ttoolCallId,\n\t\t\tinvalidate: () => {},\n\t\t\tlastComponent,\n\t\t\tstate: getState(toolCallId),\n\t\t\tcwd,\n\t\t\texecutionStarted: true,\n\t\t\targsComplete: true,\n\t\t\tisPartial,\n\t\t\texpanded,\n\t\t\tshowImages: false,\n\t\t\tisError,\n\t\t};\n\t};\n\n\treturn {\n\t\trenderCall(toolCallId: string, toolName: string, args: unknown): string | undefined {\n\t\t\ttry {\n\t\t\t\trenderedArgs.set(toolCallId, args);\n\t\t\t\tconst toolDef = getToolDefinition(toolName);\n\t\t\t\tif (!toolDef?.renderCall) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tconst component = toolDef.renderCall(\n\t\t\t\t\targs,\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedCallComponents.get(toolCallId), false, true, false),\n\t\t\t\t);\n\t\t\t\trenderedCallComponents.set(toolCallId, component);\n\t\t\t\tconst lines = component.render(width);\n\t\t\t\treturn ansiLinesToHtml(lines);\n\t\t\t} catch {\n\t\t\t\t// On error, return undefined so HTML export can fall back to structured result rendering\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\n\t\trenderResult(\n\t\t\ttoolCallId: string,\n\t\t\ttoolName: string,\n\t\t\tresult: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,\n\t\t\tdetails: unknown,\n\t\t\tisError: boolean,\n\t\t): { collapsed?: string; expanded?: string } | undefined {\n\t\t\ttry {\n\t\t\t\tconst toolDef = getToolDefinition(toolName);\n\t\t\t\tif (!toolDef?.renderResult) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\t// Build AgentToolResult from content array\n\t\t\t\t// Cast content since session storage uses generic object types\n\t\t\t\tconst agentToolResult = {\n\t\t\t\t\tcontent: result as (TextContent | ImageContent)[],\n\t\t\t\t\tdetails,\n\t\t\t\t\tisError,\n\t\t\t\t};\n\n\t\t\t\t// Render collapsed\n\t\t\t\tconst collapsedComponent = toolDef.renderResult(\n\t\t\t\t\tagentToolResult,\n\t\t\t\t\t{ expanded: false, isPartial: false },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedResultComponents.get(toolCallId), false, false, isError),\n\t\t\t\t);\n\t\t\t\trenderedResultComponents.set(toolCallId, collapsedComponent);\n\t\t\t\tconst collapsed = ansiLinesToHtml(trimRenderedResultLines(collapsedComponent.render(width)));\n\n\t\t\t\t// Render expanded\n\t\t\t\tconst expandedComponent = toolDef.renderResult(\n\t\t\t\t\tagentToolResult,\n\t\t\t\t\t{ expanded: true, isPartial: false },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcreateRenderContext(toolCallId, renderedResultComponents.get(toolCallId), true, false, isError),\n\t\t\t\t);\n\t\t\t\trenderedResultComponents.set(toolCallId, expandedComponent);\n\t\t\t\tconst expanded = ansiLinesToHtml(trimRenderedResultLines(expandedComponent.render(width)));\n\n\t\t\t\treturn {\n\t\t\t\t\t...(collapsed && collapsed !== expanded ? { collapsed } : {}),\n\t\t\t\t\texpanded,\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\t// On error, return undefined so HTML export can fall back to structured result rendering\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t},\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/export-html/vendor/highlight.min.js b/dist/core/export-html/vendor/highlight.min.js new file mode 100644 index 0000000..5d699ae --- /dev/null +++ b/dist/core/export-html/vendor/highlight.min.js @@ -0,0 +1,1213 @@ +/*! + Highlight.js v11.9.0 (git: f47103d4f1) + (c) 2006-2023 undefined and other contributors + License: BSD-3-Clause + */ +var hljs=function(){"use strict";function e(n){ +return n instanceof Map?n.clear=n.delete=n.set=()=>{ +throw Error("map is read-only")}:n instanceof Set&&(n.add=n.clear=n.delete=()=>{ +throw Error("set is read-only") +}),Object.freeze(n),Object.getOwnPropertyNames(n).forEach((t=>{ +const a=n[t],i=typeof a;"object"!==i&&"function"!==i||Object.isFrozen(a)||e(a) +})),n}class n{constructor(e){ +void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1} +ignoreMatch(){this.isMatchIgnored=!0}}function t(e){ +return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'") +}function a(e,...n){const t=Object.create(null);for(const n in e)t[n]=e[n] +;return n.forEach((e=>{for(const n in e)t[n]=e[n]})),t}const i=e=>!!e.scope +;class r{constructor(e,n){ +this.buffer="",this.classPrefix=n.classPrefix,e.walk(this)}addText(e){ +this.buffer+=t(e)}openNode(e){if(!i(e))return;const n=((e,{prefix:n})=>{ +if(e.startsWith("language:"))return e.replace("language:","language-") +;if(e.includes(".")){const t=e.split(".") +;return[`${n}${t.shift()}`,...t.map(((e,n)=>`${e}${"_".repeat(n+1)}`))].join(" ") +}return`${n}${e}`})(e.scope,{prefix:this.classPrefix});this.span(n)} +closeNode(e){i(e)&&(this.buffer+="")}value(){return this.buffer}span(e){ +this.buffer+=``}}const s=(e={})=>{const n={children:[]} +;return Object.assign(n,e),n};class o{constructor(){ +this.rootNode=s(),this.stack=[this.rootNode]}get top(){ +return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){ +this.top.children.push(e)}openNode(e){const n=s({scope:e}) +;this.add(n),this.stack.push(n)}closeNode(){ +if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){ +for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)} +walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,n){ +return"string"==typeof n?e.addText(n):n.children&&(e.openNode(n), +n.children.forEach((n=>this._walk(e,n))),e.closeNode(n)),e}static _collapse(e){ +"string"!=typeof e&&e.children&&(e.children.every((e=>"string"==typeof e))?e.children=[e.children.join("")]:e.children.forEach((e=>{ +o._collapse(e)})))}}class l extends o{constructor(e){super(),this.options=e} +addText(e){""!==e&&this.add(e)}startScope(e){this.openNode(e)}endScope(){ +this.closeNode()}__addSublanguage(e,n){const t=e.root +;n&&(t.scope="language:"+n),this.add(t)}toHTML(){ +return new r(this,this.options).value()}finalize(){ +return this.closeAllNodes(),!0}}function c(e){ +return e?"string"==typeof e?e:e.source:null}function d(e){return b("(?=",e,")")} +function g(e){return b("(?:",e,")*")}function u(e){return b("(?:",e,")?")} +function b(...e){return e.map((e=>c(e))).join("")}function m(...e){const n=(e=>{ +const n=e[e.length-1] +;return"object"==typeof n&&n.constructor===Object?(e.splice(e.length-1,1),n):{} +})(e);return"("+(n.capture?"":"?:")+e.map((e=>c(e))).join("|")+")"} +function p(e){return RegExp(e.toString()+"|").exec("").length-1} +const _=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./ +;function h(e,{joinWith:n}){let t=0;return e.map((e=>{t+=1;const n=t +;let a=c(e),i="";for(;a.length>0;){const e=_.exec(a);if(!e){i+=a;break} +i+=a.substring(0,e.index), +a=a.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?i+="\\"+(Number(e[1])+n):(i+=e[0], +"("===e[0]&&t++)}return i})).map((e=>`(${e})`)).join(n)} +const f="[a-zA-Z]\\w*",E="[a-zA-Z_]\\w*",y="\\b\\d+(\\.\\d+)?",N="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",w="\\b(0b[01]+)",v={ +begin:"\\\\[\\s\\S]",relevance:0},O={scope:"string",begin:"'",end:"'", +illegal:"\\n",contains:[v]},k={scope:"string",begin:'"',end:'"',illegal:"\\n", +contains:[v]},x=(e,n,t={})=>{const i=a({scope:"comment",begin:e,end:n, +contains:[]},t);i.contains.push({scope:"doctag", +begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)", +end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0}) +;const r=m("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/) +;return i.contains.push({begin:b(/[ ]+/,"(",r,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),i +},M=x("//","$"),S=x("/\\*","\\*/"),A=x("#","$");var C=Object.freeze({ +__proto__:null,APOS_STRING_MODE:O,BACKSLASH_ESCAPE:v,BINARY_NUMBER_MODE:{ +scope:"number",begin:w,relevance:0},BINARY_NUMBER_RE:w,COMMENT:x, +C_BLOCK_COMMENT_MODE:S,C_LINE_COMMENT_MODE:M,C_NUMBER_MODE:{scope:"number", +begin:N,relevance:0},C_NUMBER_RE:N,END_SAME_AS_BEGIN:e=>Object.assign(e,{ +"on:begin":(e,n)=>{n.data._beginMatch=e[1]},"on:end":(e,n)=>{ +n.data._beginMatch!==e[1]&&n.ignoreMatch()}}),HASH_COMMENT_MODE:A,IDENT_RE:f, +MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:{begin:"\\.\\s*"+E,relevance:0}, +NUMBER_MODE:{scope:"number",begin:y,relevance:0},NUMBER_RE:y, +PHRASAL_WORDS_MODE:{ +begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/ +},QUOTE_STRING_MODE:k,REGEXP_MODE:{scope:"regexp",begin:/\/(?=[^/\n]*\/)/, +end:/\/[gimuy]*/,contains:[v,{begin:/\[/,end:/\]/,relevance:0,contains:[v]}]}, +RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~", +SHEBANG:(e={})=>{const n=/^#![ ]*\// +;return e.binary&&(e.begin=b(n,/.*\b/,e.binary,/\b.*/)),a({scope:"meta",begin:n, +end:/$/,relevance:0,"on:begin":(e,n)=>{0!==e.index&&n.ignoreMatch()}},e)}, +TITLE_MODE:{scope:"title",begin:f,relevance:0},UNDERSCORE_IDENT_RE:E, +UNDERSCORE_TITLE_MODE:{scope:"title",begin:E,relevance:0}});function T(e,n){ +"."===e.input[e.index-1]&&n.ignoreMatch()}function R(e,n){ +void 0!==e.className&&(e.scope=e.className,delete e.className)}function D(e,n){ +n&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)", +e.__beforeBegin=T,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords, +void 0===e.relevance&&(e.relevance=0))}function I(e,n){ +Array.isArray(e.illegal)&&(e.illegal=m(...e.illegal))}function L(e,n){ +if(e.match){ +if(e.begin||e.end)throw Error("begin & end are not supported with match") +;e.begin=e.match,delete e.match}}function B(e,n){ +void 0===e.relevance&&(e.relevance=1)}const $=(e,n)=>{if(!e.beforeMatch)return +;if(e.starts)throw Error("beforeMatch cannot be used with starts") +;const t=Object.assign({},e);Object.keys(e).forEach((n=>{delete e[n] +})),e.keywords=t.keywords,e.begin=b(t.beforeMatch,d(t.begin)),e.starts={ +relevance:0,contains:[Object.assign(t,{endsParent:!0})] +},e.relevance=0,delete t.beforeMatch +},z=["of","and","for","in","not","or","if","then","parent","list","value"],F="keyword" +;function U(e,n,t=F){const a=Object.create(null) +;return"string"==typeof e?i(t,e.split(" ")):Array.isArray(e)?i(t,e):Object.keys(e).forEach((t=>{ +Object.assign(a,U(e[t],n,t))})),a;function i(e,t){ +n&&(t=t.map((e=>e.toLowerCase()))),t.forEach((n=>{const t=n.split("|") +;a[t[0]]=[e,j(t[0],t[1])]}))}}function j(e,n){ +return n?Number(n):(e=>z.includes(e.toLowerCase()))(e)?0:1}const P={},K=e=>{ +console.error(e)},H=(e,...n)=>{console.log("WARN: "+e,...n)},q=(e,n)=>{ +P[`${e}/${n}`]||(console.log(`Deprecated as of ${e}. ${n}`),P[`${e}/${n}`]=!0) +},G=Error();function Z(e,n,{key:t}){let a=0;const i=e[t],r={},s={} +;for(let e=1;e<=n.length;e++)s[e+a]=i[e],r[e+a]=!0,a+=p(n[e-1]) +;e[t]=s,e[t]._emit=r,e[t]._multi=!0}function W(e){(e=>{ +e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope, +delete e.scope)})(e),"string"==typeof e.beginScope&&(e.beginScope={ +_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope +}),(e=>{if(Array.isArray(e.begin)){ +if(e.skip||e.excludeBegin||e.returnBegin)throw K("skip, excludeBegin, returnBegin not compatible with beginScope: {}"), +G +;if("object"!=typeof e.beginScope||null===e.beginScope)throw K("beginScope must be object"), +G;Z(e,e.begin,{key:"beginScope"}),e.begin=h(e.begin,{joinWith:""})}})(e),(e=>{ +if(Array.isArray(e.end)){ +if(e.skip||e.excludeEnd||e.returnEnd)throw K("skip, excludeEnd, returnEnd not compatible with endScope: {}"), +G +;if("object"!=typeof e.endScope||null===e.endScope)throw K("endScope must be object"), +G;Z(e,e.end,{key:"endScope"}),e.end=h(e.end,{joinWith:""})}})(e)}function Q(e){ +function n(n,t){ +return RegExp(c(n),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(t?"g":"")) +}class t{constructor(){ +this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0} +addRule(e,n){ +n.position=this.position++,this.matchIndexes[this.matchAt]=n,this.regexes.push([n,e]), +this.matchAt+=p(e)+1}compile(){0===this.regexes.length&&(this.exec=()=>null) +;const e=this.regexes.map((e=>e[1]));this.matcherRe=n(h(e,{joinWith:"|" +}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex +;const n=this.matcherRe.exec(e);if(!n)return null +;const t=n.findIndex(((e,n)=>n>0&&void 0!==e)),a=this.matchIndexes[t] +;return n.splice(0,t),Object.assign(n,a)}}class i{constructor(){ +this.rules=[],this.multiRegexes=[], +this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){ +if(this.multiRegexes[e])return this.multiRegexes[e];const n=new t +;return this.rules.slice(e).forEach((([e,t])=>n.addRule(e,t))), +n.compile(),this.multiRegexes[e]=n,n}resumingScanAtSamePosition(){ +return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(e,n){ +this.rules.push([e,n]),"begin"===n.type&&this.count++}exec(e){ +const n=this.getMatcher(this.regexIndex);n.lastIndex=this.lastIndex +;let t=n.exec(e) +;if(this.resumingScanAtSamePosition())if(t&&t.index===this.lastIndex);else{ +const n=this.getMatcher(0);n.lastIndex=this.lastIndex+1,t=n.exec(e)} +return t&&(this.regexIndex+=t.position+1, +this.regexIndex===this.count&&this.considerAll()),t}} +if(e.compilerExtensions||(e.compilerExtensions=[]), +e.contains&&e.contains.includes("self"))throw Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.") +;return e.classNameAliases=a(e.classNameAliases||{}),function t(r,s){const o=r +;if(r.isCompiled)return o +;[R,L,W,$].forEach((e=>e(r,s))),e.compilerExtensions.forEach((e=>e(r,s))), +r.__beforeBegin=null,[D,I,B].forEach((e=>e(r,s))),r.isCompiled=!0;let l=null +;return"object"==typeof r.keywords&&r.keywords.$pattern&&(r.keywords=Object.assign({},r.keywords), +l=r.keywords.$pattern, +delete r.keywords.$pattern),l=l||/\w+/,r.keywords&&(r.keywords=U(r.keywords,e.case_insensitive)), +o.keywordPatternRe=n(l,!0), +s&&(r.begin||(r.begin=/\B|\b/),o.beginRe=n(o.begin),r.end||r.endsWithParent||(r.end=/\B|\b/), +r.end&&(o.endRe=n(o.end)), +o.terminatorEnd=c(o.end)||"",r.endsWithParent&&s.terminatorEnd&&(o.terminatorEnd+=(r.end?"|":"")+s.terminatorEnd)), +r.illegal&&(o.illegalRe=n(r.illegal)), +r.contains||(r.contains=[]),r.contains=[].concat(...r.contains.map((e=>(e=>(e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map((n=>a(e,{ +variants:null},n)))),e.cachedVariants?e.cachedVariants:X(e)?a(e,{ +starts:e.starts?a(e.starts):null +}):Object.isFrozen(e)?a(e):e))("self"===e?r:e)))),r.contains.forEach((e=>{t(e,o) +})),r.starts&&t(r.starts,s),o.matcher=(e=>{const n=new i +;return e.contains.forEach((e=>n.addRule(e.begin,{rule:e,type:"begin" +}))),e.terminatorEnd&&n.addRule(e.terminatorEnd,{type:"end" +}),e.illegal&&n.addRule(e.illegal,{type:"illegal"}),n})(o),o}(e)}function X(e){ +return!!e&&(e.endsWithParent||X(e.starts))}class V extends Error{ +constructor(e,n){super(e),this.name="HTMLInjectionError",this.html=n}} +const J=t,Y=a,ee=Symbol("nomatch"),ne=t=>{ +const a=Object.create(null),i=Object.create(null),r=[];let s=!0 +;const o="Could not find the language '{}', did you forget to load/include a language module?",c={ +disableAutodetect:!0,name:"Plain text",contains:[]};let p={ +ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i, +languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-", +cssSelector:"pre code",languages:null,__emitter:l};function _(e){ +return p.noHighlightRe.test(e)}function h(e,n,t){let a="",i="" +;"object"==typeof n?(a=e, +t=n.ignoreIllegals,i=n.language):(q("10.7.0","highlight(lang, code, ...args) has been deprecated."), +q("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"), +i=e,a=n),void 0===t&&(t=!0);const r={code:a,language:i};x("before:highlight",r) +;const s=r.result?r.result:f(r.language,r.code,t) +;return s.code=r.code,x("after:highlight",s),s}function f(e,t,i,r){ +const l=Object.create(null);function c(){if(!x.keywords)return void S.addText(A) +;let e=0;x.keywordPatternRe.lastIndex=0;let n=x.keywordPatternRe.exec(A),t="" +;for(;n;){t+=A.substring(e,n.index) +;const i=w.case_insensitive?n[0].toLowerCase():n[0],r=(a=i,x.keywords[a]);if(r){ +const[e,a]=r +;if(S.addText(t),t="",l[i]=(l[i]||0)+1,l[i]<=7&&(C+=a),e.startsWith("_"))t+=n[0];else{ +const t=w.classNameAliases[e]||e;g(n[0],t)}}else t+=n[0] +;e=x.keywordPatternRe.lastIndex,n=x.keywordPatternRe.exec(A)}var a +;t+=A.substring(e),S.addText(t)}function d(){null!=x.subLanguage?(()=>{ +if(""===A)return;let e=null;if("string"==typeof x.subLanguage){ +if(!a[x.subLanguage])return void S.addText(A) +;e=f(x.subLanguage,A,!0,M[x.subLanguage]),M[x.subLanguage]=e._top +}else e=E(A,x.subLanguage.length?x.subLanguage:null) +;x.relevance>0&&(C+=e.relevance),S.__addSublanguage(e._emitter,e.language) +})():c(),A=""}function g(e,n){ +""!==e&&(S.startScope(n),S.addText(e),S.endScope())}function u(e,n){let t=1 +;const a=n.length-1;for(;t<=a;){if(!e._emit[t]){t++;continue} +const a=w.classNameAliases[e[t]]||e[t],i=n[t];a?g(i,a):(A=i,c(),A=""),t++}} +function b(e,n){ +return e.scope&&"string"==typeof e.scope&&S.openNode(w.classNameAliases[e.scope]||e.scope), +e.beginScope&&(e.beginScope._wrap?(g(A,w.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap), +A=""):e.beginScope._multi&&(u(e.beginScope,n),A="")),x=Object.create(e,{parent:{ +value:x}}),x}function m(e,t,a){let i=((e,n)=>{const t=e&&e.exec(n) +;return t&&0===t.index})(e.endRe,a);if(i){if(e["on:end"]){const a=new n(e) +;e["on:end"](t,a),a.isMatchIgnored&&(i=!1)}if(i){ +for(;e.endsParent&&e.parent;)e=e.parent;return e}} +if(e.endsWithParent)return m(e.parent,t,a)}function _(e){ +return 0===x.matcher.regexIndex?(A+=e[0],1):(D=!0,0)}function h(e){ +const n=e[0],a=t.substring(e.index),i=m(x,e,a);if(!i)return ee;const r=x +;x.endScope&&x.endScope._wrap?(d(), +g(n,x.endScope._wrap)):x.endScope&&x.endScope._multi?(d(), +u(x.endScope,e)):r.skip?A+=n:(r.returnEnd||r.excludeEnd||(A+=n), +d(),r.excludeEnd&&(A=n));do{ +x.scope&&S.closeNode(),x.skip||x.subLanguage||(C+=x.relevance),x=x.parent +}while(x!==i.parent);return i.starts&&b(i.starts,e),r.returnEnd?0:n.length} +let y={};function N(a,r){const o=r&&r[0];if(A+=a,null==o)return d(),0 +;if("begin"===y.type&&"end"===r.type&&y.index===r.index&&""===o){ +if(A+=t.slice(r.index,r.index+1),!s){const n=Error(`0 width match regex (${e})`) +;throw n.languageName=e,n.badRule=y.rule,n}return 1} +if(y=r,"begin"===r.type)return(e=>{ +const t=e[0],a=e.rule,i=new n(a),r=[a.__beforeBegin,a["on:begin"]] +;for(const n of r)if(n&&(n(e,i),i.isMatchIgnored))return _(t) +;return a.skip?A+=t:(a.excludeBegin&&(A+=t), +d(),a.returnBegin||a.excludeBegin||(A=t)),b(a,e),a.returnBegin?0:t.length})(r) +;if("illegal"===r.type&&!i){ +const e=Error('Illegal lexeme "'+o+'" for mode "'+(x.scope||"")+'"') +;throw e.mode=x,e}if("end"===r.type){const e=h(r);if(e!==ee)return e} +if("illegal"===r.type&&""===o)return 1 +;if(R>1e5&&R>3*r.index)throw Error("potential infinite loop, way more iterations than matches") +;return A+=o,o.length}const w=v(e) +;if(!w)throw K(o.replace("{}",e)),Error('Unknown language: "'+e+'"') +;const O=Q(w);let k="",x=r||O;const M={},S=new p.__emitter(p);(()=>{const e=[] +;for(let n=x;n!==w;n=n.parent)n.scope&&e.unshift(n.scope) +;e.forEach((e=>S.openNode(e)))})();let A="",C=0,T=0,R=0,D=!1;try{ +if(w.__emitTokens)w.__emitTokens(t,S);else{for(x.matcher.considerAll();;){ +R++,D?D=!1:x.matcher.considerAll(),x.matcher.lastIndex=T +;const e=x.matcher.exec(t);if(!e)break;const n=N(t.substring(T,e.index),e) +;T=e.index+n}N(t.substring(T))}return S.finalize(),k=S.toHTML(),{language:e, +value:k,relevance:C,illegal:!1,_emitter:S,_top:x}}catch(n){ +if(n.message&&n.message.includes("Illegal"))return{language:e,value:J(t), +illegal:!0,relevance:0,_illegalBy:{message:n.message,index:T, +context:t.slice(T-100,T+100),mode:n.mode,resultSoFar:k},_emitter:S};if(s)return{ +language:e,value:J(t),illegal:!1,relevance:0,errorRaised:n,_emitter:S,_top:x} +;throw n}}function E(e,n){n=n||p.languages||Object.keys(a);const t=(e=>{ +const n={value:J(e),illegal:!1,relevance:0,_top:c,_emitter:new p.__emitter(p)} +;return n._emitter.addText(e),n})(e),i=n.filter(v).filter(k).map((n=>f(n,e,!1))) +;i.unshift(t);const r=i.sort(((e,n)=>{ +if(e.relevance!==n.relevance)return n.relevance-e.relevance +;if(e.language&&n.language){if(v(e.language).supersetOf===n.language)return 1 +;if(v(n.language).supersetOf===e.language)return-1}return 0})),[s,o]=r,l=s +;return l.secondBest=o,l}function y(e){let n=null;const t=(e=>{ +let n=e.className+" ";n+=e.parentNode?e.parentNode.className:"" +;const t=p.languageDetectRe.exec(n);if(t){const n=v(t[1]) +;return n||(H(o.replace("{}",t[1])), +H("Falling back to no-highlight mode for this block.",e)),n?t[1]:"no-highlight"} +return n.split(/\s+/).find((e=>_(e)||v(e)))})(e);if(_(t))return +;if(x("before:highlightElement",{el:e,language:t +}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e) +;if(e.children.length>0&&(p.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."), +console.warn("https://github.com/highlightjs/highlight.js/wiki/security"), +console.warn("The element with unescaped HTML:"), +console.warn(e)),p.throwUnescapedHTML))throw new V("One of your code blocks includes unescaped HTML.",e.innerHTML) +;n=e;const a=n.textContent,r=t?h(a,{language:t,ignoreIllegals:!0}):E(a) +;e.innerHTML=r.value,e.dataset.highlighted="yes",((e,n,t)=>{const a=n&&i[n]||t +;e.classList.add("hljs"),e.classList.add("language-"+a) +})(e,t,r.language),e.result={language:r.language,re:r.relevance, +relevance:r.relevance},r.secondBest&&(e.secondBest={ +language:r.secondBest.language,relevance:r.secondBest.relevance +}),x("after:highlightElement",{el:e,result:r,text:a})}let N=!1;function w(){ +"loading"!==document.readyState?document.querySelectorAll(p.cssSelector).forEach(y):N=!0 +}function v(e){return e=(e||"").toLowerCase(),a[e]||a[i[e]]} +function O(e,{languageName:n}){"string"==typeof e&&(e=[e]),e.forEach((e=>{ +i[e.toLowerCase()]=n}))}function k(e){const n=v(e) +;return n&&!n.disableAutodetect}function x(e,n){const t=e;r.forEach((e=>{ +e[t]&&e[t](n)}))} +"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("DOMContentLoaded",(()=>{ +N&&w()}),!1),Object.assign(t,{highlight:h,highlightAuto:E,highlightAll:w, +highlightElement:y, +highlightBlock:e=>(q("10.7.0","highlightBlock will be removed entirely in v12.0"), +q("10.7.0","Please use highlightElement now."),y(e)),configure:e=>{p=Y(p,e)}, +initHighlighting:()=>{ +w(),q("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")}, +initHighlightingOnLoad:()=>{ +w(),q("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.") +},registerLanguage:(e,n)=>{let i=null;try{i=n(t)}catch(n){ +if(K("Language definition for '{}' could not be registered.".replace("{}",e)), +!s)throw n;K(n),i=c} +i.name||(i.name=e),a[e]=i,i.rawDefinition=n.bind(null,t),i.aliases&&O(i.aliases,{ +languageName:e})},unregisterLanguage:e=>{delete a[e] +;for(const n of Object.keys(i))i[n]===e&&delete i[n]}, +listLanguages:()=>Object.keys(a),getLanguage:v,registerAliases:O, +autoDetection:k,inherit:Y,addPlugin:e=>{(e=>{ +e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=n=>{ +e["before:highlightBlock"](Object.assign({block:n.el},n)) +}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=n=>{ +e["after:highlightBlock"](Object.assign({block:n.el},n))})})(e),r.push(e)}, +removePlugin:e=>{const n=r.indexOf(e);-1!==n&&r.splice(n,1)}}),t.debugMode=()=>{ +s=!1},t.safeMode=()=>{s=!0},t.versionString="11.9.0",t.regex={concat:b, +lookahead:d,either:m,optional:u,anyNumberOfTimes:g} +;for(const n in C)"object"==typeof C[n]&&e(C[n]);return Object.assign(t,C),t +},te=ne({});te.newInstance=()=>ne({});var ae=te;const ie=e=>({IMPORTANT:{ +scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{ +scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/}, +FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/}, +ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$", +contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{ +scope:"number", +begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?", +relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/} +}),re=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","p","q","quote","samp","section","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],se=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"],oe=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"],le=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"],ce=["align-content","align-items","align-self","all","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","content","content-visibility","counter-increment","counter-reset","cue","cue-after","cue-before","cursor","direction","display","empty-cells","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-size","font-size-adjust","font-smoothing","font-stretch","font-style","font-synthesis","font-variant","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","gap","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","inline-size","isolation","justify-content","left","letter-spacing","line-break","line-height","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-wrap","overflow-x","overflow-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page-break-after","page-break-before","page-break-inside","pause","pause-after","pause-before","perspective","perspective-origin","pointer-events","position","quotes","resize","rest","rest-after","rest-before","right","row-gap","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","speak","speak-as","src","tab-size","table-layout","text-align","text-align-all","text-align-last","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-transform","text-underline-position","top","transform","transform-box","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","z-index"].reverse(),de=oe.concat(le) +;var ge="[0-9](_*[0-9])*",ue=`\\.(${ge})`,be="[0-9a-fA-F](_*[0-9a-fA-F])*",me={ +className:"number",variants:[{ +begin:`(\\b(${ge})((${ue})|\\.)?|(${ue}))[eE][+-]?(${ge})[fFdD]?\\b`},{ +begin:`\\b(${ge})((${ue})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{ +begin:`(${ue})[fFdD]?\\b`},{begin:`\\b(${ge})[fFdD]\\b`},{ +begin:`\\b0[xX]((${be})\\.?|(${be})?\\.(${be}))[pP][+-]?(${ge})[fFdD]?\\b`},{ +begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${be})[lL]?\\b`},{ +begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}], +relevance:0};function pe(e,n,t){return-1===t?"":e.replace(n,(a=>pe(e,n,t-1)))} +const _e="[A-Za-z$_][0-9A-Za-z$_]*",he=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends"],fe=["true","false","null","undefined","NaN","Infinity"],Ee=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],ye=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Ne=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],we=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],ve=[].concat(Ne,Ee,ye) +;function Oe(e){const n=e.regex,t=_e,a={begin:/<[A-Za-z0-9\\._:-]+/, +end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,n)=>{ +const t=e[0].length+e.index,a=e.input[t] +;if("<"===a||","===a)return void n.ignoreMatch();let i +;">"===a&&(((e,{after:n})=>{const t="",M={ +match:[/const|var|let/,/\s+/,t,/\s*/,/=\s*/,/(async\s*)?/,n.lookahead(x)], +keywords:"async",className:{1:"keyword",3:"title.function"},contains:[f]} +;return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:i,exports:{ +PARAMS_CONTAINS:h,CLASS_REFERENCE:y},illegal:/#(?![$_A-z])/, +contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{ +label:"use_strict",className:"meta",relevance:10, +begin:/^\s*['"]use (strict|asm)['"]/ +},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,d,g,u,b,m,{match:/\$\d+/},l,y,{ +className:"attr",begin:t+n.lookahead(":"),relevance:0},M,{ +begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*", +keywords:"return throw case",relevance:0,contains:[m,e.REGEXP_MODE,{ +className:"function",begin:x,returnBegin:!0,end:"\\s*=>",contains:[{ +className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{ +className:null,begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0, +excludeEnd:!0,keywords:i,contains:h}]}]},{begin:/,/,relevance:0},{match:/\s+/, +relevance:0},{variants:[{begin:"<>",end:""},{ +match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:a.begin, +"on:begin":a.isTrulyOpeningTag,end:a.end}],subLanguage:"xml",contains:[{ +begin:a.begin,end:a.end,skip:!0,contains:["self"]}]}]},N,{ +beginKeywords:"while if switch catch for"},{ +begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{", +returnBegin:!0,label:"func.def",contains:[f,e.inherit(e.TITLE_MODE,{begin:t, +className:"title.function"})]},{match:/\.\.\./,relevance:0},O,{match:"\\$"+t, +relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"}, +contains:[f]},w,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/, +className:"variable.constant"},E,k,{match:/\$[(.]/}]}} +const ke=e=>b(/\b/,e,/\w$/.test(e)?/\b/:/\B/),xe=["Protocol","Type"].map(ke),Me=["init","self"].map(ke),Se=["Any","Self"],Ae=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],Ce=["false","nil","true"],Te=["assignment","associativity","higherThan","left","lowerThan","none","right"],Re=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],De=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],Ie=m(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),Le=m(Ie,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),Be=b(Ie,Le,"*"),$e=m(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),ze=m($e,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),Fe=b($e,ze,"*"),Ue=b(/[A-Z]/,ze,"*"),je=["attached","autoclosure",b(/convention\(/,m("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",b(/objc\(/,Fe,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],Pe=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"] +;var Ke=Object.freeze({__proto__:null,grmr_bash:e=>{const n=e.regex,t={},a={ +begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[t]}]} +;Object.assign(t,{className:"variable",variants:[{ +begin:n.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},a]});const i={ +className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},r={ +begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/, +end:/(\w+)/,className:"string"})]}},s={className:"string",begin:/"/,end:/"/, +contains:[e.BACKSLASH_ESCAPE,t,i]};i.contains.push(s);const o={begin:/\$?\(\(/, +end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,t] +},l=e.SHEBANG({binary:"(fish|bash|zsh|sh|csh|ksh|tcsh|dash|scsh)",relevance:10 +}),c={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0, +contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{ +name:"Bash",aliases:["sh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/, +keyword:["if","then","else","elif","fi","for","while","until","in","do","done","case","esac","function","select"], +literal:["true","false"], +built_in:["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset","alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","type","typeset","ulimit","unalias","set","shopt","autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp","chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"] +},contains:[l,e.SHEBANG(),c,o,e.HASH_COMMENT_MODE,r,{match:/(\/[a-z._-]+)+/},s,{ +match:/\\"/},{className:"string",begin:/'/,end:/'/},{match:/\\'/},t]}}, +grmr_c:e=>{const n=e.regex,t=e.COMMENT("//","$",{contains:[{begin:/\\\n/}] +}),a="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",r="("+a+"|"+n.optional(i)+"[a-zA-Z_]\\w*"+n.optional("<[^<>]+>")+")",s={ +className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{ +match:/\batomic_[a-z]{3,6}\b/}]},o={className:"string",variants:[{ +begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{ +begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)", +end:"'",illegal:"."},e.END_SAME_AS_BEGIN({ +begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={ +className:"number",variants:[{begin:"\\b(0b[01']+)"},{ +begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)" +},{ +begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)" +}],relevance:0},c={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{ +keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include" +},contains:[{begin:/\\\n/,relevance:0},e.inherit(o,{className:"string"}),{ +className:"string",begin:/<.*?>/},t,e.C_BLOCK_COMMENT_MODE]},d={ +className:"title",begin:n.optional(i)+e.IDENT_RE,relevance:0 +},g=n.optional(i)+e.IDENT_RE+"\\s*\\(",u={ +keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"], +type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal128","const","static","complex","bool","imaginary"], +literal:"true false NULL", +built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr" +},b=[c,s,t,e.C_BLOCK_COMMENT_MODE,l,o],m={variants:[{begin:/=/,end:/;/},{ +begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}], +keywords:u,contains:b.concat([{begin:/\(/,end:/\)/,keywords:u, +contains:b.concat(["self"]),relevance:0}]),relevance:0},p={ +begin:"("+r+"[\\*&\\s]+)+"+g,returnBegin:!0,end:/[{;=]/,excludeEnd:!0, +keywords:u,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:a,keywords:u,relevance:0},{ +begin:g,returnBegin:!0,contains:[e.inherit(d,{className:"title.function"})], +relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/, +keywords:u,relevance:0,contains:[t,e.C_BLOCK_COMMENT_MODE,o,l,s,{begin:/\(/, +end:/\)/,keywords:u,relevance:0,contains:["self",t,e.C_BLOCK_COMMENT_MODE,o,l,s] +}]},s,t,e.C_BLOCK_COMMENT_MODE,c]};return{name:"C",aliases:["h"],keywords:u, +disableAutodetect:!0,illegal:"=]/,contains:[{ +beginKeywords:"final class struct"},e.TITLE_MODE]}]),exports:{preprocessor:c, +strings:o,keywords:u}}},grmr_cpp:e=>{const n=e.regex,t=e.COMMENT("//","$",{ +contains:[{begin:/\\\n/}] +}),a="decltype\\(auto\\)",i="[a-zA-Z_]\\w*::",r="(?!struct)("+a+"|"+n.optional(i)+"[a-zA-Z_]\\w*"+n.optional("<[^<>]+>")+")",s={ +className:"type",begin:"\\b[a-z\\d_]*_t\\b"},o={className:"string",variants:[{ +begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{ +begin:"(u8?|U|L)?'(\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)|.)", +end:"'",illegal:"."},e.END_SAME_AS_BEGIN({ +begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},l={ +className:"number",variants:[{begin:"\\b(0b[01']+)"},{ +begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)" +},{ +begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)" +}],relevance:0},c={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{ +keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include" +},contains:[{begin:/\\\n/,relevance:0},e.inherit(o,{className:"string"}),{ +className:"string",begin:/<.*?>/},t,e.C_BLOCK_COMMENT_MODE]},d={ +className:"title",begin:n.optional(i)+e.IDENT_RE,relevance:0 +},g=n.optional(i)+e.IDENT_RE+"\\s*\\(",u={ +type:["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"], +keyword:["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"], +literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"], +_type_hints:["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"] +},b={className:"function.dispatch",relevance:0,keywords:{ +_hint:["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"] +}, +begin:n.concat(/\b/,/(?!decltype)/,/(?!if)/,/(?!for)/,/(?!switch)/,/(?!while)/,e.IDENT_RE,n.lookahead(/(<[^<>]+>|)\s*\(/)) +},m=[b,c,s,t,e.C_BLOCK_COMMENT_MODE,l,o],p={variants:[{begin:/=/,end:/;/},{ +begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}], +keywords:u,contains:m.concat([{begin:/\(/,end:/\)/,keywords:u, +contains:m.concat(["self"]),relevance:0}]),relevance:0},_={className:"function", +begin:"("+r+"[\\*&\\s]+)+"+g,returnBegin:!0,end:/[{;=]/,excludeEnd:!0, +keywords:u,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:a,keywords:u,relevance:0},{ +begin:g,returnBegin:!0,contains:[d],relevance:0},{begin:/::/,relevance:0},{ +begin:/:/,endsWithParent:!0,contains:[o,l]},{relevance:0,match:/,/},{ +className:"params",begin:/\(/,end:/\)/,keywords:u,relevance:0, +contains:[t,e.C_BLOCK_COMMENT_MODE,o,l,s,{begin:/\(/,end:/\)/,keywords:u, +relevance:0,contains:["self",t,e.C_BLOCK_COMMENT_MODE,o,l,s]}] +},s,t,e.C_BLOCK_COMMENT_MODE,c]};return{name:"C++", +aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:u,illegal:"",keywords:u,contains:["self",s]},{begin:e.IDENT_RE+"::",keywords:u},{ +match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/], +className:{1:"keyword",3:"title.class"}}])}},grmr_csharp:e=>{const n={ +keyword:["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"].concat(["add","alias","and","ascending","async","await","by","descending","equals","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","remove","select","set","unmanaged","value|0","var","when","where","with","yield"]), +built_in:["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"], +literal:["default","false","null","true"]},t=e.inherit(e.TITLE_MODE,{ +begin:"[a-zA-Z](\\.?\\w)*"}),a={className:"number",variants:[{ +begin:"\\b(0b[01']+)"},{ +begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{ +begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)" +}],relevance:0},i={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}] +},r=e.inherit(i,{illegal:/\n/}),s={className:"subst",begin:/\{/,end:/\}/, +keywords:n},o=e.inherit(s,{illegal:/\n/}),l={className:"string",begin:/\$"/, +end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/ +},e.BACKSLASH_ESCAPE,o]},c={className:"string",begin:/\$@"/,end:'"',contains:[{ +begin:/\{\{/},{begin:/\}\}/},{begin:'""'},s]},d=e.inherit(c,{illegal:/\n/, +contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},o]}) +;s.contains=[c,l,i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,a,e.C_BLOCK_COMMENT_MODE], +o.contains=[d,l,r,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,a,e.inherit(e.C_BLOCK_COMMENT_MODE,{ +illegal:/\n/})];const g={variants:[c,l,i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE] +},u={begin:"<",end:">",contains:[{beginKeywords:"in out"},t] +},b=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",m={ +begin:"@"+e.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"], +keywords:n,illegal:/::/,contains:[e.COMMENT("///","$",{returnBegin:!0, +contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{ +begin:"\x3c!--|--\x3e"},{begin:""}]}] +}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#", +end:"$",keywords:{ +keyword:"if else elif endif define undef warning error line region endregion pragma checksum" +}},g,a,{beginKeywords:"class interface",relevance:0,end:/[{;=]/, +illegal:/[^\s:,]/,contains:[{beginKeywords:"where class" +},t,u,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace", +relevance:0,end:/[{;=]/,illegal:/[^\s:]/, +contains:[t,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{ +beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/, +contains:[t,u,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"meta", +begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{ +className:"string",begin:/"/,end:/"/}]},{ +beginKeywords:"new return throw await else",relevance:0},{className:"function", +begin:"("+b+"\\s+)+"+e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0, +end:/\s*[{;=]/,excludeEnd:!0,keywords:n,contains:[{ +beginKeywords:"public private protected static internal protected abstract async extern override unsafe virtual new sealed partial", +relevance:0},{begin:e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0, +contains:[e.TITLE_MODE,u],relevance:0},{match:/\(\)/},{className:"params", +begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:n,relevance:0, +contains:[g,a,e.C_BLOCK_COMMENT_MODE] +},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},m]}},grmr_css:e=>{ +const n=e.regex,t=ie(e),a=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{ +name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{ +keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"}, +contains:[t.BLOCK_COMMENT,{begin:/-(webkit|moz|ms|o)-(?=[a-z])/ +},t.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0 +},{className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0 +},t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{ +begin:":("+oe.join("|")+")"},{begin:":(:)?("+le.join("|")+")"}] +},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+ce.join("|")+")\\b"},{ +begin:/:/,end:/[;}{]/, +contains:[t.BLOCK_COMMENT,t.HEXCOLOR,t.IMPORTANT,t.CSS_NUMBER_MODE,...a,{ +begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri" +},contains:[...a,{className:"string",begin:/[^)]/,endsWithParent:!0, +excludeEnd:!0}]},t.FUNCTION_DISPATCH]},{begin:n.lookahead(/@/),end:"[{;]", +relevance:0,illegal:/:/,contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/ +},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{ +$pattern:/[a-z-]+/,keyword:"and or not only",attribute:se.join(" ")},contains:[{ +begin:/[a-z-]+(?=:)/,className:"attribute"},...a,t.CSS_NUMBER_MODE]}]},{ +className:"selector-tag",begin:"\\b("+re.join("|")+")\\b"}]}},grmr_diff:e=>{ +const n=e.regex;return{name:"Diff",aliases:["patch"],contains:[{ +className:"meta",relevance:10, +match:n.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/) +},{className:"comment",variants:[{ +begin:n.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/), +end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{ +className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/, +end:/$/}]}},grmr_go:e=>{const n={ +keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"], +type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"], +literal:["true","false","iota","nil"], +built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"] +};return{name:"Go",aliases:["golang"],keywords:n,illegal:"{const n=e.regex;return{name:"GraphQL",aliases:["gql"], +case_insensitive:!0,disableAutodetect:!1,keywords:{ +keyword:["query","mutation","subscription","type","input","schema","directive","interface","union","scalar","fragment","enum","on"], +literal:["true","false","null"]}, +contains:[e.HASH_COMMENT_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,{ +scope:"punctuation",match:/[.]{3}/,relevance:0},{scope:"punctuation", +begin:/[\!\(\)\:\=\[\]\{\|\}]{1}/,relevance:0},{scope:"variable",begin:/\$/, +end:/\W/,excludeEnd:!0,relevance:0},{scope:"meta",match:/@\w+/,excludeEnd:!0},{ +scope:"symbol",begin:n.concat(/[_A-Za-z][_0-9A-Za-z]*/,n.lookahead(/\s*:/)), +relevance:0}],illegal:[/[;<']/,/BEGIN/]}},grmr_ini:e=>{const n=e.regex,t={ +className:"number",relevance:0,variants:[{begin:/([+-]+)?[\d]+_[\d_]+/},{ +begin:e.NUMBER_RE}]},a=e.COMMENT();a.variants=[{begin:/;/,end:/$/},{begin:/#/, +end:/$/}];const i={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{ +begin:/\$\{(.*?)\}/}]},r={className:"literal", +begin:/\bon|off|true|false|yes|no\b/},s={className:"string", +contains:[e.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{ +begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}] +},o={begin:/\[/,end:/\]/,contains:[a,r,i,s,t,"self"],relevance:0 +},l=n.either(/[A-Za-z0-9_-]+/,/"(\\"|[^"])*"/,/'[^']*'/);return{ +name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/, +contains:[a,{className:"section",begin:/\[+/,end:/\]+/},{ +begin:n.concat(l,"(\\s*\\.\\s*",l,")*",n.lookahead(/\s*=\s*[^#\s]/)), +className:"attr",starts:{end:/$/,contains:[a,o,r,i,s,t]}}]}},grmr_java:e=>{ +const n=e.regex,t="[\xc0-\u02b8a-zA-Z_$][\xc0-\u02b8a-zA-Z_$0-9]*",a=t+pe("(?:<"+t+"~~~(?:\\s*,\\s*"+t+"~~~)*>)?",/~~~/g,2),i={ +keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits"], +literal:["false","true","null"], +type:["char","boolean","long","float","int","byte","short","double"], +built_in:["super","this"]},r={className:"meta",begin:"@"+t,contains:[{ +begin:/\(/,end:/\)/,contains:["self"]}]},s={className:"params",begin:/\(/, +end:/\)/,keywords:i,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:!0} +;return{name:"Java",aliases:["jsp"],keywords:i,illegal:/<\/|#/, +contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/, +relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{ +begin:/import java\.[a-z]+\./,keywords:"import",relevance:2 +},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/, +className:"string",contains:[e.BACKSLASH_ESCAPE] +},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{ +match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,t],className:{ +1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{ +begin:[n.concat(/(?!else)/,t),/\s+/,t,/\s+/,/=(?!=)/],className:{1:"type", +3:"variable",5:"operator"}},{begin:[/record/,/\s+/,t],className:{1:"keyword", +3:"title.class"},contains:[s,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{ +beginKeywords:"new throw return else",relevance:0},{ +begin:["(?:"+a+"\\s+)",e.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{ +2:"title.function"},keywords:i,contains:[{className:"params",begin:/\(/, +end:/\)/,keywords:i,relevance:0, +contains:[r,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,me,e.C_BLOCK_COMMENT_MODE] +},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},me,r]}},grmr_javascript:Oe, +grmr_json:e=>{const n=["true","false","null"],t={scope:"literal", +beginKeywords:n.join(" ")};return{name:"JSON",keywords:{literal:n},contains:[{ +className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},{ +match:/[{}[\],:]/,className:"punctuation",relevance:0 +},e.QUOTE_STRING_MODE,t,e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE], +illegal:"\\S"}},grmr_kotlin:e=>{const n={ +keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual", +built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing", +literal:"true false null"},t={className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"@" +},a={className:"subst",begin:/\$\{/,end:/\}/,contains:[e.C_NUMBER_MODE]},i={ +className:"variable",begin:"\\$"+e.UNDERSCORE_IDENT_RE},r={className:"string", +variants:[{begin:'"""',end:'"""(?=[^"])',contains:[i,a]},{begin:"'",end:"'", +illegal:/\n/,contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/, +contains:[e.BACKSLASH_ESCAPE,i,a]}]};a.contains.push(r);const s={ +className:"meta", +begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UNDERSCORE_IDENT_RE+")?" +},o={className:"meta",begin:"@"+e.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/, +end:/\)/,contains:[e.inherit(r,{className:"string"}),"self"]}] +},l=me,c=e.COMMENT("/\\*","\\*/",{contains:[e.C_BLOCK_COMMENT_MODE]}),d={ +variants:[{className:"type",begin:e.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/, +contains:[]}]},g=d;return g.variants[1].contains=[d],d.variants[1].contains=[g], +{name:"Kotlin",aliases:["kt","kts"],keywords:n, +contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag", +begin:"@[A-Za-z]+"}]}),e.C_LINE_COMMENT_MODE,c,{className:"keyword", +begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol", +begin:/@\w+/}]}},t,s,o,{className:"function",beginKeywords:"fun",end:"[(]|$", +returnBegin:!0,excludeEnd:!0,keywords:n,relevance:5,contains:[{ +begin:e.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0, +contains:[e.UNDERSCORE_TITLE_MODE]},{className:"type",begin://, +keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/, +endsParent:!0,keywords:n,relevance:0,contains:[{begin:/:/,end:/[=,\/]/, +endsWithParent:!0,contains:[d,e.C_LINE_COMMENT_MODE,c],relevance:0 +},e.C_LINE_COMMENT_MODE,c,s,o,r,e.C_NUMBER_MODE]},c]},{ +begin:[/class|interface|trait/,/\s+/,e.UNDERSCORE_IDENT_RE],beginScope:{ +3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0, +illegal:"extends implements",contains:[{ +beginKeywords:"public protected internal private constructor" +},e.UNDERSCORE_TITLE_MODE,{className:"type",begin://,excludeBegin:!0, +excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/, +excludeBegin:!0,returnEnd:!0},s,o]},r,{className:"meta",begin:"^#!/usr/bin/env", +end:"$",illegal:"\n"},l]}},grmr_less:e=>{ +const n=ie(e),t=de,a="[\\w-]+",i="("+a+"|@\\{"+a+"\\})",r=[],s=[],o=e=>({ +className:"string",begin:"~?"+e+".*?"+e}),l=(e,n,t)=>({className:e,begin:n, +relevance:t}),c={$pattern:/[a-z-]+/,keyword:"and or not only", +attribute:se.join(" ")},d={begin:"\\(",end:"\\)",contains:s,keywords:c, +relevance:0} +;s.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,o("'"),o('"'),n.CSS_NUMBER_MODE,{ +begin:"(url|data-uri)\\(",starts:{className:"string",end:"[\\)\\n]", +excludeEnd:!0} +},n.HEXCOLOR,d,l("variable","@@?"+a,10),l("variable","@\\{"+a+"\\}"),l("built_in","~?`[^`]*?`"),{ +className:"attribute",begin:a+"\\s*:",end:":",returnBegin:!0,excludeEnd:!0 +},n.IMPORTANT,{beginKeywords:"and not"},n.FUNCTION_DISPATCH);const g=s.concat({ +begin:/\{/,end:/\}/,contains:r}),u={beginKeywords:"when",endsWithParent:!0, +contains:[{beginKeywords:"and not"}].concat(s)},b={begin:i+"\\s*:", +returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/ +},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+ce.join("|")+")\\b", +end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:s}}] +},m={className:"keyword", +begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b", +starts:{end:"[;{}]",keywords:c,returnEnd:!0,contains:s,relevance:0}},p={ +className:"variable",variants:[{begin:"@"+a+"\\s*:",relevance:15},{begin:"@"+a +}],starts:{end:"[;}]",returnEnd:!0,contains:g}},_={variants:[{ +begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:i,end:/\{/}],returnBegin:!0, +returnEnd:!0,illegal:"[<='$\"]",relevance:0, +contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,u,l("keyword","all\\b"),l("variable","@\\{"+a+"\\}"),{ +begin:"\\b("+re.join("|")+")\\b",className:"selector-tag" +},n.CSS_NUMBER_MODE,l("selector-tag",i,0),l("selector-id","#"+i),l("selector-class","\\."+i,0),l("selector-tag","&",0),n.ATTRIBUTE_SELECTOR_MODE,{ +className:"selector-pseudo",begin:":("+oe.join("|")+")"},{ +className:"selector-pseudo",begin:":(:)?("+le.join("|")+")"},{begin:/\(/, +end:/\)/,relevance:0,contains:g},{begin:"!important"},n.FUNCTION_DISPATCH]},h={ +begin:a+":(:)?"+`(${t.join("|")})`,returnBegin:!0,contains:[_]} +;return r.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,m,p,h,b,_,u,n.FUNCTION_DISPATCH), +{name:"Less",case_insensitive:!0,illegal:"[=>'/<($\"]",contains:r}}, +grmr_lua:e=>{const n="\\[=*\\[",t="\\]=*\\]",a={begin:n,end:t,contains:["self"] +},i=[e.COMMENT("--(?!"+n+")","$"),e.COMMENT("--"+n,t,{contains:[a],relevance:10 +})];return{name:"Lua",keywords:{$pattern:e.UNDERSCORE_IDENT_RE, +literal:"true false nil", +keyword:"and break do else elseif end for goto if in local not or repeat return then until while", +built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove" +},contains:i.concat([{className:"function",beginKeywords:"function",end:"\\)", +contains:[e.inherit(e.TITLE_MODE,{ +begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params", +begin:"\\(",endsWithParent:!0,contains:i}].concat(i) +},e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string", +begin:n,end:t,contains:[a],relevance:5}])}},grmr_makefile:e=>{const n={ +className:"variable",variants:[{begin:"\\$\\("+e.UNDERSCORE_IDENT_RE+"\\)", +contains:[e.BACKSLASH_ESCAPE]},{begin:/\$[@%{ +const n={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},t={ +variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{ +begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/, +relevance:2},{ +begin:e.regex.concat(/\[.+?\]\(/,/[A-Za-z][A-Za-z0-9+.-]*/,/:\/\/.*?\)/), +relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{ +begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/ +},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0, +returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)", +excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[", +end:"\\]",excludeBegin:!0,excludeEnd:!0}]},a={className:"strong",contains:[], +variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}] +},i={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{ +begin:/_(?![_\s])/,end:/_/,relevance:0}]},r=e.inherit(a,{contains:[] +}),s=e.inherit(i,{contains:[]});a.contains.push(s),i.contains.push(r) +;let o=[n,t];return[a,i,r,s].forEach((e=>{e.contains=e.contains.concat(o) +})),o=o.concat(a,i),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{ +className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:o},{ +begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n", +contains:o}]}]},n,{className:"bullet",begin:"^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)", +end:"\\s+",excludeEnd:!0},a,i,{className:"quote",begin:"^>\\s+",contains:o, +end:"$"},{className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{ +begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{ +begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))", +contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},{ +begin:"^[-\\*]{3,}",end:"$"},t,{begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{ +className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{ +className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]}]}},grmr_objectivec:e=>{ +const n=/[a-zA-Z@][a-zA-Z0-9_]*/,t={$pattern:n, +keyword:["@interface","@class","@protocol","@implementation"]};return{ +name:"Objective-C",aliases:["mm","objc","obj-c","obj-c++","objective-c++"], +keywords:{"variable.language":["this","super"],$pattern:n, +keyword:["while","export","sizeof","typedef","const","struct","for","union","volatile","static","mutable","if","do","return","goto","enum","else","break","extern","asm","case","default","register","explicit","typename","switch","continue","inline","readonly","assign","readwrite","self","@synchronized","id","typeof","nonatomic","IBOutlet","IBAction","strong","weak","copy","in","out","inout","bycopy","byref","oneway","__strong","__weak","__block","__autoreleasing","@private","@protected","@public","@try","@property","@end","@throw","@catch","@finally","@autoreleasepool","@synthesize","@dynamic","@selector","@optional","@required","@encode","@package","@import","@defs","@compatibility_alias","__bridge","__bridge_transfer","__bridge_retained","__bridge_retain","__covariant","__contravariant","__kindof","_Nonnull","_Nullable","_Null_unspecified","__FUNCTION__","__PRETTY_FUNCTION__","__attribute__","getter","setter","retain","unsafe_unretained","nonnull","nullable","null_unspecified","null_resettable","class","instancetype","NS_DESIGNATED_INITIALIZER","NS_UNAVAILABLE","NS_REQUIRES_SUPER","NS_RETURNS_INNER_POINTER","NS_INLINE","NS_AVAILABLE","NS_DEPRECATED","NS_ENUM","NS_OPTIONS","NS_SWIFT_UNAVAILABLE","NS_ASSUME_NONNULL_BEGIN","NS_ASSUME_NONNULL_END","NS_REFINED_FOR_SWIFT","NS_SWIFT_NAME","NS_SWIFT_NOTHROW","NS_DURING","NS_HANDLER","NS_ENDHANDLER","NS_VALUERETURN","NS_VOIDRETURN"], +literal:["false","true","FALSE","TRUE","nil","YES","NO","NULL"], +built_in:["dispatch_once_t","dispatch_queue_t","dispatch_sync","dispatch_async","dispatch_once"], +type:["int","float","char","unsigned","signed","short","long","double","wchar_t","unichar","void","bool","BOOL","id|0","_Bool"] +},illegal:"/,end:/$/,illegal:"\\n" +},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"class", +begin:"("+t.keyword.join("|")+")\\b",end:/(\{|$)/,excludeEnd:!0,keywords:t, +contains:[e.UNDERSCORE_TITLE_MODE]},{begin:"\\."+e.UNDERSCORE_IDENT_RE, +relevance:0}]}},grmr_perl:e=>{const n=e.regex,t=/[dualxmsipngr]{0,12}/,a={ +$pattern:/[\w.]+/, +keyword:"abs accept alarm and atan2 bind binmode bless break caller chdir chmod chomp chop chown chr chroot close closedir connect continue cos crypt dbmclose dbmopen defined delete die do dump each else elsif endgrent endhostent endnetent endprotoent endpwent endservent eof eval exec exists exit exp fcntl fileno flock for foreach fork format formline getc getgrent getgrgid getgrnam gethostbyaddr gethostbyname gethostent getlogin getnetbyaddr getnetbyname getnetent getpeername getpgrp getpriority getprotobyname getprotobynumber getprotoent getpwent getpwnam getpwuid getservbyname getservbyport getservent getsockname getsockopt given glob gmtime goto grep gt hex if index int ioctl join keys kill last lc lcfirst length link listen local localtime log lstat lt ma map mkdir msgctl msgget msgrcv msgsnd my ne next no not oct open opendir or ord our pack package pipe pop pos print printf prototype push q|0 qq quotemeta qw qx rand read readdir readline readlink readpipe recv redo ref rename require reset return reverse rewinddir rindex rmdir say scalar seek seekdir select semctl semget semop send setgrent sethostent setnetent setpgrp setpriority setprotoent setpwent setservent setsockopt shift shmctl shmget shmread shmwrite shutdown sin sleep socket socketpair sort splice split sprintf sqrt srand stat state study sub substr symlink syscall sysopen sysread sysseek system syswrite tell telldir tie tied time times tr truncate uc ucfirst umask undef unless unlink unpack unshift untie until use utime values vec wait waitpid wantarray warn when while write x|0 xor y|0" +},i={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:a},r={begin:/->\{/, +end:/\}/},s={variants:[{begin:/\$\d/},{ +begin:n.concat(/[$%@](\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za-z])(?![@$%])") +},{begin:/[$%@][^\s\w{]/,relevance:0}] +},o=[e.BACKSLASH_ESCAPE,i,s],l=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],c=(e,a,i="\\1")=>{ +const r="\\1"===i?i:n.concat(i,a) +;return n.concat(n.concat("(?:",e,")"),a,/(?:\\.|[^\\\/])*?/,r,/(?:\\.|[^\\\/])*?/,i,t) +},d=(e,a,i)=>n.concat(n.concat("(?:",e,")"),a,/(?:\\.|[^\\\/])*?/,i,t),g=[s,e.HASH_COMMENT_MODE,e.COMMENT(/^=\w/,/=cut/,{ +endsWithParent:!0}),r,{className:"string",contains:o,variants:[{ +begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[", +end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{ +begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">", +relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'", +contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`", +contains:[e.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{ +begin:"-?\\w+\\s*=>",relevance:0}]},{className:"number", +begin:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b", +relevance:0},{ +begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*", +keywords:"split return print reverse grep",relevance:0, +contains:[e.HASH_COMMENT_MODE,{className:"regexp",variants:[{ +begin:c("s|tr|y",n.either(...l,{capture:!0}))},{begin:c("s|tr|y","\\(","\\)")},{ +begin:c("s|tr|y","\\[","\\]")},{begin:c("s|tr|y","\\{","\\}")}],relevance:2},{ +className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{ +begin:d("(?:m|qr)?",/\//,/\//)},{begin:d("m|qr",n.either(...l,{capture:!0 +}),/\1/)},{begin:d("m|qr",/\(/,/\)/)},{begin:d("m|qr",/\[/,/\]/)},{ +begin:d("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub", +end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE]},{ +begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$", +subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}] +}];return i.contains=g,r.contains=g,{name:"Perl",aliases:["pl","pm"],keywords:a, +contains:g}},grmr_php:e=>{ +const n=e.regex,t=/(?![A-Za-z0-9])(?![$])/,a=n.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,t),i=n.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,t),r={ +scope:"variable",match:"\\$+"+a},s={scope:"subst",variants:[{begin:/\$\w+/},{ +begin:/\{\$/,end:/\}/}]},o=e.inherit(e.APOS_STRING_MODE,{illegal:null +}),l="[ \t\n]",c={scope:"string",variants:[e.inherit(e.QUOTE_STRING_MODE,{ +illegal:null,contains:e.QUOTE_STRING_MODE.contains.concat(s)}),o,{ +begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/, +contains:e.QUOTE_STRING_MODE.contains.concat(s),"on:begin":(e,n)=>{ +n.data._beginMatch=e[1]||e[2]},"on:end":(e,n)=>{ +n.data._beginMatch!==e[1]&&n.ignoreMatch()}},e.END_SAME_AS_BEGIN({ +begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/})]},d={scope:"number",variants:[{ +begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{ +begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{ +begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?" +}],relevance:0 +},g=["false","null","true"],u=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],b=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],m={ +keyword:u,literal:(e=>{const n=[];return e.forEach((e=>{ +n.push(e),e.toLowerCase()===e?n.push(e.toUpperCase()):n.push(e.toLowerCase()) +})),n})(g),built_in:b},p=e=>e.map((e=>e.replace(/\|\d+$/,""))),_={variants:[{ +match:[/new/,n.concat(l,"+"),n.concat("(?!",p(b).join("\\b|"),"\\b)"),i],scope:{ +1:"keyword",4:"title.class"}}]},h=n.concat(a,"\\b(?!\\()"),f={variants:[{ +match:[n.concat(/::/,n.lookahead(/(?!class\b)/)),h],scope:{2:"variable.constant" +}},{match:[/::/,/class/],scope:{2:"variable.language"}},{ +match:[i,n.concat(/::/,n.lookahead(/(?!class\b)/)),h],scope:{1:"title.class", +3:"variable.constant"}},{match:[i,n.concat("::",n.lookahead(/(?!class\b)/))], +scope:{1:"title.class"}},{match:[i,/::/,/class/],scope:{1:"title.class", +3:"variable.language"}}]},E={scope:"attr", +match:n.concat(a,n.lookahead(":"),n.lookahead(/(?!::)/))},y={relevance:0, +begin:/\(/,end:/\)/,keywords:m,contains:[E,r,f,e.C_BLOCK_COMMENT_MODE,c,d,_] +},N={relevance:0, +match:[/\b/,n.concat("(?!fn\\b|function\\b|",p(u).join("\\b|"),"|",p(b).join("\\b|"),"\\b)"),a,n.concat(l,"*"),n.lookahead(/(?=\()/)], +scope:{3:"title.function.invoke"},contains:[y]};y.contains.push(N) +;const w=[E,f,e.C_BLOCK_COMMENT_MODE,c,d,_];return{case_insensitive:!1, +keywords:m,contains:[{begin:n.concat(/#\[\s*/,i),beginScope:"meta",end:/]/, +endScope:"meta",keywords:{literal:g,keyword:["new","array"]},contains:[{ +begin:/\[/,end:/]/,keywords:{literal:g,keyword:["new","array"]}, +contains:["self",...w]},...w,{scope:"meta",match:i}] +},e.HASH_COMMENT_MODE,e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/",{contains:[{ +scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/, +keywords:"__halt_compiler",starts:{scope:"comment",end:e.MATCH_NOTHING_RE, +contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},{scope:"meta",variants:[{ +begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{ +begin:/\?>/}]},{scope:"variable.language",match:/\$this\b/},r,N,f,{ +match:[/const/,/\s/,a],scope:{1:"keyword",3:"variable.constant"}},_,{ +scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/, +excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use" +},e.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params", +begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:m, +contains:["self",r,f,e.C_BLOCK_COMMENT_MODE,c,d]}]},{scope:"class",variants:[{ +beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait", +illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{ +beginKeywords:"extends implements"},e.UNDERSCORE_TITLE_MODE]},{ +beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/, +contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{ +beginKeywords:"use",relevance:0,end:";",contains:[{ +match:/\b(as|const|function)\b/,scope:"keyword"},e.UNDERSCORE_TITLE_MODE]},c,d]} +},grmr_php_template:e=>({name:"PHP template",subLanguage:"xml",contains:[{ +begin:/<\?(php|=)?/,end:/\?>/,subLanguage:"php",contains:[{begin:"/\\*", +end:"\\*/",skip:!0},{begin:'b"',end:'"',skip:!0},{begin:"b'",end:"'",skip:!0 +},e.inherit(e.APOS_STRING_MODE,{illegal:null,className:null,contains:null, +skip:!0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null,className:null, +contains:null,skip:!0})]}]}),grmr_plaintext:e=>({name:"Plain text", +aliases:["text","txt"],disableAutodetect:!0}),grmr_python:e=>{ +const n=e.regex,t=/[\p{XID_Start}_]\p{XID_Continue}*/u,a=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],i={ +$pattern:/[A-Za-z]\w+|__\w+__/,keyword:a, +built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"], +literal:["__debug__","Ellipsis","False","None","NotImplemented","True"], +type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"] +},r={className:"meta",begin:/^(>>>|\.\.\.) /},s={className:"subst",begin:/\{/, +end:/\}/,keywords:i,illegal:/#/},o={begin:/\{\{/,relevance:0},l={ +className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{ +begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/, +contains:[e.BACKSLASH_ESCAPE,r],relevance:10},{ +begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/, +contains:[e.BACKSLASH_ESCAPE,r],relevance:10},{ +begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/, +contains:[e.BACKSLASH_ESCAPE,r,o,s]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/, +end:/"""/,contains:[e.BACKSLASH_ESCAPE,r,o,s]},{begin:/([uU]|[rR])'/,end:/'/, +relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{ +begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/, +end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/, +contains:[e.BACKSLASH_ESCAPE,o,s]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/, +contains:[e.BACKSLASH_ESCAPE,o,s]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE] +},c="[0-9](_?[0-9])*",d=`(\\b(${c}))?\\.(${c})|\\b(${c})\\.`,g="\\b|"+a.join("|"),u={ +className:"number",relevance:0,variants:[{ +begin:`(\\b(${c})|(${d}))[eE][+-]?(${c})[jJ]?(?=${g})`},{begin:`(${d})[jJ]?`},{ +begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${g})`},{ +begin:`\\b0[bB](_?[01])+[lL]?(?=${g})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${g})` +},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${g})`},{begin:`\\b(${c})[jJ](?=${g})` +}]},b={className:"comment",begin:n.lookahead(/# type:/),end:/$/,keywords:i, +contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},m={ +className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/, +end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:i, +contains:["self",r,u,l,e.HASH_COMMENT_MODE]}]};return s.contains=[l,u,r],{ +name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:i, +illegal:/(<\/|\?)|=>/,contains:[r,u,{begin:/\bself\b/},{beginKeywords:"if", +relevance:0},l,b,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,t],scope:{ +1:"keyword",3:"title.function"},contains:[m]},{variants:[{ +match:[/\bclass/,/\s+/,t,/\s*/,/\(\s*/,t,/\s*\)/]},{match:[/\bclass/,/\s+/,t]}], +scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{ +className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[u,m,l]}]}}, +grmr_python_repl:e=>({aliases:["pycon"],contains:[{className:"meta.prompt", +starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{ +begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}),grmr_r:e=>{ +const n=e.regex,t=/(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/,a=n.either(/0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,/0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/),i=/[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/,r=n.either(/[()]/,/[{}]/,/\[\[/,/[[\]]/,/\\/,/,/) +;return{name:"R",keywords:{$pattern:t, +keyword:"function if in break next repeat else for while", +literal:"NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10", +built_in:"LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm" +},contains:[e.COMMENT(/#'/,/$/,{contains:[{scope:"doctag",match:/@examples/, +starts:{end:n.lookahead(n.either(/\n^#'\s*(?=@[a-zA-Z]+)/,/\n^(?!#')/)), +endsParent:!0}},{scope:"doctag",begin:"@param",end:/$/,contains:[{ +scope:"variable",variants:[{match:t},{match:/`(?:\\.|[^`\\])+`/}],endsParent:!0 +}]},{scope:"doctag",match:/@[a-zA-Z]+/},{scope:"keyword",match:/\\[a-zA-Z]+/}] +}),e.HASH_COMMENT_MODE,{scope:"string",contains:[e.BACKSLASH_ESCAPE], +variants:[e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\(/,end:/\)(-*)"/ +}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\{/,end:/\}(-*)"/ +}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\[/,end:/\](-*)"/ +}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\(/,end:/\)(-*)'/ +}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\{/,end:/\}(-*)'/ +}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\[/,end:/\](-*)'/}),{begin:'"',end:'"', +relevance:0},{begin:"'",end:"'",relevance:0}]},{relevance:0,variants:[{scope:{ +1:"operator",2:"number"},match:[i,a]},{scope:{1:"operator",2:"number"}, +match:[/%[^%]*%/,a]},{scope:{1:"punctuation",2:"number"},match:[r,a]},{scope:{ +2:"number"},match:[/[^a-zA-Z0-9._]|^/,a]}]},{scope:{3:"operator"}, +match:[t,/\s+/,/<-/,/\s+/]},{scope:"operator",relevance:0,variants:[{match:i},{ +match:/%[^%]*%/}]},{scope:"punctuation",relevance:0,match:r},{begin:"`",end:"`", +contains:[{begin:/\\./}]}]}},grmr_ruby:e=>{ +const n=e.regex,t="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",a=n.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),i=n.concat(a,/(::\w+)*/),r={ +"variable.constant":["__FILE__","__LINE__","__ENCODING__"], +"variable.language":["self","super"], +keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield","include","extend","prepend","public","private","protected","raise","throw"], +built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"], +literal:["true","false","nil"]},s={className:"doctag",begin:"@[A-Za-z]+"},o={ +begin:"#<",end:">"},l=[e.COMMENT("#","$",{contains:[s] +}),e.COMMENT("^=begin","^=end",{contains:[s],relevance:10 +}),e.COMMENT("^__END__",e.MATCH_NOTHING_RE)],c={className:"subst",begin:/#\{/, +end:/\}/,keywords:r},d={className:"string",contains:[e.BACKSLASH_ESCAPE,c], +variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{ +begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{ +begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?/},{begin:/%[qQwWx]?\//, +end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{ +begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{ +begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{ +begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{ +begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{ +begin:n.concat(/<<[-~]?'?/,n.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)), +contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/, +contains:[e.BACKSLASH_ESCAPE,c]})]}]},g="[0-9](_?[0-9])*",u={className:"number", +relevance:0,variants:[{ +begin:`\\b([1-9](_?[0-9])*|0)(\\.(${g}))?([eE][+-]?(${g})|r)?i?\\b`},{ +begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b" +},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{ +begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{ +begin:"\\b0(_?[0-7])+r?i?\\b"}]},b={variants:[{match:/\(\)/},{ +className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0, +keywords:r}]},m=[d,{variants:[{match:[/class\s+/,i,/\s+<\s+/,i]},{ +match:[/\b(class|module)\s+/,i]}],scope:{2:"title.class", +4:"title.class.inherited"},keywords:r},{match:[/(include|extend)\s+/,i],scope:{ +2:"title.class"},keywords:r},{relevance:0,match:[i,/\.new[. (]/],scope:{ +1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/, +className:"variable.constant"},{relevance:0,match:a,scope:"title.class"},{ +match:[/def/,/\s+/,t],scope:{1:"keyword",3:"title.function"},contains:[b]},{ +begin:e.IDENT_RE+"::"},{className:"symbol", +begin:e.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol", +begin:":(?!\\s)",contains:[d,{begin:t}],relevance:0},u,{className:"variable", +begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{ +className:"params",begin:/\|/,end:/\|/,excludeBegin:!0,excludeEnd:!0, +relevance:0,keywords:r},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*", +keywords:"unless",contains:[{className:"regexp",contains:[e.BACKSLASH_ESCAPE,c], +illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{ +begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[", +end:"\\][a-z]*"}]}].concat(o,l),relevance:0}].concat(o,l) +;c.contains=m,b.contains=m;const p=[{begin:/^\s*=>/,starts:{end:"$",contains:m} +},{className:"meta.prompt", +begin:"^([>?]>|[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]|(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>)(?=[ ])", +starts:{end:"$",keywords:r,contains:m}}];return l.unshift(o),{name:"Ruby", +aliases:["rb","gemspec","podspec","thor","irb"],keywords:r,illegal:/\/\*/, +contains:[e.SHEBANG({binary:"ruby"})].concat(p).concat(l).concat(m)}}, +grmr_rust:e=>{const n=e.regex,t={className:"title.function.invoke",relevance:0, +begin:n.concat(/\b/,/(?!let|for|while|if|else|match\b)/,e.IDENT_RE,n.lookahead(/\s*\(/)) +},a="([ui](8|16|32|64|128|size)|f(32|64))?",i=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],r=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"] +;return{name:"Rust",aliases:["rs"],keywords:{$pattern:e.IDENT_RE+"!?",type:r, +keyword:["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","unsafe","unsized","use","virtual","where","while","yield"], +literal:["true","false","Some","None","Ok","Err"],built_in:i},illegal:""},t]}}, +grmr_scss:e=>{const n=ie(e),t=le,a=oe,i="@[a-z-]+",r={className:"variable", +begin:"(\\$[a-zA-Z-][a-zA-Z0-9_-]*)\\b",relevance:0};return{name:"SCSS", +case_insensitive:!0,illegal:"[=/|']", +contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,n.CSS_NUMBER_MODE,{ +className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{ +className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0 +},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag", +begin:"\\b("+re.join("|")+")\\b",relevance:0},{className:"selector-pseudo", +begin:":("+a.join("|")+")"},{className:"selector-pseudo", +begin:":(:)?("+t.join("|")+")"},r,{begin:/\(/,end:/\)/, +contains:[n.CSS_NUMBER_MODE]},n.CSS_VARIABLE,{className:"attribute", +begin:"\\b("+ce.join("|")+")\\b"},{ +begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b" +},{begin:/:/,end:/[;}{]/,relevance:0, +contains:[n.BLOCK_COMMENT,r,n.HEXCOLOR,n.CSS_NUMBER_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,n.IMPORTANT,n.FUNCTION_DISPATCH] +},{begin:"@(page|font-face)",keywords:{$pattern:i,keyword:"@page @font-face"}},{ +begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/, +keyword:"and or not only",attribute:se.join(" ")},contains:[{begin:i, +className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute" +},r,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,n.HEXCOLOR,n.CSS_NUMBER_MODE] +},n.FUNCTION_DISPATCH]}},grmr_shell:e=>({name:"Shell Session", +aliases:["console","shellsession"],contains:[{className:"meta.prompt", +begin:/^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/, +subLanguage:"bash"}}]}),grmr_sql:e=>{ +const n=e.regex,t=e.COMMENT("--","$"),a=["true","false","unknown"],i=["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],r=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],s=["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"],o=r,l=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year","add","asc","collation","desc","final","first","last","view"].filter((e=>!r.includes(e))),c={ +begin:n.concat(/\b/,n.either(...o),/\s*\(/),relevance:0,keywords:{built_in:o}} +;return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{ +$pattern:/\b[\w\.]+/,keyword:((e,{exceptions:n,when:t}={})=>{const a=t +;return n=n||[],e.map((e=>e.match(/\|\d+$/)||n.includes(e)?e:a(e)?e+"|0":e)) +})(l,{when:e=>e.length<3}),literal:a,type:i, +built_in:["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"] +},contains:[{begin:n.either(...s),relevance:0,keywords:{$pattern:/[\w\.]+/, +keyword:l.concat(s),literal:a,type:i}},{className:"type", +begin:n.either("double precision","large object","with timezone","without timezone") +},c,{className:"variable",begin:/@[a-z0-9][a-z0-9_]*/},{className:"string", +variants:[{begin:/'/,end:/'/,contains:[{begin:/''/}]}]},{begin:/"/,end:/"/, +contains:[{begin:/""/}]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,t,{ +className:"operator",begin:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/, +relevance:0}]}},grmr_swift:e=>{const n={match:/\s+/,relevance:0 +},t=e.COMMENT("/\\*","\\*/",{contains:["self"]}),a=[e.C_LINE_COMMENT_MODE,t],i={ +match:[/\./,m(...xe,...Me)],className:{2:"keyword"}},r={match:b(/\./,m(...Ae)), +relevance:0},s=Ae.filter((e=>"string"==typeof e)).concat(["_|0"]),o={variants:[{ +className:"keyword", +match:m(...Ae.filter((e=>"string"!=typeof e)).concat(Se).map(ke),...Me)}]},l={ +$pattern:m(/\b\w+/,/#\w+/),keyword:s.concat(Re),literal:Ce},c=[i,r,o],g=[{ +match:b(/\./,m(...De)),relevance:0},{className:"built_in", +match:b(/\b/,m(...De),/(?=\()/)}],u={match:/->/,relevance:0},p=[u,{ +className:"operator",relevance:0,variants:[{match:Be},{match:`\\.(\\.|${Le})+`}] +}],_="([0-9]_*)+",h="([0-9a-fA-F]_*)+",f={className:"number",relevance:0, +variants:[{match:`\\b(${_})(\\.(${_}))?([eE][+-]?(${_}))?\\b`},{ +match:`\\b0x(${h})(\\.(${h}))?([pP][+-]?(${_}))?\\b`},{match:/\b0o([0-7]_*)+\b/ +},{match:/\b0b([01]_*)+\b/}]},E=(e="")=>({className:"subst",variants:[{ +match:b(/\\/,e,/[0\\tnr"']/)},{match:b(/\\/,e,/u\{[0-9a-fA-F]{1,8}\}/)}] +}),y=(e="")=>({className:"subst",match:b(/\\/,e,/[\t ]*(?:[\r\n]|\r\n)/) +}),N=(e="")=>({className:"subst",label:"interpol",begin:b(/\\/,e,/\(/),end:/\)/ +}),w=(e="")=>({begin:b(e,/"""/),end:b(/"""/,e),contains:[E(e),y(e),N(e)] +}),v=(e="")=>({begin:b(e,/"/),end:b(/"/,e),contains:[E(e),N(e)]}),O={ +className:"string", +variants:[w(),w("#"),w("##"),w("###"),v(),v("#"),v("##"),v("###")] +},k=[e.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0, +contains:[e.BACKSLASH_ESCAPE]}],x={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//, +contains:k},M=e=>{const n=b(e,/\//),t=b(/\//,e);return{begin:n,end:t, +contains:[...k,{scope:"comment",begin:`#(?!.*${t})`,end:/$/}]}},S={ +scope:"regexp",variants:[M("###"),M("##"),M("#"),x]},A={match:b(/`/,Fe,/`/) +},C=[A,{className:"variable",match:/\$\d+/},{className:"variable", +match:`\\$${ze}+`}],T=[{match:/(@|#(un)?)available/,scope:"keyword",starts:{ +contains:[{begin:/\(/,end:/\)/,keywords:Pe,contains:[...p,f,O]}]}},{ +scope:"keyword",match:b(/@/,m(...je))},{scope:"meta",match:b(/@/,Fe)}],R={ +match:d(/\b[A-Z]/),relevance:0,contains:[{className:"type", +match:b(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,ze,"+") +},{className:"type",match:Ue,relevance:0},{match:/[?!]+/,relevance:0},{ +match:/\.\.\./,relevance:0},{match:b(/\s+&\s+/,d(Ue)),relevance:0}]},D={ +begin://,keywords:l,contains:[...a,...c,...T,u,R]};R.contains.push(D) +;const I={begin:/\(/,end:/\)/,relevance:0,keywords:l,contains:["self",{ +match:b(Fe,/\s*:/),keywords:"_|0",relevance:0 +},...a,S,...c,...g,...p,f,O,...C,...T,R]},L={begin://, +keywords:"repeat each",contains:[...a,R]},B={begin:/\(/,end:/\)/,keywords:l, +contains:[{begin:m(d(b(Fe,/\s*:/)),d(b(Fe,/\s+/,Fe,/\s*:/))),end:/:/, +relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params", +match:Fe}]},...a,...c,...p,f,O,...T,R,I],endsParent:!0,illegal:/["']/},$={ +match:[/(func|macro)/,/\s+/,m(A.match,Fe,Be)],className:{1:"keyword", +3:"title.function"},contains:[L,B,n],illegal:[/\[/,/%/]},z={ +match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"}, +contains:[L,B,n],illegal:/\[|%/},F={match:[/operator/,/\s+/,Be],className:{ +1:"keyword",3:"title"}},U={begin:[/precedencegroup/,/\s+/,Ue],className:{ +1:"keyword",3:"title"},contains:[R],keywords:[...Te,...Ce],end:/}/} +;for(const e of O.variants){const n=e.contains.find((e=>"interpol"===e.label)) +;n.keywords=l;const t=[...c,...g,...p,f,O,...C];n.contains=[...t,{begin:/\(/, +end:/\)/,contains:["self",...t]}]}return{name:"Swift",keywords:l, +contains:[...a,$,z,{beginKeywords:"struct protocol class extension enum actor", +end:"\\{",excludeEnd:!0,keywords:l,contains:[e.inherit(e.TITLE_MODE,{ +className:"title.class",begin:/[A-Za-z$_][\u00C0-\u02B80-9A-Za-z$_]*/}),...c] +},F,U,{beginKeywords:"import",end:/$/,contains:[...a],relevance:0 +},S,...c,...g,...p,f,O,...C,...T,R,I]}},grmr_typescript:e=>{ +const n=Oe(e),t=_e,a=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],i={ +beginKeywords:"namespace",end:/\{/,excludeEnd:!0, +contains:[n.exports.CLASS_REFERENCE]},r={beginKeywords:"interface",end:/\{/, +excludeEnd:!0,keywords:{keyword:"interface extends",built_in:a}, +contains:[n.exports.CLASS_REFERENCE]},s={$pattern:_e, +keyword:he.concat(["type","namespace","interface","public","private","protected","implements","declare","abstract","readonly","enum","override"]), +literal:fe,built_in:ve.concat(a),"variable.language":we},o={className:"meta", +begin:"@"+t},l=(e,n,t)=>{const a=e.contains.findIndex((e=>e.label===n)) +;if(-1===a)throw Error("can not find mode to replace");e.contains.splice(a,1,t)} +;return Object.assign(n.keywords,s), +n.exports.PARAMS_CONTAINS.push(o),n.contains=n.contains.concat([o,i,r]), +l(n,"shebang",e.SHEBANG()),l(n,"use_strict",{className:"meta",relevance:10, +begin:/^\s*['"]use strict['"]/ +}),n.contains.find((e=>"func.def"===e.label)).relevance=0,Object.assign(n,{ +name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n},grmr_vbnet:e=>{ +const n=e.regex,t=/\d{1,2}\/\d{1,2}\/\d{4}/,a=/\d{4}-\d{1,2}-\d{1,2}/,i=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,r=/\d{1,2}(:\d{1,2}){1,2}/,s={ +className:"literal",variants:[{begin:n.concat(/# */,n.either(a,t),/ *#/)},{ +begin:n.concat(/# */,r,/ *#/)},{begin:n.concat(/# */,i,/ *#/)},{ +begin:n.concat(/# */,n.either(a,t),/ +/,n.either(i,r),/ *#/)}] +},o=e.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}] +}),l=e.COMMENT(null,/$/,{variants:[{begin:/'/},{begin:/([\t ]|^)REM(?=\s)/}]}) +;return{name:"Visual Basic .NET",aliases:["vb"],case_insensitive:!0, +classNameAliases:{label:"symbol"},keywords:{ +keyword:"addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield", +built_in:"addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort", +type:"boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort", +literal:"true false nothing"}, +illegal:"//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",contains:[{ +className:"string",begin:/"(""|[^/n])"C\b/},{className:"string",begin:/"/, +end:/"/,illegal:/\n/,contains:[{begin:/""/}]},s,{className:"number",relevance:0, +variants:[{begin:/\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/ +},{begin:/\b\d[\d_]*((U?[SIL])|[%&])?/},{begin:/&H[\dA-F_]+((U?[SIL])|[%&])?/},{ +begin:/&O[0-7_]+((U?[SIL])|[%&])?/},{begin:/&B[01_]+((U?[SIL])|[%&])?/}]},{ +className:"label",begin:/^\w+:/},o,l,{className:"meta", +begin:/[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/, +end:/$/,keywords:{ +keyword:"const disable else elseif enable end externalsource if region then"}, +contains:[l]}]}},grmr_wasm:e=>{e.regex;const n=e.COMMENT(/\(;/,/;\)/) +;return n.contains.push("self"),{name:"WebAssembly",keywords:{$pattern:/[\w.]+/, +keyword:["anyfunc","block","br","br_if","br_table","call","call_indirect","data","drop","elem","else","end","export","func","global.get","global.set","local.get","local.set","local.tee","get_global","get_local","global","if","import","local","loop","memory","memory.grow","memory.size","module","mut","nop","offset","param","result","return","select","set_global","set_local","start","table","tee_local","then","type","unreachable"] +},contains:[e.COMMENT(/;;/,/$/),n,{match:[/(?:offset|align)/,/\s*/,/=/], +className:{1:"keyword",3:"operator"}},{className:"variable",begin:/\$[\w_]+/},{ +match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},{ +begin:[/(?:func|call|call_indirect)/,/\s+/,/\$[^\s)]+/],className:{1:"keyword", +3:"title.function"}},e.QUOTE_STRING_MODE,{match:/(i32|i64|f32|f64)(?!\.)/, +className:"type"},{className:"keyword", +match:/\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/ +},{className:"number",relevance:0, +match:/[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/ +}]}},grmr_xml:e=>{ +const n=e.regex,t=n.concat(/[\p{L}_]/u,n.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),a={ +className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},i={begin:/\s/, +contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}] +},r=e.inherit(i,{begin:/\(/,end:/\)/}),s=e.inherit(e.APOS_STRING_MODE,{ +className:"string"}),o=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),l={ +endsWithParent:!0,illegal:/`]+/}]}]}]};return{ +name:"HTML, XML", +aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"], +case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin://,relevance:10,contains:[i,o,s,r,{begin:/\[/,end:/\]/,contains:[{ +className:"meta",begin://,contains:[i,r,o,s]}]}] +},e.COMMENT(//,{relevance:10}),{begin://, +relevance:10},a,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/, +relevance:10,contains:[o]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag", +begin:/)/,end:/>/,keywords:{name:"style"},contains:[l],starts:{ +end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag", +begin:/)/,end:/>/,keywords:{name:"script"},contains:[l],starts:{ +end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{ +className:"tag",begin:/<>|<\/>/},{className:"tag", +begin:n.concat(//,/>/,/\s/)))), +end:/\/?>/,contains:[{className:"name",begin:t,relevance:0,starts:l}]},{ +className:"tag",begin:n.concat(/<\//,n.lookahead(n.concat(t,/>/))),contains:[{ +className:"name",begin:t,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]} +},grmr_yaml:e=>{ +const n="true false yes no null",t="[\\w#;/?:@&=+$,.~*'()[\\]]+",a={ +className:"string",relevance:0,variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/ +},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable", +variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},i=e.inherit(a,{ +variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),r={ +end:",",endsWithParent:!0,excludeEnd:!0,keywords:n,relevance:0},s={begin:/\{/, +end:/\}/,contains:[r],illegal:"\\n",relevance:0},o={begin:"\\[",end:"\\]", +contains:[r],illegal:"\\n",relevance:0},l=[{className:"attr",variants:[{ +begin:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{begin:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{ +begin:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{className:"meta",begin:"^---\\s*$", +relevance:10},{className:"string", +begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{ +begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0, +relevance:0},{className:"type",begin:"!\\w+!"+t},{className:"type", +begin:"!<"+t+">"},{className:"type",begin:"!"+t},{className:"type",begin:"!!"+t +},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta", +begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)", +relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:n,keywords:{literal:n}},{ +className:"number", +begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b" +},{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},s,o,a],c=[...l] +;return c.pop(),c.push(i),r.contains=c,{name:"YAML",case_insensitive:!0, +aliases:["yml"],contains:l}}});const He=ae;for(const e of Object.keys(Ke)){ +const n=e.replace("grmr_","").replace("_","-");He.registerLanguage(n,Ke[e])} +return He}() +;"object"==typeof exports&&"undefined"!=typeof module&&(module.exports=hljs); \ No newline at end of file diff --git a/dist/core/export-html/vendor/marked.min.js b/dist/core/export-html/vendor/marked.min.js new file mode 100644 index 0000000..9d79575 --- /dev/null +++ b/dist/core/export-html/vendor/marked.min.js @@ -0,0 +1,78 @@ +/** + * marked v18.0.5 - a markdown parser + * Copyright (c) 2018-2026, MarkedJS. (MIT License) + * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) + * https://github.com/markedjs/marked + */ + +/** + * DO NOT EDIT THIS FILE + * The code in this file is generated from files in ./src/ + */ +(function(g,f){if(typeof exports=="object"&&typeof module<"u"){module.exports=f()}else if("function"==typeof define && define.amd){define("marked",f)}else {g["marked"]=f()}}(typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : this,function(){var exports={};var __exports=exports;var module={exports}; +"use strict";var N=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var ye=Object.prototype.hasOwnProperty;var Pe=(l,e)=>{for(var t in e)N(l,t,{get:e[t],enumerable:!0})},Se=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of we(e))!ye.call(l,s)&&s!==t&&N(l,s,{get:()=>e[s],enumerable:!(n=Oe(e,s))||n.enumerable});return l};var $e=l=>Se(N({},"__esModule",{value:!0}),l);var Rt={};Pe(Rt,{Hooks:()=>P,Lexer:()=>x,Marked:()=>C,Parser:()=>b,Renderer:()=>y,TextRenderer:()=>S,Tokenizer:()=>w,defaults:()=>T,getDefaults:()=>_,lexer:()=>bt,marked:()=>g,options:()=>ht,parse:()=>mt,parseInline:()=>ft,parser:()=>xt,setOptions:()=>kt,use:()=>dt,walkTokens:()=>gt});module.exports=$e(Rt);function _(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=_();function Q(l){T=l}var z={exec:()=>null};function E(l){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l(n),e[n]=s),s}}function d(l,e=""){let t=typeof l=="string"?l:l.source,n={replace:(s,r)=>{let i=typeof r=="string"?r:r.source;return i=i.replace(m.caret,"$1"),t=t.replace(s,i),n},getRegex:()=>new RegExp(t,e)};return n}var Le=((l="")=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l=>new RegExp(`^( {0,3}${l})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:E(l=>new RegExp(`^ {0,${l}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:E(l=>new RegExp(`^ {0,${l}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:E(l=>new RegExp(`^ {0,${l}}(?:\`\`\`|~~~)`)),headingBeginRegex:E(l=>new RegExp(`^ {0,${l}}#`)),htmlBeginRegex:E(l=>new RegExp(`^ {0,${l}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:E(l=>new RegExp(`^ {0,${l}}>`))},_e=/^(?:[ \t]*(?:\n|$))+/,ze=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Me=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,D=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ee=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,F=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ae=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,le=d(ae).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Ie=d(ae).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),U=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ae=/^[^\n]+/,K=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Ce=d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",K).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Be=d(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,F).getRegex(),H="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",W=/|$))/,De=d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",W).replace("tag",H).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ue=d(U).replace("hr",D).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),qe=d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",ue).getRegex(),X={blockquote:qe,code:ze,def:Ce,fences:Me,heading:Ee,hr:D,html:De,lheading:le,list:Be,newline:_e,paragraph:ue,table:z,text:Ae},ie=d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",D).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex(),ve={...X,lheading:Ie,table:ie,paragraph:d(U).replace("hr",D).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ie).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",H).getRegex()},He={...X,html:d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",W).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:z,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(U).replace("hr",D).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",le).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Ze=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ge=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,pe=/^( {2,}|\\)\n(?!\s*$)/,Ne=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Le?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),he=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Ke=d(he,"u").replace(/punct/g,I).getRegex(),We=d(he,"u").replace(/punct/g,ce).getRegex(),ke="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Xe=d(ke,"gu").replace(/notPunctSpace/g,J).replace(/punctSpace/g,Z).replace(/punct/g,I).getRegex(),Je=d(ke,"gu").replace(/notPunctSpace/g,Fe).replace(/punctSpace/g,je).replace(/punct/g,ce).getRegex(),Ve=d("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,J).replace(/punctSpace/g,Z).replace(/punct/g,I).getRegex(),Ye=d(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,I).getRegex(),et="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",tt=d(et,"gu").replace(/notPunctSpace/g,J).replace(/punctSpace/g,Z).replace(/punct/g,I).getRegex(),nt=d(/\\(punct)/,"gu").replace(/punct/g,I).getRegex(),rt=d(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),st=d(W).replace("(?:-->|$)","-->").getRegex(),it=d("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",st).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),v=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,ot=d(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",v).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),de=d(/^!?\[(label)\]\[(ref)\]/).replace("label",v).replace("ref",K).getRegex(),ge=d(/^!?\[(ref)\](?:\[\])?/).replace("ref",K).getRegex(),at=d("reflink|nolink(?!\\()","g").replace("reflink",de).replace("nolink",ge).getRegex(),oe=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,V={_backpedal:z,anyPunctuation:nt,autolink:rt,blockSkip:Ue,br:pe,code:Ge,del:z,delLDelim:z,delRDelim:z,emStrongLDelim:Ke,emStrongRDelimAst:Xe,emStrongRDelimUnd:Ve,escape:Ze,link:ot,nolink:ge,punctuation:Qe,reflink:de,reflinkSearch:at,tag:it,text:Ne,url:z},lt={...V,link:d(/^!?\[(label)\]\((.*?)\)/).replace("label",v).getRegex(),reflink:d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",v).getRegex()},j={...V,emStrongRDelimAst:Je,emStrongLDelim:We,delLDelim:Ye,delRDelim:tt,url:d(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",oe).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:d(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},fe=l=>pt[l];function O(l,e){if(e){if(m.escapeTest.test(l))return l.replace(m.escapeReplace,fe)}else if(m.escapeTestNoEncode.test(l))return l.replace(m.escapeReplaceNoEncode,fe);return l}function Y(l){try{l=encodeURI(l).replace(m.percentDecode,"%")}catch{return null}return l}function ee(l,e){let t=l.replace(m.findPipe,(r,i,o)=>{let u=!1,a=i;for(;--a>=0&&o[a]==="\\";)u=!u;return u?"|":" |"}),n=t.split(m.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length=0&&m.blankLine.test(e[t]);)t--;return e.length-t<=2?l:e.slice(0,t+1).join(` +`)}function me(l,e){if(l.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n0?-2:-1}function xe(l,e=0){let t=e,n="";for(let s of l)if(s===" "){let r=4-t%4;n+=" ".repeat(r),t+=r}else n+=s,t++;return n}function be(l,e,t,n,s){let r=e.href,i=e.title||null,o=l[1].replace(s.other.outputLinkReplace,"$1");n.state.inLink=!0;let u={type:l[0].charAt(0)==="!"?"image":"link",raw:t,href:r,title:i,text:o,tokens:n.inlineTokens(o)};return n.state.inLink=!1,u}function ct(l,e,t){let n=l.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(` +`).map(r=>{let i=r.match(t.other.beginningSpace);if(i===null)return r;let[o]=i;return o.length>=s.length?r.slice(s.length):r}).join(` +`)}var w=class{options;rules;lexer;constructor(e){this.options=e||T}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:te(t[0]),s=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=ct(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=L(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:L(t[0],` +`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:L(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=L(t[0],` +`).split(` +`),s="",r="",i=[];for(;n.length>0;){let o=!1,u=[],a;for(a=0;a1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let i=this.rules.other.listItemRegex(n),o=!1;for(;e;){let a=!1,c="",p="";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let k=xe(t[2].split(` +`,1)[0],t[1].length),h=e.split(` +`,1)[0],R=!k.trim(),f=0;if(this.options.pedantic?(f=2,p=k.trimStart()):R?f=t[1].length+1:(f=k.search(this.rules.other.nonSpaceChar),f=f>4?1:f,p=k.slice(f),f+=t[1].length),R&&this.rules.other.blankLine.test(h)&&(c+=h+` +`,e=e.substring(h.length+1),a=!0),!a){let $=this.rules.other.nextBulletRegex(f),ne=this.rules.other.hrRegex(f),re=this.rules.other.fencesBeginRegex(f),se=this.rules.other.headingBeginRegex(f),Re=this.rules.other.htmlBeginRegex(f),Te=this.rules.other.blockquoteBeginRegex(f);for(;e;){let G=e.split(` +`,1)[0],B;if(h=G,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting," "),B=h):B=h.replace(this.rules.other.tabCharGlobal," "),re.test(h)||se.test(h)||Re.test(h)||Te.test(h)||$.test(h)||ne.test(h))break;if(B.search(this.rules.other.nonSpaceChar)>=f||!h.trim())p+=` +`+B.slice(f);else{if(R||k.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||re.test(k)||se.test(k)||ne.test(k))break;p+=` +`+h}R=!h.trim(),c+=G+` +`,e=e.substring(G.length+1),k=B.slice(f)}}r.loose||(o?r.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),r.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),r.raw+=c}let u=r.items.at(-1);if(u)u.raw=u.raw.trimEnd(),u.text=u.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let a of r.items){this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]);let c=a.tokens[0];if(a.task&&(c?.type==="text"||c?.type==="paragraph")){a.text=a.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let k=this.lexer.inlineQueue.length-1;k>=0;k--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[k].src)){this.lexer.inlineQueue[k].src=this.lexer.inlineQueue[k].src.replace(this.rules.other.listReplaceTask,"");break}let p=this.rules.other.listTaskCheckbox.exec(a.raw);if(p){let k={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};a.checked=k.checked,r.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=k.raw+a.tokens[0].raw,a.tokens[0].text=k.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(k)):a.tokens.unshift({type:"paragraph",raw:k.raw,text:k.raw,tokens:[k]}):a.tokens.unshift(k)}}else a.task&&(a.task=!1);if(!r.loose){let p=a.tokens.filter(h=>h.type==="space"),k=p.length>0&&p.some(h=>this.rules.other.anyLine.test(h.raw));r.loose=k}}if(r.loose)for(let a of r.items){a.loose=!0;for(let c of a.tokens)c.type==="text"&&(c.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=te(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:L(t[0],` +`),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=ee(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` +`):[],i={type:"table",raw:L(t[0],` +`),header:[],align:[],rows:[]};if(n.length===s.length){for(let o of s)this.rules.other.tableAlignRight.test(o)?i.align.push("right"):this.rules.other.tableAlignCenter.test(o)?i.align.push("center"):this.rules.other.tableAlignLeft.test(o)?i.align.push("left"):i.align.push(null);for(let o=0;o({text:u,tokens:this.lexer.inline(u),header:!1,align:i.align[a]})));return i}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:L(t[0],` +`),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` +`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=L(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=me(t[2],"()");if(i===-2)return;if(i>-1){let u=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,u).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],r=i[3])}else r=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),be(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[s.toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return be(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(s[1]||s[3]||"")||!n||this.rules.inline.punctuation.exec(n)){let i=[...s[0]].length-1,o,u,a=i,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+i);(s=p.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(u=[...o].length,s[3]||s[4]){a+=u;continue}else if((s[5]||s[6])&&i%3&&!((i+u)%3)){c+=u;continue}if(a-=u,a>0)continue;u=Math.min(u,u+a+c);let k=[...s[0]][0].length,h=e.slice(0,i+s.index+k+u);if(Math.min(i,u)%2){let f=h.slice(1,-1);return{type:"em",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}let R=h.slice(2,-2);return{type:"strong",raw:h,text:R,tokens:this.lexer.inlineTokens(R)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let s=this.rules.inline.delLDelim.exec(e);if(!s)return;if(!(s[1]||"")||!n||this.rules.inline.punctuation.exec(n)){let i=[...s[0]].length-1,o,u,a=i,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+i);(s=c.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(u=[...o].length,u!==i))continue;if(s[3]||s[4]){a+=u;continue}if(a-=u,a>0)continue;u=Math.min(u,u+a);let p=[...s[0]][0].length,k=e.slice(0,i+s.index+p+u),h=k.slice(i,-i);return{type:"del",raw:k,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]==="@")n=t[0],s="mailto:"+n;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}};var x=class l{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||T,this.options.tokenizer=this.options.tokenizer||new w,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:q.normal,inline:A.normal};this.options.pedantic?(t.block=q.pedantic,t.inline=A.pedantic):this.options.gfm&&(t.block=q.gfm,this.options.breaks?t.inline=A.breaks:t.inline=A.gfm),this.tokenizer.rules=t}static get rules(){return{block:q,inline:A}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,` +`),this.blockTokens(e,this.tokens);for(let t=0;t(r=o.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let o=t.at(-1);r.raw.length===1&&o!==void 0?o.raw+=` +`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let o=t.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` +`)?"":` +`)+r.raw,o.text+=` +`+r.text,this.inlineQueue.at(-1).src=o.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let o=t.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` +`)?"":` +`)+r.raw,o.text+=` +`+r.raw,this.inlineQueue.at(-1).src=o.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let o=1/0,u=e.slice(1),a;this.options.extensions.startBlock.forEach(c=>{a=c.call({lexer:this},u),typeof a=="number"&&a>=0&&(o=Math.min(o,a))}),o<1/0&&o>=0&&(i=e.substring(0,o+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let o=t.at(-1);n&&o?.type==="paragraph"?(o.raw+=(o.raw.endsWith(` +`)?"":` +`)+r.raw,o.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let o=t.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(` +`)?"":` +`)+r.raw,o.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,s=null;if(this.tokens.links){let a=Object.keys(this.tokens.links);if(a.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)a.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,s.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(s=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)r=s[2]?s[2].length:0,n=n.slice(0,s.index+r)+"["+"a".repeat(s[0].length-r-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let i=!1,o="",u=1/0;for(;e;){if(e.length(a=p.call({lexer:this},e,t))?(e=e.substring(a.raw.length),t.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let p=t.at(-1);a.type==="text"&&p?.type==="text"?(p.raw+=a.raw,p.text+=a.text):t.push(a);continue}if(a=this.tokenizer.emStrong(e,n,o)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.del(e,n,o)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),t.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),t.push(a);continue}let c=e;if(this.options.extensions?.startInline){let p=1/0,k=e.slice(1),h;this.options.extensions.startInline.forEach(R=>{h=R.call({lexer:this},k),typeof h=="number"&&h>=0&&(p=Math.min(p,h))}),p<1/0&&p>=0&&(c=e.substring(0,p+1))}if(a=this.tokenizer.inlineText(c)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(o=a.raw.slice(-1)),i=!0;let p=t.at(-1);p?.type==="text"?(p.raw+=a.raw,p.text+=a.text):t.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}};var y=class{options;parser;constructor(e){this.options=e||T}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(m.notSpaceStart)?.[0],r=e.replace(m.endingNewline,"")+` +`;return s?'
'+(n?r:O(r,!0))+`
+`:"
"+(n?r:O(r,!0))+`
+`}blockquote({tokens:e}){return`
+${this.parser.parse(e)}
+`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} +`}hr(e){return`
+`}list(e){let t=e.ordered,n=e.start,s="";for(let o=0;o +`+s+" +`}listitem(e){return`
  • ${this.parser.parse(e.tokens)}
  • +`}checkbox({checked:e}){return" '}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    +`}table(e){let t="",n="";for(let r=0;r${s}`),` + +`+t+` +`+s+`
    +`}tablerow({text:e}){return` +${e} +`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${O(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),r=Y(e);if(r===null)return s;e=r;let i='
    ",i}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=Y(e);if(r===null)return O(n);e=r;let i=`${O(n)}{let o=r[i].flat(1/0);n=n.concat(this.walkTokens(o,t))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let i=t.renderers[r.name];i?t.renderers[r.name]=function(...o){let u=r.renderer.apply(this,o);return u===!1&&(u=i.apply(this,o)),u}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=t[r.level];i?i.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new y(this.defaults);for(let i in n.renderer){if(!(i in r))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,u=n.renderer[o],a=r[o];r[o]=(...c)=>{let p=u.apply(r,c);return p===!1&&(p=a.apply(r,c)),p||""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new w(this.defaults);for(let i in n.tokenizer){if(!(i in r))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,u=n.tokenizer[o],a=r[o];r[o]=(...c)=>{let p=u.apply(r,c);return p===!1&&(p=a.apply(r,c)),p}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new P;for(let i in n.hooks){if(!(i in r))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,u=n.hooks[o],a=r[o];P.passThroughHooks.has(i)?r[o]=c=>{if(this.defaults.async&&P.passThroughHooksRespectAsync.has(i))return(async()=>{let k=await u.call(r,c);return a.call(r,k)})();let p=u.call(r,c);return a.call(r,p)}:r[o]=(...c)=>{if(this.defaults.async)return(async()=>{let k=await u.apply(r,c);return k===!1&&(k=await a.apply(r,c)),k})();let p=u.apply(r,c);return p===!1&&(p=a.apply(r,c)),p}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,i=n.walkTokens;s.walkTokens=function(o){let u=[];return u.push(i.call(this,o)),r&&(u=u.concat(r.call(this,o))),u}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let r={...s},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let u=i.hooks?await i.hooks.preprocess(n):n,c=await(i.hooks?await i.hooks.provideLexer(e):e?x.lex:x.lexInline)(u,i),p=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(p,i.walkTokens));let h=await(i.hooks?await i.hooks.provideParser(e):e?b.parse:b.parseInline)(p,i);return i.hooks?await i.hooks.postprocess(h):h})().catch(o);try{i.hooks&&(n=i.hooks.preprocess(n));let a=(i.hooks?i.hooks.provideLexer(e):e?x.lex:x.lexInline)(n,i);i.hooks&&(a=i.hooks.processAllTokens(a)),i.walkTokens&&this.walkTokens(a,i.walkTokens);let p=(i.hooks?i.hooks.provideParser(e):e?b.parse:b.parseInline)(a,i);return i.hooks&&(p=i.hooks.postprocess(p)),p}catch(u){return o(u)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let s="

    An error occurred:

    "+O(n.message+"",!0)+"
    ";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}};var M=new C;function g(l,e){return M.parse(l,e)}g.options=g.setOptions=function(l){return M.setOptions(l),g.defaults=M.defaults,Q(g.defaults),g};g.getDefaults=_;g.defaults=T;g.use=function(...l){return M.use(...l),g.defaults=M.defaults,Q(g.defaults),g};g.walkTokens=function(l,e){return M.walkTokens(l,e)};g.parseInline=M.parseInline;g.Parser=b;g.parser=b.parse;g.Renderer=y;g.TextRenderer=S;g.Lexer=x;g.lexer=x.lex;g.Tokenizer=w;g.Hooks=P;g.parse=g;var ht=g.options,kt=g.setOptions,dt=g.use,gt=g.walkTokens,ft=g.parseInline,mt=g,xt=b.parse,bt=x.lex; + +if(__exports != exports)module.exports = exports;return module.exports})); diff --git a/dist/core/extensions/index.d.ts b/dist/core/extensions/index.d.ts new file mode 100644 index 0000000..d2933c1 --- /dev/null +++ b/dist/core/extensions/index.d.ts @@ -0,0 +1,12 @@ +/** + * Extension system for lifecycle events and custom tools. + */ +export type { SlashCommandInfo, SlashCommandSource } from "../slash-commands.ts"; +export type { SourceInfo } from "../source-info.ts"; +export { createExtensionRuntime, discoverAndLoadExtensions, loadExtensionFromFactory, loadExtensions, } from "./loader.ts"; +export type { ExtensionErrorListener, ForkHandler, NavigateTreeHandler, NewSessionHandler, ShutdownHandler, SwitchSessionHandler, } from "./runner.ts"; +export { ExtensionRunner } from "./runner.ts"; +export type { AfterProviderResponseEvent, AgentEndEvent, AgentSettledEvent, AgentStartEvent, AgentToolResult, AgentToolUpdateCallback, AppendEntryHandler, AppKeybinding, AutocompleteProviderFactory, BashToolCallEvent, BashToolResultEvent, BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, BeforeProviderRequestEventResult, BuildSystemPromptOptions, CompactOptions, ContextEvent, ContextEventResult, ContextUsage, CustomToolCallEvent, CustomToolResultEvent, EditorFactory, EditToolCallEvent, EditToolResultEvent, EntryRenderer, EntryRenderOptions, ExecOptions, ExecResult, Extension, ExtensionActions, ExtensionAPI, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionError, ExtensionEvent, ExtensionFactory, ExtensionFlag, ExtensionHandler, ExtensionMode, ExtensionRuntime, ExtensionShortcut, ExtensionUIContext, ExtensionUIDialogOptions, ExtensionWidgetOptions, FindToolCallEvent, FindToolResultEvent, GetActiveToolsHandler, GetAllToolsHandler, GetCommandsHandler, GetThinkingLevelHandler, GrepToolCallEvent, GrepToolResultEvent, InlineExtension, InputEvent, InputEventResult, InputSource, KeybindingsManager, LoadExtensionsResult, LsToolCallEvent, LsToolResultEvent, MessageEndEvent, MessageRenderer, MessageRenderOptions, MessageStartEvent, MessageUpdateEvent, ModelSelectEvent, ModelSelectSource, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventDecision, ProjectTrustEventResult, ProjectTrustHandler, ProviderConfig, ProviderModelConfig, ReadToolCallEvent, ReadToolResultEvent, RegisteredCommand, RegisteredTool, ReplacedSessionContext, ResolvedCommand, ResourcesDiscoverEvent, ResourcesDiscoverResult, SendMessageHandler, SendUserMessageHandler, SessionBeforeCompactEvent, SessionBeforeCompactResult, SessionBeforeForkEvent, SessionBeforeForkResult, SessionBeforeSwitchEvent, SessionBeforeSwitchResult, SessionBeforeTreeEvent, SessionBeforeTreeResult, SessionCompactEvent, SessionEvent, SessionInfoChangedEvent, SessionShutdownEvent, SessionStartEvent, SessionTreeEvent, SetActiveToolsHandler, SetLabelHandler, SetModelHandler, SetThinkingLevelHandler, TerminalInputHandler, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionMode, ToolExecutionStartEvent, ToolExecutionUpdateEvent, ToolInfo, ToolRenderResultOptions, ToolResultEvent, ToolResultEventResult, TreePreparation, TurnEndEvent, TurnStartEvent, UserBashEvent, UserBashEventResult, WidgetPlacement, WorkingIndicatorOptions, WriteToolCallEvent, WriteToolResultEvent, } from "./types.ts"; +export { defineTool, isBashToolResult, isEditToolResult, isFindToolResult, isGrepToolResult, isLsToolResult, isReadToolResult, isToolCallEventType, isWriteToolResult, } from "./types.ts"; +export { wrapRegisteredTool, wrapRegisteredTools } from "./wrapper.ts"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/core/extensions/index.d.ts.map b/dist/core/extensions/index.d.ts.map new file mode 100644 index 0000000..7f34e67 --- /dev/null +++ b/dist/core/extensions/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,YAAY,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACjF,YAAY,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EACN,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,cAAc,GACd,MAAM,aAAa,CAAC;AACrB,YAAY,EACX,sBAAsB,EACtB,WAAW,EACX,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,oBAAoB,GACpB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,YAAY,EACX,0BAA0B,EAC1B,aAAa,EACb,iBAAiB,EACjB,eAAe,EAEf,eAAe,EACf,uBAAuB,EACvB,kBAAkB,EAElB,aAAa,EACb,2BAA2B,EAE3B,iBAAiB,EACjB,mBAAmB,EACnB,qBAAqB,EACrB,2BAA2B,EAC3B,0BAA0B,EAC1B,0BAA0B,EAC1B,gCAAgC,EAChC,wBAAwB,EAExB,cAAc,EAEd,YAAY,EAEZ,kBAAkB,EAClB,YAAY,EACZ,mBAAmB,EACnB,qBAAqB,EACrB,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EAEnB,aAAa,EACb,kBA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AAqB,EACrB,eAAe,EACf,YAAY,EACZ,cAAc,EAEd,aAAa,EACb,mBAAmB,EACnB,eAAe,EACf,uBAAuB,EACvB,kBAAkB,EAClB,oBAAoB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACN,UAAU,EACV,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,GACjB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["/**\n * Extension system for lifecycle events and custom tools.\n */\n\nexport type { SlashCommandInfo, SlashCommandSource } from \"../slash-commands.ts\";\nexport type { SourceInfo } from \"../source-info.ts\";\nexport {\n\tcreateExtensionRuntime,\n\tdiscoverAndLoadExtensions,\n\tloadExtensionFromFactory,\n\tloadExtensions,\n} from \"./loader.ts\";\nexport type {\n\tExtensionErrorListener,\n\tForkHandler,\n\tNavigateTreeHandler,\n\tNewSessionHandler,\n\tShutdownHandler,\n\tSwitchSessionHandler,\n} from \"./runner.ts\";\nexport { ExtensionRunner } from \"./runner.ts\";\nexport type {\n\tAfterProviderResponseEvent,\n\tAgentEndEvent,\n\tAgentSettledEvent,\n\tAgentStartEvent,\n\t// Re-exports\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n\tAppendEntryHandler,\n\t// App keybindings (for custom editors)\n\tAppKeybinding,\n\tAutocompleteProviderFactory,\n\t// Events - Tool (ToolCallEvent types)\n\tBashToolCallEvent,\n\tBashToolResultEvent,\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tBeforeProviderHeadersEvent,\n\tBeforeProviderRequestEvent,\n\tBeforeProviderRequestEventResult,\n\tBuildSystemPromptOptions,\n\t// Context\n\tCompactOptions,\n\t// Events - Agent\n\tContextEvent,\n\t// Event Results\n\tContextEventResult,\n\tContextUsage,\n\tCustomToolCallEvent,\n\tCustomToolResultEvent,\n\tEditorFactory,\n\tEditToolCallEvent,\n\tEditToolResultEvent,\n\t// Message and Entry Rendering\n\tEntryRenderer,\n\tEntryRenderOptions,\n\tExecOptions,\n\tExecResult,\n\tExtension,\n\tExtensionActions,\n\t// API\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\t// Errors\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFactory,\n\tExtensionFlag,\n\tExtensionHandler,\n\tExtensionMode,\n\t// Runtime\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tFindToolCallEvent,\n\tFindToolResultEvent,\n\tGetActiveToolsHandler,\n\tGetAllToolsHandler,\n\tGetCommandsHandler,\n\tGetThinkingLevelHandler,\n\tGrepToolCallEvent,\n\tGrepToolResultEvent,\n\tInlineExtension,\n\t// Events - Input\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tKeybindingsManager,\n\tLoadExtensionsResult,\n\tLsToolCallEvent,\n\tLsToolResultEvent,\n\t// Events - Message\n\tMessageEndEvent,\n\tMessageRenderer,\n\tMessageRenderOptions,\n\tMessageStartEvent,\n\tMessageUpdateEvent,\n\tModelSelectEvent,\n\tModelSelectSource,\n\tProjectTrustContext,\n\tProjectTrustEvent,\n\tProjectTrustEventDecision,\n\tProjectTrustEventResult,\n\tProjectTrustHandler,\n\t// Provider Registration\n\tProviderConfig,\n\tProviderModelConfig,\n\tReadToolCallEvent,\n\tReadToolResultEvent,\n\t// Commands\n\tRegisteredCommand,\n\tRegisteredTool,\n\tReplacedSessionContext,\n\tResolvedCommand,\n\t// Events - Resources\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSendMessageHandler,\n\tSendUserMessageHandler,\n\tSessionBeforeCompactEvent,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkEvent,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchEvent,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeEvent,\n\tSessionBeforeTreeResult,\n\tSessionCompactEvent,\n\tSessionEvent,\n\tSessionInfoChangedEvent,\n\tSessionShutdownEvent,\n\t// Events - Session\n\tSessionStartEvent,\n\tSessionTreeEvent,\n\tSetActiveToolsHandler,\n\tSetLabelHandler,\n\tSetModelHandler,\n\tSetThinkingLevelHandler,\n\tTerminalInputHandler,\n\t// Events - Tool\n\tToolCallEvent,\n\tToolCallEventResult,\n\t// Tools\n\tToolDefinition,\n\t// Events - Tool Execution\n\tToolExecutionEndEvent,\n\t// Tool execution mode\n\tToolExecutionMode,\n\tToolExecutionStartEvent,\n\tToolExecutionUpdateEvent,\n\tToolInfo,\n\tToolRenderResultOptions,\n\tToolResultEvent,\n\tToolResultEventResult,\n\tTreePreparation,\n\tTurnEndEvent,\n\tTurnStartEvent,\n\t// Events - User Bash\n\tUserBashEvent,\n\tUserBashEventResult,\n\tWidgetPlacement,\n\tWorkingIndicatorOptions,\n\tWriteToolCallEvent,\n\tWriteToolResultEvent,\n} from \"./types.ts\";\n// Type guards\nexport {\n\tdefineTool,\n\tisBashToolResult,\n\tisEditToolResult,\n\tisFindToolResult,\n\tisGrepToolResult,\n\tisLsToolResult,\n\tisReadToolResult,\n\tisToolCallEventType,\n\tisWriteToolResult,\n} from \"./types.ts\";\nexport { wrapRegisteredTool, wrapRegisteredTools } from \"./wrapper.ts\";\n"]} \ No newline at end of file diff --git a/dist/core/extensions/index.js b/dist/core/extensions/index.js new file mode 100644 index 0000000..013ce8a --- /dev/null +++ b/dist/core/extensions/index.js @@ -0,0 +1,9 @@ +/** + * Extension system for lifecycle events and custom tools. + */ +export { createExtensionRuntime, discoverAndLoadExtensions, loadExtensionFromFactory, loadExtensions, } from "./loader.js"; +export { ExtensionRunner } from "./runner.js"; +// Type guards +export { defineTool, isBashToolResult, isEditToolResult, isFindToolResult, isGrepToolResult, isLsToolResult, isReadToolResult, isToolCallEventType, isWriteToolResult, } from "./types.js"; +export { wrapRegisteredTool, wrapRegisteredTools } from "./wrapper.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/core/extensions/index.js.map b/dist/core/extensions/index.js.map new file mode 100644 index 0000000..9ef6173 --- /dev/null +++ b/dist/core/extensions/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/extensions/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EACN,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,cAAc,GACd,MAAM,aAAa,CAAC;AASrB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAuJ9C,cAAc;AACd,OAAO,EACN,UAAU,EACV,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,GACjB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["/**\n * Extension system for lifecycle events and custom tools.\n */\n\nexport type { SlashCommandInfo, SlashCommandSource } from \"../slash-commands.ts\";\nexport type { SourceInfo } from \"../source-info.ts\";\nexport {\n\tcreateExtensionRuntime,\n\tdiscoverAndLoadExtensions,\n\tloadExtensionFromFactory,\n\tloadExtensions,\n} from \"./loader.ts\";\nexport type {\n\tExtensionErrorListener,\n\tForkHandler,\n\tNavigateTreeHandler,\n\tNewSessionHandler,\n\tShutdownHandler,\n\tSwitchSessionHandler,\n} from \"./runner.ts\";\nexport { ExtensionRunner } from \"./runner.ts\";\nexport type {\n\tAfterProviderResponseEvent,\n\tAgentEndEvent,\n\tAgentSettledEvent,\n\tAgentStartEvent,\n\t// Re-exports\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n\tAppendEntryHandler,\n\t// App keybindings (for custom editors)\n\tAppKeybinding,\n\tAutocompleteProviderFactory,\n\t// Events - Tool (ToolCallEvent types)\n\tBashToolCallEvent,\n\tBashToolResultEvent,\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tBeforeProviderHeadersEvent,\n\tBeforeProviderRequestEvent,\n\tBeforeProviderRequestEventResult,\n\tBuildSystemPromptOptions,\n\t// Context\n\tCompactOptions,\n\t// Events - Agent\n\tContextEvent,\n\t// Event Results\n\tContextEventResult,\n\tContextUsage,\n\tCustomToolCallEvent,\n\tCustomToolResultEvent,\n\tEditorFactory,\n\tEditToolCallEvent,\n\tEditToolResultEvent,\n\t// Message and Entry Rendering\n\tEntryRenderer,\n\tEntryRenderOptions,\n\tExecOptions,\n\tExecResult,\n\tExtension,\n\tExtensionActions,\n\t// API\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\t// Errors\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFactory,\n\tExtensionFlag,\n\tExtensionHandler,\n\tExtensionMode,\n\t// Runtime\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tFindToolCallEvent,\n\tFindToolResultEvent,\n\tGetActiveToolsHandler,\n\tGetAllToolsHandler,\n\tGetCommandsHandler,\n\tGetThinkingLevelHandler,\n\tGrepToolCallEvent,\n\tGrepToolResultEvent,\n\tInlineExtension,\n\t// Events - Input\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tKeybindingsManager,\n\tLoadExtensionsResult,\n\tLsToolCallEvent,\n\tLsToolResultEvent,\n\t// Events - Message\n\tMessageEndEvent,\n\tMessageRenderer,\n\tMessageRenderOptions,\n\tMessageStartEvent,\n\tMessageUpdateEvent,\n\tModelSelectEvent,\n\tModelSelectSource,\n\tProjectTrustContext,\n\tProjectTrustEvent,\n\tProjectTrustEventDecision,\n\tProjectTrustEventResult,\n\tProjectTrustHandler,\n\t// Provider Registration\n\tProviderConfig,\n\tProviderModelConfig,\n\tReadToolCallEvent,\n\tReadToolResultEvent,\n\t// Commands\n\tRegisteredCommand,\n\tRegisteredTool,\n\tReplacedSessionContext,\n\tResolvedCommand,\n\t// Events - Resources\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSendMessageHandler,\n\tSendUserMessageHandler,\n\tSessionBeforeCompactEvent,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkEvent,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchEvent,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeEvent,\n\tSessionBeforeTreeResult,\n\tSessionCompactEvent,\n\tSessionEvent,\n\tSessionInfoChangedEvent,\n\tSessionShutdownEvent,\n\t// Events - Session\n\tSessionStartEvent,\n\tSessionTreeEvent,\n\tSetActiveToolsHandler,\n\tSetLabelHandler,\n\tSetModelHandler,\n\tSetThinkingLevelHandler,\n\tTerminalInputHandler,\n\t// Events - Tool\n\tToolCallEvent,\n\tToolCallEventResult,\n\t// Tools\n\tToolDefinition,\n\t// Events - Tool Execution\n\tToolExecutionEndEvent,\n\t// Tool execution mode\n\tToolExecutionMode,\n\tToolExecutionStartEvent,\n\tToolExecutionUpdateEvent,\n\tToolInfo,\n\tToolRenderResultOptions,\n\tToolResultEvent,\n\tToolResultEventResult,\n\tTreePreparation,\n\tTurnEndEvent,\n\tTurnStartEvent,\n\t// Events - User Bash\n\tUserBashEvent,\n\tUserBashEventResult,\n\tWidgetPlacement,\n\tWorkingIndicatorOptions,\n\tWriteToolCallEvent,\n\tWriteToolResultEvent,\n} from \"./types.ts\";\n// Type guards\nexport {\n\tdefineTool,\n\tisBashToolResult,\n\tisEditToolResult,\n\tisFindToolResult,\n\tisGrepToolResult,\n\tisLsToolResult,\n\tisReadToolResult,\n\tisToolCallEventType,\n\tisWriteToolResult,\n} from \"./types.ts\";\nexport { wrapRegisteredTool, wrapRegisteredTools } from \"./wrapper.ts\";\n"]} \ No newline at end of file diff --git a/dist/core/extensions/loader.d.ts b/dist/core/extensions/loader.d.ts new file mode 100644 index 0000000..2550734 --- /dev/null +++ b/dist/core/extensions/loader.d.ts @@ -0,0 +1,23 @@ +/** + * Extension loader - loads TypeScript extension modules using jiti. + * + */ +import { type EventBus } from "../event-bus.ts"; +import type { Extension, ExtensionFactory, ExtensionRuntime, LoadExtensionsResult } from "./types.ts"; +export declare function clearExtensionCache(): void; +/** + * Create a runtime with throwing stubs for action methods. + * Runner.bindCore() replaces these with real implementations. + */ +export declare function createExtensionRuntime(): ExtensionRuntime; +/** + * Create an Extension from an inline factory function. + */ +export declare function loadExtensionFromFactory(factory: ExtensionFactory, cwd: string, eventBus: EventBus, runtime: ExtensionRuntime, extensionPath?: string): Promise; +export declare function loadExtensions(paths: string[], cwd: string, eventBus?: EventBus, runtime?: ExtensionRuntime): Promise; +export declare function loadExtensionsCached(paths: string[], cwd: string, eventBus?: EventBus, runtime?: ExtensionRuntime): Promise; +/** + * Discover and load extensions from standard locations. + */ +export declare function discoverAndLoadExtensions(configuredPaths: string[], cwd: string, agentDir?: string, eventBus?: EventBus): Promise; +//# sourceMappingURL=loader.d.ts.map \ No newline at end of file diff --git a/dist/core/extensions/loader.d.ts.map b/dist/core/extensions/loader.d.ts.map new file mode 100644 index 0000000..e935584 --- /dev/null +++ b/dist/core/extensions/loader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/loader.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAyBH,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAKhE,OAAO,KAAK,EAEX,SAAS,EAET,gBAAgB,EAChB,gBAAgB,EAChB,oBAAoB,EAKpB,MAAM,YAAY,CAAC;AA0GpB,wBAAgB,mBAAmB,IAAI,IAAI,CAI1C;AAWD;;;GAGG;AACH,wBAAgB,sBAAsB,IAAI,gBAAgB,CAqDzD;AAmQD;;GAEG;AACH,wBAAsB,wBAAwB,CAC7C,OAAO,EAAE,gBAAgB,EACzB,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,gBAAgB,EACzB,aAAa,SAAa,GACxB,OAAO,CAAC,SAAS,CAAC,CAOpB;AA6CD,wBAAsB,cAAc,CACnC,KAAK,EAAE,MAAM,EAAE,EACf,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,QAAQ,EACnB,OAAO,CAAC,EAAE,gBAAgB,GACxB,OAAO,CAAC,oBAAoB,CAAC,CAE/B;AAED,wBAAsB,oBAAoB,CACzC,KAAK,EAAE,MAAM,EAAE,EACf,GAAG,EAAE,MAAM,EACX,QAAQ,CAAC,EAAE,QAAQ,EACnB,OAAO,CAAC,EAAE,gBAAgB,GACxB,OAAO,CAAC,oBAAoB,CAAC,CAE/B;AA+GD;;GAEG;AACH,wBAAsB,yBAAyB,CAC9C,eAAe,EAAE,MAAM,EAAE,EACzB,GAAG,EAAE,MAAM,EACX,QAAQ,GAAE,MAAsB,EAChC,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,oBAAoB,CAAC,CA2C/B","sourcesContent":["/**\n * Extension loader - loads TypeScript extension modules using jiti.\n *\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport * as _bundledPiAgentCore from \"@earendil-works/pi-agent-core\";\nimport type { Provider } from \"@earendil-works/pi-ai\";\nimport * as _bundledPiAiCompat from \"@earendil-works/pi-ai/compat\";\nimport * as _bundledPiAiOauth from \"@earendil-works/pi-ai/oauth\";\nimport * as _bundledPiAiProviders from \"@earendil-works/pi-ai/providers/all\";\nimport type { KeyId } from \"@earendil-works/pi-tui\";\nimport * as _bundledPiTui from \"@earendil-works/pi-tui\";\nimport { createJiti } from \"jiti/static\";\n// Static imports of packages that extensions may use.\n// These MUST be static so Bun bundles them into the compiled binary.\n// The virtualModules option then makes them available to extensions.\nimport * as _bundledTypebox from \"typebox\";\nimport * as _bundledTypeboxCompile from \"typebox/compile\";\nimport * as _bundledTypeboxValue from \"typebox/value\";\nimport { CONFIG_DIR_NAME, getAgentDir, isBunBinary } from \"../../config.ts\";\n// NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n// avoiding a circular dependency. Extensions can import from @earendil-works/pi-coding-agent.\nimport * as _bundledPiCodingAgent from \"../../index.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { createEventBus, type EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions } from \"../exec.ts\";\nimport { execCommand } from \"../exec.ts\";\nimport { createSyntheticSourceInfo } from \"../source-info.ts\";\nimport { time } from \"../timings.ts\";\nimport type {\n\tEntryRenderer,\n\tExtension,\n\tExtensionAPI,\n\tExtensionFactory,\n\tExtensionRuntime,\n\tLoadExtensionsResult,\n\tMessageRenderer,\n\tProviderConfig,\n\tRegisteredCommand,\n\tToolDefinition,\n} from \"./types.ts\";\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary) */\nconst VIRTUAL_MODULES: Record = {\n\ttypebox: _bundledTypebox,\n\t\"typebox/compile\": _bundledTypeboxCompile,\n\t\"typebox/value\": _bundledTypeboxValue,\n\t\"@sinclair/typebox\": _bundledTypebox,\n\t\"@sinclair/typebox/compile\": _bundledTypeboxCompile,\n\t\"@sinclair/typebox/value\": _bundledTypeboxValue,\n\t\"@earendil-works/pi-agent-core\": _bundledPiAgentCore,\n\t\"@earendil-works/pi-tui\": _bundledPiTui,\n\t// Extensions resolve the pi-ai root to the compat entrypoint (a strict\n\t// superset of the core entrypoint): existing extensions using the old\n\t// global API keep working at runtime until compat is removed.\n\t\"@earendil-works/pi-ai\": _bundledPiAiCompat,\n\t\"@earendil-works/pi-ai/compat\": _bundledPiAiCompat,\n\t\"@earendil-works/pi-ai/oauth\": _bundledPiAiOauth,\n\t\"@earendil-works/pi-ai/providers/all\": _bundledPiAiProviders,\n\t\"@earendil-works/pi-coding-agent\": _bundledPiCodingAgent,\n\t\"@mariozechner/pi-agent-core\": _bundledPiAgentCore,\n\t\"@mariozechner/pi-tui\": _bundledPiTui,\n\t\"@mariozechner/pi-ai\": _bundledPiAiCompat,\n\t\"@mariozechner/pi-ai/compat\": _bundledPiAiCompat,\n\t\"@mariozechner/pi-ai/oauth\": _bundledPiAiOauth,\n\t\"@mariozechner/pi-ai/providers/all\": _bundledPiAiProviders,\n\t\"@mariozechner/pi-coding-agent\": _bundledPiCodingAgent,\n};\n\nconst require = createRequire(import.meta.url);\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nlet _aliases: Record | null = null;\n\nfunction getAliases(): Record {\n\tif (_aliases) return _aliases;\n\n\tconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\tconst packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n\tconst typeboxEntry = require.resolve(\"typebox\");\n\tconst typeboxCompileEntry = require.resolve(\"typebox/compile\");\n\tconst typeboxValueEntry = require.resolve(\"typebox/value\");\n\n\tconst packagesRoot = path.resolve(__dirname, \"../../../../\");\n\tconst resolveWorkspaceOrImport = (workspaceRelativePath: string, specifier: string): string => {\n\t\tconst workspacePath = path.join(packagesRoot, workspaceRelativePath);\n\t\tif (fs.existsSync(workspacePath)) {\n\t\t\treturn workspacePath;\n\t\t}\n\t\treturn fileURLToPath(import.meta.resolve(specifier));\n\t};\n\n\tconst piCodingAgentEntry = packageIndex;\n\tconst piAgentCoreEntry = resolveWorkspaceOrImport(\"agent/dist/index.js\", \"@earendil-works/pi-agent-core\");\n\tconst piTuiEntry = resolveWorkspaceOrImport(\"tui/dist/index.js\", \"@earendil-works/pi-tui\");\n\t// Extensions resolve the pi-ai root to the compat entrypoint (a strict\n\t// superset of the core entrypoint): existing extensions using the old\n\t// global API keep working at runtime until compat is removed.\n\tconst piAiCompatEntry = resolveWorkspaceOrImport(\"ai/dist/compat.js\", \"@earendil-works/pi-ai/compat\");\n\tconst piAiOauthEntry = resolveWorkspaceOrImport(\"ai/dist/oauth.js\", \"@earendil-works/pi-ai/oauth\");\n\tconst piAiProvidersEntry = resolveWorkspaceOrImport(\n\t\t\"ai/dist/providers/all.js\",\n\t\t\"@earendil-works/pi-ai/providers/all\",\n\t);\n\n\t_aliases = {\n\t\t\"@earendil-works/pi-coding-agent\": piCodingAgentEntry,\n\t\t\"@earendil-works/pi-agent-core\": piAgentCoreEntry,\n\t\t\"@earendil-works/pi-tui\": piTuiEntry,\n\t\t\"@earendil-works/pi-ai/providers/all\": piAiProvidersEntry,\n\t\t\"@earendil-works/pi-ai/compat\": piAiCompatEntry,\n\t\t\"@earendil-works/pi-ai/oauth\": piAiOauthEntry,\n\t\t\"@earendil-works/pi-ai\": piAiCompatEntry,\n\t\t\"@mariozechner/pi-coding-agent\": piCodingAgentEntry,\n\t\t\"@mariozechner/pi-agent-core\": piAgentCoreEntry,\n\t\t\"@mariozechner/pi-tui\": piTuiEntry,\n\t\t\"@mariozechner/pi-ai/providers/all\": piAiProvidersEntry,\n\t\t\"@mariozechner/pi-ai/compat\": piAiCompatEntry,\n\t\t\"@mariozechner/pi-ai/oauth\": piAiOauthEntry,\n\t\t\"@mariozechner/pi-ai\": piAiCompatEntry,\n\t\ttypebox: typeboxEntry,\n\t\t\"typebox/compile\": typeboxCompileEntry,\n\t\t\"typebox/value\": typeboxValueEntry,\n\t\t\"@sinclair/typebox\": typeboxEntry,\n\t\t\"@sinclair/typebox/compile\": typeboxCompileEntry,\n\t\t\"@sinclair/typebox/value\": typeboxValueEntry,\n\t};\n\n\treturn _aliases;\n}\n\ntype HandlerFn = (...args: unknown[]) => Promise;\n\nlet extensionCacheCwd: string | undefined;\nlet extensionCacheGeneration = 0;\nconst extensionCache = new Map();\n\ninterface ExtensionCacheToken {\n\tcwd: string;\n\tgeneration: number;\n}\n\nexport function clearExtensionCache(): void {\n\textensionCache.clear();\n\textensionCacheCwd = undefined;\n\textensionCacheGeneration++;\n}\n\nfunction useExtensionCacheCwd(cwd: string): ExtensionCacheToken {\n\tconst resolvedCwd = resolvePath(cwd);\n\tif (extensionCacheCwd !== undefined && extensionCacheCwd !== resolvedCwd) {\n\t\tclearExtensionCache();\n\t}\n\textensionCacheCwd = resolvedCwd;\n\treturn { cwd: resolvedCwd, generation: extensionCacheGeneration };\n}\n\n/**\n * Create a runtime with throwing stubs for action methods.\n * Runner.bindCore() replaces these with real implementations.\n */\nexport function createExtensionRuntime(): ExtensionRuntime {\n\tconst notInitialized = () => {\n\t\tthrow new Error(\"Extension runtime not initialized. Action methods cannot be called during extension loading.\");\n\t};\n\tconst state: { staleMessage?: string } = {};\n\tconst assertActive = () => {\n\t\tif (state.staleMessage) {\n\t\t\tthrow new Error(state.staleMessage);\n\t\t}\n\t};\n\n\tconst runtime: ExtensionRuntime = {\n\t\tsendMessage: notInitialized,\n\t\tsendUserMessage: notInitialized,\n\t\tappendEntry: notInitialized,\n\t\tsetSessionName: notInitialized,\n\t\tgetSessionName: notInitialized,\n\t\tsetLabel: notInitialized,\n\t\tgetActiveTools: notInitialized,\n\t\tgetAllTools: notInitialized,\n\t\tsetActiveTools: notInitialized,\n\t\t// registerTool() is valid during extension load; refresh is only needed post-bind.\n\t\trefreshTools: () => {},\n\t\tgetCommands: notInitialized,\n\t\tsetModel: () => Promise.reject(new Error(\"Extension runtime not initialized\")),\n\t\tgetThinkingLevel: notInitialized,\n\t\tsetThinkingLevel: notInitialized,\n\t\tflagValues: new Map(),\n\t\tpendingProviderRegistrations: [],\n\t\tpendingNativeProviderRegistrations: [],\n\t\tassertActive,\n\t\tinvalidate: (message) => {\n\t\t\tstate.staleMessage ??=\n\t\t\t\tmessage ??\n\t\t\t\t\"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\";\n\t\t},\n\t\t// Pre-bind: queue registrations so bindCore() can flush them once the\n\t\t// model registry is available. bindCore() replaces both with direct calls.\n\t\tregisterProvider: (name, config, extensionPath = \"\") => {\n\t\t\truntime.pendingProviderRegistrations.push({ name, config, extensionPath });\n\t\t},\n\t\tregisterNativeProvider: (provider, extensionPath = \"\") => {\n\t\t\truntime.pendingNativeProviderRegistrations.push({ provider, extensionPath });\n\t\t},\n\t\tunregisterProvider: (name) => {\n\t\t\truntime.pendingProviderRegistrations = runtime.pendingProviderRegistrations.filter((r) => r.name !== name);\n\t\t\truntime.pendingNativeProviderRegistrations = runtime.pendingNativeProviderRegistrations.filter(\n\t\t\t\t(r) => r.provider.id !== name,\n\t\t\t);\n\t\t},\n\t};\n\n\treturn runtime;\n}\n\n/**\n * Create the ExtensionAPI for an extension.\n * Registration methods write to the extension object.\n * Action methods delegate to the shared runtime.\n */\nfunction createExtensionAPI(\n\textension: Extension,\n\truntime: ExtensionRuntime,\n\tcwd: string,\n\teventBus: EventBus,\n): ExtensionAPI {\n\tconst api = {\n\t\t// Registration methods - write to extension\n\t\ton(event: string, handler: HandlerFn): void {\n\t\t\truntime.assertActive();\n\t\t\tconst list = extension.handlers.get(event) ?? [];\n\t\t\tlist.push(handler);\n\t\t\textension.handlers.set(event, list);\n\t\t},\n\n\t\tregisterTool(tool: ToolDefinition): void {\n\t\t\truntime.assertActive();\n\t\t\textension.tools.set(tool.name, {\n\t\t\t\tdefinition: tool,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t});\n\t\t\truntime.refreshTools();\n\t\t},\n\n\t\tregisterCommand(name: string, options: Omit): void {\n\t\t\truntime.assertActive();\n\t\t\textension.commands.set(name, {\n\t\t\t\tname,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\t...options,\n\t\t\t});\n\t\t},\n\n\t\tregisterShortcut(\n\t\t\tshortcut: KeyId,\n\t\t\toptions: {\n\t\t\t\tdescription?: string;\n\t\t\t\thandler: (ctx: import(\"./types.ts\").ExtensionContext) => Promise | void;\n\t\t\t},\n\t\t): void {\n\t\t\truntime.assertActive();\n\t\t\textension.shortcuts.set(shortcut, { shortcut, extensionPath: extension.path, ...options });\n\t\t},\n\n\t\tregisterFlag(\n\t\t\tname: string,\n\t\t\toptions: { description?: string; type: \"boolean\" | \"string\"; default?: boolean | string },\n\t\t): void {\n\t\t\truntime.assertActive();\n\t\t\textension.flags.set(name, { name, extensionPath: extension.path, ...options });\n\t\t\tif (options.default !== undefined && !runtime.flagValues.has(name)) {\n\t\t\t\truntime.flagValues.set(name, options.default);\n\t\t\t}\n\t\t},\n\n\t\tregisterMessageRenderer(customType: string, renderer: MessageRenderer): void {\n\t\t\truntime.assertActive();\n\t\t\textension.messageRenderers.set(customType, renderer as MessageRenderer);\n\t\t},\n\n\t\tregisterEntryRenderer(customType: string, renderer: EntryRenderer): void {\n\t\t\truntime.assertActive();\n\t\t\textension.entryRenderers ??= new Map();\n\t\t\textension.entryRenderers.set(customType, renderer as EntryRenderer);\n\t\t},\n\n\t\t// Flag access - checks extension registered it, reads from runtime\n\t\tgetFlag(name: string): boolean | string | undefined {\n\t\t\truntime.assertActive();\n\t\t\tif (!extension.flags.has(name)) return undefined;\n\t\t\treturn runtime.flagValues.get(name);\n\t\t},\n\n\t\t// Action methods - delegate to shared runtime\n\t\tsendMessage(message, options): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.sendMessage(message, options);\n\t\t},\n\n\t\tsendUserMessage(content, options): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.sendUserMessage(content, options);\n\t\t},\n\n\t\tappendEntry(customType: string, data?: unknown): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.appendEntry(customType, data);\n\t\t},\n\n\t\tsetSessionName(name: string): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setSessionName(name);\n\t\t},\n\n\t\tgetSessionName(): string | undefined {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getSessionName();\n\t\t},\n\n\t\tsetLabel(entryId: string, label: string | undefined): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setLabel(entryId, label);\n\t\t},\n\n\t\texec(command: string, args: string[], options?: ExecOptions) {\n\t\t\truntime.assertActive();\n\t\t\treturn execCommand(command, args, options?.cwd ?? cwd, options);\n\t\t},\n\n\t\tgetActiveTools(): string[] {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getActiveTools();\n\t\t},\n\n\t\tgetAllTools() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getAllTools();\n\t\t},\n\n\t\tsetActiveTools(toolNames: string[]): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setActiveTools(toolNames);\n\t\t},\n\n\t\tgetCommands() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getCommands();\n\t\t},\n\n\t\tsetModel(model) {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.setModel(model);\n\t\t},\n\n\t\tgetThinkingLevel() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getThinkingLevel();\n\t\t},\n\n\t\tsetThinkingLevel(level) {\n\t\t\truntime.assertActive();\n\t\t\truntime.setThinkingLevel(level);\n\t\t},\n\n\t\tregisterProvider(providerOrName: Provider | string, config?: ProviderConfig) {\n\t\t\truntime.assertActive();\n\t\t\tif (typeof providerOrName === \"string\") {\n\t\t\t\tif (!config) throw new Error(\"Provider config is required when registering by name\");\n\t\t\t\truntime.registerProvider(providerOrName, config, extension.path);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.registerNativeProvider(providerOrName, extension.path);\n\t\t},\n\n\t\tunregisterProvider(name: string) {\n\t\t\truntime.assertActive();\n\t\t\truntime.unregisterProvider(name, extension.path);\n\t\t},\n\n\t\tevents: eventBus,\n\t} as ExtensionAPI;\n\n\treturn api;\n}\n\nfunction isCurrentCacheToken(cacheToken: ExtensionCacheToken | undefined): cacheToken is ExtensionCacheToken {\n\treturn (\n\t\tcacheToken !== undefined &&\n\t\textensionCacheCwd === cacheToken.cwd &&\n\t\textensionCacheGeneration === cacheToken.generation\n\t);\n}\n\nasync function loadExtensionModule(extensionPath: string, cacheToken?: ExtensionCacheToken) {\n\tif (isCurrentCacheToken(cacheToken)) {\n\t\tconst cachedFactory = extensionCache.get(extensionPath);\n\t\tif (cachedFactory) {\n\t\t\treturn cachedFactory;\n\t\t}\n\t}\n\n\tconst jiti = createJiti(import.meta.url, {\n\t\tmoduleCache: false,\n\t\t// In Bun binary: use virtualModules for bundled packages (no filesystem resolution)\n\t\t// Also disable tryNative so jiti handles ALL imports (not just the entry point)\n\t\t// In Node.js/dev: use aliases to resolve to node_modules paths\n\t\t...(isBunBinary ? { virtualModules: VIRTUAL_MODULES, tryNative: false } : { alias: getAliases() }),\n\t});\n\n\tconst module = await jiti.import(extensionPath, { default: true });\n\tconst factory = module as ExtensionFactory;\n\tif (typeof factory !== \"function\") {\n\t\treturn undefined;\n\t}\n\tif (isCurrentCacheToken(cacheToken)) {\n\t\textensionCache.set(extensionPath, factory);\n\t}\n\treturn factory;\n}\n\n/**\n * Create an Extension object with empty collections.\n */\nfunction createExtension(extensionPath: string, resolvedPath: string): Extension {\n\tconst source =\n\t\textensionPath.startsWith(\"<\") && extensionPath.endsWith(\">\")\n\t\t\t? extensionPath.slice(1, -1).split(\":\")[0] || \"temporary\"\n\t\t\t: \"local\";\n\tconst baseDir = extensionPath.startsWith(\"<\") ? undefined : path.dirname(resolvedPath);\n\n\treturn {\n\t\tpath: extensionPath,\n\t\tresolvedPath,\n\t\tsourceInfo: createSyntheticSourceInfo(extensionPath, { source, baseDir }),\n\t\thandlers: new Map(),\n\t\ttools: new Map(),\n\t\tmessageRenderers: new Map(),\n\t\tentryRenderers: new Map(),\n\t\tcommands: new Map(),\n\t\tflags: new Map(),\n\t\tshortcuts: new Map(),\n\t};\n}\n\nasync function loadExtension(\n\textensionPath: string,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n\tcacheToken?: ExtensionCacheToken,\n): Promise<{ extension: Extension | null; error: string | null }> {\n\tconst resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true });\n\n\ttry {\n\t\tconst factory = await loadExtensionModule(resolvedPath, cacheToken);\n\t\ttime(`${extensionPath} module import`, \"extensions\");\n\t\tif (!factory) {\n\t\t\treturn { extension: null, error: `Extension does not export a valid factory function: ${extensionPath}` };\n\t\t}\n\n\t\tconst extension = createExtension(extensionPath, resolvedPath);\n\t\tconst api = createExtensionAPI(extension, runtime, cwd, eventBus);\n\t\tawait factory(api);\n\t\ttime(`${extensionPath} factory`, \"extensions\");\n\n\t\treturn { extension, error: null };\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\treturn { extension: null, error: `Failed to load extension: ${message}` };\n\t}\n}\n\n/**\n * Create an Extension from an inline factory function.\n */\nexport async function loadExtensionFromFactory(\n\tfactory: ExtensionFactory,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n\textensionPath = \"\",\n): Promise {\n\tconst extension = createExtension(extensionPath, extensionPath);\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst api = createExtensionAPI(extension, runtime, resolvedCwd, eventBus);\n\tawait factory(api);\n\ttime(`${extensionPath} factory`, \"extensions\");\n\treturn extension;\n}\n\n/**\n * Load extensions from paths.\n */\nasync function loadExtensionsInternal(\n\tpaths: string[],\n\tcwd: string,\n\teventBus?: EventBus,\n\truntime?: ExtensionRuntime,\n\tuseCache = false,\n): Promise {\n\tconst extensions: Extension[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\tconst cacheToken = useCache ? useExtensionCacheCwd(cwd) : undefined;\n\tconst resolvedCwd = cacheToken?.cwd ?? resolvePath(cwd);\n\tconst resolvedEventBus = eventBus ?? createEventBus();\n\tconst resolvedRuntime = runtime ?? createExtensionRuntime();\n\n\tfor (const extPath of paths) {\n\t\tconst { extension, error } = await loadExtension(\n\t\t\textPath,\n\t\t\tresolvedCwd,\n\t\t\tresolvedEventBus,\n\t\t\tresolvedRuntime,\n\t\t\tcacheToken,\n\t\t);\n\n\t\tif (error) {\n\t\t\terrors.push({ path: extPath, error });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (extension) {\n\t\t\textensions.push(extension);\n\t\t}\n\t}\n\n\treturn {\n\t\textensions,\n\t\terrors,\n\t\truntime: resolvedRuntime,\n\t};\n}\n\nexport async function loadExtensions(\n\tpaths: string[],\n\tcwd: string,\n\teventBus?: EventBus,\n\truntime?: ExtensionRuntime,\n): Promise {\n\treturn loadExtensionsInternal(paths, cwd, eventBus, runtime);\n}\n\nexport async function loadExtensionsCached(\n\tpaths: string[],\n\tcwd: string,\n\teventBus?: EventBus,\n\truntime?: ExtensionRuntime,\n): Promise {\n\treturn loadExtensionsInternal(paths, cwd, eventBus, runtime, true);\n}\n\ninterface PiManifest {\n\textensions?: string[];\n\tthemes?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n}\n\nfunction readPiManifest(packageJsonPath: string): PiManifest | null {\n\ttry {\n\t\tconst content = fs.readFileSync(packageJsonPath, \"utf-8\");\n\t\tconst pkg = JSON.parse(content);\n\t\tif (pkg.pi && typeof pkg.pi === \"object\") {\n\t\t\treturn pkg.pi as PiManifest;\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction isExtensionFile(name: string): boolean {\n\treturn name.endsWith(\".ts\") || name.endsWith(\".js\");\n}\n\n/**\n * Resolve extension entry points from a directory.\n *\n * Checks for:\n * 1. package.json with \"pi.extensions\" field -> returns declared paths\n * 2. index.ts or index.js -> returns the index file\n *\n * Returns resolved paths or null if no entry points found.\n */\nfunction resolveExtensionEntries(dir: string): string[] | null {\n\t// Check for package.json with \"pi\" field first\n\tconst packageJsonPath = path.join(dir, \"package.json\");\n\tif (fs.existsSync(packageJsonPath)) {\n\t\tconst manifest = readPiManifest(packageJsonPath);\n\t\tif (manifest?.extensions?.length) {\n\t\t\tconst entries: string[] = [];\n\t\t\tfor (const extPath of manifest.extensions) {\n\t\t\t\tconst resolvedExtPath = path.resolve(dir, extPath);\n\t\t\t\tif (fs.existsSync(resolvedExtPath)) {\n\t\t\t\t\tentries.push(resolvedExtPath);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (entries.length > 0) {\n\t\t\t\treturn entries;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check for index.ts or index.js\n\tconst indexTs = path.join(dir, \"index.ts\");\n\tconst indexJs = path.join(dir, \"index.js\");\n\tif (fs.existsSync(indexTs)) {\n\t\treturn [indexTs];\n\t}\n\tif (fs.existsSync(indexJs)) {\n\t\treturn [indexJs];\n\t}\n\n\treturn null;\n}\n\n/**\n * Discover extensions in a directory.\n *\n * Discovery rules:\n * 1. Direct files: `extensions/*.ts` or `*.js` → load\n * 2. Subdirectory with index: `extensions/* /index.ts` or `index.js` → load\n * 3. Subdirectory with package.json: `extensions/* /package.json` with \"pi\" field → load what it declares\n *\n * No recursion beyond one level. Complex packages must use package.json manifest.\n */\nfunction discoverExtensionsInDir(dir: string): string[] {\n\tif (!fs.existsSync(dir)) {\n\t\treturn [];\n\t}\n\n\tconst discovered: string[] = [];\n\n\ttry {\n\t\tconst entries = fs.readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of entries) {\n\t\t\tconst entryPath = path.join(dir, entry.name);\n\n\t\t\t// 1. Direct files: *.ts or *.js\n\t\t\tif ((entry.isFile() || entry.isSymbolicLink()) && isExtensionFile(entry.name)) {\n\t\t\t\tdiscovered.push(entryPath);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// 2 & 3. Subdirectories\n\t\t\tif (entry.isDirectory() || entry.isSymbolicLink()) {\n\t\t\t\tconst entries = resolveExtensionEntries(entryPath);\n\t\t\t\tif (entries) {\n\t\t\t\t\tdiscovered.push(...entries);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn [];\n\t}\n\n\treturn discovered;\n}\n\n/**\n * Discover and load extensions from standard locations.\n */\nexport async function discoverAndLoadExtensions(\n\tconfiguredPaths: string[],\n\tcwd: string,\n\tagentDir: string = getAgentDir(),\n\teventBus?: EventBus,\n): Promise {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir);\n\tconst allPaths: string[] = [];\n\tconst seen = new Set();\n\n\tconst addPaths = (paths: string[]) => {\n\t\tfor (const p of paths) {\n\t\t\tconst resolved = path.resolve(p);\n\t\t\tif (!seen.has(resolved)) {\n\t\t\t\tseen.add(resolved);\n\t\t\t\tallPaths.push(p);\n\t\t\t}\n\t\t}\n\t};\n\n\t// 1. Project-local extensions: cwd/${CONFIG_DIR_NAME}/extensions/\n\tconst localExtDir = path.join(resolvedCwd, CONFIG_DIR_NAME, \"extensions\");\n\taddPaths(discoverExtensionsInDir(localExtDir));\n\n\t// 2. Global extensions: agentDir/extensions/\n\tconst globalExtDir = path.join(resolvedAgentDir, \"extensions\");\n\taddPaths(discoverExtensionsInDir(globalExtDir));\n\n\t// 3. Explicitly configured paths\n\tfor (const p of configuredPaths) {\n\t\tconst resolved = resolvePath(p, resolvedCwd, { normalizeUnicodeSpaces: true });\n\t\tif (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {\n\t\t\t// Check for package.json with pi manifest or index.ts\n\t\t\tconst entries = resolveExtensionEntries(resolved);\n\t\t\tif (entries) {\n\t\t\t\taddPaths(entries);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// No explicit entries - discover individual files in directory\n\t\t\taddPaths(discoverExtensionsInDir(resolved));\n\t\t\tcontinue;\n\t\t}\n\n\t\taddPaths([resolved]);\n\t}\n\n\treturn loadExtensions(allPaths, resolvedCwd, eventBus);\n}\n"]} \ No newline at end of file diff --git a/dist/core/extensions/loader.js b/dist/core/extensions/loader.js new file mode 100644 index 0000000..099e74e --- /dev/null +++ b/dist/core/extensions/loader.js @@ -0,0 +1,558 @@ +/** + * Extension loader - loads TypeScript extension modules using jiti. + * + */ +import * as fs from "node:fs"; +import { createRequire } from "node:module"; +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as _bundledPiAgentCore from "@earendil-works/pi-agent-core"; +import * as _bundledPiAiCompat from "@earendil-works/pi-ai/compat"; +import * as _bundledPiAiOauth from "@earendil-works/pi-ai/oauth"; +import * as _bundledPiAiProviders from "@earendil-works/pi-ai/providers/all"; +import * as _bundledPiTui from "@earendil-works/pi-tui"; +import { createJiti } from "jiti/static"; +// Static imports of packages that extensions may use. +// These MUST be static so Bun bundles them into the compiled binary. +// The virtualModules option then makes them available to extensions. +import * as _bundledTypebox from "typebox"; +import * as _bundledTypeboxCompile from "typebox/compile"; +import * as _bundledTypeboxValue from "typebox/value"; +import { CONFIG_DIR_NAME, getAgentDir, isBunBinary } from "../../config.js"; +// NOTE: This import works because loader.ts exports are NOT re-exported from index.ts, +// avoiding a circular dependency. Extensions can import from @earendil-works/pi-coding-agent. +import * as _bundledPiCodingAgent from "../../index.js"; +import { resolvePath } from "../../utils/paths.js"; +import { createEventBus } from "../event-bus.js"; +import { execCommand } from "../exec.js"; +import { createSyntheticSourceInfo } from "../source-info.js"; +import { time } from "../timings.js"; +/** Modules available to extensions via virtualModules (for compiled Bun binary) */ +const VIRTUAL_MODULES = { + typebox: _bundledTypebox, + "typebox/compile": _bundledTypeboxCompile, + "typebox/value": _bundledTypeboxValue, + "@sinclair/typebox": _bundledTypebox, + "@sinclair/typebox/compile": _bundledTypeboxCompile, + "@sinclair/typebox/value": _bundledTypeboxValue, + "@earendil-works/pi-agent-core": _bundledPiAgentCore, + "@earendil-works/pi-tui": _bundledPiTui, + // Extensions resolve the pi-ai root to the compat entrypoint (a strict + // superset of the core entrypoint): existing extensions using the old + // global API keep working at runtime until compat is removed. + "@earendil-works/pi-ai": _bundledPiAiCompat, + "@earendil-works/pi-ai/compat": _bundledPiAiCompat, + "@earendil-works/pi-ai/oauth": _bundledPiAiOauth, + "@earendil-works/pi-ai/providers/all": _bundledPiAiProviders, + "@earendil-works/pi-coding-agent": _bundledPiCodingAgent, + "@mariozechner/pi-agent-core": _bundledPiAgentCore, + "@mariozechner/pi-tui": _bundledPiTui, + "@mariozechner/pi-ai": _bundledPiAiCompat, + "@mariozechner/pi-ai/compat": _bundledPiAiCompat, + "@mariozechner/pi-ai/oauth": _bundledPiAiOauth, + "@mariozechner/pi-ai/providers/all": _bundledPiAiProviders, + "@mariozechner/pi-coding-agent": _bundledPiCodingAgent, +}; +const require = createRequire(import.meta.url); +/** + * Get aliases for jiti (used in Node.js/development mode). + * In Bun binary mode, virtualModules is used instead. + */ +let _aliases = null; +function getAliases() { + if (_aliases) + return _aliases; + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + const packageIndex = path.resolve(__dirname, "../..", "index.js"); + const typeboxEntry = require.resolve("typebox"); + const typeboxCompileEntry = require.resolve("typebox/compile"); + const typeboxValueEntry = require.resolve("typebox/value"); + const packagesRoot = path.resolve(__dirname, "../../../../"); + const resolveWorkspaceOrImport = (workspaceRelativePath, specifier) => { + const workspacePath = path.join(packagesRoot, workspaceRelativePath); + if (fs.existsSync(workspacePath)) { + return workspacePath; + } + return fileURLToPath(import.meta.resolve(specifier)); + }; + const piCodingAgentEntry = packageIndex; + const piAgentCoreEntry = resolveWorkspaceOrImport("agent/dist/index.js", "@earendil-works/pi-agent-core"); + const piTuiEntry = resolveWorkspaceOrImport("tui/dist/index.js", "@earendil-works/pi-tui"); + // Extensions resolve the pi-ai root to the compat entrypoint (a strict + // superset of the core entrypoint): existing extensions using the old + // global API keep working at runtime until compat is removed. + const piAiCompatEntry = resolveWorkspaceOrImport("ai/dist/compat.js", "@earendil-works/pi-ai/compat"); + const piAiOauthEntry = resolveWorkspaceOrImport("ai/dist/oauth.js", "@earendil-works/pi-ai/oauth"); + const piAiProvidersEntry = resolveWorkspaceOrImport("ai/dist/providers/all.js", "@earendil-works/pi-ai/providers/all"); + _aliases = { + "@earendil-works/pi-coding-agent": piCodingAgentEntry, + "@earendil-works/pi-agent-core": piAgentCoreEntry, + "@earendil-works/pi-tui": piTuiEntry, + "@earendil-works/pi-ai/providers/all": piAiProvidersEntry, + "@earendil-works/pi-ai/compat": piAiCompatEntry, + "@earendil-works/pi-ai/oauth": piAiOauthEntry, + "@earendil-works/pi-ai": piAiCompatEntry, + "@mariozechner/pi-coding-agent": piCodingAgentEntry, + "@mariozechner/pi-agent-core": piAgentCoreEntry, + "@mariozechner/pi-tui": piTuiEntry, + "@mariozechner/pi-ai/providers/all": piAiProvidersEntry, + "@mariozechner/pi-ai/compat": piAiCompatEntry, + "@mariozechner/pi-ai/oauth": piAiOauthEntry, + "@mariozechner/pi-ai": piAiCompatEntry, + typebox: typeboxEntry, + "typebox/compile": typeboxCompileEntry, + "typebox/value": typeboxValueEntry, + "@sinclair/typebox": typeboxEntry, + "@sinclair/typebox/compile": typeboxCompileEntry, + "@sinclair/typebox/value": typeboxValueEntry, + }; + return _aliases; +} +let extensionCacheCwd; +let extensionCacheGeneration = 0; +const extensionCache = new Map(); +export function clearExtensionCache() { + extensionCache.clear(); + extensionCacheCwd = undefined; + extensionCacheGeneration++; +} +function useExtensionCacheCwd(cwd) { + const resolvedCwd = resolvePath(cwd); + if (extensionCacheCwd !== undefined && extensionCacheCwd !== resolvedCwd) { + clearExtensionCache(); + } + extensionCacheCwd = resolvedCwd; + return { cwd: resolvedCwd, generation: extensionCacheGeneration }; +} +/** + * Create a runtime with throwing stubs for action methods. + * Runner.bindCore() replaces these with real implementations. + */ +export function createExtensionRuntime() { + const notInitialized = () => { + throw new Error("Extension runtime not initialized. Action methods cannot be called during extension loading."); + }; + const state = {}; + const assertActive = () => { + if (state.staleMessage) { + throw new Error(state.staleMessage); + } + }; + const runtime = { + sendMessage: notInitialized, + sendUserMessage: notInitialized, + appendEntry: notInitialized, + setSessionName: notInitialized, + getSessionName: notInitialized, + setLabel: notInitialized, + getActiveTools: notInitialized, + getAllTools: notInitialized, + setActiveTools: notInitialized, + // registerTool() is valid during extension load; refresh is only needed post-bind. + refreshTools: () => { }, + getCommands: notInitialized, + setModel: () => Promise.reject(new Error("Extension runtime not initialized")), + getThinkingLevel: notInitialized, + setThinkingLevel: notInitialized, + flagValues: new Map(), + pendingProviderRegistrations: [], + pendingNativeProviderRegistrations: [], + assertActive, + invalidate: (message) => { + state.staleMessage ??= + message ?? + "This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload()."; + }, + // Pre-bind: queue registrations so bindCore() can flush them once the + // model registry is available. bindCore() replaces both with direct calls. + registerProvider: (name, config, extensionPath = "") => { + runtime.pendingProviderRegistrations.push({ name, config, extensionPath }); + }, + registerNativeProvider: (provider, extensionPath = "") => { + runtime.pendingNativeProviderRegistrations.push({ provider, extensionPath }); + }, + unregisterProvider: (name) => { + runtime.pendingProviderRegistrations = runtime.pendingProviderRegistrations.filter((r) => r.name !== name); + runtime.pendingNativeProviderRegistrations = runtime.pendingNativeProviderRegistrations.filter((r) => r.provider.id !== name); + }, + }; + return runtime; +} +/** + * Create the ExtensionAPI for an extension. + * Registration methods write to the extension object. + * Action methods delegate to the shared runtime. + */ +function createExtensionAPI(extension, runtime, cwd, eventBus) { + const api = { + // Registration methods - write to extension + on(event, handler) { + runtime.assertActive(); + const list = extension.handlers.get(event) ?? []; + list.push(handler); + extension.handlers.set(event, list); + }, + registerTool(tool) { + runtime.assertActive(); + extension.tools.set(tool.name, { + definition: tool, + sourceInfo: extension.sourceInfo, + }); + runtime.refreshTools(); + }, + registerCommand(name, options) { + runtime.assertActive(); + extension.commands.set(name, { + name, + sourceInfo: extension.sourceInfo, + ...options, + }); + }, + registerShortcut(shortcut, options) { + runtime.assertActive(); + extension.shortcuts.set(shortcut, { shortcut, extensionPath: extension.path, ...options }); + }, + registerFlag(name, options) { + runtime.assertActive(); + extension.flags.set(name, { name, extensionPath: extension.path, ...options }); + if (options.default !== undefined && !runtime.flagValues.has(name)) { + runtime.flagValues.set(name, options.default); + } + }, + registerMessageRenderer(customType, renderer) { + runtime.assertActive(); + extension.messageRenderers.set(customType, renderer); + }, + registerEntryRenderer(customType, renderer) { + runtime.assertActive(); + extension.entryRenderers ??= new Map(); + extension.entryRenderers.set(customType, renderer); + }, + // Flag access - checks extension registered it, reads from runtime + getFlag(name) { + runtime.assertActive(); + if (!extension.flags.has(name)) + return undefined; + return runtime.flagValues.get(name); + }, + // Action methods - delegate to shared runtime + sendMessage(message, options) { + runtime.assertActive(); + runtime.sendMessage(message, options); + }, + sendUserMessage(content, options) { + runtime.assertActive(); + runtime.sendUserMessage(content, options); + }, + appendEntry(customType, data) { + runtime.assertActive(); + runtime.appendEntry(customType, data); + }, + setSessionName(name) { + runtime.assertActive(); + runtime.setSessionName(name); + }, + getSessionName() { + runtime.assertActive(); + return runtime.getSessionName(); + }, + setLabel(entryId, label) { + runtime.assertActive(); + runtime.setLabel(entryId, label); + }, + exec(command, args, options) { + runtime.assertActive(); + return execCommand(command, args, options?.cwd ?? cwd, options); + }, + getActiveTools() { + runtime.assertActive(); + return runtime.getActiveTools(); + }, + getAllTools() { + runtime.assertActive(); + return runtime.getAllTools(); + }, + setActiveTools(toolNames) { + runtime.assertActive(); + runtime.setActiveTools(toolNames); + }, + getCommands() { + runtime.assertActive(); + return runtime.getCommands(); + }, + setModel(model) { + runtime.assertActive(); + return runtime.setModel(model); + }, + getThinkingLevel() { + runtime.assertActive(); + return runtime.getThinkingLevel(); + }, + setThinkingLevel(level) { + runtime.assertActive(); + runtime.setThinkingLevel(level); + }, + registerProvider(providerOrName, config) { + runtime.assertActive(); + if (typeof providerOrName === "string") { + if (!config) + throw new Error("Provider config is required when registering by name"); + runtime.registerProvider(providerOrName, config, extension.path); + return; + } + runtime.registerNativeProvider(providerOrName, extension.path); + }, + unregisterProvider(name) { + runtime.assertActive(); + runtime.unregisterProvider(name, extension.path); + }, + events: eventBus, + }; + return api; +} +function isCurrentCacheToken(cacheToken) { + return (cacheToken !== undefined && + extensionCacheCwd === cacheToken.cwd && + extensionCacheGeneration === cacheToken.generation); +} +async function loadExtensionModule(extensionPath, cacheToken) { + if (isCurrentCacheToken(cacheToken)) { + const cachedFactory = extensionCache.get(extensionPath); + if (cachedFactory) { + return cachedFactory; + } + } + const jiti = createJiti(import.meta.url, { + moduleCache: false, + // In Bun binary: use virtualModules for bundled packages (no filesystem resolution) + // Also disable tryNative so jiti handles ALL imports (not just the entry point) + // In Node.js/dev: use aliases to resolve to node_modules paths + ...(isBunBinary ? { virtualModules: VIRTUAL_MODULES, tryNative: false } : { alias: getAliases() }), + }); + const module = await jiti.import(extensionPath, { default: true }); + const factory = module; + if (typeof factory !== "function") { + return undefined; + } + if (isCurrentCacheToken(cacheToken)) { + extensionCache.set(extensionPath, factory); + } + return factory; +} +/** + * Create an Extension object with empty collections. + */ +function createExtension(extensionPath, resolvedPath) { + const source = extensionPath.startsWith("<") && extensionPath.endsWith(">") + ? extensionPath.slice(1, -1).split(":")[0] || "temporary" + : "local"; + const baseDir = extensionPath.startsWith("<") ? undefined : path.dirname(resolvedPath); + return { + path: extensionPath, + resolvedPath, + sourceInfo: createSyntheticSourceInfo(extensionPath, { source, baseDir }), + handlers: new Map(), + tools: new Map(), + messageRenderers: new Map(), + entryRenderers: new Map(), + commands: new Map(), + flags: new Map(), + shortcuts: new Map(), + }; +} +async function loadExtension(extensionPath, cwd, eventBus, runtime, cacheToken) { + const resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true }); + try { + const factory = await loadExtensionModule(resolvedPath, cacheToken); + time(`${extensionPath} module import`, "extensions"); + if (!factory) { + return { extension: null, error: `Extension does not export a valid factory function: ${extensionPath}` }; + } + const extension = createExtension(extensionPath, resolvedPath); + const api = createExtensionAPI(extension, runtime, cwd, eventBus); + await factory(api); + time(`${extensionPath} factory`, "extensions"); + return { extension, error: null }; + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + return { extension: null, error: `Failed to load extension: ${message}` }; + } +} +/** + * Create an Extension from an inline factory function. + */ +export async function loadExtensionFromFactory(factory, cwd, eventBus, runtime, extensionPath = "") { + const extension = createExtension(extensionPath, extensionPath); + const resolvedCwd = resolvePath(cwd); + const api = createExtensionAPI(extension, runtime, resolvedCwd, eventBus); + await factory(api); + time(`${extensionPath} factory`, "extensions"); + return extension; +} +/** + * Load extensions from paths. + */ +async function loadExtensionsInternal(paths, cwd, eventBus, runtime, useCache = false) { + const extensions = []; + const errors = []; + const cacheToken = useCache ? useExtensionCacheCwd(cwd) : undefined; + const resolvedCwd = cacheToken?.cwd ?? resolvePath(cwd); + const resolvedEventBus = eventBus ?? createEventBus(); + const resolvedRuntime = runtime ?? createExtensionRuntime(); + for (const extPath of paths) { + const { extension, error } = await loadExtension(extPath, resolvedCwd, resolvedEventBus, resolvedRuntime, cacheToken); + if (error) { + errors.push({ path: extPath, error }); + continue; + } + if (extension) { + extensions.push(extension); + } + } + return { + extensions, + errors, + runtime: resolvedRuntime, + }; +} +export async function loadExtensions(paths, cwd, eventBus, runtime) { + return loadExtensionsInternal(paths, cwd, eventBus, runtime); +} +export async function loadExtensionsCached(paths, cwd, eventBus, runtime) { + return loadExtensionsInternal(paths, cwd, eventBus, runtime, true); +} +function readPiManifest(packageJsonPath) { + try { + const content = fs.readFileSync(packageJsonPath, "utf-8"); + const pkg = JSON.parse(content); + if (pkg.pi && typeof pkg.pi === "object") { + return pkg.pi; + } + return null; + } + catch { + return null; + } +} +function isExtensionFile(name) { + return name.endsWith(".ts") || name.endsWith(".js"); +} +/** + * Resolve extension entry points from a directory. + * + * Checks for: + * 1. package.json with "pi.extensions" field -> returns declared paths + * 2. index.ts or index.js -> returns the index file + * + * Returns resolved paths or null if no entry points found. + */ +function resolveExtensionEntries(dir) { + // Check for package.json with "pi" field first + const packageJsonPath = path.join(dir, "package.json"); + if (fs.existsSync(packageJsonPath)) { + const manifest = readPiManifest(packageJsonPath); + if (manifest?.extensions?.length) { + const entries = []; + for (const extPath of manifest.extensions) { + const resolvedExtPath = path.resolve(dir, extPath); + if (fs.existsSync(resolvedExtPath)) { + entries.push(resolvedExtPath); + } + } + if (entries.length > 0) { + return entries; + } + } + } + // Check for index.ts or index.js + const indexTs = path.join(dir, "index.ts"); + const indexJs = path.join(dir, "index.js"); + if (fs.existsSync(indexTs)) { + return [indexTs]; + } + if (fs.existsSync(indexJs)) { + return [indexJs]; + } + return null; +} +/** + * Discover extensions in a directory. + * + * Discovery rules: + * 1. Direct files: `extensions/*.ts` or `*.js` → load + * 2. Subdirectory with index: `extensions/* /index.ts` or `index.js` → load + * 3. Subdirectory with package.json: `extensions/* /package.json` with "pi" field → load what it declares + * + * No recursion beyond one level. Complex packages must use package.json manifest. + */ +function discoverExtensionsInDir(dir) { + if (!fs.existsSync(dir)) { + return []; + } + const discovered = []; + try { + const entries = fs.readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + const entryPath = path.join(dir, entry.name); + // 1. Direct files: *.ts or *.js + if ((entry.isFile() || entry.isSymbolicLink()) && isExtensionFile(entry.name)) { + discovered.push(entryPath); + continue; + } + // 2 & 3. Subdirectories + if (entry.isDirectory() || entry.isSymbolicLink()) { + const entries = resolveExtensionEntries(entryPath); + if (entries) { + discovered.push(...entries); + } + } + } + } + catch { + return []; + } + return discovered; +} +/** + * Discover and load extensions from standard locations. + */ +export async function discoverAndLoadExtensions(configuredPaths, cwd, agentDir = getAgentDir(), eventBus) { + const resolvedCwd = resolvePath(cwd); + const resolvedAgentDir = resolvePath(agentDir); + const allPaths = []; + const seen = new Set(); + const addPaths = (paths) => { + for (const p of paths) { + const resolved = path.resolve(p); + if (!seen.has(resolved)) { + seen.add(resolved); + allPaths.push(p); + } + } + }; + // 1. Project-local extensions: cwd/${CONFIG_DIR_NAME}/extensions/ + const localExtDir = path.join(resolvedCwd, CONFIG_DIR_NAME, "extensions"); + addPaths(discoverExtensionsInDir(localExtDir)); + // 2. Global extensions: agentDir/extensions/ + const globalExtDir = path.join(resolvedAgentDir, "extensions"); + addPaths(discoverExtensionsInDir(globalExtDir)); + // 3. Explicitly configured paths + for (const p of configuredPaths) { + const resolved = resolvePath(p, resolvedCwd, { normalizeUnicodeSpaces: true }); + if (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) { + // Check for package.json with pi manifest or index.ts + const entries = resolveExtensionEntries(resolved); + if (entries) { + addPaths(entries); + continue; + } + // No explicit entries - discover individual files in directory + addPaths(discoverExtensionsInDir(resolved)); + continue; + } + addPaths([resolved]); + } + return loadExtensions(allPaths, resolvedCwd, eventBus); +} +//# sourceMappingURL=loader.js.map \ No newline at end of file diff --git a/dist/core/extensions/loader.js.map b/dist/core/extensions/loader.js.map new file mode 100644 index 0000000..5214e52 --- /dev/null +++ b/dist/core/extensions/loader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"loader.js","sourceRoot":"","sources":["../../../src/core/extensions/loader.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,KAAK,mBAAmB,MAAM,+BAA+B,CAAC;AAErE,OAAO,KAAK,kBAAkB,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,iBAAiB,MAAM,6BAA6B,CAAC;AACjE,OAAO,KAAK,qBAAqB,MAAM,qCAAqC,CAAC;AAE7E,OAAO,KAAK,aAAa,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,sDAAsD;AACtD,qEAAqE;AACrE,qEAAqE;AACrE,OAAO,KAAK,eAAe,MAAM,SAAS,CAAC;AAC3C,OAAO,KAAK,sBAAsB,MAAM,iBAAiB,CAAC;AAC1D,OAAO,KAAK,oBAAoB,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC5E,uF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AAC,CAAC;IACtB,CAAC;IAED,OAAO,cAAc,CAAC,QAAQ,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;AAAA,CACvD","sourcesContent":["/**\n * Extension loader - loads TypeScript extension modules using jiti.\n *\n */\n\nimport * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport * as _bundledPiAgentCore from \"@earendil-works/pi-agent-core\";\nimport type { Provider } from \"@earendil-works/pi-ai\";\nimport * as _bundledPiAiCompat from \"@earendil-works/pi-ai/compat\";\nimport * as _bundledPiAiOauth from \"@earendil-works/pi-ai/oauth\";\nimport * as _bundledPiAiProviders from \"@earendil-works/pi-ai/providers/all\";\nimport type { KeyId } from \"@earendil-works/pi-tui\";\nimport * as _bundledPiTui from \"@earendil-works/pi-tui\";\nimport { createJiti } from \"jiti/static\";\n// Static imports of packages that extensions may use.\n// These MUST be static so Bun bundles them into the compiled binary.\n// The virtualModules option then makes them available to extensions.\nimport * as _bundledTypebox from \"typebox\";\nimport * as _bundledTypeboxCompile from \"typebox/compile\";\nimport * as _bundledTypeboxValue from \"typebox/value\";\nimport { CONFIG_DIR_NAME, getAgentDir, isBunBinary } from \"../../config.ts\";\n// NOTE: This import works because loader.ts exports are NOT re-exported from index.ts,\n// avoiding a circular dependency. Extensions can import from @earendil-works/pi-coding-agent.\nimport * as _bundledPiCodingAgent from \"../../index.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { createEventBus, type EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions } from \"../exec.ts\";\nimport { execCommand } from \"../exec.ts\";\nimport { createSyntheticSourceInfo } from \"../source-info.ts\";\nimport { time } from \"../timings.ts\";\nimport type {\n\tEntryRenderer,\n\tExtension,\n\tExtensionAPI,\n\tExtensionFactory,\n\tExtensionRuntime,\n\tLoadExtensionsResult,\n\tMessageRenderer,\n\tProviderConfig,\n\tRegisteredCommand,\n\tToolDefinition,\n} from \"./types.ts\";\n\n/** Modules available to extensions via virtualModules (for compiled Bun binary) */\nconst VIRTUAL_MODULES: Record = {\n\ttypebox: _bundledTypebox,\n\t\"typebox/compile\": _bundledTypeboxCompile,\n\t\"typebox/value\": _bundledTypeboxValue,\n\t\"@sinclair/typebox\": _bundledTypebox,\n\t\"@sinclair/typebox/compile\": _bundledTypeboxCompile,\n\t\"@sinclair/typebox/value\": _bundledTypeboxValue,\n\t\"@earendil-works/pi-agent-core\": _bundledPiAgentCore,\n\t\"@earendil-works/pi-tui\": _bundledPiTui,\n\t// Extensions resolve the pi-ai root to the compat entrypoint (a strict\n\t// superset of the core entrypoint): existing extensions using the old\n\t// global API keep working at runtime until compat is removed.\n\t\"@earendil-works/pi-ai\": _bundledPiAiCompat,\n\t\"@earendil-works/pi-ai/compat\": _bundledPiAiCompat,\n\t\"@earendil-works/pi-ai/oauth\": _bundledPiAiOauth,\n\t\"@earendil-works/pi-ai/providers/all\": _bundledPiAiProviders,\n\t\"@earendil-works/pi-coding-agent\": _bundledPiCodingAgent,\n\t\"@mariozechner/pi-agent-core\": _bundledPiAgentCore,\n\t\"@mariozechner/pi-tui\": _bundledPiTui,\n\t\"@mariozechner/pi-ai\": _bundledPiAiCompat,\n\t\"@mariozechner/pi-ai/compat\": _bundledPiAiCompat,\n\t\"@mariozechner/pi-ai/oauth\": _bundledPiAiOauth,\n\t\"@mariozechner/pi-ai/providers/all\": _bundledPiAiProviders,\n\t\"@mariozechner/pi-coding-agent\": _bundledPiCodingAgent,\n};\n\nconst require = createRequire(import.meta.url);\n\n/**\n * Get aliases for jiti (used in Node.js/development mode).\n * In Bun binary mode, virtualModules is used instead.\n */\nlet _aliases: Record | null = null;\n\nfunction getAliases(): Record {\n\tif (_aliases) return _aliases;\n\n\tconst __dirname = path.dirname(fileURLToPath(import.meta.url));\n\tconst packageIndex = path.resolve(__dirname, \"../..\", \"index.js\");\n\n\tconst typeboxEntry = require.resolve(\"typebox\");\n\tconst typeboxCompileEntry = require.resolve(\"typebox/compile\");\n\tconst typeboxValueEntry = require.resolve(\"typebox/value\");\n\n\tconst packagesRoot = path.resolve(__dirname, \"../../../../\");\n\tconst resolveWorkspaceOrImport = (workspaceRelativePath: string, specifier: string): string => {\n\t\tconst workspacePath = path.join(packagesRoot, workspaceRelativePath);\n\t\tif (fs.existsSync(workspacePath)) {\n\t\t\treturn workspacePath;\n\t\t}\n\t\treturn fileURLToPath(import.meta.resolve(specifier));\n\t};\n\n\tconst piCodingAgentEntry = packageIndex;\n\tconst piAgentCoreEntry = resolveWorkspaceOrImport(\"agent/dist/index.js\", \"@earendil-works/pi-agent-core\");\n\tconst piTuiEntry = resolveWorkspaceOrImport(\"tui/dist/index.js\", \"@earendil-works/pi-tui\");\n\t// Extensions resolve the pi-ai root to the compat entrypoint (a strict\n\t// superset of the core entrypoint): existing extensions using the old\n\t// global API keep working at runtime until compat is removed.\n\tconst piAiCompatEntry = resolveWorkspaceOrImport(\"ai/dist/compat.js\", \"@earendil-works/pi-ai/compat\");\n\tconst piAiOauthEntry = resolveWorkspaceOrImport(\"ai/dist/oauth.js\", \"@earendil-works/pi-ai/oauth\");\n\tconst piAiProvidersEntry = resolveWorkspaceOrImport(\n\t\t\"ai/dist/providers/all.js\",\n\t\t\"@earendil-works/pi-ai/providers/all\",\n\t);\n\n\t_aliases = {\n\t\t\"@earendil-works/pi-coding-agent\": piCodingAgentEntry,\n\t\t\"@earendil-works/pi-agent-core\": piAgentCoreEntry,\n\t\t\"@earendil-works/pi-tui\": piTuiEntry,\n\t\t\"@earendil-works/pi-ai/providers/all\": piAiProvidersEntry,\n\t\t\"@earendil-works/pi-ai/compat\": piAiCompatEntry,\n\t\t\"@earendil-works/pi-ai/oauth\": piAiOauthEntry,\n\t\t\"@earendil-works/pi-ai\": piAiCompatEntry,\n\t\t\"@mariozechner/pi-coding-agent\": piCodingAgentEntry,\n\t\t\"@mariozechner/pi-agent-core\": piAgentCoreEntry,\n\t\t\"@mariozechner/pi-tui\": piTuiEntry,\n\t\t\"@mariozechner/pi-ai/providers/all\": piAiProvidersEntry,\n\t\t\"@mariozechner/pi-ai/compat\": piAiCompatEntry,\n\t\t\"@mariozechner/pi-ai/oauth\": piAiOauthEntry,\n\t\t\"@mariozechner/pi-ai\": piAiCompatEntry,\n\t\ttypebox: typeboxEntry,\n\t\t\"typebox/compile\": typeboxCompileEntry,\n\t\t\"typebox/value\": typeboxValueEntry,\n\t\t\"@sinclair/typebox\": typeboxEntry,\n\t\t\"@sinclair/typebox/compile\": typeboxCompileEntry,\n\t\t\"@sinclair/typebox/value\": typeboxValueEntry,\n\t};\n\n\treturn _aliases;\n}\n\ntype HandlerFn = (...args: unknown[]) => Promise;\n\nlet extensionCacheCwd: string | undefined;\nlet extensionCacheGeneration = 0;\nconst extensionCache = new Map();\n\ninterface ExtensionCacheToken {\n\tcwd: string;\n\tgeneration: number;\n}\n\nexport function clearExtensionCache(): void {\n\textensionCache.clear();\n\textensionCacheCwd = undefined;\n\textensionCacheGeneration++;\n}\n\nfunction useExtensionCacheCwd(cwd: string): ExtensionCacheToken {\n\tconst resolvedCwd = resolvePath(cwd);\n\tif (extensionCacheCwd !== undefined && extensionCacheCwd !== resolvedCwd) {\n\t\tclearExtensionCache();\n\t}\n\textensionCacheCwd = resolvedCwd;\n\treturn { cwd: resolvedCwd, generation: extensionCacheGeneration };\n}\n\n/**\n * Create a runtime with throwing stubs for action methods.\n * Runner.bindCore() replaces these with real implementations.\n */\nexport function createExtensionRuntime(): ExtensionRuntime {\n\tconst notInitialized = () => {\n\t\tthrow new Error(\"Extension runtime not initialized. Action methods cannot be called during extension loading.\");\n\t};\n\tconst state: { staleMessage?: string } = {};\n\tconst assertActive = () => {\n\t\tif (state.staleMessage) {\n\t\t\tthrow new Error(state.staleMessage);\n\t\t}\n\t};\n\n\tconst runtime: ExtensionRuntime = {\n\t\tsendMessage: notInitialized,\n\t\tsendUserMessage: notInitialized,\n\t\tappendEntry: notInitialized,\n\t\tsetSessionName: notInitialized,\n\t\tgetSessionName: notInitialized,\n\t\tsetLabel: notInitialized,\n\t\tgetActiveTools: notInitialized,\n\t\tgetAllTools: notInitialized,\n\t\tsetActiveTools: notInitialized,\n\t\t// registerTool() is valid during extension load; refresh is only needed post-bind.\n\t\trefreshTools: () => {},\n\t\tgetCommands: notInitialized,\n\t\tsetModel: () => Promise.reject(new Error(\"Extension runtime not initialized\")),\n\t\tgetThinkingLevel: notInitialized,\n\t\tsetThinkingLevel: notInitialized,\n\t\tflagValues: new Map(),\n\t\tpendingProviderRegistrations: [],\n\t\tpendingNativeProviderRegistrations: [],\n\t\tassertActive,\n\t\tinvalidate: (message) => {\n\t\t\tstate.staleMessage ??=\n\t\t\t\tmessage ??\n\t\t\t\t\"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\";\n\t\t},\n\t\t// Pre-bind: queue registrations so bindCore() can flush them once the\n\t\t// model registry is available. bindCore() replaces both with direct calls.\n\t\tregisterProvider: (name, config, extensionPath = \"\") => {\n\t\t\truntime.pendingProviderRegistrations.push({ name, config, extensionPath });\n\t\t},\n\t\tregisterNativeProvider: (provider, extensionPath = \"\") => {\n\t\t\truntime.pendingNativeProviderRegistrations.push({ provider, extensionPath });\n\t\t},\n\t\tunregisterProvider: (name) => {\n\t\t\truntime.pendingProviderRegistrations = runtime.pendingProviderRegistrations.filter((r) => r.name !== name);\n\t\t\truntime.pendingNativeProviderRegistrations = runtime.pendingNativeProviderRegistrations.filter(\n\t\t\t\t(r) => r.provider.id !== name,\n\t\t\t);\n\t\t},\n\t};\n\n\treturn runtime;\n}\n\n/**\n * Create the ExtensionAPI for an extension.\n * Registration methods write to the extension object.\n * Action methods delegate to the shared runtime.\n */\nfunction createExtensionAPI(\n\textension: Extension,\n\truntime: ExtensionRuntime,\n\tcwd: string,\n\teventBus: EventBus,\n): ExtensionAPI {\n\tconst api = {\n\t\t// Registration methods - write to extension\n\t\ton(event: string, handler: HandlerFn): void {\n\t\t\truntime.assertActive();\n\t\t\tconst list = extension.handlers.get(event) ?? [];\n\t\t\tlist.push(handler);\n\t\t\textension.handlers.set(event, list);\n\t\t},\n\n\t\tregisterTool(tool: ToolDefinition): void {\n\t\t\truntime.assertActive();\n\t\t\textension.tools.set(tool.name, {\n\t\t\t\tdefinition: tool,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t});\n\t\t\truntime.refreshTools();\n\t\t},\n\n\t\tregisterCommand(name: string, options: Omit): void {\n\t\t\truntime.assertActive();\n\t\t\textension.commands.set(name, {\n\t\t\t\tname,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\t...options,\n\t\t\t});\n\t\t},\n\n\t\tregisterShortcut(\n\t\t\tshortcut: KeyId,\n\t\t\toptions: {\n\t\t\t\tdescription?: string;\n\t\t\t\thandler: (ctx: import(\"./types.ts\").ExtensionContext) => Promise | void;\n\t\t\t},\n\t\t): void {\n\t\t\truntime.assertActive();\n\t\t\textension.shortcuts.set(shortcut, { shortcut, extensionPath: extension.path, ...options });\n\t\t},\n\n\t\tregisterFlag(\n\t\t\tname: string,\n\t\t\toptions: { description?: string; type: \"boolean\" | \"string\"; default?: boolean | string },\n\t\t): void {\n\t\t\truntime.assertActive();\n\t\t\textension.flags.set(name, { name, extensionPath: extension.path, ...options });\n\t\t\tif (options.default !== undefined && !runtime.flagValues.has(name)) {\n\t\t\t\truntime.flagValues.set(name, options.default);\n\t\t\t}\n\t\t},\n\n\t\tregisterMessageRenderer(customType: string, renderer: MessageRenderer): void {\n\t\t\truntime.assertActive();\n\t\t\textension.messageRenderers.set(customType, renderer as MessageRenderer);\n\t\t},\n\n\t\tregisterEntryRenderer(customType: string, renderer: EntryRenderer): void {\n\t\t\truntime.assertActive();\n\t\t\textension.entryRenderers ??= new Map();\n\t\t\textension.entryRenderers.set(customType, renderer as EntryRenderer);\n\t\t},\n\n\t\t// Flag access - checks extension registered it, reads from runtime\n\t\tgetFlag(name: string): boolean | string | undefined {\n\t\t\truntime.assertActive();\n\t\t\tif (!extension.flags.has(name)) return undefined;\n\t\t\treturn runtime.flagValues.get(name);\n\t\t},\n\n\t\t// Action methods - delegate to shared runtime\n\t\tsendMessage(message, options): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.sendMessage(message, options);\n\t\t},\n\n\t\tsendUserMessage(content, options): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.sendUserMessage(content, options);\n\t\t},\n\n\t\tappendEntry(customType: string, data?: unknown): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.appendEntry(customType, data);\n\t\t},\n\n\t\tsetSessionName(name: string): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setSessionName(name);\n\t\t},\n\n\t\tgetSessionName(): string | undefined {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getSessionName();\n\t\t},\n\n\t\tsetLabel(entryId: string, label: string | undefined): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setLabel(entryId, label);\n\t\t},\n\n\t\texec(command: string, args: string[], options?: ExecOptions) {\n\t\t\truntime.assertActive();\n\t\t\treturn execCommand(command, args, options?.cwd ?? cwd, options);\n\t\t},\n\n\t\tgetActiveTools(): string[] {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getActiveTools();\n\t\t},\n\n\t\tgetAllTools() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getAllTools();\n\t\t},\n\n\t\tsetActiveTools(toolNames: string[]): void {\n\t\t\truntime.assertActive();\n\t\t\truntime.setActiveTools(toolNames);\n\t\t},\n\n\t\tgetCommands() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getCommands();\n\t\t},\n\n\t\tsetModel(model) {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.setModel(model);\n\t\t},\n\n\t\tgetThinkingLevel() {\n\t\t\truntime.assertActive();\n\t\t\treturn runtime.getThinkingLevel();\n\t\t},\n\n\t\tsetThinkingLevel(level) {\n\t\t\truntime.assertActive();\n\t\t\truntime.setThinkingLevel(level);\n\t\t},\n\n\t\tregisterProvider(providerOrName: Provider | string, config?: ProviderConfig) {\n\t\t\truntime.assertActive();\n\t\t\tif (typeof providerOrName === \"string\") {\n\t\t\t\tif (!config) throw new Error(\"Provider config is required when registering by name\");\n\t\t\t\truntime.registerProvider(providerOrName, config, extension.path);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.registerNativeProvider(providerOrName, extension.path);\n\t\t},\n\n\t\tunregisterProvider(name: string) {\n\t\t\truntime.assertActive();\n\t\t\truntime.unregisterProvider(name, extension.path);\n\t\t},\n\n\t\tevents: eventBus,\n\t} as ExtensionAPI;\n\n\treturn api;\n}\n\nfunction isCurrentCacheToken(cacheToken: ExtensionCacheToken | undefined): cacheToken is ExtensionCacheToken {\n\treturn (\n\t\tcacheToken !== undefined &&\n\t\textensionCacheCwd === cacheToken.cwd &&\n\t\textensionCacheGeneration === cacheToken.generation\n\t);\n}\n\nasync function loadExtensionModule(extensionPath: string, cacheToken?: ExtensionCacheToken) {\n\tif (isCurrentCacheToken(cacheToken)) {\n\t\tconst cachedFactory = extensionCache.get(extensionPath);\n\t\tif (cachedFactory) {\n\t\t\treturn cachedFactory;\n\t\t}\n\t}\n\n\tconst jiti = createJiti(import.meta.url, {\n\t\tmoduleCache: false,\n\t\t// In Bun binary: use virtualModules for bundled packages (no filesystem resolution)\n\t\t// Also disable tryNative so jiti handles ALL imports (not just the entry point)\n\t\t// In Node.js/dev: use aliases to resolve to node_modules paths\n\t\t...(isBunBinary ? { virtualModules: VIRTUAL_MODULES, tryNative: false } : { alias: getAliases() }),\n\t});\n\n\tconst module = await jiti.import(extensionPath, { default: true });\n\tconst factory = module as ExtensionFactory;\n\tif (typeof factory !== \"function\") {\n\t\treturn undefined;\n\t}\n\tif (isCurrentCacheToken(cacheToken)) {\n\t\textensionCache.set(extensionPath, factory);\n\t}\n\treturn factory;\n}\n\n/**\n * Create an Extension object with empty collections.\n */\nfunction createExtension(extensionPath: string, resolvedPath: string): Extension {\n\tconst source =\n\t\textensionPath.startsWith(\"<\") && extensionPath.endsWith(\">\")\n\t\t\t? extensionPath.slice(1, -1).split(\":\")[0] || \"temporary\"\n\t\t\t: \"local\";\n\tconst baseDir = extensionPath.startsWith(\"<\") ? undefined : path.dirname(resolvedPath);\n\n\treturn {\n\t\tpath: extensionPath,\n\t\tresolvedPath,\n\t\tsourceInfo: createSyntheticSourceInfo(extensionPath, { source, baseDir }),\n\t\thandlers: new Map(),\n\t\ttools: new Map(),\n\t\tmessageRenderers: new Map(),\n\t\tentryRenderers: new Map(),\n\t\tcommands: new Map(),\n\t\tflags: new Map(),\n\t\tshortcuts: new Map(),\n\t};\n}\n\nasync function loadExtension(\n\textensionPath: string,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n\tcacheToken?: ExtensionCacheToken,\n): Promise<{ extension: Extension | null; error: string | null }> {\n\tconst resolvedPath = resolvePath(extensionPath, cwd, { normalizeUnicodeSpaces: true });\n\n\ttry {\n\t\tconst factory = await loadExtensionModule(resolvedPath, cacheToken);\n\t\ttime(`${extensionPath} module import`, \"extensions\");\n\t\tif (!factory) {\n\t\t\treturn { extension: null, error: `Extension does not export a valid factory function: ${extensionPath}` };\n\t\t}\n\n\t\tconst extension = createExtension(extensionPath, resolvedPath);\n\t\tconst api = createExtensionAPI(extension, runtime, cwd, eventBus);\n\t\tawait factory(api);\n\t\ttime(`${extensionPath} factory`, \"extensions\");\n\n\t\treturn { extension, error: null };\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\treturn { extension: null, error: `Failed to load extension: ${message}` };\n\t}\n}\n\n/**\n * Create an Extension from an inline factory function.\n */\nexport async function loadExtensionFromFactory(\n\tfactory: ExtensionFactory,\n\tcwd: string,\n\teventBus: EventBus,\n\truntime: ExtensionRuntime,\n\textensionPath = \"\",\n): Promise {\n\tconst extension = createExtension(extensionPath, extensionPath);\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst api = createExtensionAPI(extension, runtime, resolvedCwd, eventBus);\n\tawait factory(api);\n\ttime(`${extensionPath} factory`, \"extensions\");\n\treturn extension;\n}\n\n/**\n * Load extensions from paths.\n */\nasync function loadExtensionsInternal(\n\tpaths: string[],\n\tcwd: string,\n\teventBus?: EventBus,\n\truntime?: ExtensionRuntime,\n\tuseCache = false,\n): Promise {\n\tconst extensions: Extension[] = [];\n\tconst errors: Array<{ path: string; error: string }> = [];\n\tconst cacheToken = useCache ? useExtensionCacheCwd(cwd) : undefined;\n\tconst resolvedCwd = cacheToken?.cwd ?? resolvePath(cwd);\n\tconst resolvedEventBus = eventBus ?? createEventBus();\n\tconst resolvedRuntime = runtime ?? createExtensionRuntime();\n\n\tfor (const extPath of paths) {\n\t\tconst { extension, error } = await loadExtension(\n\t\t\textPath,\n\t\t\tresolvedCwd,\n\t\t\tresolvedEventBus,\n\t\t\tresolvedRuntime,\n\t\t\tcacheToken,\n\t\t);\n\n\t\tif (error) {\n\t\t\terrors.push({ path: extPath, error });\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (extension) {\n\t\t\textensions.push(extension);\n\t\t}\n\t}\n\n\treturn {\n\t\textensions,\n\t\terrors,\n\t\truntime: resolvedRuntime,\n\t};\n}\n\nexport async function loadExtensions(\n\tpaths: string[],\n\tcwd: string,\n\teventBus?: EventBus,\n\truntime?: ExtensionRuntime,\n): Promise {\n\treturn loadExtensionsInternal(paths, cwd, eventBus, runtime);\n}\n\nexport async function loadExtensionsCached(\n\tpaths: string[],\n\tcwd: string,\n\teventBus?: EventBus,\n\truntime?: ExtensionRuntime,\n): Promise {\n\treturn loadExtensionsInternal(paths, cwd, eventBus, runtime, true);\n}\n\ninterface PiManifest {\n\textensions?: string[];\n\tthemes?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n}\n\nfunction readPiManifest(packageJsonPath: string): PiManifest | null {\n\ttry {\n\t\tconst content = fs.readFileSync(packageJsonPath, \"utf-8\");\n\t\tconst pkg = JSON.parse(content);\n\t\tif (pkg.pi && typeof pkg.pi === \"object\") {\n\t\t\treturn pkg.pi as PiManifest;\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction isExtensionFile(name: string): boolean {\n\treturn name.endsWith(\".ts\") || name.endsWith(\".js\");\n}\n\n/**\n * Resolve extension entry points from a directory.\n *\n * Checks for:\n * 1. package.json with \"pi.extensions\" field -> returns declared paths\n * 2. index.ts or index.js -> returns the index file\n *\n * Returns resolved paths or null if no entry points found.\n */\nfunction resolveExtensionEntries(dir: string): string[] | null {\n\t// Check for package.json with \"pi\" field first\n\tconst packageJsonPath = path.join(dir, \"package.json\");\n\tif (fs.existsSync(packageJsonPath)) {\n\t\tconst manifest = readPiManifest(packageJsonPath);\n\t\tif (manifest?.extensions?.length) {\n\t\t\tconst entries: string[] = [];\n\t\t\tfor (const extPath of manifest.extensions) {\n\t\t\t\tconst resolvedExtPath = path.resolve(dir, extPath);\n\t\t\t\tif (fs.existsSync(resolvedExtPath)) {\n\t\t\t\t\tentries.push(resolvedExtPath);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (entries.length > 0) {\n\t\t\t\treturn entries;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check for index.ts or index.js\n\tconst indexTs = path.join(dir, \"index.ts\");\n\tconst indexJs = path.join(dir, \"index.js\");\n\tif (fs.existsSync(indexTs)) {\n\t\treturn [indexTs];\n\t}\n\tif (fs.existsSync(indexJs)) {\n\t\treturn [indexJs];\n\t}\n\n\treturn null;\n}\n\n/**\n * Discover extensions in a directory.\n *\n * Discovery rules:\n * 1. Direct files: `extensions/*.ts` or `*.js` → load\n * 2. Subdirectory with index: `extensions/* /index.ts` or `index.js` → load\n * 3. Subdirectory with package.json: `extensions/* /package.json` with \"pi\" field → load what it declares\n *\n * No recursion beyond one level. Complex packages must use package.json manifest.\n */\nfunction discoverExtensionsInDir(dir: string): string[] {\n\tif (!fs.existsSync(dir)) {\n\t\treturn [];\n\t}\n\n\tconst discovered: string[] = [];\n\n\ttry {\n\t\tconst entries = fs.readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of entries) {\n\t\t\tconst entryPath = path.join(dir, entry.name);\n\n\t\t\t// 1. Direct files: *.ts or *.js\n\t\t\tif ((entry.isFile() || entry.isSymbolicLink()) && isExtensionFile(entry.name)) {\n\t\t\t\tdiscovered.push(entryPath);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// 2 & 3. Subdirectories\n\t\t\tif (entry.isDirectory() || entry.isSymbolicLink()) {\n\t\t\t\tconst entries = resolveExtensionEntries(entryPath);\n\t\t\t\tif (entries) {\n\t\t\t\t\tdiscovered.push(...entries);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn [];\n\t}\n\n\treturn discovered;\n}\n\n/**\n * Discover and load extensions from standard locations.\n */\nexport async function discoverAndLoadExtensions(\n\tconfiguredPaths: string[],\n\tcwd: string,\n\tagentDir: string = getAgentDir(),\n\teventBus?: EventBus,\n): Promise {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir);\n\tconst allPaths: string[] = [];\n\tconst seen = new Set();\n\n\tconst addPaths = (paths: string[]) => {\n\t\tfor (const p of paths) {\n\t\t\tconst resolved = path.resolve(p);\n\t\t\tif (!seen.has(resolved)) {\n\t\t\t\tseen.add(resolved);\n\t\t\t\tallPaths.push(p);\n\t\t\t}\n\t\t}\n\t};\n\n\t// 1. Project-local extensions: cwd/${CONFIG_DIR_NAME}/extensions/\n\tconst localExtDir = path.join(resolvedCwd, CONFIG_DIR_NAME, \"extensions\");\n\taddPaths(discoverExtensionsInDir(localExtDir));\n\n\t// 2. Global extensions: agentDir/extensions/\n\tconst globalExtDir = path.join(resolvedAgentDir, \"extensions\");\n\taddPaths(discoverExtensionsInDir(globalExtDir));\n\n\t// 3. Explicitly configured paths\n\tfor (const p of configuredPaths) {\n\t\tconst resolved = resolvePath(p, resolvedCwd, { normalizeUnicodeSpaces: true });\n\t\tif (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {\n\t\t\t// Check for package.json with pi manifest or index.ts\n\t\t\tconst entries = resolveExtensionEntries(resolved);\n\t\t\tif (entries) {\n\t\t\t\taddPaths(entries);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// No explicit entries - discover individual files in directory\n\t\t\taddPaths(discoverExtensionsInDir(resolved));\n\t\t\tcontinue;\n\t\t}\n\n\t\taddPaths([resolved]);\n\t}\n\n\treturn loadExtensions(allPaths, resolvedCwd, eventBus);\n}\n"]} \ No newline at end of file diff --git a/dist/core/extensions/runner.d.ts b/dist/core/extensions/runner.d.ts new file mode 100644 index 0000000..99b17f6 --- /dev/null +++ b/dist/core/extensions/runner.d.ts @@ -0,0 +1,172 @@ +/** + * Extension runner - executes extensions and manages their lifecycle. + */ +import type { AgentMessage } from "@earendil-works/pi-agent-core"; +import type { ImageContent, Provider, ProviderHeaders } from "@earendil-works/pi-ai"; +import type { KeyId } from "@earendil-works/pi-tui"; +import type { ResourceDiagnostic } from "../diagnostics.ts"; +import type { KeybindingsConfig } from "../keybindings.ts"; +import type { ModelRegistry } from "../model-registry.ts"; +import type { SessionManager } from "../session-manager.ts"; +import type { BuildSystemPromptOptions } from "../system-prompt.ts"; +import type { BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, ContextEvent, EntryRenderer, Extension, ExtensionActions, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionError, ExtensionEvent, ExtensionFlag, ExtensionMode, ExtensionRuntime, ExtensionShortcut, ExtensionUIContext, InputEvent, InputEventResult, InputSource, LoadExtensionsResult, MessageEndEvent, MessageRenderer, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventResult, ProviderConfig, RegisteredTool, ReplacedSessionContext, ResolvedCommand, ResourcesDiscoverEvent, SessionBeforeCompactResult, SessionBeforeForkResult, SessionBeforeSwitchResult, SessionBeforeTreeResult, SessionShutdownEvent, ToolCallEvent, ToolCallEventResult, ToolResultEvent, ToolResultEventResult, UserBashEvent, UserBashEventResult } from "./types.ts"; +/** Combined result from all before_agent_start handlers */ +interface BeforeAgentStartCombinedResult { + messages?: NonNullable[]; + systemPrompt?: string; +} +/** + * Events handled by the generic emit() method. + * Events with dedicated emitXxx() methods are excluded for stronger type safety. + */ +type RunnerEmitEvent = Exclude; +type RunnerEmitResult = TEvent extends { + type: "session_before_switch"; +} ? SessionBeforeSwitchResult | undefined : TEvent extends { + type: "session_before_fork"; +} ? SessionBeforeForkResult | undefined : TEvent extends { + type: "session_before_compact"; +} ? SessionBeforeCompactResult | undefined : TEvent extends { + type: "session_before_tree"; +} ? SessionBeforeTreeResult | undefined : undefined; +export type ExtensionErrorListener = (error: ExtensionError) => void; +export type NewSessionHandler = (options?: { + parentSession?: string; + setup?: (sessionManager: SessionManager) => Promise; + withSession?: (ctx: ReplacedSessionContext) => Promise; +}) => Promise<{ + cancelled: boolean; +}>; +export type ForkHandler = (entryId: string, options?: { + position?: "before" | "at"; + withSession?: (ctx: ReplacedSessionContext) => Promise; +}) => Promise<{ + cancelled: boolean; +}>; +export type NavigateTreeHandler = (targetId: string, options?: { + summarize?: boolean; + customInstructions?: string; + replaceInstructions?: boolean; + label?: string; +}) => Promise<{ + cancelled: boolean; +}>; +export type SwitchSessionHandler = (sessionPath: string, options?: { + withSession?: (ctx: ReplacedSessionContext) => Promise; +}) => Promise<{ + cancelled: boolean; +}>; +export type ReloadHandler = () => Promise; +export type ShutdownHandler = () => void; +/** + * Helper function to emit session_shutdown event to extensions. + * Returns true if the event was emitted, false if there were no handlers. + */ +export declare function emitSessionShutdownEvent(extensionRunner: ExtensionRunner, event: SessionShutdownEvent): Promise; +export declare function emitProjectTrustEvent(extensionsResult: LoadExtensionsResult, event: ProjectTrustEvent, ctx: ProjectTrustContext): Promise<{ + result?: ProjectTrustEventResult; + errors: ExtensionError[]; +}>; +export declare class ExtensionRunner { + private extensions; + private runtime; + private uiContext; + private mode; + private cwd; + private sessionManager; + private modelRegistry; + private errorListeners; + private getModel; + private getScopedModels; + private isIdleFn; + private isProjectTrustedFn; + private getSignalFn; + private waitForIdleFn; + private abortFn; + private hasPendingMessagesFn; + private getContextUsageFn; + private compactFn; + private getSystemPromptFn; + private getSystemPromptOptionsFn; + private newSessionHandler; + private forkHandler; + private navigateTreeHandler; + private switchSessionHandler; + private reloadHandler; + private shutdownHandler; + private shortcutDiagnostics; + private commandDiagnostics; + private staleMessage; + constructor(extensions: Extension[], runtime: ExtensionRuntime, cwd: string, sessionManager: SessionManager, modelRegistry: ModelRegistry); + bindCore(actions: ExtensionActions, contextActions: ExtensionContextActions, providerActions?: { + registerProvider?: (name: string, config: ProviderConfig) => void; + registerNativeProvider?: (provider: Provider) => void; + unregisterProvider?: (name: string) => void; + }): void; + bindCommandContext(actions?: ExtensionCommandContextActions): void; + setUIContext(uiContext?: ExtensionUIContext, mode?: ExtensionMode): void; + getUIContext(): ExtensionUIContext; + hasUI(): boolean; + getExtensionPaths(): string[]; + /** Get all registered tools from all extensions (first registration per name wins). */ + getAllRegisteredTools(): RegisteredTool[]; + /** Get a tool definition by name. Returns undefined if not found. */ + getToolDefinition(toolName: string): RegisteredTool["definition"] | undefined; + getFlags(): Map; + setFlagValue(name: string, value: boolean | string): void; + getFlagValues(): Map; + getShortcuts(resolvedKeybindings: KeybindingsConfig): Map; + getShortcutDiagnostics(): ResourceDiagnostic[]; + invalidate(message?: string): void; + private assertActive; + onError(listener: ExtensionErrorListener): () => void; + emitError(error: ExtensionError): void; + hasHandlers(eventType: string): boolean; + getMessageRenderer(customType: string): MessageRenderer | undefined; + getEntryRenderer(customType: string): EntryRenderer | undefined; + private resolveRegisteredCommands; + getModelRegistry(): ModelRegistry; + getRegisteredCommands(): ResolvedCommand[]; + getCommandDiagnostics(): ResourceDiagnostic[]; + getCommand(name: string): ResolvedCommand | undefined; + /** + * Request a graceful shutdown. Called by extension tools and event handlers. + * The actual shutdown behavior is provided by the mode via bindExtensions(). + */ + shutdown(): void; + getActiveTools(): string[]; + /** + * Create an ExtensionContext for use in event handlers and tool execution. + * Context values are resolved at call time, so changes via bindCore/bindUI are reflected. + */ + createContext(): ExtensionContext; + createCommandContext(): ExtensionCommandContext; + private isSessionBeforeEvent; + emit(event: TEvent): Promise>; + emitMessageEnd(event: MessageEndEvent): Promise; + emitToolResult(event: ToolResultEvent): Promise; + emitToolCall(event: ToolCallEvent): Promise; + emitUserBash(event: UserBashEvent): Promise; + emitContext(messages: AgentMessage[]): Promise; + emitBeforeProviderRequest(payload: unknown): Promise; + emitBeforeProviderHeaders(headers: ProviderHeaders): Promise; + emitBeforeAgentStart(prompt: string, images: ImageContent[] | undefined, systemPrompt: string, systemPromptOptions: BuildSystemPromptOptions): Promise; + emitResourcesDiscover(cwd: string, reason: ResourcesDiscoverEvent["reason"]): Promise<{ + skillPaths: Array<{ + path: string; + extensionPath: string; + }>; + promptPaths: Array<{ + path: string; + extensionPath: string; + }>; + themePaths: Array<{ + path: string; + extensionPath: string; + }>; + }>; + /** Emit input event. Transforms chain, "handled" short-circuits. */ + emitInput(text: string, images: ImageContent[] | undefined, source: InputSource, streamingBehavior?: "steer" | "followUp"): Promise; +} +export {}; +//# sourceMappingURL=runner.d.ts.map \ No newline at end of file diff --git a/dist/core/extensions/runner.d.ts.map b/dist/core/extensions/runner.d.ts.map new file mode 100644 index 0000000..fe9605b --- /dev/null +++ b/dist/core/extensions/runner.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAS,QAAQ,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC5F,OAAO,KAAK,EAAE,KAAK,EA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AC,GACtC,OAAO,CAAC;QACV,UAAU,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,aAAa,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;QAC3D,WAAW,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,aAAa,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;QAC5D,UAAU,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,aAAa,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;KAC3D,CAAC,CAuCD;IAED,oEAAoE;IAC9D,SAAS,CACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,YAAY,EAAE,GAAG,SAAS,EAClC,MAAM,EAAE,WAAW,EACnB,iBAAiB,CAAC,EAAE,OAAO,GAAG,UAAU,GACtC,OAAO,CAAC,gBAAgB,CAAC,CAkC3B;CACD","sourcesContent":["/**\n * Extension runner - executes extensions and manages their lifecycle.\n */\n\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, Model, Provider, ProviderHeaders } from \"@earendil-works/pi-ai\";\nimport type { KeyId } from \"@earendil-works/pi-tui\";\nimport { type Theme, theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ResourceDiagnostic } from \"../diagnostics.ts\";\nimport type { KeybindingsConfig } from \"../keybindings.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type { ScopedModel } from \"../model-resolver.ts\";\nimport type { SessionManager } from \"../session-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tBeforeProviderHeadersEvent,\n\tBeforeProviderRequestEvent,\n\tCompactOptions,\n\tContextEvent,\n\tContextEventResult,\n\tContextUsage,\n\tEntryRenderer,\n\tExtension,\n\tExtensionActions,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFlag,\n\tExtensionMode,\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tLoadExtensionsResult,\n\tMessageEndEvent,\n\tMessageEndEventResult,\n\tMessageRenderer,\n\tProjectTrustContext,\n\tProjectTrustEvent,\n\tProjectTrustEventResult,\n\tProviderConfig,\n\tRegisteredCommand,\n\tRegisteredTool,\n\tReplacedSessionContext,\n\tResolvedCommand,\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tSessionShutdownEvent,\n\tToolCallEvent,\n\tToolCallEventResult,\n\tToolResultEvent,\n\tToolResultEventResult,\n\tUserBashEvent,\n\tUserBashEventResult,\n} from \"./types.ts\";\n\n// Extension shortcuts compete with canonical keybinding ids from keybindings.json.\n// Only editor-global shortcuts are reserved here. Picker-specific bindings are not.\nconst RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS = [\n\t\"app.interrupt\",\n\t\"app.clear\",\n\t\"app.exit\",\n\t\"app.suspend\",\n\t\"app.thinking.cycle\",\n\t\"app.model.cycleForward\",\n\t\"app.model.cycleBackward\",\n\t\"app.model.select\",\n\t\"app.tools.expand\",\n\t\"app.thinking.toggle\",\n\t\"app.editor.external\",\n\t\"app.message.copy\",\n\t\"app.message.followUp\",\n\t\"tui.input.submit\",\n\t\"tui.select.confirm\",\n\t\"tui.select.cancel\",\n\t\"tui.input.copy\",\n\t\"tui.editor.deleteToLineEnd\",\n] as const;\n\ntype BuiltInKeyBindings = Partial>;\n\nconst buildBuiltinKeybindings = (resolvedKeybindings: KeybindingsConfig): BuiltInKeyBindings => {\n\tconst builtinKeybindings = {} as BuiltInKeyBindings;\n\tfor (const [keybinding, keys] of Object.entries(resolvedKeybindings)) {\n\t\tif (keys === undefined) continue;\n\t\tconst keyList = Array.isArray(keys) ? keys : [keys];\n\t\tconst restrictOverride = (RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS as readonly string[]).includes(keybinding);\n\t\tfor (const key of keyList) {\n\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\t\t\t// If multiple actions bind the same key, the reserved action wins so extensions\n\t\t\t// remain blocked by reserved shortcuts regardless of iteration order.\n\t\t\tconst existing = builtinKeybindings[normalizedKey];\n\t\t\tif (existing?.restrictOverride && !restrictOverride) continue;\n\t\t\tbuiltinKeybindings[normalizedKey] = {\n\t\t\t\tkeybinding,\n\t\t\t\trestrictOverride,\n\t\t\t};\n\t\t}\n\t}\n\treturn builtinKeybindings;\n};\n\n/** Combined result from all before_agent_start handlers */\ninterface BeforeAgentStartCombinedResult {\n\tmessages?: NonNullable[];\n\tsystemPrompt?: string;\n}\n\n/**\n * Events handled by the generic emit() method.\n * Events with dedicated emitXxx() methods are excluded for stronger type safety.\n */\ntype RunnerEmitEvent = Exclude<\n\tExtensionEvent,\n\t| ToolCallEvent\n\t| ProjectTrustEvent\n\t| ToolResultEvent\n\t| UserBashEvent\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeProviderHeadersEvent\n\t| BeforeAgentStartEvent\n\t| MessageEndEvent\n\t| ResourcesDiscoverEvent\n\t| InputEvent\n>;\n\ntype SessionBeforeEvent = Extract<\n\tRunnerEmitEvent,\n\t{ type: \"session_before_switch\" | \"session_before_fork\" | \"session_before_compact\" | \"session_before_tree\" }\n>;\n\ntype SessionBeforeEventResult =\n\t| SessionBeforeSwitchResult\n\t| SessionBeforeForkResult\n\t| SessionBeforeCompactResult\n\t| SessionBeforeTreeResult;\n\ntype RunnerEmitResult = TEvent extends { type: \"session_before_switch\" }\n\t? SessionBeforeSwitchResult | undefined\n\t: TEvent extends { type: \"session_before_fork\" }\n\t\t? SessionBeforeForkResult | undefined\n\t\t: TEvent extends { type: \"session_before_compact\" }\n\t\t\t? SessionBeforeCompactResult | undefined\n\t\t\t: TEvent extends { type: \"session_before_tree\" }\n\t\t\t\t? SessionBeforeTreeResult | undefined\n\t\t\t\t: undefined;\n\nexport type ExtensionErrorListener = (error: ExtensionError) => void;\n\nexport type NewSessionHandler = (options?: {\n\tparentSession?: string;\n\tsetup?: (sessionManager: SessionManager) => Promise;\n\twithSession?: (ctx: ReplacedSessionContext) => Promise;\n}) => Promise<{ cancelled: boolean }>;\n\nexport type ForkHandler = (\n\tentryId: string,\n\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise },\n) => Promise<{ cancelled: boolean }>;\n\nexport type NavigateTreeHandler = (\n\ttargetId: string,\n\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n) => Promise<{ cancelled: boolean }>;\n\nexport type SwitchSessionHandler = (\n\tsessionPath: string,\n\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise },\n) => Promise<{ cancelled: boolean }>;\n\nexport type ReloadHandler = () => Promise;\n\nexport type ShutdownHandler = () => void;\n\n/**\n * Helper function to emit session_shutdown event to extensions.\n * Returns true if the event was emitted, false if there were no handlers.\n */\nexport async function emitSessionShutdownEvent(\n\textensionRunner: ExtensionRunner,\n\tevent: SessionShutdownEvent,\n): Promise {\n\tif (extensionRunner.hasHandlers(\"session_shutdown\")) {\n\t\tawait extensionRunner.emit(event);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport async function emitProjectTrustEvent(\n\textensionsResult: LoadExtensionsResult,\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n): Promise<{ result?: ProjectTrustEventResult; errors: ExtensionError[] }> {\n\tconst errors: ExtensionError[] = [];\n\tfor (const ext of extensionsResult.extensions) {\n\t\t// A single extension may register multiple handlers for the same event.\n\t\t// The first project_trust handler that returns yes/no wins; undecided falls through.\n\t\tconst handlers = ext.handlers.get(\"project_trust\");\n\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\tfor (const handler of handlers) {\n\t\t\ttry {\n\t\t\t\tconst handlerResult = (await handler(event, ctx)) as ProjectTrustEventResult;\n\t\t\t\tif (handlerResult.trusted === \"undecided\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn { result: handlerResult, errors };\n\t\t\t} catch (error) {\n\t\t\t\terrors.push({\n\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\tevent: event.type,\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\tstack: error instanceof Error ? error.stack : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\treturn { errors };\n}\n\nconst noOpUIContext: ExtensionUIContext = {\n\tselect: async () => undefined,\n\tconfirm: async () => false,\n\tinput: async () => undefined,\n\tnotify: () => {},\n\tonTerminalInput: () => () => {},\n\tsetStatus: () => {},\n\tsetWorkingMessage: () => {},\n\tsetWorkingVisible: () => {},\n\tsetWorkingIndicator: () => {},\n\tsetHiddenThinkingLabel: () => {},\n\tsetWidget: () => {},\n\tsetFooter: () => {},\n\tsetHeader: () => {},\n\tsetTitle: () => {},\n\tcustom: async () => undefined as never,\n\tpasteToEditor: () => {},\n\tsetEditorText: () => {},\n\tgetEditorText: () => \"\",\n\teditor: async () => undefined,\n\taddAutocompleteProvider: () => {},\n\tsetEditorComponent: () => {},\n\tgetEditorComponent: () => undefined,\n\tget theme() {\n\t\treturn theme;\n\t},\n\tgetAllThemes: () => [],\n\tgetTheme: () => undefined,\n\tsetTheme: (_theme: string | Theme) => ({ success: false, error: \"UI not available\" }),\n\tgetToolsExpanded: () => false,\n\tsetToolsExpanded: () => {},\n};\n\nexport class ExtensionRunner {\n\tprivate extensions: Extension[];\n\tprivate runtime: ExtensionRuntime;\n\tprivate uiContext: ExtensionUIContext;\n\tprivate mode: ExtensionMode = \"print\";\n\tprivate cwd: string;\n\tprivate sessionManager: SessionManager;\n\tprivate modelRegistry: ModelRegistry;\n\tprivate errorListeners: Set = new Set();\n\tprivate getModel: () => Model | undefined = () => undefined;\n\tprivate getScopedModels: () => readonly ScopedModel[] = () => [];\n\tprivate isIdleFn: () => boolean = () => true;\n\tprivate isProjectTrustedFn: () => boolean = () => true;\n\tprivate getSignalFn: () => AbortSignal | undefined = () => undefined;\n\tprivate waitForIdleFn: () => Promise = async () => {};\n\tprivate abortFn: () => void = () => {};\n\tprivate hasPendingMessagesFn: () => boolean = () => false;\n\tprivate getContextUsageFn: () => ContextUsage | undefined = () => undefined;\n\tprivate compactFn: (options?: CompactOptions) => void = () => {};\n\tprivate getSystemPromptFn: () => string = () => \"\";\n\tprivate getSystemPromptOptionsFn: () => BuildSystemPromptOptions = () => ({ cwd: this.cwd });\n\tprivate newSessionHandler: NewSessionHandler = async () => ({ cancelled: false });\n\tprivate forkHandler: ForkHandler = async () => ({ cancelled: false });\n\tprivate navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false });\n\tprivate switchSessionHandler: SwitchSessionHandler = async () => ({ cancelled: false });\n\tprivate reloadHandler: ReloadHandler = async () => {};\n\tprivate shutdownHandler: ShutdownHandler = () => {};\n\tprivate shortcutDiagnostics: ResourceDiagnostic[] = [];\n\tprivate commandDiagnostics: ResourceDiagnostic[] = [];\n\tprivate staleMessage: string | undefined;\n\n\tconstructor(\n\t\textensions: Extension[],\n\t\truntime: ExtensionRuntime,\n\t\tcwd: string,\n\t\tsessionManager: SessionManager,\n\t\tmodelRegistry: ModelRegistry,\n\t) {\n\t\tthis.extensions = extensions;\n\t\tthis.runtime = runtime;\n\t\tthis.uiContext = noOpUIContext;\n\t\tthis.cwd = cwd;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.modelRegistry = modelRegistry;\n\t}\n\n\tbindCore(\n\t\tactions: ExtensionActions,\n\t\tcontextActions: ExtensionContextActions,\n\t\tproviderActions?: {\n\t\t\tregisterProvider?: (name: string, config: ProviderConfig) => void;\n\t\t\tregisterNativeProvider?: (provider: Provider) => void;\n\t\t\tunregisterProvider?: (name: string) => void;\n\t\t},\n\t): void {\n\t\t// Copy actions into the shared runtime (all extension APIs reference this)\n\t\tthis.runtime.sendMessage = actions.sendMessage;\n\t\tthis.runtime.sendUserMessage = actions.sendUserMessage;\n\t\tthis.runtime.appendEntry = actions.appendEntry;\n\t\tthis.runtime.setSessionName = actions.setSessionName;\n\t\tthis.runtime.getSessionName = actions.getSessionName;\n\t\tthis.runtime.setLabel = actions.setLabel;\n\t\tthis.runtime.getActiveTools = actions.getActiveTools;\n\t\tthis.runtime.getAllTools = actions.getAllTools;\n\t\tthis.runtime.setActiveTools = actions.setActiveTools;\n\t\tthis.runtime.refreshTools = actions.refreshTools;\n\t\tthis.runtime.getCommands = actions.getCommands;\n\t\tthis.runtime.setModel = actions.setModel;\n\t\tthis.runtime.getThinkingLevel = actions.getThinkingLevel;\n\t\tthis.runtime.setThinkingLevel = actions.setThinkingLevel;\n\n\t\t// Context actions (required)\n\t\tthis.getModel = contextActions.getModel;\n\t\tthis.getScopedModels = contextActions.getScopedModels;\n\t\tthis.isIdleFn = contextActions.isIdle;\n\t\tthis.isProjectTrustedFn = contextActions.isProjectTrusted;\n\t\tthis.getSignalFn = contextActions.getSignal;\n\t\tthis.abortFn = contextActions.abort;\n\t\tthis.hasPendingMessagesFn = contextActions.hasPendingMessages;\n\t\tthis.shutdownHandler = contextActions.shutdown;\n\t\tthis.getContextUsageFn = contextActions.getContextUsage;\n\t\tthis.compactFn = contextActions.compact;\n\t\tthis.getSystemPromptFn = contextActions.getSystemPrompt;\n\t\tthis.getSystemPromptOptionsFn = contextActions.getSystemPromptOptions ?? (() => ({ cwd: this.cwd }));\n\n\t\t// Flush provider registrations queued during extension loading\n\t\tfor (const { name, config, extensionPath } of this.runtime.pendingProviderRegistrations) {\n\t\t\ttry {\n\t\t\t\tif (providerActions?.registerProvider) {\n\t\t\t\t\tproviderActions.registerProvider(name, config);\n\t\t\t\t} else {\n\t\t\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis.emitError({\n\t\t\t\t\textensionPath,\n\t\t\t\t\tevent: \"register_provider\",\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis.runtime.pendingProviderRegistrations = [];\n\t\tfor (const { provider, extensionPath } of this.runtime.pendingNativeProviderRegistrations) {\n\t\t\ttry {\n\t\t\t\tif (providerActions?.registerNativeProvider) {\n\t\t\t\t\tproviderActions.registerNativeProvider(provider);\n\t\t\t\t} else {\n\t\t\t\t\tthis.modelRegistry.registerProvider(provider);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis.emitError({\n\t\t\t\t\textensionPath,\n\t\t\t\t\tevent: \"register_provider\",\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis.runtime.pendingNativeProviderRegistrations = [];\n\n\t\t// From this point on, provider registration/unregistration takes effect immediately\n\t\t// without requiring a /reload.\n\t\tthis.runtime.registerProvider = (name, config) => {\n\t\t\tif (providerActions?.registerProvider) {\n\t\t\t\tproviderActions.registerProvider(name, config);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t};\n\t\tthis.runtime.registerNativeProvider = (provider) => {\n\t\t\tif (providerActions?.registerNativeProvider) {\n\t\t\t\tproviderActions.registerNativeProvider(provider);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.modelRegistry.registerProvider(provider);\n\t\t};\n\t\tthis.runtime.unregisterProvider = (name) => {\n\t\t\tif (providerActions?.unregisterProvider) {\n\t\t\t\tproviderActions.unregisterProvider(name);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.modelRegistry.unregisterProvider(name);\n\t\t};\n\t}\n\n\tbindCommandContext(actions?: ExtensionCommandContextActions): void {\n\t\tif (actions) {\n\t\t\tthis.waitForIdleFn = actions.waitForIdle;\n\t\t\tthis.newSessionHandler = actions.newSession;\n\t\t\tthis.forkHandler = actions.fork;\n\t\t\tthis.navigateTreeHandler = actions.navigateTree;\n\t\t\tthis.switchSessionHandler = actions.switchSession;\n\t\t\tthis.reloadHandler = actions.reload;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.waitForIdleFn = async () => {};\n\t\tthis.newSessionHandler = async () => ({ cancelled: false });\n\t\tthis.forkHandler = async () => ({ cancelled: false });\n\t\tthis.navigateTreeHandler = async () => ({ cancelled: false });\n\t\tthis.switchSessionHandler = async () => ({ cancelled: false });\n\t\tthis.reloadHandler = async () => {};\n\t}\n\n\tsetUIContext(uiContext?: ExtensionUIContext, mode: ExtensionMode = \"print\"): void {\n\t\tthis.uiContext = uiContext ?? noOpUIContext;\n\t\tthis.mode = mode;\n\t}\n\n\tgetUIContext(): ExtensionUIContext {\n\t\treturn this.uiContext;\n\t}\n\n\thasUI(): boolean {\n\t\treturn this.uiContext !== noOpUIContext;\n\t}\n\n\tgetExtensionPaths(): string[] {\n\t\treturn this.extensions.map((e) => e.path);\n\t}\n\n\t/** Get all registered tools from all extensions (first registration per name wins). */\n\tgetAllRegisteredTools(): RegisteredTool[] {\n\t\tconst toolsByName = new Map();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const tool of ext.tools.values()) {\n\t\t\t\tif (!toolsByName.has(tool.definition.name)) {\n\t\t\t\t\ttoolsByName.set(tool.definition.name, tool);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn Array.from(toolsByName.values());\n\t}\n\n\t/** Get a tool definition by name. Returns undefined if not found. */\n\tgetToolDefinition(toolName: string): RegisteredTool[\"definition\"] | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst tool = ext.tools.get(toolName);\n\t\t\tif (tool) {\n\t\t\t\treturn tool.definition;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tgetFlags(): Map {\n\t\tconst allFlags = new Map();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [name, flag] of ext.flags) {\n\t\t\t\tif (!allFlags.has(name)) {\n\t\t\t\t\tallFlags.set(name, flag);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn allFlags;\n\t}\n\n\tsetFlagValue(name: string, value: boolean | string): void {\n\t\tthis.runtime.flagValues.set(name, value);\n\t}\n\n\tgetFlagValues(): Map {\n\t\treturn new Map(this.runtime.flagValues);\n\t}\n\n\tgetShortcuts(resolvedKeybindings: KeybindingsConfig): Map {\n\t\tthis.shortcutDiagnostics = [];\n\t\tconst builtinKeybindings = buildBuiltinKeybindings(resolvedKeybindings);\n\t\tconst extensionShortcuts = new Map();\n\n\t\tconst addDiagnostic = (message: string, extensionPath: string) => {\n\t\t\tthis.shortcutDiagnostics.push({ type: \"warning\", message, path: extensionPath });\n\t\t\tif (!this.hasUI()) {\n\t\t\t\tconsole.warn(message);\n\t\t\t}\n\t\t};\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [key, shortcut] of ext.shortcuts) {\n\t\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\n\t\t\t\tconst builtInKeybinding = builtinKeybindings[normalizedKey];\n\t\t\t\tif (builtInKeybinding?.restrictOverride === true) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut '${key}' from ${shortcut.extensionPath} conflicts with built-in shortcut. Skipping.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (builtInKeybinding?.restrictOverride === false) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' is built-in shortcut for ${builtInKeybinding.keybinding} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst existingExtensionShortcut = extensionShortcuts.get(normalizedKey);\n\t\t\t\tif (existingExtensionShortcut) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' registered by both ${existingExtensionShortcut.extensionPath} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\textensionShortcuts.set(normalizedKey, shortcut);\n\t\t\t}\n\t\t}\n\t\treturn extensionShortcuts;\n\t}\n\n\tgetShortcutDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.shortcutDiagnostics;\n\t}\n\n\tinvalidate(\n\t\tmessage = \"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\",\n\t): void {\n\t\tif (!this.staleMessage) {\n\t\t\tthis.staleMessage = message;\n\t\t\tthis.runtime.invalidate(message);\n\t\t}\n\t}\n\n\tprivate assertActive(): void {\n\t\tif (this.staleMessage) {\n\t\t\tthrow new Error(this.staleMessage);\n\t\t}\n\t}\n\n\tonError(listener: ExtensionErrorListener): () => void {\n\t\tthis.errorListeners.add(listener);\n\t\treturn () => this.errorListeners.delete(listener);\n\t}\n\n\temitError(error: ExtensionError): void {\n\t\tfor (const listener of this.errorListeners) {\n\t\t\tlistener(error);\n\t\t}\n\t}\n\n\thasHandlers(eventType: string): boolean {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(eventType);\n\t\t\tif (handlers && handlers.length > 0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tgetMessageRenderer(customType: string): MessageRenderer | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst renderer = ext.messageRenderers.get(customType);\n\t\t\tif (renderer) {\n\t\t\t\treturn renderer;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tgetEntryRenderer(customType: string): EntryRenderer | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst renderer = ext.entryRenderers?.get(customType);\n\t\t\tif (renderer) {\n\t\t\t\treturn renderer;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate resolveRegisteredCommands(): ResolvedCommand[] {\n\t\tconst commands: RegisteredCommand[] = [];\n\t\tconst counts = new Map();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const command of ext.commands.values()) {\n\t\t\t\tcommands.push(command);\n\t\t\t\tcounts.set(command.name, (counts.get(command.name) ?? 0) + 1);\n\t\t\t}\n\t\t}\n\n\t\tconst seen = new Map();\n\t\tconst takenInvocationNames = new Set();\n\n\t\treturn commands.map((command) => {\n\t\t\tconst occurrence = (seen.get(command.name) ?? 0) + 1;\n\t\t\tseen.set(command.name, occurrence);\n\n\t\t\tlet invocationName = (counts.get(command.name) ?? 0) > 1 ? `${command.name}:${occurrence}` : command.name;\n\n\t\t\tif (takenInvocationNames.has(invocationName)) {\n\t\t\t\tlet suffix = occurrence;\n\t\t\t\tdo {\n\t\t\t\t\tsuffix++;\n\t\t\t\t\tinvocationName = `${command.name}:${suffix}`;\n\t\t\t\t} while (takenInvocationNames.has(invocationName));\n\t\t\t}\n\n\t\t\ttakenInvocationNames.add(invocationName);\n\t\t\treturn {\n\t\t\t\t...command,\n\t\t\t\tinvocationName,\n\t\t\t};\n\t\t});\n\t}\n\n\tgetModelRegistry(): ModelRegistry {\n\t\treturn this.modelRegistry;\n\t}\n\n\tgetRegisteredCommands(): ResolvedCommand[] {\n\t\tthis.commandDiagnostics = [];\n\t\treturn this.resolveRegisteredCommands();\n\t}\n\n\tgetCommandDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.commandDiagnostics;\n\t}\n\n\tgetCommand(name: string): ResolvedCommand | undefined {\n\t\treturn this.resolveRegisteredCommands().find((command) => command.invocationName === name);\n\t}\n\n\t/**\n\t * Request a graceful shutdown. Called by extension tools and event handlers.\n\t * The actual shutdown behavior is provided by the mode via bindExtensions().\n\t */\n\tshutdown(): void {\n\t\tthis.shutdownHandler();\n\t}\n\n\tgetActiveTools(): string[] {\n\t\tthis.assertActive();\n\t\treturn this.runtime.getActiveTools();\n\t}\n\n\t/**\n\t * Create an ExtensionContext for use in event handlers and tool execution.\n\t * Context values are resolved at call time, so changes via bindCore/bindUI are reflected.\n\t */\n\tcreateContext(): ExtensionContext {\n\t\tconst runner = this;\n\t\tconst getModel = this.getModel;\n\t\tconst getScopedModels = this.getScopedModels;\n\t\treturn {\n\t\t\tget ui() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.uiContext;\n\t\t\t},\n\t\t\tget mode() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.mode;\n\t\t\t},\n\t\t\tget hasUI() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.hasUI();\n\t\t\t},\n\t\t\tget cwd() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.cwd;\n\t\t\t},\n\t\t\tget sessionManager() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.sessionManager;\n\t\t\t},\n\t\t\tget modelRegistry() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.modelRegistry;\n\t\t\t},\n\t\t\tget model() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn getModel();\n\t\t\t},\n\t\t\tget scopedModels() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn getScopedModels();\n\t\t\t},\n\t\t\tget thinkingLevel() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.runtime.getThinkingLevel();\n\t\t\t},\n\t\t\tisIdle: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.isIdleFn();\n\t\t\t},\n\t\t\tisProjectTrusted: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.isProjectTrustedFn();\n\t\t\t},\n\t\t\tget signal() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getSignalFn();\n\t\t\t},\n\t\t\tabort: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.abortFn();\n\t\t\t},\n\t\t\thasPendingMessages: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.hasPendingMessagesFn();\n\t\t\t},\n\t\t\tshutdown: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.shutdownHandler();\n\t\t\t},\n\t\t\tgetContextUsage: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getContextUsageFn();\n\t\t\t},\n\t\t\tcompact: (options) => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.compactFn(options);\n\t\t\t},\n\t\t\tgetSystemPrompt: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getSystemPromptFn();\n\t\t\t},\n\t\t};\n\t}\n\n\tcreateCommandContext(): ExtensionCommandContext {\n\t\t// Use property descriptors instead of object spread so the guarded getters from\n\t\t// createContext() stay lazy. A spread would eagerly read them once and freeze the\n\t\t// old values into the returned object, bypassing stale-instance checks.\n\t\tconst context = Object.defineProperties(\n\t\t\t{},\n\t\t\tObject.getOwnPropertyDescriptors(this.createContext()),\n\t\t) as ExtensionCommandContext;\n\t\tcontext.getSystemPromptOptions = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.getSystemPromptOptionsFn();\n\t\t};\n\t\tcontext.waitForIdle = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.waitForIdleFn();\n\t\t};\n\t\tcontext.newSession = (options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.newSessionHandler(options);\n\t\t};\n\t\tcontext.fork = (entryId, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.forkHandler(entryId, options);\n\t\t};\n\t\tcontext.navigateTree = (targetId, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.navigateTreeHandler(targetId, options);\n\t\t};\n\t\tcontext.switchSession = (sessionPath, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.switchSessionHandler(sessionPath, options);\n\t\t};\n\t\tcontext.reload = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.reloadHandler();\n\t\t};\n\t\treturn context;\n\t}\n\n\tprivate isSessionBeforeEvent(event: RunnerEmitEvent): event is SessionBeforeEvent {\n\t\treturn (\n\t\t\tevent.type === \"session_before_switch\" ||\n\t\t\tevent.type === \"session_before_fork\" ||\n\t\t\tevent.type === \"session_before_compact\" ||\n\t\t\tevent.type === \"session_before_tree\"\n\t\t);\n\t}\n\n\tasync emit(event: TEvent): Promise> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: SessionBeforeEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(event.type);\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (this.isSessionBeforeEvent(event) && handlerResult) {\n\t\t\t\t\t\tresult = handlerResult as SessionBeforeEventResult;\n\t\t\t\t\t\tif (result.cancel) {\n\t\t\t\t\t\t\treturn result as RunnerEmitResult;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: event.type,\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result as RunnerEmitResult;\n\t}\n\n\tasync emitMessageEnd(event: MessageEndEvent): Promise {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessage = event.message;\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"message_end\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst currentEvent: MessageEndEvent = { ...event, message: currentMessage };\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as MessageEndEventResult | undefined;\n\t\t\t\t\tif (!handlerResult?.message) continue;\n\n\t\t\t\t\tif (handlerResult.message.role !== currentMessage.role) {\n\t\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\t\tevent: \"message_end\",\n\t\t\t\t\t\t\terror: \"message_end handlers must return a message with the same role\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentMessage = handlerResult.message;\n\t\t\t\t\tmodified = true;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"message_end\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn modified ? currentMessage : undefined;\n\t}\n\n\tasync emitToolResult(event: ToolResultEvent): Promise {\n\t\tconst ctx = this.createContext();\n\t\tconst currentEvent: ToolResultEvent = { ...event };\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_result\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as ToolResultEventResult | undefined;\n\t\t\t\t\tif (!handlerResult) continue;\n\n\t\t\t\t\tif (handlerResult.content !== undefined) {\n\t\t\t\t\t\tcurrentEvent.content = handlerResult.content;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.details !== undefined) {\n\t\t\t\t\t\tcurrentEvent.details = handlerResult.details;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.isError !== undefined) {\n\t\t\t\t\t\tcurrentEvent.isError = handlerResult.isError;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.usage !== undefined) {\n\t\t\t\t\t\tcurrentEvent.usage = handlerResult.usage;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"tool_result\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!modified) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: currentEvent.content,\n\t\t\tdetails: currentEvent.details,\n\t\t\tisError: currentEvent.isError,\n\t\t\tusage: currentEvent.usage,\n\t\t};\n\t}\n\n\tasync emitToolCall(event: ToolCallEvent): Promise {\n\t\tconst ctx = this.createContext();\n\t\tlet result: ToolCallEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_call\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\tif (handlerResult) {\n\t\t\t\t\tresult = handlerResult as ToolCallEventResult;\n\t\t\t\t\tif (result.block) {\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tasync emitUserBash(event: UserBashEvent): Promise {\n\t\tconst ctx = this.createContext();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"user_bash\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\treturn handlerResult as UserBashEventResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"user_bash\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitContext(messages: AgentMessage[]): Promise {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessages = structuredClone(messages);\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"context\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ContextEvent = { type: \"context\", messages: currentMessages };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult && (handlerResult as ContextEventResult).messages) {\n\t\t\t\t\t\tcurrentMessages = (handlerResult as ContextEventResult).messages!;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"context\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentMessages;\n\t}\n\n\tasync emitBeforeProviderRequest(payload: unknown): Promise {\n\t\tconst ctx = this.createContext();\n\t\tlet currentPayload = payload;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_provider_request\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeProviderRequestEvent = {\n\t\t\t\t\t\ttype: \"before_provider_request\",\n\t\t\t\t\t\tpayload: currentPayload,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult !== undefined) {\n\t\t\t\t\t\tcurrentPayload = handlerResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_provider_request\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentPayload;\n\t}\n\n\tasync emitBeforeProviderHeaders(headers: ProviderHeaders): Promise {\n\t\tconst ctx = this.createContext();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_provider_headers\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\t// Handlers mutate `headers` in place; the return value is ignored.\n\t\t\t\t\tconst event: BeforeProviderHeadersEvent = {\n\t\t\t\t\t\ttype: \"before_provider_headers\",\n\t\t\t\t\t\theaders,\n\t\t\t\t\t};\n\t\t\t\t\tawait handler(event, ctx);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_provider_headers\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn headers;\n\t}\n\n\tasync emitBeforeAgentStart(\n\t\tprompt: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsystemPrompt: string,\n\t\tsystemPromptOptions: BuildSystemPromptOptions,\n\t): Promise {\n\t\tlet currentSystemPrompt = systemPrompt;\n\t\tconst ctx = Object.defineProperties(\n\t\t\t{},\n\t\t\tObject.getOwnPropertyDescriptors(this.createContext()),\n\t\t) as ExtensionContext;\n\t\tctx.getSystemPrompt = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn currentSystemPrompt;\n\t\t};\n\t\tconst messages: NonNullable[] = [];\n\t\tlet systemPromptModified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_agent_start\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeAgentStartEvent = {\n\t\t\t\t\t\ttype: \"before_agent_start\",\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\timages,\n\t\t\t\t\t\tsystemPrompt: currentSystemPrompt,\n\t\t\t\t\t\tsystemPromptOptions,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\tconst result = handlerResult as BeforeAgentStartEventResult;\n\t\t\t\t\t\tif (result.message) {\n\t\t\t\t\t\t\tmessages.push(result.message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.systemPrompt !== undefined) {\n\t\t\t\t\t\t\tcurrentSystemPrompt = result.systemPrompt;\n\t\t\t\t\t\t\tsystemPromptModified = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_agent_start\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (messages.length > 0 || systemPromptModified) {\n\t\t\treturn {\n\t\t\t\tmessages: messages.length > 0 ? messages : undefined,\n\t\t\t\tsystemPrompt: systemPromptModified ? currentSystemPrompt : undefined,\n\t\t\t};\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitResourcesDiscover(\n\t\tcwd: string,\n\t\treason: ResourcesDiscoverEvent[\"reason\"],\n\t): Promise<{\n\t\tskillPaths: Array<{ path: string; extensionPath: string }>;\n\t\tpromptPaths: Array<{ path: string; extensionPath: string }>;\n\t\tthemePaths: Array<{ path: string; extensionPath: string }>;\n\t}> {\n\t\tconst ctx = this.createContext();\n\t\tconst skillPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst promptPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst themePaths: Array<{ path: string; extensionPath: string }> = [];\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"resources_discover\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ResourcesDiscoverEvent = { type: \"resources_discover\", cwd, reason };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tconst result = handlerResult as ResourcesDiscoverResult | undefined;\n\n\t\t\t\t\tif (result?.skillPaths?.length) {\n\t\t\t\t\t\tskillPaths.push(...result.skillPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.promptPaths?.length) {\n\t\t\t\t\t\tpromptPaths.push(...result.promptPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.themePaths?.length) {\n\t\t\t\t\t\tthemePaths.push(...result.themePaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"resources_discover\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { skillPaths, promptPaths, themePaths };\n\t}\n\n\t/** Emit input event. Transforms chain, \"handled\" short-circuits. */\n\tasync emitInput(\n\t\ttext: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsource: InputSource,\n\t\tstreamingBehavior?: \"steer\" | \"followUp\",\n\t): Promise {\n\t\tconst ctx = this.createContext();\n\t\tlet currentText = text;\n\t\tlet currentImages = images;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const handler of ext.handlers.get(\"input\") ?? []) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: InputEvent = {\n\t\t\t\t\t\ttype: \"input\",\n\t\t\t\t\t\ttext: currentText,\n\t\t\t\t\t\timages: currentImages,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tstreamingBehavior,\n\t\t\t\t\t};\n\t\t\t\t\tconst result = (await handler(event, ctx)) as InputEventResult | undefined;\n\t\t\t\t\tif (result?.action === \"handled\") return result;\n\t\t\t\t\tif (result?.action === \"transform\") {\n\t\t\t\t\t\tcurrentText = result.text;\n\t\t\t\t\t\tcurrentImages = result.images ?? currentImages;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"input\",\n\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn currentText !== text || currentImages !== images\n\t\t\t? { action: \"transform\", text: currentText, images: currentImages }\n\t\t\t: { action: \"continue\" };\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/extensions/runner.js b/dist/core/extensions/runner.js new file mode 100644 index 0000000..265b2fa --- /dev/null +++ b/dist/core/extensions/runner.js @@ -0,0 +1,964 @@ +/** + * Extension runner - executes extensions and manages their lifecycle. + */ +import { theme } from "../../modes/interactive/theme/theme.js"; +// Extension shortcuts compete with canonical keybinding ids from keybindings.json. +// Only editor-global shortcuts are reserved here. Picker-specific bindings are not. +const RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS = [ + "app.interrupt", + "app.clear", + "app.exit", + "app.suspend", + "app.thinking.cycle", + "app.model.cycleForward", + "app.model.cycleBackward", + "app.model.select", + "app.tools.expand", + "app.thinking.toggle", + "app.editor.external", + "app.message.copy", + "app.message.followUp", + "tui.input.submit", + "tui.select.confirm", + "tui.select.cancel", + "tui.input.copy", + "tui.editor.deleteToLineEnd", +]; +const buildBuiltinKeybindings = (resolvedKeybindings) => { + const builtinKeybindings = {}; + for (const [keybinding, keys] of Object.entries(resolvedKeybindings)) { + if (keys === undefined) + continue; + const keyList = Array.isArray(keys) ? keys : [keys]; + const restrictOverride = RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS.includes(keybinding); + for (const key of keyList) { + const normalizedKey = key.toLowerCase(); + // If multiple actions bind the same key, the reserved action wins so extensions + // remain blocked by reserved shortcuts regardless of iteration order. + const existing = builtinKeybindings[normalizedKey]; + if (existing?.restrictOverride && !restrictOverride) + continue; + builtinKeybindings[normalizedKey] = { + keybinding, + restrictOverride, + }; + } + } + return builtinKeybindings; +}; +/** + * Helper function to emit session_shutdown event to extensions. + * Returns true if the event was emitted, false if there were no handlers. + */ +export async function emitSessionShutdownEvent(extensionRunner, event) { + if (extensionRunner.hasHandlers("session_shutdown")) { + await extensionRunner.emit(event); + return true; + } + return false; +} +export async function emitProjectTrustEvent(extensionsResult, event, ctx) { + const errors = []; + for (const ext of extensionsResult.extensions) { + // A single extension may register multiple handlers for the same event. + // The first project_trust handler that returns yes/no wins; undecided falls through. + const handlers = ext.handlers.get("project_trust"); + if (!handlers || handlers.length === 0) + continue; + for (const handler of handlers) { + try { + const handlerResult = (await handler(event, ctx)); + if (handlerResult.trusted === "undecided") { + continue; + } + return { result: handlerResult, errors }; + } + catch (error) { + errors.push({ + extensionPath: ext.path, + event: event.type, + error: error instanceof Error ? error.message : String(error), + stack: error instanceof Error ? error.stack : undefined, + }); + } + } + } + return { errors }; +} +const noOpUIContext = { + select: async () => undefined, + confirm: async () => false, + input: async () => undefined, + notify: () => { }, + onTerminalInput: () => () => { }, + setStatus: () => { }, + setWorkingMessage: () => { }, + setWorkingVisible: () => { }, + setWorkingIndicator: () => { }, + setHiddenThinkingLabel: () => { }, + setWidget: () => { }, + setFooter: () => { }, + setHeader: () => { }, + setTitle: () => { }, + custom: async () => undefined, + pasteToEditor: () => { }, + setEditorText: () => { }, + getEditorText: () => "", + editor: async () => undefined, + addAutocompleteProvider: () => { }, + setEditorComponent: () => { }, + getEditorComponent: () => undefined, + get theme() { + return theme; + }, + getAllThemes: () => [], + getTheme: () => undefined, + setTheme: (_theme) => ({ success: false, error: "UI not available" }), + getToolsExpanded: () => false, + setToolsExpanded: () => { }, +}; +export class ExtensionRunner { + extensions; + runtime; + uiContext; + mode = "print"; + cwd; + sessionManager; + modelRegistry; + errorListeners = new Set(); + getModel = () => undefined; + getScopedModels = () => []; + isIdleFn = () => true; + isProjectTrustedFn = () => true; + getSignalFn = () => undefined; + waitForIdleFn = async () => { }; + abortFn = () => { }; + hasPendingMessagesFn = () => false; + getContextUsageFn = () => undefined; + compactFn = () => { }; + getSystemPromptFn = () => ""; + getSystemPromptOptionsFn = () => ({ cwd: this.cwd }); + newSessionHandler = async () => ({ cancelled: false }); + forkHandler = async () => ({ cancelled: false }); + navigateTreeHandler = async () => ({ cancelled: false }); + switchSessionHandler = async () => ({ cancelled: false }); + reloadHandler = async () => { }; + shutdownHandler = () => { }; + shortcutDiagnostics = []; + commandDiagnostics = []; + staleMessage; + constructor(extensions, runtime, cwd, sessionManager, modelRegistry) { + this.extensions = extensions; + this.runtime = runtime; + this.uiContext = noOpUIContext; + this.cwd = cwd; + this.sessionManager = sessionManager; + this.modelRegistry = modelRegistry; + } + bindCore(actions, contextActions, providerActions) { + // Copy actions into the shared runtime (all extension APIs reference this) + this.runtime.sendMessage = actions.sendMessage; + this.runtime.sendUserMessage = actions.sendUserMessage; + this.runtime.appendEntry = actions.appendEntry; + this.runtime.setSessionName = actions.setSessionName; + this.runtime.getSessionName = actions.getSessionName; + this.runtime.setLabel = actions.setLabel; + this.runtime.getActiveTools = actions.getActiveTools; + this.runtime.getAllTools = actions.getAllTools; + this.runtime.setActiveTools = actions.setActiveTools; + this.runtime.refreshTools = actions.refreshTools; + this.runtime.getCommands = actions.getCommands; + this.runtime.setModel = actions.setModel; + this.runtime.getThinkingLevel = actions.getThinkingLevel; + this.runtime.setThinkingLevel = actions.setThinkingLevel; + // Context actions (required) + this.getModel = contextActions.getModel; + this.getScopedModels = contextActions.getScopedModels; + this.isIdleFn = contextActions.isIdle; + this.isProjectTrustedFn = contextActions.isProjectTrusted; + this.getSignalFn = contextActions.getSignal; + this.abortFn = contextActions.abort; + this.hasPendingMessagesFn = contextActions.hasPendingMessages; + this.shutdownHandler = contextActions.shutdown; + this.getContextUsageFn = contextActions.getContextUsage; + this.compactFn = contextActions.compact; + this.getSystemPromptFn = contextActions.getSystemPrompt; + this.getSystemPromptOptionsFn = contextActions.getSystemPromptOptions ?? (() => ({ cwd: this.cwd })); + // Flush provider registrations queued during extension loading + for (const { name, config, extensionPath } of this.runtime.pendingProviderRegistrations) { + try { + if (providerActions?.registerProvider) { + providerActions.registerProvider(name, config); + } + else { + this.modelRegistry.registerProvider(name, config); + } + } + catch (err) { + this.emitError({ + extensionPath, + event: "register_provider", + error: err instanceof Error ? err.message : String(err), + stack: err instanceof Error ? err.stack : undefined, + }); + } + } + this.runtime.pendingProviderRegistrations = []; + for (const { provider, extensionPath } of this.runtime.pendingNativeProviderRegistrations) { + try { + if (providerActions?.registerNativeProvider) { + providerActions.registerNativeProvider(provider); + } + else { + this.modelRegistry.registerProvider(provider); + } + } + catch (err) { + this.emitError({ + extensionPath, + event: "register_provider", + error: err instanceof Error ? err.message : String(err), + stack: err instanceof Error ? err.stack : undefined, + }); + } + } + this.runtime.pendingNativeProviderRegistrations = []; + // From this point on, provider registration/unregistration takes effect immediately + // without requiring a /reload. + this.runtime.registerProvider = (name, config) => { + if (providerActions?.registerProvider) { + providerActions.registerProvider(name, config); + return; + } + this.modelRegistry.registerProvider(name, config); + }; + this.runtime.registerNativeProvider = (provider) => { + if (providerActions?.registerNativeProvider) { + providerActions.registerNativeProvider(provider); + return; + } + this.modelRegistry.registerProvider(provider); + }; + this.runtime.unregisterProvider = (name) => { + if (providerActions?.unregisterProvider) { + providerActions.unregisterProvider(name); + return; + } + this.modelRegistry.unregisterProvider(name); + }; + } + bindCommandContext(actions) { + if (actions) { + this.waitForIdleFn = actions.waitForIdle; + this.newSessionHandler = actions.newSession; + this.forkHandler = actions.fork; + this.navigateTreeHandler = actions.navigateTree; + this.switchSessionHandler = actions.switchSession; + this.reloadHandler = actions.reload; + return; + } + this.waitForIdleFn = async () => { }; + this.newSessionHandler = async () => ({ cancelled: false }); + this.forkHandler = async () => ({ cancelled: false }); + this.navigateTreeHandler = async () => ({ cancelled: false }); + this.switchSessionHandler = async () => ({ cancelled: false }); + this.reloadHandler = async () => { }; + } + setUIContext(uiContext, mode = "print") { + this.uiContext = uiContext ?? noOpUIContext; + this.mode = mode; + } + getUIContext() { + return this.uiContext; + } + hasUI() { + return this.uiContext !== noOpUIContext; + } + getExtensionPaths() { + return this.extensions.map((e) => e.path); + } + /** Get all registered tools from all extensions (first registration per name wins). */ + getAllRegisteredTools() { + const toolsByName = new Map(); + for (const ext of this.extensions) { + for (const tool of ext.tools.values()) { + if (!toolsByName.has(tool.definition.name)) { + toolsByName.set(tool.definition.name, tool); + } + } + } + return Array.from(toolsByName.values()); + } + /** Get a tool definition by name. Returns undefined if not found. */ + getToolDefinition(toolName) { + for (const ext of this.extensions) { + const tool = ext.tools.get(toolName); + if (tool) { + return tool.definition; + } + } + return undefined; + } + getFlags() { + const allFlags = new Map(); + for (const ext of this.extensions) { + for (const [name, flag] of ext.flags) { + if (!allFlags.has(name)) { + allFlags.set(name, flag); + } + } + } + return allFlags; + } + setFlagValue(name, value) { + this.runtime.flagValues.set(name, value); + } + getFlagValues() { + return new Map(this.runtime.flagValues); + } + getShortcuts(resolvedKeybindings) { + this.shortcutDiagnostics = []; + const builtinKeybindings = buildBuiltinKeybindings(resolvedKeybindings); + const extensionShortcuts = new Map(); + const addDiagnostic = (message, extensionPath) => { + this.shortcutDiagnostics.push({ type: "warning", message, path: extensionPath }); + if (!this.hasUI()) { + console.warn(message); + } + }; + for (const ext of this.extensions) { + for (const [key, shortcut] of ext.shortcuts) { + const normalizedKey = key.toLowerCase(); + const builtInKeybinding = builtinKeybindings[normalizedKey]; + if (builtInKeybinding?.restrictOverride === true) { + addDiagnostic(`Extension shortcut '${key}' from ${shortcut.extensionPath} conflicts with built-in shortcut. Skipping.`, shortcut.extensionPath); + continue; + } + if (builtInKeybinding?.restrictOverride === false) { + addDiagnostic(`Extension shortcut conflict: '${key}' is built-in shortcut for ${builtInKeybinding.keybinding} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`, shortcut.extensionPath); + } + const existingExtensionShortcut = extensionShortcuts.get(normalizedKey); + if (existingExtensionShortcut) { + addDiagnostic(`Extension shortcut conflict: '${key}' registered by both ${existingExtensionShortcut.extensionPath} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`, shortcut.extensionPath); + } + extensionShortcuts.set(normalizedKey, shortcut); + } + } + return extensionShortcuts; + } + getShortcutDiagnostics() { + return this.shortcutDiagnostics; + } + invalidate(message = "This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().") { + if (!this.staleMessage) { + this.staleMessage = message; + this.runtime.invalidate(message); + } + } + assertActive() { + if (this.staleMessage) { + throw new Error(this.staleMessage); + } + } + onError(listener) { + this.errorListeners.add(listener); + return () => this.errorListeners.delete(listener); + } + emitError(error) { + for (const listener of this.errorListeners) { + listener(error); + } + } + hasHandlers(eventType) { + for (const ext of this.extensions) { + const handlers = ext.handlers.get(eventType); + if (handlers && handlers.length > 0) { + return true; + } + } + return false; + } + getMessageRenderer(customType) { + for (const ext of this.extensions) { + const renderer = ext.messageRenderers.get(customType); + if (renderer) { + return renderer; + } + } + return undefined; + } + getEntryRenderer(customType) { + for (const ext of this.extensions) { + const renderer = ext.entryRenderers?.get(customType); + if (renderer) { + return renderer; + } + } + return undefined; + } + resolveRegisteredCommands() { + const commands = []; + const counts = new Map(); + for (const ext of this.extensions) { + for (const command of ext.commands.values()) { + commands.push(command); + counts.set(command.name, (counts.get(command.name) ?? 0) + 1); + } + } + const seen = new Map(); + const takenInvocationNames = new Set(); + return commands.map((command) => { + const occurrence = (seen.get(command.name) ?? 0) + 1; + seen.set(command.name, occurrence); + let invocationName = (counts.get(command.name) ?? 0) > 1 ? `${command.name}:${occurrence}` : command.name; + if (takenInvocationNames.has(invocationName)) { + let suffix = occurrence; + do { + suffix++; + invocationName = `${command.name}:${suffix}`; + } while (takenInvocationNames.has(invocationName)); + } + takenInvocationNames.add(invocationName); + return { + ...command, + invocationName, + }; + }); + } + getModelRegistry() { + return this.modelRegistry; + } + getRegisteredCommands() { + this.commandDiagnostics = []; + return this.resolveRegisteredCommands(); + } + getCommandDiagnostics() { + return this.commandDiagnostics; + } + getCommand(name) { + return this.resolveRegisteredCommands().find((command) => command.invocationName === name); + } + /** + * Request a graceful shutdown. Called by extension tools and event handlers. + * The actual shutdown behavior is provided by the mode via bindExtensions(). + */ + shutdown() { + this.shutdownHandler(); + } + getActiveTools() { + this.assertActive(); + return this.runtime.getActiveTools(); + } + /** + * Create an ExtensionContext for use in event handlers and tool execution. + * Context values are resolved at call time, so changes via bindCore/bindUI are reflected. + */ + createContext() { + const runner = this; + const getModel = this.getModel; + const getScopedModels = this.getScopedModels; + return { + get ui() { + runner.assertActive(); + return runner.uiContext; + }, + get mode() { + runner.assertActive(); + return runner.mode; + }, + get hasUI() { + runner.assertActive(); + return runner.hasUI(); + }, + get cwd() { + runner.assertActive(); + return runner.cwd; + }, + get sessionManager() { + runner.assertActive(); + return runner.sessionManager; + }, + get modelRegistry() { + runner.assertActive(); + return runner.modelRegistry; + }, + get model() { + runner.assertActive(); + return getModel(); + }, + get scopedModels() { + runner.assertActive(); + return getScopedModels(); + }, + get thinkingLevel() { + runner.assertActive(); + return runner.runtime.getThinkingLevel(); + }, + isIdle: () => { + runner.assertActive(); + return runner.isIdleFn(); + }, + isProjectTrusted: () => { + runner.assertActive(); + return runner.isProjectTrustedFn(); + }, + get signal() { + runner.assertActive(); + return runner.getSignalFn(); + }, + abort: () => { + runner.assertActive(); + runner.abortFn(); + }, + hasPendingMessages: () => { + runner.assertActive(); + return runner.hasPendingMessagesFn(); + }, + shutdown: () => { + runner.assertActive(); + runner.shutdownHandler(); + }, + getContextUsage: () => { + runner.assertActive(); + return runner.getContextUsageFn(); + }, + compact: (options) => { + runner.assertActive(); + runner.compactFn(options); + }, + getSystemPrompt: () => { + runner.assertActive(); + return runner.getSystemPromptFn(); + }, + }; + } + createCommandContext() { + // Use property descriptors instead of object spread so the guarded getters from + // createContext() stay lazy. A spread would eagerly read them once and freeze the + // old values into the returned object, bypassing stale-instance checks. + const context = Object.defineProperties({}, Object.getOwnPropertyDescriptors(this.createContext())); + context.getSystemPromptOptions = () => { + this.assertActive(); + return this.getSystemPromptOptionsFn(); + }; + context.waitForIdle = () => { + this.assertActive(); + return this.waitForIdleFn(); + }; + context.newSession = (options) => { + this.assertActive(); + return this.newSessionHandler(options); + }; + context.fork = (entryId, options) => { + this.assertActive(); + return this.forkHandler(entryId, options); + }; + context.navigateTree = (targetId, options) => { + this.assertActive(); + return this.navigateTreeHandler(targetId, options); + }; + context.switchSession = (sessionPath, options) => { + this.assertActive(); + return this.switchSessionHandler(sessionPath, options); + }; + context.reload = () => { + this.assertActive(); + return this.reloadHandler(); + }; + return context; + } + isSessionBeforeEvent(event) { + return (event.type === "session_before_switch" || + event.type === "session_before_fork" || + event.type === "session_before_compact" || + event.type === "session_before_tree"); + } + async emit(event) { + const ctx = this.createContext(); + let result; + for (const ext of this.extensions) { + const handlers = ext.handlers.get(event.type); + if (!handlers || handlers.length === 0) + continue; + for (const handler of handlers) { + try { + const handlerResult = await handler(event, ctx); + if (this.isSessionBeforeEvent(event) && handlerResult) { + result = handlerResult; + if (result.cancel) { + return result; + } + } + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + const stack = err instanceof Error ? err.stack : undefined; + this.emitError({ + extensionPath: ext.path, + event: event.type, + error: message, + stack, + }); + } + } + } + return result; + } + async emitMessageEnd(event) { + const ctx = this.createContext(); + let currentMessage = event.message; + let modified = false; + for (const ext of this.extensions) { + const handlers = ext.handlers.get("message_end"); + if (!handlers || handlers.length === 0) + continue; + for (const handler of handlers) { + try { + const currentEvent = { ...event, message: currentMessage }; + const handlerResult = (await handler(currentEvent, ctx)); + if (!handlerResult?.message) + continue; + if (handlerResult.message.role !== currentMessage.role) { + this.emitError({ + extensionPath: ext.path, + event: "message_end", + error: "message_end handlers must return a message with the same role", + }); + continue; + } + currentMessage = handlerResult.message; + modified = true; + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + const stack = err instanceof Error ? err.stack : undefined; + this.emitError({ + extensionPath: ext.path, + event: "message_end", + error: message, + stack, + }); + } + } + } + return modified ? currentMessage : undefined; + } + async emitToolResult(event) { + const ctx = this.createContext(); + const currentEvent = { ...event }; + let modified = false; + for (const ext of this.extensions) { + const handlers = ext.handlers.get("tool_result"); + if (!handlers || handlers.length === 0) + continue; + for (const handler of handlers) { + try { + const handlerResult = (await handler(currentEvent, ctx)); + if (!handlerResult) + continue; + if (handlerResult.content !== undefined) { + currentEvent.content = handlerResult.content; + modified = true; + } + if (handlerResult.details !== undefined) { + currentEvent.details = handlerResult.details; + modified = true; + } + if (handlerResult.isError !== undefined) { + currentEvent.isError = handlerResult.isError; + modified = true; + } + if (handlerResult.usage !== undefined) { + currentEvent.usage = handlerResult.usage; + modified = true; + } + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + const stack = err instanceof Error ? err.stack : undefined; + this.emitError({ + extensionPath: ext.path, + event: "tool_result", + error: message, + stack, + }); + } + } + } + if (!modified) { + return undefined; + } + return { + content: currentEvent.content, + details: currentEvent.details, + isError: currentEvent.isError, + usage: currentEvent.usage, + }; + } + async emitToolCall(event) { + const ctx = this.createContext(); + let result; + for (const ext of this.extensions) { + const handlers = ext.handlers.get("tool_call"); + if (!handlers || handlers.length === 0) + continue; + for (const handler of handlers) { + const handlerResult = await handler(event, ctx); + if (handlerResult) { + result = handlerResult; + if (result.block) { + return result; + } + } + } + } + return result; + } + async emitUserBash(event) { + const ctx = this.createContext(); + for (const ext of this.extensions) { + const handlers = ext.handlers.get("user_bash"); + if (!handlers || handlers.length === 0) + continue; + for (const handler of handlers) { + try { + const handlerResult = await handler(event, ctx); + if (handlerResult) { + return handlerResult; + } + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + const stack = err instanceof Error ? err.stack : undefined; + this.emitError({ + extensionPath: ext.path, + event: "user_bash", + error: message, + stack, + }); + } + } + } + return undefined; + } + async emitContext(messages) { + const ctx = this.createContext(); + let currentMessages = structuredClone(messages); + for (const ext of this.extensions) { + const handlers = ext.handlers.get("context"); + if (!handlers || handlers.length === 0) + continue; + for (const handler of handlers) { + try { + const event = { type: "context", messages: currentMessages }; + const handlerResult = await handler(event, ctx); + if (handlerResult && handlerResult.messages) { + currentMessages = handlerResult.messages; + } + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + const stack = err instanceof Error ? err.stack : undefined; + this.emitError({ + extensionPath: ext.path, + event: "context", + error: message, + stack, + }); + } + } + } + return currentMessages; + } + async emitBeforeProviderRequest(payload) { + const ctx = this.createContext(); + let currentPayload = payload; + for (const ext of this.extensions) { + const handlers = ext.handlers.get("before_provider_request"); + if (!handlers || handlers.length === 0) + continue; + for (const handler of handlers) { + try { + const event = { + type: "before_provider_request", + payload: currentPayload, + }; + const handlerResult = await handler(event, ctx); + if (handlerResult !== undefined) { + currentPayload = handlerResult; + } + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + const stack = err instanceof Error ? err.stack : undefined; + this.emitError({ + extensionPath: ext.path, + event: "before_provider_request", + error: message, + stack, + }); + } + } + } + return currentPayload; + } + async emitBeforeProviderHeaders(headers) { + const ctx = this.createContext(); + for (const ext of this.extensions) { + const handlers = ext.handlers.get("before_provider_headers"); + if (!handlers || handlers.length === 0) + continue; + for (const handler of handlers) { + try { + // Handlers mutate `headers` in place; the return value is ignored. + const event = { + type: "before_provider_headers", + headers, + }; + await handler(event, ctx); + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + const stack = err instanceof Error ? err.stack : undefined; + this.emitError({ + extensionPath: ext.path, + event: "before_provider_headers", + error: message, + stack, + }); + } + } + } + return headers; + } + async emitBeforeAgentStart(prompt, images, systemPrompt, systemPromptOptions) { + let currentSystemPrompt = systemPrompt; + const ctx = Object.defineProperties({}, Object.getOwnPropertyDescriptors(this.createContext())); + ctx.getSystemPrompt = () => { + this.assertActive(); + return currentSystemPrompt; + }; + const messages = []; + let systemPromptModified = false; + for (const ext of this.extensions) { + const handlers = ext.handlers.get("before_agent_start"); + if (!handlers || handlers.length === 0) + continue; + for (const handler of handlers) { + try { + const event = { + type: "before_agent_start", + prompt, + images, + systemPrompt: currentSystemPrompt, + systemPromptOptions, + }; + const handlerResult = await handler(event, ctx); + if (handlerResult) { + const result = handlerResult; + if (result.message) { + messages.push(result.message); + } + if (result.systemPrompt !== undefined) { + currentSystemPrompt = result.systemPrompt; + systemPromptModified = true; + } + } + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + const stack = err instanceof Error ? err.stack : undefined; + this.emitError({ + extensionPath: ext.path, + event: "before_agent_start", + error: message, + stack, + }); + } + } + } + if (messages.length > 0 || systemPromptModified) { + return { + messages: messages.length > 0 ? messages : undefined, + systemPrompt: systemPromptModified ? currentSystemPrompt : undefined, + }; + } + return undefined; + } + async emitResourcesDiscover(cwd, reason) { + const ctx = this.createContext(); + const skillPaths = []; + const promptPaths = []; + const themePaths = []; + for (const ext of this.extensions) { + const handlers = ext.handlers.get("resources_discover"); + if (!handlers || handlers.length === 0) + continue; + for (const handler of handlers) { + try { + const event = { type: "resources_discover", cwd, reason }; + const handlerResult = await handler(event, ctx); + const result = handlerResult; + if (result?.skillPaths?.length) { + skillPaths.push(...result.skillPaths.map((path) => ({ path, extensionPath: ext.path }))); + } + if (result?.promptPaths?.length) { + promptPaths.push(...result.promptPaths.map((path) => ({ path, extensionPath: ext.path }))); + } + if (result?.themePaths?.length) { + themePaths.push(...result.themePaths.map((path) => ({ path, extensionPath: ext.path }))); + } + } + catch (err) { + const message = err instanceof Error ? err.message : String(err); + const stack = err instanceof Error ? err.stack : undefined; + this.emitError({ + extensionPath: ext.path, + event: "resources_discover", + error: message, + stack, + }); + } + } + } + return { skillPaths, promptPaths, themePaths }; + } + /** Emit input event. Transforms chain, "handled" short-circuits. */ + async emitInput(text, images, source, streamingBehavior) { + const ctx = this.createContext(); + let currentText = text; + let currentImages = images; + for (const ext of this.extensions) { + for (const handler of ext.handlers.get("input") ?? []) { + try { + const event = { + type: "input", + text: currentText, + images: currentImages, + source, + streamingBehavior, + }; + const result = (await handler(event, ctx)); + if (result?.action === "handled") + return result; + if (result?.action === "transform") { + currentText = result.text; + currentImages = result.images ?? currentImages; + } + } + catch (err) { + this.emitError({ + extensionPath: ext.path, + event: "input", + error: err instanceof Error ? err.message : String(err), + stack: err instanceof Error ? err.stack : undefined, + }); + } + } + } + return currentText !== text || currentImages !== images + ? { action: "transform", text: currentText, images: currentImages } + : { action: "continue" }; + } +} +//# sourceMappingURL=runner.js.map \ No newline at end of file diff --git a/dist/core/extensions/runner.js.map b/dist/core/extensions/runner.js.map new file mode 100644 index 0000000..fe1496e --- /dev/null +++ b/dist/core/extensions/runner.js.map @@ -0,0 +1 @@ +{"version":3,"file":"runner.js","sourceRoot":"","sources":["../../../src/core/extensions/runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,OAAO,EAAc,KAAK,EAAE,MAAM,wCAAwC,CAAC;AA4D3E,mFAAmF;AACnF,oFAAoF;AACpF,MAAM,4CAA4C,GAAG;IACpD,eAAe;IACf,WAAW;IACX,UAAU;IACV,aAAa;IACb,oBAAoB;IACpB,wBAAwB;IACxB,yBAAyB;IACzB,kBAAkB;IAClB,kBAAkB;IAClB,qBAAqB;IACrB,qBAAqB;IACrB,kBAAkB;IAClB,sBAAsB;IACtB,kBAAkB;IAClB,oBAAoB;IACpB,mBAAmB;IACnB,gBAAgB;IAChB,4BAA4B;CACnB,CAAC;AAIX,MAAM,uBAAuB,GAAG,CAAC,mBAAsC,EAAsB,EAAE,CAAC;IAC/F,MAAM,kBAAkB,GAAG,EAAwB,CAAC;IACpD,KAAK,MAAM,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE,CAAC;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CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;wBACvD,KAAK,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;qBACnD,CAAC,CAAC;gBACJ,CAAC;YACF,CAAC;QACF,CAAC;QACD,OAAO,WAAW,KAAK,IAAI,IAAI,aAAa,KAAK,MAAM;YACtD,CAAC,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE;YACnE,CAAC,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IAAA,CAC1B;CACD","sourcesContent":["/**\n * Extension runner - executes extensions and manages their lifecycle.\n */\n\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, Model, Provider, ProviderHeaders } from \"@earendil-works/pi-ai\";\nimport type { KeyId } from \"@earendil-works/pi-tui\";\nimport { type Theme, theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ResourceDiagnostic } from \"../diagnostics.ts\";\nimport type { KeybindingsConfig } from \"../keybindings.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type { ScopedModel } from \"../model-resolver.ts\";\nimport type { SessionManager } from \"../session-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tBeforeProviderHeadersEvent,\n\tBeforeProviderRequestEvent,\n\tCompactOptions,\n\tContextEvent,\n\tContextEventResult,\n\tContextUsage,\n\tEntryRenderer,\n\tExtension,\n\tExtensionActions,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFlag,\n\tExtensionMode,\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tLoadExtensionsResult,\n\tMessageEndEvent,\n\tMessageEndEventResult,\n\tMessageRenderer,\n\tProjectTrustContext,\n\tProjectTrustEvent,\n\tProjectTrustEventResult,\n\tProviderConfig,\n\tRegisteredCommand,\n\tRegisteredTool,\n\tReplacedSessionContext,\n\tResolvedCommand,\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tSessionShutdownEvent,\n\tToolCallEvent,\n\tToolCallEventResult,\n\tToolResultEvent,\n\tToolResultEventResult,\n\tUserBashEvent,\n\tUserBashEventResult,\n} from \"./types.ts\";\n\n// Extension shortcuts compete with canonical keybinding ids from keybindings.json.\n// Only editor-global shortcuts are reserved here. Picker-specific bindings are not.\nconst RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS = [\n\t\"app.interrupt\",\n\t\"app.clear\",\n\t\"app.exit\",\n\t\"app.suspend\",\n\t\"app.thinking.cycle\",\n\t\"app.model.cycleForward\",\n\t\"app.model.cycleBackward\",\n\t\"app.model.select\",\n\t\"app.tools.expand\",\n\t\"app.thinking.toggle\",\n\t\"app.editor.external\",\n\t\"app.message.copy\",\n\t\"app.message.followUp\",\n\t\"tui.input.submit\",\n\t\"tui.select.confirm\",\n\t\"tui.select.cancel\",\n\t\"tui.input.copy\",\n\t\"tui.editor.deleteToLineEnd\",\n] as const;\n\ntype BuiltInKeyBindings = Partial>;\n\nconst buildBuiltinKeybindings = (resolvedKeybindings: KeybindingsConfig): BuiltInKeyBindings => {\n\tconst builtinKeybindings = {} as BuiltInKeyBindings;\n\tfor (const [keybinding, keys] of Object.entries(resolvedKeybindings)) {\n\t\tif (keys === undefined) continue;\n\t\tconst keyList = Array.isArray(keys) ? keys : [keys];\n\t\tconst restrictOverride = (RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS as readonly string[]).includes(keybinding);\n\t\tfor (const key of keyList) {\n\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\t\t\t// If multiple actions bind the same key, the reserved action wins so extensions\n\t\t\t// remain blocked by reserved shortcuts regardless of iteration order.\n\t\t\tconst existing = builtinKeybindings[normalizedKey];\n\t\t\tif (existing?.restrictOverride && !restrictOverride) continue;\n\t\t\tbuiltinKeybindings[normalizedKey] = {\n\t\t\t\tkeybinding,\n\t\t\t\trestrictOverride,\n\t\t\t};\n\t\t}\n\t}\n\treturn builtinKeybindings;\n};\n\n/** Combined result from all before_agent_start handlers */\ninterface BeforeAgentStartCombinedResult {\n\tmessages?: NonNullable[];\n\tsystemPrompt?: string;\n}\n\n/**\n * Events handled by the generic emit() method.\n * Events with dedicated emitXxx() methods are excluded for stronger type safety.\n */\ntype RunnerEmitEvent = Exclude<\n\tExtensionEvent,\n\t| ToolCallEvent\n\t| ProjectTrustEvent\n\t| ToolResultEvent\n\t| UserBashEvent\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeProviderHeadersEvent\n\t| BeforeAgentStartEvent\n\t| MessageEndEvent\n\t| ResourcesDiscoverEvent\n\t| InputEvent\n>;\n\ntype SessionBeforeEvent = Extract<\n\tRunnerEmitEvent,\n\t{ type: \"session_before_switch\" | \"session_before_fork\" | \"session_before_compact\" | \"session_before_tree\" }\n>;\n\ntype SessionBeforeEventResult =\n\t| SessionBeforeSwitchResult\n\t| SessionBeforeForkResult\n\t| SessionBeforeCompactResult\n\t| SessionBeforeTreeResult;\n\ntype RunnerEmitResult = TEvent extends { type: \"session_before_switch\" }\n\t? SessionBeforeSwitchResult | undefined\n\t: TEvent extends { type: \"session_before_fork\" }\n\t\t? SessionBeforeForkResult | undefined\n\t\t: TEvent extends { type: \"session_before_compact\" }\n\t\t\t? SessionBeforeCompactResult | undefined\n\t\t\t: TEvent extends { type: \"session_before_tree\" }\n\t\t\t\t? SessionBeforeTreeResult | undefined\n\t\t\t\t: undefined;\n\nexport type ExtensionErrorListener = (error: ExtensionError) => void;\n\nexport type NewSessionHandler = (options?: {\n\tparentSession?: string;\n\tsetup?: (sessionManager: SessionManager) => Promise;\n\twithSession?: (ctx: ReplacedSessionContext) => Promise;\n}) => Promise<{ cancelled: boolean }>;\n\nexport type ForkHandler = (\n\tentryId: string,\n\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise },\n) => Promise<{ cancelled: boolean }>;\n\nexport type NavigateTreeHandler = (\n\ttargetId: string,\n\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n) => Promise<{ cancelled: boolean }>;\n\nexport type SwitchSessionHandler = (\n\tsessionPath: string,\n\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise },\n) => Promise<{ cancelled: boolean }>;\n\nexport type ReloadHandler = () => Promise;\n\nexport type ShutdownHandler = () => void;\n\n/**\n * Helper function to emit session_shutdown event to extensions.\n * Returns true if the event was emitted, false if there were no handlers.\n */\nexport async function emitSessionShutdownEvent(\n\textensionRunner: ExtensionRunner,\n\tevent: SessionShutdownEvent,\n): Promise {\n\tif (extensionRunner.hasHandlers(\"session_shutdown\")) {\n\t\tawait extensionRunner.emit(event);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nexport async function emitProjectTrustEvent(\n\textensionsResult: LoadExtensionsResult,\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n): Promise<{ result?: ProjectTrustEventResult; errors: ExtensionError[] }> {\n\tconst errors: ExtensionError[] = [];\n\tfor (const ext of extensionsResult.extensions) {\n\t\t// A single extension may register multiple handlers for the same event.\n\t\t// The first project_trust handler that returns yes/no wins; undecided falls through.\n\t\tconst handlers = ext.handlers.get(\"project_trust\");\n\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\tfor (const handler of handlers) {\n\t\t\ttry {\n\t\t\t\tconst handlerResult = (await handler(event, ctx)) as ProjectTrustEventResult;\n\t\t\t\tif (handlerResult.trusted === \"undecided\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn { result: handlerResult, errors };\n\t\t\t} catch (error) {\n\t\t\t\terrors.push({\n\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\tevent: event.type,\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\tstack: error instanceof Error ? error.stack : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\treturn { errors };\n}\n\nconst noOpUIContext: ExtensionUIContext = {\n\tselect: async () => undefined,\n\tconfirm: async () => false,\n\tinput: async () => undefined,\n\tnotify: () => {},\n\tonTerminalInput: () => () => {},\n\tsetStatus: () => {},\n\tsetWorkingMessage: () => {},\n\tsetWorkingVisible: () => {},\n\tsetWorkingIndicator: () => {},\n\tsetHiddenThinkingLabel: () => {},\n\tsetWidget: () => {},\n\tsetFooter: () => {},\n\tsetHeader: () => {},\n\tsetTitle: () => {},\n\tcustom: async () => undefined as never,\n\tpasteToEditor: () => {},\n\tsetEditorText: () => {},\n\tgetEditorText: () => \"\",\n\teditor: async () => undefined,\n\taddAutocompleteProvider: () => {},\n\tsetEditorComponent: () => {},\n\tgetEditorComponent: () => undefined,\n\tget theme() {\n\t\treturn theme;\n\t},\n\tgetAllThemes: () => [],\n\tgetTheme: () => undefined,\n\tsetTheme: (_theme: string | Theme) => ({ success: false, error: \"UI not available\" }),\n\tgetToolsExpanded: () => false,\n\tsetToolsExpanded: () => {},\n};\n\nexport class ExtensionRunner {\n\tprivate extensions: Extension[];\n\tprivate runtime: ExtensionRuntime;\n\tprivate uiContext: ExtensionUIContext;\n\tprivate mode: ExtensionMode = \"print\";\n\tprivate cwd: string;\n\tprivate sessionManager: SessionManager;\n\tprivate modelRegistry: ModelRegistry;\n\tprivate errorListeners: Set = new Set();\n\tprivate getModel: () => Model | undefined = () => undefined;\n\tprivate getScopedModels: () => readonly ScopedModel[] = () => [];\n\tprivate isIdleFn: () => boolean = () => true;\n\tprivate isProjectTrustedFn: () => boolean = () => true;\n\tprivate getSignalFn: () => AbortSignal | undefined = () => undefined;\n\tprivate waitForIdleFn: () => Promise = async () => {};\n\tprivate abortFn: () => void = () => {};\n\tprivate hasPendingMessagesFn: () => boolean = () => false;\n\tprivate getContextUsageFn: () => ContextUsage | undefined = () => undefined;\n\tprivate compactFn: (options?: CompactOptions) => void = () => {};\n\tprivate getSystemPromptFn: () => string = () => \"\";\n\tprivate getSystemPromptOptionsFn: () => BuildSystemPromptOptions = () => ({ cwd: this.cwd });\n\tprivate newSessionHandler: NewSessionHandler = async () => ({ cancelled: false });\n\tprivate forkHandler: ForkHandler = async () => ({ cancelled: false });\n\tprivate navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false });\n\tprivate switchSessionHandler: SwitchSessionHandler = async () => ({ cancelled: false });\n\tprivate reloadHandler: ReloadHandler = async () => {};\n\tprivate shutdownHandler: ShutdownHandler = () => {};\n\tprivate shortcutDiagnostics: ResourceDiagnostic[] = [];\n\tprivate commandDiagnostics: ResourceDiagnostic[] = [];\n\tprivate staleMessage: string | undefined;\n\n\tconstructor(\n\t\textensions: Extension[],\n\t\truntime: ExtensionRuntime,\n\t\tcwd: string,\n\t\tsessionManager: SessionManager,\n\t\tmodelRegistry: ModelRegistry,\n\t) {\n\t\tthis.extensions = extensions;\n\t\tthis.runtime = runtime;\n\t\tthis.uiContext = noOpUIContext;\n\t\tthis.cwd = cwd;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.modelRegistry = modelRegistry;\n\t}\n\n\tbindCore(\n\t\tactions: ExtensionActions,\n\t\tcontextActions: ExtensionContextActions,\n\t\tproviderActions?: {\n\t\t\tregisterProvider?: (name: string, config: ProviderConfig) => void;\n\t\t\tregisterNativeProvider?: (provider: Provider) => void;\n\t\t\tunregisterProvider?: (name: string) => void;\n\t\t},\n\t): void {\n\t\t// Copy actions into the shared runtime (all extension APIs reference this)\n\t\tthis.runtime.sendMessage = actions.sendMessage;\n\t\tthis.runtime.sendUserMessage = actions.sendUserMessage;\n\t\tthis.runtime.appendEntry = actions.appendEntry;\n\t\tthis.runtime.setSessionName = actions.setSessionName;\n\t\tthis.runtime.getSessionName = actions.getSessionName;\n\t\tthis.runtime.setLabel = actions.setLabel;\n\t\tthis.runtime.getActiveTools = actions.getActiveTools;\n\t\tthis.runtime.getAllTools = actions.getAllTools;\n\t\tthis.runtime.setActiveTools = actions.setActiveTools;\n\t\tthis.runtime.refreshTools = actions.refreshTools;\n\t\tthis.runtime.getCommands = actions.getCommands;\n\t\tthis.runtime.setModel = actions.setModel;\n\t\tthis.runtime.getThinkingLevel = actions.getThinkingLevel;\n\t\tthis.runtime.setThinkingLevel = actions.setThinkingLevel;\n\n\t\t// Context actions (required)\n\t\tthis.getModel = contextActions.getModel;\n\t\tthis.getScopedModels = contextActions.getScopedModels;\n\t\tthis.isIdleFn = contextActions.isIdle;\n\t\tthis.isProjectTrustedFn = contextActions.isProjectTrusted;\n\t\tthis.getSignalFn = contextActions.getSignal;\n\t\tthis.abortFn = contextActions.abort;\n\t\tthis.hasPendingMessagesFn = contextActions.hasPendingMessages;\n\t\tthis.shutdownHandler = contextActions.shutdown;\n\t\tthis.getContextUsageFn = contextActions.getContextUsage;\n\t\tthis.compactFn = contextActions.compact;\n\t\tthis.getSystemPromptFn = contextActions.getSystemPrompt;\n\t\tthis.getSystemPromptOptionsFn = contextActions.getSystemPromptOptions ?? (() => ({ cwd: this.cwd }));\n\n\t\t// Flush provider registrations queued during extension loading\n\t\tfor (const { name, config, extensionPath } of this.runtime.pendingProviderRegistrations) {\n\t\t\ttry {\n\t\t\t\tif (providerActions?.registerProvider) {\n\t\t\t\t\tproviderActions.registerProvider(name, config);\n\t\t\t\t} else {\n\t\t\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis.emitError({\n\t\t\t\t\textensionPath,\n\t\t\t\t\tevent: \"register_provider\",\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis.runtime.pendingProviderRegistrations = [];\n\t\tfor (const { provider, extensionPath } of this.runtime.pendingNativeProviderRegistrations) {\n\t\t\ttry {\n\t\t\t\tif (providerActions?.registerNativeProvider) {\n\t\t\t\t\tproviderActions.registerNativeProvider(provider);\n\t\t\t\t} else {\n\t\t\t\t\tthis.modelRegistry.registerProvider(provider);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis.emitError({\n\t\t\t\t\textensionPath,\n\t\t\t\t\tevent: \"register_provider\",\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis.runtime.pendingNativeProviderRegistrations = [];\n\n\t\t// From this point on, provider registration/unregistration takes effect immediately\n\t\t// without requiring a /reload.\n\t\tthis.runtime.registerProvider = (name, config) => {\n\t\t\tif (providerActions?.registerProvider) {\n\t\t\t\tproviderActions.registerProvider(name, config);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t};\n\t\tthis.runtime.registerNativeProvider = (provider) => {\n\t\t\tif (providerActions?.registerNativeProvider) {\n\t\t\t\tproviderActions.registerNativeProvider(provider);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.modelRegistry.registerProvider(provider);\n\t\t};\n\t\tthis.runtime.unregisterProvider = (name) => {\n\t\t\tif (providerActions?.unregisterProvider) {\n\t\t\t\tproviderActions.unregisterProvider(name);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.modelRegistry.unregisterProvider(name);\n\t\t};\n\t}\n\n\tbindCommandContext(actions?: ExtensionCommandContextActions): void {\n\t\tif (actions) {\n\t\t\tthis.waitForIdleFn = actions.waitForIdle;\n\t\t\tthis.newSessionHandler = actions.newSession;\n\t\t\tthis.forkHandler = actions.fork;\n\t\t\tthis.navigateTreeHandler = actions.navigateTree;\n\t\t\tthis.switchSessionHandler = actions.switchSession;\n\t\t\tthis.reloadHandler = actions.reload;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.waitForIdleFn = async () => {};\n\t\tthis.newSessionHandler = async () => ({ cancelled: false });\n\t\tthis.forkHandler = async () => ({ cancelled: false });\n\t\tthis.navigateTreeHandler = async () => ({ cancelled: false });\n\t\tthis.switchSessionHandler = async () => ({ cancelled: false });\n\t\tthis.reloadHandler = async () => {};\n\t}\n\n\tsetUIContext(uiContext?: ExtensionUIContext, mode: ExtensionMode = \"print\"): void {\n\t\tthis.uiContext = uiContext ?? noOpUIContext;\n\t\tthis.mode = mode;\n\t}\n\n\tgetUIContext(): ExtensionUIContext {\n\t\treturn this.uiContext;\n\t}\n\n\thasUI(): boolean {\n\t\treturn this.uiContext !== noOpUIContext;\n\t}\n\n\tgetExtensionPaths(): string[] {\n\t\treturn this.extensions.map((e) => e.path);\n\t}\n\n\t/** Get all registered tools from all extensions (first registration per name wins). */\n\tgetAllRegisteredTools(): RegisteredTool[] {\n\t\tconst toolsByName = new Map();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const tool of ext.tools.values()) {\n\t\t\t\tif (!toolsByName.has(tool.definition.name)) {\n\t\t\t\t\ttoolsByName.set(tool.definition.name, tool);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn Array.from(toolsByName.values());\n\t}\n\n\t/** Get a tool definition by name. Returns undefined if not found. */\n\tgetToolDefinition(toolName: string): RegisteredTool[\"definition\"] | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst tool = ext.tools.get(toolName);\n\t\t\tif (tool) {\n\t\t\t\treturn tool.definition;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tgetFlags(): Map {\n\t\tconst allFlags = new Map();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [name, flag] of ext.flags) {\n\t\t\t\tif (!allFlags.has(name)) {\n\t\t\t\t\tallFlags.set(name, flag);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn allFlags;\n\t}\n\n\tsetFlagValue(name: string, value: boolean | string): void {\n\t\tthis.runtime.flagValues.set(name, value);\n\t}\n\n\tgetFlagValues(): Map {\n\t\treturn new Map(this.runtime.flagValues);\n\t}\n\n\tgetShortcuts(resolvedKeybindings: KeybindingsConfig): Map {\n\t\tthis.shortcutDiagnostics = [];\n\t\tconst builtinKeybindings = buildBuiltinKeybindings(resolvedKeybindings);\n\t\tconst extensionShortcuts = new Map();\n\n\t\tconst addDiagnostic = (message: string, extensionPath: string) => {\n\t\t\tthis.shortcutDiagnostics.push({ type: \"warning\", message, path: extensionPath });\n\t\t\tif (!this.hasUI()) {\n\t\t\t\tconsole.warn(message);\n\t\t\t}\n\t\t};\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [key, shortcut] of ext.shortcuts) {\n\t\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\n\t\t\t\tconst builtInKeybinding = builtinKeybindings[normalizedKey];\n\t\t\t\tif (builtInKeybinding?.restrictOverride === true) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut '${key}' from ${shortcut.extensionPath} conflicts with built-in shortcut. Skipping.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (builtInKeybinding?.restrictOverride === false) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' is built-in shortcut for ${builtInKeybinding.keybinding} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst existingExtensionShortcut = extensionShortcuts.get(normalizedKey);\n\t\t\t\tif (existingExtensionShortcut) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' registered by both ${existingExtensionShortcut.extensionPath} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\textensionShortcuts.set(normalizedKey, shortcut);\n\t\t\t}\n\t\t}\n\t\treturn extensionShortcuts;\n\t}\n\n\tgetShortcutDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.shortcutDiagnostics;\n\t}\n\n\tinvalidate(\n\t\tmessage = \"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\",\n\t): void {\n\t\tif (!this.staleMessage) {\n\t\t\tthis.staleMessage = message;\n\t\t\tthis.runtime.invalidate(message);\n\t\t}\n\t}\n\n\tprivate assertActive(): void {\n\t\tif (this.staleMessage) {\n\t\t\tthrow new Error(this.staleMessage);\n\t\t}\n\t}\n\n\tonError(listener: ExtensionErrorListener): () => void {\n\t\tthis.errorListeners.add(listener);\n\t\treturn () => this.errorListeners.delete(listener);\n\t}\n\n\temitError(error: ExtensionError): void {\n\t\tfor (const listener of this.errorListeners) {\n\t\t\tlistener(error);\n\t\t}\n\t}\n\n\thasHandlers(eventType: string): boolean {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(eventType);\n\t\t\tif (handlers && handlers.length > 0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tgetMessageRenderer(customType: string): MessageRenderer | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst renderer = ext.messageRenderers.get(customType);\n\t\t\tif (renderer) {\n\t\t\t\treturn renderer;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tgetEntryRenderer(customType: string): EntryRenderer | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst renderer = ext.entryRenderers?.get(customType);\n\t\t\tif (renderer) {\n\t\t\t\treturn renderer;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate resolveRegisteredCommands(): ResolvedCommand[] {\n\t\tconst commands: RegisteredCommand[] = [];\n\t\tconst counts = new Map();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const command of ext.commands.values()) {\n\t\t\t\tcommands.push(command);\n\t\t\t\tcounts.set(command.name, (counts.get(command.name) ?? 0) + 1);\n\t\t\t}\n\t\t}\n\n\t\tconst seen = new Map();\n\t\tconst takenInvocationNames = new Set();\n\n\t\treturn commands.map((command) => {\n\t\t\tconst occurrence = (seen.get(command.name) ?? 0) + 1;\n\t\t\tseen.set(command.name, occurrence);\n\n\t\t\tlet invocationName = (counts.get(command.name) ?? 0) > 1 ? `${command.name}:${occurrence}` : command.name;\n\n\t\t\tif (takenInvocationNames.has(invocationName)) {\n\t\t\t\tlet suffix = occurrence;\n\t\t\t\tdo {\n\t\t\t\t\tsuffix++;\n\t\t\t\t\tinvocationName = `${command.name}:${suffix}`;\n\t\t\t\t} while (takenInvocationNames.has(invocationName));\n\t\t\t}\n\n\t\t\ttakenInvocationNames.add(invocationName);\n\t\t\treturn {\n\t\t\t\t...command,\n\t\t\t\tinvocationName,\n\t\t\t};\n\t\t});\n\t}\n\n\tgetModelRegistry(): ModelRegistry {\n\t\treturn this.modelRegistry;\n\t}\n\n\tgetRegisteredCommands(): ResolvedCommand[] {\n\t\tthis.commandDiagnostics = [];\n\t\treturn this.resolveRegisteredCommands();\n\t}\n\n\tgetCommandDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.commandDiagnostics;\n\t}\n\n\tgetCommand(name: string): ResolvedCommand | undefined {\n\t\treturn this.resolveRegisteredCommands().find((command) => command.invocationName === name);\n\t}\n\n\t/**\n\t * Request a graceful shutdown. Called by extension tools and event handlers.\n\t * The actual shutdown behavior is provided by the mode via bindExtensions().\n\t */\n\tshutdown(): void {\n\t\tthis.shutdownHandler();\n\t}\n\n\tgetActiveTools(): string[] {\n\t\tthis.assertActive();\n\t\treturn this.runtime.getActiveTools();\n\t}\n\n\t/**\n\t * Create an ExtensionContext for use in event handlers and tool execution.\n\t * Context values are resolved at call time, so changes via bindCore/bindUI are reflected.\n\t */\n\tcreateContext(): ExtensionContext {\n\t\tconst runner = this;\n\t\tconst getModel = this.getModel;\n\t\tconst getScopedModels = this.getScopedModels;\n\t\treturn {\n\t\t\tget ui() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.uiContext;\n\t\t\t},\n\t\t\tget mode() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.mode;\n\t\t\t},\n\t\t\tget hasUI() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.hasUI();\n\t\t\t},\n\t\t\tget cwd() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.cwd;\n\t\t\t},\n\t\t\tget sessionManager() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.sessionManager;\n\t\t\t},\n\t\t\tget modelRegistry() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.modelRegistry;\n\t\t\t},\n\t\t\tget model() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn getModel();\n\t\t\t},\n\t\t\tget scopedModels() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn getScopedModels();\n\t\t\t},\n\t\t\tget thinkingLevel() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.runtime.getThinkingLevel();\n\t\t\t},\n\t\t\tisIdle: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.isIdleFn();\n\t\t\t},\n\t\t\tisProjectTrusted: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.isProjectTrustedFn();\n\t\t\t},\n\t\t\tget signal() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getSignalFn();\n\t\t\t},\n\t\t\tabort: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.abortFn();\n\t\t\t},\n\t\t\thasPendingMessages: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.hasPendingMessagesFn();\n\t\t\t},\n\t\t\tshutdown: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.shutdownHandler();\n\t\t\t},\n\t\t\tgetContextUsage: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getContextUsageFn();\n\t\t\t},\n\t\t\tcompact: (options) => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.compactFn(options);\n\t\t\t},\n\t\t\tgetSystemPrompt: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getSystemPromptFn();\n\t\t\t},\n\t\t};\n\t}\n\n\tcreateCommandContext(): ExtensionCommandContext {\n\t\t// Use property descriptors instead of object spread so the guarded getters from\n\t\t// createContext() stay lazy. A spread would eagerly read them once and freeze the\n\t\t// old values into the returned object, bypassing stale-instance checks.\n\t\tconst context = Object.defineProperties(\n\t\t\t{},\n\t\t\tObject.getOwnPropertyDescriptors(this.createContext()),\n\t\t) as ExtensionCommandContext;\n\t\tcontext.getSystemPromptOptions = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.getSystemPromptOptionsFn();\n\t\t};\n\t\tcontext.waitForIdle = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.waitForIdleFn();\n\t\t};\n\t\tcontext.newSession = (options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.newSessionHandler(options);\n\t\t};\n\t\tcontext.fork = (entryId, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.forkHandler(entryId, options);\n\t\t};\n\t\tcontext.navigateTree = (targetId, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.navigateTreeHandler(targetId, options);\n\t\t};\n\t\tcontext.switchSession = (sessionPath, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.switchSessionHandler(sessionPath, options);\n\t\t};\n\t\tcontext.reload = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.reloadHandler();\n\t\t};\n\t\treturn context;\n\t}\n\n\tprivate isSessionBeforeEvent(event: RunnerEmitEvent): event is SessionBeforeEvent {\n\t\treturn (\n\t\t\tevent.type === \"session_before_switch\" ||\n\t\t\tevent.type === \"session_before_fork\" ||\n\t\t\tevent.type === \"session_before_compact\" ||\n\t\t\tevent.type === \"session_before_tree\"\n\t\t);\n\t}\n\n\tasync emit(event: TEvent): Promise> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: SessionBeforeEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(event.type);\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (this.isSessionBeforeEvent(event) && handlerResult) {\n\t\t\t\t\t\tresult = handlerResult as SessionBeforeEventResult;\n\t\t\t\t\t\tif (result.cancel) {\n\t\t\t\t\t\t\treturn result as RunnerEmitResult;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: event.type,\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result as RunnerEmitResult;\n\t}\n\n\tasync emitMessageEnd(event: MessageEndEvent): Promise {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessage = event.message;\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"message_end\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst currentEvent: MessageEndEvent = { ...event, message: currentMessage };\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as MessageEndEventResult | undefined;\n\t\t\t\t\tif (!handlerResult?.message) continue;\n\n\t\t\t\t\tif (handlerResult.message.role !== currentMessage.role) {\n\t\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\t\tevent: \"message_end\",\n\t\t\t\t\t\t\terror: \"message_end handlers must return a message with the same role\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentMessage = handlerResult.message;\n\t\t\t\t\tmodified = true;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"message_end\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn modified ? currentMessage : undefined;\n\t}\n\n\tasync emitToolResult(event: ToolResultEvent): Promise {\n\t\tconst ctx = this.createContext();\n\t\tconst currentEvent: ToolResultEvent = { ...event };\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_result\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as ToolResultEventResult | undefined;\n\t\t\t\t\tif (!handlerResult) continue;\n\n\t\t\t\t\tif (handlerResult.content !== undefined) {\n\t\t\t\t\t\tcurrentEvent.content = handlerResult.content;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.details !== undefined) {\n\t\t\t\t\t\tcurrentEvent.details = handlerResult.details;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.isError !== undefined) {\n\t\t\t\t\t\tcurrentEvent.isError = handlerResult.isError;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.usage !== undefined) {\n\t\t\t\t\t\tcurrentEvent.usage = handlerResult.usage;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"tool_result\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!modified) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: currentEvent.content,\n\t\t\tdetails: currentEvent.details,\n\t\t\tisError: currentEvent.isError,\n\t\t\tusage: currentEvent.usage,\n\t\t};\n\t}\n\n\tasync emitToolCall(event: ToolCallEvent): Promise {\n\t\tconst ctx = this.createContext();\n\t\tlet result: ToolCallEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_call\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\tif (handlerResult) {\n\t\t\t\t\tresult = handlerResult as ToolCallEventResult;\n\t\t\t\t\tif (result.block) {\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tasync emitUserBash(event: UserBashEvent): Promise {\n\t\tconst ctx = this.createContext();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"user_bash\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\treturn handlerResult as UserBashEventResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"user_bash\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitContext(messages: AgentMessage[]): Promise {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessages = structuredClone(messages);\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"context\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ContextEvent = { type: \"context\", messages: currentMessages };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult && (handlerResult as ContextEventResult).messages) {\n\t\t\t\t\t\tcurrentMessages = (handlerResult as ContextEventResult).messages!;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"context\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentMessages;\n\t}\n\n\tasync emitBeforeProviderRequest(payload: unknown): Promise {\n\t\tconst ctx = this.createContext();\n\t\tlet currentPayload = payload;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_provider_request\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeProviderRequestEvent = {\n\t\t\t\t\t\ttype: \"before_provider_request\",\n\t\t\t\t\t\tpayload: currentPayload,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult !== undefined) {\n\t\t\t\t\t\tcurrentPayload = handlerResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_provider_request\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentPayload;\n\t}\n\n\tasync emitBeforeProviderHeaders(headers: ProviderHeaders): Promise {\n\t\tconst ctx = this.createContext();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_provider_headers\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\t// Handlers mutate `headers` in place; the return value is ignored.\n\t\t\t\t\tconst event: BeforeProviderHeadersEvent = {\n\t\t\t\t\t\ttype: \"before_provider_headers\",\n\t\t\t\t\t\theaders,\n\t\t\t\t\t};\n\t\t\t\t\tawait handler(event, ctx);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_provider_headers\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn headers;\n\t}\n\n\tasync emitBeforeAgentStart(\n\t\tprompt: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsystemPrompt: string,\n\t\tsystemPromptOptions: BuildSystemPromptOptions,\n\t): Promise {\n\t\tlet currentSystemPrompt = systemPrompt;\n\t\tconst ctx = Object.defineProperties(\n\t\t\t{},\n\t\t\tObject.getOwnPropertyDescriptors(this.createContext()),\n\t\t) as ExtensionContext;\n\t\tctx.getSystemPrompt = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn currentSystemPrompt;\n\t\t};\n\t\tconst messages: NonNullable[] = [];\n\t\tlet systemPromptModified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_agent_start\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeAgentStartEvent = {\n\t\t\t\t\t\ttype: \"before_agent_start\",\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\timages,\n\t\t\t\t\t\tsystemPrompt: currentSystemPrompt,\n\t\t\t\t\t\tsystemPromptOptions,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\tconst result = handlerResult as BeforeAgentStartEventResult;\n\t\t\t\t\t\tif (result.message) {\n\t\t\t\t\t\t\tmessages.push(result.message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.systemPrompt !== undefined) {\n\t\t\t\t\t\t\tcurrentSystemPrompt = result.systemPrompt;\n\t\t\t\t\t\t\tsystemPromptModified = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_agent_start\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (messages.length > 0 || systemPromptModified) {\n\t\t\treturn {\n\t\t\t\tmessages: messages.length > 0 ? messages : undefined,\n\t\t\t\tsystemPrompt: systemPromptModified ? currentSystemPrompt : undefined,\n\t\t\t};\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitResourcesDiscover(\n\t\tcwd: string,\n\t\treason: ResourcesDiscoverEvent[\"reason\"],\n\t): Promise<{\n\t\tskillPaths: Array<{ path: string; extensionPath: string }>;\n\t\tpromptPaths: Array<{ path: string; extensionPath: string }>;\n\t\tthemePaths: Array<{ path: string; extensionPath: string }>;\n\t}> {\n\t\tconst ctx = this.createContext();\n\t\tconst skillPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst promptPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst themePaths: Array<{ path: string; extensionPath: string }> = [];\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"resources_discover\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ResourcesDiscoverEvent = { type: \"resources_discover\", cwd, reason };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tconst result = handlerResult as ResourcesDiscoverResult | undefined;\n\n\t\t\t\t\tif (result?.skillPaths?.length) {\n\t\t\t\t\t\tskillPaths.push(...result.skillPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.promptPaths?.length) {\n\t\t\t\t\t\tpromptPaths.push(...result.promptPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.themePaths?.length) {\n\t\t\t\t\t\tthemePaths.push(...result.themePaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"resources_discover\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { skillPaths, promptPaths, themePaths };\n\t}\n\n\t/** Emit input event. Transforms chain, \"handled\" short-circuits. */\n\tasync emitInput(\n\t\ttext: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsource: InputSource,\n\t\tstreamingBehavior?: \"steer\" | \"followUp\",\n\t): Promise {\n\t\tconst ctx = this.createContext();\n\t\tlet currentText = text;\n\t\tlet currentImages = images;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const handler of ext.handlers.get(\"input\") ?? []) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: InputEvent = {\n\t\t\t\t\t\ttype: \"input\",\n\t\t\t\t\t\ttext: currentText,\n\t\t\t\t\t\timages: currentImages,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tstreamingBehavior,\n\t\t\t\t\t};\n\t\t\t\t\tconst result = (await handler(event, ctx)) as InputEventResult | undefined;\n\t\t\t\t\tif (result?.action === \"handled\") return result;\n\t\t\t\t\tif (result?.action === \"transform\") {\n\t\t\t\t\t\tcurrentText = result.text;\n\t\t\t\t\t\tcurrentImages = result.images ?? currentImages;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"input\",\n\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn currentText !== text || currentImages !== images\n\t\t\t? { action: \"transform\", text: currentText, images: currentImages }\n\t\t\t: { action: \"continue\" };\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/extensions/types.d.ts b/dist/core/extensions/types.d.ts new file mode 100644 index 0000000..1a06f40 --- /dev/null +++ b/dist/core/extensions/types.d.ts @@ -0,0 +1,1272 @@ +/** + * Extension system types. + * + * Extensions are TypeScript modules that can: + * - Subscribe to agent lifecycle events + * - Register LLM-callable tools + * - Register commands, keyboard shortcuts, and CLI flags + * - Interact with the user via UI primitives + */ +import type { AgentMessage, AgentToolResult, AgentToolUpdateCallback, ThinkingLevel, ToolExecutionMode } from "@earendil-works/pi-agent-core"; +import type { Api, AssistantMessageEvent, AssistantMessageEventStream, ConstrainedSamplingConfig, Context, ImageContent, Model, OAuthCredentials, OAuthLoginCallbacks, Provider, ProviderHeaders, RefreshModelsContext, SimpleStreamOptions, TextContent, ToolResultMessage, Usage } from "@earendil-works/pi-ai"; +import type { AutocompleteItem, AutocompleteProvider, Component, EditorComponent, EditorTheme, KeyId, OverlayHandle, OverlayOptions, TUI } from "@earendil-works/pi-tui"; +import type { Static, TSchema } from "typebox"; +import type { Theme } from "../../modes/interactive/theme/theme.ts"; +import type { BashResult } from "../bash-executor.ts"; +import type { CompactionPreparation, CompactionResult } from "../compaction/index.ts"; +import type { EventBus } from "../event-bus.ts"; +import type { ExecOptions, ExecResult } from "../exec.ts"; +import type { ReadonlyFooterDataProvider } from "../footer-data-provider.ts"; +import type { KeybindingsManager } from "../keybindings.ts"; +import type { CustomMessage } from "../messages.ts"; +import type { ModelRegistry } from "../model-registry.ts"; +import type { ScopedModel } from "../model-resolver.ts"; +import type { BranchSummaryEntry, CompactionEntry, CustomEntry, ReadonlySessionManager, SessionEntry, SessionManager } from "../session-manager.ts"; +import type { SlashCommandInfo } from "../slash-commands.ts"; +import type { SourceInfo } from "../source-info.ts"; +import type { BuildSystemPromptOptions } from "../system-prompt.ts"; +import type { BashOperations } from "../tools/bash.ts"; +import type { EditToolDetails } from "../tools/edit.ts"; +import type { BashToolDetails, BashToolInput, EditToolInput, FindToolDetails, FindToolInput, GrepToolDetails, GrepToolInput, LsToolDetails, LsToolInput, ReadToolDetails, ReadToolInput, WriteToolInput } from "../tools/index.ts"; +export type { ExecOptions, ExecResult } from "../exec.ts"; +export type { BuildSystemPromptOptions } from "../system-prompt.ts"; +export type { AgentToolResult, AgentToolUpdateCallback, ToolExecutionMode }; +export type { AppKeybinding, KeybindingsManager } from "../keybindings.ts"; +/** Options for extension UI dialogs. */ +export interface ExtensionUIDialogOptions { + /** AbortSignal to programmatically dismiss the dialog. */ + signal?: AbortSignal; + /** Timeout in milliseconds. Dialog auto-dismisses with live countdown display. */ + timeout?: number; +} +/** Placement for extension widgets. */ +export type WidgetPlacement = "aboveEditor" | "belowEditor"; +/** Options for extension widgets. */ +export interface ExtensionWidgetOptions { + /** Where the widget is rendered. Defaults to "aboveEditor". */ + placement?: WidgetPlacement; +} +/** Raw terminal input listener for extensions. */ +export type TerminalInputHandler = (data: string) => { + consume?: boolean; + data?: string; +} | undefined; +/** Working indicator configuration for the interactive streaming loader. */ +export interface WorkingIndicatorOptions { + /** Animation frames. Use an empty array to hide the indicator entirely. Custom frames are rendered verbatim. */ + frames?: string[]; + /** Frame interval in milliseconds for animated indicators. */ + intervalMs?: number; +} +/** Wrap the current autocomplete provider with additional behavior. */ +export type AutocompleteProviderFactory = (current: AutocompleteProvider) => AutocompleteProvider; +export type EditorFactory = (tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) => EditorComponent; +/** + * UI context for extensions to request interactive UI. + * Each mode (interactive, RPC, print) provides its own implementation. + */ +export interface ExtensionUIContext { + /** Show a selector and return the user's choice. */ + select(title: string, options: string[], opts?: ExtensionUIDialogOptions): Promise; + /** Show a confirmation dialog. */ + confirm(title: string, message: string, opts?: ExtensionUIDialogOptions): Promise; + /** Show a text input dialog. */ + input(title: string, placeholder?: string, opts?: ExtensionUIDialogOptions): Promise; + /** Show a notification to the user. */ + notify(message: string, type?: "info" | "warning" | "error"): void; + /** Listen to raw terminal input (interactive mode only). Returns an unsubscribe function. */ + onTerminalInput(handler: TerminalInputHandler): () => void; + /** Set status text in the footer/status bar. Pass undefined to clear. */ + setStatus(key: string, text: string | undefined): void; + /** Set the working/loading message shown during streaming. Call with no argument to restore default. */ + setWorkingMessage(message?: string): void; + /** Show or hide the built-in interactive working loader row during streaming. */ + setWorkingVisible(visible: boolean): void; + /** + * Configure the interactive working indicator shown during streaming. + * + * - Omit the argument to restore the default animated spinner. + * - Use `frames: ["●"]` for a static indicator. + * - Use `frames: []` to hide the indicator entirely. + * - Custom frames are rendered as provided, so extensions must add their own colors. + */ + setWorkingIndicator(options?: WorkingIndicatorOptions): void; + /** Set the label shown for hidden thinking blocks. Call with no argument to restore default. */ + setHiddenThinkingLabel(label?: string): void; + /** Set a widget to display above or below the editor. Accepts string array or component factory. */ + setWidget(key: string, content: string[] | undefined, options?: ExtensionWidgetOptions): void; + setWidget(key: string, content: ((tui: TUI, theme: Theme) => Component & { + dispose?(): void; + }) | undefined, options?: ExtensionWidgetOptions): void; + /** Set a custom footer component, or undefined to restore the built-in footer. + * + * The factory receives a FooterDataProvider for data not otherwise accessible: + * git branch and extension statuses from setStatus(). Token stats, model info, + * etc. are available via ctx.sessionManager and ctx.model. + */ + setFooter(factory: ((tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => Component & { + dispose?(): void; + }) | undefined): void; + /** Set a custom header component (shown at startup, above chat), or undefined to restore the built-in header. */ + setHeader(factory: ((tui: TUI, theme: Theme) => Component & { + dispose?(): void; + }) | undefined): void; + /** Set the terminal window/tab title. */ + setTitle(title: string): void; + /** Show a custom component with keyboard focus. */ + custom(factory: (tui: TUI, theme: Theme, keybindings: KeybindingsManager, done: (result: T) => void) => (Component & { + dispose?(): void; + }) | Promise, options?: { + overlay?: boolean; + /** Overlay positioning/sizing options. Can be static or a function for dynamic updates. */ + overlayOptions?: OverlayOptions | (() => OverlayOptions); + /** Called with the overlay handle after the overlay is shown. Use to control visibility. */ + onHandle?: (handle: OverlayHandle) => void; + }): Promise; + /** Paste text into the editor, triggering paste handling (collapse for large content). */ + pasteToEditor(text: string): void; + /** Set the text in the core input editor. */ + setEditorText(text: string): void; + /** Get the current text from the core input editor. */ + getEditorText(): string; + /** Show a multi-line editor for text editing. */ + editor(title: string, prefill?: string): Promise; + /** Stack additional autocomplete behavior on top of the built-in provider. */ + addAutocompleteProvider(factory: AutocompleteProviderFactory): void; + /** + * Set a custom editor component via factory function. + * Pass undefined to restore the default editor. + * + * The factory receives: + * - `theme`: EditorTheme for styling borders and autocomplete + * - `keybindings`: KeybindingsManager for app-level keybindings + * + * For full app keybinding support (escape, ctrl+d, model switching, etc.), + * extend `CustomEditor` from `@earendil-works/pi-coding-agent` and call + * `super.handleInput(data)` for keys you don't handle. + * + * @example + * ```ts + * import { CustomEditor } from "@earendil-works/pi-coding-agent"; + * + * class VimEditor extends CustomEditor { + * private mode: "normal" | "insert" = "insert"; + * + * handleInput(data: string): void { + * if (this.mode === "normal") { + * // Handle vim normal mode keys... + * if (data === "i") { this.mode = "insert"; return; } + * } + * super.handleInput(data); // App keybindings + text editing + * } + * } + * + * ctx.ui.setEditorComponent((tui, theme, keybindings) => + * new VimEditor(tui, theme, keybindings) + * ); + * ``` + */ + setEditorComponent(factory: EditorFactory | undefined): void; + /** Get the currently configured custom editor factory, or undefined when using the default editor. */ + getEditorComponent(): EditorFactory | undefined; + /** Get the current theme for styling. */ + readonly theme: Theme; + /** Get all available themes with their names and file paths. */ + getAllThemes(): { + name: string; + path: string | undefined; + }[]; + /** Load a theme by name without switching to it. Returns undefined if not found. */ + getTheme(name: string): Theme | undefined; + /** Set the current theme by name or Theme object. */ + setTheme(theme: string | Theme): { + success: boolean; + error?: string; + }; + /** Get current tool output expansion state. */ + getToolsExpanded(): boolean; + /** Set tool output expansion state. */ + setToolsExpanded(expanded: boolean): void; +} +export interface ContextUsage { + /** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */ + tokens: number | null; + contextWindow: number; + /** Context usage as percentage of context window, or null if tokens is unknown. */ + percent: number | null; +} +export interface CompactOptions { + customInstructions?: string; + onComplete?: (result: CompactionResult) => void; + onError?: (error: Error) => void; +} +/** + * Context passed to extension event handlers. + */ +export type ExtensionMode = "tui" | "rpc" | "json" | "print"; +export interface ExtensionContext { + /** UI methods for user interaction */ + ui: ExtensionUIContext; + /** Current run mode. Use "tui" to guard terminal-only UI such as custom components. */ + mode: ExtensionMode; + /** Whether dialog-capable UI is available (true in TUI and RPC modes) */ + hasUI: boolean; + /** Current working directory */ + cwd: string; + /** Session manager (read-only) */ + sessionManager: ReadonlySessionManager; + /** Model registry for API key resolution */ + modelRegistry: ModelRegistry; + /** Current model (may be undefined) */ + model: Model | undefined; + /** Models scoped to this session (resolved from `--models` / + * `enabledModels` settings against the available catalogue). Same set + * the `/scoped-models` command shows. Empty when no scoping is + * configured (all available models are usable). Read-only snapshot. */ + scopedModels: readonly ScopedModel[]; + /** Current thinking level, when provided by the session runtime. */ + thinkingLevel?: ThinkingLevel; + /** Whether the agent is idle (not streaming) */ + isIdle(): boolean; + /** Whether project-local trust is active for this context. */ + isProjectTrusted(): boolean; + /** The current abort signal, or undefined when the agent is not streaming. */ + signal: AbortSignal | undefined; + /** Abort the current agent operation */ + abort(): void; + /** Whether there are queued messages waiting */ + hasPendingMessages(): boolean; + /** Gracefully shutdown pi and exit. Available in all contexts. */ + shutdown(): void; + /** Get current context usage for the active model. */ + getContextUsage(): ContextUsage | undefined; + /** Trigger compaction without awaiting completion. */ + compact(options?: CompactOptions): void; + /** Get the current effective system prompt. */ + getSystemPrompt(): string; +} +/** + * Extended context for command handlers. + * Includes session control methods only safe in user-initiated commands. + */ +export interface ExtensionCommandContext extends ExtensionContext { + /** Get the current base system-prompt construction options. */ + getSystemPromptOptions(): BuildSystemPromptOptions; + /** Wait for the agent to finish streaming */ + waitForIdle(): Promise; + /** Start a new session, optionally with initialization. */ + newSession(options?: { + parentSession?: string; + setup?: (sessionManager: SessionManager) => Promise; + withSession?: (ctx: ReplacedSessionContext) => Promise; + }): Promise<{ + cancelled: boolean; + }>; + /** Fork from a specific entry, creating a new session file. */ + fork(entryId: string, options?: { + position?: "before" | "at"; + withSession?: (ctx: ReplacedSessionContext) => Promise; + }): Promise<{ + cancelled: boolean; + }>; + /** Navigate to a different point in the session tree. */ + navigateTree(targetId: string, options?: { + summarize?: boolean; + customInstructions?: string; + replaceInstructions?: boolean; + label?: string; + }): Promise<{ + cancelled: boolean; + }>; + /** Switch to a different session file. */ + switchSession(sessionPath: string, options?: { + withSession?: (ctx: ReplacedSessionContext) => Promise; + }): Promise<{ + cancelled: boolean; + }>; + /** Reload extensions, skills, prompts, themes, and context files. */ + reload(): Promise; +} +/** + * Fresh command-capable context bound to the replacement session after a session switch. + * + * This is passed to `withSession()` callbacks on `newSession()`, `fork()`, and `switchSession()`. + */ +export interface ReplacedSessionContext extends ExtensionCommandContext { + sendMessage(message: Pick, "customType" | "content" | "display" | "details">, options?: { + triggerTurn?: boolean; + deliverAs?: "steer" | "followUp" | "nextTurn"; + }): Promise; + sendUserMessage(content: string | (TextContent | ImageContent)[], options?: { + deliverAs?: "steer" | "followUp"; + }): Promise; +} +/** Rendering options for tool results */ +export interface ToolRenderResultOptions { + /** Whether the result view is expanded */ + expanded: boolean; + /** Whether this is a partial/streaming result */ + isPartial: boolean; +} +/** Context passed to tool renderers. */ +export interface ToolRenderContext { + /** Current tool call arguments. Shared across call/result renders for the same tool call. */ + args: TArgs; + /** Unique id for this tool execution. Stable across call/result renders for the same tool call. */ + toolCallId: string; + /** Invalidate just this tool execution component for redraw. */ + invalidate: () => void; + /** Previously returned component for this render slot, if any. */ + lastComponent: Component | undefined; + /** Shared renderer state for this tool row. Initialized by tool-execution.ts. */ + state: TState; + /** Working directory for this tool execution. */ + cwd: string; + /** Whether the tool execution has started. */ + executionStarted: boolean; + /** Whether the tool call arguments are complete. */ + argsComplete: boolean; + /** Whether the tool result is partial/streaming. */ + isPartial: boolean; + /** Whether the result view is expanded. */ + expanded: boolean; + /** Whether inline images are currently shown in the TUI. */ + showImages: boolean; + /** Whether the current result is an error. */ + isError: boolean; +} +/** + * Tool definition for registerTool(). + */ +export interface ToolDefinition { + /** Tool name (used in LLM tool calls) */ + name: string; + /** Human-readable label for UI */ + label: string; + /** Description for LLM */ + description: string; + /** Optional one-line snippet for the Available tools section in the default system prompt. Custom tools are omitted from that section when this is not provided. */ + promptSnippet?: string; + /** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */ + promptGuidelines?: string[]; + /** Parameter schema (TypeBox) */ + parameters: TParams; + /** Optional provider-side constrained sampling request for this tool. Set false to explicitly disable it, equivalent to leaving it undefined. */ + constrainedSampling?: false | ConstrainedSamplingConfig; + /** Controls whether ToolExecutionComponent renders the standard colored shell or the tool renders its own framing. */ + renderShell?: "default" | "self"; + /** Optional compatibility shim to prepare raw tool call arguments before schema validation. Must return an object conforming to TParams. */ + prepareArguments?: (args: unknown) => Static; + /** + * Per-tool execution mode override. + * - "sequential": this tool must execute one at a time with other tool calls. + * - "parallel": this tool can execute concurrently with other tool calls. + * + * If omitted, the default execution mode applies. + */ + executionMode?: ToolExecutionMode; + /** Execute the tool. */ + execute(toolCallId: string, params: Static, signal: AbortSignal | undefined, onUpdate: AgentToolUpdateCallback | undefined, ctx: ExtensionContext): Promise>; + /** Custom rendering for tool call display */ + renderCall?: (args: Static, theme: Theme, context: ToolRenderContext>) => Component; + /** Custom rendering for tool result display */ + renderResult?: (result: AgentToolResult, options: ToolRenderResultOptions, theme: Theme, context: ToolRenderContext>) => Component; +} +type AnyToolDefinition = ToolDefinition; +/** + * Preserve parameter inference for standalone tool definitions. + * + * Use this when assigning a tool to a variable or passing it through arrays such + * as `customTools`, where contextual typing would otherwise widen params to + * `unknown`. + */ +export declare function defineTool(tool: ToolDefinition): ToolDefinition & AnyToolDefinition; +export interface ProjectTrustEvent { + type: "project_trust"; + cwd: string; +} +export type ProjectTrustEventDecision = "yes" | "no" | "undecided"; +export interface ProjectTrustEventResult { + trusted: ProjectTrustEventDecision; + remember?: boolean; +} +export interface ProjectTrustContext { + cwd: string; + mode: ExtensionMode; + hasUI: boolean; + ui: Pick; +} +export type ProjectTrustHandler = (event: ProjectTrustEvent, ctx: ProjectTrustContext) => Promise | ProjectTrustEventResult; +/** Fired after session_start to allow extensions to provide additional resource paths. */ +export interface ResourcesDiscoverEvent { + type: "resources_discover"; + cwd: string; + reason: "startup" | "reload"; +} +/** Result from resources_discover event handler */ +export interface ResourcesDiscoverResult { + skillPaths?: string[]; + promptPaths?: string[]; + themePaths?: string[]; +} +/** Fired when a session is started, loaded, or reloaded */ +export interface SessionStartEvent { + type: "session_start"; + /** Why this session start happened. */ + reason: "startup" | "reload" | "new" | "resume" | "fork"; + /** Previously active session file. Present for "new", "resume", and "fork". */ + previousSessionFile?: string; +} +/** Fired when the current session metadata changes. */ +export interface SessionInfoChangedEvent { + type: "session_info_changed"; + /** Current normalized session name. Undefined when the name is cleared. */ + name: string | undefined; +} +/** Fired before switching to another session (can be cancelled) */ +export interface SessionBeforeSwitchEvent { + type: "session_before_switch"; + reason: "new" | "resume"; + targetSessionFile?: string; +} +/** Fired before forking a session (can be cancelled) */ +export interface SessionBeforeForkEvent { + type: "session_before_fork"; + entryId: string; + position: "before" | "at"; +} +/** Fired before context compaction (can be cancelled or customized) */ +export interface SessionBeforeCompactEvent { + type: "session_before_compact"; + preparation: CompactionPreparation; + branchEntries: SessionEntry[]; + customInstructions?: string; + /** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */ + reason: "manual" | "threshold" | "overflow"; + /** True when the aborted turn is retried after this compaction (overflow recovery) */ + willRetry: boolean; + signal: AbortSignal; +} +/** Fired after context compaction */ +export interface SessionCompactEvent { + type: "session_compact"; + compactionEntry: CompactionEntry; + fromExtension: boolean; + /** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */ + reason: "manual" | "threshold" | "overflow"; + /** True when the aborted turn is retried after this compaction (overflow recovery) */ + willRetry: boolean; +} +/** Fired before an extension runtime is torn down due to quit, reload, or session replacement. */ +export interface SessionShutdownEvent { + type: "session_shutdown"; + reason: "quit" | "reload" | "new" | "resume" | "fork"; + /** Destination session file when shutting down due to session replacement. */ + targetSessionFile?: string; +} +/** Preparation data for tree navigation */ +export interface TreePreparation { + targetId: string; + oldLeafId: string | null; + commonAncestorId: string | null; + entriesToSummarize: SessionEntry[]; + userWantsSummary: boolean; + /** Custom instructions for summarization */ + customInstructions?: string; + /** If true, customInstructions replaces the default prompt instead of being appended */ + replaceInstructions?: boolean; + /** Label to attach to the branch summary entry */ + label?: string; +} +/** Fired before navigating in the session tree (can be cancelled) */ +export interface SessionBeforeTreeEvent { + type: "session_before_tree"; + preparation: TreePreparation; + signal: AbortSignal; +} +/** Fired after navigating in the session tree */ +export interface SessionTreeEvent { + type: "session_tree"; + newLeafId: string | null; + oldLeafId: string | null; + summaryEntry?: BranchSummaryEntry; + fromExtension?: boolean; +} +export type SessionEvent = SessionStartEvent | SessionInfoChangedEvent | SessionBeforeSwitchEvent | SessionBeforeForkEvent | SessionBeforeCompactEvent | SessionCompactEvent | SessionShutdownEvent | SessionBeforeTreeEvent | SessionTreeEvent; +/** Fired before each LLM call. Can modify messages. */ +export interface ContextEvent { + type: "context"; + messages: AgentMessage[]; +} +/** Fired before a provider request is sent. Can replace the payload. */ +export interface BeforeProviderRequestEvent { + type: "before_provider_request"; + payload: unknown; +} +/** + * Fired after request headers are assembled, before the provider HTTP call. + * Handlers mutate `headers` in place (e.g. to inject tracing/session headers); + * the return value is ignored. A `null` value deletes that header. + */ +export interface BeforeProviderHeadersEvent { + type: "before_provider_headers"; + headers: ProviderHeaders; +} +/** Fired after a provider response is received and before the response stream is consumed. */ +export interface AfterProviderResponseEvent { + type: "after_provider_response"; + status: number; + headers: Record; +} +/** Fired after user submits prompt but before agent loop. */ +export interface BeforeAgentStartEvent { + type: "before_agent_start"; + /** The raw user prompt text (after expansion). */ + prompt: string; + /** Images attached to the user prompt, if any. */ + images?: ImageContent[]; + /** The fully assembled system prompt string. */ + systemPrompt: string; + /** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */ + systemPromptOptions: BuildSystemPromptOptions; +} +/** Fired when an agent loop starts */ +export interface AgentStartEvent { + type: "agent_start"; +} +/** Fired when an agent loop ends */ +export interface AgentEndEvent { + type: "agent_end"; + messages: AgentMessage[]; +} +/** Fired after an agent run has fully settled and no automatic retry, compaction, or queued continuation will run. */ +export interface AgentSettledEvent { + type: "agent_settled"; +} +/** Fired at the start of each turn */ +export interface TurnStartEvent { + type: "turn_start"; + turnIndex: number; + timestamp: number; +} +/** Fired at the end of each turn */ +export interface TurnEndEvent { + type: "turn_end"; + turnIndex: number; + message: AgentMessage; + toolResults: ToolResultMessage[]; +} +/** Fired when a message starts (user, assistant, or toolResult) */ +export interface MessageStartEvent { + type: "message_start"; + message: AgentMessage; +} +/** Fired during assistant message streaming with token-by-token updates */ +export interface MessageUpdateEvent { + type: "message_update"; + message: AgentMessage; + assistantMessageEvent: AssistantMessageEvent; +} +/** Fired when a message ends */ +export interface MessageEndEvent { + type: "message_end"; + message: AgentMessage; +} +/** Fired when a tool starts executing */ +export interface ToolExecutionStartEvent { + type: "tool_execution_start"; + toolCallId: string; + toolName: string; + args: any; +} +/** Fired during tool execution with partial/streaming output */ +export interface ToolExecutionUpdateEvent { + type: "tool_execution_update"; + toolCallId: string; + toolName: string; + args: any; + partialResult: any; +} +/** Fired when a tool finishes executing */ +export interface ToolExecutionEndEvent { + type: "tool_execution_end"; + toolCallId: string; + toolName: string; + result: any; + isError: boolean; +} +export type ModelSelectSource = "set" | "cycle" | "restore"; +/** Fired when a new model is selected */ +export interface ModelSelectEvent { + type: "model_select"; + model: Model; + previousModel: Model | undefined; + source: ModelSelectSource; +} +/** Fired when a new thinking level is selected */ +export interface ThinkingLevelSelectEvent { + type: "thinking_level_select"; + level: ThinkingLevel; + previousLevel: ThinkingLevel; +} +/** Fired when user executes a bash command via ! or !! prefix */ +export interface UserBashEvent { + type: "user_bash"; + /** The command to execute */ + command: string; + /** True if !! prefix was used (excluded from LLM context) */ + excludeFromContext: boolean; + /** Current working directory */ + cwd: string; +} +/** Source of user input */ +export type InputSource = "interactive" | "rpc" | "extension"; +/** Fired when user input is received, before agent processing */ +export interface InputEvent { + type: "input"; + /** The input text */ + text: string; + /** Attached images, if any */ + images?: ImageContent[]; + /** Where the input came from */ + source: InputSource; + /** How the input will be delivered during streaming, or undefined when idle */ + streamingBehavior?: "steer" | "followUp"; +} +/** Result from input event handler */ +export type InputEventResult = { + action: "continue"; +} | { + action: "transform"; + text: string; + images?: ImageContent[]; +} | { + action: "handled"; +}; +interface ToolCallEventBase { + type: "tool_call"; + toolCallId: string; +} +export interface BashToolCallEvent extends ToolCallEventBase { + toolName: "bash"; + input: BashToolInput; +} +export interface ReadToolCallEvent extends ToolCallEventBase { + toolName: "read"; + input: ReadToolInput; +} +export interface EditToolCallEvent extends ToolCallEventBase { + toolName: "edit"; + input: EditToolInput; +} +export interface WriteToolCallEvent extends ToolCallEventBase { + toolName: "write"; + input: WriteToolInput; +} +export interface GrepToolCallEvent extends ToolCallEventBase { + toolName: "grep"; + input: GrepToolInput; +} +export interface FindToolCallEvent extends ToolCallEventBase { + toolName: "find"; + input: FindToolInput; +} +export interface LsToolCallEvent extends ToolCallEventBase { + toolName: "ls"; + input: LsToolInput; +} +export interface CustomToolCallEvent extends ToolCallEventBase { + toolName: string; + input: Record; +} +/** + * Fired before a tool executes. Can block. + * + * `event.input` is mutable. Mutate it in place to patch tool arguments before execution. + * Later `tool_call` handlers see earlier mutations. No re-validation is performed after mutation. + */ +export type ToolCallEvent = BashToolCallEvent | ReadToolCallEvent | EditToolCallEvent | WriteToolCallEvent | GrepToolCallEvent | FindToolCallEvent | LsToolCallEvent | CustomToolCallEvent; +interface ToolResultEventBase { + type: "tool_result"; + toolCallId: string; + input: Record; + content: (TextContent | ImageContent)[]; + isError: boolean; + /** Usage from the tool execution itself, if available. */ + usage?: Usage; +} +export interface BashToolResultEvent extends ToolResultEventBase { + toolName: "bash"; + details: BashToolDetails | undefined; +} +export interface ReadToolResultEvent extends ToolResultEventBase { + toolName: "read"; + details: ReadToolDetails | undefined; +} +export interface EditToolResultEvent extends ToolResultEventBase { + toolName: "edit"; + details: EditToolDetails | undefined; +} +export interface WriteToolResultEvent extends ToolResultEventBase { + toolName: "write"; + details: undefined; +} +export interface GrepToolResultEvent extends ToolResultEventBase { + toolName: "grep"; + details: GrepToolDetails | undefined; +} +export interface FindToolResultEvent extends ToolResultEventBase { + toolName: "find"; + details: FindToolDetails | undefined; +} +export interface LsToolResultEvent extends ToolResultEventBase { + toolName: "ls"; + details: LsToolDetails | undefined; +} +export interface CustomToolResultEvent extends ToolResultEventBase { + toolName: string; + details: unknown; +} +/** Fired after a tool executes. Can modify result. */ +export type ToolResultEvent = BashToolResultEvent | ReadToolResultEvent | EditToolResultEvent | WriteToolResultEvent | GrepToolResultEvent | FindToolResultEvent | LsToolResultEvent | CustomToolResultEvent; +export declare function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent; +export declare function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent; +export declare function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent; +export declare function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent; +export declare function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent; +export declare function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent; +export declare function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent; +/** + * Type guard for narrowing ToolCallEvent by tool name. + * + * Built-in tools narrow automatically (no type params needed): + * ```ts + * if (isToolCallEventType("bash", event)) { + * event.input.command; // string + * } + * ``` + * + * Custom tools require explicit type parameters: + * ```ts + * if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) { + * event.input.action; // typed + * } + * ``` + * + * Note: Direct narrowing via `event.toolName === "bash"` doesn't work because + * CustomToolCallEvent.toolName is `string` which overlaps with all literals. + */ +export declare function isToolCallEventType(toolName: "bash", event: ToolCallEvent): event is BashToolCallEvent; +export declare function isToolCallEventType(toolName: "read", event: ToolCallEvent): event is ReadToolCallEvent; +export declare function isToolCallEventType(toolName: "edit", event: ToolCallEvent): event is EditToolCallEvent; +export declare function isToolCallEventType(toolName: "write", event: ToolCallEvent): event is WriteToolCallEvent; +export declare function isToolCallEventType(toolName: "grep", event: ToolCallEvent): event is GrepToolCallEvent; +export declare function isToolCallEventType(toolName: "find", event: ToolCallEvent): event is FindToolCallEvent; +export declare function isToolCallEventType(toolName: "ls", event: ToolCallEvent): event is LsToolCallEvent; +export declare function isToolCallEventType>(toolName: TName, event: ToolCallEvent): event is ToolCallEvent & { + toolName: TName; + input: TInput; +}; +/** Union of all event types */ +export type ExtensionEvent = ProjectTrustEvent | ResourcesDiscoverEvent | SessionEvent | ContextEvent | BeforeProviderRequestEvent | BeforeProviderHeadersEvent | AfterProviderResponseEvent | BeforeAgentStartEvent | AgentStartEvent | AgentEndEvent | AgentSettledEvent | TurnStartEvent | TurnEndEvent | MessageStartEvent | MessageUpdateEvent | MessageEndEvent | ToolExecutionStartEvent | ToolExecutionUpdateEvent | ToolExecutionEndEvent | ModelSelectEvent | ThinkingLevelSelectEvent | UserBashEvent | InputEvent | ToolCallEvent | ToolResultEvent; +export interface ContextEventResult { + messages?: AgentMessage[]; +} +export type BeforeProviderRequestEventResult = unknown; +export interface ToolCallEventResult { + /** Block tool execution. To modify arguments, mutate `event.input` in place instead. */ + block?: boolean; + reason?: string; +} +/** Result from user_bash event handler */ +export interface UserBashEventResult { + /** Custom operations to use for execution */ + operations?: BashOperations; + /** Full replacement: extension handled execution, use this result */ + result?: BashResult; +} +export interface ToolResultEventResult { + content?: (TextContent | ImageContent)[]; + details?: unknown; + isError?: boolean; + usage?: Usage; +} +export interface MessageEndEventResult { + /** Replace the finalized message. The replacement must keep the original message role. */ + message?: AgentMessage; +} +export interface BeforeAgentStartEventResult { + message?: Pick; + /** Replace the system prompt for this turn. If multiple extensions return this, they are chained. */ + systemPrompt?: string; +} +export interface SessionBeforeSwitchResult { + cancel?: boolean; +} +export interface SessionBeforeForkResult { + cancel?: boolean; + skipConversationRestore?: boolean; +} +export interface SessionBeforeCompactResult { + cancel?: boolean; + compaction?: CompactionResult; +} +export interface SessionBeforeTreeResult { + cancel?: boolean; + summary?: { + summary: string; + details?: unknown; + usage?: Usage; + }; + /** Override custom instructions for summarization */ + customInstructions?: string; + /** Override whether customInstructions replaces the default prompt */ + replaceInstructions?: boolean; + /** Override label to attach to the branch summary entry */ + label?: string; +} +export interface MessageRenderOptions { + expanded: boolean; + /** Horizontal padding configured by the outputPad setting. */ + outputPad: number; +} +export interface EntryRenderOptions { + expanded: boolean; +} +export type MessageRenderer = (message: CustomMessage, options: MessageRenderOptions, theme: Theme) => Component | undefined; +export type EntryRenderer = (entry: CustomEntry, options: EntryRenderOptions, theme: Theme) => Component | undefined; +export interface RegisteredCommand { + name: string; + sourceInfo: SourceInfo; + description?: string; + getArgumentCompletions?: (argumentPrefix: string) => AutocompleteItem[] | null | Promise; + handler: (args: string, ctx: ExtensionCommandContext) => Promise; +} +export interface ResolvedCommand extends RegisteredCommand { + invocationName: string; +} +/** Handler function type for events */ +export type ExtensionHandler = (event: E, ctx: ExtensionContext) => Promise | R | void; +/** + * ExtensionAPI passed to extension factory functions. + */ +export interface ExtensionAPI { + on(event: "project_trust", handler: ProjectTrustHandler): void; + on(event: "resources_discover", handler: ExtensionHandler): void; + on(event: "session_start", handler: ExtensionHandler): void; + on(event: "session_info_changed", handler: ExtensionHandler): void; + on(event: "session_before_switch", handler: ExtensionHandler): void; + on(event: "session_before_fork", handler: ExtensionHandler): void; + on(event: "session_before_compact", handler: ExtensionHandler): void; + on(event: "session_compact", handler: ExtensionHandler): void; + on(event: "session_shutdown", handler: ExtensionHandler): void; + on(event: "session_before_tree", handler: ExtensionHandler): void; + on(event: "session_tree", handler: ExtensionHandler): void; + on(event: "context", handler: ExtensionHandler): void; + on(event: "before_provider_request", handler: ExtensionHandler): void; + on(event: "before_provider_headers", handler: ExtensionHandler): void; + on(event: "after_provider_response", handler: ExtensionHandler): void; + on(event: "before_agent_start", handler: ExtensionHandler): void; + on(event: "agent_start", handler: ExtensionHandler): void; + on(event: "agent_end", handler: ExtensionHandler): void; + on(event: "agent_settled", handler: ExtensionHandler): void; + on(event: "turn_start", handler: ExtensionHandler): void; + on(event: "turn_end", handler: ExtensionHandler): void; + on(event: "message_start", handler: ExtensionHandler): void; + on(event: "message_update", handler: ExtensionHandler): void; + on(event: "message_end", handler: ExtensionHandler): void; + on(event: "tool_execution_start", handler: ExtensionHandler): void; + on(event: "tool_execution_update", handler: ExtensionHandler): void; + on(event: "tool_execution_end", handler: ExtensionHandler): void; + on(event: "model_select", handler: ExtensionHandler): void; + on(event: "thinking_level_select", handler: ExtensionHandler): void; + on(event: "tool_call", handler: ExtensionHandler): void; + on(event: "tool_result", handler: ExtensionHandler): void; + on(event: "user_bash", handler: ExtensionHandler): void; + on(event: "input", handler: ExtensionHandler): void; + /** Register a tool that the LLM can call. */ + registerTool(tool: ToolDefinition): void; + /** Register a custom command. */ + registerCommand(name: string, options: Omit): void; + /** Register a keyboard shortcut. */ + registerShortcut(shortcut: KeyId, options: { + description?: string; + handler: (ctx: ExtensionContext) => Promise | void; + }): void; + /** Register a CLI flag. */ + registerFlag(name: string, options: { + description?: string; + type: "boolean" | "string"; + default?: boolean | string; + }): void; + /** Get the value of a registered CLI flag. */ + getFlag(name: string): boolean | string | undefined; + /** Register a custom renderer for CustomMessageEntry. */ + registerMessageRenderer(customType: string, renderer: MessageRenderer): void; + /** Register a custom renderer for CustomEntry. Custom entries do not participate in LLM context. */ + registerEntryRenderer(customType: string, renderer: EntryRenderer): void; + /** Send a custom message to the session. */ + sendMessage(message: Pick, "customType" | "content" | "display" | "details">, options?: { + triggerTurn?: boolean; + deliverAs?: "steer" | "followUp" | "nextTurn"; + }): void; + /** + * Send a user message to the agent. Always triggers a turn. + * When the agent is streaming, use deliverAs to specify how to queue the message. + */ + sendUserMessage(content: string | (TextContent | ImageContent)[], options?: { + deliverAs?: "steer" | "followUp"; + }): void; + /** Append a custom entry to the session for state persistence (not sent to LLM). */ + appendEntry(customType: string, data?: T): void; + /** Set the session display name (shown in session selector). */ + setSessionName(name: string): void; + /** Get the current session name, if set. */ + getSessionName(): string | undefined; + /** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */ + setLabel(entryId: string, label: string | undefined): void; + /** Execute a shell command. */ + exec(command: string, args: string[], options?: ExecOptions): Promise; + /** Get the list of currently active tool names. */ + getActiveTools(): string[]; + /** Get all configured tools with parameter schema, prompt guidelines, and source metadata. */ + getAllTools(): ToolInfo[]; + /** Set the active tools by name. */ + setActiveTools(toolNames: string[]): void; + /** Get available slash commands in the current session. */ + getCommands(): SlashCommandInfo[]; + /** Set the current model. Returns false if no API key available. */ + setModel(model: Model): Promise; + /** Get current thinking level. */ + getThinkingLevel(): ThinkingLevel; + /** Set thinking level (clamped to model capabilities). */ + setThinkingLevel(level: ThinkingLevel): void; + /** + * Register or override a model provider. + * + * If `models` is provided: replaces all existing models for this provider. + * If only `baseUrl` is provided: overrides the URL for existing models. + * If `oauth` is provided: registers OAuth provider for /login support. + * If `streamSimple` is provided: registers a custom API stream handler. + * + * During initial extension load this call is queued and applied once the + * runner has bound its context. After that it takes effect immediately, so + * it is safe to call from command handlers or event callbacks without + * requiring a `/reload`. + * + * @example + * // Register a new provider with custom models + * pi.registerProvider("my-proxy", { + * baseUrl: "https://proxy.example.com", + * apiKey: "$PROXY_API_KEY", + * api: "anthropic-messages", + * models: [ + * { + * id: "claude-sonnet-4-20250514", + * name: "Claude 4 Sonnet (proxy)", + * reasoning: false, + * input: ["text", "image"], + * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + * contextWindow: 200000, + * maxTokens: 16384 + * } + * ] + * }); + * + * @example + * // Override baseUrl for an existing provider + * pi.registerProvider("anthropic", { + * baseUrl: "https://proxy.example.com" + * }); + * + * @example + * // Register provider with OAuth support + * pi.registerProvider("corporate-ai", { + * baseUrl: "https://ai.corp.com", + * api: "openai-responses", + * models: [...], + * oauth: { + * name: "Corporate AI (SSO)", + * async login(callbacks) { ... }, + * async refreshToken(credentials) { ... }, + * getApiKey(credentials) { return credentials.access; } + * } + * }); + */ + registerProvider(provider: Provider): void; + registerProvider(name: string, config: ProviderConfig): void; + /** + * Unregister a previously registered provider. + * + * Removes all models belonging to the named provider and restores any + * built-in models that were overridden by it. Has no effect if the provider + * is not currently registered. + * + * Like `registerProvider`, this takes effect immediately when called after + * the initial load phase. + * + * @example + * pi.unregisterProvider("my-proxy"); + */ + unregisterProvider(name: string): void; + /** Shared event bus for extension communication. */ + events: EventBus; +} +/** Configuration for registering a provider via pi.registerProvider(). */ +export interface ProviderConfig { + /** Display name for the provider in UI. */ + name?: string; + /** Base URL for the API endpoint. Required when defining models. */ + baseUrl?: string; + /** API key literal, env interpolation ($ENV_VAR or ${ENV_VAR}), or leading !command. Required when defining models (unless oauth provided). */ + apiKey?: string; + /** API type. Required at provider or model level when defining models. */ + api?: Api; + /** Optional streamSimple handler for custom APIs. */ + streamSimple?: (model: Model, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream; + /** Custom headers to include in requests. */ + headers?: Record; + /** If true, adds Authorization: Bearer header with the resolved API key. */ + authHeader?: boolean; + /** Models to register. If provided, replaces all existing models for this provider. */ + models?: ProviderModelConfig[]; + /** + * Refresh this provider's model list. The returned list replaces extension-provided models. + * Use context.store explicitly when the catalog should persist across sessions. + */ + refreshModels?(context: RefreshModelsContext): Promise; + /** OAuth provider for /login support. The `id` is set automatically from the provider name. */ + oauth?: { + /** Display name for the provider in login UI. */ + name: string; + /** @deprecated Retained for source compatibility; canonical auth flows ignore it. */ + usesCallbackServer?: boolean; + /** Run the login flow, return credentials to persist. */ + login(callbacks: OAuthLoginCallbacks): Promise; + /** Refresh expired credentials, return updated credentials to persist. */ + refreshToken(credentials: OAuthCredentials): Promise; + /** Convert credentials to API key string for the provider. */ + getApiKey(credentials: OAuthCredentials): string; + /** Legacy synchronous credential-dependent model projection. */ + modifyModels?(models: Model[], credentials: OAuthCredentials): Model[]; + }; +} +/** Configuration for a model within a provider. */ +export interface ProviderModelConfig { + /** Model ID (e.g., "claude-sonnet-4-20250514"). */ + id: string; + /** Display name (e.g., "Claude 4 Sonnet"). */ + name: string; + /** API type override for this model. */ + api?: Api; + /** API endpoint URL override for this model. */ + baseUrl?: string; + /** Whether the model supports extended thinking. */ + reasoning: boolean; + /** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */ + thinkingLevelMap?: Model["thinkingLevelMap"]; + /** Supported input types. */ + input: ("text" | "image")[]; + /** Per-million-token cost rates and optional request-wide input pricing tiers. */ + cost: Model["cost"]; + /** Maximum context window size in tokens. */ + contextWindow: number; + /** Maximum output tokens. */ + maxTokens: number; + /** Custom headers for this model. */ + headers?: Record; + /** OpenAI compatibility settings. */ + compat?: Model["compat"]; +} +/** Extension factory function type. Supports both sync and async initialization. */ +export type ExtensionFactory = (pi: ExtensionAPI) => void | Promise; +export type InlineExtension = ExtensionFactory | { + /** Display name shown as `` in the startup Extensions list. */ + name: string; + factory: ExtensionFactory; + /** Omit this extension from the startup Extensions list. */ + hidden?: boolean; +}; +export interface RegisteredTool { + definition: ToolDefinition; + sourceInfo: SourceInfo; +} +export interface ExtensionFlag { + name: string; + description?: string; + type: "boolean" | "string"; + default?: boolean | string; + extensionPath: string; +} +export interface ExtensionShortcut { + shortcut: KeyId; + description?: string; + handler: (ctx: ExtensionContext) => Promise | void; + extensionPath: string; +} +type HandlerFn = (...args: unknown[]) => Promise; +export type SendMessageHandler = (message: Pick, "customType" | "content" | "display" | "details">, options?: { + triggerTurn?: boolean; + deliverAs?: "steer" | "followUp" | "nextTurn"; +}) => void; +export type SendUserMessageHandler = (content: string | (TextContent | ImageContent)[], options?: { + deliverAs?: "steer" | "followUp"; +}) => void; +export type AppendEntryHandler = (customType: string, data?: T) => void; +export type SetSessionNameHandler = (name: string) => void; +export type GetSessionNameHandler = () => string | undefined; +export type GetActiveToolsHandler = () => string[]; +/** Tool info with name, description, parameter schema, prompt guidelines, and source metadata. */ +export type ToolInfo = Pick & { + sourceInfo: SourceInfo; +}; +export type GetAllToolsHandler = () => ToolInfo[]; +export type GetCommandsHandler = () => SlashCommandInfo[]; +export type SetActiveToolsHandler = (toolNames: string[]) => void; +export type RefreshToolsHandler = () => void; +export type SetModelHandler = (model: Model) => Promise; +export type GetThinkingLevelHandler = () => ThinkingLevel; +export type SetThinkingLevelHandler = (level: ThinkingLevel) => void; +export type SetLabelHandler = (entryId: string, label: string | undefined) => void; +/** + * Shared state created by loader, used during registration and runtime. + * Contains flag values (defaults set during registration, CLI values set after). + */ +export interface ExtensionRuntimeState { + flagValues: Map; + /** Legacy provider-config registrations queued during extension loading, processed when runner binds. */ + pendingProviderRegistrations: Array<{ + name: string; + config: ProviderConfig; + extensionPath: string; + }>; + /** Native pi-ai provider registrations queued during extension loading, processed when runner binds. */ + pendingNativeProviderRegistrations: Array<{ + provider: Provider; + extensionPath: string; + }>; + /** Throws when this extension instance is stale after runtime replacement. */ + assertActive: () => void; + /** Marks this extension instance as stale after runtime replacement or reload. */ + invalidate: (message?: string) => void; + /** + * Register or unregister a provider. + * + * Before bindCore(): queues registrations / removes from queue. + * After bindCore(): calls ModelRegistry directly for immediate effect. + */ + registerProvider: (name: string, config: ProviderConfig, extensionPath?: string) => void; + registerNativeProvider: (provider: Provider, extensionPath?: string) => void; + unregisterProvider: (name: string, extensionPath?: string) => void; +} +/** + * Action implementations for pi.* API methods. + * Provided to runner.initialize(), copied into the shared runtime. + */ +export interface ExtensionActions { + sendMessage: SendMessageHandler; + sendUserMessage: SendUserMessageHandler; + appendEntry: AppendEntryHandler; + setSessionName: SetSessionNameHandler; + getSessionName: GetSessionNameHandler; + setLabel: SetLabelHandler; + getActiveTools: GetActiveToolsHandler; + getAllTools: GetAllToolsHandler; + setActiveTools: SetActiveToolsHandler; + refreshTools: RefreshToolsHandler; + getCommands: GetCommandsHandler; + setModel: SetModelHandler; + getThinkingLevel: GetThinkingLevelHandler; + setThinkingLevel: SetThinkingLevelHandler; +} +/** + * Actions for ExtensionContext (ctx.* in event handlers). + * Required by all modes. + */ +export interface ExtensionContextActions { + getModel: () => Model | undefined; + getScopedModels: () => readonly ScopedModel[]; + isIdle: () => boolean; + isProjectTrusted: () => boolean; + getSignal: () => AbortSignal | undefined; + abort: () => void; + hasPendingMessages: () => boolean; + shutdown: () => void; + getContextUsage: () => ContextUsage | undefined; + compact: (options?: CompactOptions) => void; + getSystemPrompt: () => string; + getSystemPromptOptions?: () => BuildSystemPromptOptions; +} +/** + * Actions for ExtensionCommandContext (ctx.* in command handlers). + * Only needed for interactive mode where extension commands are invokable. + */ +export interface ExtensionCommandContextActions { + waitForIdle: () => Promise; + newSession: (options?: { + parentSession?: string; + setup?: (sessionManager: SessionManager) => Promise; + withSession?: (ctx: ReplacedSessionContext) => Promise; + }) => Promise<{ + cancelled: boolean; + }>; + fork: (entryId: string, options?: { + position?: "before" | "at"; + withSession?: (ctx: ReplacedSessionContext) => Promise; + }) => Promise<{ + cancelled: boolean; + }>; + navigateTree: (targetId: string, options?: { + summarize?: boolean; + customInstructions?: string; + replaceInstructions?: boolean; + label?: string; + }) => Promise<{ + cancelled: boolean; + }>; + switchSession: (sessionPath: string, options?: { + withSession?: (ctx: ReplacedSessionContext) => Promise; + }) => Promise<{ + cancelled: boolean; + }>; + reload: () => Promise; +} +/** + * Full runtime = state + actions. + * Created by loader with throwing action stubs, completed by runner.initialize(). + */ +export interface ExtensionRuntime extends ExtensionRuntimeState, ExtensionActions { +} +/** Loaded extension with all registered items. */ +export interface Extension { + path: string; + resolvedPath: string; + hidden?: boolean; + sourceInfo: SourceInfo; + handlers: Map; + tools: Map; + messageRenderers: Map; + entryRenderers?: Map; + commands: Map; + flags: Map; + shortcuts: Map; +} +/** Result of loading extensions. */ +export interface LoadExtensionsResult { + extensions: Extension[]; + errors: Array<{ + path: string; + error: string; + }>; + /** Shared runtime - actions are throwing stubs until runner.initialize() */ + runtime: ExtensionRuntime; +} +export interface ExtensionError { + extensionPath: string; + event: string; + error: string; + stack?: string; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/core/extensions/types.d.ts.map b/dist/core/extensions/types.d.ts.map new file mode 100644 index 0000000..9c9eba9 --- /dev/null +++ b/dist/core/extensions/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EACX,YAAY,EACZ,eAAe,EACf,uBAAuB,EACvB,aAAa,EACb,iBAAiB,EACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EACX,GAAG,EACH,qBAAqB,EACrB,2BAA2B,EAC3B,yBAAyB,EACzB,OAAO,EACP,YAAY,EACZ,KAAK,EACL,gBAAgB,EAChB,mBAAmB,EACnB,QAAQ,EACR,eAAe,EACf,oBAAoB,EACpB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,KAAK,EACL,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EACX,gBAAgB,EAChB,oBAAoB,EACpB,SAAS,EACT,eAAe,EACf,WAAW,EACX,KAAK,EACL,aAAa,EACb,cAAc,EACd,GAAG,EACH,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,KAAK,EAAE,KA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E,cAAc,CAAC,CAAC;IACnC,gBAAgB,EAAE,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAC/C,cAAc,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC5C,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;IACzC,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAClC,SAAS,EAAE,GAAG,CAAC,KAAK,EAAE,iBAAiB,CAAC,CAAC;CACzC;AAED,oCAAoC;AACpC,MAAM,WAAW,oBAAoB;IACpC,UAAU,EAAE,SAAS,EAAE,CAAC;IACxB,MAAM,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC/C,4EAA4E;IAC5E,OAAO,EAAE,gBAAgB,CAAC;CAC1B;AAMD,MAAM,WAAW,cAAc;IAC9B,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;CACf","sourcesContent":["/**\n * Extension system types.\n *\n * Extensions are TypeScript modules that can:\n * - Subscribe to agent lifecycle events\n * - Register LLM-callable tools\n * - Register commands, keyboard shortcuts, and CLI flags\n * - Interact with the user via UI primitives\n */\n\nimport type {\n\tAgentMessage,\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n\tThinkingLevel,\n\tToolExecutionMode,\n} from \"@earendil-works/pi-agent-core\";\nimport type {\n\tApi,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tConstrainedSamplingConfig,\n\tContext,\n\tImageContent,\n\tModel,\n\tOAuthCredentials,\n\tOAuthLoginCallbacks,\n\tProvider,\n\tProviderHeaders,\n\tRefreshModelsContext,\n\tSimpleStreamOptions,\n\tTextContent,\n\tToolResultMessage,\n\tUsage,\n} from \"@earendil-works/pi-ai\";\nimport type {\n\tAutocompleteItem,\n\tAutocompleteProvider,\n\tComponent,\n\tEditorComponent,\n\tEditorTheme,\n\tKeyId,\n\tOverlayHandle,\n\tOverlayOptions,\n\tTUI,\n} from \"@earendil-works/pi-tui\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { BashResult } from \"../bash-executor.ts\";\nimport type { CompactionPreparation, CompactionResult } from \"../compaction/index.ts\";\nimport type { EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions, ExecResult } from \"../exec.ts\";\nimport type { ReadonlyFooterDataProvider } from \"../footer-data-provider.ts\";\nimport type { KeybindingsManager } from \"../keybindings.ts\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type { ScopedModel } from \"../model-resolver.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tCustomEntry,\n\tReadonlySessionManager,\n\tSessionEntry,\n\tSessionManager,\n} from \"../session-manager.ts\";\nimport type { SlashCommandInfo } from \"../slash-commands.ts\";\nimport type { SourceInfo } from \"../source-info.ts\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { BashOperations } from \"../tools/bash.ts\";\nimport type { EditToolDetails } from \"../tools/edit.ts\";\nimport type {\n\tBashToolDetails,\n\tBashToolInput,\n\tEditToolInput,\n\tFindToolDetails,\n\tFindToolInput,\n\tGrepToolDetails,\n\tGrepToolInput,\n\tLsToolDetails,\n\tLsToolInput,\n\tReadToolDetails,\n\tReadToolInput,\n\tWriteToolInput,\n} from \"../tools/index.ts\";\n\nexport type { ExecOptions, ExecResult } from \"../exec.ts\";\nexport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nexport type { AgentToolResult, AgentToolUpdateCallback, ToolExecutionMode };\nexport type { AppKeybinding, KeybindingsManager } from \"../keybindings.ts\";\n\n// ============================================================================\n// UI Context\n// ============================================================================\n\n/** Options for extension UI dialogs. */\nexport interface ExtensionUIDialogOptions {\n\t/** AbortSignal to programmatically dismiss the dialog. */\n\tsignal?: AbortSignal;\n\t/** Timeout in milliseconds. Dialog auto-dismisses with live countdown display. */\n\ttimeout?: number;\n}\n\n/** Placement for extension widgets. */\nexport type WidgetPlacement = \"aboveEditor\" | \"belowEditor\";\n\n/** Options for extension widgets. */\nexport interface ExtensionWidgetOptions {\n\t/** Where the widget is rendered. Defaults to \"aboveEditor\". */\n\tplacement?: WidgetPlacement;\n}\n\n/** Raw terminal input listener for extensions. */\nexport type TerminalInputHandler = (data: string) => { consume?: boolean; data?: string } | undefined;\n\n/** Working indicator configuration for the interactive streaming loader. */\nexport interface WorkingIndicatorOptions {\n\t/** Animation frames. Use an empty array to hide the indicator entirely. Custom frames are rendered verbatim. */\n\tframes?: string[];\n\t/** Frame interval in milliseconds for animated indicators. */\n\tintervalMs?: number;\n}\n\n/** Wrap the current autocomplete provider with additional behavior. */\nexport type AutocompleteProviderFactory = (current: AutocompleteProvider) => AutocompleteProvider;\nexport type EditorFactory = (tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) => EditorComponent;\n\n/**\n * UI context for extensions to request interactive UI.\n * Each mode (interactive, RPC, print) provides its own implementation.\n */\nexport interface ExtensionUIContext {\n\t/** Show a selector and return the user's choice. */\n\tselect(title: string, options: string[], opts?: ExtensionUIDialogOptions): Promise;\n\n\t/** Show a confirmation dialog. */\n\tconfirm(title: string, message: string, opts?: ExtensionUIDialogOptions): Promise;\n\n\t/** Show a text input dialog. */\n\tinput(title: string, placeholder?: string, opts?: ExtensionUIDialogOptions): Promise;\n\n\t/** Show a notification to the user. */\n\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\n\t/** Listen to raw terminal input (interactive mode only). Returns an unsubscribe function. */\n\tonTerminalInput(handler: TerminalInputHandler): () => void;\n\n\t/** Set status text in the footer/status bar. Pass undefined to clear. */\n\tsetStatus(key: string, text: string | undefined): void;\n\n\t/** Set the working/loading message shown during streaming. Call with no argument to restore default. */\n\tsetWorkingMessage(message?: string): void;\n\n\t/** Show or hide the built-in interactive working loader row during streaming. */\n\tsetWorkingVisible(visible: boolean): void;\n\n\t/**\n\t * Configure the interactive working indicator shown during streaming.\n\t *\n\t * - Omit the argument to restore the default animated spinner.\n\t * - Use `frames: [\"●\"]` for a static indicator.\n\t * - Use `frames: []` to hide the indicator entirely.\n\t * - Custom frames are rendered as provided, so extensions must add their own colors.\n\t */\n\tsetWorkingIndicator(options?: WorkingIndicatorOptions): void;\n\n\t/** Set the label shown for hidden thinking blocks. Call with no argument to restore default. */\n\tsetHiddenThinkingLabel(label?: string): void;\n\n\t/** Set a widget to display above or below the editor. Accepts string array or component factory. */\n\tsetWidget(key: string, content: string[] | undefined, options?: ExtensionWidgetOptions): void;\n\tsetWidget(\n\t\tkey: string,\n\t\tcontent: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined,\n\t\toptions?: ExtensionWidgetOptions,\n\t): void;\n\n\t/** Set a custom footer component, or undefined to restore the built-in footer.\n\t *\n\t * The factory receives a FooterDataProvider for data not otherwise accessible:\n\t * git branch and extension statuses from setStatus(). Token stats, model info,\n\t * etc. are available via ctx.sessionManager and ctx.model.\n\t */\n\tsetFooter(\n\t\tfactory:\n\t\t\t| ((tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => Component & { dispose?(): void })\n\t\t\t| undefined,\n\t): void;\n\n\t/** Set a custom header component (shown at startup, above chat), or undefined to restore the built-in header. */\n\tsetHeader(factory: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined): void;\n\n\t/** Set the terminal window/tab title. */\n\tsetTitle(title: string): void;\n\n\t/** Show a custom component with keyboard focus. */\n\tcustom(\n\t\tfactory: (\n\t\t\ttui: TUI,\n\t\t\ttheme: Theme,\n\t\t\tkeybindings: KeybindingsManager,\n\t\t\tdone: (result: T) => void,\n\t\t) => (Component & { dispose?(): void }) | Promise,\n\t\toptions?: {\n\t\t\toverlay?: boolean;\n\t\t\t/** Overlay positioning/sizing options. Can be static or a function for dynamic updates. */\n\t\t\toverlayOptions?: OverlayOptions | (() => OverlayOptions);\n\t\t\t/** Called with the overlay handle after the overlay is shown. Use to control visibility. */\n\t\t\tonHandle?: (handle: OverlayHandle) => void;\n\t\t},\n\t): Promise;\n\n\t/** Paste text into the editor, triggering paste handling (collapse for large content). */\n\tpasteToEditor(text: string): void;\n\n\t/** Set the text in the core input editor. */\n\tsetEditorText(text: string): void;\n\n\t/** Get the current text from the core input editor. */\n\tgetEditorText(): string;\n\n\t/** Show a multi-line editor for text editing. */\n\teditor(title: string, prefill?: string): Promise;\n\n\t/** Stack additional autocomplete behavior on top of the built-in provider. */\n\taddAutocompleteProvider(factory: AutocompleteProviderFactory): void;\n\n\t/**\n\t * Set a custom editor component via factory function.\n\t * Pass undefined to restore the default editor.\n\t *\n\t * The factory receives:\n\t * - `theme`: EditorTheme for styling borders and autocomplete\n\t * - `keybindings`: KeybindingsManager for app-level keybindings\n\t *\n\t * For full app keybinding support (escape, ctrl+d, model switching, etc.),\n\t * extend `CustomEditor` from `@earendil-works/pi-coding-agent` and call\n\t * `super.handleInput(data)` for keys you don't handle.\n\t *\n\t * @example\n\t * ```ts\n\t * import { CustomEditor } from \"@earendil-works/pi-coding-agent\";\n\t *\n\t * class VimEditor extends CustomEditor {\n\t * private mode: \"normal\" | \"insert\" = \"insert\";\n\t *\n\t * handleInput(data: string): void {\n\t * if (this.mode === \"normal\") {\n\t * // Handle vim normal mode keys...\n\t * if (data === \"i\") { this.mode = \"insert\"; return; }\n\t * }\n\t * super.handleInput(data); // App keybindings + text editing\n\t * }\n\t * }\n\t *\n\t * ctx.ui.setEditorComponent((tui, theme, keybindings) =>\n\t * new VimEditor(tui, theme, keybindings)\n\t * );\n\t * ```\n\t */\n\tsetEditorComponent(factory: EditorFactory | undefined): void;\n\n\t/** Get the currently configured custom editor factory, or undefined when using the default editor. */\n\tgetEditorComponent(): EditorFactory | undefined;\n\n\t/** Get the current theme for styling. */\n\treadonly theme: Theme;\n\n\t/** Get all available themes with their names and file paths. */\n\tgetAllThemes(): { name: string; path: string | undefined }[];\n\n\t/** Load a theme by name without switching to it. Returns undefined if not found. */\n\tgetTheme(name: string): Theme | undefined;\n\n\t/** Set the current theme by name or Theme object. */\n\tsetTheme(theme: string | Theme): { success: boolean; error?: string };\n\n\t/** Get current tool output expansion state. */\n\tgetToolsExpanded(): boolean;\n\n\t/** Set tool output expansion state. */\n\tsetToolsExpanded(expanded: boolean): void;\n}\n\n// ============================================================================\n// Extension Context\n// ============================================================================\n\nexport interface ContextUsage {\n\t/** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */\n\ttokens: number | null;\n\tcontextWindow: number;\n\t/** Context usage as percentage of context window, or null if tokens is unknown. */\n\tpercent: number | null;\n}\n\nexport interface CompactOptions {\n\tcustomInstructions?: string;\n\tonComplete?: (result: CompactionResult) => void;\n\tonError?: (error: Error) => void;\n}\n\n/**\n * Context passed to extension event handlers.\n */\nexport type ExtensionMode = \"tui\" | \"rpc\" | \"json\" | \"print\";\n\nexport interface ExtensionContext {\n\t/** UI methods for user interaction */\n\tui: ExtensionUIContext;\n\t/** Current run mode. Use \"tui\" to guard terminal-only UI such as custom components. */\n\tmode: ExtensionMode;\n\t/** Whether dialog-capable UI is available (true in TUI and RPC modes) */\n\thasUI: boolean;\n\t/** Current working directory */\n\tcwd: string;\n\t/** Session manager (read-only) */\n\tsessionManager: ReadonlySessionManager;\n\t/** Model registry for API key resolution */\n\tmodelRegistry: ModelRegistry;\n\t/** Current model (may be undefined) */\n\tmodel: Model | undefined;\n\t/** Models scoped to this session (resolved from `--models` /\n\t * `enabledModels` settings against the available catalogue). Same set\n\t * the `/scoped-models` command shows. Empty when no scoping is\n\t * configured (all available models are usable). Read-only snapshot. */\n\tscopedModels: readonly ScopedModel[];\n\t/** Current thinking level, when provided by the session runtime. */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Whether the agent is idle (not streaming) */\n\tisIdle(): boolean;\n\t/** Whether project-local trust is active for this context. */\n\tisProjectTrusted(): boolean;\n\t/** The current abort signal, or undefined when the agent is not streaming. */\n\tsignal: AbortSignal | undefined;\n\t/** Abort the current agent operation */\n\tabort(): void;\n\t/** Whether there are queued messages waiting */\n\thasPendingMessages(): boolean;\n\t/** Gracefully shutdown pi and exit. Available in all contexts. */\n\tshutdown(): void;\n\t/** Get current context usage for the active model. */\n\tgetContextUsage(): ContextUsage | undefined;\n\t/** Trigger compaction without awaiting completion. */\n\tcompact(options?: CompactOptions): void;\n\t/** Get the current effective system prompt. */\n\tgetSystemPrompt(): string;\n}\n\n/**\n * Extended context for command handlers.\n * Includes session control methods only safe in user-initiated commands.\n */\nexport interface ExtensionCommandContext extends ExtensionContext {\n\t/** Get the current base system-prompt construction options. */\n\tgetSystemPromptOptions(): BuildSystemPromptOptions;\n\n\t/** Wait for the agent to finish streaming */\n\twaitForIdle(): Promise;\n\n\t/** Start a new session, optionally with initialization. */\n\tnewSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/** Fork from a specific entry, creating a new session file. */\n\tfork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Navigate to a different point in the session tree. */\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Switch to a different session file. */\n\tswitchSession(\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Reload extensions, skills, prompts, themes, and context files. */\n\treload(): Promise;\n}\n\n/**\n * Fresh command-capable context bound to the replacement session after a session switch.\n *\n * This is passed to `withSession()` callbacks on `newSession()`, `fork()`, and `switchSession()`.\n */\nexport interface ReplacedSessionContext extends ExtensionCommandContext {\n\tsendMessage(\n\t\tmessage: Pick, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n\t): Promise;\n\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): Promise;\n}\n\n// ============================================================================\n// Tool Types\n// ============================================================================\n\n/** Rendering options for tool results */\nexport interface ToolRenderResultOptions {\n\t/** Whether the result view is expanded */\n\texpanded: boolean;\n\t/** Whether this is a partial/streaming result */\n\tisPartial: boolean;\n}\n\n/** Context passed to tool renderers. */\nexport interface ToolRenderContext {\n\t/** Current tool call arguments. Shared across call/result renders for the same tool call. */\n\targs: TArgs;\n\t/** Unique id for this tool execution. Stable across call/result renders for the same tool call. */\n\ttoolCallId: string;\n\t/** Invalidate just this tool execution component for redraw. */\n\tinvalidate: () => void;\n\t/** Previously returned component for this render slot, if any. */\n\tlastComponent: Component | undefined;\n\t/** Shared renderer state for this tool row. Initialized by tool-execution.ts. */\n\tstate: TState;\n\t/** Working directory for this tool execution. */\n\tcwd: string;\n\t/** Whether the tool execution has started. */\n\texecutionStarted: boolean;\n\t/** Whether the tool call arguments are complete. */\n\targsComplete: boolean;\n\t/** Whether the tool result is partial/streaming. */\n\tisPartial: boolean;\n\t/** Whether the result view is expanded. */\n\texpanded: boolean;\n\t/** Whether inline images are currently shown in the TUI. */\n\tshowImages: boolean;\n\t/** Whether the current result is an error. */\n\tisError: boolean;\n}\n\n/**\n * Tool definition for registerTool().\n */\nexport interface ToolDefinition {\n\t/** Tool name (used in LLM tool calls) */\n\tname: string;\n\t/** Human-readable label for UI */\n\tlabel: string;\n\t/** Description for LLM */\n\tdescription: string;\n\t/** Optional one-line snippet for the Available tools section in the default system prompt. Custom tools are omitted from that section when this is not provided. */\n\tpromptSnippet?: string;\n\t/** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */\n\tpromptGuidelines?: string[];\n\t/** Parameter schema (TypeBox) */\n\tparameters: TParams;\n\t/** Optional provider-side constrained sampling request for this tool. Set false to explicitly disable it, equivalent to leaving it undefined. */\n\tconstrainedSampling?: false | ConstrainedSamplingConfig;\n\t/** Controls whether ToolExecutionComponent renders the standard colored shell or the tool renders its own framing. */\n\trenderShell?: \"default\" | \"self\";\n\n\t/** Optional compatibility shim to prepare raw tool call arguments before schema validation. Must return an object conforming to TParams. */\n\tprepareArguments?: (args: unknown) => Static;\n\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n\n\t/** Execute the tool. */\n\texecute(\n\t\ttoolCallId: string,\n\t\tparams: Static,\n\t\tsignal: AbortSignal | undefined,\n\t\tonUpdate: AgentToolUpdateCallback | undefined,\n\t\tctx: ExtensionContext,\n\t): Promise>;\n\n\t/** Custom rendering for tool call display */\n\trenderCall?: (args: Static, theme: Theme, context: ToolRenderContext>) => Component;\n\n\t/** Custom rendering for tool result display */\n\trenderResult?: (\n\t\tresult: AgentToolResult,\n\t\toptions: ToolRenderResultOptions,\n\t\ttheme: Theme,\n\t\tcontext: ToolRenderContext>,\n\t) => Component;\n}\n\ntype AnyToolDefinition = ToolDefinition;\n\n/**\n * Preserve parameter inference for standalone tool definitions.\n *\n * Use this when assigning a tool to a variable or passing it through arrays such\n * as `customTools`, where contextual typing would otherwise widen params to\n * `unknown`.\n */\nexport function defineTool(\n\ttool: ToolDefinition,\n): ToolDefinition & AnyToolDefinition {\n\treturn tool as ToolDefinition & AnyToolDefinition;\n}\n\n// ============================================================================\n// Startup/Resource Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise | ProjectTrustEventResult;\n\n/** Fired after session_start to allow extensions to provide additional resource paths. */\nexport interface ResourcesDiscoverEvent {\n\ttype: \"resources_discover\";\n\tcwd: string;\n\treason: \"startup\" | \"reload\";\n}\n\n/** Result from resources_discover event handler */\nexport interface ResourcesDiscoverResult {\n\tskillPaths?: string[];\n\tpromptPaths?: string[];\n\tthemePaths?: string[];\n}\n\n// ============================================================================\n// Session Events\n// ============================================================================\n\n/** Fired when a session is started, loaded, or reloaded */\nexport interface SessionStartEvent {\n\ttype: \"session_start\";\n\t/** Why this session start happened. */\n\treason: \"startup\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\t/** Previously active session file. Present for \"new\", \"resume\", and \"fork\". */\n\tpreviousSessionFile?: string;\n}\n\n/** Fired when the current session metadata changes. */\nexport interface SessionInfoChangedEvent {\n\ttype: \"session_info_changed\";\n\t/** Current normalized session name. Undefined when the name is cleared. */\n\tname: string | undefined;\n}\n\n/** Fired before switching to another session (can be cancelled) */\nexport interface SessionBeforeSwitchEvent {\n\ttype: \"session_before_switch\";\n\treason: \"new\" | \"resume\";\n\ttargetSessionFile?: string;\n}\n\n/** Fired before forking a session (can be cancelled) */\nexport interface SessionBeforeForkEvent {\n\ttype: \"session_before_fork\";\n\tentryId: string;\n\tposition: \"before\" | \"at\";\n}\n\n/** Fired before context compaction (can be cancelled or customized) */\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\tpreparation: CompactionPreparation;\n\tbranchEntries: SessionEntry[];\n\tcustomInstructions?: string;\n\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** True when the aborted turn is retried after this compaction (overflow recovery) */\n\twillRetry: boolean;\n\tsignal: AbortSignal;\n}\n\n/** Fired after context compaction */\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\tfromExtension: boolean;\n\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** True when the aborted turn is retried after this compaction (overflow recovery) */\n\twillRetry: boolean;\n}\n\n/** Fired before an extension runtime is torn down due to quit, reload, or session replacement. */\nexport interface SessionShutdownEvent {\n\ttype: \"session_shutdown\";\n\treason: \"quit\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\t/** Destination session file when shutting down due to session replacement. */\n\ttargetSessionFile?: string;\n}\n\n/** Preparation data for tree navigation */\nexport interface TreePreparation {\n\ttargetId: string;\n\toldLeafId: string | null;\n\tcommonAncestorId: string | null;\n\tentriesToSummarize: SessionEntry[];\n\tuserWantsSummary: boolean;\n\t/** Custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Label to attach to the branch summary entry */\n\tlabel?: string;\n}\n\n/** Fired before navigating in the session tree (can be cancelled) */\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\tpreparation: TreePreparation;\n\tsignal: AbortSignal;\n}\n\n/** Fired after navigating in the session tree */\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\tnewLeafId: string | null;\n\toldLeafId: string | null;\n\tsummaryEntry?: BranchSummaryEntry;\n\tfromExtension?: boolean;\n}\n\nexport type SessionEvent =\n\t| SessionStartEvent\n\t| SessionInfoChangedEvent\n\t| SessionBeforeSwitchEvent\n\t| SessionBeforeForkEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionShutdownEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent;\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/** Fired before each LLM call. Can modify messages. */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/**\n * Fired after request headers are assembled, before the provider HTTP call.\n * Handlers mutate `headers` in place (e.g. to inject tracing/session headers);\n * the return value is ignored. A `null` value deletes that header.\n */\nexport interface BeforeProviderHeadersEvent {\n\ttype: \"before_provider_headers\";\n\theaders: ProviderHeaders;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The fully assembled system prompt string. */\n\tsystemPrompt: string;\n\t/** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */\n\tsystemPromptOptions: BuildSystemPromptOptions;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired after an agent run has fully settled and no automatic retry, compaction, or queued continuation will run. */\nexport interface AgentSettledEvent {\n\ttype: \"agent_settled\";\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: any;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: any;\n\tpartialResult: any;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: any;\n\tisError: boolean;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model;\n\tpreviousModel: Model | undefined;\n\tsource: ModelSelectSource;\n}\n\n/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n\t/** How the input will be delivered during streaming, or undefined when idle */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n\n// ============================================================================\n// Tool Events\n// ============================================================================\n\ninterface ToolCallEventBase {\n\ttype: \"tool_call\";\n\ttoolCallId: string;\n}\n\nexport interface BashToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"bash\";\n\tinput: BashToolInput;\n}\n\nexport interface ReadToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"read\";\n\tinput: ReadToolInput;\n}\n\nexport interface EditToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"edit\";\n\tinput: EditToolInput;\n}\n\nexport interface WriteToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"write\";\n\tinput: WriteToolInput;\n}\n\nexport interface GrepToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"grep\";\n\tinput: GrepToolInput;\n}\n\nexport interface FindToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"find\";\n\tinput: FindToolInput;\n}\n\nexport interface LsToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"ls\";\n\tinput: LsToolInput;\n}\n\nexport interface CustomToolCallEvent extends ToolCallEventBase {\n\ttoolName: string;\n\tinput: Record;\n}\n\n/**\n * Fired before a tool executes. Can block.\n *\n * `event.input` is mutable. Mutate it in place to patch tool arguments before execution.\n * Later `tool_call` handlers see earlier mutations. No re-validation is performed after mutation.\n */\nexport type ToolCallEvent =\n\t| BashToolCallEvent\n\t| ReadToolCallEvent\n\t| EditToolCallEvent\n\t| WriteToolCallEvent\n\t| GrepToolCallEvent\n\t| FindToolCallEvent\n\t| LsToolCallEvent\n\t| CustomToolCallEvent;\n\ninterface ToolResultEventBase {\n\ttype: \"tool_result\";\n\ttoolCallId: string;\n\tinput: Record;\n\tcontent: (TextContent | ImageContent)[];\n\tisError: boolean;\n\t/** Usage from the tool execution itself, if available. */\n\tusage?: Usage;\n}\n\nexport interface BashToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"bash\";\n\tdetails: BashToolDetails | undefined;\n}\n\nexport interface ReadToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"read\";\n\tdetails: ReadToolDetails | undefined;\n}\n\nexport interface EditToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"edit\";\n\tdetails: EditToolDetails | undefined;\n}\n\nexport interface WriteToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"write\";\n\tdetails: undefined;\n}\n\nexport interface GrepToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"grep\";\n\tdetails: GrepToolDetails | undefined;\n}\n\nexport interface FindToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"find\";\n\tdetails: FindToolDetails | undefined;\n}\n\nexport interface LsToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"ls\";\n\tdetails: LsToolDetails | undefined;\n}\n\nexport interface CustomToolResultEvent extends ToolResultEventBase {\n\ttoolName: string;\n\tdetails: unknown;\n}\n\n/** Fired after a tool executes. Can modify result. */\nexport type ToolResultEvent =\n\t| BashToolResultEvent\n\t| ReadToolResultEvent\n\t| EditToolResultEvent\n\t| WriteToolResultEvent\n\t| GrepToolResultEvent\n\t| FindToolResultEvent\n\t| LsToolResultEvent\n\t| CustomToolResultEvent;\n\n// Type guards for ToolResultEvent\nexport function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {\n\treturn e.toolName === \"bash\";\n}\nexport function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {\n\treturn e.toolName === \"read\";\n}\nexport function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {\n\treturn e.toolName === \"edit\";\n}\nexport function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {\n\treturn e.toolName === \"write\";\n}\nexport function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {\n\treturn e.toolName === \"grep\";\n}\nexport function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {\n\treturn e.toolName === \"find\";\n}\nexport function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {\n\treturn e.toolName === \"ls\";\n}\n\n/**\n * Type guard for narrowing ToolCallEvent by tool name.\n *\n * Built-in tools narrow automatically (no type params needed):\n * ```ts\n * if (isToolCallEventType(\"bash\", event)) {\n * event.input.command; // string\n * }\n * ```\n *\n * Custom tools require explicit type parameters:\n * ```ts\n * if (isToolCallEventType<\"my_tool\", MyToolInput>(\"my_tool\", event)) {\n * event.input.action; // typed\n * }\n * ```\n *\n * Note: Direct narrowing via `event.toolName === \"bash\"` doesn't work because\n * CustomToolCallEvent.toolName is `string` which overlaps with all literals.\n */\nexport function isToolCallEventType(toolName: \"bash\", event: ToolCallEvent): event is BashToolCallEvent;\nexport function isToolCallEventType(toolName: \"read\", event: ToolCallEvent): event is ReadToolCallEvent;\nexport function isToolCallEventType(toolName: \"edit\", event: ToolCallEvent): event is EditToolCallEvent;\nexport function isToolCallEventType(toolName: \"write\", event: ToolCallEvent): event is WriteToolCallEvent;\nexport function isToolCallEventType(toolName: \"grep\", event: ToolCallEvent): event is GrepToolCallEvent;\nexport function isToolCallEventType(toolName: \"find\", event: ToolCallEvent): event is FindToolCallEvent;\nexport function isToolCallEventType(toolName: \"ls\", event: ToolCallEvent): event is LsToolCallEvent;\nexport function isToolCallEventType>(\n\ttoolName: TName,\n\tevent: ToolCallEvent,\n): event is ToolCallEvent & { toolName: TName; input: TInput };\nexport function isToolCallEventType(toolName: string, event: ToolCallEvent): boolean {\n\treturn event.toolName === toolName;\n}\n\n/** Union of all event types */\nexport type ExtensionEvent =\n\t| ProjectTrustEvent\n\t| ResourcesDiscoverEvent\n\t| SessionEvent\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeProviderHeadersEvent\n\t| AfterProviderResponseEvent\n\t| BeforeAgentStartEvent\n\t| AgentStartEvent\n\t| AgentEndEvent\n\t| AgentSettledEvent\n\t| TurnStartEvent\n\t| TurnEndEvent\n\t| MessageStartEvent\n\t| MessageUpdateEvent\n\t| MessageEndEvent\n\t| ToolExecutionStartEvent\n\t| ToolExecutionUpdateEvent\n\t| ToolExecutionEndEvent\n\t| ModelSelectEvent\n\t| ThinkingLevelSelectEvent\n\t| UserBashEvent\n\t| InputEvent\n\t| ToolCallEvent\n\t| ToolResultEvent;\n\n// ============================================================================\n// Event Results\n// ============================================================================\n\nexport interface ContextEventResult {\n\tmessages?: AgentMessage[];\n}\n\nexport type BeforeProviderRequestEventResult = unknown;\n\nexport interface ToolCallEventResult {\n\t/** Block tool execution. To modify arguments, mutate `event.input` in place instead. */\n\tblock?: boolean;\n\treason?: string;\n}\n\n/** Result from user_bash event handler */\nexport interface UserBashEventResult {\n\t/** Custom operations to use for execution */\n\toperations?: BashOperations;\n\t/** Full replacement: extension handled execution, use this result */\n\tresult?: BashResult;\n}\n\nexport interface ToolResultEventResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n\tusage?: Usage;\n}\n\nexport interface MessageEndEventResult {\n\t/** Replace the finalized message. The replacement must keep the original message role. */\n\tmessage?: AgentMessage;\n}\n\nexport interface BeforeAgentStartEventResult {\n\tmessage?: Pick;\n\t/** Replace the system prompt for this turn. If multiple extensions return this, they are chained. */\n\tsystemPrompt?: string;\n}\n\nexport interface SessionBeforeSwitchResult {\n\tcancel?: boolean;\n}\n\nexport interface SessionBeforeForkResult {\n\tcancel?: boolean;\n\tskipConversationRestore?: boolean;\n}\n\nexport interface SessionBeforeCompactResult {\n\tcancel?: boolean;\n\tcompaction?: CompactionResult;\n}\n\nexport interface SessionBeforeTreeResult {\n\tcancel?: boolean;\n\tsummary?: {\n\t\tsummary: string;\n\t\tdetails?: unknown;\n\t\tusage?: Usage;\n\t};\n\t/** Override custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** Override whether customInstructions replaces the default prompt */\n\treplaceInstructions?: boolean;\n\t/** Override label to attach to the branch summary entry */\n\tlabel?: string;\n}\n\n// ============================================================================\n// Message and Entry Rendering\n// ============================================================================\n\nexport interface MessageRenderOptions {\n\texpanded: boolean;\n\t/** Horizontal padding configured by the outputPad setting. */\n\toutputPad: number;\n}\n\nexport interface EntryRenderOptions {\n\texpanded: boolean;\n}\n\nexport type MessageRenderer = (\n\tmessage: CustomMessage,\n\toptions: MessageRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\nexport type EntryRenderer = (\n\tentry: CustomEntry,\n\toptions: EntryRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\nexport interface RegisteredCommand {\n\tname: string;\n\tsourceInfo: SourceInfo;\n\tdescription?: string;\n\tgetArgumentCompletions?: (argumentPrefix: string) => AutocompleteItem[] | null | Promise;\n\thandler: (args: string, ctx: ExtensionCommandContext) => Promise;\n}\n\nexport interface ResolvedCommand extends RegisteredCommand {\n\tinvocationName: string;\n}\n\n// ============================================================================\n// Extension API\n// ============================================================================\n\n/** Handler function type for events */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements\nexport type ExtensionHandler = (event: E, ctx: ExtensionContext) => Promise | R | void;\n\n/**\n * ExtensionAPI passed to extension factory functions.\n */\nexport interface ExtensionAPI {\n\t// =========================================================================\n\t// Event Subscription\n\t// =========================================================================\n\n\ton(event: \"project_trust\", handler: ProjectTrustHandler): void;\n\ton(event: \"resources_discover\", handler: ExtensionHandler): void;\n\ton(event: \"session_start\", handler: ExtensionHandler): void;\n\ton(event: \"session_info_changed\", handler: ExtensionHandler): void;\n\ton(\n\t\tevent: \"session_before_switch\",\n\t\thandler: ExtensionHandler,\n\t): void;\n\ton(event: \"session_before_fork\", handler: ExtensionHandler): void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: ExtensionHandler,\n\t): void;\n\ton(event: \"session_compact\", handler: ExtensionHandler): void;\n\ton(event: \"session_shutdown\", handler: ExtensionHandler): void;\n\ton(event: \"session_before_tree\", handler: ExtensionHandler): void;\n\ton(event: \"session_tree\", handler: ExtensionHandler): void;\n\ton(event: \"context\", handler: ExtensionHandler): void;\n\ton(\n\t\tevent: \"before_provider_request\",\n\t\thandler: ExtensionHandler,\n\t): void;\n\ton(event: \"before_provider_headers\", handler: ExtensionHandler): void;\n\ton(event: \"after_provider_response\", handler: ExtensionHandler): void;\n\ton(event: \"before_agent_start\", handler: ExtensionHandler): void;\n\ton(event: \"agent_start\", handler: ExtensionHandler): void;\n\ton(event: \"agent_end\", handler: ExtensionHandler): void;\n\ton(event: \"agent_settled\", handler: ExtensionHandler): void;\n\ton(event: \"turn_start\", handler: ExtensionHandler): void;\n\ton(event: \"turn_end\", handler: ExtensionHandler): void;\n\ton(event: \"message_start\", handler: ExtensionHandler): void;\n\ton(event: \"message_update\", handler: ExtensionHandler): void;\n\ton(event: \"message_end\", handler: ExtensionHandler): void;\n\ton(event: \"tool_execution_start\", handler: ExtensionHandler): void;\n\ton(event: \"tool_execution_update\", handler: ExtensionHandler): void;\n\ton(event: \"tool_execution_end\", handler: ExtensionHandler): void;\n\ton(event: \"model_select\", handler: ExtensionHandler): void;\n\ton(event: \"thinking_level_select\", handler: ExtensionHandler): void;\n\ton(event: \"tool_call\", handler: ExtensionHandler): void;\n\ton(event: \"tool_result\", handler: ExtensionHandler): void;\n\ton(event: \"user_bash\", handler: ExtensionHandler): void;\n\ton(event: \"input\", handler: ExtensionHandler): void;\n\n\t// =========================================================================\n\t// Tool Registration\n\t// =========================================================================\n\n\t/** Register a tool that the LLM can call. */\n\tregisterTool(\n\t\ttool: ToolDefinition,\n\t): void;\n\n\t// =========================================================================\n\t// Command, Shortcut, Flag Registration\n\t// =========================================================================\n\n\t/** Register a custom command. */\n\tregisterCommand(name: string, options: Omit): void;\n\n\t/** Register a keyboard shortcut. */\n\tregisterShortcut(\n\t\tshortcut: KeyId,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\thandler: (ctx: ExtensionContext) => Promise | void;\n\t\t},\n\t): void;\n\n\t/** Register a CLI flag. */\n\tregisterFlag(\n\t\tname: string,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\ttype: \"boolean\" | \"string\";\n\t\t\tdefault?: boolean | string;\n\t\t},\n\t): void;\n\n\t/** Get the value of a registered CLI flag. */\n\tgetFlag(name: string): boolean | string | undefined;\n\n\t// =========================================================================\n\t// Message Rendering\n\t// =========================================================================\n\n\t/** Register a custom renderer for CustomMessageEntry. */\n\tregisterMessageRenderer(customType: string, renderer: MessageRenderer): void;\n\n\t/** Register a custom renderer for CustomEntry. Custom entries do not participate in LLM context. */\n\tregisterEntryRenderer(customType: string, renderer: EntryRenderer): void;\n\n\t// =========================================================================\n\t// Actions\n\t// =========================================================================\n\n\t/** Send a custom message to the session. */\n\tsendMessage(\n\t\tmessage: Pick, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n\t): void;\n\n\t/**\n\t * Send a user message to the agent. Always triggers a turn.\n\t * When the agent is streaming, use deliverAs to specify how to queue the message.\n\t */\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): void;\n\n\t/** Append a custom entry to the session for state persistence (not sent to LLM). */\n\tappendEntry(customType: string, data?: T): void;\n\n\t// =========================================================================\n\t// Session Metadata\n\t// =========================================================================\n\n\t/** Set the session display name (shown in session selector). */\n\tsetSessionName(name: string): void;\n\n\t/** Get the current session name, if set. */\n\tgetSessionName(): string | undefined;\n\n\t/** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */\n\tsetLabel(entryId: string, label: string | undefined): void;\n\n\t/** Execute a shell command. */\n\texec(command: string, args: string[], options?: ExecOptions): Promise;\n\n\t/** Get the list of currently active tool names. */\n\tgetActiveTools(): string[];\n\n\t/** Get all configured tools with parameter schema, prompt guidelines, and source metadata. */\n\tgetAllTools(): ToolInfo[];\n\n\t/** Set the active tools by name. */\n\tsetActiveTools(toolNames: string[]): void;\n\n\t/** Get available slash commands in the current session. */\n\tgetCommands(): SlashCommandInfo[];\n\n\t// =========================================================================\n\t// Model and Thinking Level\n\t// =========================================================================\n\n\t/** Set the current model. Returns false if no API key available. */\n\tsetModel(model: Model): Promise;\n\n\t/** Get current thinking level. */\n\tgetThinkingLevel(): ThinkingLevel;\n\n\t/** Set thinking level (clamped to model capabilities). */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\n\t// =========================================================================\n\t// Provider Registration\n\t// =========================================================================\n\n\t/**\n\t * Register or override a model provider.\n\t *\n\t * If `models` is provided: replaces all existing models for this provider.\n\t * If only `baseUrl` is provided: overrides the URL for existing models.\n\t * If `oauth` is provided: registers OAuth provider for /login support.\n\t * If `streamSimple` is provided: registers a custom API stream handler.\n\t *\n\t * During initial extension load this call is queued and applied once the\n\t * runner has bound its context. After that it takes effect immediately, so\n\t * it is safe to call from command handlers or event callbacks without\n\t * requiring a `/reload`.\n\t *\n\t * @example\n\t * // Register a new provider with custom models\n\t * pi.registerProvider(\"my-proxy\", {\n\t * baseUrl: \"https://proxy.example.com\",\n\t * apiKey: \"$PROXY_API_KEY\",\n\t * api: \"anthropic-messages\",\n\t * models: [\n\t * {\n\t * id: \"claude-sonnet-4-20250514\",\n\t * name: \"Claude 4 Sonnet (proxy)\",\n\t * reasoning: false,\n\t * input: [\"text\", \"image\"],\n\t * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t * contextWindow: 200000,\n\t * maxTokens: 16384\n\t * }\n\t * ]\n\t * });\n\t *\n\t * @example\n\t * // Override baseUrl for an existing provider\n\t * pi.registerProvider(\"anthropic\", {\n\t * baseUrl: \"https://proxy.example.com\"\n\t * });\n\t *\n\t * @example\n\t * // Register provider with OAuth support\n\t * pi.registerProvider(\"corporate-ai\", {\n\t * baseUrl: \"https://ai.corp.com\",\n\t * api: \"openai-responses\",\n\t * models: [...],\n\t * oauth: {\n\t * name: \"Corporate AI (SSO)\",\n\t * async login(callbacks) { ... },\n\t * async refreshToken(credentials) { ... },\n\t * getApiKey(credentials) { return credentials.access; }\n\t * }\n\t * });\n\t */\n\tregisterProvider(provider: Provider): void;\n\tregisterProvider(name: string, config: ProviderConfig): void;\n\n\t/**\n\t * Unregister a previously registered provider.\n\t *\n\t * Removes all models belonging to the named provider and restores any\n\t * built-in models that were overridden by it. Has no effect if the provider\n\t * is not currently registered.\n\t *\n\t * Like `registerProvider`, this takes effect immediately when called after\n\t * the initial load phase.\n\t *\n\t * @example\n\t * pi.unregisterProvider(\"my-proxy\");\n\t */\n\tunregisterProvider(name: string): void;\n\n\t/** Shared event bus for extension communication. */\n\tevents: EventBus;\n}\n\n// ============================================================================\n// Provider Registration Types\n// ============================================================================\n\n/** Configuration for registering a provider via pi.registerProvider(). */\nexport interface ProviderConfig {\n\t/** Display name for the provider in UI. */\n\tname?: string;\n\t/** Base URL for the API endpoint. Required when defining models. */\n\tbaseUrl?: string;\n\t/** API key literal, env interpolation ($ENV_VAR or ${ENV_VAR}), or leading !command. Required when defining models (unless oauth provided). */\n\tapiKey?: string;\n\t/** API type. Required at provider or model level when defining models. */\n\tapi?: Api;\n\t/** Optional streamSimple handler for custom APIs. */\n\tstreamSimple?: (model: Model, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\t/** Custom headers to include in requests. */\n\theaders?: Record;\n\t/** If true, adds Authorization: Bearer header with the resolved API key. */\n\tauthHeader?: boolean;\n\t/** Models to register. If provided, replaces all existing models for this provider. */\n\tmodels?: ProviderModelConfig[];\n\t/**\n\t * Refresh this provider's model list. The returned list replaces extension-provided models.\n\t * Use context.store explicitly when the catalog should persist across sessions.\n\t */\n\trefreshModels?(context: RefreshModelsContext): Promise;\n\t/** OAuth provider for /login support. The `id` is set automatically from the provider name. */\n\toauth?: {\n\t\t/** Display name for the provider in login UI. */\n\t\tname: string;\n\t\t/** @deprecated Retained for source compatibility; canonical auth flows ignore it. */\n\t\tusesCallbackServer?: boolean;\n\t\t/** Run the login flow, return credentials to persist. */\n\t\tlogin(callbacks: OAuthLoginCallbacks): Promise;\n\t\t/** Refresh expired credentials, return updated credentials to persist. */\n\t\trefreshToken(credentials: OAuthCredentials): Promise;\n\t\t/** Convert credentials to API key string for the provider. */\n\t\tgetApiKey(credentials: OAuthCredentials): string;\n\t\t/** Legacy synchronous credential-dependent model projection. */\n\t\tmodifyModels?(models: Model[], credentials: OAuthCredentials): Model[];\n\t};\n}\n\n/** Configuration for a model within a provider. */\nexport interface ProviderModelConfig {\n\t/** Model ID (e.g., \"claude-sonnet-4-20250514\"). */\n\tid: string;\n\t/** Display name (e.g., \"Claude 4 Sonnet\"). */\n\tname: string;\n\t/** API type override for this model. */\n\tapi?: Api;\n\t/** API endpoint URL override for this model. */\n\tbaseUrl?: string;\n\t/** Whether the model supports extended thinking. */\n\treasoning: boolean;\n\t/** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */\n\tthinkingLevelMap?: Model[\"thinkingLevelMap\"];\n\t/** Supported input types. */\n\tinput: (\"text\" | \"image\")[];\n\t/** Per-million-token cost rates and optional request-wide input pricing tiers. */\n\tcost: Model[\"cost\"];\n\t/** Maximum context window size in tokens. */\n\tcontextWindow: number;\n\t/** Maximum output tokens. */\n\tmaxTokens: number;\n\t/** Custom headers for this model. */\n\theaders?: Record;\n\t/** OpenAI compatibility settings. */\n\tcompat?: Model[\"compat\"];\n}\n\n/** Extension factory function type. Supports both sync and async initialization. */\nexport type ExtensionFactory = (pi: ExtensionAPI) => void | Promise;\n\nexport type InlineExtension =\n\t| ExtensionFactory\n\t| {\n\t\t\t/** Display name shown as `` in the startup Extensions list. */\n\t\t\tname: string;\n\t\t\tfactory: ExtensionFactory;\n\t\t\t/** Omit this extension from the startup Extensions list. */\n\t\t\thidden?: boolean;\n\t };\n\n// ============================================================================\n// Loaded Extension Types\n// ============================================================================\n\nexport interface RegisteredTool {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface ExtensionFlag {\n\tname: string;\n\tdescription?: string;\n\ttype: \"boolean\" | \"string\";\n\tdefault?: boolean | string;\n\textensionPath: string;\n}\n\nexport interface ExtensionShortcut {\n\tshortcut: KeyId;\n\tdescription?: string;\n\thandler: (ctx: ExtensionContext) => Promise | void;\n\textensionPath: string;\n}\n\ntype HandlerFn = (...args: unknown[]) => Promise;\n\nexport type SendMessageHandler = (\n\tmessage: Pick, \"customType\" | \"content\" | \"display\" | \"details\">,\n\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n) => void;\n\nexport type SendUserMessageHandler = (\n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n) => void;\n\nexport type AppendEntryHandler = (customType: string, data?: T) => void;\n\nexport type SetSessionNameHandler = (name: string) => void;\n\nexport type GetSessionNameHandler = () => string | undefined;\n\nexport type GetActiveToolsHandler = () => string[];\n\n/** Tool info with name, description, parameter schema, prompt guidelines, and source metadata. */\nexport type ToolInfo = Pick & {\n\tsourceInfo: SourceInfo;\n};\n\nexport type GetAllToolsHandler = () => ToolInfo[];\n\nexport type GetCommandsHandler = () => SlashCommandInfo[];\n\nexport type SetActiveToolsHandler = (toolNames: string[]) => void;\n\nexport type RefreshToolsHandler = () => void;\n\nexport type SetModelHandler = (model: Model) => Promise;\n\nexport type GetThinkingLevelHandler = () => ThinkingLevel;\n\nexport type SetThinkingLevelHandler = (level: ThinkingLevel) => void;\n\nexport type SetLabelHandler = (entryId: string, label: string | undefined) => void;\n\n/**\n * Shared state created by loader, used during registration and runtime.\n * Contains flag values (defaults set during registration, CLI values set after).\n */\nexport interface ExtensionRuntimeState {\n\tflagValues: Map;\n\t/** Legacy provider-config registrations queued during extension loading, processed when runner binds. */\n\tpendingProviderRegistrations: Array<{ name: string; config: ProviderConfig; extensionPath: string }>;\n\t/** Native pi-ai provider registrations queued during extension loading, processed when runner binds. */\n\tpendingNativeProviderRegistrations: Array<{ provider: Provider; extensionPath: string }>;\n\t/** Throws when this extension instance is stale after runtime replacement. */\n\tassertActive: () => void;\n\t/** Marks this extension instance as stale after runtime replacement or reload. */\n\tinvalidate: (message?: string) => void;\n\t/**\n\t * Register or unregister a provider.\n\t *\n\t * Before bindCore(): queues registrations / removes from queue.\n\t * After bindCore(): calls ModelRegistry directly for immediate effect.\n\t */\n\tregisterProvider: (name: string, config: ProviderConfig, extensionPath?: string) => void;\n\tregisterNativeProvider: (provider: Provider, extensionPath?: string) => void;\n\tunregisterProvider: (name: string, extensionPath?: string) => void;\n}\n\n/**\n * Action implementations for pi.* API methods.\n * Provided to runner.initialize(), copied into the shared runtime.\n */\nexport interface ExtensionActions {\n\tsendMessage: SendMessageHandler;\n\tsendUserMessage: SendUserMessageHandler;\n\tappendEntry: AppendEntryHandler;\n\tsetSessionName: SetSessionNameHandler;\n\tgetSessionName: GetSessionNameHandler;\n\tsetLabel: SetLabelHandler;\n\tgetActiveTools: GetActiveToolsHandler;\n\tgetAllTools: GetAllToolsHandler;\n\tsetActiveTools: SetActiveToolsHandler;\n\trefreshTools: RefreshToolsHandler;\n\tgetCommands: GetCommandsHandler;\n\tsetModel: SetModelHandler;\n\tgetThinkingLevel: GetThinkingLevelHandler;\n\tsetThinkingLevel: SetThinkingLevelHandler;\n}\n\n/**\n * Actions for ExtensionContext (ctx.* in event handlers).\n * Required by all modes.\n */\nexport interface ExtensionContextActions {\n\tgetModel: () => Model | undefined;\n\tgetScopedModels: () => readonly ScopedModel[];\n\tisIdle: () => boolean;\n\tisProjectTrusted: () => boolean;\n\tgetSignal: () => AbortSignal | undefined;\n\tabort: () => void;\n\thasPendingMessages: () => boolean;\n\tshutdown: () => void;\n\tgetContextUsage: () => ContextUsage | undefined;\n\tcompact: (options?: CompactOptions) => void;\n\tgetSystemPrompt: () => string;\n\tgetSystemPromptOptions?: () => BuildSystemPromptOptions;\n}\n\n/**\n * Actions for ExtensionCommandContext (ctx.* in command handlers).\n * Only needed for interactive mode where extension commands are invokable.\n */\nexport interface ExtensionCommandContextActions {\n\twaitForIdle: () => Promise;\n\tnewSession: (options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise;\n\t}) => Promise<{ cancelled: boolean }>;\n\tfork: (\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise },\n\t) => Promise<{ cancelled: boolean }>;\n\tnavigateTree: (\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t) => Promise<{ cancelled: boolean }>;\n\tswitchSession: (\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise },\n\t) => Promise<{ cancelled: boolean }>;\n\treload: () => Promise;\n}\n\n/**\n * Full runtime = state + actions.\n * Created by loader with throwing action stubs, completed by runner.initialize().\n */\nexport interface ExtensionRuntime extends ExtensionRuntimeState, ExtensionActions {}\n\n/** Loaded extension with all registered items. */\nexport interface Extension {\n\tpath: string;\n\tresolvedPath: string;\n\thidden?: boolean;\n\tsourceInfo: SourceInfo;\n\thandlers: Map;\n\ttools: Map;\n\tmessageRenderers: Map;\n\tentryRenderers?: Map;\n\tcommands: Map;\n\tflags: Map;\n\tshortcuts: Map;\n}\n\n/** Result of loading extensions. */\nexport interface LoadExtensionsResult {\n\textensions: Extension[];\n\terrors: Array<{ path: string; error: string }>;\n\t/** Shared runtime - actions are throwing stubs until runner.initialize() */\n\truntime: ExtensionRuntime;\n}\n\n// ============================================================================\n// Extension Error\n// ============================================================================\n\nexport interface ExtensionError {\n\textensionPath: string;\n\tevent: string;\n\terror: string;\n\tstack?: string;\n}\n"]} \ No newline at end of file diff --git a/dist/core/extensions/types.js b/dist/core/extensions/types.js new file mode 100644 index 0000000..69f32e4 --- /dev/null +++ b/dist/core/extensions/types.js @@ -0,0 +1,45 @@ +/** + * Extension system types. + * + * Extensions are TypeScript modules that can: + * - Subscribe to agent lifecycle events + * - Register LLM-callable tools + * - Register commands, keyboard shortcuts, and CLI flags + * - Interact with the user via UI primitives + */ +/** + * Preserve parameter inference for standalone tool definitions. + * + * Use this when assigning a tool to a variable or passing it through arrays such + * as `customTools`, where contextual typing would otherwise widen params to + * `unknown`. + */ +export function defineTool(tool) { + return tool; +} +// Type guards for ToolResultEvent +export function isBashToolResult(e) { + return e.toolName === "bash"; +} +export function isReadToolResult(e) { + return e.toolName === "read"; +} +export function isEditToolResult(e) { + return e.toolName === "edit"; +} +export function isWriteToolResult(e) { + return e.toolName === "write"; +} +export function isGrepToolResult(e) { + return e.toolName === "grep"; +} +export function isFindToolResult(e) { + return e.toolName === "find"; +} +export function isLsToolResult(e) { + return e.toolName === "ls"; +} +export function isToolCallEventType(toolName, event) { + return event.toolName === toolName; +} +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/core/extensions/types.js.map b/dist/core/extensions/types.js.map new file mode 100644 index 0000000..224c2b4 --- /dev/null +++ b/dist/core/extensions/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/extensions/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AA6eH;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CACzB,IAA+C,EACiB;IAChE,OAAO,IAAqE,CAAC;AAAA,CAC7E;AA8cD,kCAAkC;AAClC,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,iBAAiB,CAAC,CAAkB,EAA6B;IAChF,OAAO,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC;AAAA,CAC9B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB,EAA4B;IAC9E,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAAA,CAC7B;AACD,MAAM,UAAU,cAAc,CAAC,CAAkB,EAA0B;IAC1E,OAAO,CAAC,CAAC,QAAQ,KAAK,IAAI,CAAC;AAAA,CAC3B;AAiCD,MAAM,UAAU,mBAAmB,CAAC,QAAgB,EAAE,KAAoB,EAAW;IACpF,OAAO,KAAK,CAAC,QAAQ,KAAK,QAAQ,CAAC;AAAA,CACnC","sourcesContent":["/**\n * Extension system types.\n *\n * Extensions are TypeScript modules that can:\n * - Subscribe to agent lifecycle events\n * - Register LLM-callable tools\n * - Register commands, keyboard shortcuts, and CLI flags\n * - Interact with the user via UI primitives\n */\n\nimport type {\n\tAgentMessage,\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n\tThinkingLevel,\n\tToolExecutionMode,\n} from \"@earendil-works/pi-agent-core\";\nimport type {\n\tApi,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tConstrainedSamplingConfig,\n\tContext,\n\tImageContent,\n\tModel,\n\tOAuthCredentials,\n\tOAuthLoginCallbacks,\n\tProvider,\n\tProviderHeaders,\n\tRefreshModelsContext,\n\tSimpleStreamOptions,\n\tTextContent,\n\tToolResultMessage,\n\tUsage,\n} from \"@earendil-works/pi-ai\";\nimport type {\n\tAutocompleteItem,\n\tAutocompleteProvider,\n\tComponent,\n\tEditorComponent,\n\tEditorTheme,\n\tKeyId,\n\tOverlayHandle,\n\tOverlayOptions,\n\tTUI,\n} from \"@earendil-works/pi-tui\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { BashResult } from \"../bash-executor.ts\";\nimport type { CompactionPreparation, CompactionResult } from \"../compaction/index.ts\";\nimport type { EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions, ExecResult } from \"../exec.ts\";\nimport type { ReadonlyFooterDataProvider } from \"../footer-data-provider.ts\";\nimport type { KeybindingsManager } from \"../keybindings.ts\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type { ScopedModel } from \"../model-resolver.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tCustomEntry,\n\tReadonlySessionManager,\n\tSessionEntry,\n\tSessionManager,\n} from \"../session-manager.ts\";\nimport type { SlashCommandInfo } from \"../slash-commands.ts\";\nimport type { SourceInfo } from \"../source-info.ts\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { BashOperations } from \"../tools/bash.ts\";\nimport type { EditToolDetails } from \"../tools/edit.ts\";\nimport type {\n\tBashToolDetails,\n\tBashToolInput,\n\tEditToolInput,\n\tFindToolDetails,\n\tFindToolInput,\n\tGrepToolDetails,\n\tGrepToolInput,\n\tLsToolDetails,\n\tLsToolInput,\n\tReadToolDetails,\n\tReadToolInput,\n\tWriteToolInput,\n} from \"../tools/index.ts\";\n\nexport type { ExecOptions, ExecResult } from \"../exec.ts\";\nexport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nexport type { AgentToolResult, AgentToolUpdateCallback, ToolExecutionMode };\nexport type { AppKeybinding, KeybindingsManager } from \"../keybindings.ts\";\n\n// ============================================================================\n// UI Context\n// ============================================================================\n\n/** Options for extension UI dialogs. */\nexport interface ExtensionUIDialogOptions {\n\t/** AbortSignal to programmatically dismiss the dialog. */\n\tsignal?: AbortSignal;\n\t/** Timeout in milliseconds. Dialog auto-dismisses with live countdown display. */\n\ttimeout?: number;\n}\n\n/** Placement for extension widgets. */\nexport type WidgetPlacement = \"aboveEditor\" | \"belowEditor\";\n\n/** Options for extension widgets. */\nexport interface ExtensionWidgetOptions {\n\t/** Where the widget is rendered. Defaults to \"aboveEditor\". */\n\tplacement?: WidgetPlacement;\n}\n\n/** Raw terminal input listener for extensions. */\nexport type TerminalInputHandler = (data: string) => { consume?: boolean; data?: string } | undefined;\n\n/** Working indicator configuration for the interactive streaming loader. */\nexport interface WorkingIndicatorOptions {\n\t/** Animation frames. Use an empty array to hide the indicator entirely. Custom frames are rendered verbatim. */\n\tframes?: string[];\n\t/** Frame interval in milliseconds for animated indicators. */\n\tintervalMs?: number;\n}\n\n/** Wrap the current autocomplete provider with additional behavior. */\nexport type AutocompleteProviderFactory = (current: AutocompleteProvider) => AutocompleteProvider;\nexport type EditorFactory = (tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) => EditorComponent;\n\n/**\n * UI context for extensions to request interactive UI.\n * Each mode (interactive, RPC, print) provides its own implementation.\n */\nexport interface ExtensionUIContext {\n\t/** Show a selector and return the user's choice. */\n\tselect(title: string, options: string[], opts?: ExtensionUIDialogOptions): Promise;\n\n\t/** Show a confirmation dialog. */\n\tconfirm(title: string, message: string, opts?: ExtensionUIDialogOptions): Promise;\n\n\t/** Show a text input dialog. */\n\tinput(title: string, placeholder?: string, opts?: ExtensionUIDialogOptions): Promise;\n\n\t/** Show a notification to the user. */\n\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\n\t/** Listen to raw terminal input (interactive mode only). Returns an unsubscribe function. */\n\tonTerminalInput(handler: TerminalInputHandler): () => void;\n\n\t/** Set status text in the footer/status bar. Pass undefined to clear. */\n\tsetStatus(key: string, text: string | undefined): void;\n\n\t/** Set the working/loading message shown during streaming. Call with no argument to restore default. */\n\tsetWorkingMessage(message?: string): void;\n\n\t/** Show or hide the built-in interactive working loader row during streaming. */\n\tsetWorkingVisible(visible: boolean): void;\n\n\t/**\n\t * Configure the interactive working indicator shown during streaming.\n\t *\n\t * - Omit the argument to restore the default animated spinner.\n\t * - Use `frames: [\"●\"]` for a static indicator.\n\t * - Use `frames: []` to hide the indicator entirely.\n\t * - Custom frames are rendered as provided, so extensions must add their own colors.\n\t */\n\tsetWorkingIndicator(options?: WorkingIndicatorOptions): void;\n\n\t/** Set the label shown for hidden thinking blocks. Call with no argument to restore default. */\n\tsetHiddenThinkingLabel(label?: string): void;\n\n\t/** Set a widget to display above or below the editor. Accepts string array or component factory. */\n\tsetWidget(key: string, content: string[] | undefined, options?: ExtensionWidgetOptions): void;\n\tsetWidget(\n\t\tkey: string,\n\t\tcontent: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined,\n\t\toptions?: ExtensionWidgetOptions,\n\t): void;\n\n\t/** Set a custom footer component, or undefined to restore the built-in footer.\n\t *\n\t * The factory receives a FooterDataProvider for data not otherwise accessible:\n\t * git branch and extension statuses from setStatus(). Token stats, model info,\n\t * etc. are available via ctx.sessionManager and ctx.model.\n\t */\n\tsetFooter(\n\t\tfactory:\n\t\t\t| ((tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => Component & { dispose?(): void })\n\t\t\t| undefined,\n\t): void;\n\n\t/** Set a custom header component (shown at startup, above chat), or undefined to restore the built-in header. */\n\tsetHeader(factory: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined): void;\n\n\t/** Set the terminal window/tab title. */\n\tsetTitle(title: string): void;\n\n\t/** Show a custom component with keyboard focus. */\n\tcustom(\n\t\tfactory: (\n\t\t\ttui: TUI,\n\t\t\ttheme: Theme,\n\t\t\tkeybindings: KeybindingsManager,\n\t\t\tdone: (result: T) => void,\n\t\t) => (Component & { dispose?(): void }) | Promise,\n\t\toptions?: {\n\t\t\toverlay?: boolean;\n\t\t\t/** Overlay positioning/sizing options. Can be static or a function for dynamic updates. */\n\t\t\toverlayOptions?: OverlayOptions | (() => OverlayOptions);\n\t\t\t/** Called with the overlay handle after the overlay is shown. Use to control visibility. */\n\t\t\tonHandle?: (handle: OverlayHandle) => void;\n\t\t},\n\t): Promise;\n\n\t/** Paste text into the editor, triggering paste handling (collapse for large content). */\n\tpasteToEditor(text: string): void;\n\n\t/** Set the text in the core input editor. */\n\tsetEditorText(text: string): void;\n\n\t/** Get the current text from the core input editor. */\n\tgetEditorText(): string;\n\n\t/** Show a multi-line editor for text editing. */\n\teditor(title: string, prefill?: string): Promise;\n\n\t/** Stack additional autocomplete behavior on top of the built-in provider. */\n\taddAutocompleteProvider(factory: AutocompleteProviderFactory): void;\n\n\t/**\n\t * Set a custom editor component via factory function.\n\t * Pass undefined to restore the default editor.\n\t *\n\t * The factory receives:\n\t * - `theme`: EditorTheme for styling borders and autocomplete\n\t * - `keybindings`: KeybindingsManager for app-level keybindings\n\t *\n\t * For full app keybinding support (escape, ctrl+d, model switching, etc.),\n\t * extend `CustomEditor` from `@earendil-works/pi-coding-agent` and call\n\t * `super.handleInput(data)` for keys you don't handle.\n\t *\n\t * @example\n\t * ```ts\n\t * import { CustomEditor } from \"@earendil-works/pi-coding-agent\";\n\t *\n\t * class VimEditor extends CustomEditor {\n\t * private mode: \"normal\" | \"insert\" = \"insert\";\n\t *\n\t * handleInput(data: string): void {\n\t * if (this.mode === \"normal\") {\n\t * // Handle vim normal mode keys...\n\t * if (data === \"i\") { this.mode = \"insert\"; return; }\n\t * }\n\t * super.handleInput(data); // App keybindings + text editing\n\t * }\n\t * }\n\t *\n\t * ctx.ui.setEditorComponent((tui, theme, keybindings) =>\n\t * new VimEditor(tui, theme, keybindings)\n\t * );\n\t * ```\n\t */\n\tsetEditorComponent(factory: EditorFactory | undefined): void;\n\n\t/** Get the currently configured custom editor factory, or undefined when using the default editor. */\n\tgetEditorComponent(): EditorFactory | undefined;\n\n\t/** Get the current theme for styling. */\n\treadonly theme: Theme;\n\n\t/** Get all available themes with their names and file paths. */\n\tgetAllThemes(): { name: string; path: string | undefined }[];\n\n\t/** Load a theme by name without switching to it. Returns undefined if not found. */\n\tgetTheme(name: string): Theme | undefined;\n\n\t/** Set the current theme by name or Theme object. */\n\tsetTheme(theme: string | Theme): { success: boolean; error?: string };\n\n\t/** Get current tool output expansion state. */\n\tgetToolsExpanded(): boolean;\n\n\t/** Set tool output expansion state. */\n\tsetToolsExpanded(expanded: boolean): void;\n}\n\n// ============================================================================\n// Extension Context\n// ============================================================================\n\nexport interface ContextUsage {\n\t/** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */\n\ttokens: number | null;\n\tcontextWindow: number;\n\t/** Context usage as percentage of context window, or null if tokens is unknown. */\n\tpercent: number | null;\n}\n\nexport interface CompactOptions {\n\tcustomInstructions?: string;\n\tonComplete?: (result: CompactionResult) => void;\n\tonError?: (error: Error) => void;\n}\n\n/**\n * Context passed to extension event handlers.\n */\nexport type ExtensionMode = \"tui\" | \"rpc\" | \"json\" | \"print\";\n\nexport interface ExtensionContext {\n\t/** UI methods for user interaction */\n\tui: ExtensionUIContext;\n\t/** Current run mode. Use \"tui\" to guard terminal-only UI such as custom components. */\n\tmode: ExtensionMode;\n\t/** Whether dialog-capable UI is available (true in TUI and RPC modes) */\n\thasUI: boolean;\n\t/** Current working directory */\n\tcwd: string;\n\t/** Session manager (read-only) */\n\tsessionManager: ReadonlySessionManager;\n\t/** Model registry for API key resolution */\n\tmodelRegistry: ModelRegistry;\n\t/** Current model (may be undefined) */\n\tmodel: Model | undefined;\n\t/** Models scoped to this session (resolved from `--models` /\n\t * `enabledModels` settings against the available catalogue). Same set\n\t * the `/scoped-models` command shows. Empty when no scoping is\n\t * configured (all available models are usable). Read-only snapshot. */\n\tscopedModels: readonly ScopedModel[];\n\t/** Current thinking level, when provided by the session runtime. */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Whether the agent is idle (not streaming) */\n\tisIdle(): boolean;\n\t/** Whether project-local trust is active for this context. */\n\tisProjectTrusted(): boolean;\n\t/** The current abort signal, or undefined when the agent is not streaming. */\n\tsignal: AbortSignal | undefined;\n\t/** Abort the current agent operation */\n\tabort(): void;\n\t/** Whether there are queued messages waiting */\n\thasPendingMessages(): boolean;\n\t/** Gracefully shutdown pi and exit. Available in all contexts. */\n\tshutdown(): void;\n\t/** Get current context usage for the active model. */\n\tgetContextUsage(): ContextUsage | undefined;\n\t/** Trigger compaction without awaiting completion. */\n\tcompact(options?: CompactOptions): void;\n\t/** Get the current effective system prompt. */\n\tgetSystemPrompt(): string;\n}\n\n/**\n * Extended context for command handlers.\n * Includes session control methods only safe in user-initiated commands.\n */\nexport interface ExtensionCommandContext extends ExtensionContext {\n\t/** Get the current base system-prompt construction options. */\n\tgetSystemPromptOptions(): BuildSystemPromptOptions;\n\n\t/** Wait for the agent to finish streaming */\n\twaitForIdle(): Promise;\n\n\t/** Start a new session, optionally with initialization. */\n\tnewSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/** Fork from a specific entry, creating a new session file. */\n\tfork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Navigate to a different point in the session tree. */\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Switch to a different session file. */\n\tswitchSession(\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Reload extensions, skills, prompts, themes, and context files. */\n\treload(): Promise;\n}\n\n/**\n * Fresh command-capable context bound to the replacement session after a session switch.\n *\n * This is passed to `withSession()` callbacks on `newSession()`, `fork()`, and `switchSession()`.\n */\nexport interface ReplacedSessionContext extends ExtensionCommandContext {\n\tsendMessage(\n\t\tmessage: Pick, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n\t): Promise;\n\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): Promise;\n}\n\n// ============================================================================\n// Tool Types\n// ============================================================================\n\n/** Rendering options for tool results */\nexport interface ToolRenderResultOptions {\n\t/** Whether the result view is expanded */\n\texpanded: boolean;\n\t/** Whether this is a partial/streaming result */\n\tisPartial: boolean;\n}\n\n/** Context passed to tool renderers. */\nexport interface ToolRenderContext {\n\t/** Current tool call arguments. Shared across call/result renders for the same tool call. */\n\targs: TArgs;\n\t/** Unique id for this tool execution. Stable across call/result renders for the same tool call. */\n\ttoolCallId: string;\n\t/** Invalidate just this tool execution component for redraw. */\n\tinvalidate: () => void;\n\t/** Previously returned component for this render slot, if any. */\n\tlastComponent: Component | undefined;\n\t/** Shared renderer state for this tool row. Initialized by tool-execution.ts. */\n\tstate: TState;\n\t/** Working directory for this tool execution. */\n\tcwd: string;\n\t/** Whether the tool execution has started. */\n\texecutionStarted: boolean;\n\t/** Whether the tool call arguments are complete. */\n\targsComplete: boolean;\n\t/** Whether the tool result is partial/streaming. */\n\tisPartial: boolean;\n\t/** Whether the result view is expanded. */\n\texpanded: boolean;\n\t/** Whether inline images are currently shown in the TUI. */\n\tshowImages: boolean;\n\t/** Whether the current result is an error. */\n\tisError: boolean;\n}\n\n/**\n * Tool definition for registerTool().\n */\nexport interface ToolDefinition {\n\t/** Tool name (used in LLM tool calls) */\n\tname: string;\n\t/** Human-readable label for UI */\n\tlabel: string;\n\t/** Description for LLM */\n\tdescription: string;\n\t/** Optional one-line snippet for the Available tools section in the default system prompt. Custom tools are omitted from that section when this is not provided. */\n\tpromptSnippet?: string;\n\t/** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */\n\tpromptGuidelines?: string[];\n\t/** Parameter schema (TypeBox) */\n\tparameters: TParams;\n\t/** Optional provider-side constrained sampling request for this tool. Set false to explicitly disable it, equivalent to leaving it undefined. */\n\tconstrainedSampling?: false | ConstrainedSamplingConfig;\n\t/** Controls whether ToolExecutionComponent renders the standard colored shell or the tool renders its own framing. */\n\trenderShell?: \"default\" | \"self\";\n\n\t/** Optional compatibility shim to prepare raw tool call arguments before schema validation. Must return an object conforming to TParams. */\n\tprepareArguments?: (args: unknown) => Static;\n\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n\n\t/** Execute the tool. */\n\texecute(\n\t\ttoolCallId: string,\n\t\tparams: Static,\n\t\tsignal: AbortSignal | undefined,\n\t\tonUpdate: AgentToolUpdateCallback | undefined,\n\t\tctx: ExtensionContext,\n\t): Promise>;\n\n\t/** Custom rendering for tool call display */\n\trenderCall?: (args: Static, theme: Theme, context: ToolRenderContext>) => Component;\n\n\t/** Custom rendering for tool result display */\n\trenderResult?: (\n\t\tresult: AgentToolResult,\n\t\toptions: ToolRenderResultOptions,\n\t\ttheme: Theme,\n\t\tcontext: ToolRenderContext>,\n\t) => Component;\n}\n\ntype AnyToolDefinition = ToolDefinition;\n\n/**\n * Preserve parameter inference for standalone tool definitions.\n *\n * Use this when assigning a tool to a variable or passing it through arrays such\n * as `customTools`, where contextual typing would otherwise widen params to\n * `unknown`.\n */\nexport function defineTool(\n\ttool: ToolDefinition,\n): ToolDefinition & AnyToolDefinition {\n\treturn tool as ToolDefinition & AnyToolDefinition;\n}\n\n// ============================================================================\n// Startup/Resource Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise | ProjectTrustEventResult;\n\n/** Fired after session_start to allow extensions to provide additional resource paths. */\nexport interface ResourcesDiscoverEvent {\n\ttype: \"resources_discover\";\n\tcwd: string;\n\treason: \"startup\" | \"reload\";\n}\n\n/** Result from resources_discover event handler */\nexport interface ResourcesDiscoverResult {\n\tskillPaths?: string[];\n\tpromptPaths?: string[];\n\tthemePaths?: string[];\n}\n\n// ============================================================================\n// Session Events\n// ============================================================================\n\n/** Fired when a session is started, loaded, or reloaded */\nexport interface SessionStartEvent {\n\ttype: \"session_start\";\n\t/** Why this session start happened. */\n\treason: \"startup\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\t/** Previously active session file. Present for \"new\", \"resume\", and \"fork\". */\n\tpreviousSessionFile?: string;\n}\n\n/** Fired when the current session metadata changes. */\nexport interface SessionInfoChangedEvent {\n\ttype: \"session_info_changed\";\n\t/** Current normalized session name. Undefined when the name is cleared. */\n\tname: string | undefined;\n}\n\n/** Fired before switching to another session (can be cancelled) */\nexport interface SessionBeforeSwitchEvent {\n\ttype: \"session_before_switch\";\n\treason: \"new\" | \"resume\";\n\ttargetSessionFile?: string;\n}\n\n/** Fired before forking a session (can be cancelled) */\nexport interface SessionBeforeForkEvent {\n\ttype: \"session_before_fork\";\n\tentryId: string;\n\tposition: \"before\" | \"at\";\n}\n\n/** Fired before context compaction (can be cancelled or customized) */\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\tpreparation: CompactionPreparation;\n\tbranchEntries: SessionEntry[];\n\tcustomInstructions?: string;\n\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** True when the aborted turn is retried after this compaction (overflow recovery) */\n\twillRetry: boolean;\n\tsignal: AbortSignal;\n}\n\n/** Fired after context compaction */\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\tfromExtension: boolean;\n\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** True when the aborted turn is retried after this compaction (overflow recovery) */\n\twillRetry: boolean;\n}\n\n/** Fired before an extension runtime is torn down due to quit, reload, or session replacement. */\nexport interface SessionShutdownEvent {\n\ttype: \"session_shutdown\";\n\treason: \"quit\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\t/** Destination session file when shutting down due to session replacement. */\n\ttargetSessionFile?: string;\n}\n\n/** Preparation data for tree navigation */\nexport interface TreePreparation {\n\ttargetId: string;\n\toldLeafId: string | null;\n\tcommonAncestorId: string | null;\n\tentriesToSummarize: SessionEntry[];\n\tuserWantsSummary: boolean;\n\t/** Custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Label to attach to the branch summary entry */\n\tlabel?: string;\n}\n\n/** Fired before navigating in the session tree (can be cancelled) */\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\tpreparation: TreePreparation;\n\tsignal: AbortSignal;\n}\n\n/** Fired after navigating in the session tree */\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\tnewLeafId: string | null;\n\toldLeafId: string | null;\n\tsummaryEntry?: BranchSummaryEntry;\n\tfromExtension?: boolean;\n}\n\nexport type SessionEvent =\n\t| SessionStartEvent\n\t| SessionInfoChangedEvent\n\t| SessionBeforeSwitchEvent\n\t| SessionBeforeForkEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionShutdownEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent;\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/** Fired before each LLM call. Can modify messages. */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/**\n * Fired after request headers are assembled, before the provider HTTP call.\n * Handlers mutate `headers` in place (e.g. to inject tracing/session headers);\n * the return value is ignored. A `null` value deletes that header.\n */\nexport interface BeforeProviderHeadersEvent {\n\ttype: \"before_provider_headers\";\n\theaders: ProviderHeaders;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The fully assembled system prompt string. */\n\tsystemPrompt: string;\n\t/** Structured options used to build the system prompt. Extensions can inspect this to understand what Pi loaded without re-discovering resources. */\n\tsystemPromptOptions: BuildSystemPromptOptions;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired after an agent run has fully settled and no automatic retry, compaction, or queued continuation will run. */\nexport interface AgentSettledEvent {\n\ttype: \"agent_settled\";\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: any;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: any;\n\tpartialResult: any;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: any;\n\tisError: boolean;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model;\n\tpreviousModel: Model | undefined;\n\tsource: ModelSelectSource;\n}\n\n/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n\t/** How the input will be delivered during streaming, or undefined when idle */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n\n// ============================================================================\n// Tool Events\n// ============================================================================\n\ninterface ToolCallEventBase {\n\ttype: \"tool_call\";\n\ttoolCallId: string;\n}\n\nexport interface BashToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"bash\";\n\tinput: BashToolInput;\n}\n\nexport interface ReadToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"read\";\n\tinput: ReadToolInput;\n}\n\nexport interface EditToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"edit\";\n\tinput: EditToolInput;\n}\n\nexport interface WriteToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"write\";\n\tinput: WriteToolInput;\n}\n\nexport interface GrepToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"grep\";\n\tinput: GrepToolInput;\n}\n\nexport interface FindToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"find\";\n\tinput: FindToolInput;\n}\n\nexport interface LsToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"ls\";\n\tinput: LsToolInput;\n}\n\nexport interface CustomToolCallEvent extends ToolCallEventBase {\n\ttoolName: string;\n\tinput: Record;\n}\n\n/**\n * Fired before a tool executes. Can block.\n *\n * `event.input` is mutable. Mutate it in place to patch tool arguments before execution.\n * Later `tool_call` handlers see earlier mutations. No re-validation is performed after mutation.\n */\nexport type ToolCallEvent =\n\t| BashToolCallEvent\n\t| ReadToolCallEvent\n\t| EditToolCallEvent\n\t| WriteToolCallEvent\n\t| GrepToolCallEvent\n\t| FindToolCallEvent\n\t| LsToolCallEvent\n\t| CustomToolCallEvent;\n\ninterface ToolResultEventBase {\n\ttype: \"tool_result\";\n\ttoolCallId: string;\n\tinput: Record;\n\tcontent: (TextContent | ImageContent)[];\n\tisError: boolean;\n\t/** Usage from the tool execution itself, if available. */\n\tusage?: Usage;\n}\n\nexport interface BashToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"bash\";\n\tdetails: BashToolDetails | undefined;\n}\n\nexport interface ReadToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"read\";\n\tdetails: ReadToolDetails | undefined;\n}\n\nexport interface EditToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"edit\";\n\tdetails: EditToolDetails | undefined;\n}\n\nexport interface WriteToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"write\";\n\tdetails: undefined;\n}\n\nexport interface GrepToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"grep\";\n\tdetails: GrepToolDetails | undefined;\n}\n\nexport interface FindToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"find\";\n\tdetails: FindToolDetails | undefined;\n}\n\nexport interface LsToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"ls\";\n\tdetails: LsToolDetails | undefined;\n}\n\nexport interface CustomToolResultEvent extends ToolResultEventBase {\n\ttoolName: string;\n\tdetails: unknown;\n}\n\n/** Fired after a tool executes. Can modify result. */\nexport type ToolResultEvent =\n\t| BashToolResultEvent\n\t| ReadToolResultEvent\n\t| EditToolResultEvent\n\t| WriteToolResultEvent\n\t| GrepToolResultEvent\n\t| FindToolResultEvent\n\t| LsToolResultEvent\n\t| CustomToolResultEvent;\n\n// Type guards for ToolResultEvent\nexport function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {\n\treturn e.toolName === \"bash\";\n}\nexport function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {\n\treturn e.toolName === \"read\";\n}\nexport function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {\n\treturn e.toolName === \"edit\";\n}\nexport function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {\n\treturn e.toolName === \"write\";\n}\nexport function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {\n\treturn e.toolName === \"grep\";\n}\nexport function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {\n\treturn e.toolName === \"find\";\n}\nexport function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {\n\treturn e.toolName === \"ls\";\n}\n\n/**\n * Type guard for narrowing ToolCallEvent by tool name.\n *\n * Built-in tools narrow automatically (no type params needed):\n * ```ts\n * if (isToolCallEventType(\"bash\", event)) {\n * event.input.command; // string\n * }\n * ```\n *\n * Custom tools require explicit type parameters:\n * ```ts\n * if (isToolCallEventType<\"my_tool\", MyToolInput>(\"my_tool\", event)) {\n * event.input.action; // typed\n * }\n * ```\n *\n * Note: Direct narrowing via `event.toolName === \"bash\"` doesn't work because\n * CustomToolCallEvent.toolName is `string` which overlaps with all literals.\n */\nexport function isToolCallEventType(toolName: \"bash\", event: ToolCallEvent): event is BashToolCallEvent;\nexport function isToolCallEventType(toolName: \"read\", event: ToolCallEvent): event is ReadToolCallEvent;\nexport function isToolCallEventType(toolName: \"edit\", event: ToolCallEvent): event is EditToolCallEvent;\nexport function isToolCallEventType(toolName: \"write\", event: ToolCallEvent): event is WriteToolCallEvent;\nexport function isToolCallEventType(toolName: \"grep\", event: ToolCallEvent): event is GrepToolCallEvent;\nexport function isToolCallEventType(toolName: \"find\", event: ToolCallEvent): event is FindToolCallEvent;\nexport function isToolCallEventType(toolName: \"ls\", event: ToolCallEvent): event is LsToolCallEvent;\nexport function isToolCallEventType>(\n\ttoolName: TName,\n\tevent: ToolCallEvent,\n): event is ToolCallEvent & { toolName: TName; input: TInput };\nexport function isToolCallEventType(toolName: string, event: ToolCallEvent): boolean {\n\treturn event.toolName === toolName;\n}\n\n/** Union of all event types */\nexport type ExtensionEvent =\n\t| ProjectTrustEvent\n\t| ResourcesDiscoverEvent\n\t| SessionEvent\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeProviderHeadersEvent\n\t| AfterProviderResponseEvent\n\t| BeforeAgentStartEvent\n\t| AgentStartEvent\n\t| AgentEndEvent\n\t| AgentSettledEvent\n\t| TurnStartEvent\n\t| TurnEndEvent\n\t| MessageStartEvent\n\t| MessageUpdateEvent\n\t| MessageEndEvent\n\t| ToolExecutionStartEvent\n\t| ToolExecutionUpdateEvent\n\t| ToolExecutionEndEvent\n\t| ModelSelectEvent\n\t| ThinkingLevelSelectEvent\n\t| UserBashEvent\n\t| InputEvent\n\t| ToolCallEvent\n\t| ToolResultEvent;\n\n// ============================================================================\n// Event Results\n// ============================================================================\n\nexport interface ContextEventResult {\n\tmessages?: AgentMessage[];\n}\n\nexport type BeforeProviderRequestEventResult = unknown;\n\nexport interface ToolCallEventResult {\n\t/** Block tool execution. To modify arguments, mutate `event.input` in place instead. */\n\tblock?: boolean;\n\treason?: string;\n}\n\n/** Result from user_bash event handler */\nexport interface UserBashEventResult {\n\t/** Custom operations to use for execution */\n\toperations?: BashOperations;\n\t/** Full replacement: extension handled execution, use this result */\n\tresult?: BashResult;\n}\n\nexport interface ToolResultEventResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n\tusage?: Usage;\n}\n\nexport interface MessageEndEventResult {\n\t/** Replace the finalized message. The replacement must keep the original message role. */\n\tmessage?: AgentMessage;\n}\n\nexport interface BeforeAgentStartEventResult {\n\tmessage?: Pick;\n\t/** Replace the system prompt for this turn. If multiple extensions return this, they are chained. */\n\tsystemPrompt?: string;\n}\n\nexport interface SessionBeforeSwitchResult {\n\tcancel?: boolean;\n}\n\nexport interface SessionBeforeForkResult {\n\tcancel?: boolean;\n\tskipConversationRestore?: boolean;\n}\n\nexport interface SessionBeforeCompactResult {\n\tcancel?: boolean;\n\tcompaction?: CompactionResult;\n}\n\nexport interface SessionBeforeTreeResult {\n\tcancel?: boolean;\n\tsummary?: {\n\t\tsummary: string;\n\t\tdetails?: unknown;\n\t\tusage?: Usage;\n\t};\n\t/** Override custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** Override whether customInstructions replaces the default prompt */\n\treplaceInstructions?: boolean;\n\t/** Override label to attach to the branch summary entry */\n\tlabel?: string;\n}\n\n// ============================================================================\n// Message and Entry Rendering\n// ============================================================================\n\nexport interface MessageRenderOptions {\n\texpanded: boolean;\n\t/** Horizontal padding configured by the outputPad setting. */\n\toutputPad: number;\n}\n\nexport interface EntryRenderOptions {\n\texpanded: boolean;\n}\n\nexport type MessageRenderer = (\n\tmessage: CustomMessage,\n\toptions: MessageRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\nexport type EntryRenderer = (\n\tentry: CustomEntry,\n\toptions: EntryRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\nexport interface RegisteredCommand {\n\tname: string;\n\tsourceInfo: SourceInfo;\n\tdescription?: string;\n\tgetArgumentCompletions?: (argumentPrefix: string) => AutocompleteItem[] | null | Promise;\n\thandler: (args: string, ctx: ExtensionCommandContext) => Promise;\n}\n\nexport interface ResolvedCommand extends RegisteredCommand {\n\tinvocationName: string;\n}\n\n// ============================================================================\n// Extension API\n// ============================================================================\n\n/** Handler function type for events */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements\nexport type ExtensionHandler = (event: E, ctx: ExtensionContext) => Promise | R | void;\n\n/**\n * ExtensionAPI passed to extension factory functions.\n */\nexport interface ExtensionAPI {\n\t// =========================================================================\n\t// Event Subscription\n\t// =========================================================================\n\n\ton(event: \"project_trust\", handler: ProjectTrustHandler): void;\n\ton(event: \"resources_discover\", handler: ExtensionHandler): void;\n\ton(event: \"session_start\", handler: ExtensionHandler): void;\n\ton(event: \"session_info_changed\", handler: ExtensionHandler): void;\n\ton(\n\t\tevent: \"session_before_switch\",\n\t\thandler: ExtensionHandler,\n\t): void;\n\ton(event: \"session_before_fork\", handler: ExtensionHandler): void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: ExtensionHandler,\n\t): void;\n\ton(event: \"session_compact\", handler: ExtensionHandler): void;\n\ton(event: \"session_shutdown\", handler: ExtensionHandler): void;\n\ton(event: \"session_before_tree\", handler: ExtensionHandler): void;\n\ton(event: \"session_tree\", handler: ExtensionHandler): void;\n\ton(event: \"context\", handler: ExtensionHandler): void;\n\ton(\n\t\tevent: \"before_provider_request\",\n\t\thandler: ExtensionHandler,\n\t): void;\n\ton(event: \"before_provider_headers\", handler: ExtensionHandler): void;\n\ton(event: \"after_provider_response\", handler: ExtensionHandler): void;\n\ton(event: \"before_agent_start\", handler: ExtensionHandler): void;\n\ton(event: \"agent_start\", handler: ExtensionHandler): void;\n\ton(event: \"agent_end\", handler: ExtensionHandler): void;\n\ton(event: \"agent_settled\", handler: ExtensionHandler): void;\n\ton(event: \"turn_start\", handler: ExtensionHandler): void;\n\ton(event: \"turn_end\", handler: ExtensionHandler): void;\n\ton(event: \"message_start\", handler: ExtensionHandler): void;\n\ton(event: \"message_update\", handler: ExtensionHandler): void;\n\ton(event: \"message_end\", handler: ExtensionHandler): void;\n\ton(event: \"tool_execution_start\", handler: ExtensionHandler): void;\n\ton(event: \"tool_execution_update\", handler: ExtensionHandler): void;\n\ton(event: \"tool_execution_end\", handler: ExtensionHandler): void;\n\ton(event: \"model_select\", handler: ExtensionHandler): void;\n\ton(event: \"thinking_level_select\", handler: ExtensionHandler): void;\n\ton(event: \"tool_call\", handler: ExtensionHandler): void;\n\ton(event: \"tool_result\", handler: ExtensionHandler): void;\n\ton(event: \"user_bash\", handler: ExtensionHandler): void;\n\ton(event: \"input\", handler: ExtensionHandler): void;\n\n\t// =========================================================================\n\t// Tool Registration\n\t// =========================================================================\n\n\t/** Register a tool that the LLM can call. */\n\tregisterTool(\n\t\ttool: ToolDefinition,\n\t): void;\n\n\t// =========================================================================\n\t// Command, Shortcut, Flag Registration\n\t// =========================================================================\n\n\t/** Register a custom command. */\n\tregisterCommand(name: string, options: Omit): void;\n\n\t/** Register a keyboard shortcut. */\n\tregisterShortcut(\n\t\tshortcut: KeyId,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\thandler: (ctx: ExtensionContext) => Promise | void;\n\t\t},\n\t): void;\n\n\t/** Register a CLI flag. */\n\tregisterFlag(\n\t\tname: string,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\ttype: \"boolean\" | \"string\";\n\t\t\tdefault?: boolean | string;\n\t\t},\n\t): void;\n\n\t/** Get the value of a registered CLI flag. */\n\tgetFlag(name: string): boolean | string | undefined;\n\n\t// =========================================================================\n\t// Message Rendering\n\t// =========================================================================\n\n\t/** Register a custom renderer for CustomMessageEntry. */\n\tregisterMessageRenderer(customType: string, renderer: MessageRenderer): void;\n\n\t/** Register a custom renderer for CustomEntry. Custom entries do not participate in LLM context. */\n\tregisterEntryRenderer(customType: string, renderer: EntryRenderer): void;\n\n\t// =========================================================================\n\t// Actions\n\t// =========================================================================\n\n\t/** Send a custom message to the session. */\n\tsendMessage(\n\t\tmessage: Pick, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n\t): void;\n\n\t/**\n\t * Send a user message to the agent. Always triggers a turn.\n\t * When the agent is streaming, use deliverAs to specify how to queue the message.\n\t */\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): void;\n\n\t/** Append a custom entry to the session for state persistence (not sent to LLM). */\n\tappendEntry(customType: string, data?: T): void;\n\n\t// =========================================================================\n\t// Session Metadata\n\t// =========================================================================\n\n\t/** Set the session display name (shown in session selector). */\n\tsetSessionName(name: string): void;\n\n\t/** Get the current session name, if set. */\n\tgetSessionName(): string | undefined;\n\n\t/** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */\n\tsetLabel(entryId: string, label: string | undefined): void;\n\n\t/** Execute a shell command. */\n\texec(command: string, args: string[], options?: ExecOptions): Promise;\n\n\t/** Get the list of currently active tool names. */\n\tgetActiveTools(): string[];\n\n\t/** Get all configured tools with parameter schema, prompt guidelines, and source metadata. */\n\tgetAllTools(): ToolInfo[];\n\n\t/** Set the active tools by name. */\n\tsetActiveTools(toolNames: string[]): void;\n\n\t/** Get available slash commands in the current session. */\n\tgetCommands(): SlashCommandInfo[];\n\n\t// =========================================================================\n\t// Model and Thinking Level\n\t// =========================================================================\n\n\t/** Set the current model. Returns false if no API key available. */\n\tsetModel(model: Model): Promise;\n\n\t/** Get current thinking level. */\n\tgetThinkingLevel(): ThinkingLevel;\n\n\t/** Set thinking level (clamped to model capabilities). */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\n\t// =========================================================================\n\t// Provider Registration\n\t// =========================================================================\n\n\t/**\n\t * Register or override a model provider.\n\t *\n\t * If `models` is provided: replaces all existing models for this provider.\n\t * If only `baseUrl` is provided: overrides the URL for existing models.\n\t * If `oauth` is provided: registers OAuth provider for /login support.\n\t * If `streamSimple` is provided: registers a custom API stream handler.\n\t *\n\t * During initial extension load this call is queued and applied once the\n\t * runner has bound its context. After that it takes effect immediately, so\n\t * it is safe to call from command handlers or event callbacks without\n\t * requiring a `/reload`.\n\t *\n\t * @example\n\t * // Register a new provider with custom models\n\t * pi.registerProvider(\"my-proxy\", {\n\t * baseUrl: \"https://proxy.example.com\",\n\t * apiKey: \"$PROXY_API_KEY\",\n\t * api: \"anthropic-messages\",\n\t * models: [\n\t * {\n\t * id: \"claude-sonnet-4-20250514\",\n\t * name: \"Claude 4 Sonnet (proxy)\",\n\t * reasoning: false,\n\t * input: [\"text\", \"image\"],\n\t * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t * contextWindow: 200000,\n\t * maxTokens: 16384\n\t * }\n\t * ]\n\t * });\n\t *\n\t * @example\n\t * // Override baseUrl for an existing provider\n\t * pi.registerProvider(\"anthropic\", {\n\t * baseUrl: \"https://proxy.example.com\"\n\t * });\n\t *\n\t * @example\n\t * // Register provider with OAuth support\n\t * pi.registerProvider(\"corporate-ai\", {\n\t * baseUrl: \"https://ai.corp.com\",\n\t * api: \"openai-responses\",\n\t * models: [...],\n\t * oauth: {\n\t * name: \"Corporate AI (SSO)\",\n\t * async login(callbacks) { ... },\n\t * async refreshToken(credentials) { ... },\n\t * getApiKey(credentials) { return credentials.access; }\n\t * }\n\t * });\n\t */\n\tregisterProvider(provider: Provider): void;\n\tregisterProvider(name: string, config: ProviderConfig): void;\n\n\t/**\n\t * Unregister a previously registered provider.\n\t *\n\t * Removes all models belonging to the named provider and restores any\n\t * built-in models that were overridden by it. Has no effect if the provider\n\t * is not currently registered.\n\t *\n\t * Like `registerProvider`, this takes effect immediately when called after\n\t * the initial load phase.\n\t *\n\t * @example\n\t * pi.unregisterProvider(\"my-proxy\");\n\t */\n\tunregisterProvider(name: string): void;\n\n\t/** Shared event bus for extension communication. */\n\tevents: EventBus;\n}\n\n// ============================================================================\n// Provider Registration Types\n// ============================================================================\n\n/** Configuration for registering a provider via pi.registerProvider(). */\nexport interface ProviderConfig {\n\t/** Display name for the provider in UI. */\n\tname?: string;\n\t/** Base URL for the API endpoint. Required when defining models. */\n\tbaseUrl?: string;\n\t/** API key literal, env interpolation ($ENV_VAR or ${ENV_VAR}), or leading !command. Required when defining models (unless oauth provided). */\n\tapiKey?: string;\n\t/** API type. Required at provider or model level when defining models. */\n\tapi?: Api;\n\t/** Optional streamSimple handler for custom APIs. */\n\tstreamSimple?: (model: Model, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\t/** Custom headers to include in requests. */\n\theaders?: Record;\n\t/** If true, adds Authorization: Bearer header with the resolved API key. */\n\tauthHeader?: boolean;\n\t/** Models to register. If provided, replaces all existing models for this provider. */\n\tmodels?: ProviderModelConfig[];\n\t/**\n\t * Refresh this provider's model list. The returned list replaces extension-provided models.\n\t * Use context.store explicitly when the catalog should persist across sessions.\n\t */\n\trefreshModels?(context: RefreshModelsContext): Promise;\n\t/** OAuth provider for /login support. The `id` is set automatically from the provider name. */\n\toauth?: {\n\t\t/** Display name for the provider in login UI. */\n\t\tname: string;\n\t\t/** @deprecated Retained for source compatibility; canonical auth flows ignore it. */\n\t\tusesCallbackServer?: boolean;\n\t\t/** Run the login flow, return credentials to persist. */\n\t\tlogin(callbacks: OAuthLoginCallbacks): Promise;\n\t\t/** Refresh expired credentials, return updated credentials to persist. */\n\t\trefreshToken(credentials: OAuthCredentials): Promise;\n\t\t/** Convert credentials to API key string for the provider. */\n\t\tgetApiKey(credentials: OAuthCredentials): string;\n\t\t/** Legacy synchronous credential-dependent model projection. */\n\t\tmodifyModels?(models: Model[], credentials: OAuthCredentials): Model[];\n\t};\n}\n\n/** Configuration for a model within a provider. */\nexport interface ProviderModelConfig {\n\t/** Model ID (e.g., \"claude-sonnet-4-20250514\"). */\n\tid: string;\n\t/** Display name (e.g., \"Claude 4 Sonnet\"). */\n\tname: string;\n\t/** API type override for this model. */\n\tapi?: Api;\n\t/** API endpoint URL override for this model. */\n\tbaseUrl?: string;\n\t/** Whether the model supports extended thinking. */\n\treasoning: boolean;\n\t/** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */\n\tthinkingLevelMap?: Model[\"thinkingLevelMap\"];\n\t/** Supported input types. */\n\tinput: (\"text\" | \"image\")[];\n\t/** Per-million-token cost rates and optional request-wide input pricing tiers. */\n\tcost: Model[\"cost\"];\n\t/** Maximum context window size in tokens. */\n\tcontextWindow: number;\n\t/** Maximum output tokens. */\n\tmaxTokens: number;\n\t/** Custom headers for this model. */\n\theaders?: Record;\n\t/** OpenAI compatibility settings. */\n\tcompat?: Model[\"compat\"];\n}\n\n/** Extension factory function type. Supports both sync and async initialization. */\nexport type ExtensionFactory = (pi: ExtensionAPI) => void | Promise;\n\nexport type InlineExtension =\n\t| ExtensionFactory\n\t| {\n\t\t\t/** Display name shown as `` in the startup Extensions list. */\n\t\t\tname: string;\n\t\t\tfactory: ExtensionFactory;\n\t\t\t/** Omit this extension from the startup Extensions list. */\n\t\t\thidden?: boolean;\n\t };\n\n// ============================================================================\n// Loaded Extension Types\n// ============================================================================\n\nexport interface RegisteredTool {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface ExtensionFlag {\n\tname: string;\n\tdescription?: string;\n\ttype: \"boolean\" | \"string\";\n\tdefault?: boolean | string;\n\textensionPath: string;\n}\n\nexport interface ExtensionShortcut {\n\tshortcut: KeyId;\n\tdescription?: string;\n\thandler: (ctx: ExtensionContext) => Promise | void;\n\textensionPath: string;\n}\n\ntype HandlerFn = (...args: unknown[]) => Promise;\n\nexport type SendMessageHandler = (\n\tmessage: Pick, \"customType\" | \"content\" | \"display\" | \"details\">,\n\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n) => void;\n\nexport type SendUserMessageHandler = (\n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n) => void;\n\nexport type AppendEntryHandler = (customType: string, data?: T) => void;\n\nexport type SetSessionNameHandler = (name: string) => void;\n\nexport type GetSessionNameHandler = () => string | undefined;\n\nexport type GetActiveToolsHandler = () => string[];\n\n/** Tool info with name, description, parameter schema, prompt guidelines, and source metadata. */\nexport type ToolInfo = Pick & {\n\tsourceInfo: SourceInfo;\n};\n\nexport type GetAllToolsHandler = () => ToolInfo[];\n\nexport type GetCommandsHandler = () => SlashCommandInfo[];\n\nexport type SetActiveToolsHandler = (toolNames: string[]) => void;\n\nexport type RefreshToolsHandler = () => void;\n\nexport type SetModelHandler = (model: Model) => Promise;\n\nexport type GetThinkingLevelHandler = () => ThinkingLevel;\n\nexport type SetThinkingLevelHandler = (level: ThinkingLevel) => void;\n\nexport type SetLabelHandler = (entryId: string, label: string | undefined) => void;\n\n/**\n * Shared state created by loader, used during registration and runtime.\n * Contains flag values (defaults set during registration, CLI values set after).\n */\nexport interface ExtensionRuntimeState {\n\tflagValues: Map;\n\t/** Legacy provider-config registrations queued during extension loading, processed when runner binds. */\n\tpendingProviderRegistrations: Array<{ name: string; config: ProviderConfig; extensionPath: string }>;\n\t/** Native pi-ai provider registrations queued during extension loading, processed when runner binds. */\n\tpendingNativeProviderRegistrations: Array<{ provider: Provider; extensionPath: string }>;\n\t/** Throws when this extension instance is stale after runtime replacement. */\n\tassertActive: () => void;\n\t/** Marks this extension instance as stale after runtime replacement or reload. */\n\tinvalidate: (message?: string) => void;\n\t/**\n\t * Register or unregister a provider.\n\t *\n\t * Before bindCore(): queues registrations / removes from queue.\n\t * After bindCore(): calls ModelRegistry directly for immediate effect.\n\t */\n\tregisterProvider: (name: string, config: ProviderConfig, extensionPath?: string) => void;\n\tregisterNativeProvider: (provider: Provider, extensionPath?: string) => void;\n\tunregisterProvider: (name: string, extensionPath?: string) => void;\n}\n\n/**\n * Action implementations for pi.* API methods.\n * Provided to runner.initialize(), copied into the shared runtime.\n */\nexport interface ExtensionActions {\n\tsendMessage: SendMessageHandler;\n\tsendUserMessage: SendUserMessageHandler;\n\tappendEntry: AppendEntryHandler;\n\tsetSessionName: SetSessionNameHandler;\n\tgetSessionName: GetSessionNameHandler;\n\tsetLabel: SetLabelHandler;\n\tgetActiveTools: GetActiveToolsHandler;\n\tgetAllTools: GetAllToolsHandler;\n\tsetActiveTools: SetActiveToolsHandler;\n\trefreshTools: RefreshToolsHandler;\n\tgetCommands: GetCommandsHandler;\n\tsetModel: SetModelHandler;\n\tgetThinkingLevel: GetThinkingLevelHandler;\n\tsetThinkingLevel: SetThinkingLevelHandler;\n}\n\n/**\n * Actions for ExtensionContext (ctx.* in event handlers).\n * Required by all modes.\n */\nexport interface ExtensionContextActions {\n\tgetModel: () => Model | undefined;\n\tgetScopedModels: () => readonly ScopedModel[];\n\tisIdle: () => boolean;\n\tisProjectTrusted: () => boolean;\n\tgetSignal: () => AbortSignal | undefined;\n\tabort: () => void;\n\thasPendingMessages: () => boolean;\n\tshutdown: () => void;\n\tgetContextUsage: () => ContextUsage | undefined;\n\tcompact: (options?: CompactOptions) => void;\n\tgetSystemPrompt: () => string;\n\tgetSystemPromptOptions?: () => BuildSystemPromptOptions;\n}\n\n/**\n * Actions for ExtensionCommandContext (ctx.* in command handlers).\n * Only needed for interactive mode where extension commands are invokable.\n */\nexport interface ExtensionCommandContextActions {\n\twaitForIdle: () => Promise;\n\tnewSession: (options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise;\n\t}) => Promise<{ cancelled: boolean }>;\n\tfork: (\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise },\n\t) => Promise<{ cancelled: boolean }>;\n\tnavigateTree: (\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t) => Promise<{ cancelled: boolean }>;\n\tswitchSession: (\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise },\n\t) => Promise<{ cancelled: boolean }>;\n\treload: () => Promise;\n}\n\n/**\n * Full runtime = state + actions.\n * Created by loader with throwing action stubs, completed by runner.initialize().\n */\nexport interface ExtensionRuntime extends ExtensionRuntimeState, ExtensionActions {}\n\n/** Loaded extension with all registered items. */\nexport interface Extension {\n\tpath: string;\n\tresolvedPath: string;\n\thidden?: boolean;\n\tsourceInfo: SourceInfo;\n\thandlers: Map;\n\ttools: Map;\n\tmessageRenderers: Map;\n\tentryRenderers?: Map;\n\tcommands: Map;\n\tflags: Map;\n\tshortcuts: Map;\n}\n\n/** Result of loading extensions. */\nexport interface LoadExtensionsResult {\n\textensions: Extension[];\n\terrors: Array<{ path: string; error: string }>;\n\t/** Shared runtime - actions are throwing stubs until runner.initialize() */\n\truntime: ExtensionRuntime;\n}\n\n// ============================================================================\n// Extension Error\n// ============================================================================\n\nexport interface ExtensionError {\n\textensionPath: string;\n\tevent: string;\n\terror: string;\n\tstack?: string;\n}\n"]} \ No newline at end of file diff --git a/dist/core/extensions/wrapper.d.ts b/dist/core/extensions/wrapper.d.ts new file mode 100644 index 0000000..0fc6ba1 --- /dev/null +++ b/dist/core/extensions/wrapper.d.ts @@ -0,0 +1,20 @@ +/** + * Tool wrappers for extension-registered tools. + * + * These wrappers only adapt tool execution so extension tools receive the runner context. + * Tool call and tool result interception is handled by AgentSession via agent-core hooks. + */ +import type { AgentTool } from "@earendil-works/pi-agent-core"; +import type { ExtensionRunner } from "./runner.ts"; +import type { RegisteredTool } from "./types.ts"; +/** + * Wrap a RegisteredTool into an AgentTool. + * Uses the runner's createContext() for consistent context across tools and event handlers. + */ +export declare function wrapRegisteredTool(registeredTool: RegisteredTool, runner: ExtensionRunner): AgentTool; +/** + * Wrap all registered tools into AgentTools. + * Uses the runner's createContext() for consistent context across tools and event handlers. + */ +export declare function wrapRegisteredTools(registeredTools: RegisteredTool[], runner: ExtensionRunner): AgentTool[]; +//# sourceMappingURL=wrapper.d.ts.map \ No newline at end of file diff --git a/dist/core/extensions/wrapper.d.ts.map b/dist/core/extensions/wrapper.d.ts.map new file mode 100644 index 0000000..0ad5627 --- /dev/null +++ b/dist/core/extensions/wrapper.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"wrapper.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/wrapper.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAE/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,cAAc,EAAE,cAAc,EAAE,MAAM,EAAE,eAAe,GAAG,SAAS,CAoBrG;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,eAAe,EAAE,cAAc,EAAE,EAAE,MAAM,EAAE,eAAe,GAAG,SAAS,EAAE,CAE3G","sourcesContent":["/**\n * Tool wrappers for extension-registered tools.\n *\n * These wrappers only adapt tool execution so extension tools receive the runner context.\n * Tool call and tool result interception is handled by AgentSession via agent-core hooks.\n */\n\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { wrapToolDefinition } from \"../tools/tool-definition-wrapper.ts\";\nimport type { ExtensionRunner } from \"./runner.ts\";\nimport type { RegisteredTool } from \"./types.ts\";\n\n/**\n * Wrap a RegisteredTool into an AgentTool.\n * Uses the runner's createContext() for consistent context across tools and event handlers.\n */\nexport function wrapRegisteredTool(registeredTool: RegisteredTool, runner: ExtensionRunner): AgentTool {\n\tconst tool = wrapToolDefinition(registeredTool.definition, () => runner.createContext());\n\tconst execute = tool.execute;\n\treturn {\n\t\t...tool,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => {\n\t\t\tconst activeBefore = runner.getActiveTools();\n\t\t\tconst result = await execute(toolCallId, params, signal, onUpdate);\n\t\t\tconst activeAfter = runner.getActiveTools();\n\t\t\tif (!activeBefore.every((name) => activeAfter.includes(name))) return result;\n\n\t\t\tconst beforeNames = new Set(activeBefore);\n\t\t\tconst addedToolNames = activeAfter.filter((name) => !beforeNames.has(name));\n\t\t\tif (addedToolNames.length === 0) return result;\n\t\t\treturn {\n\t\t\t\t...result,\n\t\t\t\taddedToolNames: [...new Set([...(result.addedToolNames ?? []), ...addedToolNames])],\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Wrap all registered tools into AgentTools.\n * Uses the runner's createContext() for consistent context across tools and event handlers.\n */\nexport function wrapRegisteredTools(registeredTools: RegisteredTool[], runner: ExtensionRunner): AgentTool[] {\n\treturn registeredTools.map((tool) => wrapRegisteredTool(tool, runner));\n}\n"]} \ No newline at end of file diff --git a/dist/core/extensions/wrapper.js b/dist/core/extensions/wrapper.js new file mode 100644 index 0000000..1e9f713 --- /dev/null +++ b/dist/core/extensions/wrapper.js @@ -0,0 +1,41 @@ +/** + * Tool wrappers for extension-registered tools. + * + * These wrappers only adapt tool execution so extension tools receive the runner context. + * Tool call and tool result interception is handled by AgentSession via agent-core hooks. + */ +import { wrapToolDefinition } from "../tools/tool-definition-wrapper.js"; +/** + * Wrap a RegisteredTool into an AgentTool. + * Uses the runner's createContext() for consistent context across tools and event handlers. + */ +export function wrapRegisteredTool(registeredTool, runner) { + const tool = wrapToolDefinition(registeredTool.definition, () => runner.createContext()); + const execute = tool.execute; + return { + ...tool, + execute: async (toolCallId, params, signal, onUpdate) => { + const activeBefore = runner.getActiveTools(); + const result = await execute(toolCallId, params, signal, onUpdate); + const activeAfter = runner.getActiveTools(); + if (!activeBefore.every((name) => activeAfter.includes(name))) + return result; + const beforeNames = new Set(activeBefore); + const addedToolNames = activeAfter.filter((name) => !beforeNames.has(name)); + if (addedToolNames.length === 0) + return result; + return { + ...result, + addedToolNames: [...new Set([...(result.addedToolNames ?? []), ...addedToolNames])], + }; + }, + }; +} +/** + * Wrap all registered tools into AgentTools. + * Uses the runner's createContext() for consistent context across tools and event handlers. + */ +export function wrapRegisteredTools(registeredTools, runner) { + return registeredTools.map((tool) => wrapRegisteredTool(tool, runner)); +} +//# sourceMappingURL=wrapper.js.map \ No newline at end of file diff --git a/dist/core/extensions/wrapper.js.map b/dist/core/extensions/wrapper.js.map new file mode 100644 index 0000000..7058526 --- /dev/null +++ b/dist/core/extensions/wrapper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"wrapper.js","sourceRoot":"","sources":["../../../src/core/extensions/wrapper.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,kBAAkB,EAAE,MAAM,qCAAqC,CAAC;AAIzE;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,cAA8B,EAAE,MAAuB,EAAa;IACtG,MAAM,IAAI,GAAG,kBAAkB,CAAC,cAAc,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MAAM,CAAC,CAAC,CAAC;AAAA,CACvE","sourcesContent":["/**\n * Tool wrappers for extension-registered tools.\n *\n * These wrappers only adapt tool execution so extension tools receive the runner context.\n * Tool call and tool result interception is handled by AgentSession via agent-core hooks.\n */\n\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { wrapToolDefinition } from \"../tools/tool-definition-wrapper.ts\";\nimport type { ExtensionRunner } from \"./runner.ts\";\nimport type { RegisteredTool } from \"./types.ts\";\n\n/**\n * Wrap a RegisteredTool into an AgentTool.\n * Uses the runner's createContext() for consistent context across tools and event handlers.\n */\nexport function wrapRegisteredTool(registeredTool: RegisteredTool, runner: ExtensionRunner): AgentTool {\n\tconst tool = wrapToolDefinition(registeredTool.definition, () => runner.createContext());\n\tconst execute = tool.execute;\n\treturn {\n\t\t...tool,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => {\n\t\t\tconst activeBefore = runner.getActiveTools();\n\t\t\tconst result = await execute(toolCallId, params, signal, onUpdate);\n\t\t\tconst activeAfter = runner.getActiveTools();\n\t\t\tif (!activeBefore.every((name) => activeAfter.includes(name))) return result;\n\n\t\t\tconst beforeNames = new Set(activeBefore);\n\t\t\tconst addedToolNames = activeAfter.filter((name) => !beforeNames.has(name));\n\t\t\tif (addedToolNames.length === 0) return result;\n\t\t\treturn {\n\t\t\t\t...result,\n\t\t\t\taddedToolNames: [...new Set([...(result.addedToolNames ?? []), ...addedToolNames])],\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Wrap all registered tools into AgentTools.\n * Uses the runner's createContext() for consistent context across tools and event handlers.\n */\nexport function wrapRegisteredTools(registeredTools: RegisteredTool[], runner: ExtensionRunner): AgentTool[] {\n\treturn registeredTools.map((tool) => wrapRegisteredTool(tool, runner));\n}\n"]} \ No newline at end of file diff --git a/dist/core/footer-data-provider.d.ts b/dist/core/footer-data-provider.d.ts new file mode 100644 index 0000000..7c64e48 --- /dev/null +++ b/dist/core/footer-data-provider.d.ts @@ -0,0 +1,64 @@ +export type GitPaths = { + repoDir: string; + commonGitDir: string; + headPath: string; +}; +/** + * Find git metadata paths by walking up from cwd. + * Handles both regular git repos (.git is a directory) and worktrees (.git is a file). + */ +export declare function findGitPaths(cwd: string): GitPaths | null; +/** + * Provides git branch and extension statuses - data not otherwise accessible to extensions. + * Token stats, model info available via ctx.sessionManager and ctx.model. + */ +export declare class FooterDataProvider { + private cwd; + private static readonly WATCH_DEBOUNCE_MS; + private extensionStatuses; + private cachedBranch; + private gitPaths; + private headWatcher; + private headWatchFilePath; + private headWatchFileListener; + private reftableWatcher; + private reftableTablesListWatcher; + private reftableTablesListPath; + private branchChangeCallbacks; + private availableProviderCount; + private refreshTimer; + private gitWatcherRetryTimer; + private refreshInFlight; + private refreshPending; + private disposed; + constructor(cwd: string); + /** Current git branch, null if not in repo, "detached" if detached HEAD */ + getGitBranch(): string | null; + /** Extension status texts set via ctx.ui.setStatus() */ + getExtensionStatuses(): ReadonlyMap; + /** Subscribe to git branch changes. Returns unsubscribe function. */ + onBranchChange(callback: () => void): () => void; + /** Internal: set extension status */ + setExtensionStatus(key: string, text: string | undefined): void; + /** Internal: clear extension statuses */ + clearExtensionStatuses(): void; + /** Number of unique providers with available models (for footer display) */ + getAvailableProviderCount(): number; + /** Internal: update available provider count */ + setAvailableProviderCount(count: number): void; + setCwd(cwd: string): void; + /** Internal: cleanup */ + dispose(): void; + private notifyBranchChange; + private scheduleRefresh; + private refreshGitBranchAsync; + private resolveGitBranchSync; + private resolveGitBranchAsync; + private clearGitWatchers; + private scheduleGitWatcherRetry; + private handleGitWatcherError; + private setupGitWatcher; +} +/** Read-only view for extensions - excludes setExtensionStatus, setAvailableProviderCount and dispose */ +export type ReadonlyFooterDataProvider = Pick; +//# sourceMappingURL=footer-data-provider.d.ts.map \ No newline at end of file diff --git a/dist/core/footer-data-provider.d.ts.map b/dist/core/footer-data-provider.d.ts.map new file mode 100644 index 0000000..1675826 --- /dev/null +++ b/dist/core/footer-data-provider.d.ts.map @@ -0,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IACrC,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAM9D;IAED,yCAAyC;IACzC,sBAAsB,IAAI,IAAI,CAE7B;IAED,4EAA4E;IAC5E,yBAAyB,IAAI,MAAM,CAElC;IAED,gDAAgD;IAChD,yBAAyB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAE7C;IAED,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAexB;IAED,wBAAwB;IACxB,OAAO,IAAI,IAAI,CAQd;IAED,OAAO,CAAC,kBAAkB;IAI1B,OAAO,CAAC,eAAe;YAYT,qBAAqB;IA0BnC,OAAO,CAAC,oBAAoB;YAcd,qBAAqB;IAgBnC,OAAO,CAAC,gBAAgB;IAsBxB,OAAO,CAAC,uBAAuB;IAW/B,OAAO,CAAC,qBAAqB;IAK7B,OAAO,CAAC,eAAe;CA2EvB;AAED,yGAAyG;AACzG,MAAM,MAAM,0BAA0B,GAAG,IAAI,CAC5C,kBAAkB,EAClB,cAAc,GAAG,sBAAsB,GAAG,2BAA2B,GAAG,gBAAgB,CACxF,CAAC","sourcesContent":["import { type ExecFileException, execFile, spawnSync } from \"child_process\";\nimport { existsSync, type FSWatcher, readFileSync, type Stats, statSync, unwatchFile, watchFile } from \"fs\";\nimport { dirname, join, resolve } from \"path\";\nimport { closeWatcher, FS_WATCH_RETRY_DELAY_MS, watchWithErrorHandler } from \"../utils/fs-watch.ts\";\n\nexport type GitPaths = {\n\trepoDir: string;\n\tcommonGitDir: string;\n\theadPath: string;\n};\n\n/**\n * Find git metadata paths by walking up from cwd.\n * Handles both regular git repos (.git is a directory) and worktrees (.git is a file).\n */\nexport function findGitPaths(cwd: string): GitPaths | null {\n\tlet dir = cwd;\n\twhile (true) {\n\t\tconst gitPath = join(dir, \".git\");\n\t\tif (existsSync(gitPath)) {\n\t\t\ttry {\n\t\t\t\tconst stat = statSync(gitPath);\n\t\t\t\tif (stat.isFile()) {\n\t\t\t\t\tconst content = readFileSync(gitPath, \"utf8\").trim();\n\t\t\t\t\tif (content.startsWith(\"gitdir: \")) {\n\t\t\t\t\t\tconst gitDir = resolve(dir, content.slice(8).trim());\n\t\t\t\t\t\tconst headPath = join(gitDir, \"HEAD\");\n\t\t\t\t\t\tif (!existsSync(headPath)) return null;\n\t\t\t\t\t\tconst commonDirPath = join(gitDir, \"commondir\");\n\t\t\t\t\t\tconst commonGitDir = existsSync(commonDirPath)\n\t\t\t\t\t\t\t? resolve(gitDir, readFileSync(commonDirPath, \"utf8\").trim())\n\t\t\t\t\t\t\t: gitDir;\n\t\t\t\t\t\treturn { repoDir: dir, commonGitDir, headPath };\n\t\t\t\t\t}\n\t\t\t\t} else if (stat.isDirectory()) {\n\t\t\t\t\tconst headPath = join(gitPath, \"HEAD\");\n\t\t\t\t\tif (!existsSync(headPath)) return null;\n\t\t\t\t\treturn { repoDir: dir, commonGitDir: gitPath, headPath };\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return null;\n\t\tdir = parent;\n\t}\n}\n\n/** Ask git for the current branch. Returns null on detached HEAD or if git is unavailable. */\nfunction resolveBranchWithGitSync(repoDir: string): string | null {\n\tconst result = spawnSync(\"git\", [\"--no-optional-locks\", \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"], {\n\t\tcwd: repoDir,\n\t\tencoding: \"utf8\",\n\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t});\n\tconst branch = result.status === 0 ? result.stdout.trim() : \"\";\n\treturn branch || null;\n}\n\n/** Ask git for the current branch asynchronously. Returns null on detached HEAD or if git is unavailable. */\nfunction resolveBranchWithGitAsync(repoDir: string): Promise {\n\treturn new Promise((resolvePromise) => {\n\t\texecFile(\n\t\t\t\"git\",\n\t\t\t[\"--no-optional-locks\", \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"],\n\t\t\t{\n\t\t\t\tcwd: repoDir,\n\t\t\t\tencoding: \"utf8\",\n\t\t\t},\n\t\t\t(error: ExecFileException | null, stdout: string) => {\n\t\t\t\tif (error) {\n\t\t\t\t\tresolvePromise(null);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst branch = stdout.trim();\n\t\t\t\tresolvePromise(branch || null);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction isWslEnvironment(): boolean {\n\treturn process.platform === \"linux\" && !!(process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP);\n}\n\nfunction isWindowsMountedRepoPath(repoDir: string): boolean {\n\treturn /^\\/mnt\\/[a-z](?:\\/|$)/i.test(repoDir);\n}\n\nfunction shouldPollGitHead(repoDir: string): boolean {\n\treturn isWslEnvironment() && isWindowsMountedRepoPath(repoDir);\n}\n\n/**\n * Provides git branch and extension statuses - data not otherwise accessible to extensions.\n * Token stats, model info available via ctx.sessionManager and ctx.model.\n */\nexport class FooterDataProvider {\n\tprivate cwd: string;\n\tprivate static readonly WATCH_DEBOUNCE_MS = 500;\n\n\tprivate extensionStatuses = new Map();\n\tprivate cachedBranch: string | null | undefined = undefined;\n\tprivate gitPaths: GitPaths | null | undefined = undefined;\n\tprivate headWatcher: FSWatcher | null = null;\n\tprivate headWatchFilePath: string | null = null;\n\tprivate headWatchFileListener: ((current: Stats, previous: Stats) => void) | null = null;\n\tprivate reftableWatcher: FSWatcher | null = null;\n\tprivate reftableTablesListWatcher: FSWatcher | null = null;\n\tprivate reftableTablesListPath: string | null = null;\n\tprivate branchChangeCallbacks = new Set<() => void>();\n\tprivate availableProviderCount = 0;\n\tprivate refreshTimer: ReturnType | null = null;\n\tprivate gitWatcherRetryTimer: ReturnType | null = null;\n\tprivate refreshInFlight = false;\n\tprivate refreshPending = false;\n\tprivate disposed = false;\n\n\tconstructor(cwd: string) {\n\t\tthis.cwd = cwd;\n\t\tthis.gitPaths = findGitPaths(cwd);\n\t\tthis.setupGitWatcher();\n\t}\n\n\t/** Current git branch, null if not in repo, \"detached\" if detached HEAD */\n\tgetGitBranch(): string | null {\n\t\tif (this.cachedBranch === undefined) {\n\t\t\tthis.cachedBranch = this.resolveGitBranchSync();\n\t\t}\n\t\treturn this.cachedBranch;\n\t}\n\n\t/** Extension status texts set via ctx.ui.setStatus() */\n\tgetExtensionStatuses(): ReadonlyMap {\n\t\treturn this.extensionStatuses;\n\t}\n\n\t/** Subscribe to git branch changes. Returns unsubscribe function. */\n\tonBranchChange(callback: () => void): () => void {\n\t\tthis.branchChangeCallbacks.add(callback);\n\t\treturn () => this.branchChangeCallbacks.delete(callback);\n\t}\n\n\t/** Internal: set extension status */\n\tsetExtensionStatus(key: string, text: string | undefined): void {\n\t\tif (text === undefined) {\n\t\t\tthis.extensionStatuses.delete(key);\n\t\t} else {\n\t\t\tthis.extensionStatuses.set(key, text);\n\t\t}\n\t}\n\n\t/** Internal: clear extension statuses */\n\tclearExtensionStatuses(): void {\n\t\tthis.extensionStatuses.clear();\n\t}\n\n\t/** Number of unique providers with available models (for footer display) */\n\tgetAvailableProviderCount(): number {\n\t\treturn this.availableProviderCount;\n\t}\n\n\t/** Internal: update available provider count */\n\tsetAvailableProviderCount(count: number): void {\n\t\tthis.availableProviderCount = count;\n\t}\n\n\tsetCwd(cwd: string): void {\n\t\tif (this.cwd === cwd) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.cwd = cwd;\n\t\tif (this.refreshTimer) {\n\t\t\tclearTimeout(this.refreshTimer);\n\t\t\tthis.refreshTimer = null;\n\t\t}\n\t\tthis.clearGitWatchers();\n\t\tthis.cachedBranch = undefined;\n\t\tthis.gitPaths = findGitPaths(cwd);\n\t\tthis.setupGitWatcher();\n\t\tthis.notifyBranchChange();\n\t}\n\n\t/** Internal: cleanup */\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tif (this.refreshTimer) {\n\t\t\tclearTimeout(this.refreshTimer);\n\t\t\tthis.refreshTimer = null;\n\t\t}\n\t\tthis.clearGitWatchers();\n\t\tthis.branchChangeCallbacks.clear();\n\t}\n\n\tprivate notifyBranchChange(): void {\n\t\tfor (const cb of this.branchChangeCallbacks) cb();\n\t}\n\n\tprivate scheduleRefresh(): void {\n\t\tif (this.disposed || this.refreshTimer) return;\n\t\tif (this.refreshInFlight) {\n\t\t\tthis.refreshPending = true;\n\t\t\treturn;\n\t\t}\n\t\tthis.refreshTimer = setTimeout(() => {\n\t\t\tthis.refreshTimer = null;\n\t\t\tvoid this.refreshGitBranchAsync();\n\t\t}, FooterDataProvider.WATCH_DEBOUNCE_MS);\n\t}\n\n\tprivate async refreshGitBranchAsync(): Promise {\n\t\tif (this.disposed) return;\n\t\tif (this.refreshInFlight) {\n\t\t\tthis.refreshPending = true;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.refreshInFlight = true;\n\t\ttry {\n\t\t\tconst nextBranch = await this.resolveGitBranchAsync();\n\t\t\tif (this.disposed) return;\n\t\t\tif (this.cachedBranch !== undefined && this.cachedBranch !== nextBranch) {\n\t\t\t\tthis.cachedBranch = nextBranch;\n\t\t\t\tthis.notifyBranchChange();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.cachedBranch = nextBranch;\n\t\t} finally {\n\t\t\tthis.refreshInFlight = false;\n\t\t\tif (this.refreshPending && !this.disposed) {\n\t\t\t\tthis.refreshPending = false;\n\t\t\t\tthis.scheduleRefresh();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate resolveGitBranchSync(): string | null {\n\t\ttry {\n\t\t\tif (!this.gitPaths) return null;\n\t\t\tconst content = readFileSync(this.gitPaths.headPath, \"utf8\").trim();\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\tconst branch = content.slice(16);\n\t\t\t\treturn branch === \".invalid\" ? (resolveBranchWithGitSync(this.gitPaths.repoDir) ?? \"detached\") : branch;\n\t\t\t}\n\t\t\treturn \"detached\";\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate async resolveGitBranchAsync(): Promise {\n\t\ttry {\n\t\t\tif (!this.gitPaths) return null;\n\t\t\tconst content = readFileSync(this.gitPaths.headPath, \"utf8\").trim();\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\tconst branch = content.slice(16);\n\t\t\t\treturn branch === \".invalid\"\n\t\t\t\t\t? ((await resolveBranchWithGitAsync(this.gitPaths.repoDir)) ?? \"detached\")\n\t\t\t\t\t: branch;\n\t\t\t}\n\t\t\treturn \"detached\";\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate clearGitWatchers(): void {\n\t\tcloseWatcher(this.headWatcher);\n\t\tthis.headWatcher = null;\n\t\tif (this.headWatchFilePath && this.headWatchFileListener) {\n\t\t\tunwatchFile(this.headWatchFilePath, this.headWatchFileListener);\n\t\t\tthis.headWatchFilePath = null;\n\t\t\tthis.headWatchFileListener = null;\n\t\t}\n\t\tcloseWatcher(this.reftableWatcher);\n\t\tthis.reftableWatcher = null;\n\t\tcloseWatcher(this.reftableTablesListWatcher);\n\t\tthis.reftableTablesListWatcher = null;\n\t\tif (this.reftableTablesListPath) {\n\t\t\tunwatchFile(this.reftableTablesListPath);\n\t\t\tthis.reftableTablesListPath = null;\n\t\t}\n\t\tif (this.gitWatcherRetryTimer) {\n\t\t\tclearTimeout(this.gitWatcherRetryTimer);\n\t\t\tthis.gitWatcherRetryTimer = null;\n\t\t}\n\t}\n\n\tprivate scheduleGitWatcherRetry(): void {\n\t\tif (this.disposed || this.gitWatcherRetryTimer) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.gitWatcherRetryTimer = setTimeout(() => {\n\t\t\tthis.gitWatcherRetryTimer = null;\n\t\t\tthis.setupGitWatcher();\n\t\t}, FS_WATCH_RETRY_DELAY_MS);\n\t}\n\n\tprivate handleGitWatcherError(): void {\n\t\tthis.clearGitWatchers();\n\t\tthis.scheduleGitWatcherRetry();\n\t}\n\n\tprivate setupGitWatcher(): void {\n\t\tthis.clearGitWatchers();\n\t\tif (!this.gitPaths) return;\n\n\t\tconst pollGitHead = shouldPollGitHead(this.gitPaths.repoDir);\n\n\t\t// Watch the directory containing HEAD, not HEAD itself.\n\t\t// Git uses atomic writes (write temp, rename over HEAD), which changes the inode.\n\t\t// fs.watch on a file stops working after the inode changes.\n\t\tthis.headWatcher = watchWithErrorHandler(\n\t\t\tdirname(this.gitPaths.headPath),\n\t\t\t(_eventType, filename) => {\n\t\t\t\tif (!filename || filename === \"HEAD\") {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => this.handleGitWatcherError(),\n\t\t);\n\t\tif (pollGitHead) {\n\t\t\tthis.headWatchFilePath = this.gitPaths.headPath;\n\t\t\tthis.headWatchFileListener = (current, previous) => {\n\t\t\t\tif (\n\t\t\t\t\tcurrent.mtimeMs !== previous.mtimeMs ||\n\t\t\t\t\tcurrent.ctimeMs !== previous.ctimeMs ||\n\t\t\t\t\tcurrent.size !== previous.size\n\t\t\t\t) {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t}\n\t\t\t};\n\t\t\twatchFile(this.headWatchFilePath, { interval: 1000 }, this.headWatchFileListener);\n\t\t}\n\t\tif (!this.headWatcher && !pollGitHead) {\n\t\t\treturn;\n\t\t}\n\n\t\t// In reftable repos, branch switches update files in the reftable directory\n\t\t// instead of HEAD. Watch it separately so the footer picks up those changes.\n\t\tconst reftableDir = join(this.gitPaths.commonGitDir, \"reftable\");\n\t\tif (existsSync(reftableDir)) {\n\t\t\tthis.reftableWatcher = watchWithErrorHandler(\n\t\t\t\treftableDir,\n\t\t\t\t() => {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t},\n\t\t\t\t() => this.handleGitWatcherError(),\n\t\t\t);\n\t\t\tif (!this.reftableWatcher) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst tablesListPath = join(reftableDir, \"tables.list\");\n\t\t\tif (existsSync(tablesListPath)) {\n\t\t\t\tthis.reftableTablesListPath = tablesListPath;\n\t\t\t\tthis.reftableTablesListWatcher = watchWithErrorHandler(\n\t\t\t\t\ttablesListPath,\n\t\t\t\t\t() => {\n\t\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t\t},\n\t\t\t\t\t() => this.handleGitWatcherError(),\n\t\t\t\t);\n\t\t\t\tif (!this.reftableTablesListWatcher) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\twatchFile(tablesListPath, { interval: 250 }, (current, previous) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tcurrent.mtimeMs !== previous.mtimeMs ||\n\t\t\t\t\t\tcurrent.ctimeMs !== previous.ctimeMs ||\n\t\t\t\t\t\tcurrent.size !== previous.size\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Read-only view for extensions - excludes setExtensionStatus, setAvailableProviderCount and dispose */\nexport type ReadonlyFooterDataProvider = Pick<\n\tFooterDataProvider,\n\t\"getGitBranch\" | \"getExtensionStatuses\" | \"getAvailableProviderCount\" | \"onBranchChange\"\n>;\n"]} \ No newline at end of file diff --git a/dist/core/footer-data-provider.js b/dist/core/footer-data-provider.js new file mode 100644 index 0000000..64a98f8 --- /dev/null +++ b/dist/core/footer-data-provider.js @@ -0,0 +1,338 @@ +import { execFile, spawnSync } from "child_process"; +import { existsSync, readFileSync, statSync, unwatchFile, watchFile } from "fs"; +import { dirname, join, resolve } from "path"; +import { closeWatcher, FS_WATCH_RETRY_DELAY_MS, watchWithErrorHandler } from "../utils/fs-watch.js"; +/** + * Find git metadata paths by walking up from cwd. + * Handles both regular git repos (.git is a directory) and worktrees (.git is a file). + */ +export function findGitPaths(cwd) { + let dir = cwd; + while (true) { + const gitPath = join(dir, ".git"); + if (existsSync(gitPath)) { + try { + const stat = statSync(gitPath); + if (stat.isFile()) { + const content = readFileSync(gitPath, "utf8").trim(); + if (content.startsWith("gitdir: ")) { + const gitDir = resolve(dir, content.slice(8).trim()); + const headPath = join(gitDir, "HEAD"); + if (!existsSync(headPath)) + return null; + const commonDirPath = join(gitDir, "commondir"); + const commonGitDir = existsSync(commonDirPath) + ? resolve(gitDir, readFileSync(commonDirPath, "utf8").trim()) + : gitDir; + return { repoDir: dir, commonGitDir, headPath }; + } + } + else if (stat.isDirectory()) { + const headPath = join(gitPath, "HEAD"); + if (!existsSync(headPath)) + return null; + return { repoDir: dir, commonGitDir: gitPath, headPath }; + } + } + catch { + return null; + } + } + const parent = dirname(dir); + if (parent === dir) + return null; + dir = parent; + } +} +/** Ask git for the current branch. Returns null on detached HEAD or if git is unavailable. */ +function resolveBranchWithGitSync(repoDir) { + const result = spawnSync("git", ["--no-optional-locks", "symbolic-ref", "--quiet", "--short", "HEAD"], { + cwd: repoDir, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }); + const branch = result.status === 0 ? result.stdout.trim() : ""; + return branch || null; +} +/** Ask git for the current branch asynchronously. Returns null on detached HEAD or if git is unavailable. */ +function resolveBranchWithGitAsync(repoDir) { + return new Promise((resolvePromise) => { + execFile("git", ["--no-optional-locks", "symbolic-ref", "--quiet", "--short", "HEAD"], { + cwd: repoDir, + encoding: "utf8", + }, (error, stdout) => { + if (error) { + resolvePromise(null); + return; + } + const branch = stdout.trim(); + resolvePromise(branch || null); + }); + }); +} +function isWslEnvironment() { + return process.platform === "linux" && !!(process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP); +} +function isWindowsMountedRepoPath(repoDir) { + return /^\/mnt\/[a-z](?:\/|$)/i.test(repoDir); +} +function shouldPollGitHead(repoDir) { + return isWslEnvironment() && isWindowsMountedRepoPath(repoDir); +} +/** + * Provides git branch and extension statuses - data not otherwise accessible to extensions. + * Token stats, model info available via ctx.sessionManager and ctx.model. + */ +export class FooterDataProvider { + cwd; + static WATCH_DEBOUNCE_MS = 500; + extensionStatuses = new Map(); + cachedBranch = undefined; + gitPaths = undefined; + headWatcher = null; + headWatchFilePath = null; + headWatchFileListener = null; + reftableWatcher = null; + reftableTablesListWatcher = null; + reftableTablesListPath = null; + branchChangeCallbacks = new Set(); + availableProviderCount = 0; + refreshTimer = null; + gitWatcherRetryTimer = null; + refreshInFlight = false; + refreshPending = false; + disposed = false; + constructor(cwd) { + this.cwd = cwd; + this.gitPaths = findGitPaths(cwd); + this.setupGitWatcher(); + } + /** Current git branch, null if not in repo, "detached" if detached HEAD */ + getGitBranch() { + if (this.cachedBranch === undefined) { + this.cachedBranch = this.resolveGitBranchSync(); + } + return this.cachedBranch; + } + /** Extension status texts set via ctx.ui.setStatus() */ + getExtensionStatuses() { + return this.extensionStatuses; + } + /** Subscribe to git branch changes. Returns unsubscribe function. */ + onBranchChange(callback) { + this.branchChangeCallbacks.add(callback); + return () => this.branchChangeCallbacks.delete(callback); + } + /** Internal: set extension status */ + setExtensionStatus(key, text) { + if (text === undefined) { + this.extensionStatuses.delete(key); + } + else { + this.extensionStatuses.set(key, text); + } + } + /** Internal: clear extension statuses */ + clearExtensionStatuses() { + this.extensionStatuses.clear(); + } + /** Number of unique providers with available models (for footer display) */ + getAvailableProviderCount() { + return this.availableProviderCount; + } + /** Internal: update available provider count */ + setAvailableProviderCount(count) { + this.availableProviderCount = count; + } + setCwd(cwd) { + if (this.cwd === cwd) { + return; + } + this.cwd = cwd; + if (this.refreshTimer) { + clearTimeout(this.refreshTimer); + this.refreshTimer = null; + } + this.clearGitWatchers(); + this.cachedBranch = undefined; + this.gitPaths = findGitPaths(cwd); + this.setupGitWatcher(); + this.notifyBranchChange(); + } + /** Internal: cleanup */ + dispose() { + this.disposed = true; + if (this.refreshTimer) { + clearTimeout(this.refreshTimer); + this.refreshTimer = null; + } + this.clearGitWatchers(); + this.branchChangeCallbacks.clear(); + } + notifyBranchChange() { + for (const cb of this.branchChangeCallbacks) + cb(); + } + scheduleRefresh() { + if (this.disposed || this.refreshTimer) + return; + if (this.refreshInFlight) { + this.refreshPending = true; + return; + } + this.refreshTimer = setTimeout(() => { + this.refreshTimer = null; + void this.refreshGitBranchAsync(); + }, FooterDataProvider.WATCH_DEBOUNCE_MS); + } + async refreshGitBranchAsync() { + if (this.disposed) + return; + if (this.refreshInFlight) { + this.refreshPending = true; + return; + } + this.refreshInFlight = true; + try { + const nextBranch = await this.resolveGitBranchAsync(); + if (this.disposed) + return; + if (this.cachedBranch !== undefined && this.cachedBranch !== nextBranch) { + this.cachedBranch = nextBranch; + this.notifyBranchChange(); + return; + } + this.cachedBranch = nextBranch; + } + finally { + this.refreshInFlight = false; + if (this.refreshPending && !this.disposed) { + this.refreshPending = false; + this.scheduleRefresh(); + } + } + } + resolveGitBranchSync() { + try { + if (!this.gitPaths) + return null; + const content = readFileSync(this.gitPaths.headPath, "utf8").trim(); + if (content.startsWith("ref: refs/heads/")) { + const branch = content.slice(16); + return branch === ".invalid" ? (resolveBranchWithGitSync(this.gitPaths.repoDir) ?? "detached") : branch; + } + return "detached"; + } + catch { + return null; + } + } + async resolveGitBranchAsync() { + try { + if (!this.gitPaths) + return null; + const content = readFileSync(this.gitPaths.headPath, "utf8").trim(); + if (content.startsWith("ref: refs/heads/")) { + const branch = content.slice(16); + return branch === ".invalid" + ? ((await resolveBranchWithGitAsync(this.gitPaths.repoDir)) ?? "detached") + : branch; + } + return "detached"; + } + catch { + return null; + } + } + clearGitWatchers() { + closeWatcher(this.headWatcher); + this.headWatcher = null; + if (this.headWatchFilePath && this.headWatchFileListener) { + unwatchFile(this.headWatchFilePath, this.headWatchFileListener); + this.headWatchFilePath = null; + this.headWatchFileListener = null; + } + closeWatcher(this.reftableWatcher); + this.reftableWatcher = null; + closeWatcher(this.reftableTablesListWatcher); + this.reftableTablesListWatcher = null; + if (this.reftableTablesListPath) { + unwatchFile(this.reftableTablesListPath); + this.reftableTablesListPath = null; + } + if (this.gitWatcherRetryTimer) { + clearTimeout(this.gitWatcherRetryTimer); + this.gitWatcherRetryTimer = null; + } + } + scheduleGitWatcherRetry() { + if (this.disposed || this.gitWatcherRetryTimer) { + return; + } + this.gitWatcherRetryTimer = setTimeout(() => { + this.gitWatcherRetryTimer = null; + this.setupGitWatcher(); + }, FS_WATCH_RETRY_DELAY_MS); + } + handleGitWatcherError() { + this.clearGitWatchers(); + this.scheduleGitWatcherRetry(); + } + setupGitWatcher() { + this.clearGitWatchers(); + if (!this.gitPaths) + return; + const pollGitHead = shouldPollGitHead(this.gitPaths.repoDir); + // Watch the directory containing HEAD, not HEAD itself. + // Git uses atomic writes (write temp, rename over HEAD), which changes the inode. + // fs.watch on a file stops working after the inode changes. + this.headWatcher = watchWithErrorHandler(dirname(this.gitPaths.headPath), (_eventType, filename) => { + if (!filename || filename === "HEAD") { + this.scheduleRefresh(); + } + }, () => this.handleGitWatcherError()); + if (pollGitHead) { + this.headWatchFilePath = this.gitPaths.headPath; + this.headWatchFileListener = (current, previous) => { + if (current.mtimeMs !== previous.mtimeMs || + current.ctimeMs !== previous.ctimeMs || + current.size !== previous.size) { + this.scheduleRefresh(); + } + }; + watchFile(this.headWatchFilePath, { interval: 1000 }, this.headWatchFileListener); + } + if (!this.headWatcher && !pollGitHead) { + return; + } + // In reftable repos, branch switches update files in the reftable directory + // instead of HEAD. Watch it separately so the footer picks up those changes. + const reftableDir = join(this.gitPaths.commonGitDir, "reftable"); + if (existsSync(reftableDir)) { + this.reftableWatcher = watchWithErrorHandler(reftableDir, () => { + this.scheduleRefresh(); + }, () => this.handleGitWatcherError()); + if (!this.reftableWatcher) { + return; + } + const tablesListPath = join(reftableDir, "tables.list"); + if (existsSync(tablesListPath)) { + this.reftableTablesListPath = tablesListPath; + this.reftableTablesListWatcher = watchWithErrorHandler(tablesListPath, () => { + this.scheduleRefresh(); + }, () => this.handleGitWatcherError()); + if (!this.reftableTablesListWatcher) { + return; + } + watchFile(tablesListPath, { interval: 250 }, (current, previous) => { + if (current.mtimeMs !== previous.mtimeMs || + current.ctimeMs !== previous.ctimeMs || + current.size !== previous.size) { + this.scheduleRefresh(); + } + }); + } + } + } +} +//# sourceMappingURL=footer-data-provider.js.map \ No newline at end of file diff --git a/dist/core/footer-data-provider.js.map b/dist/core/footer-data-provider.js.map new file mode 100644 index 0000000..b72d816 --- /dev/null +++ b/dist/core/footer-data-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"footer-data-provider.js","sourceRoot":"","sources":["../../src/core/footer-data-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,QAAQ,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC5E,OAAO,EAAE,UAAU,EAAkB,YAAY,EAAc,QAAQ,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC5G,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,uBAAuB,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAQpG;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,GAAW,EAAmB;IAC1D,IAAI,GAAG,GAAG,GAAG,CAAC;IACd,OAAO,IAAI,EAAE,CAAC;QACb,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAClC,IAAI,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;YACzB,IAAI,CAAC;gBACJ,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC;gBAC/B,IAAI,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC;oBACnB,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;oBACrD,IAAI,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;wBACpC,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;wBACrD,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;w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,OAAO;gBACR,CAAC;gBACD,SAAS,CAAC,cAAc,EAAE,EAAE,QAAQ,EAAE,GAAG,EAAE,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,EAAE,CAAC;oBACnE,IACC,OAAO,CAAC,OAAO,KAAK,QAAQ,CAAC,OAAO;wBACpC,OAAO,CAAC,OAAO,KAAK,QAAQ,CAAC,OAAO;wBACpC,OAAO,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,EAC7B,CAAC;wBACF,IAAI,CAAC,eAAe,EAAE,CAAC;oBACxB,CAAC;gBAAA,CACD,CAAC,CAAC;YACJ,CAAC;QACF,CAAC;IAAA,CACD;CACD","sourcesContent":["import { type ExecFileException, execFile, spawnSync } from \"child_process\";\nimport { existsSync, type FSWatcher, readFileSync, type Stats, statSync, unwatchFile, watchFile } from \"fs\";\nimport { dirname, join, resolve } from \"path\";\nimport { closeWatcher, FS_WATCH_RETRY_DELAY_MS, watchWithErrorHandler } from \"../utils/fs-watch.ts\";\n\nexport type GitPaths = {\n\trepoDir: string;\n\tcommonGitDir: string;\n\theadPath: string;\n};\n\n/**\n * Find git metadata paths by walking up from cwd.\n * Handles both regular git repos (.git is a directory) and worktrees (.git is a file).\n */\nexport function findGitPaths(cwd: string): GitPaths | null {\n\tlet dir = cwd;\n\twhile (true) {\n\t\tconst gitPath = join(dir, \".git\");\n\t\tif (existsSync(gitPath)) {\n\t\t\ttry {\n\t\t\t\tconst stat = statSync(gitPath);\n\t\t\t\tif (stat.isFile()) {\n\t\t\t\t\tconst content = readFileSync(gitPath, \"utf8\").trim();\n\t\t\t\t\tif (content.startsWith(\"gitdir: \")) {\n\t\t\t\t\t\tconst gitDir = resolve(dir, content.slice(8).trim());\n\t\t\t\t\t\tconst headPath = join(gitDir, \"HEAD\");\n\t\t\t\t\t\tif (!existsSync(headPath)) return null;\n\t\t\t\t\t\tconst commonDirPath = join(gitDir, \"commondir\");\n\t\t\t\t\t\tconst commonGitDir = existsSync(commonDirPath)\n\t\t\t\t\t\t\t? resolve(gitDir, readFileSync(commonDirPath, \"utf8\").trim())\n\t\t\t\t\t\t\t: gitDir;\n\t\t\t\t\t\treturn { repoDir: dir, commonGitDir, headPath };\n\t\t\t\t\t}\n\t\t\t\t} else if (stat.isDirectory()) {\n\t\t\t\t\tconst headPath = join(gitPath, \"HEAD\");\n\t\t\t\t\tif (!existsSync(headPath)) return null;\n\t\t\t\t\treturn { repoDir: dir, commonGitDir: gitPath, headPath };\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return null;\n\t\tdir = parent;\n\t}\n}\n\n/** Ask git for the current branch. Returns null on detached HEAD or if git is unavailable. */\nfunction resolveBranchWithGitSync(repoDir: string): string | null {\n\tconst result = spawnSync(\"git\", [\"--no-optional-locks\", \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"], {\n\t\tcwd: repoDir,\n\t\tencoding: \"utf8\",\n\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t});\n\tconst branch = result.status === 0 ? result.stdout.trim() : \"\";\n\treturn branch || null;\n}\n\n/** Ask git for the current branch asynchronously. Returns null on detached HEAD or if git is unavailable. */\nfunction resolveBranchWithGitAsync(repoDir: string): Promise {\n\treturn new Promise((resolvePromise) => {\n\t\texecFile(\n\t\t\t\"git\",\n\t\t\t[\"--no-optional-locks\", \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"],\n\t\t\t{\n\t\t\t\tcwd: repoDir,\n\t\t\t\tencoding: \"utf8\",\n\t\t\t},\n\t\t\t(error: ExecFileException | null, stdout: string) => {\n\t\t\t\tif (error) {\n\t\t\t\t\tresolvePromise(null);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst branch = stdout.trim();\n\t\t\t\tresolvePromise(branch || null);\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction isWslEnvironment(): boolean {\n\treturn process.platform === \"linux\" && !!(process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP);\n}\n\nfunction isWindowsMountedRepoPath(repoDir: string): boolean {\n\treturn /^\\/mnt\\/[a-z](?:\\/|$)/i.test(repoDir);\n}\n\nfunction shouldPollGitHead(repoDir: string): boolean {\n\treturn isWslEnvironment() && isWindowsMountedRepoPath(repoDir);\n}\n\n/**\n * Provides git branch and extension statuses - data not otherwise accessible to extensions.\n * Token stats, model info available via ctx.sessionManager and ctx.model.\n */\nexport class FooterDataProvider {\n\tprivate cwd: string;\n\tprivate static readonly WATCH_DEBOUNCE_MS = 500;\n\n\tprivate extensionStatuses = new Map();\n\tprivate cachedBranch: string | null | undefined = undefined;\n\tprivate gitPaths: GitPaths | null | undefined = undefined;\n\tprivate headWatcher: FSWatcher | null = null;\n\tprivate headWatchFilePath: string | null = null;\n\tprivate headWatchFileListener: ((current: Stats, previous: Stats) => void) | null = null;\n\tprivate reftableWatcher: FSWatcher | null = null;\n\tprivate reftableTablesListWatcher: FSWatcher | null = null;\n\tprivate reftableTablesListPath: string | null = null;\n\tprivate branchChangeCallbacks = new Set<() => void>();\n\tprivate availableProviderCount = 0;\n\tprivate refreshTimer: ReturnType | null = null;\n\tprivate gitWatcherRetryTimer: ReturnType | null = null;\n\tprivate refreshInFlight = false;\n\tprivate refreshPending = false;\n\tprivate disposed = false;\n\n\tconstructor(cwd: string) {\n\t\tthis.cwd = cwd;\n\t\tthis.gitPaths = findGitPaths(cwd);\n\t\tthis.setupGitWatcher();\n\t}\n\n\t/** Current git branch, null if not in repo, \"detached\" if detached HEAD */\n\tgetGitBranch(): string | null {\n\t\tif (this.cachedBranch === undefined) {\n\t\t\tthis.cachedBranch = this.resolveGitBranchSync();\n\t\t}\n\t\treturn this.cachedBranch;\n\t}\n\n\t/** Extension status texts set via ctx.ui.setStatus() */\n\tgetExtensionStatuses(): ReadonlyMap {\n\t\treturn this.extensionStatuses;\n\t}\n\n\t/** Subscribe to git branch changes. Returns unsubscribe function. */\n\tonBranchChange(callback: () => void): () => void {\n\t\tthis.branchChangeCallbacks.add(callback);\n\t\treturn () => this.branchChangeCallbacks.delete(callback);\n\t}\n\n\t/** Internal: set extension status */\n\tsetExtensionStatus(key: string, text: string | undefined): void {\n\t\tif (text === undefined) {\n\t\t\tthis.extensionStatuses.delete(key);\n\t\t} else {\n\t\t\tthis.extensionStatuses.set(key, text);\n\t\t}\n\t}\n\n\t/** Internal: clear extension statuses */\n\tclearExtensionStatuses(): void {\n\t\tthis.extensionStatuses.clear();\n\t}\n\n\t/** Number of unique providers with available models (for footer display) */\n\tgetAvailableProviderCount(): number {\n\t\treturn this.availableProviderCount;\n\t}\n\n\t/** Internal: update available provider count */\n\tsetAvailableProviderCount(count: number): void {\n\t\tthis.availableProviderCount = count;\n\t}\n\n\tsetCwd(cwd: string): void {\n\t\tif (this.cwd === cwd) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.cwd = cwd;\n\t\tif (this.refreshTimer) {\n\t\t\tclearTimeout(this.refreshTimer);\n\t\t\tthis.refreshTimer = null;\n\t\t}\n\t\tthis.clearGitWatchers();\n\t\tthis.cachedBranch = undefined;\n\t\tthis.gitPaths = findGitPaths(cwd);\n\t\tthis.setupGitWatcher();\n\t\tthis.notifyBranchChange();\n\t}\n\n\t/** Internal: cleanup */\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tif (this.refreshTimer) {\n\t\t\tclearTimeout(this.refreshTimer);\n\t\t\tthis.refreshTimer = null;\n\t\t}\n\t\tthis.clearGitWatchers();\n\t\tthis.branchChangeCallbacks.clear();\n\t}\n\n\tprivate notifyBranchChange(): void {\n\t\tfor (const cb of this.branchChangeCallbacks) cb();\n\t}\n\n\tprivate scheduleRefresh(): void {\n\t\tif (this.disposed || this.refreshTimer) return;\n\t\tif (this.refreshInFlight) {\n\t\t\tthis.refreshPending = true;\n\t\t\treturn;\n\t\t}\n\t\tthis.refreshTimer = setTimeout(() => {\n\t\t\tthis.refreshTimer = null;\n\t\t\tvoid this.refreshGitBranchAsync();\n\t\t}, FooterDataProvider.WATCH_DEBOUNCE_MS);\n\t}\n\n\tprivate async refreshGitBranchAsync(): Promise {\n\t\tif (this.disposed) return;\n\t\tif (this.refreshInFlight) {\n\t\t\tthis.refreshPending = true;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.refreshInFlight = true;\n\t\ttry {\n\t\t\tconst nextBranch = await this.resolveGitBranchAsync();\n\t\t\tif (this.disposed) return;\n\t\t\tif (this.cachedBranch !== undefined && this.cachedBranch !== nextBranch) {\n\t\t\t\tthis.cachedBranch = nextBranch;\n\t\t\t\tthis.notifyBranchChange();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.cachedBranch = nextBranch;\n\t\t} finally {\n\t\t\tthis.refreshInFlight = false;\n\t\t\tif (this.refreshPending && !this.disposed) {\n\t\t\t\tthis.refreshPending = false;\n\t\t\t\tthis.scheduleRefresh();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate resolveGitBranchSync(): string | null {\n\t\ttry {\n\t\t\tif (!this.gitPaths) return null;\n\t\t\tconst content = readFileSync(this.gitPaths.headPath, \"utf8\").trim();\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\tconst branch = content.slice(16);\n\t\t\t\treturn branch === \".invalid\" ? (resolveBranchWithGitSync(this.gitPaths.repoDir) ?? \"detached\") : branch;\n\t\t\t}\n\t\t\treturn \"detached\";\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate async resolveGitBranchAsync(): Promise {\n\t\ttry {\n\t\t\tif (!this.gitPaths) return null;\n\t\t\tconst content = readFileSync(this.gitPaths.headPath, \"utf8\").trim();\n\t\t\tif (content.startsWith(\"ref: refs/heads/\")) {\n\t\t\t\tconst branch = content.slice(16);\n\t\t\t\treturn branch === \".invalid\"\n\t\t\t\t\t? ((await resolveBranchWithGitAsync(this.gitPaths.repoDir)) ?? \"detached\")\n\t\t\t\t\t: branch;\n\t\t\t}\n\t\t\treturn \"detached\";\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate clearGitWatchers(): void {\n\t\tcloseWatcher(this.headWatcher);\n\t\tthis.headWatcher = null;\n\t\tif (this.headWatchFilePath && this.headWatchFileListener) {\n\t\t\tunwatchFile(this.headWatchFilePath, this.headWatchFileListener);\n\t\t\tthis.headWatchFilePath = null;\n\t\t\tthis.headWatchFileListener = null;\n\t\t}\n\t\tcloseWatcher(this.reftableWatcher);\n\t\tthis.reftableWatcher = null;\n\t\tcloseWatcher(this.reftableTablesListWatcher);\n\t\tthis.reftableTablesListWatcher = null;\n\t\tif (this.reftableTablesListPath) {\n\t\t\tunwatchFile(this.reftableTablesListPath);\n\t\t\tthis.reftableTablesListPath = null;\n\t\t}\n\t\tif (this.gitWatcherRetryTimer) {\n\t\t\tclearTimeout(this.gitWatcherRetryTimer);\n\t\t\tthis.gitWatcherRetryTimer = null;\n\t\t}\n\t}\n\n\tprivate scheduleGitWatcherRetry(): void {\n\t\tif (this.disposed || this.gitWatcherRetryTimer) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.gitWatcherRetryTimer = setTimeout(() => {\n\t\t\tthis.gitWatcherRetryTimer = null;\n\t\t\tthis.setupGitWatcher();\n\t\t}, FS_WATCH_RETRY_DELAY_MS);\n\t}\n\n\tprivate handleGitWatcherError(): void {\n\t\tthis.clearGitWatchers();\n\t\tthis.scheduleGitWatcherRetry();\n\t}\n\n\tprivate setupGitWatcher(): void {\n\t\tthis.clearGitWatchers();\n\t\tif (!this.gitPaths) return;\n\n\t\tconst pollGitHead = shouldPollGitHead(this.gitPaths.repoDir);\n\n\t\t// Watch the directory containing HEAD, not HEAD itself.\n\t\t// Git uses atomic writes (write temp, rename over HEAD), which changes the inode.\n\t\t// fs.watch on a file stops working after the inode changes.\n\t\tthis.headWatcher = watchWithErrorHandler(\n\t\t\tdirname(this.gitPaths.headPath),\n\t\t\t(_eventType, filename) => {\n\t\t\t\tif (!filename || filename === \"HEAD\") {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => this.handleGitWatcherError(),\n\t\t);\n\t\tif (pollGitHead) {\n\t\t\tthis.headWatchFilePath = this.gitPaths.headPath;\n\t\t\tthis.headWatchFileListener = (current, previous) => {\n\t\t\t\tif (\n\t\t\t\t\tcurrent.mtimeMs !== previous.mtimeMs ||\n\t\t\t\t\tcurrent.ctimeMs !== previous.ctimeMs ||\n\t\t\t\t\tcurrent.size !== previous.size\n\t\t\t\t) {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t}\n\t\t\t};\n\t\t\twatchFile(this.headWatchFilePath, { interval: 1000 }, this.headWatchFileListener);\n\t\t}\n\t\tif (!this.headWatcher && !pollGitHead) {\n\t\t\treturn;\n\t\t}\n\n\t\t// In reftable repos, branch switches update files in the reftable directory\n\t\t// instead of HEAD. Watch it separately so the footer picks up those changes.\n\t\tconst reftableDir = join(this.gitPaths.commonGitDir, \"reftable\");\n\t\tif (existsSync(reftableDir)) {\n\t\t\tthis.reftableWatcher = watchWithErrorHandler(\n\t\t\t\treftableDir,\n\t\t\t\t() => {\n\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t},\n\t\t\t\t() => this.handleGitWatcherError(),\n\t\t\t);\n\t\t\tif (!this.reftableWatcher) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst tablesListPath = join(reftableDir, \"tables.list\");\n\t\t\tif (existsSync(tablesListPath)) {\n\t\t\t\tthis.reftableTablesListPath = tablesListPath;\n\t\t\t\tthis.reftableTablesListWatcher = watchWithErrorHandler(\n\t\t\t\t\ttablesListPath,\n\t\t\t\t\t() => {\n\t\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t\t},\n\t\t\t\t\t() => this.handleGitWatcherError(),\n\t\t\t\t);\n\t\t\t\tif (!this.reftableTablesListWatcher) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\twatchFile(tablesListPath, { interval: 250 }, (current, previous) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tcurrent.mtimeMs !== previous.mtimeMs ||\n\t\t\t\t\t\tcurrent.ctimeMs !== previous.ctimeMs ||\n\t\t\t\t\t\tcurrent.size !== previous.size\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.scheduleRefresh();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Read-only view for extensions - excludes setExtensionStatus, setAvailableProviderCount and dispose */\nexport type ReadonlyFooterDataProvider = Pick<\n\tFooterDataProvider,\n\t\"getGitBranch\" | \"getExtensionStatuses\" | \"getAvailableProviderCount\" | \"onBranchChange\"\n>;\n"]} \ No newline at end of file diff --git a/dist/core/http-dispatcher.d.ts b/dist/core/http-dispatcher.d.ts new file mode 100644 index 0000000..b9d6d73 --- /dev/null +++ b/dist/core/http-dispatcher.d.ts @@ -0,0 +1,22 @@ +export declare const DEFAULT_HTTP_IDLE_TIMEOUT_MS = 300000; +export declare const HTTP_IDLE_TIMEOUT_CHOICES: readonly [{ + readonly label: "30 sec"; + readonly timeoutMs: 30000; +}, { + readonly label: "1 min"; + readonly timeoutMs: 60000; +}, { + readonly label: "2 min"; + readonly timeoutMs: 120000; +}, { + readonly label: "5 min"; + readonly timeoutMs: 300000; +}, { + readonly label: "disabled"; + readonly timeoutMs: 0; +}]; +export declare function parseHttpIdleTimeoutMs(value: unknown): number | undefined; +export declare function formatHttpIdleTimeoutMs(timeoutMs: number): string; +export declare function applyHttpProxySettings(httpProxy: string | undefined): void; +export declare function configureHttpDispatcher(timeoutMs?: number): void; +//# sourceMappingURL=http-dispatcher.d.ts.map \ No newline at end of file diff --git a/dist/core/http-dispatcher.d.ts.map b/dist/core/http-dispatcher.d.ts.map new file mode 100644 index 0000000..a465816 --- /dev/null +++ b/dist/core/http-dispatcher.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"http-dispatcher.d.ts","sourceRoot":"","sources":["../../src/core/http-dispatcher.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,4BAA4B,SAAU,CAAC;AAEpD,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;EAM5B,CAAC;AAKX,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAgBzE;AAED,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAMjE;AAED,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAK1E;AA+BD,wBAAgB,uBAAuB,CAAC,SAAS,GAAE,MAAqC,GAAG,IAAI,CA2B9F","sourcesContent":["import { EventEmitter } from \"node:events\";\nimport * as undici from \"undici\";\n\nexport const DEFAULT_HTTP_IDLE_TIMEOUT_MS = 300_000;\n\nexport const HTTP_IDLE_TIMEOUT_CHOICES = [\n\t{ label: \"30 sec\", timeoutMs: 30_000 },\n\t{ label: \"1 min\", timeoutMs: 60_000 },\n\t{ label: \"2 min\", timeoutMs: 120_000 },\n\t{ label: \"5 min\", timeoutMs: 300_000 },\n\t{ label: \"disabled\", timeoutMs: 0 },\n] as const;\n\nconst originalGlobalFetch = globalThis.fetch;\nlet installedGlobalFetch: typeof globalThis.fetch | undefined;\n\nexport function parseHttpIdleTimeoutMs(value: unknown): number | undefined {\n\tif (typeof value === \"string\") {\n\t\tconst trimmed = value.trim();\n\t\tif (trimmed.toLowerCase() === \"disabled\") {\n\t\t\treturn 0;\n\t\t}\n\t\tif (trimmed.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn parseHttpIdleTimeoutMs(Number(trimmed));\n\t}\n\n\tif (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n\t\treturn undefined;\n\t}\n\treturn Math.floor(value);\n}\n\nexport function formatHttpIdleTimeoutMs(timeoutMs: number): string {\n\tconst choice = HTTP_IDLE_TIMEOUT_CHOICES.find((item) => item.timeoutMs === timeoutMs);\n\tif (choice) {\n\t\treturn choice.label;\n\t}\n\treturn `${timeoutMs / 1000} sec`;\n}\n\nexport function applyHttpProxySettings(httpProxy: string | undefined): void {\n\tconst proxy = httpProxy?.trim();\n\tif (!proxy) return;\n\tprocess.env.HTTP_PROXY ??= proxy;\n\tprocess.env.HTTPS_PROXY ??= proxy;\n}\n\nconst ignoreUndiciDispatcherError = (_error: unknown): void => {};\n\n// Undici can emit an internal Client \"error\" while terminating a mid-stream\n// fetch body. The body stream still rejects through reader.read(); this listener\n// only prevents EventEmitter's unhandled \"error\" special case from crashing pi.\nfunction withUndiciErrorListener(dispatcher: T): T {\n\tif (dispatcher instanceof EventEmitter) {\n\t\tEventEmitter.prototype.on.call(dispatcher, \"error\", ignoreUndiciDispatcherError);\n\t}\n\treturn dispatcher;\n}\n\nfunction createUndiciClient(origin: string | URL, options: object): undici.Dispatcher {\n\treturn withUndiciErrorListener(new undici.Client(origin, options as undici.Client.Options));\n}\n\nfunction createUndiciOriginDispatcher(origin: string | URL, options: object): undici.Dispatcher {\n\tconst dispatcherOptions = options as undici.Pool.Options;\n\tif (dispatcherOptions.connections === 1) {\n\t\treturn createUndiciClient(origin, dispatcherOptions);\n\t}\n\treturn withUndiciErrorListener(\n\t\tnew undici.Pool(origin, {\n\t\t\t...dispatcherOptions,\n\t\t\tfactory: createUndiciClient,\n\t\t}),\n\t);\n}\n\nexport function configureHttpDispatcher(timeoutMs: number = DEFAULT_HTTP_IDLE_TIMEOUT_MS): void {\n\tconst normalizedTimeoutMs = parseHttpIdleTimeoutMs(timeoutMs);\n\tif (normalizedTimeoutMs === undefined) {\n\t\tthrow new Error(`Invalid HTTP idle timeout: ${String(timeoutMs)}`);\n\t}\n\tconst dispatcher = withUndiciErrorListener(\n\t\tnew undici.EnvHttpProxyAgent({\n\t\t\tallowH2: false,\n\t\t\tbodyTimeout: normalizedTimeoutMs,\n\t\t\theadersTimeout: normalizedTimeoutMs,\n\t\t\tclientFactory: createUndiciClient,\n\t\t\tfactory: createUndiciOriginDispatcher,\n\t\t}),\n\t);\n\tundici.setGlobalDispatcher(dispatcher);\n\t// Keep fetch and the dispatcher on the same undici implementation. Node 26.0's\n\t// bundled fetch can otherwise consume compressed responses through npm undici's\n\t// dispatcher without decompressing them, causing response.json() failures.\n\t// If a caller replaced fetch after module load, preserve that deliberate override.\n\tconst shouldInstallGlobals =\n\t\tinstalledGlobalFetch === undefined\n\t\t\t? globalThis.fetch === originalGlobalFetch\n\t\t\t: globalThis.fetch === installedGlobalFetch;\n\tif (shouldInstallGlobals) {\n\t\tundici.install?.();\n\t\tinstalledGlobalFetch = globalThis.fetch;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/http-dispatcher.js b/dist/core/http-dispatcher.js new file mode 100644 index 0000000..6615475 --- /dev/null +++ b/dist/core/http-dispatcher.js @@ -0,0 +1,91 @@ +import { EventEmitter } from "node:events"; +import * as undici from "undici"; +export const DEFAULT_HTTP_IDLE_TIMEOUT_MS = 300_000; +export const HTTP_IDLE_TIMEOUT_CHOICES = [ + { label: "30 sec", timeoutMs: 30_000 }, + { label: "1 min", timeoutMs: 60_000 }, + { label: "2 min", timeoutMs: 120_000 }, + { label: "5 min", timeoutMs: 300_000 }, + { label: "disabled", timeoutMs: 0 }, +]; +const originalGlobalFetch = globalThis.fetch; +let installedGlobalFetch; +export function parseHttpIdleTimeoutMs(value) { + if (typeof value === "string") { + const trimmed = value.trim(); + if (trimmed.toLowerCase() === "disabled") { + return 0; + } + if (trimmed.length === 0) { + return undefined; + } + return parseHttpIdleTimeoutMs(Number(trimmed)); + } + if (typeof value !== "number" || !Number.isFinite(value) || value < 0) { + return undefined; + } + return Math.floor(value); +} +export function formatHttpIdleTimeoutMs(timeoutMs) { + const choice = HTTP_IDLE_TIMEOUT_CHOICES.find((item) => item.timeoutMs === timeoutMs); + if (choice) { + return choice.label; + } + return `${timeoutMs / 1000} sec`; +} +export function applyHttpProxySettings(httpProxy) { + const proxy = httpProxy?.trim(); + if (!proxy) + return; + process.env.HTTP_PROXY ??= proxy; + process.env.HTTPS_PROXY ??= proxy; +} +const ignoreUndiciDispatcherError = (_error) => { }; +// Undici can emit an internal Client "error" while terminating a mid-stream +// fetch body. The body stream still rejects through reader.read(); this listener +// only prevents EventEmitter's unhandled "error" special case from crashing pi. +function withUndiciErrorListener(dispatcher) { + if (dispatcher instanceof EventEmitter) { + EventEmitter.prototype.on.call(dispatcher, "error", ignoreUndiciDispatcherError); + } + return dispatcher; +} +function createUndiciClient(origin, options) { + return withUndiciErrorListener(new undici.Client(origin, options)); +} +function createUndiciOriginDispatcher(origin, options) { + const dispatcherOptions = options; + if (dispatcherOptions.connections === 1) { + return createUndiciClient(origin, dispatcherOptions); + } + return withUndiciErrorListener(new undici.Pool(origin, { + ...dispatcherOptions, + factory: createUndiciClient, + })); +} +export function configureHttpDispatcher(timeoutMs = DEFAULT_HTTP_IDLE_TIMEOUT_MS) { + const normalizedTimeoutMs = parseHttpIdleTimeoutMs(timeoutMs); + if (normalizedTimeoutMs === undefined) { + throw new Error(`Invalid HTTP idle timeout: ${String(timeoutMs)}`); + } + const dispatcher = withUndiciErrorListener(new undici.EnvHttpProxyAgent({ + allowH2: false, + bodyTimeout: normalizedTimeoutMs, + headersTimeout: normalizedTimeoutMs, + clientFactory: createUndiciClient, + factory: createUndiciOriginDispatcher, + })); + undici.setGlobalDispatcher(dispatcher); + // Keep fetch and the dispatcher on the same undici implementation. Node 26.0's + // bundled fetch can otherwise consume compressed responses through npm undici's + // dispatcher without decompressing them, causing response.json() failures. + // If a caller replaced fetch after module load, preserve that deliberate override. + const shouldInstallGlobals = installedGlobalFetch === undefined + ? globalThis.fetch === originalGlobalFetch + : globalThis.fetch === installedGlobalFetch; + if (shouldInstallGlobals) { + undici.install?.(); + installedGlobalFetch = globalThis.fetch; + } +} +//# sourceMappingURL=http-dispatcher.js.map \ No newline at end of file diff --git a/dist/core/http-dispatcher.js.map b/dist/core/http-dispatcher.js.map new file mode 100644 index 0000000..bb7e4cb --- /dev/null +++ b/dist/core/http-dispatcher.js.map @@ -0,0 +1 @@ +{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EOUT_MS = 300_000;\n\nexport const HTTP_IDLE_TIMEOUT_CHOICES = [\n\t{ label: \"30 sec\", timeoutMs: 30_000 },\n\t{ label: \"1 min\", timeoutMs: 60_000 },\n\t{ label: \"2 min\", timeoutMs: 120_000 },\n\t{ label: \"5 min\", timeoutMs: 300_000 },\n\t{ label: \"disabled\", timeoutMs: 0 },\n] as const;\n\nconst originalGlobalFetch = globalThis.fetch;\nlet installedGlobalFetch: typeof globalThis.fetch | undefined;\n\nexport function parseHttpIdleTimeoutMs(value: unknown): number | undefined {\n\tif (typeof value === \"string\") {\n\t\tconst trimmed = value.trim();\n\t\tif (trimmed.toLowerCase() === \"disabled\") {\n\t\t\treturn 0;\n\t\t}\n\t\tif (trimmed.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn parseHttpIdleTimeoutMs(Number(trimmed));\n\t}\n\n\tif (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n\t\treturn undefined;\n\t}\n\treturn Math.floor(value);\n}\n\nexport function formatHttpIdleTimeoutMs(timeoutMs: number): string {\n\tconst choice = HTTP_IDLE_TIMEOUT_CHOICES.find((item) => item.timeoutMs === timeoutMs);\n\tif (choice) {\n\t\treturn choice.label;\n\t}\n\treturn `${timeoutMs / 1000} sec`;\n}\n\nexport function applyHttpProxySettings(httpProxy: string | undefined): void {\n\tconst proxy = httpProxy?.trim();\n\tif (!proxy) return;\n\tprocess.env.HTTP_PROXY ??= proxy;\n\tprocess.env.HTTPS_PROXY ??= proxy;\n}\n\nconst ignoreUndiciDispatcherError = (_error: unknown): void => {};\n\n// Undici can emit an internal Client \"error\" while terminating a mid-stream\n// fetch body. The body stream still rejects through reader.read(); this listener\n// only prevents EventEmitter's unhandled \"error\" special case from crashing pi.\nfunction withUndiciErrorListener(dispatcher: T): T {\n\tif (dispatcher instanceof EventEmitter) {\n\t\tEventEmitter.prototype.on.call(dispatcher, \"error\", ignoreUndiciDispatcherError);\n\t}\n\treturn dispatcher;\n}\n\nfunction createUndiciClient(origin: string | URL, options: object): undici.Dispatcher {\n\treturn withUndiciErrorListener(new undici.Client(origin, options as undici.Client.Options));\n}\n\nfunction createUndiciOriginDispatcher(origin: string | URL, options: object): undici.Dispatcher {\n\tconst dispatcherOptions = options as undici.Pool.Options;\n\tif (dispatcherOptions.connections === 1) {\n\t\treturn createUndiciClient(origin, dispatcherOptions);\n\t}\n\treturn withUndiciErrorListener(\n\t\tnew undici.Pool(origin, {\n\t\t\t...dispatcherOptions,\n\t\t\tfactory: createUndiciClient,\n\t\t}),\n\t);\n}\n\nexport function configureHttpDispatcher(timeoutMs: number = DEFAULT_HTTP_IDLE_TIMEOUT_MS): void {\n\tconst normalizedTimeoutMs = parseHttpIdleTimeoutMs(timeoutMs);\n\tif (normalizedTimeoutMs === undefined) {\n\t\tthrow new Error(`Invalid HTTP idle timeout: ${String(timeoutMs)}`);\n\t}\n\tconst dispatcher = withUndiciErrorListener(\n\t\tnew undici.EnvHttpProxyAgent({\n\t\t\tallowH2: false,\n\t\t\tbodyTimeout: normalizedTimeoutMs,\n\t\t\theadersTimeout: normalizedTimeoutMs,\n\t\t\tclientFactory: createUndiciClient,\n\t\t\tfactory: createUndiciOriginDispatcher,\n\t\t}),\n\t);\n\tundici.setGlobalDispatcher(dispatcher);\n\t// Keep fetch and the dispatcher on the same undici implementation. Node 26.0's\n\t// bundled fetch can otherwise consume compressed responses through npm undici's\n\t// dispatcher without decompressing them, causing response.json() failures.\n\t// If a caller replaced fetch after module load, preserve that deliberate override.\n\tconst shouldInstallGlobals =\n\t\tinstalledGlobalFetch === undefined\n\t\t\t? globalThis.fetch === originalGlobalFetch\n\t\t\t: globalThis.fetch === installedGlobalFetch;\n\tif (shouldInstallGlobals) {\n\t\tundici.install?.();\n\t\tinstalledGlobalFetch = globalThis.fetch;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/index.d.ts b/dist/core/index.d.ts new file mode 100644 index 0000000..a1b9d76 --- /dev/null +++ b/dist/core/index.d.ts @@ -0,0 +1,13 @@ +/** + * Core modules shared between all run modes. + */ +export { AgentSession, type AgentSessionConfig, type AgentSessionEvent, type AgentSessionEventListener, type ModelCycleResult, type PromptOptions, type SessionStats, } from "./agent-session.ts"; +export { AgentSessionRuntime, type CreateAgentSessionRuntimeFactory, type CreateAgentSessionRuntimeResult, createAgentSessionRuntime, } from "./agent-session-runtime.ts"; +export { type AgentSessionRuntimeDiagnostic, type AgentSessionServices, type CreateAgentSessionFromServicesOptions, type CreateAgentSessionServicesOptions, createAgentSessionFromServices, createAgentSessionServices, } from "./agent-session-services.ts"; +export { type BashExecutorOptions, type BashResult, executeBashWithOperations } from "./bash-executor.ts"; +export type { CompactionResult } from "./compaction/index.ts"; +export { createEventBus, type EventBus, type EventBusController } from "./event-bus.ts"; +export { areExperimentalFeaturesEnabled } from "./experimental.ts"; +export { type AgentEndEvent, type AgentSettledEvent, type AgentStartEvent, type AgentToolResult, type AgentToolUpdateCallback, type BeforeAgentStartEvent, type BeforeAgentStartEventResult, type BuildSystemPromptOptions, type ContextEvent, defineTool, discoverAndLoadExtensions, type ExecOptions, type ExecResult, type Extension, type ExtensionAPI, type ExtensionCommandContext, type ExtensionContext, type ExtensionError, type ExtensionEvent, type ExtensionFactory, type ExtensionFlag, type ExtensionHandler, ExtensionRunner, type ExtensionShortcut, type ExtensionUIContext, type InlineExtension, type LoadExtensionsResult, type MessageRenderer, type RegisteredCommand, type SessionBeforeCompactEvent, type SessionBeforeForkEvent, type SessionBeforeSwitchEvent, type SessionBeforeTreeEvent, type SessionCompactEvent, type SessionShutdownEvent, type SessionStartEvent, type SessionTreeEvent, type ToolCallEvent, type ToolCallEventResult, type ToolDefinition, type ToolRenderResultOptions, type ToolResultEvent, type TurnEndEvent, type TurnStartEvent, type WorkingIndicatorOptions, } from "./extensions/index.ts"; +export { createSyntheticSourceInfo } from "./source-info.ts"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/core/index.d.ts.map b/dist/core/index.d.ts.map new file mode 100644 index 0000000..ef22bcc --- /dev/null +++ b/dist/core/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EACN,YAAY,EACZ,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,yBAAyB,EAC9B,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,YAAY,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACN,mBAAmB,EACnB,KAAK,gCAAgC,EACrC,KAAK,+BAA+B,EACpC,yBAAyB,GACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACN,KAAK,6BAA6B,EAClC,KAAK,oBAAoB,EACzB,KAAK,qCAAqC,EAC1C,KAAK,iCAAiC,EACtC,8BAA8B,EAC9B,0BAA0B,GAC1B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,UAAU,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC1G,YAAY,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,KAAK,QAAQ,EAAE,KAAK,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACxF,OAAO,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AAEnE,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,KAAK,2BAA2B,EAChC,KAAK,wBAAwB,EAC7B,KAAK,YAAY,EACjB,UAAU,EACV,yBAAyB,EACzB,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,uBAAuB,EAC5B,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,eAAe,EACf,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,eAAe,EACpB,KAAK,oBAAoB,EACzB,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACtB,KAAK,yBAAyB,EAC9B,KAAK,sBAAsB,EAC3B,KAAK,wBAAwB,EAC7B,KAAK,sBAAsB,EAC3B,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,mBAAmB,EACxB,KAAK,cAAc,EACnB,KAAK,uBAAuB,EAC5B,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,KAAK,uBAAuB,GAC5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["/**\n * Core modules shared between all run modes.\n */\n\nexport {\n\tAgentSession,\n\ttype AgentSessionConfig,\n\ttype AgentSessionEvent,\n\ttype AgentSessionEventListener,\n\ttype ModelCycleResult,\n\ttype PromptOptions,\n\ttype SessionStats,\n} from \"./agent-session.ts\";\nexport {\n\tAgentSessionRuntime,\n\ttype CreateAgentSessionRuntimeFactory,\n\ttype CreateAgentSessionRuntimeResult,\n\tcreateAgentSessionRuntime,\n} from \"./agent-session-runtime.ts\";\nexport {\n\ttype AgentSessionRuntimeDiagnostic,\n\ttype AgentSessionServices,\n\ttype CreateAgentSessionFromServicesOptions,\n\ttype CreateAgentSessionServicesOptions,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionServices,\n} from \"./agent-session-services.ts\";\nexport { type BashExecutorOptions, type BashResult, executeBashWithOperations } from \"./bash-executor.ts\";\nexport type { CompactionResult } from \"./compaction/index.ts\";\nexport { createEventBus, type EventBus, type EventBusController } from \"./event-bus.ts\";\nexport { areExperimentalFeaturesEnabled } from \"./experimental.ts\";\n// Extensions system\nexport {\n\ttype AgentEndEvent,\n\ttype AgentSettledEvent,\n\ttype AgentStartEvent,\n\ttype AgentToolResult,\n\ttype AgentToolUpdateCallback,\n\ttype BeforeAgentStartEvent,\n\ttype BeforeAgentStartEventResult,\n\ttype BuildSystemPromptOptions,\n\ttype ContextEvent,\n\tdefineTool,\n\tdiscoverAndLoadExtensions,\n\ttype ExecOptions,\n\ttype ExecResult,\n\ttype Extension,\n\ttype ExtensionAPI,\n\ttype ExtensionCommandContext,\n\ttype ExtensionContext,\n\ttype ExtensionError,\n\ttype ExtensionEvent,\n\ttype ExtensionFactory,\n\ttype ExtensionFlag,\n\ttype ExtensionHandler,\n\tExtensionRunner,\n\ttype ExtensionShortcut,\n\ttype ExtensionUIContext,\n\ttype InlineExtension,\n\ttype LoadExtensionsResult,\n\ttype MessageRenderer,\n\ttype RegisteredCommand,\n\ttype SessionBeforeCompactEvent,\n\ttype SessionBeforeForkEvent,\n\ttype SessionBeforeSwitchEvent,\n\ttype SessionBeforeTreeEvent,\n\ttype SessionCompactEvent,\n\ttype SessionShutdownEvent,\n\ttype SessionStartEvent,\n\ttype SessionTreeEvent,\n\ttype ToolCallEvent,\n\ttype ToolCallEventResult,\n\ttype ToolDefinition,\n\ttype ToolRenderResultOptions,\n\ttype ToolResultEvent,\n\ttype TurnEndEvent,\n\ttype TurnStartEvent,\n\ttype WorkingIndicatorOptions,\n} from \"./extensions/index.ts\";\nexport { createSyntheticSourceInfo } from \"./source-info.ts\";\n"]} \ No newline at end of file diff --git a/dist/core/index.js b/dist/core/index.js new file mode 100644 index 0000000..4374288 --- /dev/null +++ b/dist/core/index.js @@ -0,0 +1,13 @@ +/** + * Core modules shared between all run modes. + */ +export { AgentSession, } from "./agent-session.js"; +export { AgentSessionRuntime, createAgentSessionRuntime, } from "./agent-session-runtime.js"; +export { createAgentSessionFromServices, createAgentSessionServices, } from "./agent-session-services.js"; +export { executeBashWithOperations } from "./bash-executor.js"; +export { createEventBus } from "./event-bus.js"; +export { areExperimentalFeaturesEnabled } from "./experimental.js"; +// Extensions system +export { defineTool, discoverAndLoadExtensions, ExtensionRunner, } from "./extensions/index.js"; +export { createSyntheticSourceInfo } from "./source-info.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/core/index.js.map b/dist/core/index.js.map new file mode 100644 index 0000000..7787ce7 --- /dev/null +++ b/dist/core/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EACN,YAAY,GAOZ,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACN,mBAAmB,EAGnB,yBAAyB,GACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAKN,8BAA8B,EAC9B,0BAA0B,GAC1B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAA6C,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAE1G,OAAO,EAAE,cAAc,EAA0C,MAAM,gBAAgB,CAAC;AACxF,OAAO,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AACnE,oBAAoB;AACpB,OAAO,EAUN,UAAU,EACV,yBAAyB,EAYzB,eAAe,GAuBf,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["/**\n * Core modules shared between all run modes.\n */\n\nexport {\n\tAgentSession,\n\ttype AgentSessionConfig,\n\ttype AgentSessionEvent,\n\ttype AgentSessionEventListener,\n\ttype ModelCycleResult,\n\ttype PromptOptions,\n\ttype SessionStats,\n} from \"./agent-session.ts\";\nexport {\n\tAgentSessionRuntime,\n\ttype CreateAgentSessionRuntimeFactory,\n\ttype CreateAgentSessionRuntimeResult,\n\tcreateAgentSessionRuntime,\n} from \"./agent-session-runtime.ts\";\nexport {\n\ttype AgentSessionRuntimeDiagnostic,\n\ttype AgentSessionServices,\n\ttype CreateAgentSessionFromServicesOptions,\n\ttype CreateAgentSessionServicesOptions,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionServices,\n} from \"./agent-session-services.ts\";\nexport { type BashExecutorOptions, type BashResult, executeBashWithOperations } from \"./bash-executor.ts\";\nexport type { CompactionResult } from \"./compaction/index.ts\";\nexport { createEventBus, type EventBus, type EventBusController } from \"./event-bus.ts\";\nexport { areExperimentalFeaturesEnabled } from \"./experimental.ts\";\n// Extensions system\nexport {\n\ttype AgentEndEvent,\n\ttype AgentSettledEvent,\n\ttype AgentStartEvent,\n\ttype AgentToolResult,\n\ttype AgentToolUpdateCallback,\n\ttype BeforeAgentStartEvent,\n\ttype BeforeAgentStartEventResult,\n\ttype BuildSystemPromptOptions,\n\ttype ContextEvent,\n\tdefineTool,\n\tdiscoverAndLoadExtensions,\n\ttype ExecOptions,\n\ttype ExecResult,\n\ttype Extension,\n\ttype ExtensionAPI,\n\ttype ExtensionCommandContext,\n\ttype ExtensionContext,\n\ttype ExtensionError,\n\ttype ExtensionEvent,\n\ttype ExtensionFactory,\n\ttype ExtensionFlag,\n\ttype ExtensionHandler,\n\tExtensionRunner,\n\ttype ExtensionShortcut,\n\ttype ExtensionUIContext,\n\ttype InlineExtension,\n\ttype LoadExtensionsResult,\n\ttype MessageRenderer,\n\ttype RegisteredCommand,\n\ttype SessionBeforeCompactEvent,\n\ttype SessionBeforeForkEvent,\n\ttype SessionBeforeSwitchEvent,\n\ttype SessionBeforeTreeEvent,\n\ttype SessionCompactEvent,\n\ttype SessionShutdownEvent,\n\ttype SessionStartEvent,\n\ttype SessionTreeEvent,\n\ttype ToolCallEvent,\n\ttype ToolCallEventResult,\n\ttype ToolDefinition,\n\ttype ToolRenderResultOptions,\n\ttype ToolResultEvent,\n\ttype TurnEndEvent,\n\ttype TurnStartEvent,\n\ttype WorkingIndicatorOptions,\n} from \"./extensions/index.ts\";\nexport { createSyntheticSourceInfo } from \"./source-info.ts\";\n"]} \ No newline at end of file diff --git a/dist/core/keybindings.d.ts b/dist/core/keybindings.d.ts new file mode 100644 index 0000000..59b987b --- /dev/null +++ b/dist/core/keybindings.d.ts @@ -0,0 +1,358 @@ +import { type Keybinding, type KeybindingsConfig, type KeyId, KeybindingsManager as TuiKeybindingsManager } from "@earendil-works/pi-tui"; +export interface AppKeybindings { + "app.interrupt": true; + "app.clear": true; + "app.exit": true; + "app.suspend": true; + "app.thinking.cycle": true; + "app.model.cycleForward": true; + "app.model.cycleBackward": true; + "app.model.select": true; + "app.tools.expand": true; + "app.thinking.toggle": true; + "app.session.toggleNamedFilter": true; + "app.editor.external": true; + "app.message.copy": true; + "app.message.followUp": true; + "app.message.dequeue": true; + "app.clipboard.pasteImage": true; + "app.session.new": true; + "app.session.tree": true; + "app.session.fork": true; + "app.session.resume": true; + "app.tree.foldOrUp": true; + "app.tree.unfoldOrDown": true; + "app.tree.editLabel": true; + "app.tree.toggleLabelTimestamp": true; + "app.session.togglePath": true; + "app.session.toggleSort": true; + "app.session.rename": true; + "app.session.delete": true; + "app.session.deleteNoninvasive": true; + "app.models.save": true; + "app.models.enableAll": true; + "app.models.clearAll": true; + "app.models.toggleProvider": true; + "app.models.reorderUp": true; + "app.models.reorderDown": true; + "app.tree.filter.default": true; + "app.tree.filter.noTools": true; + "app.tree.filter.userOnly": true; + "app.tree.filter.labeledOnly": true; + "app.tree.filter.all": true; + "app.tree.filter.cycleForward": true; + "app.tree.filter.cycleBackward": true; +} +export type AppKeybinding = keyof AppKeybindings; +declare module "@earendil-works/pi-tui" { + interface Keybindings extends AppKeybindings { + } +} +export declare const KEYBINDINGS: { + readonly "tui.editor.cursorUp": { + readonly defaultKeys: "up"; + readonly description: "Move cursor up"; + }; + readonly "tui.editor.cursorDown": { + readonly defaultKeys: "down"; + readonly description: "Move cursor down"; + }; + readonly "tui.editor.cursorLeft": { + readonly defaultKeys: ["left", "ctrl+b"]; + readonly description: "Move cursor left"; + }; + readonly "tui.editor.cursorRight": { + readonly defaultKeys: ["right", "ctrl+f"]; + readonly description: "Move cursor right"; + }; + readonly "tui.editor.cursorWordLeft": { + readonly defaultKeys: ["alt+left", "ctrl+left", "alt+b"]; + readonly description: "Move cursor word left"; + }; + readonly "tui.editor.cursorWordRight": { + readonly defaultKeys: ["alt+right", "ctrl+right", "alt+f"]; + readonly description: "Move cursor word right"; + }; + readonly "tui.editor.cursorLineStart": { + readonly defaultKeys: ["home", "ctrl+a"]; + readonly description: "Move to line start"; + }; + readonly "tui.editor.cursorLineEnd": { + readonly defaultKeys: ["end", "ctrl+e"]; + readonly description: "Move to line end"; + }; + readonly "tui.editor.jumpForward": { + readonly defaultKeys: "ctrl+]"; + readonly description: "Jump forward to character"; + }; + readonly "tui.editor.jumpBackward": { + readonly defaultKeys: "ctrl+alt+]"; + readonly description: "Jump backward to character"; + }; + readonly "tui.editor.pageUp": { + readonly defaultKeys: "pageUp"; + readonly description: "Page up"; + }; + readonly "tui.editor.pageDown": { + readonly defaultKeys: "pageDown"; + readonly description: "Page down"; + }; + readonly "tui.editor.deleteCharBackward": { + readonly defaultKeys: "backspace"; + readonly description: "Delete character backward"; + }; + readonly "tui.editor.deleteCharForward": { + readonly defaultKeys: ["delete", "ctrl+d"]; + readonly description: "Delete character forward"; + }; + readonly "tui.editor.deleteWordBackward": { + readonly defaultKeys: ["ctrl+w", "alt+backspace"]; + readonly description: "Delete word backward"; + }; + readonly "tui.editor.deleteWordForward": { + readonly defaultKeys: ["alt+d", "alt+delete"]; + readonly description: "Delete word forward"; + }; + readonly "tui.editor.deleteToLineStart": { + readonly defaultKeys: "ctrl+u"; + readonly description: "Delete to line start"; + }; + readonly "tui.editor.deleteToLineEnd": { + readonly defaultKeys: "ctrl+k"; + readonly description: "Delete to line end"; + }; + readonly "tui.editor.yank": { + readonly defaultKeys: "ctrl+y"; + readonly description: "Yank"; + }; + readonly "tui.editor.yankPop": { + readonly defaultKeys: "alt+y"; + readonly description: "Yank pop"; + }; + readonly "tui.editor.undo": { + readonly defaultKeys: "ctrl+-"; + readonly description: "Undo"; + }; + readonly "tui.input.newLine": { + readonly defaultKeys: ["shift+enter", "ctrl+j"]; + readonly description: "Insert newline"; + }; + readonly "tui.input.submit": { + readonly defaultKeys: "enter"; + readonly description: "Submit input"; + }; + readonly "tui.input.tab": { + readonly defaultKeys: "tab"; + readonly description: "Tab / autocomplete"; + }; + readonly "tui.input.copy": { + readonly defaultKeys: "ctrl+c"; + readonly description: "Copy selection"; + }; + readonly "tui.select.up": { + readonly defaultKeys: "up"; + readonly description: "Move selection up"; + }; + readonly "tui.select.down": { + readonly defaultKeys: "down"; + readonly description: "Move selection down"; + }; + readonly "tui.select.pageUp": { + readonly defaultKeys: "pageUp"; + readonly description: "Selection page up"; + }; + readonly "tui.select.pageDown": { + readonly defaultKeys: "pageDown"; + readonly description: "Selection page down"; + }; + readonly "tui.select.confirm": { + readonly defaultKeys: "enter"; + readonly description: "Confirm selection"; + }; + readonly "tui.select.cancel": { + readonly defaultKeys: ["escape", "ctrl+c"]; + readonly description: "Cancel selection"; + }; + readonly "app.interrupt": { + readonly defaultKeys: "escape"; + readonly description: "Cancel or abort"; + }; + readonly "app.clear": { + readonly defaultKeys: "ctrl+c"; + readonly description: "Clear editor"; + }; + readonly "app.exit": { + readonly defaultKeys: "ctrl+d"; + readonly description: "Exit when editor is empty"; + }; + readonly "app.suspend": { + readonly defaultKeys: "ctrl+z" | never[]; + readonly description: "Suspend to background"; + }; + readonly "app.thinking.cycle": { + readonly defaultKeys: "shift+tab"; + readonly description: "Cycle thinking level"; + }; + readonly "app.model.cycleForward": { + readonly defaultKeys: "ctrl+p"; + readonly description: "Cycle to next model"; + }; + readonly "app.model.cycleBackward": { + readonly defaultKeys: "shift+ctrl+p"; + readonly description: "Cycle to previous model"; + }; + readonly "app.model.select": { + readonly defaultKeys: "ctrl+l"; + readonly description: "Open model selector"; + }; + readonly "app.tools.expand": { + readonly defaultKeys: "ctrl+o"; + readonly description: "Toggle tool output"; + }; + readonly "app.thinking.toggle": { + readonly defaultKeys: "ctrl+t"; + readonly description: "Toggle thinking blocks"; + }; + readonly "app.session.toggleNamedFilter": { + readonly defaultKeys: "ctrl+n"; + readonly description: "Toggle named session filter"; + }; + readonly "app.editor.external": { + readonly defaultKeys: "ctrl+g"; + readonly description: "Open external editor"; + }; + readonly "app.message.copy": { + readonly defaultKeys: "ctrl+x"; + readonly description: "Copy message to clipboard"; + }; + readonly "app.message.followUp": { + readonly defaultKeys: "alt+enter"; + readonly description: "Queue follow-up message"; + }; + readonly "app.message.dequeue": { + readonly defaultKeys: "alt+up"; + readonly description: "Restore queued messages"; + }; + readonly "app.clipboard.pasteImage": { + readonly defaultKeys: "alt+v" | "ctrl+v"; + readonly description: "Paste image from clipboard (text fallback)"; + }; + readonly "app.session.new": { + readonly defaultKeys: []; + readonly description: "Start a new session"; + }; + readonly "app.session.tree": { + readonly defaultKeys: []; + readonly description: "Open session tree"; + }; + readonly "app.session.fork": { + readonly defaultKeys: []; + readonly description: "Fork current session"; + }; + readonly "app.session.resume": { + readonly defaultKeys: []; + readonly description: "Resume a session"; + }; + readonly "app.tree.foldOrUp": { + readonly defaultKeys: ("alt+left" | "ctrl+left")[]; + readonly description: "Fold tree branch or move up"; + }; + readonly "app.tree.unfoldOrDown": { + readonly defaultKeys: ("alt+right" | "ctrl+right")[]; + readonly description: "Unfold tree branch or move down"; + }; + readonly "app.tree.editLabel": { + readonly defaultKeys: "shift+l"; + readonly description: "Edit tree label"; + }; + readonly "app.tree.toggleLabelTimestamp": { + readonly defaultKeys: "shift+t"; + readonly description: "Toggle tree label timestamps"; + }; + readonly "app.session.togglePath": { + readonly defaultKeys: "ctrl+p"; + readonly description: "Toggle session path display"; + }; + readonly "app.session.toggleSort": { + readonly defaultKeys: "ctrl+s"; + readonly description: "Toggle session sort mode"; + }; + readonly "app.session.rename": { + readonly defaultKeys: "ctrl+r"; + readonly description: "Rename session"; + }; + readonly "app.session.delete": { + readonly defaultKeys: "ctrl+d"; + readonly description: "Delete session"; + }; + readonly "app.session.deleteNoninvasive": { + readonly defaultKeys: "ctrl+backspace"; + readonly description: "Delete session when query is empty"; + }; + readonly "app.models.save": { + readonly defaultKeys: "ctrl+s"; + readonly description: "Save model selection"; + }; + readonly "app.models.enableAll": { + readonly defaultKeys: "ctrl+a"; + readonly description: "Enable all models"; + }; + readonly "app.models.clearAll": { + readonly defaultKeys: "ctrl+x"; + readonly description: "Clear all models"; + }; + readonly "app.models.toggleProvider": { + readonly defaultKeys: "ctrl+p"; + readonly description: "Toggle all models for provider"; + }; + readonly "app.models.reorderUp": { + readonly defaultKeys: "alt+up"; + readonly description: "Move model up in order"; + }; + readonly "app.models.reorderDown": { + readonly defaultKeys: "alt+down"; + readonly description: "Move model down in order"; + }; + readonly "app.tree.filter.default": { + readonly defaultKeys: "ctrl+d"; + readonly description: "Tree filter: default view"; + }; + readonly "app.tree.filter.noTools": { + readonly defaultKeys: "ctrl+t"; + readonly description: "Tree filter: hide tool results"; + }; + readonly "app.tree.filter.userOnly": { + readonly defaultKeys: "ctrl+u"; + readonly description: "Tree filter: user messages only"; + }; + readonly "app.tree.filter.labeledOnly": { + readonly defaultKeys: "ctrl+l"; + readonly description: "Tree filter: labeled entries only"; + }; + readonly "app.tree.filter.all": { + readonly defaultKeys: "ctrl+a"; + readonly description: "Tree filter: show all entries"; + }; + readonly "app.tree.filter.cycleForward": { + readonly defaultKeys: "ctrl+o"; + readonly description: "Tree filter: cycle forward"; + }; + readonly "app.tree.filter.cycleBackward": { + readonly defaultKeys: "shift+ctrl+o"; + readonly description: "Tree filter: cycle backward"; + }; +}; +export declare function migrateKeybindingsConfig(rawConfig: Record): { + config: Record; + migrated: boolean; +}; +export declare class KeybindingsManager extends TuiKeybindingsManager { + private configPath; + constructor(userBindings?: KeybindingsConfig, configPath?: string); + static create(agentDir?: string): KeybindingsManager; + reload(): void; + getEffectiveConfig(): KeybindingsConfig; + private static loadFromFile; +} +export type { Keybinding, KeyId, KeybindingsConfig }; +//# sourceMappingURL=keybindings.d.ts.map \ No newline at end of file diff --git a/dist/core/keybindings.d.ts.map b/dist/core/keybindings.d.ts.map new file mode 100644 index 0000000..f9ab1a4 --- /dev/null +++ b/dist/core/keybindings.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"keybindings.d.ts","sourceRoot":"","sources":["../../src/core/keybindings.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,UAAU,EAEf,KAAK,iBAAiB,EACtB,KAAK,KAAK,EAEV,kBAAkB,IAAI,qBAAqB,EAC3C,MAAM,wBAAwB,CAAC;AAKhC,MAAM,WAAW,cAAc;IAC9B,eAAe,EAAE,IAAI,CAAC;IACtB,WAAW,EAAE,IAAI,CAAC;IAClB,UAAU,EAAE,IAAI,CAAC;IACjB,aAAa,EAAE,IAAI,CAAC;IACpB,oBAAoB,EAAE,IAAI,CAAC;IAC3B,wBAAwB,EAAE,IAAI,CAAC;IAC/B,yBAAyB,EAAE,IAAI,CAAC;IAChC,kBAAkB,EAAE,IAAI,CAAC;IACzB,kBAAkB,EAAE,IAAI,CAAC;IACzB,qBAAqB,EAAE,IAAI,CAAC;IAC5B,+BAA+B,EAAE,IAAI,CAAC;IACtC,qBAAqB,EAAE,IAAI,CAAC;IAC5B,kBAAkB,EAAE,IAAI,CAAC;IACzB,sBAAsB,EAAE,IAAI,CAAC;IAC7B,qBAAqB,EAAE,IAAI,CAAC;IAC5B,0BAA0B,EAAE,IAAI,CAAC;IACjC,iBAAiB,EAAE,IAAI,CAAC;IACxB,kBAAkB,EAAE,IAAI,CAAC;IACzB,kBAAkB,EAAE,IAAI,CAAC;IACzB,oBAAoB,EAAE,IAAI,CAAC;IAC3B,mBAAmB,EAAE,IAAI,CAAC;IAC1B,uBAAuB,EAAE,IAAI,CAAC;IAC9B,oBAAoB,EAAE,IAAI,CAAC;IAC3B,+BAA+B,EAAE,IAAI,CAAC;IACtC,wBAAwB,EAAE,IAAI,CAAC;IAC/B,wBAAwB,EAAE,IAAI,CAAC;IAC/B,oBAAoB,EAAE,IAAI,CAAC;IAC3B,oBAAoB,EAAE,IAAI,CAAC;IA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AC,UAAU,CAAqB;IAEvC,YAAY,YAAY,GAAE,iBAAsB,EAAE,UAAU,CAAC,EAAE,MAAM,EAGpE;IAED,MAAM,CAAC,MAAM,CAAC,QAAQ,GAAE,MAAsB,GAAG,kBAAkB,CAIlE;IAED,MAAM,IAAI,IAAI,CAGb;IAED,kBAAkB,IAAI,iBAAiB,CAEtC;IAED,OAAO,CAAC,MAAM,CAAC,YAAY;CAK3B;AAED,YAAY,EAAE,UAAU,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC","sourcesContent":["import {\n\ttype Keybinding,\n\ttype KeybindingDefinitions,\n\ttype KeybindingsConfig,\n\ttype KeyId,\n\tTUI_KEYBINDINGS,\n\tKeybindingsManager as TuiKeybindingsManager,\n} from \"@earendil-works/pi-tui\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { getAgentDir } from \"../config.ts\";\n\nexport interface AppKeybindings {\n\t\"app.interrupt\": true;\n\t\"app.clear\": true;\n\t\"app.exit\": true;\n\t\"app.suspend\": true;\n\t\"app.thinking.cycle\": true;\n\t\"app.model.cycleForward\": true;\n\t\"app.model.cycleBackward\": true;\n\t\"app.model.select\": true;\n\t\"app.tools.expand\": true;\n\t\"app.thinking.toggle\": true;\n\t\"app.session.toggleNamedFilter\": true;\n\t\"app.editor.external\": true;\n\t\"app.message.copy\": true;\n\t\"app.message.followUp\": true;\n\t\"app.message.dequeue\": true;\n\t\"app.clipboard.pasteImage\": true;\n\t\"app.session.new\": true;\n\t\"app.session.tree\": true;\n\t\"app.session.fork\": true;\n\t\"app.session.resume\": true;\n\t\"app.tree.foldOrUp\": true;\n\t\"app.tree.unfoldOrDown\": true;\n\t\"app.tree.editLabel\": true;\n\t\"app.tree.toggleLabelTimestamp\": true;\n\t\"app.session.togglePath\": true;\n\t\"app.session.toggleSort\": true;\n\t\"app.session.rename\": true;\n\t\"app.session.delete\": true;\n\t\"app.session.deleteNoninvasive\": true;\n\t\"app.models.save\": true;\n\t\"app.models.enableAll\": true;\n\t\"app.models.clearAll\": true;\n\t\"app.models.toggleProvider\": true;\n\t\"app.models.reorderUp\": true;\n\t\"app.models.reorderDown\": true;\n\t\"app.tree.filter.default\": true;\n\t\"app.tree.filter.noTools\": true;\n\t\"app.tree.filter.userOnly\": true;\n\t\"app.tree.filter.labeledOnly\": true;\n\t\"app.tree.filter.all\": true;\n\t\"app.tree.filter.cycleForward\": true;\n\t\"app.tree.filter.cycleBackward\": true;\n}\n\nexport type AppKeybinding = keyof AppKeybindings;\n\ndeclare module \"@earendil-works/pi-tui\" {\n\tinterface Keybindings extends AppKeybindings {}\n}\n\nexport const KEYBINDINGS = {\n\t...TUI_KEYBINDINGS,\n\t\"app.interrupt\": { defaultKeys: \"escape\", description: \"Cancel or abort\" },\n\t\"app.clear\": { defaultKeys: \"ctrl+c\", description: \"Clear editor\" },\n\t\"app.exit\": { defaultKeys: \"ctrl+d\", description: \"Exit when editor is empty\" },\n\t\"app.suspend\": {\n\t\tdefaultKeys: process.platform === \"win32\" ? [] : \"ctrl+z\",\n\t\tdescription: \"Suspend to background\",\n\t},\n\t\"app.thinking.cycle\": {\n\t\tdefaultKeys: \"shift+tab\",\n\t\tdescription: \"Cycle thinking level\",\n\t},\n\t\"app.model.cycleForward\": {\n\t\tdefaultKeys: \"ctrl+p\",\n\t\tdescription: \"Cycle to next model\",\n\t},\n\t\"app.model.cycleBackward\": {\n\t\tdefaultKeys: \"shift+ctrl+p\",\n\t\tdescription: \"Cycle to previous model\",\n\t},\n\t\"app.model.select\": { defaultKeys: \"ctrl+l\", description: \"Open model selector\" },\n\t\"app.tools.expand\": { defaultKeys: \"ctrl+o\", description: \"Toggle tool output\" },\n\t\"app.thinking.toggle\": {\n\t\tdefaultKeys: \"ctrl+t\",\n\t\tdescription: \"Toggle thinking blocks\",\n\t},\n\t\"app.session.toggleNamedFilter\": {\n\t\tdefaultKeys: \"ctrl+n\",\n\t\tdescription: \"Toggle named session filter\",\n\t},\n\t\"app.editor.external\": {\n\t\tdefaultKeys: \"ctrl+g\",\n\t\tdescription: \"Open external editor\",\n\t},\n\t\"app.message.copy\": {\n\t\tdefaultKeys: \"ctrl+x\",\n\t\tdescription: \"Copy message to clipboard\",\n\t},\n\t\"app.message.followUp\": {\n\t\tdefaultKeys: \"alt+enter\",\n\t\tdescription: \"Queue follow-up message\",\n\t},\n\t\"app.message.dequeue\": {\n\t\tdefaultKeys: \"alt+up\",\n\t\tdescription: \"Restore queued messages\",\n\t},\n\t\"app.clipboard.pasteImage\": {\n\t\tdefaultKeys: process.platform === \"win32\" ? \"alt+v\" : \"ctrl+v\",\n\t\tdescription: \"Paste image from clipboard (text fallback)\",\n\t},\n\t\"app.session.new\": { defaultKeys: [], description: \"Start a new session\" },\n\t\"app.session.tree\": { defaultKeys: [], description: \"Open session tree\" },\n\t\"app.session.fork\": { defaultKeys: [], description: \"Fork current session\" },\n\t\"app.session.resume\": { defaultKeys: [], description: \"Resume a session\" },\n\t\"app.tree.foldOrUp\": {\n\t\tdefaultKeys: process.platform === \"darwin\" ? [\"alt+left\", \"ctrl+left\"] : [\"ctrl+left\", \"alt+left\"],\n\t\tdescription: \"Fold tree branch or move up\",\n\t},\n\t\"app.tree.unfoldOrDown\": {\n\t\tdefaultKeys: process.platform === \"darwin\" ? [\"alt+right\", \"ctrl+right\"] : [\"ctrl+right\", \"alt+right\"],\n\t\tdescription: \"Unfold tree branch or move down\",\n\t},\n\t\"app.tree.editLabel\": {\n\t\tdefaultKeys: \"shift+l\",\n\t\tdescription: \"Edit tree label\",\n\t},\n\t\"app.tree.toggleLabelTimestamp\": {\n\t\tdefaultKeys: \"shift+t\",\n\t\tdescription: \"Toggle tree label timestamps\",\n\t},\n\t\"app.session.togglePath\": {\n\t\tdefaultKeys: \"ctrl+p\",\n\t\tdescription: \"Toggle session path display\",\n\t},\n\t\"app.session.toggleSort\": {\n\t\tdefaultKeys: \"ctrl+s\",\n\t\tdescription: \"Toggle session sort mode\",\n\t},\n\t\"app.session.rename\": {\n\t\tdefaultKeys: \"ctrl+r\",\n\t\tdescription: \"Rename session\",\n\t},\n\t\"app.session.delete\": {\n\t\tdefaultKeys: \"ctrl+d\",\n\t\tdescription: \"Delete session\",\n\t},\n\t\"app.session.deleteNoninvasive\": {\n\t\tdefaultKeys: \"ctrl+backspace\",\n\t\tdescription: \"Delete session when query is empty\",\n\t},\n\t\"app.models.save\": {\n\t\tdefaultKeys: \"ctrl+s\",\n\t\tdescription: \"Save model selection\",\n\t},\n\t\"app.models.enableAll\": {\n\t\tdefaultKeys: \"ctrl+a\",\n\t\tdescription: \"Enable all models\",\n\t},\n\t\"app.models.clearAll\": {\n\t\tdefaultKeys: \"ctrl+x\",\n\t\tdescription: \"Clear all models\",\n\t},\n\t\"app.models.toggleProvider\": {\n\t\tdefaultKeys: \"ctrl+p\",\n\t\tdescription: \"Toggle all models for provider\",\n\t},\n\t\"app.models.reorderUp\": {\n\t\tdefaultKeys: \"alt+up\",\n\t\tdescription: \"Move model up in order\",\n\t},\n\t\"app.models.reorderDown\": {\n\t\tdefaultKeys: \"alt+down\",\n\t\tdescription: \"Move model down in order\",\n\t},\n\t\"app.tree.filter.default\": {\n\t\tdefaultKeys: \"ctrl+d\",\n\t\tdescription: \"Tree filter: default view\",\n\t},\n\t\"app.tree.filter.noTools\": {\n\t\tdefaultKeys: \"ctrl+t\",\n\t\tdescription: \"Tree filter: hide tool results\",\n\t},\n\t\"app.tree.filter.userOnly\": {\n\t\tdefaultKeys: \"ctrl+u\",\n\t\tdescription: \"Tree filter: user messages only\",\n\t},\n\t\"app.tree.filter.labeledOnly\": {\n\t\tdefaultKeys: \"ctrl+l\",\n\t\tdescription: \"Tree filter: labeled entries only\",\n\t},\n\t\"app.tree.filter.all\": {\n\t\tdefaultKeys: \"ctrl+a\",\n\t\tdescription: \"Tree filter: show all entries\",\n\t},\n\t\"app.tree.filter.cycleForward\": {\n\t\tdefaultKeys: \"ctrl+o\",\n\t\tdescription: \"Tree filter: cycle forward\",\n\t},\n\t\"app.tree.filter.cycleBackward\": {\n\t\tdefaultKeys: \"shift+ctrl+o\",\n\t\tdescription: \"Tree filter: cycle backward\",\n\t},\n} as const satisfies KeybindingDefinitions;\n\nconst KEYBINDING_NAME_MIGRATIONS = {\n\tcursorUp: \"tui.editor.cursorUp\",\n\tcursorDown: \"tui.editor.cursorDown\",\n\tcursorLeft: \"tui.editor.cursorLeft\",\n\tcursorRight: \"tui.editor.cursorRight\",\n\tcursorWordLeft: \"tui.editor.cursorWordLeft\",\n\tcursorWordRight: \"tui.editor.cursorWordRight\",\n\tcursorLineStart: \"tui.editor.cursorLineStart\",\n\tcursorLineEnd: \"tui.editor.cursorLineEnd\",\n\tjumpForward: \"tui.editor.jumpForward\",\n\tjumpBackward: \"tui.editor.jumpBackward\",\n\tpageUp: \"tui.editor.pageUp\",\n\tpageDown: \"tui.editor.pageDown\",\n\tdeleteCharBackward: \"tui.editor.deleteCharBackward\",\n\tdeleteCharForward: \"tui.editor.deleteCharForward\",\n\tdeleteWordBackward: \"tui.editor.deleteWordBackward\",\n\tdeleteWordForward: \"tui.editor.deleteWordForward\",\n\tdeleteToLineStart: \"tui.editor.deleteToLineStart\",\n\tdeleteToLineEnd: \"tui.editor.deleteToLineEnd\",\n\tyank: \"tui.editor.yank\",\n\tyankPop: \"tui.editor.yankPop\",\n\tundo: \"tui.editor.undo\",\n\tnewLine: \"tui.input.newLine\",\n\tsubmit: \"tui.input.submit\",\n\ttab: \"tui.input.tab\",\n\tcopy: \"tui.input.copy\",\n\tselectUp: \"tui.select.up\",\n\tselectDown: \"tui.select.down\",\n\tselectPageUp: \"tui.select.pageUp\",\n\tselectPageDown: \"tui.select.pageDown\",\n\tselectConfirm: \"tui.select.confirm\",\n\tselectCancel: \"tui.select.cancel\",\n\tinterrupt: \"app.interrupt\",\n\tclear: \"app.clear\",\n\texit: \"app.exit\",\n\tsuspend: \"app.suspend\",\n\tcycleThinkingLevel: \"app.thinking.cycle\",\n\tcycleModelForward: \"app.model.cycleForward\",\n\tcycleModelBackward: \"app.model.cycleBackward\",\n\tselectModel: \"app.model.select\",\n\texpandTools: \"app.tools.expand\",\n\ttoggleThinking: \"app.thinking.toggle\",\n\ttoggleSessionNamedFilter: \"app.session.toggleNamedFilter\",\n\texternalEditor: \"app.editor.external\",\n\tfollowUp: \"app.message.followUp\",\n\tdequeue: \"app.message.dequeue\",\n\tpasteImage: \"app.clipboard.pasteImage\",\n\tnewSession: \"app.session.new\",\n\ttree: \"app.session.tree\",\n\tfork: \"app.session.fork\",\n\tresume: \"app.session.resume\",\n\ttreeFoldOrUp: \"app.tree.foldOrUp\",\n\ttreeUnfoldOrDown: \"app.tree.unfoldOrDown\",\n\ttreeEditLabel: \"app.tree.editLabel\",\n\ttreeToggleLabelTimestamp: \"app.tree.toggleLabelTimestamp\",\n\ttoggleSessionPath: \"app.session.togglePath\",\n\ttoggleSessionSort: \"app.session.toggleSort\",\n\trenameSession: \"app.session.rename\",\n\tdeleteSession: \"app.session.delete\",\n\tdeleteSessionNoninvasive: \"app.session.deleteNoninvasive\",\n} as const satisfies Record;\n\nfunction isLegacyKeybindingName(key: string): key is keyof typeof KEYBINDING_NAME_MIGRATIONS {\n\treturn key in KEYBINDING_NAME_MIGRATIONS;\n}\n\nfunction toKeybindingsConfig(value: Record): KeybindingsConfig {\n\tconst config: KeybindingsConfig = {};\n\tfor (const [key, binding] of Object.entries(value)) {\n\t\tif (typeof binding === \"string\") {\n\t\t\tconfig[key] = binding as KeyId;\n\t\t\tcontinue;\n\t\t}\n\t\tif (Array.isArray(binding) && binding.every((entry) => typeof entry === \"string\")) {\n\t\t\tconfig[key] = binding as KeyId[];\n\t\t}\n\t}\n\treturn config;\n}\n\nexport function migrateKeybindingsConfig(rawConfig: Record): {\n\tconfig: Record;\n\tmigrated: boolean;\n} {\n\tconst config: Record = {};\n\tlet migrated = false;\n\n\tfor (const [key, value] of Object.entries(rawConfig)) {\n\t\tconst nextKey = isLegacyKeybindingName(key) ? KEYBINDING_NAME_MIGRATIONS[key] : key;\n\t\tif (nextKey !== key) {\n\t\t\tmigrated = true;\n\t\t}\n\t\tif (key !== nextKey && Object.hasOwn(rawConfig, nextKey)) {\n\t\t\tmigrated = true;\n\t\t\tcontinue;\n\t\t}\n\t\tconfig[nextKey] = value;\n\t}\n\n\treturn { config: orderKeybindingsConfig(config), migrated };\n}\n\nfunction orderKeybindingsConfig(config: Record): Record {\n\tconst ordered: Record = {};\n\tfor (const keybinding of Object.keys(KEYBINDINGS)) {\n\t\tif (Object.hasOwn(config, keybinding)) {\n\t\t\tordered[keybinding] = config[keybinding];\n\t\t}\n\t}\n\n\tconst extras = Object.keys(config)\n\t\t.filter((key) => !Object.hasOwn(ordered, key))\n\t\t.sort();\n\tfor (const key of extras) {\n\t\tordered[key] = config[key];\n\t}\n\n\treturn ordered;\n}\n\nfunction loadRawConfig(path: string): Record | undefined {\n\tif (!existsSync(path)) return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n\t\tif (typeof parsed !== \"object\" || parsed === null) return undefined;\n\t\treturn parsed as Record;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport class KeybindingsManager extends TuiKeybindingsManager {\n\tprivate configPath: string | undefined;\n\n\tconstructor(userBindings: KeybindingsConfig = {}, configPath?: string) {\n\t\tsuper(KEYBINDINGS, userBindings);\n\t\tthis.configPath = configPath;\n\t}\n\n\tstatic create(agentDir: string = getAgentDir()): KeybindingsManager {\n\t\tconst configPath = join(agentDir, \"keybindings.json\");\n\t\tconst userBindings = KeybindingsManager.loadFromFile(configPath);\n\t\treturn new KeybindingsManager(userBindings, configPath);\n\t}\n\n\treload(): void {\n\t\tif (!this.configPath) return;\n\t\tthis.setUserBindings(KeybindingsManager.loadFromFile(this.configPath));\n\t}\n\n\tgetEffectiveConfig(): KeybindingsConfig {\n\t\treturn this.getResolvedBindings();\n\t}\n\n\tprivate static loadFromFile(path: string): KeybindingsConfig {\n\t\tconst rawConfig = loadRawConfig(path);\n\t\tif (!rawConfig) return {};\n\t\treturn toKeybindingsConfig(migrateKeybindingsConfig(rawConfig).config);\n\t}\n}\n\nexport type { Keybinding, KeyId, KeybindingsConfig };\n"]} \ No newline at end of file diff --git a/dist/core/keybindings.js b/dist/core/keybindings.js new file mode 100644 index 0000000..3bf81e7 --- /dev/null +++ b/dist/core/keybindings.js @@ -0,0 +1,296 @@ +import { TUI_KEYBINDINGS, KeybindingsManager as TuiKeybindingsManager, } from "@earendil-works/pi-tui"; +import { existsSync, readFileSync } from "fs"; +import { join } from "path"; +import { getAgentDir } from "../config.js"; +export const KEYBINDINGS = { + ...TUI_KEYBINDINGS, + "app.interrupt": { defaultKeys: "escape", description: "Cancel or abort" }, + "app.clear": { defaultKeys: "ctrl+c", description: "Clear editor" }, + "app.exit": { defaultKeys: "ctrl+d", description: "Exit when editor is empty" }, + "app.suspend": { + defaultKeys: process.platform === "win32" ? [] : "ctrl+z", + description: "Suspend to background", + }, + "app.thinking.cycle": { + defaultKeys: "shift+tab", + description: "Cycle thinking level", + }, + "app.model.cycleForward": { + defaultKeys: "ctrl+p", + description: "Cycle to next model", + }, + "app.model.cycleBackward": { + defaultKeys: "shift+ctrl+p", + description: "Cycle to previous model", + }, + "app.model.select": { defaultKeys: "ctrl+l", description: "Open model selector" }, + "app.tools.expand": { defaultKeys: "ctrl+o", description: "Toggle tool output" }, + "app.thinking.toggle": { + defaultKeys: "ctrl+t", + description: "Toggle thinking blocks", + }, + "app.session.toggleNamedFilter": { + defaultKeys: "ctrl+n", + description: "Toggle named session filter", + }, + "app.editor.external": { + defaultKeys: "ctrl+g", + description: "Open external editor", + }, + "app.message.copy": { + defaultKeys: "ctrl+x", + description: "Copy message to clipboard", + }, + "app.message.followUp": { + defaultKeys: "alt+enter", + description: "Queue follow-up message", + }, + "app.message.dequeue": { + defaultKeys: "alt+up", + description: "Restore queued messages", + }, + "app.clipboard.pasteImage": { + defaultKeys: process.platform === "win32" ? "alt+v" : "ctrl+v", + description: "Paste image from clipboard (text fallback)", + }, + "app.session.new": { defaultKeys: [], description: "Start a new session" }, + "app.session.tree": { defaultKeys: [], description: "Open session tree" }, + "app.session.fork": { defaultKeys: [], description: "Fork current session" }, + "app.session.resume": { defaultKeys: [], description: "Resume a session" }, + "app.tree.foldOrUp": { + defaultKeys: process.platform === "darwin" ? ["alt+left", "ctrl+left"] : ["ctrl+left", "alt+left"], + description: "Fold tree branch or move up", + }, + "app.tree.unfoldOrDown": { + defaultKeys: process.platform === "darwin" ? ["alt+right", "ctrl+right"] : ["ctrl+right", "alt+right"], + description: "Unfold tree branch or move down", + }, + "app.tree.editLabel": { + defaultKeys: "shift+l", + description: "Edit tree label", + }, + "app.tree.toggleLabelTimestamp": { + defaultKeys: "shift+t", + description: "Toggle tree label timestamps", + }, + "app.session.togglePath": { + defaultKeys: "ctrl+p", + description: "Toggle session path display", + }, + "app.session.toggleSort": { + defaultKeys: "ctrl+s", + description: "Toggle session sort mode", + }, + "app.session.rename": { + defaultKeys: "ctrl+r", + description: "Rename session", + }, + "app.session.delete": { + defaultKeys: "ctrl+d", + description: "Delete session", + }, + "app.session.deleteNoninvasive": { + defaultKeys: "ctrl+backspace", + description: "Delete session when query is empty", + }, + "app.models.save": { + defaultKeys: "ctrl+s", + description: "Save model selection", + }, + "app.models.enableAll": { + defaultKeys: "ctrl+a", + description: "Enable all models", + }, + "app.models.clearAll": { + defaultKeys: "ctrl+x", + description: "Clear all models", + }, + "app.models.toggleProvider": { + defaultKeys: "ctrl+p", + description: "Toggle all models for provider", + }, + "app.models.reorderUp": { + defaultKeys: "alt+up", + description: "Move model up in order", + }, + "app.models.reorderDown": { + defaultKeys: "alt+down", + description: "Move model down in order", + }, + "app.tree.filter.default": { + defaultKeys: "ctrl+d", + description: "Tree filter: default view", + }, + "app.tree.filter.noTools": { + defaultKeys: "ctrl+t", + description: "Tree filter: hide tool results", + }, + "app.tree.filter.userOnly": { + defaultKeys: "ctrl+u", + description: "Tree filter: user messages only", + }, + "app.tree.filter.labeledOnly": { + defaultKeys: "ctrl+l", + description: "Tree filter: labeled entries only", + }, + "app.tree.filter.all": { + defaultKeys: "ctrl+a", + description: "Tree filter: show all entries", + }, + "app.tree.filter.cycleForward": { + defaultKeys: "ctrl+o", + description: "Tree filter: cycle forward", + }, + "app.tree.filter.cycleBackward": { + defaultKeys: "shift+ctrl+o", + description: "Tree filter: cycle backward", + }, +}; +const KEYBINDING_NAME_MIGRATIONS = { + cursorUp: "tui.editor.cursorUp", + cursorDown: "tui.editor.cursorDown", + cursorLeft: "tui.editor.cursorLeft", + cursorRight: "tui.editor.cursorRight", + cursorWordLeft: "tui.editor.cursorWordLeft", + cursorWordRight: "tui.editor.cursorWordRight", + cursorLineStart: "tui.editor.cursorLineStart", + cursorLineEnd: "tui.editor.cursorLineEnd", + jumpForward: "tui.editor.jumpForward", + jumpBackward: "tui.editor.jumpBackward", + pageUp: "tui.editor.pageUp", + pageDown: "tui.editor.pageDown", + deleteCharBackward: "tui.editor.deleteCharBackward", + deleteCharForward: "tui.editor.deleteCharForward", + deleteWordBackward: "tui.editor.deleteWordBackward", + deleteWordForward: "tui.editor.deleteWordForward", + deleteToLineStart: "tui.editor.deleteToLineStart", + deleteToLineEnd: "tui.editor.deleteToLineEnd", + yank: "tui.editor.yank", + yankPop: "tui.editor.yankPop", + undo: "tui.editor.undo", + newLine: "tui.input.newLine", + submit: "tui.input.submit", + tab: "tui.input.tab", + copy: "tui.input.copy", + selectUp: "tui.select.up", + selectDown: "tui.select.down", + selectPageUp: "tui.select.pageUp", + selectPageDown: "tui.select.pageDown", + selectConfirm: "tui.select.confirm", + selectCancel: "tui.select.cancel", + interrupt: "app.interrupt", + clear: "app.clear", + exit: "app.exit", + suspend: "app.suspend", + cycleThinkingLevel: "app.thinking.cycle", + cycleModelForward: "app.model.cycleForward", + cycleModelBackward: "app.model.cycleBackward", + selectModel: "app.model.select", + expandTools: "app.tools.expand", + toggleThinking: "app.thinking.toggle", + toggleSessionNamedFilter: "app.session.toggleNamedFilter", + externalEditor: "app.editor.external", + followUp: "app.message.followUp", + dequeue: "app.message.dequeue", + pasteImage: "app.clipboard.pasteImage", + newSession: "app.session.new", + tree: "app.session.tree", + fork: "app.session.fork", + resume: "app.session.resume", + treeFoldOrUp: "app.tree.foldOrUp", + treeUnfoldOrDown: "app.tree.unfoldOrDown", + treeEditLabel: "app.tree.editLabel", + treeToggleLabelTimestamp: "app.tree.toggleLabelTimestamp", + toggleSessionPath: "app.session.togglePath", + toggleSessionSort: "app.session.toggleSort", + renameSession: "app.session.rename", + deleteSession: "app.session.delete", + deleteSessionNoninvasive: "app.session.deleteNoninvasive", +}; +function isLegacyKeybindingName(key) { + return key in KEYBINDING_NAME_MIGRATIONS; +} +function toKeybindingsConfig(value) { + const config = {}; + for (const [key, binding] of Object.entries(value)) { + if (typeof binding === "string") { + config[key] = binding; + continue; + } + if (Array.isArray(binding) && binding.every((entry) => typeof entry === "string")) { + config[key] = binding; + } + } + return config; +} +export function migrateKeybindingsConfig(rawConfig) { + const config = {}; + let migrated = false; + for (const [key, value] of Object.entries(rawConfig)) { + const nextKey = isLegacyKeybindingName(key) ? KEYBINDING_NAME_MIGRATIONS[key] : key; + if (nextKey !== key) { + migrated = true; + } + if (key !== nextKey && Object.hasOwn(rawConfig, nextKey)) { + migrated = true; + continue; + } + config[nextKey] = value; + } + return { config: orderKeybindingsConfig(config), migrated }; +} +function orderKeybindingsConfig(config) { + const ordered = {}; + for (const keybinding of Object.keys(KEYBINDINGS)) { + if (Object.hasOwn(config, keybinding)) { + ordered[keybinding] = config[keybinding]; + } + } + const extras = Object.keys(config) + .filter((key) => !Object.hasOwn(ordered, key)) + .sort(); + for (const key of extras) { + ordered[key] = config[key]; + } + return ordered; +} +function loadRawConfig(path) { + if (!existsSync(path)) + return undefined; + try { + const parsed = JSON.parse(readFileSync(path, "utf-8")); + if (typeof parsed !== "object" || parsed === null) + return undefined; + return parsed; + } + catch { + return undefined; + } +} +export class KeybindingsManager extends TuiKeybindingsManager { + configPath; + constructor(userBindings = {}, configPath) { + super(KEYBINDINGS, userBindings); + this.configPath = configPath; + } + static create(agentDir = getAgentDir()) { + const configPath = join(agentDir, "keybindings.json"); + const userBindings = KeybindingsManager.loadFromFile(configPath); + return new KeybindingsManager(userBindings, configPath); + } + reload() { + if (!this.configPath) + return; + this.setUserBindings(KeybindingsManager.loadFromFile(this.configPath)); + } + getEffectiveConfig() { + return this.getResolvedBindings(); + } + static loadFromFile(path) { + const rawConfig = loadRawConfig(path); + if (!rawConfig) + return {}; + return toKeybindingsConfig(migrateKeybindingsConfig(rawConfig).config); + } +} +//# sourceMappingURL=keybindings.js.map \ No newline at end of file diff --git a/dist/core/keybindings.js.map b/dist/core/keybindings.js.map new file mode 100644 index 0000000..62aa1df --- /dev/null +++ b/dist/core/keybindings.js.map @@ -0,0 +1 @@ +{"version":3,"file":"keybindings.js","sourceRoot":"","sources":["../../src/core/keybindings.ts"],"names":[],"mappings":"AAAA,OAAO,EAKN,eAAe,EACf,kBAAkB,IAAI,qBAAqB,GAC3C,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAqD3C,MAAM,CAAC,MAAM,WAAW,GAAG;IAC1B,GAAG,eAAe;IAClB,eAAe,EAAE,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,iBAAiB,EAAE;IAC1E,WAAW,EAAE,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,cAAc,EAAE;IACnE,UAAU,EAAE,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,2BAA2B,EAAE;IAC/E,aAAa,EAAE;QACd,WAAW,EAAE,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ;QACzD,WAAW,EAAE,u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ClB,CAAC;AAAA,CACD;AAED,MAAM,OAAO,kBAAmB,SAAQ,qBAAqB;IACpD,UAAU,CAAqB;IAEvC,YAAY,YAAY,GAAsB,EAAE,EAAE,UAAmB,EAAE;QACtE,KAAK,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;QACjC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAAA,CAC7B;IAED,MAAM,CAAC,MAAM,CAAC,QAAQ,GAAW,WAAW,EAAE,EAAsB;QACnE,MAAM,UAAU,GAAG,IAAI,CAAC,QAAQ,EAAE,kBAAkB,CAAC,CAAC;QACtD,MAAM,YAAY,GAAG,kBAAkB,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC;QACjE,OAAO,IAAI,kBAAkB,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;IAAA,CACxD;IAED,MAAM,GAAS;QACd,IAAI,CAAC,IAAI,CAAC,UAAU;YAAE,OAAO;QAC7B,IAAI,CAAC,eAAe,CAAC,kBAAkB,CAAC,YAAY,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IAAA,CACvE;IAED,kBAAkB,GAAsB;QACvC,OAAO,IAAI,CAAC,mBAAmB,EAAE,CAAC;IAAA,CAClC;IAEO,MAAM,CAAC,YAAY,CAAC,IAAY,EAAqB;QAC5D,MAAM,SAAS,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC;QACtC,IAAI,CAAC,SAAS;YAAE,OAAO,EAAE,CAAC;QAC1B,OAAO,mBAAmB,CAAC,wBAAwB,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC;IAAA,CACvE;CACD","sourcesContent":["import {\n\ttype Keybinding,\n\ttype KeybindingDefinitions,\n\ttype KeybindingsConfig,\n\ttype KeyId,\n\tTUI_KEYBINDINGS,\n\tKeybindingsManager as TuiKeybindingsManager,\n} from \"@earendil-works/pi-tui\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { getAgentDir } from \"../config.ts\";\n\nexport interface AppKeybindings {\n\t\"app.interrupt\": true;\n\t\"app.clear\": true;\n\t\"app.exit\": true;\n\t\"app.suspend\": true;\n\t\"app.thinking.cycle\": true;\n\t\"app.model.cycleForward\": true;\n\t\"app.model.cycleBackward\": true;\n\t\"app.model.select\": true;\n\t\"app.tools.expand\": true;\n\t\"app.thinking.toggle\": true;\n\t\"app.session.toggleNamedFilter\": true;\n\t\"app.editor.external\": true;\n\t\"app.message.copy\": true;\n\t\"app.message.followUp\": true;\n\t\"app.message.dequeue\": true;\n\t\"app.clipboard.pasteImage\": true;\n\t\"app.session.new\": true;\n\t\"app.session.tree\": true;\n\t\"app.session.fork\": true;\n\t\"app.session.resume\": true;\n\t\"app.tree.foldOrUp\": true;\n\t\"app.tree.unfoldOrDown\": true;\n\t\"app.tree.editLabel\": true;\n\t\"app.tree.toggleLabelTimestamp\": true;\n\t\"app.session.togglePath\": true;\n\t\"app.session.toggleSort\": true;\n\t\"app.session.rename\": true;\n\t\"app.session.delete\": true;\n\t\"app.session.deleteNoninvasive\": true;\n\t\"app.models.save\": true;\n\t\"app.models.enableAll\": true;\n\t\"app.models.clearAll\": true;\n\t\"app.models.toggleProvider\": true;\n\t\"app.models.reorderUp\": true;\n\t\"app.models.reorderDown\": true;\n\t\"app.tree.filter.default\": true;\n\t\"app.tree.filter.noTools\": true;\n\t\"app.tree.filter.userOnly\": true;\n\t\"app.tree.filter.labeledOnly\": true;\n\t\"app.tree.filter.all\": true;\n\t\"app.tree.filter.cycleForward\": true;\n\t\"app.tree.filter.cycleBackward\": true;\n}\n\nexport type AppKeybinding = keyof AppKeybindings;\n\ndeclare module \"@earendil-works/pi-tui\" {\n\tinterface Keybindings extends AppKeybindings {}\n}\n\nexport const KEYBINDINGS = {\n\t...TUI_KEYBINDINGS,\n\t\"app.interrupt\": { defaultKeys: \"escape\", description: \"Cancel or abort\" },\n\t\"app.clear\": { defaultKeys: \"ctrl+c\", description: \"Clear editor\" },\n\t\"app.exit\": { defaultKeys: \"ctrl+d\", description: \"Exit when editor is empty\" },\n\t\"app.suspend\": {\n\t\tdefaultKeys: process.platform === \"win32\" ? [] : \"ctrl+z\",\n\t\tdescription: \"Suspend to background\",\n\t},\n\t\"app.thinking.cycle\": {\n\t\tdefaultKeys: \"shift+tab\",\n\t\tdescription: \"Cycle thinking level\",\n\t},\n\t\"app.model.cycleForward\": {\n\t\tdefaultKeys: \"ctrl+p\",\n\t\tdescription: \"Cycle to next model\",\n\t},\n\t\"app.model.cycleBackward\": {\n\t\tdefaultKeys: \"shift+ctrl+p\",\n\t\tdescription: \"Cycle to previous model\",\n\t},\n\t\"app.model.select\": { defaultKeys: \"ctrl+l\", description: \"Open model selector\" },\n\t\"app.tools.expand\": { defaultKeys: \"ctrl+o\", description: \"Toggle tool output\" },\n\t\"app.thinking.toggle\": {\n\t\tdefaultKeys: \"ctrl+t\",\n\t\tdescription: \"Toggle thinking blocks\",\n\t},\n\t\"app.session.toggleNamedFilter\": {\n\t\tdefaultKeys: \"ctrl+n\",\n\t\tdescription: \"Toggle named session filter\",\n\t},\n\t\"app.editor.external\": {\n\t\tdefaultKeys: \"ctrl+g\",\n\t\tdescription: \"Open external editor\",\n\t},\n\t\"app.message.copy\": {\n\t\tdefaultKeys: \"ctrl+x\",\n\t\tdescription: \"Copy message to clipboard\",\n\t},\n\t\"app.message.followUp\": {\n\t\tdefaultKeys: \"alt+enter\",\n\t\tdescription: \"Queue follow-up message\",\n\t},\n\t\"app.message.dequeue\": {\n\t\tdefaultKeys: \"alt+up\",\n\t\tdescription: \"Restore queued messages\",\n\t},\n\t\"app.clipboard.pasteImage\": {\n\t\tdefaultKeys: process.platform === \"win32\" ? \"alt+v\" : \"ctrl+v\",\n\t\tdescription: \"Paste image from clipboard (text fallback)\",\n\t},\n\t\"app.session.new\": { defaultKeys: [], description: \"Start a new session\" },\n\t\"app.session.tree\": { defaultKeys: [], description: \"Open session tree\" },\n\t\"app.session.fork\": { defaultKeys: [], description: \"Fork current session\" },\n\t\"app.session.resume\": { defaultKeys: [], description: \"Resume a session\" },\n\t\"app.tree.foldOrUp\": {\n\t\tdefaultKeys: process.platform === \"darwin\" ? [\"alt+left\", \"ctrl+left\"] : [\"ctrl+left\", \"alt+left\"],\n\t\tdescription: \"Fold tree branch or move up\",\n\t},\n\t\"app.tree.unfoldOrDown\": {\n\t\tdefaultKeys: process.platform === \"darwin\" ? [\"alt+right\", \"ctrl+right\"] : [\"ctrl+right\", \"alt+right\"],\n\t\tdescription: \"Unfold tree branch or move down\",\n\t},\n\t\"app.tree.editLabel\": {\n\t\tdefaultKeys: \"shift+l\",\n\t\tdescription: \"Edit tree label\",\n\t},\n\t\"app.tree.toggleLabelTimestamp\": {\n\t\tdefaultKeys: \"shift+t\",\n\t\tdescription: \"Toggle tree label timestamps\",\n\t},\n\t\"app.session.togglePath\": {\n\t\tdefaultKeys: \"ctrl+p\",\n\t\tdescription: \"Toggle session path display\",\n\t},\n\t\"app.session.toggleSort\": {\n\t\tdefaultKeys: \"ctrl+s\",\n\t\tdescription: \"Toggle session sort mode\",\n\t},\n\t\"app.session.rename\": {\n\t\tdefaultKeys: \"ctrl+r\",\n\t\tdescription: \"Rename session\",\n\t},\n\t\"app.session.delete\": {\n\t\tdefaultKeys: \"ctrl+d\",\n\t\tdescription: \"Delete session\",\n\t},\n\t\"app.session.deleteNoninvasive\": {\n\t\tdefaultKeys: \"ctrl+backspace\",\n\t\tdescription: \"Delete session when query is empty\",\n\t},\n\t\"app.models.save\": {\n\t\tdefaultKeys: \"ctrl+s\",\n\t\tdescription: \"Save model selection\",\n\t},\n\t\"app.models.enableAll\": {\n\t\tdefaultKeys: \"ctrl+a\",\n\t\tdescription: \"Enable all models\",\n\t},\n\t\"app.models.clearAll\": {\n\t\tdefaultKeys: \"ctrl+x\",\n\t\tdescription: \"Clear all models\",\n\t},\n\t\"app.models.toggleProvider\": {\n\t\tdefaultKeys: \"ctrl+p\",\n\t\tdescription: \"Toggle all models for provider\",\n\t},\n\t\"app.models.reorderUp\": {\n\t\tdefaultKeys: \"alt+up\",\n\t\tdescription: \"Move model up in order\",\n\t},\n\t\"app.models.reorderDown\": {\n\t\tdefaultKeys: \"alt+down\",\n\t\tdescription: \"Move model down in order\",\n\t},\n\t\"app.tree.filter.default\": {\n\t\tdefaultKeys: \"ctrl+d\",\n\t\tdescription: \"Tree filter: default view\",\n\t},\n\t\"app.tree.filter.noTools\": {\n\t\tdefaultKeys: \"ctrl+t\",\n\t\tdescription: \"Tree filter: hide tool results\",\n\t},\n\t\"app.tree.filter.userOnly\": {\n\t\tdefaultKeys: \"ctrl+u\",\n\t\tdescription: \"Tree filter: user messages only\",\n\t},\n\t\"app.tree.filter.labeledOnly\": {\n\t\tdefaultKeys: \"ctrl+l\",\n\t\tdescription: \"Tree filter: labeled entries only\",\n\t},\n\t\"app.tree.filter.all\": {\n\t\tdefaultKeys: \"ctrl+a\",\n\t\tdescription: \"Tree filter: show all entries\",\n\t},\n\t\"app.tree.filter.cycleForward\": {\n\t\tdefaultKeys: \"ctrl+o\",\n\t\tdescription: \"Tree filter: cycle forward\",\n\t},\n\t\"app.tree.filter.cycleBackward\": {\n\t\tdefaultKeys: \"shift+ctrl+o\",\n\t\tdescription: \"Tree filter: cycle backward\",\n\t},\n} as const satisfies KeybindingDefinitions;\n\nconst KEYBINDING_NAME_MIGRATIONS = {\n\tcursorUp: \"tui.editor.cursorUp\",\n\tcursorDown: \"tui.editor.cursorDown\",\n\tcursorLeft: \"tui.editor.cursorLeft\",\n\tcursorRight: \"tui.editor.cursorRight\",\n\tcursorWordLeft: \"tui.editor.cursorWordLeft\",\n\tcursorWordRight: \"tui.editor.cursorWordRight\",\n\tcursorLineStart: \"tui.editor.cursorLineStart\",\n\tcursorLineEnd: \"tui.editor.cursorLineEnd\",\n\tjumpForward: \"tui.editor.jumpForward\",\n\tjumpBackward: \"tui.editor.jumpBackward\",\n\tpageUp: \"tui.editor.pageUp\",\n\tpageDown: \"tui.editor.pageDown\",\n\tdeleteCharBackward: \"tui.editor.deleteCharBackward\",\n\tdeleteCharForward: \"tui.editor.deleteCharForward\",\n\tdeleteWordBackward: \"tui.editor.deleteWordBackward\",\n\tdeleteWordForward: \"tui.editor.deleteWordForward\",\n\tdeleteToLineStart: \"tui.editor.deleteToLineStart\",\n\tdeleteToLineEnd: \"tui.editor.deleteToLineEnd\",\n\tyank: \"tui.editor.yank\",\n\tyankPop: \"tui.editor.yankPop\",\n\tundo: \"tui.editor.undo\",\n\tnewLine: \"tui.input.newLine\",\n\tsubmit: \"tui.input.submit\",\n\ttab: \"tui.input.tab\",\n\tcopy: \"tui.input.copy\",\n\tselectUp: \"tui.select.up\",\n\tselectDown: \"tui.select.down\",\n\tselectPageUp: \"tui.select.pageUp\",\n\tselectPageDown: \"tui.select.pageDown\",\n\tselectConfirm: \"tui.select.confirm\",\n\tselectCancel: \"tui.select.cancel\",\n\tinterrupt: \"app.interrupt\",\n\tclear: \"app.clear\",\n\texit: \"app.exit\",\n\tsuspend: \"app.suspend\",\n\tcycleThinkingLevel: \"app.thinking.cycle\",\n\tcycleModelForward: \"app.model.cycleForward\",\n\tcycleModelBackward: \"app.model.cycleBackward\",\n\tselectModel: \"app.model.select\",\n\texpandTools: \"app.tools.expand\",\n\ttoggleThinking: \"app.thinking.toggle\",\n\ttoggleSessionNamedFilter: \"app.session.toggleNamedFilter\",\n\texternalEditor: \"app.editor.external\",\n\tfollowUp: \"app.message.followUp\",\n\tdequeue: \"app.message.dequeue\",\n\tpasteImage: \"app.clipboard.pasteImage\",\n\tnewSession: \"app.session.new\",\n\ttree: \"app.session.tree\",\n\tfork: \"app.session.fork\",\n\tresume: \"app.session.resume\",\n\ttreeFoldOrUp: \"app.tree.foldOrUp\",\n\ttreeUnfoldOrDown: \"app.tree.unfoldOrDown\",\n\ttreeEditLabel: \"app.tree.editLabel\",\n\ttreeToggleLabelTimestamp: \"app.tree.toggleLabelTimestamp\",\n\ttoggleSessionPath: \"app.session.togglePath\",\n\ttoggleSessionSort: \"app.session.toggleSort\",\n\trenameSession: \"app.session.rename\",\n\tdeleteSession: \"app.session.delete\",\n\tdeleteSessionNoninvasive: \"app.session.deleteNoninvasive\",\n} as const satisfies Record;\n\nfunction isLegacyKeybindingName(key: string): key is keyof typeof KEYBINDING_NAME_MIGRATIONS {\n\treturn key in KEYBINDING_NAME_MIGRATIONS;\n}\n\nfunction toKeybindingsConfig(value: Record): KeybindingsConfig {\n\tconst config: KeybindingsConfig = {};\n\tfor (const [key, binding] of Object.entries(value)) {\n\t\tif (typeof binding === \"string\") {\n\t\t\tconfig[key] = binding as KeyId;\n\t\t\tcontinue;\n\t\t}\n\t\tif (Array.isArray(binding) && binding.every((entry) => typeof entry === \"string\")) {\n\t\t\tconfig[key] = binding as KeyId[];\n\t\t}\n\t}\n\treturn config;\n}\n\nexport function migrateKeybindingsConfig(rawConfig: Record): {\n\tconfig: Record;\n\tmigrated: boolean;\n} {\n\tconst config: Record = {};\n\tlet migrated = false;\n\n\tfor (const [key, value] of Object.entries(rawConfig)) {\n\t\tconst nextKey = isLegacyKeybindingName(key) ? KEYBINDING_NAME_MIGRATIONS[key] : key;\n\t\tif (nextKey !== key) {\n\t\t\tmigrated = true;\n\t\t}\n\t\tif (key !== nextKey && Object.hasOwn(rawConfig, nextKey)) {\n\t\t\tmigrated = true;\n\t\t\tcontinue;\n\t\t}\n\t\tconfig[nextKey] = value;\n\t}\n\n\treturn { config: orderKeybindingsConfig(config), migrated };\n}\n\nfunction orderKeybindingsConfig(config: Record): Record {\n\tconst ordered: Record = {};\n\tfor (const keybinding of Object.keys(KEYBINDINGS)) {\n\t\tif (Object.hasOwn(config, keybinding)) {\n\t\t\tordered[keybinding] = config[keybinding];\n\t\t}\n\t}\n\n\tconst extras = Object.keys(config)\n\t\t.filter((key) => !Object.hasOwn(ordered, key))\n\t\t.sort();\n\tfor (const key of extras) {\n\t\tordered[key] = config[key];\n\t}\n\n\treturn ordered;\n}\n\nfunction loadRawConfig(path: string): Record | undefined {\n\tif (!existsSync(path)) return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n\t\tif (typeof parsed !== \"object\" || parsed === null) return undefined;\n\t\treturn parsed as Record;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport class KeybindingsManager extends TuiKeybindingsManager {\n\tprivate configPath: string | undefined;\n\n\tconstructor(userBindings: KeybindingsConfig = {}, configPath?: string) {\n\t\tsuper(KEYBINDINGS, userBindings);\n\t\tthis.configPath = configPath;\n\t}\n\n\tstatic create(agentDir: string = getAgentDir()): KeybindingsManager {\n\t\tconst configPath = join(agentDir, \"keybindings.json\");\n\t\tconst userBindings = KeybindingsManager.loadFromFile(configPath);\n\t\treturn new KeybindingsManager(userBindings, configPath);\n\t}\n\n\treload(): void {\n\t\tif (!this.configPath) return;\n\t\tthis.setUserBindings(KeybindingsManager.loadFromFile(this.configPath));\n\t}\n\n\tgetEffectiveConfig(): KeybindingsConfig {\n\t\treturn this.getResolvedBindings();\n\t}\n\n\tprivate static loadFromFile(path: string): KeybindingsConfig {\n\t\tconst rawConfig = loadRawConfig(path);\n\t\tif (!rawConfig) return {};\n\t\treturn toKeybindingsConfig(migrateKeybindingsConfig(rawConfig).config);\n\t}\n}\n\nexport type { Keybinding, KeyId, KeybindingsConfig };\n"]} \ No newline at end of file diff --git a/dist/core/messages.d.ts b/dist/core/messages.d.ts new file mode 100644 index 0000000..a38bc24 --- /dev/null +++ b/dist/core/messages.d.ts @@ -0,0 +1,77 @@ +/** + * Custom message types and transformers for the coding agent. + * + * Extends the base AgentMessage type with coding-agent specific message types, + * and provides a transformer to convert them to LLM-compatible messages. + */ +import type { AgentMessage } from "@earendil-works/pi-agent-core"; +import type { ImageContent, Message, TextContent } from "@earendil-works/pi-ai"; +export declare const COMPACTION_SUMMARY_PREFIX = "The conversation history before this point was compacted into the following summary:\n\n\n"; +export declare const COMPACTION_SUMMARY_SUFFIX = "\n"; +export declare const BRANCH_SUMMARY_PREFIX = "The following is a summary of a branch that this conversation came back from:\n\n\n"; +export declare const BRANCH_SUMMARY_SUFFIX = ""; +/** + * Message type for bash executions via the ! command. + */ +export interface BashExecutionMessage { + role: "bashExecution"; + command: string; + output: string; + exitCode: number | undefined; + cancelled: boolean; + truncated: boolean; + fullOutputPath?: string; + timestamp: number; + /** If true, this message is excluded from LLM context (!! prefix) */ + excludeFromContext?: boolean; +} +/** + * Message type for extension-injected messages via sendMessage(). + * These are custom messages that extensions can inject into the conversation. + */ +export interface CustomMessage { + role: "custom"; + customType: string; + content: string | (TextContent | ImageContent)[]; + display: boolean; + details?: T; + timestamp: number; +} +export interface BranchSummaryMessage { + role: "branchSummary"; + summary: string; + fromId: string; + timestamp: number; +} +export interface CompactionSummaryMessage { + role: "compactionSummary"; + summary: string; + tokensBefore: number; + timestamp: number; +} +declare module "@earendil-works/pi-agent-core" { + interface CustomAgentMessages { + bashExecution: BashExecutionMessage; + custom: CustomMessage; + branchSummary: BranchSummaryMessage; + compactionSummary: CompactionSummaryMessage; + } +} +/** + * Convert a BashExecutionMessage to user message text for LLM context. + */ +export declare function bashExecutionToText(msg: BashExecutionMessage): string; +export declare function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage; +export declare function createCompactionSummaryMessage(summary: string, tokensBefore: number, timestamp: string): CompactionSummaryMessage; +/** Convert CustomMessageEntry to AgentMessage format */ +export declare function createCustomMessage(customType: string, content: string | (TextContent | ImageContent)[], display: boolean, details: unknown | undefined, timestamp: string): CustomMessage; +/** + * Transform AgentMessages (including custom types) to LLM-compatible Messages. + * + * This is used by: + * - Agent's transormToLlm option (for prompt calls and queued messages) + * - Compaction's generateSummary (for summarization) + * - Custom extensions and tools + */ +export declare function convertToLlm(messages: AgentMessage[]): Message[]; +//# sourceMappingURL=messages.d.ts.map \ No newline at end of file diff --git a/dist/core/messages.d.ts.map b/dist/core/messages.d.ts.map new file mode 100644 index 0000000..508455b --- /dev/null +++ b/dist/core/messages.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"messages.d.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B,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;CAClB;AAGD,OAAO,QAAQ,+BAA+B,CAAC,CAAC;IAC/C,UAAU,mBAAmB;QAC5B,aAAa,EAAE,oBAAoB,CAAC;QACpC,MAAM,EAAE,aAAa,CAAC;QACtB,aAAa,EAAE,oBAAoB,CAAC;QACpC,iBAAiB,EAAE,wBAAwB,CAAC;KAC5C;CACD;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,oBAAoB,GAAG,MAAM,CAgBrE;AAED,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,oBAAoB,CAOnH;AAED,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,MAAM,GACf,wBAAwB,CAO1B;AAED,wDAAwD;AACxD,wBAAgB,mBAAmB,CAClC,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,GAAG,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,EAChD,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,OAAO,GAAG,SAAS,EAC5B,SAAS,EAAE,MAAM,GACf,aAAa,CASf;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,EAAE,CA+ChE","sourcesContent":["/**\n * Custom message types and transformers for the coding agent.\n *\n * Extends the base AgentMessage type with coding-agent specific message types,\n * and provides a transformer to convert them to LLM-compatible messages.\n */\n\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, Message, TextContent } from \"@earendil-works/pi-ai\";\n\nexport const COMPACTION_SUMMARY_PREFIX = `The conversation history before this point was compacted into the following summary:\n\n\n`;\n\nexport const COMPACTION_SUMMARY_SUFFIX = `\n`;\n\nexport const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:\n\n\n`;\n\nexport const BRANCH_SUMMARY_SUFFIX = ``;\n\n/**\n * Message type for bash executions via the ! command.\n */\nexport interface BashExecutionMessage {\n\trole: \"bashExecution\";\n\tcommand: string;\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n\ttimestamp: number;\n\t/** If true, this message is excluded from LLM context (!! prefix) */\n\texcludeFromContext?: boolean;\n}\n\n/**\n * Message type for extension-injected messages via sendMessage().\n * These are custom messages that extensions can inject into the conversation.\n */\nexport interface CustomMessage {\n\trole: \"custom\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: T;\n\ttimestamp: number;\n}\n\nexport interface BranchSummaryMessage {\n\trole: \"branchSummary\";\n\tsummary: string;\n\tfromId: string;\n\ttimestamp: number;\n}\n\nexport interface CompactionSummaryMessage {\n\trole: \"compactionSummary\";\n\tsummary: string;\n\ttokensBefore: number;\n\ttimestamp: number;\n}\n\n// Extend CustomAgentMessages via declaration merging\ndeclare module \"@earendil-works/pi-agent-core\" {\n\tinterface CustomAgentMessages {\n\t\tbashExecution: BashExecutionMessage;\n\t\tcustom: CustomMessage;\n\t\tbranchSummary: BranchSummaryMessage;\n\t\tcompactionSummary: CompactionSummaryMessage;\n\t}\n}\n\n/**\n * Convert a BashExecutionMessage to user message text for LLM context.\n */\nexport function bashExecutionToText(msg: BashExecutionMessage): string {\n\tlet text = `Ran \\`${msg.command}\\`\\n`;\n\tif (msg.output) {\n\t\ttext += `\\`\\`\\`\\n${msg.output}\\n\\`\\`\\``;\n\t} else {\n\t\ttext += \"(no output)\";\n\t}\n\tif (msg.cancelled) {\n\t\ttext += \"\\n\\n(command cancelled)\";\n\t} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {\n\t\ttext += `\\n\\nCommand exited with code ${msg.exitCode}`;\n\t}\n\tif (msg.truncated && msg.fullOutputPath) {\n\t\ttext += `\\n\\n[Output truncated. Full output: ${msg.fullOutputPath}]`;\n\t}\n\treturn text;\n}\n\nexport function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {\n\treturn {\n\t\trole: \"branchSummary\",\n\t\tsummary,\n\t\tfromId,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\nexport function createCompactionSummaryMessage(\n\tsummary: string,\n\ttokensBefore: number,\n\ttimestamp: string,\n): CompactionSummaryMessage {\n\treturn {\n\t\trole: \"compactionSummary\",\n\t\tsummary: summary,\n\t\ttokensBefore,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/** Convert CustomMessageEntry to AgentMessage format */\nexport function createCustomMessage(\n\tcustomType: string,\n\tcontent: string | (TextContent | ImageContent)[],\n\tdisplay: boolean,\n\tdetails: unknown | undefined,\n\ttimestamp: string,\n): CustomMessage {\n\treturn {\n\t\trole: \"custom\",\n\t\tcustomType,\n\t\tcontent,\n\t\tdisplay,\n\t\tdetails,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/**\n * Transform AgentMessages (including custom types) to LLM-compatible Messages.\n *\n * This is used by:\n * - Agent's transormToLlm option (for prompt calls and queued messages)\n * - Compaction's generateSummary (for summarization)\n * - Custom extensions and tools\n */\nexport function convertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages\n\t\t.map((m): Message | undefined => {\n\t\t\tswitch (m.role) {\n\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\t// Skip messages excluded from context (!! prefix)\n\t\t\t\t\tif (m.excludeFromContext) {\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: bashExecutionToText(m) }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"custom\": {\n\t\t\t\t\tconst content = typeof m.content === \"string\" ? [{ type: \"text\" as const, text: m.content }] : m.content;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{ type: \"text\" as const, text: COMPACTION_SUMMARY_PREFIX + m.summary + COMPACTION_SUMMARY_SUFFIX },\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"user\":\n\t\t\t\tcase \"assistant\":\n\t\t\t\tcase \"toolResult\":\n\t\t\t\t\treturn m;\n\t\t\t\tdefault:\n\t\t\t\t\t// biome-ignore lint/correctness/noSwitchDeclarations: fine\n\t\t\t\t\tconst _exhaustiveCheck: never = m;\n\t\t\t\t\treturn undefined;\n\t\t\t}\n\t\t})\n\t\t.filter((m) => m !== undefined);\n}\n"]} \ No newline at end of file diff --git a/dist/core/messages.js b/dist/core/messages.js new file mode 100644 index 0000000..69923d6 --- /dev/null +++ b/dist/core/messages.js @@ -0,0 +1,123 @@ +/** + * Custom message types and transformers for the coding agent. + * + * Extends the base AgentMessage type with coding-agent specific message types, + * and provides a transformer to convert them to LLM-compatible messages. + */ +export const COMPACTION_SUMMARY_PREFIX = `The conversation history before this point was compacted into the following summary: + + +`; +export const COMPACTION_SUMMARY_SUFFIX = ` +`; +export const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from: + + +`; +export const BRANCH_SUMMARY_SUFFIX = ``; +/** + * Convert a BashExecutionMessage to user message text for LLM context. + */ +export function bashExecutionToText(msg) { + let text = `Ran \`${msg.command}\`\n`; + if (msg.output) { + text += `\`\`\`\n${msg.output}\n\`\`\``; + } + else { + text += "(no output)"; + } + if (msg.cancelled) { + text += "\n\n(command cancelled)"; + } + else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) { + text += `\n\nCommand exited with code ${msg.exitCode}`; + } + if (msg.truncated && msg.fullOutputPath) { + text += `\n\n[Output truncated. Full output: ${msg.fullOutputPath}]`; + } + return text; +} +export function createBranchSummaryMessage(summary, fromId, timestamp) { + return { + role: "branchSummary", + summary, + fromId, + timestamp: new Date(timestamp).getTime(), + }; +} +export function createCompactionSummaryMessage(summary, tokensBefore, timestamp) { + return { + role: "compactionSummary", + summary: summary, + tokensBefore, + timestamp: new Date(timestamp).getTime(), + }; +} +/** Convert CustomMessageEntry to AgentMessage format */ +export function createCustomMessage(customType, content, display, details, timestamp) { + return { + role: "custom", + customType, + content, + display, + details, + timestamp: new Date(timestamp).getTime(), + }; +} +/** + * Transform AgentMessages (including custom types) to LLM-compatible Messages. + * + * This is used by: + * - Agent's transormToLlm option (for prompt calls and queued messages) + * - Compaction's generateSummary (for summarization) + * - Custom extensions and tools + */ +export function convertToLlm(messages) { + return messages + .map((m) => { + switch (m.role) { + case "bashExecution": + // Skip messages excluded from context (!! prefix) + if (m.excludeFromContext) { + return undefined; + } + return { + role: "user", + content: [{ type: "text", text: bashExecutionToText(m) }], + timestamp: m.timestamp, + }; + case "custom": { + const content = typeof m.content === "string" ? [{ type: "text", text: m.content }] : m.content; + return { + role: "user", + content, + timestamp: m.timestamp, + }; + } + case "branchSummary": + return { + role: "user", + content: [{ type: "text", text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }], + timestamp: m.timestamp, + }; + case "compactionSummary": + return { + role: "user", + content: [ + { type: "text", text: COMPACTION_SUMMARY_PREFIX + m.summary + COMPACTION_SUMMARY_SUFFIX }, + ], + timestamp: m.timestamp, + }; + case "user": + case "assistant": + case "toolResult": + return m; + default: + // biome-ignore lint/correctness/noSwitchDeclarations: fine + const _exhaustiveCheck = m; + return undefined; + } + }) + .filter((m) => m !== undefined); +} +//# sourceMappingURL=messages.js.map \ No newline at end of file diff --git a/dist/core/messages.js.map b/dist/core/messages.js.map new file mode 100644 index 0000000..8b46548 --- /dev/null +++ b/dist/core/messages.js.map @@ -0,0 +1 @@ +{"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAKH,MAAM,CAAC,MAAM,yBAAyB,GAAG;;;CAGxC,CAAC;AAEF,MAAM,CAAC,MAAM,yBAAyB,GAAG;WAC9B,CAAC;AAEZ,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;CAGpC,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG,YAAY,CAAC;AAuDlD;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,GAAyB,EAAU;IACtE,IAAI,IAAI,GAAG,SAAS,GAAG,CAAC,OAAO,MAAM,CAAC;IACtC,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;QAChB,IAAI,IAAI,WAAW,GAAG,CAAC,MAAM,UAAU,CAAC;IACzC,CAAC;SAAM,CAAC;QACP,IAAI,IAAI,aAAa,CAAC;IACvB,CAAC;IACD,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;QACnB,IAAI,IAAI,yBAAyB,CAAC;IACnC,CAAC;SAAM,IAAI,GAAG,CAAC,QAAQ,KAAK,IAAI,IAAI,GAAG,CAAC,QAAQ,KAAK,SAAS,IAAI,GAAG,CAAC,QAAQ,KAAK,CAAC,EAAE,CAAC;QACtF,IAAI,IAAI,gCAAgC,GAAG,CAAC,QAAQ,EAAE,CAAC;IACxD,CAAC;IACD,IAAI,GAAG,CAAC,SAAS,IA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message types and transformers for the coding agent.\n *\n * Extends the base AgentMessage type with coding-agent specific message types,\n * and provides a transformer to convert them to LLM-compatible messages.\n */\n\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, Message, TextContent } from \"@earendil-works/pi-ai\";\n\nexport const COMPACTION_SUMMARY_PREFIX = `The conversation history before this point was compacted into the following summary:\n\n\n`;\n\nexport const COMPACTION_SUMMARY_SUFFIX = `\n`;\n\nexport const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:\n\n\n`;\n\nexport const BRANCH_SUMMARY_SUFFIX = ``;\n\n/**\n * Message type for bash executions via the ! command.\n */\nexport interface BashExecutionMessage {\n\trole: \"bashExecution\";\n\tcommand: string;\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n\ttimestamp: number;\n\t/** If true, this message is excluded from LLM context (!! prefix) */\n\texcludeFromContext?: boolean;\n}\n\n/**\n * Message type for extension-injected messages via sendMessage().\n * These are custom messages that extensions can inject into the conversation.\n */\nexport interface CustomMessage {\n\trole: \"custom\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: T;\n\ttimestamp: number;\n}\n\nexport interface BranchSummaryMessage {\n\trole: \"branchSummary\";\n\tsummary: string;\n\tfromId: string;\n\ttimestamp: number;\n}\n\nexport interface CompactionSummaryMessage {\n\trole: \"compactionSummary\";\n\tsummary: string;\n\ttokensBefore: number;\n\ttimestamp: number;\n}\n\n// Extend CustomAgentMessages via declaration merging\ndeclare module \"@earendil-works/pi-agent-core\" {\n\tinterface CustomAgentMessages {\n\t\tbashExecution: BashExecutionMessage;\n\t\tcustom: CustomMessage;\n\t\tbranchSummary: BranchSummaryMessage;\n\t\tcompactionSummary: CompactionSummaryMessage;\n\t}\n}\n\n/**\n * Convert a BashExecutionMessage to user message text for LLM context.\n */\nexport function bashExecutionToText(msg: BashExecutionMessage): string {\n\tlet text = `Ran \\`${msg.command}\\`\\n`;\n\tif (msg.output) {\n\t\ttext += `\\`\\`\\`\\n${msg.output}\\n\\`\\`\\``;\n\t} else {\n\t\ttext += \"(no output)\";\n\t}\n\tif (msg.cancelled) {\n\t\ttext += \"\\n\\n(command cancelled)\";\n\t} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {\n\t\ttext += `\\n\\nCommand exited with code ${msg.exitCode}`;\n\t}\n\tif (msg.truncated && msg.fullOutputPath) {\n\t\ttext += `\\n\\n[Output truncated. Full output: ${msg.fullOutputPath}]`;\n\t}\n\treturn text;\n}\n\nexport function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {\n\treturn {\n\t\trole: \"branchSummary\",\n\t\tsummary,\n\t\tfromId,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\nexport function createCompactionSummaryMessage(\n\tsummary: string,\n\ttokensBefore: number,\n\ttimestamp: string,\n): CompactionSummaryMessage {\n\treturn {\n\t\trole: \"compactionSummary\",\n\t\tsummary: summary,\n\t\ttokensBefore,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/** Convert CustomMessageEntry to AgentMessage format */\nexport function createCustomMessage(\n\tcustomType: string,\n\tcontent: string | (TextContent | ImageContent)[],\n\tdisplay: boolean,\n\tdetails: unknown | undefined,\n\ttimestamp: string,\n): CustomMessage {\n\treturn {\n\t\trole: \"custom\",\n\t\tcustomType,\n\t\tcontent,\n\t\tdisplay,\n\t\tdetails,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/**\n * Transform AgentMessages (including custom types) to LLM-compatible Messages.\n *\n * This is used by:\n * - Agent's transormToLlm option (for prompt calls and queued messages)\n * - Compaction's generateSummary (for summarization)\n * - Custom extensions and tools\n */\nexport function convertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages\n\t\t.map((m): Message | undefined => {\n\t\t\tswitch (m.role) {\n\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\t// Skip messages excluded from context (!! prefix)\n\t\t\t\t\tif (m.excludeFromContext) {\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: bashExecutionToText(m) }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"custom\": {\n\t\t\t\t\tconst content = typeof m.content === \"string\" ? [{ type: \"text\" as const, text: m.content }] : m.content;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{ type: \"text\" as const, text: COMPACTION_SUMMARY_PREFIX + m.summary + COMPACTION_SUMMARY_SUFFIX },\n\t\t\t\t\t\t],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"user\":\n\t\t\t\tcase \"assistant\":\n\t\t\t\tcase \"toolResult\":\n\t\t\t\t\treturn m;\n\t\t\t\tdefault:\n\t\t\t\t\t// biome-ignore lint/correctness/noSwitchDeclarations: fine\n\t\t\t\t\tconst _exhaustiveCheck: never = m;\n\t\t\t\t\treturn undefined;\n\t\t\t}\n\t\t})\n\t\t.filter((m) => m !== undefined);\n}\n"]} \ No newline at end of file diff --git a/dist/core/model-config.d.ts b/dist/core/model-config.d.ts new file mode 100644 index 0000000..fc67bec --- /dev/null +++ b/dist/core/model-config.d.ts @@ -0,0 +1,542 @@ +/** Immutable, credential-blind models.json snapshot. */ +import { type Static, Type } from "typebox"; +declare const ModelDefinitionSchema: Type.TObject<{ + id: Type.TString; + name: Type.TOptional; + api: Type.TOptional; + baseUrl: Type.TOptional; + reasoning: Type.TOptional; + thinkingLevelMap: Type.TOptional>; + minimal: Type.TOptional>; + low: Type.TOptional>; + medium: Type.TOptional>; + high: Type.TOptional>; + xhigh: Type.TOptional>; + max: Type.TOptional>; + }>>; + input: Type.TOptional, Type.TLiteral<"image">]>>>; + cost: Type.TOptional>>; + }>>; + contextWindow: Type.TOptional; + maxTokens: Type.TOptional; + headers: Type.TOptional>; + compat: Type.TOptional; + supportsDeveloperRole: Type.TOptional; + supportsReasoningEffort: Type.TOptional; + supportsUsageInStreaming: Type.TOptional; + maxTokensField: Type.TOptional, Type.TLiteral<"max_tokens">]>>; + requiresToolResultName: Type.TOptional; + requiresAssistantAfterToolResult: Type.TOptional; + requiresThinkingAsText: Type.TOptional; + requiresReasoningContentOnAssistantMessages: Type.TOptional; + thinkingFormat: Type.TOptional, Type.TLiteral<"openrouter">, Type.TLiteral<"together">, Type.TLiteral<"deepseek">, Type.TLiteral<"zai">, Type.TLiteral<"qwen">, Type.TLiteral<"chat-template">, Type.TLiteral<"qwen-chat-template">, Type.TLiteral<"string-thinking">, Type.TLiteral<"ant-ling">]>>; + chatTemplateKwargs: Type.TOptional, Type.TObject<{ + $var: Type.TUnion<[Type.TLiteral<"thinking.enabled">, Type.TLiteral<"thinking.effort">]>; + omitWhenOff: Type.TOptional; + }>]>>>; + cacheControlFormat: Type.TOptional>; + openRouterRouting: Type.TOptional; + require_parameters: Type.TOptional; + data_collection: Type.TOptional, Type.TLiteral<"allow">]>>; + zdr: Type.TOptional; + enforce_distillable_text: Type.TOptional; + order: Type.TOptional>; + only: Type.TOptional>; + ignore: Type.TOptional>; + quantizations: Type.TOptional>; + sort: Type.TOptional; + partition: Type.TOptional>; + }>]>>; + max_price: Type.TOptional>; + completion: Type.TOptional>; + image: Type.TOptional>; + audio: Type.TOptional>; + request: Type.TOptional>; + }>>; + preferred_min_throughput: Type.TOptional; + p75: Type.TOptional; + p90: Type.TOptional; + p99: Type.TOptional; + }>]>>; + preferred_max_latency: Type.TOptional; + p75: Type.TOptional; + p90: Type.TOptional; + p99: Type.TOptional; + }>]>>; + }>>; + vercelGatewayRouting: Type.TOptional>; + order: Type.TOptional>; + }>>; + supportsOpenAIGrammarTools: Type.TOptional; + supportsStrictMode: Type.TOptional; + sendSessionAffinityHeaders: Type.TOptional; + deferredToolsMode: Type.TOptional>; + sessionAffinityFormat: Type.TOptional, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>; + supportsLongCacheRetention: Type.TOptional; + }>, Type.TObject<{ + supportsDeveloperRole: Type.TOptional; + sessionAffinityFormat: Type.TOptional, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>; + supportsLongCacheRetention: Type.TOptional; + supportsStrictMode: Type.TOptional; + supportsOpenAIGrammarTools: Type.TOptional; + supportsToolSearch: Type.TOptional; + }>, Type.TObject<{ + supportsEagerToolInputStreaming: Type.TOptional; + supportsLongCacheRetention: Type.TOptional; + sendSessionAffinityHeaders: Type.TOptional; + supportsCacheControlOnTools: Type.TOptional; + supportsTemperature: Type.TOptional; + forceAdaptiveThinking: Type.TOptional; + allowEmptySignature: Type.TOptional; + supportsStrictTools: Type.TOptional; + supportsToolReferences: Type.TOptional; + }>]>>; +}>; +declare const ModelOverrideSchema: Type.TObject<{ + name: Type.TOptional; + reasoning: Type.TOptional; + thinkingLevelMap: Type.TOptional>; + minimal: Type.TOptional>; + low: Type.TOptional>; + medium: Type.TOptional>; + high: Type.TOptional>; + xhigh: Type.TOptional>; + max: Type.TOptional>; + }>>; + input: Type.TOptional, Type.TLiteral<"image">]>>>; + cost: Type.TOptional; + output: Type.TOptional; + cacheRead: Type.TOptional; + cacheWrite: Type.TOptional; + tiers: Type.TOptional>>; + }>>; + contextWindow: Type.TOptional; + maxTokens: Type.TOptional; + headers: Type.TOptional>; + compat: Type.TOptional; + supportsDeveloperRole: Type.TOptional; + supportsReasoningEffort: Type.TOptional; + supportsUsageInStreaming: Type.TOptional; + maxTokensField: Type.TOptional, Type.TLiteral<"max_tokens">]>>; + requiresToolResultName: Type.TOptional; + requiresAssistantAfterToolResult: Type.TOptional; + requiresThinkingAsText: Type.TOptional; + requiresReasoningContentOnAssistantMessages: Type.TOptional; + thinkingFormat: Type.TOptional, Type.TLiteral<"openrouter">, Type.TLiteral<"together">, Type.TLiteral<"deepseek">, Type.TLiteral<"zai">, Type.TLiteral<"qwen">, Type.TLiteral<"chat-template">, Type.TLiteral<"qwen-chat-template">, Type.TLiteral<"string-thinking">, Type.TLiteral<"ant-ling">]>>; + chatTemplateKwargs: Type.TOptional, Type.TObject<{ + $var: Type.TUnion<[Type.TLiteral<"thinking.enabled">, Type.TLiteral<"thinking.effort">]>; + omitWhenOff: Type.TOptional; + }>]>>>; + cacheControlFormat: Type.TOptional>; + openRouterRouting: Type.TOptional; + require_parameters: Type.TOptional; + data_collection: Type.TOptional, Type.TLiteral<"allow">]>>; + zdr: Type.TOptional; + enforce_distillable_text: Type.TOptional; + order: Type.TOptional>; + only: Type.TOptional>; + ignore: Type.TOptional>; + quantizations: Type.TOptional>; + sort: Type.TOptional; + partition: Type.TOptional>; + }>]>>; + max_price: Type.TOptional>; + completion: Type.TOptional>; + image: Type.TOptional>; + audio: Type.TOptional>; + request: Type.TOptional>; + }>>; + preferred_min_throughput: Type.TOptional; + p75: Type.TOptional; + p90: Type.TOptional; + p99: Type.TOptional; + }>]>>; + preferred_max_latency: Type.TOptional; + p75: Type.TOptional; + p90: Type.TOptional; + p99: Type.TOptional; + }>]>>; + }>>; + vercelGatewayRouting: Type.TOptional>; + order: Type.TOptional>; + }>>; + supportsOpenAIGrammarTools: Type.TOptional; + supportsStrictMode: Type.TOptional; + sendSessionAffinityHeaders: Type.TOptional; + deferredToolsMode: Type.TOptional>; + sessionAffinityFormat: Type.TOptional, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>; + supportsLongCacheRetention: Type.TOptional; + }>, Type.TObject<{ + supportsDeveloperRole: Type.TOptional; + sessionAffinityFormat: Type.TOptional, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>; + supportsLongCacheRetention: Type.TOptional; + supportsStrictMode: Type.TOptional; + supportsOpenAIGrammarTools: Type.TOptional; + supportsToolSearch: Type.TOptional; + }>, Type.TObject<{ + supportsEagerToolInputStreaming: Type.TOptional; + supportsLongCacheRetention: Type.TOptional; + sendSessionAffinityHeaders: Type.TOptional; + supportsCacheControlOnTools: Type.TOptional; + supportsTemperature: Type.TOptional; + forceAdaptiveThinking: Type.TOptional; + allowEmptySignature: Type.TOptional; + supportsStrictTools: Type.TOptional; + supportsToolReferences: Type.TOptional; + }>]>>; +}>; +declare const ProviderConfigSchema: Type.TObject<{ + name: Type.TOptional; + baseUrl: Type.TOptional; + apiKey: Type.TOptional; + api: Type.TOptional; + oauth: Type.TOptional>; + headers: Type.TOptional>; + compat: Type.TOptional; + supportsDeveloperRole: Type.TOptional; + supportsReasoningEffort: Type.TOptional; + supportsUsageInStreaming: Type.TOptional; + maxTokensField: Type.TOptional, Type.TLiteral<"max_tokens">]>>; + requiresToolResultName: Type.TOptional; + requiresAssistantAfterToolResult: Type.TOptional; + requiresThinkingAsText: Type.TOptional; + requiresReasoningContentOnAssistantMessages: Type.TOptional; + thinkingFormat: Type.TOptional, Type.TLiteral<"openrouter">, Type.TLiteral<"together">, Type.TLiteral<"deepseek">, Type.TLiteral<"zai">, Type.TLiteral<"qwen">, Type.TLiteral<"chat-template">, Type.TLiteral<"qwen-chat-template">, Type.TLiteral<"string-thinking">, Type.TLiteral<"ant-ling">]>>; + chatTemplateKwargs: Type.TOptional, Type.TObject<{ + $var: Type.TUnion<[Type.TLiteral<"thinking.enabled">, Type.TLiteral<"thinking.effort">]>; + omitWhenOff: Type.TOptional; + }>]>>>; + cacheControlFormat: Type.TOptional>; + openRouterRouting: Type.TOptional; + require_parameters: Type.TOptional; + data_collection: Type.TOptional, Type.TLiteral<"allow">]>>; + zdr: Type.TOptional; + enforce_distillable_text: Type.TOptional; + order: Type.TOptional>; + only: Type.TOptional>; + ignore: Type.TOptional>; + quantizations: Type.TOptional>; + sort: Type.TOptional; + partition: Type.TOptional>; + }>]>>; + max_price: Type.TOptional>; + completion: Type.TOptional>; + image: Type.TOptional>; + audio: Type.TOptional>; + request: Type.TOptional>; + }>>; + preferred_min_throughput: Type.TOptional; + p75: Type.TOptional; + p90: Type.TOptional; + p99: Type.TOptional; + }>]>>; + preferred_max_latency: Type.TOptional; + p75: Type.TOptional; + p90: Type.TOptional; + p99: Type.TOptional; + }>]>>; + }>>; + vercelGatewayRouting: Type.TOptional>; + order: Type.TOptional>; + }>>; + supportsOpenAIGrammarTools: Type.TOptional; + supportsStrictMode: Type.TOptional; + sendSessionAffinityHeaders: Type.TOptional; + deferredToolsMode: Type.TOptional>; + sessionAffinityFormat: Type.TOptional, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>; + supportsLongCacheRetention: Type.TOptional; + }>, Type.TObject<{ + supportsDeveloperRole: Type.TOptional; + sessionAffinityFormat: Type.TOptional, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>; + supportsLongCacheRetention: Type.TOptional; + supportsStrictMode: Type.TOptional; + supportsOpenAIGrammarTools: Type.TOptional; + supportsToolSearch: Type.TOptional; + }>, Type.TObject<{ + supportsEagerToolInputStreaming: Type.TOptional; + supportsLongCacheRetention: Type.TOptional; + sendSessionAffinityHeaders: Type.TOptional; + supportsCacheControlOnTools: Type.TOptional; + supportsTemperature: Type.TOptional; + forceAdaptiveThinking: Type.TOptional; + allowEmptySignature: Type.TOptional; + supportsStrictTools: Type.TOptional; + supportsToolReferences: Type.TOptional; + }>]>>; + authHeader: Type.TOptional; + models: Type.TOptional; + api: Type.TOptional; + baseUrl: Type.TOptional; + reasoning: Type.TOptional; + thinkingLevelMap: Type.TOptional>; + minimal: Type.TOptional>; + low: Type.TOptional>; + medium: Type.TOptional>; + high: Type.TOptional>; + xhigh: Type.TOptional>; + max: Type.TOptional>; + }>>; + input: Type.TOptional, Type.TLiteral<"image">]>>>; + cost: Type.TOptional>>; + }>>; + contextWindow: Type.TOptional; + maxTokens: Type.TOptional; + headers: Type.TOptional>; + compat: Type.TOptional; + supportsDeveloperRole: Type.TOptional; + supportsReasoningEffort: Type.TOptional; + supportsUsageInStreaming: Type.TOptional; + maxTokensField: Type.TOptional, Type.TLiteral<"max_tokens">]>>; + requiresToolResultName: Type.TOptional; + requiresAssistantAfterToolResult: Type.TOptional; + requiresThinkingAsText: Type.TOptional; + requiresReasoningContentOnAssistantMessages: Type.TOptional; + thinkingFormat: Type.TOptional, Type.TLiteral<"openrouter">, Type.TLiteral<"together">, Type.TLiteral<"deepseek">, Type.TLiteral<"zai">, Type.TLiteral<"qwen">, Type.TLiteral<"chat-template">, Type.TLiteral<"qwen-chat-template">, Type.TLiteral<"string-thinking">, Type.TLiteral<"ant-ling">]>>; + chatTemplateKwargs: Type.TOptional, Type.TObject<{ + $var: Type.TUnion<[Type.TLiteral<"thinking.enabled">, Type.TLiteral<"thinking.effort">]>; + omitWhenOff: Type.TOptional; + }>]>>>; + cacheControlFormat: Type.TOptional>; + openRouterRouting: Type.TOptional; + require_parameters: Type.TOptional; + data_collection: Type.TOptional, Type.TLiteral<"allow">]>>; + zdr: Type.TOptional; + enforce_distillable_text: Type.TOptional; + order: Type.TOptional>; + only: Type.TOptional>; + ignore: Type.TOptional>; + quantizations: Type.TOptional>; + sort: Type.TOptional; + partition: Type.TOptional>; + }>]>>; + max_price: Type.TOptional>; + completion: Type.TOptional>; + image: Type.TOptional>; + audio: Type.TOptional>; + request: Type.TOptional>; + }>>; + preferred_min_throughput: Type.TOptional; + p75: Type.TOptional; + p90: Type.TOptional; + p99: Type.TOptional; + }>]>>; + preferred_max_latency: Type.TOptional; + p75: Type.TOptional; + p90: Type.TOptional; + p99: Type.TOptional; + }>]>>; + }>>; + vercelGatewayRouting: Type.TOptional>; + order: Type.TOptional>; + }>>; + supportsOpenAIGrammarTools: Type.TOptional; + supportsStrictMode: Type.TOptional; + sendSessionAffinityHeaders: Type.TOptional; + deferredToolsMode: Type.TOptional>; + sessionAffinityFormat: Type.TOptional, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>; + supportsLongCacheRetention: Type.TOptional; + }>, Type.TObject<{ + supportsDeveloperRole: Type.TOptional; + sessionAffinityFormat: Type.TOptional, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>; + supportsLongCacheRetention: Type.TOptional; + supportsStrictMode: Type.TOptional; + supportsOpenAIGrammarTools: Type.TOptional; + supportsToolSearch: Type.TOptional; + }>, Type.TObject<{ + supportsEagerToolInputStreaming: Type.TOptional; + supportsLongCacheRetention: Type.TOptional; + sendSessionAffinityHeaders: Type.TOptional; + supportsCacheControlOnTools: Type.TOptional; + supportsTemperature: Type.TOptional; + forceAdaptiveThinking: Type.TOptional; + allowEmptySignature: Type.TOptional; + supportsStrictTools: Type.TOptional; + supportsToolReferences: Type.TOptional; + }>]>>; + }>>>; + modelOverrides: Type.TOptional; + reasoning: Type.TOptional; + thinkingLevelMap: Type.TOptional>; + minimal: Type.TOptional>; + low: Type.TOptional>; + medium: Type.TOptional>; + high: Type.TOptional>; + xhigh: Type.TOptional>; + max: Type.TOptional>; + }>>; + input: Type.TOptional, Type.TLiteral<"image">]>>>; + cost: Type.TOptional; + output: Type.TOptional; + cacheRead: Type.TOptional; + cacheWrite: Type.TOptional; + tiers: Type.TOptional>>; + }>>; + contextWindow: Type.TOptional; + maxTokens: Type.TOptional; + headers: Type.TOptional>; + compat: Type.TOptional; + supportsDeveloperRole: Type.TOptional; + supportsReasoningEffort: Type.TOptional; + supportsUsageInStreaming: Type.TOptional; + maxTokensField: Type.TOptional, Type.TLiteral<"max_tokens">]>>; + requiresToolResultName: Type.TOptional; + requiresAssistantAfterToolResult: Type.TOptional; + requiresThinkingAsText: Type.TOptional; + requiresReasoningContentOnAssistantMessages: Type.TOptional; + thinkingFormat: Type.TOptional, Type.TLiteral<"openrouter">, Type.TLiteral<"together">, Type.TLiteral<"deepseek">, Type.TLiteral<"zai">, Type.TLiteral<"qwen">, Type.TLiteral<"chat-template">, Type.TLiteral<"qwen-chat-template">, Type.TLiteral<"string-thinking">, Type.TLiteral<"ant-ling">]>>; + chatTemplateKwargs: Type.TOptional, Type.TObject<{ + $var: Type.TUnion<[Type.TLiteral<"thinking.enabled">, Type.TLiteral<"thinking.effort">]>; + omitWhenOff: Type.TOptional; + }>]>>>; + cacheControlFormat: Type.TOptional>; + openRouterRouting: Type.TOptional; + require_parameters: Type.TOptional; + data_collection: Type.TOptional, Type.TLiteral<"allow">]>>; + zdr: Type.TOptional; + enforce_distillable_text: Type.TOptional; + order: Type.TOptional>; + only: Type.TOptional>; + ignore: Type.TOptional>; + quantizations: Type.TOptional>; + sort: Type.TOptional; + partition: Type.TOptional>; + }>]>>; + max_price: Type.TOptional>; + completion: Type.TOptional>; + image: Type.TOptional>; + audio: Type.TOptional>; + request: Type.TOptional>; + }>>; + preferred_min_throughput: Type.TOptional; + p75: Type.TOptional; + p90: Type.TOptional; + p99: Type.TOptional; + }>]>>; + preferred_max_latency: Type.TOptional; + p75: Type.TOptional; + p90: Type.TOptional; + p99: Type.TOptional; + }>]>>; + }>>; + vercelGatewayRouting: Type.TOptional>; + order: Type.TOptional>; + }>>; + supportsOpenAIGrammarTools: Type.TOptional; + supportsStrictMode: Type.TOptional; + sendSessionAffinityHeaders: Type.TOptional; + deferredToolsMode: Type.TOptional>; + sessionAffinityFormat: Type.TOptional, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>; + supportsLongCacheRetention: Type.TOptional; + }>, Type.TObject<{ + supportsDeveloperRole: Type.TOptional; + sessionAffinityFormat: Type.TOptional, Type.TLiteral<"openai-nosession">, Type.TLiteral<"openrouter">]>>; + supportsLongCacheRetention: Type.TOptional; + supportsStrictMode: Type.TOptional; + supportsOpenAIGrammarTools: Type.TOptional; + supportsToolSearch: Type.TOptional; + }>, Type.TObject<{ + supportsEagerToolInputStreaming: Type.TOptional; + supportsLongCacheRetention: Type.TOptional; + sendSessionAffinityHeaders: Type.TOptional; + supportsCacheControlOnTools: Type.TOptional; + supportsTemperature: Type.TOptional; + forceAdaptiveThinking: Type.TOptional; + allowEmptySignature: Type.TOptional; + supportsStrictTools: Type.TOptional; + supportsToolReferences: Type.TOptional; + }>]>>; + }>>>; +}>; +export type ModelsJsonModel = Static; +export type ModelsJsonModelOverride = Static; +export type ModelsJsonProvider = Static; +/** One immutable load of models.json. */ +export declare class ModelConfig { + private readonly providers; + private readonly error; + private constructor(); + static load(modelsJsonPath: string | undefined): Promise; + getProvider(providerId: string): ModelsJsonProvider | undefined; + getProviderIds(): readonly string[]; + getError(): string | undefined; +} +export {}; +//# sourceMappingURL=model-config.d.ts.map \ No newline at end of file diff --git a/dist/core/model-config.d.ts.map b/dist/core/model-config.d.ts.map new file mode 100644 index 0000000..45a9efc --- /dev/null +++ b/dist/core/model-config.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"model-config.d.ts","sourceRoot":"","sources":["../../src/core/model-config.ts"],"names":[],"mappings":"AAAA,wDAAwD;AAGxD,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAsJ5C,QAAA,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAazB,CAAC;AAEH,QAAA,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAkBvB,CAAC;AAEH,QAAA,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWxB,CAAC;AAOH,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,OAAO,qBAAqB,CAAC,CAAC;AACnE,MAAM,MAAM,uBAAuB,GAAG,MAAM,CAAC,OAAO,mBAAmB,CAAC,CAAC;AACzE,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAsBrE,yCAAyC;AACzC,qBAAa,WAAW;IACvB,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA0C;IACpE,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAqB;IAE3C,OAAO,eAGN;IAED,OAAa,IAAI,CAAC,cAAc,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,WAAW,CAAC,CAuC1E;IAED,WAAW,CAAC,UAAU,EAAE,MAAM,GAAG,kBAAkB,GAAG,SAAS,CAE9D;IAED,cAAc,IAAI,SAAS,MAAM,EAAE,CAElC;IAED,QAAQ,IAAI,MAAM,GAAG,SAAS,CAE7B;CACD","sourcesContent":["/** Immutable, credential-blind models.json snapshot. */\n\nimport { readFile } from \"node:fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { Compile } from \"typebox/compile\";\nimport type { TLocalizedValidationError } from \"typebox/error\";\nimport { stripJsonComments } from \"../utils/json.ts\";\nimport { normalizePath } from \"../utils/paths.ts\";\n\nconst PercentileCutoffsSchema = Type.Object({\n\tp50: Type.Optional(Type.Number()),\n\tp75: Type.Optional(Type.Number()),\n\tp90: Type.Optional(Type.Number()),\n\tp99: Type.Optional(Type.Number()),\n});\n\nconst OpenRouterRoutingSchema = Type.Object({\n\tallow_fallbacks: Type.Optional(Type.Boolean()),\n\trequire_parameters: Type.Optional(Type.Boolean()),\n\tdata_collection: Type.Optional(Type.Union([Type.Literal(\"deny\"), Type.Literal(\"allow\")])),\n\tzdr: Type.Optional(Type.Boolean()),\n\tenforce_distillable_text: Type.Optional(Type.Boolean()),\n\torder: Type.Optional(Type.Array(Type.String())),\n\tonly: Type.Optional(Type.Array(Type.String())),\n\tignore: Type.Optional(Type.Array(Type.String())),\n\tquantizations: Type.Optional(Type.Array(Type.String())),\n\tsort: Type.Optional(\n\t\tType.Union([\n\t\t\tType.String(),\n\t\t\tType.Object({\n\t\t\t\tby: Type.Optional(Type.String()),\n\t\t\t\tpartition: Type.Optional(Type.Union([Type.String(), Type.Null()])),\n\t\t\t}),\n\t\t]),\n\t),\n\tmax_price: Type.Optional(\n\t\tType.Object({\n\t\t\tprompt: Type.Optional(Type.Union([Type.Number(), Type.String()])),\n\t\t\tcompletion: Type.Optional(Type.Union([Type.Number(), Type.String()])),\n\t\t\timage: Type.Optional(Type.Union([Type.Number(), Type.String()])),\n\t\t\taudio: Type.Optional(Type.Union([Type.Number(), Type.String()])),\n\t\t\trequest: Type.Optional(Type.Union([Type.Number(), Type.String()])),\n\t\t}),\n\t),\n\tpreferred_min_throughput: Type.Optional(Type.Union([Type.Number(), PercentileCutoffsSchema])),\n\tpreferred_max_latency: Type.Optional(Type.Union([Type.Number(), PercentileCutoffsSchema])),\n});\n\nconst VercelGatewayRoutingSchema = Type.Object({\n\tonly: Type.Optional(Type.Array(Type.String())),\n\torder: Type.Optional(Type.Array(Type.String())),\n});\n\nconst ThinkingLevelMapValueSchema = Type.Union([Type.String(), Type.Null()]);\nconst ThinkingLevelMapSchema = Type.Object({\n\toff: Type.Optional(ThinkingLevelMapValueSchema),\n\tminimal: Type.Optional(ThinkingLevelMapValueSchema),\n\tlow: Type.Optional(ThinkingLevelMapValueSchema),\n\tmedium: Type.Optional(ThinkingLevelMapValueSchema),\n\thigh: Type.Optional(ThinkingLevelMapValueSchema),\n\txhigh: Type.Optional(ThinkingLevelMapValueSchema),\n\tmax: Type.Optional(ThinkingLevelMapValueSchema),\n});\n\nconst ChatTemplateKwargScalarSchema = Type.Union([Type.String(), Type.Number(), Type.Boolean(), Type.Null()]);\nconst ChatTemplateKwargVariableSchema = Type.Object({\n\t$var: Type.Union([Type.Literal(\"thinking.enabled\"), Type.Literal(\"thinking.effort\")]),\n\tomitWhenOff: Type.Optional(Type.Boolean()),\n});\nconst ChatTemplateKwargSchema = Type.Union([ChatTemplateKwargScalarSchema, ChatTemplateKwargVariableSchema]);\n\nconst OpenAICompletionsCompatSchema = Type.Object({\n\tsupportsStore: Type.Optional(Type.Boolean()),\n\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\tsupportsReasoningEffort: Type.Optional(Type.Boolean()),\n\tsupportsUsageInStreaming: Type.Optional(Type.Boolean()),\n\tmaxTokensField: Type.Optional(Type.Union([Type.Literal(\"max_completion_tokens\"), Type.Literal(\"max_tokens\")])),\n\trequiresToolResultName: Type.Optional(Type.Boolean()),\n\trequiresAssistantAfterToolResult: Type.Optional(Type.Boolean()),\n\trequiresThinkingAsText: Type.Optional(Type.Boolean()),\n\trequiresReasoningContentOnAssistantMessages: Type.Optional(Type.Boolean()),\n\tthinkingFormat: Type.Optional(\n\t\tType.Union([\n\t\t\tType.Literal(\"openai\"),\n\t\t\tType.Literal(\"openrouter\"),\n\t\t\tType.Literal(\"together\"),\n\t\t\tType.Literal(\"deepseek\"),\n\t\t\tType.Literal(\"zai\"),\n\t\t\tType.Literal(\"qwen\"),\n\t\t\tType.Literal(\"chat-template\"),\n\t\t\tType.Literal(\"qwen-chat-template\"),\n\t\t\tType.Literal(\"string-thinking\"),\n\t\t\tType.Literal(\"ant-ling\"),\n\t\t]),\n\t),\n\tchatTemplateKwargs: Type.Optional(Type.Record(Type.String(), ChatTemplateKwargSchema)),\n\tcacheControlFormat: Type.Optional(Type.Literal(\"anthropic\")),\n\topenRouterRouting: Type.Optional(OpenRouterRoutingSchema),\n\tvercelGatewayRouting: Type.Optional(VercelGatewayRoutingSchema),\n\tsupportsOpenAIGrammarTools: Type.Optional(Type.Boolean()),\n\tsupportsStrictMode: Type.Optional(Type.Boolean()),\n\tsendSessionAffinityHeaders: Type.Optional(Type.Boolean()),\n\tdeferredToolsMode: Type.Optional(Type.Literal(\"kimi\")),\n\tsessionAffinityFormat: Type.Optional(\n\t\tType.Union([Type.Literal(\"openai\"), Type.Literal(\"openai-nosession\"), Type.Literal(\"openrouter\")]),\n\t),\n\tsupportsLongCacheRetention: Type.Optional(Type.Boolean()),\n});\n\nconst OpenAIResponsesCompatSchema = Type.Object({\n\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\tsessionAffinityFormat: Type.Optional(\n\t\tType.Union([Type.Literal(\"openai\"), Type.Literal(\"openai-nosession\"), Type.Literal(\"openrouter\")]),\n\t),\n\tsupportsLongCacheRetention: Type.Optional(Type.Boolean()),\n\tsupportsStrictMode: Type.Optional(Type.Boolean()),\n\tsupportsOpenAIGrammarTools: Type.Optional(Type.Boolean()),\n\tsupportsToolSearch: Type.Optional(Type.Boolean()),\n});\n\nconst AnthropicMessagesCompatSchema = Type.Object({\n\tsupportsEagerToolInputStreaming: Type.Optional(Type.Boolean()),\n\tsupportsLongCacheRetention: Type.Optional(Type.Boolean()),\n\tsendSessionAffinityHeaders: Type.Optional(Type.Boolean()),\n\tsupportsCacheControlOnTools: Type.Optional(Type.Boolean()),\n\tsupportsTemperature: Type.Optional(Type.Boolean()),\n\tforceAdaptiveThinking: Type.Optional(Type.Boolean()),\n\tallowEmptySignature: Type.Optional(Type.Boolean()),\n\tsupportsStrictTools: Type.Optional(Type.Boolean()),\n\tsupportsToolReferences: Type.Optional(Type.Boolean()),\n});\n\nconst ProviderCompatSchema = Type.Union([\n\tOpenAICompletionsCompatSchema,\n\tOpenAIResponsesCompatSchema,\n\tAnthropicMessagesCompatSchema,\n]);\n\nconst ModelCostRatesSchema = {\n\tinput: Type.Number(),\n\toutput: Type.Number(),\n\tcacheRead: Type.Number(),\n\tcacheWrite: Type.Number(),\n};\nconst ModelCostTierSchema = Type.Object({\n\tinputTokensAbove: Type.Number(),\n\t...ModelCostRatesSchema,\n});\nconst ModelCostSchema = Type.Object({\n\t...ModelCostRatesSchema,\n\ttiers: Type.Optional(Type.Array(ModelCostTierSchema)),\n});\n\nconst ModelDefinitionSchema = Type.Object({\n\tid: Type.String({ minLength: 1 }),\n\tname: Type.Optional(Type.String({ minLength: 1 })),\n\tapi: Type.Optional(Type.String({ minLength: 1 })),\n\tbaseUrl: Type.Optional(Type.String({ minLength: 1 })),\n\treasoning: Type.Optional(Type.Boolean()),\n\tthinkingLevelMap: Type.Optional(ThinkingLevelMapSchema),\n\tinput: Type.Optional(Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")]))),\n\tcost: Type.Optional(ModelCostSchema),\n\tcontextWindow: Type.Optional(Type.Number()),\n\tmaxTokens: Type.Optional(Type.Number()),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tcompat: Type.Optional(ProviderCompatSchema),\n});\n\nconst ModelOverrideSchema = Type.Object({\n\tname: Type.Optional(Type.String({ minLength: 1 })),\n\treasoning: Type.Optional(Type.Boolean()),\n\tthinkingLevelMap: Type.Optional(ThinkingLevelMapSchema),\n\tinput: Type.Optional(Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")]))),\n\tcost: Type.Optional(\n\t\tType.Object({\n\t\t\tinput: Type.Optional(Type.Number()),\n\t\t\toutput: Type.Optional(Type.Number()),\n\t\t\tcacheRead: Type.Optional(Type.Number()),\n\t\t\tcacheWrite: Type.Optional(Type.Number()),\n\t\t\ttiers: Type.Optional(Type.Array(ModelCostTierSchema)),\n\t\t}),\n\t),\n\tcontextWindow: Type.Optional(Type.Number()),\n\tmaxTokens: Type.Optional(Type.Number()),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tcompat: Type.Optional(ProviderCompatSchema),\n});\n\nconst ProviderConfigSchema = Type.Object({\n\tname: Type.Optional(Type.String({ minLength: 1 })),\n\tbaseUrl: Type.Optional(Type.String({ minLength: 1 })),\n\tapiKey: Type.Optional(Type.String({ minLength: 1 })),\n\tapi: Type.Optional(Type.String({ minLength: 1 })),\n\toauth: Type.Optional(Type.Literal(\"radius\")),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tcompat: Type.Optional(ProviderCompatSchema),\n\tauthHeader: Type.Optional(Type.Boolean()),\n\tmodels: Type.Optional(Type.Array(ModelDefinitionSchema)),\n\tmodelOverrides: Type.Optional(Type.Record(Type.String(), ModelOverrideSchema)),\n});\n\nconst ModelsConfigSchema = Type.Object({\n\tproviders: Type.Record(Type.String(), ProviderConfigSchema),\n});\nconst validateModelsConfig = Compile(ModelsConfigSchema);\n\nexport type ModelsJsonModel = Static;\nexport type ModelsJsonModelOverride = Static;\nexport type ModelsJsonProvider = Static;\ntype ModelsJson = Static;\n\nfunction formatValidationPath(error: TLocalizedValidationError): string {\n\tif (error.keyword === \"required\") {\n\t\tconst requiredProperties = (error.params as { requiredProperties?: string[] }).requiredProperties;\n\t\tconst requiredProperty = requiredProperties?.[0];\n\t\tif (requiredProperty) {\n\t\t\tconst basePath = error.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\");\n\t\t\treturn basePath ? `${basePath}.${requiredProperty}` : requiredProperty;\n\t\t}\n\t}\n\tconst path = error.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\");\n\treturn path || \"root\";\n}\n\nfunction deepFreeze(value: T): T {\n\tif (typeof value !== \"object\" || value === null || Object.isFrozen(value)) return value;\n\tfor (const child of Object.values(value)) deepFreeze(child);\n\treturn Object.freeze(value);\n}\n\n/** One immutable load of models.json. */\nexport class ModelConfig {\n\tprivate readonly providers: ReadonlyMap;\n\tprivate readonly error: string | undefined;\n\n\tprivate constructor(providers: ReadonlyMap, error?: string) {\n\t\tthis.providers = providers;\n\t\tthis.error = error;\n\t}\n\n\tstatic async load(modelsJsonPath: string | undefined): Promise {\n\t\tif (!modelsJsonPath) return new ModelConfig(new Map());\n\t\tconst path = normalizePath(modelsJsonPath);\n\t\tlet content: string;\n\t\ttry {\n\t\t\tcontent = await readFile(path, \"utf-8\");\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return new ModelConfig(new Map());\n\t\t\treturn new ModelConfig(\n\t\t\t\tnew Map(),\n\t\t\t\t`Failed to load models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${path}`,\n\t\t\t);\n\t\t}\n\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(stripJsonComments(content));\n\t\t} catch (error) {\n\t\t\treturn new ModelConfig(\n\t\t\t\tnew Map(),\n\t\t\t\t`Failed to parse models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${path}`,\n\t\t\t);\n\t\t}\n\n\t\tif (!validateModelsConfig.Check(parsed)) {\n\t\t\tconst errors =\n\t\t\t\tvalidateModelsConfig\n\t\t\t\t\t.Errors(parsed)\n\t\t\t\t\t.map((error) => ` - ${formatValidationPath(error)}: ${error.message}`)\n\t\t\t\t\t.join(\"\\n\") || \"Unknown schema error\";\n\t\t\treturn new ModelConfig(new Map(), `Invalid models.json schema:\\n${errors}\\n\\nFile: ${path}`);\n\t\t}\n\n\t\tconst config = parsed as ModelsJson;\n\t\tconst providers = new Map();\n\t\tfor (const [providerId, provider] of Object.entries(config.providers)) {\n\t\t\tproviders.set(providerId, deepFreeze(structuredClone(provider)));\n\t\t}\n\t\treturn new ModelConfig(providers);\n\t}\n\n\tgetProvider(providerId: string): ModelsJsonProvider | undefined {\n\t\treturn this.providers.get(providerId);\n\t}\n\n\tgetProviderIds(): readonly string[] {\n\t\treturn [...this.providers.keys()];\n\t}\n\n\tgetError(): string | undefined {\n\t\treturn this.error;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/model-config.js b/dist/core/model-config.js new file mode 100644 index 0000000..78c7343 --- /dev/null +++ b/dist/core/model-config.js @@ -0,0 +1,249 @@ +/** Immutable, credential-blind models.json snapshot. */ +import { readFile } from "node:fs/promises"; +import { Type } from "typebox"; +import { Compile } from "typebox/compile"; +import { stripJsonComments } from "../utils/json.js"; +import { normalizePath } from "../utils/paths.js"; +const PercentileCutoffsSchema = Type.Object({ + p50: Type.Optional(Type.Number()), + p75: Type.Optional(Type.Number()), + p90: Type.Optional(Type.Number()), + p99: Type.Optional(Type.Number()), +}); +const OpenRouterRoutingSchema = Type.Object({ + allow_fallbacks: Type.Optional(Type.Boolean()), + require_parameters: Type.Optional(Type.Boolean()), + data_collection: Type.Optional(Type.Union([Type.Literal("deny"), Type.Literal("allow")])), + zdr: Type.Optional(Type.Boolean()), + enforce_distillable_text: Type.Optional(Type.Boolean()), + order: Type.Optional(Type.Array(Type.String())), + only: Type.Optional(Type.Array(Type.String())), + ignore: Type.Optional(Type.Array(Type.String())), + quantizations: Type.Optional(Type.Array(Type.String())), + sort: Type.Optional(Type.Union([ + Type.String(), + Type.Object({ + by: Type.Optional(Type.String()), + partition: Type.Optional(Type.Union([Type.String(), Type.Null()])), + }), + ])), + max_price: Type.Optional(Type.Object({ + prompt: Type.Optional(Type.Union([Type.Number(), Type.String()])), + completion: Type.Optional(Type.Union([Type.Number(), Type.String()])), + image: Type.Optional(Type.Union([Type.Number(), Type.String()])), + audio: Type.Optional(Type.Union([Type.Number(), Type.String()])), + request: Type.Optional(Type.Union([Type.Number(), Type.String()])), + })), + preferred_min_throughput: Type.Optional(Type.Union([Type.Number(), PercentileCutoffsSchema])), + preferred_max_latency: Type.Optional(Type.Union([Type.Number(), PercentileCutoffsSchema])), +}); +const VercelGatewayRoutingSchema = Type.Object({ + only: Type.Optional(Type.Array(Type.String())), + order: Type.Optional(Type.Array(Type.String())), +}); +const ThinkingLevelMapValueSchema = Type.Union([Type.String(), Type.Null()]); +const ThinkingLevelMapSchema = Type.Object({ + off: Type.Optional(ThinkingLevelMapValueSchema), + minimal: Type.Optional(ThinkingLevelMapValueSchema), + low: Type.Optional(ThinkingLevelMapValueSchema), + medium: Type.Optional(ThinkingLevelMapValueSchema), + high: Type.Optional(ThinkingLevelMapValueSchema), + xhigh: Type.Optional(ThinkingLevelMapValueSchema), + max: Type.Optional(ThinkingLevelMapValueSchema), +}); +const ChatTemplateKwargScalarSchema = Type.Union([Type.String(), Type.Number(), Type.Boolean(), Type.Null()]); +const ChatTemplateKwargVariableSchema = Type.Object({ + $var: Type.Union([Type.Literal("thinking.enabled"), Type.Literal("thinking.effort")]), + omitWhenOff: Type.Optional(Type.Boolean()), +}); +const ChatTemplateKwargSchema = Type.Union([ChatTemplateKwargScalarSchema, ChatTemplateKwargVariableSchema]); +const OpenAICompletionsCompatSchema = Type.Object({ + supportsStore: Type.Optional(Type.Boolean()), + supportsDeveloperRole: Type.Optional(Type.Boolean()), + supportsReasoningEffort: Type.Optional(Type.Boolean()), + supportsUsageInStreaming: Type.Optional(Type.Boolean()), + maxTokensField: Type.Optional(Type.Union([Type.Literal("max_completion_tokens"), Type.Literal("max_tokens")])), + requiresToolResultName: Type.Optional(Type.Boolean()), + requiresAssistantAfterToolResult: Type.Optional(Type.Boolean()), + requiresThinkingAsText: Type.Optional(Type.Boolean()), + requiresReasoningContentOnAssistantMessages: Type.Optional(Type.Boolean()), + thinkingFormat: Type.Optional(Type.Union([ + Type.Literal("openai"), + Type.Literal("openrouter"), + Type.Literal("together"), + Type.Literal("deepseek"), + Type.Literal("zai"), + Type.Literal("qwen"), + Type.Literal("chat-template"), + Type.Literal("qwen-chat-template"), + Type.Literal("string-thinking"), + Type.Literal("ant-ling"), + ])), + chatTemplateKwargs: Type.Optional(Type.Record(Type.String(), ChatTemplateKwargSchema)), + cacheControlFormat: Type.Optional(Type.Literal("anthropic")), + openRouterRouting: Type.Optional(OpenRouterRoutingSchema), + vercelGatewayRouting: Type.Optional(VercelGatewayRoutingSchema), + supportsOpenAIGrammarTools: Type.Optional(Type.Boolean()), + supportsStrictMode: Type.Optional(Type.Boolean()), + sendSessionAffinityHeaders: Type.Optional(Type.Boolean()), + deferredToolsMode: Type.Optional(Type.Literal("kimi")), + sessionAffinityFormat: Type.Optional(Type.Union([Type.Literal("openai"), Type.Literal("openai-nosession"), Type.Literal("openrouter")])), + supportsLongCacheRetention: Type.Optional(Type.Boolean()), +}); +const OpenAIResponsesCompatSchema = Type.Object({ + supportsDeveloperRole: Type.Optional(Type.Boolean()), + sessionAffinityFormat: Type.Optional(Type.Union([Type.Literal("openai"), Type.Literal("openai-nosession"), Type.Literal("openrouter")])), + supportsLongCacheRetention: Type.Optional(Type.Boolean()), + supportsStrictMode: Type.Optional(Type.Boolean()), + supportsOpenAIGrammarTools: Type.Optional(Type.Boolean()), + supportsToolSearch: Type.Optional(Type.Boolean()), +}); +const AnthropicMessagesCompatSchema = Type.Object({ + supportsEagerToolInputStreaming: Type.Optional(Type.Boolean()), + supportsLongCacheRetention: Type.Optional(Type.Boolean()), + sendSessionAffinityHeaders: Type.Optional(Type.Boolean()), + supportsCacheControlOnTools: Type.Optional(Type.Boolean()), + supportsTemperature: Type.Optional(Type.Boolean()), + forceAdaptiveThinking: Type.Optional(Type.Boolean()), + allowEmptySignature: Type.Optional(Type.Boolean()), + supportsStrictTools: Type.Optional(Type.Boolean()), + supportsToolReferences: Type.Optional(Type.Boolean()), +}); +const ProviderCompatSchema = Type.Union([ + OpenAICompletionsCompatSchema, + OpenAIResponsesCompatSchema, + AnthropicMessagesCompatSchema, +]); +const ModelCostRatesSchema = { + input: Type.Number(), + output: Type.Number(), + cacheRead: Type.Number(), + cacheWrite: Type.Number(), +}; +const ModelCostTierSchema = Type.Object({ + inputTokensAbove: Type.Number(), + ...ModelCostRatesSchema, +}); +const ModelCostSchema = Type.Object({ + ...ModelCostRatesSchema, + tiers: Type.Optional(Type.Array(ModelCostTierSchema)), +}); +const ModelDefinitionSchema = Type.Object({ + id: Type.String({ minLength: 1 }), + name: Type.Optional(Type.String({ minLength: 1 })), + api: Type.Optional(Type.String({ minLength: 1 })), + baseUrl: Type.Optional(Type.String({ minLength: 1 })), + reasoning: Type.Optional(Type.Boolean()), + thinkingLevelMap: Type.Optional(ThinkingLevelMapSchema), + input: Type.Optional(Type.Array(Type.Union([Type.Literal("text"), Type.Literal("image")]))), + cost: Type.Optional(ModelCostSchema), + contextWindow: Type.Optional(Type.Number()), + maxTokens: Type.Optional(Type.Number()), + headers: Type.Optional(Type.Record(Type.String(), Type.String())), + compat: Type.Optional(ProviderCompatSchema), +}); +const ModelOverrideSchema = Type.Object({ + name: Type.Optional(Type.String({ minLength: 1 })), + reasoning: Type.Optional(Type.Boolean()), + thinkingLevelMap: Type.Optional(ThinkingLevelMapSchema), + input: Type.Optional(Type.Array(Type.Union([Type.Literal("text"), Type.Literal("image")]))), + cost: Type.Optional(Type.Object({ + input: Type.Optional(Type.Number()), + output: Type.Optional(Type.Number()), + cacheRead: Type.Optional(Type.Number()), + cacheWrite: Type.Optional(Type.Number()), + tiers: Type.Optional(Type.Array(ModelCostTierSchema)), + })), + contextWindow: Type.Optional(Type.Number()), + maxTokens: Type.Optional(Type.Number()), + headers: Type.Optional(Type.Record(Type.String(), Type.String())), + compat: Type.Optional(ProviderCompatSchema), +}); +const ProviderConfigSchema = Type.Object({ + name: Type.Optional(Type.String({ minLength: 1 })), + baseUrl: Type.Optional(Type.String({ minLength: 1 })), + apiKey: Type.Optional(Type.String({ minLength: 1 })), + api: Type.Optional(Type.String({ minLength: 1 })), + oauth: Type.Optional(Type.Literal("radius")), + headers: Type.Optional(Type.Record(Type.String(), Type.String())), + compat: Type.Optional(ProviderCompatSchema), + authHeader: Type.Optional(Type.Boolean()), + models: Type.Optional(Type.Array(ModelDefinitionSchema)), + modelOverrides: Type.Optional(Type.Record(Type.String(), ModelOverrideSchema)), +}); +const ModelsConfigSchema = Type.Object({ + providers: Type.Record(Type.String(), ProviderConfigSchema), +}); +const validateModelsConfig = Compile(ModelsConfigSchema); +function formatValidationPath(error) { + if (error.keyword === "required") { + const requiredProperties = error.params.requiredProperties; + const requiredProperty = requiredProperties?.[0]; + if (requiredProperty) { + const basePath = error.instancePath.replace(/^\//, "").replace(/\//g, "."); + return basePath ? `${basePath}.${requiredProperty}` : requiredProperty; + } + } + const path = error.instancePath.replace(/^\//, "").replace(/\//g, "."); + return path || "root"; +} +function deepFreeze(value) { + if (typeof value !== "object" || value === null || Object.isFrozen(value)) + return value; + for (const child of Object.values(value)) + deepFreeze(child); + return Object.freeze(value); +} +/** One immutable load of models.json. */ +export class ModelConfig { + providers; + error; + constructor(providers, error) { + this.providers = providers; + this.error = error; + } + static async load(modelsJsonPath) { + if (!modelsJsonPath) + return new ModelConfig(new Map()); + const path = normalizePath(modelsJsonPath); + let content; + try { + content = await readFile(path, "utf-8"); + } + catch (error) { + if (error.code === "ENOENT") + return new ModelConfig(new Map()); + return new ModelConfig(new Map(), `Failed to load models.json: ${error instanceof Error ? error.message : error}\n\nFile: ${path}`); + } + let parsed; + try { + parsed = JSON.parse(stripJsonComments(content)); + } + catch (error) { + return new ModelConfig(new Map(), `Failed to parse models.json: ${error instanceof Error ? error.message : error}\n\nFile: ${path}`); + } + if (!validateModelsConfig.Check(parsed)) { + const errors = validateModelsConfig + .Errors(parsed) + .map((error) => ` - ${formatValidationPath(error)}: ${error.message}`) + .join("\n") || "Unknown schema error"; + return new ModelConfig(new Map(), `Invalid models.json schema:\n${errors}\n\nFile: ${path}`); + } + const config = parsed; + const providers = new Map(); + for (const [providerId, provider] of Object.entries(config.providers)) { + providers.set(providerId, deepFreeze(structuredClone(provider))); + } + return new ModelConfig(providers); + } + getProvider(providerId) { + return this.providers.get(providerId); + } + getProviderIds() { + return [...this.providers.keys()]; + } + getError() { + return this.error; + } +} +//# sourceMappingURL=model-config.js.map \ No newline at end of file diff --git a/dist/core/model-config.js.map b/dist/core/model-config.js.map new file mode 100644 index 0000000..d578cdd --- /dev/null +++ b/dist/core/model-config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"model-config.js","sourceRoot":"","sources":["../../src/core/model-config.ts"],"names":[],"mappings":"AAAA,wDAAwD;AAExD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAE1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD,MAAM,uBAAuB,GAAG,IAAI,CAAC,MAAM,CAAC;IAC3C,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;IACjC,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;IACjC,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;IACjC,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;CACjC,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,IAAI,CAAC,MAAM,CAAC;IAC3C,eAAe,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IAC9C,kBAAkB,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IACjD,eAAe,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CA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c,GAAsB;QACnC,OAAO,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC;IAAA,CAClC;IAED,QAAQ,GAAuB;QAC9B,OAAO,IAAI,CAAC,KAAK,CAAC;IAAA,CAClB;CACD","sourcesContent":["/** Immutable, credential-blind models.json snapshot. */\n\nimport { readFile } from \"node:fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { Compile } from \"typebox/compile\";\nimport type { TLocalizedValidationError } from \"typebox/error\";\nimport { stripJsonComments } from \"../utils/json.ts\";\nimport { normalizePath } from \"../utils/paths.ts\";\n\nconst PercentileCutoffsSchema = Type.Object({\n\tp50: Type.Optional(Type.Number()),\n\tp75: Type.Optional(Type.Number()),\n\tp90: Type.Optional(Type.Number()),\n\tp99: Type.Optional(Type.Number()),\n});\n\nconst OpenRouterRoutingSchema = Type.Object({\n\tallow_fallbacks: Type.Optional(Type.Boolean()),\n\trequire_parameters: Type.Optional(Type.Boolean()),\n\tdata_collection: Type.Optional(Type.Union([Type.Literal(\"deny\"), Type.Literal(\"allow\")])),\n\tzdr: Type.Optional(Type.Boolean()),\n\tenforce_distillable_text: Type.Optional(Type.Boolean()),\n\torder: Type.Optional(Type.Array(Type.String())),\n\tonly: Type.Optional(Type.Array(Type.String())),\n\tignore: Type.Optional(Type.Array(Type.String())),\n\tquantizations: Type.Optional(Type.Array(Type.String())),\n\tsort: Type.Optional(\n\t\tType.Union([\n\t\t\tType.String(),\n\t\t\tType.Object({\n\t\t\t\tby: Type.Optional(Type.String()),\n\t\t\t\tpartition: Type.Optional(Type.Union([Type.String(), Type.Null()])),\n\t\t\t}),\n\t\t]),\n\t),\n\tmax_price: Type.Optional(\n\t\tType.Object({\n\t\t\tprompt: Type.Optional(Type.Union([Type.Number(), Type.String()])),\n\t\t\tcompletion: Type.Optional(Type.Union([Type.Number(), Type.String()])),\n\t\t\timage: Type.Optional(Type.Union([Type.Number(), Type.String()])),\n\t\t\taudio: Type.Optional(Type.Union([Type.Number(), Type.String()])),\n\t\t\trequest: Type.Optional(Type.Union([Type.Number(), Type.String()])),\n\t\t}),\n\t),\n\tpreferred_min_throughput: Type.Optional(Type.Union([Type.Number(), PercentileCutoffsSchema])),\n\tpreferred_max_latency: Type.Optional(Type.Union([Type.Number(), PercentileCutoffsSchema])),\n});\n\nconst VercelGatewayRoutingSchema = Type.Object({\n\tonly: Type.Optional(Type.Array(Type.String())),\n\torder: Type.Optional(Type.Array(Type.String())),\n});\n\nconst ThinkingLevelMapValueSchema = Type.Union([Type.String(), Type.Null()]);\nconst ThinkingLevelMapSchema = Type.Object({\n\toff: Type.Optional(ThinkingLevelMapValueSchema),\n\tminimal: Type.Optional(ThinkingLevelMapValueSchema),\n\tlow: Type.Optional(ThinkingLevelMapValueSchema),\n\tmedium: Type.Optional(ThinkingLevelMapValueSchema),\n\thigh: Type.Optional(ThinkingLevelMapValueSchema),\n\txhigh: Type.Optional(ThinkingLevelMapValueSchema),\n\tmax: Type.Optional(ThinkingLevelMapValueSchema),\n});\n\nconst ChatTemplateKwargScalarSchema = Type.Union([Type.String(), Type.Number(), Type.Boolean(), Type.Null()]);\nconst ChatTemplateKwargVariableSchema = Type.Object({\n\t$var: Type.Union([Type.Literal(\"thinking.enabled\"), Type.Literal(\"thinking.effort\")]),\n\tomitWhenOff: Type.Optional(Type.Boolean()),\n});\nconst ChatTemplateKwargSchema = Type.Union([ChatTemplateKwargScalarSchema, ChatTemplateKwargVariableSchema]);\n\nconst OpenAICompletionsCompatSchema = Type.Object({\n\tsupportsStore: Type.Optional(Type.Boolean()),\n\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\tsupportsReasoningEffort: Type.Optional(Type.Boolean()),\n\tsupportsUsageInStreaming: Type.Optional(Type.Boolean()),\n\tmaxTokensField: Type.Optional(Type.Union([Type.Literal(\"max_completion_tokens\"), Type.Literal(\"max_tokens\")])),\n\trequiresToolResultName: Type.Optional(Type.Boolean()),\n\trequiresAssistantAfterToolResult: Type.Optional(Type.Boolean()),\n\trequiresThinkingAsText: Type.Optional(Type.Boolean()),\n\trequiresReasoningContentOnAssistantMessages: Type.Optional(Type.Boolean()),\n\tthinkingFormat: Type.Optional(\n\t\tType.Union([\n\t\t\tType.Literal(\"openai\"),\n\t\t\tType.Literal(\"openrouter\"),\n\t\t\tType.Literal(\"together\"),\n\t\t\tType.Literal(\"deepseek\"),\n\t\t\tType.Literal(\"zai\"),\n\t\t\tType.Literal(\"qwen\"),\n\t\t\tType.Literal(\"chat-template\"),\n\t\t\tType.Literal(\"qwen-chat-template\"),\n\t\t\tType.Literal(\"string-thinking\"),\n\t\t\tType.Literal(\"ant-ling\"),\n\t\t]),\n\t),\n\tchatTemplateKwargs: Type.Optional(Type.Record(Type.String(), ChatTemplateKwargSchema)),\n\tcacheControlFormat: Type.Optional(Type.Literal(\"anthropic\")),\n\topenRouterRouting: Type.Optional(OpenRouterRoutingSchema),\n\tvercelGatewayRouting: Type.Optional(VercelGatewayRoutingSchema),\n\tsupportsOpenAIGrammarTools: Type.Optional(Type.Boolean()),\n\tsupportsStrictMode: Type.Optional(Type.Boolean()),\n\tsendSessionAffinityHeaders: Type.Optional(Type.Boolean()),\n\tdeferredToolsMode: Type.Optional(Type.Literal(\"kimi\")),\n\tsessionAffinityFormat: Type.Optional(\n\t\tType.Union([Type.Literal(\"openai\"), Type.Literal(\"openai-nosession\"), Type.Literal(\"openrouter\")]),\n\t),\n\tsupportsLongCacheRetention: Type.Optional(Type.Boolean()),\n});\n\nconst OpenAIResponsesCompatSchema = Type.Object({\n\tsupportsDeveloperRole: Type.Optional(Type.Boolean()),\n\tsessionAffinityFormat: Type.Optional(\n\t\tType.Union([Type.Literal(\"openai\"), Type.Literal(\"openai-nosession\"), Type.Literal(\"openrouter\")]),\n\t),\n\tsupportsLongCacheRetention: Type.Optional(Type.Boolean()),\n\tsupportsStrictMode: Type.Optional(Type.Boolean()),\n\tsupportsOpenAIGrammarTools: Type.Optional(Type.Boolean()),\n\tsupportsToolSearch: Type.Optional(Type.Boolean()),\n});\n\nconst AnthropicMessagesCompatSchema = Type.Object({\n\tsupportsEagerToolInputStreaming: Type.Optional(Type.Boolean()),\n\tsupportsLongCacheRetention: Type.Optional(Type.Boolean()),\n\tsendSessionAffinityHeaders: Type.Optional(Type.Boolean()),\n\tsupportsCacheControlOnTools: Type.Optional(Type.Boolean()),\n\tsupportsTemperature: Type.Optional(Type.Boolean()),\n\tforceAdaptiveThinking: Type.Optional(Type.Boolean()),\n\tallowEmptySignature: Type.Optional(Type.Boolean()),\n\tsupportsStrictTools: Type.Optional(Type.Boolean()),\n\tsupportsToolReferences: Type.Optional(Type.Boolean()),\n});\n\nconst ProviderCompatSchema = Type.Union([\n\tOpenAICompletionsCompatSchema,\n\tOpenAIResponsesCompatSchema,\n\tAnthropicMessagesCompatSchema,\n]);\n\nconst ModelCostRatesSchema = {\n\tinput: Type.Number(),\n\toutput: Type.Number(),\n\tcacheRead: Type.Number(),\n\tcacheWrite: Type.Number(),\n};\nconst ModelCostTierSchema = Type.Object({\n\tinputTokensAbove: Type.Number(),\n\t...ModelCostRatesSchema,\n});\nconst ModelCostSchema = Type.Object({\n\t...ModelCostRatesSchema,\n\ttiers: Type.Optional(Type.Array(ModelCostTierSchema)),\n});\n\nconst ModelDefinitionSchema = Type.Object({\n\tid: Type.String({ minLength: 1 }),\n\tname: Type.Optional(Type.String({ minLength: 1 })),\n\tapi: Type.Optional(Type.String({ minLength: 1 })),\n\tbaseUrl: Type.Optional(Type.String({ minLength: 1 })),\n\treasoning: Type.Optional(Type.Boolean()),\n\tthinkingLevelMap: Type.Optional(ThinkingLevelMapSchema),\n\tinput: Type.Optional(Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")]))),\n\tcost: Type.Optional(ModelCostSchema),\n\tcontextWindow: Type.Optional(Type.Number()),\n\tmaxTokens: Type.Optional(Type.Number()),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tcompat: Type.Optional(ProviderCompatSchema),\n});\n\nconst ModelOverrideSchema = Type.Object({\n\tname: Type.Optional(Type.String({ minLength: 1 })),\n\treasoning: Type.Optional(Type.Boolean()),\n\tthinkingLevelMap: Type.Optional(ThinkingLevelMapSchema),\n\tinput: Type.Optional(Type.Array(Type.Union([Type.Literal(\"text\"), Type.Literal(\"image\")]))),\n\tcost: Type.Optional(\n\t\tType.Object({\n\t\t\tinput: Type.Optional(Type.Number()),\n\t\t\toutput: Type.Optional(Type.Number()),\n\t\t\tcacheRead: Type.Optional(Type.Number()),\n\t\t\tcacheWrite: Type.Optional(Type.Number()),\n\t\t\ttiers: Type.Optional(Type.Array(ModelCostTierSchema)),\n\t\t}),\n\t),\n\tcontextWindow: Type.Optional(Type.Number()),\n\tmaxTokens: Type.Optional(Type.Number()),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tcompat: Type.Optional(ProviderCompatSchema),\n});\n\nconst ProviderConfigSchema = Type.Object({\n\tname: Type.Optional(Type.String({ minLength: 1 })),\n\tbaseUrl: Type.Optional(Type.String({ minLength: 1 })),\n\tapiKey: Type.Optional(Type.String({ minLength: 1 })),\n\tapi: Type.Optional(Type.String({ minLength: 1 })),\n\toauth: Type.Optional(Type.Literal(\"radius\")),\n\theaders: Type.Optional(Type.Record(Type.String(), Type.String())),\n\tcompat: Type.Optional(ProviderCompatSchema),\n\tauthHeader: Type.Optional(Type.Boolean()),\n\tmodels: Type.Optional(Type.Array(ModelDefinitionSchema)),\n\tmodelOverrides: Type.Optional(Type.Record(Type.String(), ModelOverrideSchema)),\n});\n\nconst ModelsConfigSchema = Type.Object({\n\tproviders: Type.Record(Type.String(), ProviderConfigSchema),\n});\nconst validateModelsConfig = Compile(ModelsConfigSchema);\n\nexport type ModelsJsonModel = Static;\nexport type ModelsJsonModelOverride = Static;\nexport type ModelsJsonProvider = Static;\ntype ModelsJson = Static;\n\nfunction formatValidationPath(error: TLocalizedValidationError): string {\n\tif (error.keyword === \"required\") {\n\t\tconst requiredProperties = (error.params as { requiredProperties?: string[] }).requiredProperties;\n\t\tconst requiredProperty = requiredProperties?.[0];\n\t\tif (requiredProperty) {\n\t\t\tconst basePath = error.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\");\n\t\t\treturn basePath ? `${basePath}.${requiredProperty}` : requiredProperty;\n\t\t}\n\t}\n\tconst path = error.instancePath.replace(/^\\//, \"\").replace(/\\//g, \".\");\n\treturn path || \"root\";\n}\n\nfunction deepFreeze(value: T): T {\n\tif (typeof value !== \"object\" || value === null || Object.isFrozen(value)) return value;\n\tfor (const child of Object.values(value)) deepFreeze(child);\n\treturn Object.freeze(value);\n}\n\n/** One immutable load of models.json. */\nexport class ModelConfig {\n\tprivate readonly providers: ReadonlyMap;\n\tprivate readonly error: string | undefined;\n\n\tprivate constructor(providers: ReadonlyMap, error?: string) {\n\t\tthis.providers = providers;\n\t\tthis.error = error;\n\t}\n\n\tstatic async load(modelsJsonPath: string | undefined): Promise {\n\t\tif (!modelsJsonPath) return new ModelConfig(new Map());\n\t\tconst path = normalizePath(modelsJsonPath);\n\t\tlet content: string;\n\t\ttry {\n\t\t\tcontent = await readFile(path, \"utf-8\");\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return new ModelConfig(new Map());\n\t\t\treturn new ModelConfig(\n\t\t\t\tnew Map(),\n\t\t\t\t`Failed to load models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${path}`,\n\t\t\t);\n\t\t}\n\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(stripJsonComments(content));\n\t\t} catch (error) {\n\t\t\treturn new ModelConfig(\n\t\t\t\tnew Map(),\n\t\t\t\t`Failed to parse models.json: ${error instanceof Error ? error.message : error}\\n\\nFile: ${path}`,\n\t\t\t);\n\t\t}\n\n\t\tif (!validateModelsConfig.Check(parsed)) {\n\t\t\tconst errors =\n\t\t\t\tvalidateModelsConfig\n\t\t\t\t\t.Errors(parsed)\n\t\t\t\t\t.map((error) => ` - ${formatValidationPath(error)}: ${error.message}`)\n\t\t\t\t\t.join(\"\\n\") || \"Unknown schema error\";\n\t\t\treturn new ModelConfig(new Map(), `Invalid models.json schema:\\n${errors}\\n\\nFile: ${path}`);\n\t\t}\n\n\t\tconst config = parsed as ModelsJson;\n\t\tconst providers = new Map();\n\t\tfor (const [providerId, provider] of Object.entries(config.providers)) {\n\t\t\tproviders.set(providerId, deepFreeze(structuredClone(provider)));\n\t\t}\n\t\treturn new ModelConfig(providers);\n\t}\n\n\tgetProvider(providerId: string): ModelsJsonProvider | undefined {\n\t\treturn this.providers.get(providerId);\n\t}\n\n\tgetProviderIds(): readonly string[] {\n\t\treturn [...this.providers.keys()];\n\t}\n\n\tgetError(): string | undefined {\n\t\treturn this.error;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/model-registry.d.ts b/dist/core/model-registry.d.ts new file mode 100644 index 0000000..d7ef9c8 --- /dev/null +++ b/dist/core/model-registry.d.ts @@ -0,0 +1,43 @@ +import type { Api, AuthResult, Model, Provider } from "@earendil-works/pi-ai"; +import type { ModelRuntime } from "./model-runtime.ts"; +import type { AuthStatus, ProviderConfigInput } from "./provider-composer.ts"; +export type { ProviderConfigInput } from "./provider-composer.ts"; +export type ResolvedRequestAuth = { + ok: true; + apiKey?: string; + headers?: Record; + env?: Record; +} | { + ok: false; + error: string; +}; +export { clearApiKeyCache } from "./provider-composer.ts"; +/** + * Synchronous compatibility facade exposed to extensions. + * Coding-agent internals use ModelRuntime directly. + */ +export declare class ModelRegistry { + private readonly runtime; + constructor(runtime: ModelRuntime); + /** Reload models.json asynchronously. Await before making synchronous registry reads. */ + refresh(): Promise; + getError(): string | undefined; + getAll(): Model[]; + getAvailable(): Model[]; + find(provider: string, modelId: string): Model | undefined; + hasConfiguredAuth(model: Model): boolean; + getApiKeyAndHeaders(model: Model): Promise; + getProviderAuthStatus(provider: string): AuthStatus; + getProvider(provider: string): Provider | undefined; + getProviderDisplayName(provider: string): string; + getProviderAuth(provider: string): Promise; + getApiKeyForProvider(provider: string): Promise; + isUsingOAuth(model: Model): boolean; + registerProvider(provider: Provider): void; + registerProvider(providerName: string, config: ProviderConfigInput): void; + unregisterProvider(providerName: string): void; + getRegisteredProviderConfig(providerName: string): ProviderConfigInput | undefined; + getRegisteredNativeProvider(providerName: string): Provider | undefined; + getRegisteredProviderIds(): readonly string[]; +} +//# sourceMappingURL=model-registry.d.ts.map \ No newline at end of file diff --git a/dist/core/model-registry.d.ts.map b/dist/core/model-registry.d.ts.map new file mode 100644 index 0000000..d118ed3 --- /dev/null +++ b/dist/core/model-registry.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"model-registry.d.ts","sourceRoot":"","sources":["../../src/core/model-registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAC9E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAE9E,YAAY,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAClE,MAAM,MAAM,mBAAmB,GAC5B;IACA,EAAE,EAAE,IAAI,CAAC;IACT,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC5B,GACD;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAChC,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D;;;GAGG;AACH,qBAAa,aAAa;IACzB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAe;IAEvC,YAAY,OAAO,EAAE,YAAY,EAEhC;IAED,yFAAyF;IAC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AG,SAAS,CAEtE;IAED,wBAAwB,IAAI,SAAS,MAAM,EAAE,CAE5C;CACD","sourcesContent":["import type { Api, AuthResult, Model, Provider } from \"@earendil-works/pi-ai\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { AuthStatus, ProviderConfigInput } from \"./provider-composer.ts\";\n\nexport type { ProviderConfigInput } from \"./provider-composer.ts\";\nexport type ResolvedRequestAuth =\n\t| {\n\t\t\tok: true;\n\t\t\tapiKey?: string;\n\t\t\theaders?: Record;\n\t\t\tenv?: Record;\n\t }\n\t| { ok: false; error: string };\nexport { clearApiKeyCache } from \"./provider-composer.ts\";\n\n/**\n * Synchronous compatibility facade exposed to extensions.\n * Coding-agent internals use ModelRuntime directly.\n */\nexport class ModelRegistry {\n\tprivate readonly runtime: ModelRuntime;\n\n\tconstructor(runtime: ModelRuntime) {\n\t\tthis.runtime = runtime;\n\t}\n\n\t/** Reload models.json asynchronously. Await before making synchronous registry reads. */\n\tasync refresh(): Promise {\n\t\tawait this.runtime.refresh();\n\t}\n\n\tgetError(): string | undefined {\n\t\treturn this.runtime.getError();\n\t}\n\n\tgetAll(): Model[] {\n\t\treturn [...this.runtime.getModels()];\n\t}\n\n\tgetAvailable(): Model[] {\n\t\treturn [...this.runtime.getAvailableSnapshot()];\n\t}\n\n\tfind(provider: string, modelId: string): Model | undefined {\n\t\treturn this.runtime.getModel(provider, modelId);\n\t}\n\n\thasConfiguredAuth(model: Model): boolean {\n\t\treturn this.runtime.hasConfiguredAuth(model.provider);\n\t}\n\n\tasync getApiKeyAndHeaders(model: Model): Promise {\n\t\ttry {\n\t\t\tconst resolution = await this.runtime.getAuth(model);\n\t\t\tif (!resolution) {\n\t\t\t\tconst compatibility = this.runtime.getCompatibilityRequestConfig(model);\n\t\t\t\tif (compatibility.authHeader) {\n\t\t\t\t\treturn { ok: false, error: `No API key found for \"${model.provider}\"` };\n\t\t\t\t}\n\t\t\t\tconst headers = compatibility.headers\n\t\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(compatibility.headers).filter(\n\t\t\t\t\t\t\t\t(entry): entry is [string, string] => entry[1] !== null,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t: undefined;\n\t\t\t\treturn { ok: true, headers };\n\t\t\t}\n\t\t\tconst headers = resolution.auth.headers\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tObject.entries(resolution.auth.headers).filter(\n\t\t\t\t\t\t\t(entry): entry is [string, string] => entry[1] !== null,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\t\treturn { ok: true, apiKey: resolution.auth.apiKey, headers, env: resolution.env };\n\t\t} catch (error) {\n\t\t\tconst cause = error instanceof Error ? error.cause : undefined;\n\t\t\tconst message =\n\t\t\t\tcause instanceof Error ? cause.message : error instanceof Error ? error.message : String(error);\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror:\n\t\t\t\t\tmessage === \"authHeader requires a resolved API key\"\n\t\t\t\t\t\t? `No API key found for \"${model.provider}\"`\n\t\t\t\t\t\t: message,\n\t\t\t};\n\t\t}\n\t}\n\n\tgetProviderAuthStatus(provider: string): AuthStatus {\n\t\treturn this.runtime.getProviderAuthStatus(provider);\n\t}\n\n\tgetProvider(provider: string): Provider | undefined {\n\t\treturn this.runtime.getProvider(provider);\n\t}\n\n\tgetProviderDisplayName(provider: string): string {\n\t\treturn this.runtime.getProvider(provider)?.name ?? provider;\n\t}\n\n\tgetProviderAuth(provider: string): Promise {\n\t\treturn this.runtime.getAuth(provider);\n\t}\n\n\tasync getApiKeyForProvider(provider: string): Promise {\n\t\ttry {\n\t\t\treturn (await this.runtime.getAuth(provider))?.auth.apiKey;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tisUsingOAuth(model: Model): boolean {\n\t\treturn this.runtime.isUsingOAuth(model.provider);\n\t}\n\n\tregisterProvider(provider: Provider): void;\n\tregisterProvider(providerName: string, config: ProviderConfigInput): void;\n\tregisterProvider(providerOrName: Provider | string, config?: ProviderConfigInput): void {\n\t\tif (typeof providerOrName === \"string\") {\n\t\t\tif (!config) throw new Error(\"Provider config is required when registering by name\");\n\t\t\tthis.runtime.registerProvider(providerOrName, config);\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.registerNativeProvider(providerOrName);\n\t}\n\n\tunregisterProvider(providerName: string): void {\n\t\tthis.runtime.unregisterProvider(providerName);\n\t}\n\n\tgetRegisteredProviderConfig(providerName: string): ProviderConfigInput | undefined {\n\t\treturn this.runtime.getRegisteredProviderConfig(providerName);\n\t}\n\n\tgetRegisteredNativeProvider(providerName: string): Provider | undefined {\n\t\treturn this.runtime.getRegisteredNativeProvider(providerName);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn this.runtime.getRegisteredProviderIds();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/model-registry.js b/dist/core/model-registry.js new file mode 100644 index 0000000..225ccdb --- /dev/null +++ b/dist/core/model-registry.js @@ -0,0 +1,104 @@ +export { clearApiKeyCache } from "./provider-composer.js"; +/** + * Synchronous compatibility facade exposed to extensions. + * Coding-agent internals use ModelRuntime directly. + */ +export class ModelRegistry { + runtime; + constructor(runtime) { + this.runtime = runtime; + } + /** Reload models.json asynchronously. Await before making synchronous registry reads. */ + async refresh() { + await this.runtime.refresh(); + } + getError() { + return this.runtime.getError(); + } + getAll() { + return [...this.runtime.getModels()]; + } + getAvailable() { + return [...this.runtime.getAvailableSnapshot()]; + } + find(provider, modelId) { + return this.runtime.getModel(provider, modelId); + } + hasConfiguredAuth(model) { + return this.runtime.hasConfiguredAuth(model.provider); + } + async getApiKeyAndHeaders(model) { + try { + const resolution = await this.runtime.getAuth(model); + if (!resolution) { + const compatibility = this.runtime.getCompatibilityRequestConfig(model); + if (compatibility.authHeader) { + return { ok: false, error: `No API key found for "${model.provider}"` }; + } + const headers = compatibility.headers + ? Object.fromEntries(Object.entries(compatibility.headers).filter((entry) => entry[1] !== null)) + : undefined; + return { ok: true, headers }; + } + const headers = resolution.auth.headers + ? Object.fromEntries(Object.entries(resolution.auth.headers).filter((entry) => entry[1] !== null)) + : undefined; + return { ok: true, apiKey: resolution.auth.apiKey, headers, env: resolution.env }; + } + catch (error) { + const cause = error instanceof Error ? error.cause : undefined; + const message = cause instanceof Error ? cause.message : error instanceof Error ? error.message : String(error); + return { + ok: false, + error: message === "authHeader requires a resolved API key" + ? `No API key found for "${model.provider}"` + : message, + }; + } + } + getProviderAuthStatus(provider) { + return this.runtime.getProviderAuthStatus(provider); + } + getProvider(provider) { + return this.runtime.getProvider(provider); + } + getProviderDisplayName(provider) { + return this.runtime.getProvider(provider)?.name ?? provider; + } + getProviderAuth(provider) { + return this.runtime.getAuth(provider); + } + async getApiKeyForProvider(provider) { + try { + return (await this.runtime.getAuth(provider))?.auth.apiKey; + } + catch { + return undefined; + } + } + isUsingOAuth(model) { + return this.runtime.isUsingOAuth(model.provider); + } + registerProvider(providerOrName, config) { + if (typeof providerOrName === "string") { + if (!config) + throw new Error("Provider config is required when registering by name"); + this.runtime.registerProvider(providerOrName, config); + return; + } + this.runtime.registerNativeProvider(providerOrName); + } + unregisterProvider(providerName) { + this.runtime.unregisterProvider(providerName); + } + getRegisteredProviderConfig(providerName) { + return this.runtime.getRegisteredProviderConfig(providerName); + } + getRegisteredNativeProvider(providerName) { + return this.runtime.getRegisteredNativeProvider(providerName); + } + getRegisteredProviderIds() { + return this.runtime.getRegisteredProviderIds(); + } +} +//# sourceMappingURL=model-registry.js.map \ No newline at end of file diff --git a/dist/core/model-registry.js.map b/dist/core/model-registry.js.map new file mode 100644 index 0000000..1712b2a --- /dev/null +++ b/dist/core/model-registry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"model-registry.js","sourceRoot":"","sources":["../../src/core/model-registry.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D;;;GAGG;AACH,MAAM,OAAO,a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kBAAkB,CAAC,YAAoB,EAAQ;QAC9C,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,YAAY,CAAC,CAAC;IAAA,CAC9C;IAED,2BAA2B,CAAC,YAAoB,EAAmC;QAClF,OAAO,IAAI,CAAC,OAAO,CAAC,2BAA2B,CAAC,YAAY,CAAC,CAAC;IAAA,CAC9D;IAED,2BAA2B,CAAC,YAAoB,EAAwB;QACvE,OAAO,IAAI,CAAC,OAAO,CAAC,2BAA2B,CAAC,YAAY,CAAC,CAAC;IAAA,CAC9D;IAED,wBAAwB,GAAsB;QAC7C,OAAO,IAAI,CAAC,OAAO,CAAC,wBAAwB,EAAE,CAAC;IAAA,CAC/C;CACD","sourcesContent":["import type { Api, AuthResult, Model, Provider } from \"@earendil-works/pi-ai\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { AuthStatus, ProviderConfigInput } from \"./provider-composer.ts\";\n\nexport type { ProviderConfigInput } from \"./provider-composer.ts\";\nexport type ResolvedRequestAuth =\n\t| {\n\t\t\tok: true;\n\t\t\tapiKey?: string;\n\t\t\theaders?: Record;\n\t\t\tenv?: Record;\n\t }\n\t| { ok: false; error: string };\nexport { clearApiKeyCache } from \"./provider-composer.ts\";\n\n/**\n * Synchronous compatibility facade exposed to extensions.\n * Coding-agent internals use ModelRuntime directly.\n */\nexport class ModelRegistry {\n\tprivate readonly runtime: ModelRuntime;\n\n\tconstructor(runtime: ModelRuntime) {\n\t\tthis.runtime = runtime;\n\t}\n\n\t/** Reload models.json asynchronously. Await before making synchronous registry reads. */\n\tasync refresh(): Promise {\n\t\tawait this.runtime.refresh();\n\t}\n\n\tgetError(): string | undefined {\n\t\treturn this.runtime.getError();\n\t}\n\n\tgetAll(): Model[] {\n\t\treturn [...this.runtime.getModels()];\n\t}\n\n\tgetAvailable(): Model[] {\n\t\treturn [...this.runtime.getAvailableSnapshot()];\n\t}\n\n\tfind(provider: string, modelId: string): Model | undefined {\n\t\treturn this.runtime.getModel(provider, modelId);\n\t}\n\n\thasConfiguredAuth(model: Model): boolean {\n\t\treturn this.runtime.hasConfiguredAuth(model.provider);\n\t}\n\n\tasync getApiKeyAndHeaders(model: Model): Promise {\n\t\ttry {\n\t\t\tconst resolution = await this.runtime.getAuth(model);\n\t\t\tif (!resolution) {\n\t\t\t\tconst compatibility = this.runtime.getCompatibilityRequestConfig(model);\n\t\t\t\tif (compatibility.authHeader) {\n\t\t\t\t\treturn { ok: false, error: `No API key found for \"${model.provider}\"` };\n\t\t\t\t}\n\t\t\t\tconst headers = compatibility.headers\n\t\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(compatibility.headers).filter(\n\t\t\t\t\t\t\t\t(entry): entry is [string, string] => entry[1] !== null,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t: undefined;\n\t\t\t\treturn { ok: true, headers };\n\t\t\t}\n\t\t\tconst headers = resolution.auth.headers\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tObject.entries(resolution.auth.headers).filter(\n\t\t\t\t\t\t\t(entry): entry is [string, string] => entry[1] !== null,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\t\treturn { ok: true, apiKey: resolution.auth.apiKey, headers, env: resolution.env };\n\t\t} catch (error) {\n\t\t\tconst cause = error instanceof Error ? error.cause : undefined;\n\t\t\tconst message =\n\t\t\t\tcause instanceof Error ? cause.message : error instanceof Error ? error.message : String(error);\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror:\n\t\t\t\t\tmessage === \"authHeader requires a resolved API key\"\n\t\t\t\t\t\t? `No API key found for \"${model.provider}\"`\n\t\t\t\t\t\t: message,\n\t\t\t};\n\t\t}\n\t}\n\n\tgetProviderAuthStatus(provider: string): AuthStatus {\n\t\treturn this.runtime.getProviderAuthStatus(provider);\n\t}\n\n\tgetProvider(provider: string): Provider | undefined {\n\t\treturn this.runtime.getProvider(provider);\n\t}\n\n\tgetProviderDisplayName(provider: string): string {\n\t\treturn this.runtime.getProvider(provider)?.name ?? provider;\n\t}\n\n\tgetProviderAuth(provider: string): Promise {\n\t\treturn this.runtime.getAuth(provider);\n\t}\n\n\tasync getApiKeyForProvider(provider: string): Promise {\n\t\ttry {\n\t\t\treturn (await this.runtime.getAuth(provider))?.auth.apiKey;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tisUsingOAuth(model: Model): boolean {\n\t\treturn this.runtime.isUsingOAuth(model.provider);\n\t}\n\n\tregisterProvider(provider: Provider): void;\n\tregisterProvider(providerName: string, config: ProviderConfigInput): void;\n\tregisterProvider(providerOrName: Provider | string, config?: ProviderConfigInput): void {\n\t\tif (typeof providerOrName === \"string\") {\n\t\t\tif (!config) throw new Error(\"Provider config is required when registering by name\");\n\t\t\tthis.runtime.registerProvider(providerOrName, config);\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.registerNativeProvider(providerOrName);\n\t}\n\n\tunregisterProvider(providerName: string): void {\n\t\tthis.runtime.unregisterProvider(providerName);\n\t}\n\n\tgetRegisteredProviderConfig(providerName: string): ProviderConfigInput | undefined {\n\t\treturn this.runtime.getRegisteredProviderConfig(providerName);\n\t}\n\n\tgetRegisteredNativeProvider(providerName: string): Provider | undefined {\n\t\treturn this.runtime.getRegisteredNativeProvider(providerName);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn this.runtime.getRegisteredProviderIds();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/model-resolver.d.ts b/dist/core/model-resolver.d.ts new file mode 100644 index 0000000..6a5a5e0 --- /dev/null +++ b/dist/core/model-resolver.d.ts @@ -0,0 +1,122 @@ +/** + * Model resolution, scoping, and initial selection + */ +import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; +import { type Api, type KnownProvider, type Model } from "@earendil-works/pi-ai"; +import type { ModelRuntime } from "./model-runtime.ts"; +/** Default model IDs for each known provider */ +export declare const defaultModelPerProvider: Record; +export interface ScopedModel { + model: Model; + /** Thinking level if explicitly specified in pattern (e.g., "model:high"), undefined otherwise */ + thinkingLevel?: ThinkingLevel; +} +/** + * Find an exact model reference match. + * Supports either a bare model id or a canonical provider/modelId reference. + * When matching by bare id, ambiguous matches across providers are rejected. + */ +export declare function findExactModelReferenceMatch(modelReference: string, availableModels: Model[]): Model | undefined; +export interface ParsedModelResult { + model: Model | undefined; + /** Thinking level if explicitly specified in pattern, undefined otherwise */ + thinkingLevel?: ThinkingLevel; + warning: string | undefined; +} +/** + * Parse a pattern to extract model and thinking level. + * Handles models with colons in their IDs (e.g., OpenRouter's :exacto suffix). + * + * Algorithm: + * 1. Try to match full pattern as a model + * 2. If found, return it with "off" thinking level + * 3. If not found and has colons, split on last colon: + * - If suffix is valid thinking level, use it and recurse on prefix + * - If suffix is invalid, warn and recurse on prefix with "off" + * + * @internal Exported for testing + */ +export declare function parseModelPattern(pattern: string, availableModels: Model[], options?: { + allowInvalidThinkingLevelFallback?: boolean; +}): ParsedModelResult; +/** + * Resolve model patterns to actual Model objects with optional thinking levels + * Format: "pattern:level" where :level is optional + * For each pattern, finds all matching models and picks the best version: + * 1. Prefer alias (e.g., claude-sonnet-4-5) over dated versions (claude-sonnet-4-5-20250929) + * 2. If no alias, pick the latest dated version + * + * Supports models with colons in their IDs (e.g., OpenRouter's model:exacto). + * The algorithm tries to match the full pattern first, then progressively + * strips colon-suffixes to find a match. + */ +export interface ModelScopeDiagnostic { + type: "warning"; + code: "no-match" | "invalid-thinking-level"; + message: string; + pattern: string; +} +export interface ResolveModelScopeResult { + scopedModels: ScopedModel[]; + diagnostics: ModelScopeDiagnostic[]; +} +export declare function resolveModelScopeWithDiagnostics(patterns: string[], modelRuntime: ModelRuntime): Promise; +export declare function resolveModelScope(patterns: string[], modelRuntime: ModelRuntime): Promise; +export interface ResolveCliModelResult { + model: Model | undefined; + thinkingLevel?: ThinkingLevel; + warning: string | undefined; + /** + * Error message suitable for CLI display. + * When set, model will be undefined. + */ + error: string | undefined; +} +/** + * Resolve a single model from CLI flags. + * + * Supports: + * - --provider --model + * - --model / + * - Fuzzy matching (same rules as model scoping: exact id, then partial id/name) + * + * Note: This does not apply the thinking level by itself, but it may *parse* and + * return a thinking level from ":" so the caller can apply it. + */ +export declare function resolveCliModel(options: { + cliProvider?: string; + cliModel?: string; + cliThinking?: ThinkingLevel; + modelRuntime: ModelRuntime; +}): ResolveCliModelResult; +export interface InitialModelResult { + model: Model | undefined; + thinkingLevel: ThinkingLevel; + fallbackMessage: string | undefined; +} +/** + * Find the initial model to use based on priority: + * 1. CLI args (provider + model) + * 2. First model from scoped models (if not continuing/resuming) + * 3. Restored from session (if continuing/resuming) + * 4. Saved default from settings + * 5. First available model with valid API key + */ +export declare function findInitialModel(options: { + cliProvider?: string; + cliModel?: string; + scopedModels: ScopedModel[]; + isContinuing: boolean; + defaultProvider?: string; + defaultModelId?: string; + defaultThinkingLevel?: ThinkingLevel; + modelRuntime: ModelRuntime; +}): Promise; +/** + * Restore model from session, with fallback to available models + */ +export declare function restoreModelFromSession(savedProvider: string, savedModelId: string, currentModel: Model | undefined, shouldPrintMessages: boolean, modelRuntime: ModelRuntime): Promise<{ + model: Model | undefined; + fallbackMessage: string | undefined; +}>; +//# sourceMappingURL=model-resolver.d.ts.map \ No newline at end of file diff --git a/dist/core/model-resolver.d.ts.map b/dist/core/model-resolver.d.ts.map new file mode 100644 index 0000000..47b40ab --- /dev/null +++ b/dist/core/model-resolver.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"model-resolver.d.ts","sourceRoot":"","sources":["../../src/core/model-resolver.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,KAAK,GAAG,EAAE,KAAK,aAAa,EAAE,KAAK,KAAK,EAAkB,MAAM,uBAAuB,CAAC;AAKjG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAEvD,gDAAgD;AACh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AAmB,EAAE,OAAO,EAC5B,YAAY,EAAE,YAAY,GACxB,OAAO,CAAC;IAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;IAAC,eAAe,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC,CA+DjF","sourcesContent":["/**\n * Model resolution, scoping, and initial selection\n */\n\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { type Api, type KnownProvider, type Model, modelsAreEqual } from \"@earendil-works/pi-ai\";\nimport chalk from \"chalk\";\nimport { minimatch } from \"minimatch\";\nimport { isValidThinkingLevel } from \"../cli/args.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\n\n/** Default model IDs for each known provider */\nexport const defaultModelPerProvider: Record = {\n\t\"amazon-bedrock\": \"us.anthropic.claude-opus-4-6-v1\",\n\t\"ant-ling\": \"Ring-2.6-1T\",\n\tanthropic: \"claude-opus-4-8\",\n\topenai: \"gpt-5.5\",\n\t\"azure-openai-responses\": \"gpt-5.4\",\n\t\"openai-codex\": \"gpt-5.5\",\n\tradius: \"auto\",\n\tnvidia: \"nvidia/nemotron-3-super-120b-a12b\",\n\tdeepseek: \"deepseek-v4-pro\",\n\tgoogle: \"gemini-3.1-pro-preview\",\n\t\"google-vertex\": \"gemini-3.1-pro-preview\",\n\t\"github-copilot\": \"gpt-5.4\",\n\topenrouter: \"moonshotai/kimi-k2.6\",\n\t\"vercel-ai-gateway\": \"zai/glm-5.1\",\n\txai: \"grok-4.5\",\n\tgroq: \"openai/gpt-oss-120b\",\n\tcerebras: \"zai-glm-4.7\",\n\tzai: \"glm-5.1\",\n\t\"zai-coding-cn\": \"glm-5.1\",\n\tmistral: \"devstral-medium-latest\",\n\tminimax: \"MiniMax-M2.7\",\n\t\"minimax-cn\": \"MiniMax-M2.7\",\n\tmoonshotai: \"kimi-k2.6\",\n\t\"moonshotai-cn\": \"kimi-k2.6\",\n\thuggingface: \"moonshotai/Kimi-K2.6\",\n\tfireworks: \"accounts/fireworks/models/kimi-k2p6\",\n\ttogether: \"moonshotai/Kimi-K2.6\",\n\topencode: \"kimi-k2.6\",\n\t\"opencode-go\": \"kimi-k2.6\",\n\t\"kimi-coding\": \"kimi-for-coding\",\n\t\"cloudflare-workers-ai\": \"@cf/moonshotai/kimi-k2.6\",\n\t\"cloudflare-ai-gateway\": \"workers-ai/@cf/moonshotai/kimi-k2.6\",\n\t\"qwen-token-plan\": \"qwen3.7-max\",\n\t\"qwen-token-plan-cn\": \"qwen3.7-max\",\n\txiaomi: \"mimo-v2.5-pro\",\n\t\"xiaomi-token-plan-cn\": \"mimo-v2.5-pro\",\n\t\"xiaomi-token-plan-ams\": \"mimo-v2.5-pro\",\n\t\"xiaomi-token-plan-sgp\": \"mimo-v2.5-pro\",\n};\n\nexport interface ScopedModel {\n\tmodel: Model;\n\t/** Thinking level if explicitly specified in pattern (e.g., \"model:high\"), undefined otherwise */\n\tthinkingLevel?: ThinkingLevel;\n}\n\n/**\n * Helper to check if a model ID looks like an alias (no date suffix)\n * Dates are typically in format: -20241022 or -20250929\n */\nfunction isAlias(id: string): boolean {\n\t// Check if ID ends with -latest\n\tif (id.endsWith(\"-latest\")) return true;\n\n\t// Check if ID ends with a date pattern (-YYYYMMDD)\n\tconst datePattern = /-\\d{8}$/;\n\treturn !datePattern.test(id);\n}\n\n/**\n * Find an exact model reference match.\n * Supports either a bare model id or a canonical provider/modelId reference.\n * When matching by bare id, ambiguous matches across providers are rejected.\n */\nexport function findExactModelReferenceMatch(\n\tmodelReference: string,\n\tavailableModels: Model[],\n): Model | undefined {\n\tconst trimmedReference = modelReference.trim();\n\tif (!trimmedReference) {\n\t\treturn undefined;\n\t}\n\n\tconst normalizedReference = trimmedReference.toLowerCase();\n\n\tconst canonicalMatches = availableModels.filter(\n\t\t(model) => `${model.provider}/${model.id}`.toLowerCase() === normalizedReference,\n\t);\n\tif (canonicalMatches.length === 1) {\n\t\treturn canonicalMatches[0];\n\t}\n\tif (canonicalMatches.length > 1) {\n\t\treturn undefined;\n\t}\n\n\tconst slashIndex = trimmedReference.indexOf(\"/\");\n\tif (slashIndex !== -1) {\n\t\tconst provider = trimmedReference.substring(0, slashIndex).trim();\n\t\tconst modelId = trimmedReference.substring(slashIndex + 1).trim();\n\t\tif (provider && modelId) {\n\t\t\tconst providerMatches = availableModels.filter(\n\t\t\t\t(model) =>\n\t\t\t\t\tmodel.provider.toLowerCase() === provider.toLowerCase() &&\n\t\t\t\t\tmodel.id.toLowerCase() === modelId.toLowerCase(),\n\t\t\t);\n\t\t\tif (providerMatches.length === 1) {\n\t\t\t\treturn providerMatches[0];\n\t\t\t}\n\t\t\tif (providerMatches.length > 1) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst idMatches = availableModels.filter((model) => model.id.toLowerCase() === normalizedReference);\n\treturn idMatches.length === 1 ? idMatches[0] : undefined;\n}\n\n/**\n * Try to match a pattern to a model from the available models list.\n * Returns the matched model or undefined if no match found.\n */\nfunction tryMatchModel(modelPattern: string, availableModels: Model[]): Model | undefined {\n\tconst exactMatch = findExactModelReferenceMatch(modelPattern, availableModels);\n\tif (exactMatch) {\n\t\treturn exactMatch;\n\t}\n\n\t// No exact match - fall back to partial matching\n\tconst matches = availableModels.filter(\n\t\t(m) =>\n\t\t\tm.id.toLowerCase().includes(modelPattern.toLowerCase()) ||\n\t\t\tm.name?.toLowerCase().includes(modelPattern.toLowerCase()),\n\t);\n\n\tif (matches.length === 0) {\n\t\treturn undefined;\n\t}\n\n\t// Separate into aliases and dated versions\n\tconst aliases = matches.filter((m) => isAlias(m.id));\n\tconst datedVersions = matches.filter((m) => !isAlias(m.id));\n\n\tif (aliases.length > 0) {\n\t\t// Prefer alias - if multiple aliases, pick the one that sorts highest\n\t\taliases.sort((a, b) => b.id.localeCompare(a.id));\n\t\treturn aliases[0];\n\t} else {\n\t\t// No alias found, pick latest dated version\n\t\tdatedVersions.sort((a, b) => b.id.localeCompare(a.id));\n\t\treturn datedVersions[0];\n\t}\n}\n\nexport interface ParsedModelResult {\n\tmodel: Model | undefined;\n\t/** Thinking level if explicitly specified in pattern, undefined otherwise */\n\tthinkingLevel?: ThinkingLevel;\n\twarning: string | undefined;\n}\n\nfunction buildFallbackModel(provider: string, modelId: string, availableModels: Model[]): Model | undefined {\n\tconst providerModels = availableModels.filter((m) => m.provider === provider);\n\tif (providerModels.length === 0) return undefined;\n\n\tconst defaultId = defaultModelPerProvider[provider as KnownProvider];\n\tconst baseModel = defaultId\n\t\t? (providerModels.find((m) => m.id === defaultId) ?? providerModels[0])\n\t\t: providerModels[0];\n\n\treturn {\n\t\t...baseModel,\n\t\tid: modelId,\n\t\tname: modelId,\n\t};\n}\n\n/**\n * Parse a pattern to extract model and thinking level.\n * Handles models with colons in their IDs (e.g., OpenRouter's :exacto suffix).\n *\n * Algorithm:\n * 1. Try to match full pattern as a model\n * 2. If found, return it with \"off\" thinking level\n * 3. If not found and has colons, split on last colon:\n * - If suffix is valid thinking level, use it and recurse on prefix\n * - If suffix is invalid, warn and recurse on prefix with \"off\"\n *\n * @internal Exported for testing\n */\nexport function parseModelPattern(\n\tpattern: string,\n\tavailableModels: Model[],\n\toptions?: { allowInvalidThinkingLevelFallback?: boolean },\n): ParsedModelResult {\n\t// Try exact match first\n\tconst exactMatch = tryMatchModel(pattern, availableModels);\n\tif (exactMatch) {\n\t\treturn { model: exactMatch, thinkingLevel: undefined, warning: undefined };\n\t}\n\n\t// No match - try splitting on last colon if present\n\tconst lastColonIndex = pattern.lastIndexOf(\":\");\n\tif (lastColonIndex === -1) {\n\t\t// No colons, pattern simply doesn't match any model\n\t\treturn { model: undefined, thinkingLevel: undefined, warning: undefined };\n\t}\n\n\tconst prefix = pattern.substring(0, lastColonIndex);\n\tconst suffix = pattern.substring(lastColonIndex + 1);\n\n\tif (isValidThinkingLevel(suffix)) {\n\t\t// Valid thinking level - recurse on prefix and use this level\n\t\tconst result = parseModelPattern(prefix, availableModels, options);\n\t\tif (result.model) {\n\t\t\t// Only use this thinking level if no warning from inner recursion\n\t\t\treturn {\n\t\t\t\tmodel: result.model,\n\t\t\t\tthinkingLevel: result.warning ? undefined : suffix,\n\t\t\t\twarning: result.warning,\n\t\t\t};\n\t\t}\n\t\treturn result;\n\t} else {\n\t\t// Invalid suffix\n\t\tconst allowFallback = options?.allowInvalidThinkingLevelFallback ?? true;\n\t\tif (!allowFallback) {\n\t\t\t// In strict mode (CLI --model parsing), treat it as part of the model id and fail.\n\t\t\t// This avoids accidentally resolving to a different model.\n\t\t\treturn { model: undefined, thinkingLevel: undefined, warning: undefined };\n\t\t}\n\n\t\t// Scope mode: recurse on prefix and warn\n\t\tconst result = parseModelPattern(prefix, availableModels, options);\n\t\tif (result.model) {\n\t\t\treturn {\n\t\t\t\tmodel: result.model,\n\t\t\t\tthinkingLevel: undefined,\n\t\t\t\twarning: `Invalid thinking level \"${suffix}\" in pattern \"${pattern}\". Using default instead.`,\n\t\t\t};\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Resolve model patterns to actual Model objects with optional thinking levels\n * Format: \"pattern:level\" where :level is optional\n * For each pattern, finds all matching models and picks the best version:\n * 1. Prefer alias (e.g., claude-sonnet-4-5) over dated versions (claude-sonnet-4-5-20250929)\n * 2. If no alias, pick the latest dated version\n *\n * Supports models with colons in their IDs (e.g., OpenRouter's model:exacto).\n * The algorithm tries to match the full pattern first, then progressively\n * strips colon-suffixes to find a match.\n */\nexport interface ModelScopeDiagnostic {\n\ttype: \"warning\";\n\tcode: \"no-match\" | \"invalid-thinking-level\";\n\tmessage: string;\n\tpattern: string;\n}\n\nexport interface ResolveModelScopeResult {\n\tscopedModels: ScopedModel[];\n\tdiagnostics: ModelScopeDiagnostic[];\n}\n\nexport async function resolveModelScopeWithDiagnostics(\n\tpatterns: string[],\n\tmodelRuntime: ModelRuntime,\n): Promise {\n\tconst availableModels = [...(await modelRuntime.getAvailable())];\n\tconst scopedModels: ScopedModel[] = [];\n\tconst diagnostics: ModelScopeDiagnostic[] = [];\n\n\tfor (const pattern of patterns) {\n\t\t// Check if pattern contains glob characters\n\t\tif (pattern.includes(\"*\") || pattern.includes(\"?\") || pattern.includes(\"[\")) {\n\t\t\t// Extract optional thinking level suffix (e.g., \"provider/*:high\")\n\t\t\tconst colonIdx = pattern.lastIndexOf(\":\");\n\t\t\tlet globPattern = pattern;\n\t\t\tlet thinkingLevel: ThinkingLevel | undefined;\n\n\t\t\tif (colonIdx !== -1) {\n\t\t\t\tconst suffix = pattern.substring(colonIdx + 1);\n\t\t\t\tif (isValidThinkingLevel(suffix)) {\n\t\t\t\t\tthinkingLevel = suffix;\n\t\t\t\t\tglobPattern = pattern.substring(0, colonIdx);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst exactMatch = findExactModelReferenceMatch(globPattern, availableModels);\n\t\t\tif (exactMatch) {\n\t\t\t\tif (!scopedModels.find((sm) => modelsAreEqual(sm.model, exactMatch))) {\n\t\t\t\t\tscopedModels.push({ model: exactMatch, thinkingLevel });\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Match against \"provider/modelId\" format OR just model ID\n\t\t\t// This allows \"*sonnet*\" to match without requiring \"anthropic/*sonnet*\"\n\t\t\tconst matchingModels = availableModels.filter((m) => {\n\t\t\t\tconst fullId = `${m.provider}/${m.id}`;\n\t\t\t\treturn minimatch(fullId, globPattern, { nocase: true }) || minimatch(m.id, globPattern, { nocase: true });\n\t\t\t});\n\n\t\t\tif (matchingModels.length === 0) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tcode: \"no-match\",\n\t\t\t\t\tmessage: `No models match pattern \"${pattern}\"`,\n\t\t\t\t\tpattern,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (const model of matchingModels) {\n\t\t\t\tif (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n\t\t\t\t\tscopedModels.push({ model, thinkingLevel });\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst { model, thinkingLevel, warning } = parseModelPattern(pattern, availableModels);\n\n\t\tif (warning) {\n\t\t\tdiagnostics.push({ type: \"warning\", code: \"invalid-thinking-level\", message: warning, pattern });\n\t\t}\n\n\t\tif (!model) {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"no-match\",\n\t\t\t\tmessage: `No models match pattern \"${pattern}\"`,\n\t\t\t\tpattern,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Avoid duplicates\n\t\tif (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n\t\t\tscopedModels.push({ model, thinkingLevel });\n\t\t}\n\t}\n\n\treturn { scopedModels, diagnostics };\n}\n\nexport async function resolveModelScope(patterns: string[], modelRuntime: ModelRuntime): Promise {\n\tconst { scopedModels, diagnostics } = await resolveModelScopeWithDiagnostics(patterns, modelRuntime);\n\tfor (const diagnostic of diagnostics) {\n\t\tconsole.warn(chalk.yellow(`Warning: ${diagnostic.message}`));\n\t}\n\treturn scopedModels;\n}\n\nexport interface ResolveCliModelResult {\n\tmodel: Model | undefined;\n\tthinkingLevel?: ThinkingLevel;\n\twarning: string | undefined;\n\t/**\n\t * Error message suitable for CLI display.\n\t * When set, model will be undefined.\n\t */\n\terror: string | undefined;\n}\n\n/**\n * Resolve a single model from CLI flags.\n *\n * Supports:\n * - --provider --model \n * - --model /\n * - Fuzzy matching (same rules as model scoping: exact id, then partial id/name)\n *\n * Note: This does not apply the thinking level by itself, but it may *parse* and\n * return a thinking level from \":\" so the caller can apply it.\n */\nexport function resolveCliModel(options: {\n\tcliProvider?: string;\n\tcliModel?: string;\n\tcliThinking?: ThinkingLevel;\n\tmodelRuntime: ModelRuntime;\n}): ResolveCliModelResult {\n\tconst { cliProvider, cliModel, cliThinking, modelRuntime } = options;\n\n\tif (!cliModel) {\n\t\treturn { model: undefined, warning: undefined, error: undefined };\n\t}\n\n\t// Important: use *all* models here, not just models with pre-configured auth.\n\t// This allows \"--api-key\" to be used for first-time setup.\n\tconst availableModels = [...modelRuntime.getModels()];\n\tif (availableModels.length === 0) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: \"No models available. Check your installation or add models to models.json.\",\n\t\t};\n\t}\n\n\t// Build canonical provider lookup (case-insensitive)\n\tconst providerMap = new Map();\n\tfor (const m of availableModels) {\n\t\tproviderMap.set(m.provider.toLowerCase(), m.provider);\n\t}\n\n\tlet provider = cliProvider ? providerMap.get(cliProvider.toLowerCase()) : undefined;\n\tif (cliProvider && !provider) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: `Unknown provider \"${cliProvider}\". Use --list-models to see available providers/models.`,\n\t\t};\n\t}\n\n\t// If no explicit --provider, try to interpret \"provider/model\" format first.\n\t// When the prefix before the first slash matches a known provider, prefer that\n\t// interpretation over matching models whose IDs literally contain slashes\n\t// (e.g. \"zai/glm-5\" should resolve to provider=zai, model=glm-5, not to a\n\t// vercel-ai-gateway model with id \"zai/glm-5\").\n\tlet pattern = cliModel;\n\tlet inferredProvider = false;\n\n\tif (!provider) {\n\t\tconst slashIndex = cliModel.indexOf(\"/\");\n\t\tif (slashIndex !== -1) {\n\t\t\tconst maybeProvider = cliModel.substring(0, slashIndex);\n\t\t\tconst canonical = providerMap.get(maybeProvider.toLowerCase());\n\t\t\tif (canonical) {\n\t\t\t\tprovider = canonical;\n\t\t\t\tpattern = cliModel.substring(slashIndex + 1);\n\t\t\t\tinferredProvider = true;\n\t\t\t}\n\t\t}\n\t}\n\n\t// If no provider was inferred from the slash, try exact matches without provider inference.\n\t// This handles models whose IDs naturally contain slashes (e.g. OpenRouter-style IDs).\n\tif (!provider) {\n\t\tconst lower = cliModel.toLowerCase();\n\t\tconst exact = availableModels.find(\n\t\t\t(m) => m.id.toLowerCase() === lower || `${m.provider}/${m.id}`.toLowerCase() === lower,\n\t\t);\n\t\tif (exact) {\n\t\t\treturn { model: exact, warning: undefined, thinkingLevel: undefined, error: undefined };\n\t\t}\n\t}\n\n\tif (cliProvider && provider) {\n\t\t// If both were provided, tolerate --model / by stripping the provider prefix\n\t\tconst prefix = `${provider}/`;\n\t\tif (cliModel.toLowerCase().startsWith(prefix.toLowerCase())) {\n\t\t\tpattern = cliModel.substring(prefix.length);\n\t\t}\n\t}\n\n\tconst candidates = provider ? availableModels.filter((m) => m.provider === provider) : availableModels;\n\tconst { model, thinkingLevel, warning } = parseModelPattern(pattern, candidates, {\n\t\tallowInvalidThinkingLevelFallback: false,\n\t});\n\n\tif (model) {\n\t\t// If provider inference matched an unauthenticated provider/model pair, prefer\n\t\t// one exact raw model-id match that is authenticated. This keeps\n\t\t// \"provider/model\" syntax preferred when usable, but handles models whose\n\t\t// literal id starts with a known provider name (for example\n\t\t// commandcode model id \"xiaomi/mimo-v2.5-pro\").\n\t\tif (inferredProvider) {\n\t\t\tconst rawExactMatches = availableModels.filter(\n\t\t\t\t(m) => m.id.toLowerCase() === cliModel.toLowerCase() && !modelsAreEqual(m, model),\n\t\t\t);\n\t\t\tif (rawExactMatches.length > 0 && !modelRuntime.hasConfiguredAuth(model.provider)) {\n\t\t\t\tconst authenticatedRawMatches = rawExactMatches.filter((m) => modelRuntime.hasConfiguredAuth(m.provider));\n\t\t\t\tif (authenticatedRawMatches.length === 1) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tmodel: authenticatedRawMatches[0],\n\t\t\t\t\t\tthinkingLevel: undefined,\n\t\t\t\t\t\twarning: undefined,\n\t\t\t\t\t\terror: undefined,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn { model, thinkingLevel, warning, error: undefined };\n\t}\n\n\t// If we inferred a provider from the slash but found no match within that provider,\n\t// fall back to matching the full input as a raw model id across all models.\n\t// This handles OpenRouter-style IDs like \"openai/gpt-4o:extended\" where \"openai\"\n\t// looks like a provider but the full string is actually a model id on openrouter.\n\tif (inferredProvider) {\n\t\tconst lower = cliModel.toLowerCase();\n\t\tconst exact = availableModels.find(\n\t\t\t(m) => m.id.toLowerCase() === lower || `${m.provider}/${m.id}`.toLowerCase() === lower,\n\t\t);\n\t\tif (exact) {\n\t\t\treturn { model: exact, warning: undefined, thinkingLevel: undefined, error: undefined };\n\t\t}\n\t\t// Also try parseModelPattern on the full input against all models\n\t\tconst fallback = parseModelPattern(cliModel, availableModels, {\n\t\t\tallowInvalidThinkingLevelFallback: false,\n\t\t});\n\t\tif (fallback.model) {\n\t\t\treturn {\n\t\t\t\tmodel: fallback.model,\n\t\t\t\tthinkingLevel: fallback.thinkingLevel,\n\t\t\t\twarning: fallback.warning,\n\t\t\t\terror: undefined,\n\t\t\t};\n\t\t}\n\t}\n\n\tif (provider) {\n\t\t// Parse thinking level suffix from the pattern before building the fallback model,\n\t\t// but only when --thinking is not explicitly provided.\n\t\t// e.g. \"zai-org/GLM-5.1-FP8:high\" → modelId=\"zai-org/GLM-5.1-FP8\", fallbackThinking=\"high\"\n\t\tlet fallbackPattern = pattern;\n\t\tlet fallbackThinking: ThinkingLevel | undefined;\n\t\tif (!cliThinking) {\n\t\t\tconst lastColon = pattern.lastIndexOf(\":\");\n\t\t\tif (lastColon !== -1) {\n\t\t\t\tconst suffix = pattern.substring(lastColon + 1);\n\t\t\t\tif (isValidThinkingLevel(suffix)) {\n\t\t\t\t\tfallbackPattern = pattern.substring(0, lastColon);\n\t\t\t\t\tfallbackThinking = suffix;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst fallbackModel = buildFallbackModel(provider, fallbackPattern, availableModels);\n\t\tif (fallbackModel) {\n\t\t\tconst requestedThinking = cliThinking ?? fallbackThinking;\n\t\t\tconst model =\n\t\t\t\trequestedThinking && requestedThinking !== \"off\" ? { ...fallbackModel, reasoning: true } : fallbackModel;\n\t\t\tconst fallbackWarning = warning\n\t\t\t\t? `${warning} Model \"${fallbackPattern}\" not found for provider \"${provider}\". Using custom model id.`\n\t\t\t\t: `Model \"${fallbackPattern}\" not found for provider \"${provider}\". Using custom model id.`;\n\t\t\treturn { model, thinkingLevel: fallbackThinking, warning: fallbackWarning, error: undefined };\n\t\t}\n\t}\n\n\tconst display = provider ? `${provider}/${pattern}` : cliModel;\n\treturn {\n\t\tmodel: undefined,\n\t\tthinkingLevel: undefined,\n\t\twarning,\n\t\terror: `Model \"${display}\" not found. Use --list-models to see available models.`,\n\t};\n}\n\nexport interface InitialModelResult {\n\tmodel: Model | undefined;\n\tthinkingLevel: ThinkingLevel;\n\tfallbackMessage: string | undefined;\n}\n\n/**\n * Find the initial model to use based on priority:\n * 1. CLI args (provider + model)\n * 2. First model from scoped models (if not continuing/resuming)\n * 3. Restored from session (if continuing/resuming)\n * 4. Saved default from settings\n * 5. First available model with valid API key\n */\nexport async function findInitialModel(options: {\n\tcliProvider?: string;\n\tcliModel?: string;\n\tscopedModels: ScopedModel[];\n\tisContinuing: boolean;\n\tdefaultProvider?: string;\n\tdefaultModelId?: string;\n\tdefaultThinkingLevel?: ThinkingLevel;\n\tmodelRuntime: ModelRuntime;\n}): Promise {\n\tconst {\n\t\tcliProvider,\n\t\tcliModel,\n\t\tscopedModels,\n\t\tisContinuing,\n\t\tdefaultProvider,\n\t\tdefaultModelId,\n\t\tdefaultThinkingLevel,\n\t\tmodelRuntime,\n\t} = options;\n\n\tlet model: Model | undefined;\n\tlet thinkingLevel: ThinkingLevel = DEFAULT_THINKING_LEVEL;\n\n\t// 1. CLI args take priority\n\tif (cliProvider && cliModel) {\n\t\tconst resolved = resolveCliModel({\n\t\t\tcliProvider,\n\t\t\tcliModel,\n\t\t\tmodelRuntime,\n\t\t});\n\t\tif (resolved.error) {\n\t\t\tconsole.error(chalk.red(resolved.error));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tif (resolved.model) {\n\t\t\treturn { model: resolved.model, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t\t}\n\t}\n\n\t// 2. Use first model from scoped models (skip if continuing/resuming)\n\tif (scopedModels.length > 0 && !isContinuing) {\n\t\treturn {\n\t\t\tmodel: scopedModels[0].model,\n\t\t\tthinkingLevel: scopedModels[0].thinkingLevel ?? defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL,\n\t\t\tfallbackMessage: undefined,\n\t\t};\n\t}\n\n\t// 3. Try saved default from settings if auth is configured.\n\tif (defaultProvider && defaultModelId) {\n\t\tconst found = modelRuntime.getModel(defaultProvider, defaultModelId);\n\t\tif (found && modelRuntime.hasConfiguredAuth(found.provider)) {\n\t\t\tmodel = found;\n\t\t\tif (defaultThinkingLevel) {\n\t\t\t\tthinkingLevel = defaultThinkingLevel;\n\t\t\t}\n\t\t\treturn { model, thinkingLevel, fallbackMessage: undefined };\n\t\t}\n\t}\n\n\t// 4. Try first available model with valid API key\n\tconst availableModels = [...(await modelRuntime.getAvailable())];\n\n\tif (availableModels.length > 0) {\n\t\t// Try to find a default model from known providers\n\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\tconst defaultId = defaultModelPerProvider[provider];\n\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultId);\n\t\t\tif (match) {\n\t\t\t\treturn { model: match, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t\t\t}\n\t\t}\n\n\t\t// If no default found, use first available\n\t\treturn { model: availableModels[0], thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t}\n\n\t// 5. No model found\n\treturn { model: undefined, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n}\n\n/**\n * Restore model from session, with fallback to available models\n */\nexport async function restoreModelFromSession(\n\tsavedProvider: string,\n\tsavedModelId: string,\n\tcurrentModel: Model | undefined,\n\tshouldPrintMessages: boolean,\n\tmodelRuntime: ModelRuntime,\n): Promise<{ model: Model | undefined; fallbackMessage: string | undefined }> {\n\tconst restoredModel = modelRuntime.getModel(savedProvider, savedModelId);\n\n\t// Check if restored model exists and still has auth configured\n\tconst hasConfiguredAuth = restoredModel ? modelRuntime.hasConfiguredAuth(restoredModel.provider) : false;\n\n\tif (restoredModel && hasConfiguredAuth) {\n\t\tif (shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Restored model: ${savedProvider}/${savedModelId}`));\n\t\t}\n\t\treturn { model: restoredModel, fallbackMessage: undefined };\n\t}\n\n\t// Model not found or no API key - fall back\n\tconst reason = !restoredModel ? \"model no longer exists\" : \"no auth configured\";\n\n\tif (shouldPrintMessages) {\n\t\tconsole.error(chalk.yellow(`Warning: Could not restore model ${savedProvider}/${savedModelId} (${reason}).`));\n\t}\n\n\t// If we already have a model, use it as fallback\n\tif (currentModel) {\n\t\tif (shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Falling back to: ${currentModel.provider}/${currentModel.id}`));\n\t\t}\n\t\treturn {\n\t\t\tmodel: currentModel,\n\t\t\tfallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${currentModel.provider}/${currentModel.id}.`,\n\t\t};\n\t}\n\n\t// Try to find any available model\n\tconst availableModels = [...(await modelRuntime.getAvailable())];\n\n\tif (availableModels.length > 0) {\n\t\t// Try to find a default model from known providers\n\t\tlet fallbackModel: Model | undefined;\n\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\tconst defaultId = defaultModelPerProvider[provider];\n\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultId);\n\t\t\tif (match) {\n\t\t\t\tfallbackModel = match;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// If no default found, use first available\n\t\tif (!fallbackModel) {\n\t\t\tfallbackModel = availableModels[0];\n\t\t}\n\n\t\tif (shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Falling back to: ${fallbackModel.provider}/${fallbackModel.id}`));\n\t\t}\n\n\t\treturn {\n\t\t\tmodel: fallbackModel,\n\t\t\tfallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${fallbackModel.provider}/${fallbackModel.id}.`,\n\t\t};\n\t}\n\n\t// No models available\n\treturn { model: undefined, fallbackMessage: undefined };\n}\n"]} \ No newline at end of file diff --git a/dist/core/model-resolver.js b/dist/core/model-resolver.js new file mode 100644 index 0000000..4cd5156 --- /dev/null +++ b/dist/core/model-resolver.js @@ -0,0 +1,551 @@ +/** + * Model resolution, scoping, and initial selection + */ +import { modelsAreEqual } from "@earendil-works/pi-ai"; +import chalk from "chalk"; +import { minimatch } from "minimatch"; +import { isValidThinkingLevel } from "../cli/args.js"; +import { DEFAULT_THINKING_LEVEL } from "./defaults.js"; +/** Default model IDs for each known provider */ +export const defaultModelPerProvider = { + "amazon-bedrock": "us.anthropic.claude-opus-4-6-v1", + "ant-ling": "Ring-2.6-1T", + anthropic: "claude-opus-4-8", + openai: "gpt-5.5", + "azure-openai-responses": "gpt-5.4", + "openai-codex": "gpt-5.5", + radius: "auto", + nvidia: "nvidia/nemotron-3-super-120b-a12b", + deepseek: "deepseek-v4-pro", + google: "gemini-3.1-pro-preview", + "google-vertex": "gemini-3.1-pro-preview", + "github-copilot": "gpt-5.4", + openrouter: "moonshotai/kimi-k2.6", + "vercel-ai-gateway": "zai/glm-5.1", + xai: "grok-4.5", + groq: "openai/gpt-oss-120b", + cerebras: "zai-glm-4.7", + zai: "glm-5.1", + "zai-coding-cn": "glm-5.1", + mistral: "devstral-medium-latest", + minimax: "MiniMax-M2.7", + "minimax-cn": "MiniMax-M2.7", + moonshotai: "kimi-k2.6", + "moonshotai-cn": "kimi-k2.6", + huggingface: "moonshotai/Kimi-K2.6", + fireworks: "accounts/fireworks/models/kimi-k2p6", + together: "moonshotai/Kimi-K2.6", + opencode: "kimi-k2.6", + "opencode-go": "kimi-k2.6", + "kimi-coding": "kimi-for-coding", + "cloudflare-workers-ai": "@cf/moonshotai/kimi-k2.6", + "cloudflare-ai-gateway": "workers-ai/@cf/moonshotai/kimi-k2.6", + "qwen-token-plan": "qwen3.7-max", + "qwen-token-plan-cn": "qwen3.7-max", + xiaomi: "mimo-v2.5-pro", + "xiaomi-token-plan-cn": "mimo-v2.5-pro", + "xiaomi-token-plan-ams": "mimo-v2.5-pro", + "xiaomi-token-plan-sgp": "mimo-v2.5-pro", +}; +/** + * Helper to check if a model ID looks like an alias (no date suffix) + * Dates are typically in format: -20241022 or -20250929 + */ +function isAlias(id) { + // Check if ID ends with -latest + if (id.endsWith("-latest")) + return true; + // Check if ID ends with a date pattern (-YYYYMMDD) + const datePattern = /-\d{8}$/; + return !datePattern.test(id); +} +/** + * Find an exact model reference match. + * Supports either a bare model id or a canonical provider/modelId reference. + * When matching by bare id, ambiguous matches across providers are rejected. + */ +export function findExactModelReferenceMatch(modelReference, availableModels) { + const trimmedReference = modelReference.trim(); + if (!trimmedReference) { + return undefined; + } + const normalizedReference = trimmedReference.toLowerCase(); + const canonicalMatches = availableModels.filter((model) => `${model.provider}/${model.id}`.toLowerCase() === normalizedReference); + if (canonicalMatches.length === 1) { + return canonicalMatches[0]; + } + if (canonicalMatches.length > 1) { + return undefined; + } + const slashIndex = trimmedReference.indexOf("/"); + if (slashIndex !== -1) { + const provider = trimmedReference.substring(0, slashIndex).trim(); + const modelId = trimmedReference.substring(slashIndex + 1).trim(); + if (provider && modelId) { + const providerMatches = availableModels.filter((model) => model.provider.toLowerCase() === provider.toLowerCase() && + model.id.toLowerCase() === modelId.toLowerCase()); + if (providerMatches.length === 1) { + return providerMatches[0]; + } + if (providerMatches.length > 1) { + return undefined; + } + } + } + const idMatches = availableModels.filter((model) => model.id.toLowerCase() === normalizedReference); + return idMatches.length === 1 ? idMatches[0] : undefined; +} +/** + * Try to match a pattern to a model from the available models list. + * Returns the matched model or undefined if no match found. + */ +function tryMatchModel(modelPattern, availableModels) { + const exactMatch = findExactModelReferenceMatch(modelPattern, availableModels); + if (exactMatch) { + return exactMatch; + } + // No exact match - fall back to partial matching + const matches = availableModels.filter((m) => m.id.toLowerCase().includes(modelPattern.toLowerCase()) || + m.name?.toLowerCase().includes(modelPattern.toLowerCase())); + if (matches.length === 0) { + return undefined; + } + // Separate into aliases and dated versions + const aliases = matches.filter((m) => isAlias(m.id)); + const datedVersions = matches.filter((m) => !isAlias(m.id)); + if (aliases.length > 0) { + // Prefer alias - if multiple aliases, pick the one that sorts highest + aliases.sort((a, b) => b.id.localeCompare(a.id)); + return aliases[0]; + } + else { + // No alias found, pick latest dated version + datedVersions.sort((a, b) => b.id.localeCompare(a.id)); + return datedVersions[0]; + } +} +function buildFallbackModel(provider, modelId, availableModels) { + const providerModels = availableModels.filter((m) => m.provider === provider); + if (providerModels.length === 0) + return undefined; + const defaultId = defaultModelPerProvider[provider]; + const baseModel = defaultId + ? (providerModels.find((m) => m.id === defaultId) ?? providerModels[0]) + : providerModels[0]; + return { + ...baseModel, + id: modelId, + name: modelId, + }; +} +/** + * Parse a pattern to extract model and thinking level. + * Handles models with colons in their IDs (e.g., OpenRouter's :exacto suffix). + * + * Algorithm: + * 1. Try to match full pattern as a model + * 2. If found, return it with "off" thinking level + * 3. If not found and has colons, split on last colon: + * - If suffix is valid thinking level, use it and recurse on prefix + * - If suffix is invalid, warn and recurse on prefix with "off" + * + * @internal Exported for testing + */ +export function parseModelPattern(pattern, availableModels, options) { + // Try exact match first + const exactMatch = tryMatchModel(pattern, availableModels); + if (exactMatch) { + return { model: exactMatch, thinkingLevel: undefined, warning: undefined }; + } + // No match - try splitting on last colon if present + const lastColonIndex = pattern.lastIndexOf(":"); + if (lastColonIndex === -1) { + // No colons, pattern simply doesn't match any model + return { model: undefined, thinkingLevel: undefined, warning: undefined }; + } + const prefix = pattern.substring(0, lastColonIndex); + const suffix = pattern.substring(lastColonIndex + 1); + if (isValidThinkingLevel(suffix)) { + // Valid thinking level - recurse on prefix and use this level + const result = parseModelPattern(prefix, availableModels, options); + if (result.model) { + // Only use this thinking level if no warning from inner recursion + return { + model: result.model, + thinkingLevel: result.warning ? undefined : suffix, + warning: result.warning, + }; + } + return result; + } + else { + // Invalid suffix + const allowFallback = options?.allowInvalidThinkingLevelFallback ?? true; + if (!allowFallback) { + // In strict mode (CLI --model parsing), treat it as part of the model id and fail. + // This avoids accidentally resolving to a different model. + return { model: undefined, thinkingLevel: undefined, warning: undefined }; + } + // Scope mode: recurse on prefix and warn + const result = parseModelPattern(prefix, availableModels, options); + if (result.model) { + return { + model: result.model, + thinkingLevel: undefined, + warning: `Invalid thinking level "${suffix}" in pattern "${pattern}". Using default instead.`, + }; + } + return result; + } +} +export async function resolveModelScopeWithDiagnostics(patterns, modelRuntime) { + const availableModels = [...(await modelRuntime.getAvailable())]; + const scopedModels = []; + const diagnostics = []; + for (const pattern of patterns) { + // Check if pattern contains glob characters + if (pattern.includes("*") || pattern.includes("?") || pattern.includes("[")) { + // Extract optional thinking level suffix (e.g., "provider/*:high") + const colonIdx = pattern.lastIndexOf(":"); + let globPattern = pattern; + let thinkingLevel; + if (colonIdx !== -1) { + const suffix = pattern.substring(colonIdx + 1); + if (isValidThinkingLevel(suffix)) { + thinkingLevel = suffix; + globPattern = pattern.substring(0, colonIdx); + } + } + const exactMatch = findExactModelReferenceMatch(globPattern, availableModels); + if (exactMatch) { + if (!scopedModels.find((sm) => modelsAreEqual(sm.model, exactMatch))) { + scopedModels.push({ model: exactMatch, thinkingLevel }); + } + continue; + } + // Match against "provider/modelId" format OR just model ID + // This allows "*sonnet*" to match without requiring "anthropic/*sonnet*" + const matchingModels = availableModels.filter((m) => { + const fullId = `${m.provider}/${m.id}`; + return minimatch(fullId, globPattern, { nocase: true }) || minimatch(m.id, globPattern, { nocase: true }); + }); + if (matchingModels.length === 0) { + diagnostics.push({ + type: "warning", + code: "no-match", + message: `No models match pattern "${pattern}"`, + pattern, + }); + continue; + } + for (const model of matchingModels) { + if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) { + scopedModels.push({ model, thinkingLevel }); + } + } + continue; + } + const { model, thinkingLevel, warning } = parseModelPattern(pattern, availableModels); + if (warning) { + diagnostics.push({ type: "warning", code: "invalid-thinking-level", message: warning, pattern }); + } + if (!model) { + diagnostics.push({ + type: "warning", + code: "no-match", + message: `No models match pattern "${pattern}"`, + pattern, + }); + continue; + } + // Avoid duplicates + if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) { + scopedModels.push({ model, thinkingLevel }); + } + } + return { scopedModels, diagnostics }; +} +export async function resolveModelScope(patterns, modelRuntime) { + const { scopedModels, diagnostics } = await resolveModelScopeWithDiagnostics(patterns, modelRuntime); + for (const diagnostic of diagnostics) { + console.warn(chalk.yellow(`Warning: ${diagnostic.message}`)); + } + return scopedModels; +} +/** + * Resolve a single model from CLI flags. + * + * Supports: + * - --provider --model + * - --model / + * - Fuzzy matching (same rules as model scoping: exact id, then partial id/name) + * + * Note: This does not apply the thinking level by itself, but it may *parse* and + * return a thinking level from ":" so the caller can apply it. + */ +export function resolveCliModel(options) { + const { cliProvider, cliModel, cliThinking, modelRuntime } = options; + if (!cliModel) { + return { model: undefined, warning: undefined, error: undefined }; + } + // Important: use *all* models here, not just models with pre-configured auth. + // This allows "--api-key" to be used for first-time setup. + const availableModels = [...modelRuntime.getModels()]; + if (availableModels.length === 0) { + return { + model: undefined, + warning: undefined, + error: "No models available. Check your installation or add models to models.json.", + }; + } + // Build canonical provider lookup (case-insensitive) + const providerMap = new Map(); + for (const m of availableModels) { + providerMap.set(m.provider.toLowerCase(), m.provider); + } + let provider = cliProvider ? providerMap.get(cliProvider.toLowerCase()) : undefined; + if (cliProvider && !provider) { + return { + model: undefined, + warning: undefined, + error: `Unknown provider "${cliProvider}". Use --list-models to see available providers/models.`, + }; + } + // If no explicit --provider, try to interpret "provider/model" format first. + // When the prefix before the first slash matches a known provider, prefer that + // interpretation over matching models whose IDs literally contain slashes + // (e.g. "zai/glm-5" should resolve to provider=zai, model=glm-5, not to a + // vercel-ai-gateway model with id "zai/glm-5"). + let pattern = cliModel; + let inferredProvider = false; + if (!provider) { + const slashIndex = cliModel.indexOf("/"); + if (slashIndex !== -1) { + const maybeProvider = cliModel.substring(0, slashIndex); + const canonical = providerMap.get(maybeProvider.toLowerCase()); + if (canonical) { + provider = canonical; + pattern = cliModel.substring(slashIndex + 1); + inferredProvider = true; + } + } + } + // If no provider was inferred from the slash, try exact matches without provider inference. + // This handles models whose IDs naturally contain slashes (e.g. OpenRouter-style IDs). + if (!provider) { + const lower = cliModel.toLowerCase(); + const exact = availableModels.find((m) => m.id.toLowerCase() === lower || `${m.provider}/${m.id}`.toLowerCase() === lower); + if (exact) { + return { model: exact, warning: undefined, thinkingLevel: undefined, error: undefined }; + } + } + if (cliProvider && provider) { + // If both were provided, tolerate --model / by stripping the provider prefix + const prefix = `${provider}/`; + if (cliModel.toLowerCase().startsWith(prefix.toLowerCase())) { + pattern = cliModel.substring(prefix.length); + } + } + const candidates = provider ? availableModels.filter((m) => m.provider === provider) : availableModels; + const { model, thinkingLevel, warning } = parseModelPattern(pattern, candidates, { + allowInvalidThinkingLevelFallback: false, + }); + if (model) { + // If provider inference matched an unauthenticated provider/model pair, prefer + // one exact raw model-id match that is authenticated. This keeps + // "provider/model" syntax preferred when usable, but handles models whose + // literal id starts with a known provider name (for example + // commandcode model id "xiaomi/mimo-v2.5-pro"). + if (inferredProvider) { + const rawExactMatches = availableModels.filter((m) => m.id.toLowerCase() === cliModel.toLowerCase() && !modelsAreEqual(m, model)); + if (rawExactMatches.length > 0 && !modelRuntime.hasConfiguredAuth(model.provider)) { + const authenticatedRawMatches = rawExactMatches.filter((m) => modelRuntime.hasConfiguredAuth(m.provider)); + if (authenticatedRawMatches.length === 1) { + return { + model: authenticatedRawMatches[0], + thinkingLevel: undefined, + warning: undefined, + error: undefined, + }; + } + } + } + return { model, thinkingLevel, warning, error: undefined }; + } + // If we inferred a provider from the slash but found no match within that provider, + // fall back to matching the full input as a raw model id across all models. + // This handles OpenRouter-style IDs like "openai/gpt-4o:extended" where "openai" + // looks like a provider but the full string is actually a model id on openrouter. + if (inferredProvider) { + const lower = cliModel.toLowerCase(); + const exact = availableModels.find((m) => m.id.toLowerCase() === lower || `${m.provider}/${m.id}`.toLowerCase() === lower); + if (exact) { + return { model: exact, warning: undefined, thinkingLevel: undefined, error: undefined }; + } + // Also try parseModelPattern on the full input against all models + const fallback = parseModelPattern(cliModel, availableModels, { + allowInvalidThinkingLevelFallback: false, + }); + if (fallback.model) { + return { + model: fallback.model, + thinkingLevel: fallback.thinkingLevel, + warning: fallback.warning, + error: undefined, + }; + } + } + if (provider) { + // Parse thinking level suffix from the pattern before building the fallback model, + // but only when --thinking is not explicitly provided. + // e.g. "zai-org/GLM-5.1-FP8:high" → modelId="zai-org/GLM-5.1-FP8", fallbackThinking="high" + let fallbackPattern = pattern; + let fallbackThinking; + if (!cliThinking) { + const lastColon = pattern.lastIndexOf(":"); + if (lastColon !== -1) { + const suffix = pattern.substring(lastColon + 1); + if (isValidThinkingLevel(suffix)) { + fallbackPattern = pattern.substring(0, lastColon); + fallbackThinking = suffix; + } + } + } + const fallbackModel = buildFallbackModel(provider, fallbackPattern, availableModels); + if (fallbackModel) { + const requestedThinking = cliThinking ?? fallbackThinking; + const model = requestedThinking && requestedThinking !== "off" ? { ...fallbackModel, reasoning: true } : fallbackModel; + const fallbackWarning = warning + ? `${warning} Model "${fallbackPattern}" not found for provider "${provider}". Using custom model id.` + : `Model "${fallbackPattern}" not found for provider "${provider}". Using custom model id.`; + return { model, thinkingLevel: fallbackThinking, warning: fallbackWarning, error: undefined }; + } + } + const display = provider ? `${provider}/${pattern}` : cliModel; + return { + model: undefined, + thinkingLevel: undefined, + warning, + error: `Model "${display}" not found. Use --list-models to see available models.`, + }; +} +/** + * Find the initial model to use based on priority: + * 1. CLI args (provider + model) + * 2. First model from scoped models (if not continuing/resuming) + * 3. Restored from session (if continuing/resuming) + * 4. Saved default from settings + * 5. First available model with valid API key + */ +export async function findInitialModel(options) { + const { cliProvider, cliModel, scopedModels, isContinuing, defaultProvider, defaultModelId, defaultThinkingLevel, modelRuntime, } = options; + let model; + let thinkingLevel = DEFAULT_THINKING_LEVEL; + // 1. CLI args take priority + if (cliProvider && cliModel) { + const resolved = resolveCliModel({ + cliProvider, + cliModel, + modelRuntime, + }); + if (resolved.error) { + console.error(chalk.red(resolved.error)); + process.exit(1); + } + if (resolved.model) { + return { model: resolved.model, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined }; + } + } + // 2. Use first model from scoped models (skip if continuing/resuming) + if (scopedModels.length > 0 && !isContinuing) { + return { + model: scopedModels[0].model, + thinkingLevel: scopedModels[0].thinkingLevel ?? defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL, + fallbackMessage: undefined, + }; + } + // 3. Try saved default from settings if auth is configured. + if (defaultProvider && defaultModelId) { + const found = modelRuntime.getModel(defaultProvider, defaultModelId); + if (found && modelRuntime.hasConfiguredAuth(found.provider)) { + model = found; + if (defaultThinkingLevel) { + thinkingLevel = defaultThinkingLevel; + } + return { model, thinkingLevel, fallbackMessage: undefined }; + } + } + // 4. Try first available model with valid API key + const availableModels = [...(await modelRuntime.getAvailable())]; + if (availableModels.length > 0) { + // Try to find a default model from known providers + for (const provider of Object.keys(defaultModelPerProvider)) { + const defaultId = defaultModelPerProvider[provider]; + const match = availableModels.find((m) => m.provider === provider && m.id === defaultId); + if (match) { + return { model: match, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined }; + } + } + // If no default found, use first available + return { model: availableModels[0], thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined }; + } + // 5. No model found + return { model: undefined, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined }; +} +/** + * Restore model from session, with fallback to available models + */ +export async function restoreModelFromSession(savedProvider, savedModelId, currentModel, shouldPrintMessages, modelRuntime) { + const restoredModel = modelRuntime.getModel(savedProvider, savedModelId); + // Check if restored model exists and still has auth configured + const hasConfiguredAuth = restoredModel ? modelRuntime.hasConfiguredAuth(restoredModel.provider) : false; + if (restoredModel && hasConfiguredAuth) { + if (shouldPrintMessages) { + console.log(chalk.dim(`Restored model: ${savedProvider}/${savedModelId}`)); + } + return { model: restoredModel, fallbackMessage: undefined }; + } + // Model not found or no API key - fall back + const reason = !restoredModel ? "model no longer exists" : "no auth configured"; + if (shouldPrintMessages) { + console.error(chalk.yellow(`Warning: Could not restore model ${savedProvider}/${savedModelId} (${reason}).`)); + } + // If we already have a model, use it as fallback + if (currentModel) { + if (shouldPrintMessages) { + console.log(chalk.dim(`Falling back to: ${currentModel.provider}/${currentModel.id}`)); + } + return { + model: currentModel, + fallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${currentModel.provider}/${currentModel.id}.`, + }; + } + // Try to find any available model + const availableModels = [...(await modelRuntime.getAvailable())]; + if (availableModels.length > 0) { + // Try to find a default model from known providers + let fallbackModel; + for (const provider of Object.keys(defaultModelPerProvider)) { + const defaultId = defaultModelPerProvider[provider]; + const match = availableModels.find((m) => m.provider === provider && m.id === defaultId); + if (match) { + fallbackModel = match; + break; + } + } + // If no default found, use first available + if (!fallbackModel) { + fallbackModel = availableModels[0]; + } + if (shouldPrintMessages) { + console.log(chalk.dim(`Falling back to: ${fallbackModel.provider}/${fallbackModel.id}`)); + } + return { + model: fallbackModel, + fallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${fallbackModel.provider}/${fallbackModel.id}.`, + }; + } + // No models available + return { model: undefined, fallbackMessage: undefined }; +} +//# sourceMappingURL=model-resolver.js.map \ No newline at end of file diff --git a/dist/core/model-resolver.js.map b/dist/core/model-resolver.js.map new file mode 100644 index 0000000..5ca7add --- /dev/null +++ b/dist/core/model-resolver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"model-resolver.js","sourceRoot":"","sources":["../../src/core/model-resolver.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAA4C,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACjG,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAA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,CAAC,oBAAoB,aAAa,CAAC,QAAQ,IAAI,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;QAC1F,CAAC;QAED,OAAO;YACN,KAAK,EAAE,aAAa;YACpB,eAAe,EAAE,2BAA2B,aAAa,IAAI,YAAY,KAAK,MAAM,YAAY,aAAa,CAAC,QAAQ,IAAI,aAAa,CAAC,EAAE,GAAG;SAC7I,CAAC;IACH,CAAC;IAED,sBAAsB;IACtB,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;AAAA,CACxD","sourcesContent":["/**\n * Model resolution, scoping, and initial selection\n */\n\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { type Api, type KnownProvider, type Model, modelsAreEqual } from \"@earendil-works/pi-ai\";\nimport chalk from \"chalk\";\nimport { minimatch } from \"minimatch\";\nimport { isValidThinkingLevel } from \"../cli/args.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\n\n/** Default model IDs for each known provider */\nexport const defaultModelPerProvider: Record = {\n\t\"amazon-bedrock\": \"us.anthropic.claude-opus-4-6-v1\",\n\t\"ant-ling\": \"Ring-2.6-1T\",\n\tanthropic: \"claude-opus-4-8\",\n\topenai: \"gpt-5.5\",\n\t\"azure-openai-responses\": \"gpt-5.4\",\n\t\"openai-codex\": \"gpt-5.5\",\n\tradius: \"auto\",\n\tnvidia: \"nvidia/nemotron-3-super-120b-a12b\",\n\tdeepseek: \"deepseek-v4-pro\",\n\tgoogle: \"gemini-3.1-pro-preview\",\n\t\"google-vertex\": \"gemini-3.1-pro-preview\",\n\t\"github-copilot\": \"gpt-5.4\",\n\topenrouter: \"moonshotai/kimi-k2.6\",\n\t\"vercel-ai-gateway\": \"zai/glm-5.1\",\n\txai: \"grok-4.5\",\n\tgroq: \"openai/gpt-oss-120b\",\n\tcerebras: \"zai-glm-4.7\",\n\tzai: \"glm-5.1\",\n\t\"zai-coding-cn\": \"glm-5.1\",\n\tmistral: \"devstral-medium-latest\",\n\tminimax: \"MiniMax-M2.7\",\n\t\"minimax-cn\": \"MiniMax-M2.7\",\n\tmoonshotai: \"kimi-k2.6\",\n\t\"moonshotai-cn\": \"kimi-k2.6\",\n\thuggingface: \"moonshotai/Kimi-K2.6\",\n\tfireworks: \"accounts/fireworks/models/kimi-k2p6\",\n\ttogether: \"moonshotai/Kimi-K2.6\",\n\topencode: \"kimi-k2.6\",\n\t\"opencode-go\": \"kimi-k2.6\",\n\t\"kimi-coding\": \"kimi-for-coding\",\n\t\"cloudflare-workers-ai\": \"@cf/moonshotai/kimi-k2.6\",\n\t\"cloudflare-ai-gateway\": \"workers-ai/@cf/moonshotai/kimi-k2.6\",\n\t\"qwen-token-plan\": \"qwen3.7-max\",\n\t\"qwen-token-plan-cn\": \"qwen3.7-max\",\n\txiaomi: \"mimo-v2.5-pro\",\n\t\"xiaomi-token-plan-cn\": \"mimo-v2.5-pro\",\n\t\"xiaomi-token-plan-ams\": \"mimo-v2.5-pro\",\n\t\"xiaomi-token-plan-sgp\": \"mimo-v2.5-pro\",\n};\n\nexport interface ScopedModel {\n\tmodel: Model;\n\t/** Thinking level if explicitly specified in pattern (e.g., \"model:high\"), undefined otherwise */\n\tthinkingLevel?: ThinkingLevel;\n}\n\n/**\n * Helper to check if a model ID looks like an alias (no date suffix)\n * Dates are typically in format: -20241022 or -20250929\n */\nfunction isAlias(id: string): boolean {\n\t// Check if ID ends with -latest\n\tif (id.endsWith(\"-latest\")) return true;\n\n\t// Check if ID ends with a date pattern (-YYYYMMDD)\n\tconst datePattern = /-\\d{8}$/;\n\treturn !datePattern.test(id);\n}\n\n/**\n * Find an exact model reference match.\n * Supports either a bare model id or a canonical provider/modelId reference.\n * When matching by bare id, ambiguous matches across providers are rejected.\n */\nexport function findExactModelReferenceMatch(\n\tmodelReference: string,\n\tavailableModels: Model[],\n): Model | undefined {\n\tconst trimmedReference = modelReference.trim();\n\tif (!trimmedReference) {\n\t\treturn undefined;\n\t}\n\n\tconst normalizedReference = trimmedReference.toLowerCase();\n\n\tconst canonicalMatches = availableModels.filter(\n\t\t(model) => `${model.provider}/${model.id}`.toLowerCase() === normalizedReference,\n\t);\n\tif (canonicalMatches.length === 1) {\n\t\treturn canonicalMatches[0];\n\t}\n\tif (canonicalMatches.length > 1) {\n\t\treturn undefined;\n\t}\n\n\tconst slashIndex = trimmedReference.indexOf(\"/\");\n\tif (slashIndex !== -1) {\n\t\tconst provider = trimmedReference.substring(0, slashIndex).trim();\n\t\tconst modelId = trimmedReference.substring(slashIndex + 1).trim();\n\t\tif (provider && modelId) {\n\t\t\tconst providerMatches = availableModels.filter(\n\t\t\t\t(model) =>\n\t\t\t\t\tmodel.provider.toLowerCase() === provider.toLowerCase() &&\n\t\t\t\t\tmodel.id.toLowerCase() === modelId.toLowerCase(),\n\t\t\t);\n\t\t\tif (providerMatches.length === 1) {\n\t\t\t\treturn providerMatches[0];\n\t\t\t}\n\t\t\tif (providerMatches.length > 1) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst idMatches = availableModels.filter((model) => model.id.toLowerCase() === normalizedReference);\n\treturn idMatches.length === 1 ? idMatches[0] : undefined;\n}\n\n/**\n * Try to match a pattern to a model from the available models list.\n * Returns the matched model or undefined if no match found.\n */\nfunction tryMatchModel(modelPattern: string, availableModels: Model[]): Model | undefined {\n\tconst exactMatch = findExactModelReferenceMatch(modelPattern, availableModels);\n\tif (exactMatch) {\n\t\treturn exactMatch;\n\t}\n\n\t// No exact match - fall back to partial matching\n\tconst matches = availableModels.filter(\n\t\t(m) =>\n\t\t\tm.id.toLowerCase().includes(modelPattern.toLowerCase()) ||\n\t\t\tm.name?.toLowerCase().includes(modelPattern.toLowerCase()),\n\t);\n\n\tif (matches.length === 0) {\n\t\treturn undefined;\n\t}\n\n\t// Separate into aliases and dated versions\n\tconst aliases = matches.filter((m) => isAlias(m.id));\n\tconst datedVersions = matches.filter((m) => !isAlias(m.id));\n\n\tif (aliases.length > 0) {\n\t\t// Prefer alias - if multiple aliases, pick the one that sorts highest\n\t\taliases.sort((a, b) => b.id.localeCompare(a.id));\n\t\treturn aliases[0];\n\t} else {\n\t\t// No alias found, pick latest dated version\n\t\tdatedVersions.sort((a, b) => b.id.localeCompare(a.id));\n\t\treturn datedVersions[0];\n\t}\n}\n\nexport interface ParsedModelResult {\n\tmodel: Model | undefined;\n\t/** Thinking level if explicitly specified in pattern, undefined otherwise */\n\tthinkingLevel?: ThinkingLevel;\n\twarning: string | undefined;\n}\n\nfunction buildFallbackModel(provider: string, modelId: string, availableModels: Model[]): Model | undefined {\n\tconst providerModels = availableModels.filter((m) => m.provider === provider);\n\tif (providerModels.length === 0) return undefined;\n\n\tconst defaultId = defaultModelPerProvider[provider as KnownProvider];\n\tconst baseModel = defaultId\n\t\t? (providerModels.find((m) => m.id === defaultId) ?? providerModels[0])\n\t\t: providerModels[0];\n\n\treturn {\n\t\t...baseModel,\n\t\tid: modelId,\n\t\tname: modelId,\n\t};\n}\n\n/**\n * Parse a pattern to extract model and thinking level.\n * Handles models with colons in their IDs (e.g., OpenRouter's :exacto suffix).\n *\n * Algorithm:\n * 1. Try to match full pattern as a model\n * 2. If found, return it with \"off\" thinking level\n * 3. If not found and has colons, split on last colon:\n * - If suffix is valid thinking level, use it and recurse on prefix\n * - If suffix is invalid, warn and recurse on prefix with \"off\"\n *\n * @internal Exported for testing\n */\nexport function parseModelPattern(\n\tpattern: string,\n\tavailableModels: Model[],\n\toptions?: { allowInvalidThinkingLevelFallback?: boolean },\n): ParsedModelResult {\n\t// Try exact match first\n\tconst exactMatch = tryMatchModel(pattern, availableModels);\n\tif (exactMatch) {\n\t\treturn { model: exactMatch, thinkingLevel: undefined, warning: undefined };\n\t}\n\n\t// No match - try splitting on last colon if present\n\tconst lastColonIndex = pattern.lastIndexOf(\":\");\n\tif (lastColonIndex === -1) {\n\t\t// No colons, pattern simply doesn't match any model\n\t\treturn { model: undefined, thinkingLevel: undefined, warning: undefined };\n\t}\n\n\tconst prefix = pattern.substring(0, lastColonIndex);\n\tconst suffix = pattern.substring(lastColonIndex + 1);\n\n\tif (isValidThinkingLevel(suffix)) {\n\t\t// Valid thinking level - recurse on prefix and use this level\n\t\tconst result = parseModelPattern(prefix, availableModels, options);\n\t\tif (result.model) {\n\t\t\t// Only use this thinking level if no warning from inner recursion\n\t\t\treturn {\n\t\t\t\tmodel: result.model,\n\t\t\t\tthinkingLevel: result.warning ? undefined : suffix,\n\t\t\t\twarning: result.warning,\n\t\t\t};\n\t\t}\n\t\treturn result;\n\t} else {\n\t\t// Invalid suffix\n\t\tconst allowFallback = options?.allowInvalidThinkingLevelFallback ?? true;\n\t\tif (!allowFallback) {\n\t\t\t// In strict mode (CLI --model parsing), treat it as part of the model id and fail.\n\t\t\t// This avoids accidentally resolving to a different model.\n\t\t\treturn { model: undefined, thinkingLevel: undefined, warning: undefined };\n\t\t}\n\n\t\t// Scope mode: recurse on prefix and warn\n\t\tconst result = parseModelPattern(prefix, availableModels, options);\n\t\tif (result.model) {\n\t\t\treturn {\n\t\t\t\tmodel: result.model,\n\t\t\t\tthinkingLevel: undefined,\n\t\t\t\twarning: `Invalid thinking level \"${suffix}\" in pattern \"${pattern}\". Using default instead.`,\n\t\t\t};\n\t\t}\n\t\treturn result;\n\t}\n}\n\n/**\n * Resolve model patterns to actual Model objects with optional thinking levels\n * Format: \"pattern:level\" where :level is optional\n * For each pattern, finds all matching models and picks the best version:\n * 1. Prefer alias (e.g., claude-sonnet-4-5) over dated versions (claude-sonnet-4-5-20250929)\n * 2. If no alias, pick the latest dated version\n *\n * Supports models with colons in their IDs (e.g., OpenRouter's model:exacto).\n * The algorithm tries to match the full pattern first, then progressively\n * strips colon-suffixes to find a match.\n */\nexport interface ModelScopeDiagnostic {\n\ttype: \"warning\";\n\tcode: \"no-match\" | \"invalid-thinking-level\";\n\tmessage: string;\n\tpattern: string;\n}\n\nexport interface ResolveModelScopeResult {\n\tscopedModels: ScopedModel[];\n\tdiagnostics: ModelScopeDiagnostic[];\n}\n\nexport async function resolveModelScopeWithDiagnostics(\n\tpatterns: string[],\n\tmodelRuntime: ModelRuntime,\n): Promise {\n\tconst availableModels = [...(await modelRuntime.getAvailable())];\n\tconst scopedModels: ScopedModel[] = [];\n\tconst diagnostics: ModelScopeDiagnostic[] = [];\n\n\tfor (const pattern of patterns) {\n\t\t// Check if pattern contains glob characters\n\t\tif (pattern.includes(\"*\") || pattern.includes(\"?\") || pattern.includes(\"[\")) {\n\t\t\t// Extract optional thinking level suffix (e.g., \"provider/*:high\")\n\t\t\tconst colonIdx = pattern.lastIndexOf(\":\");\n\t\t\tlet globPattern = pattern;\n\t\t\tlet thinkingLevel: ThinkingLevel | undefined;\n\n\t\t\tif (colonIdx !== -1) {\n\t\t\t\tconst suffix = pattern.substring(colonIdx + 1);\n\t\t\t\tif (isValidThinkingLevel(suffix)) {\n\t\t\t\t\tthinkingLevel = suffix;\n\t\t\t\t\tglobPattern = pattern.substring(0, colonIdx);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst exactMatch = findExactModelReferenceMatch(globPattern, availableModels);\n\t\t\tif (exactMatch) {\n\t\t\t\tif (!scopedModels.find((sm) => modelsAreEqual(sm.model, exactMatch))) {\n\t\t\t\t\tscopedModels.push({ model: exactMatch, thinkingLevel });\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Match against \"provider/modelId\" format OR just model ID\n\t\t\t// This allows \"*sonnet*\" to match without requiring \"anthropic/*sonnet*\"\n\t\t\tconst matchingModels = availableModels.filter((m) => {\n\t\t\t\tconst fullId = `${m.provider}/${m.id}`;\n\t\t\t\treturn minimatch(fullId, globPattern, { nocase: true }) || minimatch(m.id, globPattern, { nocase: true });\n\t\t\t});\n\n\t\t\tif (matchingModels.length === 0) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tcode: \"no-match\",\n\t\t\t\t\tmessage: `No models match pattern \"${pattern}\"`,\n\t\t\t\t\tpattern,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (const model of matchingModels) {\n\t\t\t\tif (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n\t\t\t\t\tscopedModels.push({ model, thinkingLevel });\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst { model, thinkingLevel, warning } = parseModelPattern(pattern, availableModels);\n\n\t\tif (warning) {\n\t\t\tdiagnostics.push({ type: \"warning\", code: \"invalid-thinking-level\", message: warning, pattern });\n\t\t}\n\n\t\tif (!model) {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tcode: \"no-match\",\n\t\t\t\tmessage: `No models match pattern \"${pattern}\"`,\n\t\t\t\tpattern,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Avoid duplicates\n\t\tif (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {\n\t\t\tscopedModels.push({ model, thinkingLevel });\n\t\t}\n\t}\n\n\treturn { scopedModels, diagnostics };\n}\n\nexport async function resolveModelScope(patterns: string[], modelRuntime: ModelRuntime): Promise {\n\tconst { scopedModels, diagnostics } = await resolveModelScopeWithDiagnostics(patterns, modelRuntime);\n\tfor (const diagnostic of diagnostics) {\n\t\tconsole.warn(chalk.yellow(`Warning: ${diagnostic.message}`));\n\t}\n\treturn scopedModels;\n}\n\nexport interface ResolveCliModelResult {\n\tmodel: Model | undefined;\n\tthinkingLevel?: ThinkingLevel;\n\twarning: string | undefined;\n\t/**\n\t * Error message suitable for CLI display.\n\t * When set, model will be undefined.\n\t */\n\terror: string | undefined;\n}\n\n/**\n * Resolve a single model from CLI flags.\n *\n * Supports:\n * - --provider --model \n * - --model /\n * - Fuzzy matching (same rules as model scoping: exact id, then partial id/name)\n *\n * Note: This does not apply the thinking level by itself, but it may *parse* and\n * return a thinking level from \":\" so the caller can apply it.\n */\nexport function resolveCliModel(options: {\n\tcliProvider?: string;\n\tcliModel?: string;\n\tcliThinking?: ThinkingLevel;\n\tmodelRuntime: ModelRuntime;\n}): ResolveCliModelResult {\n\tconst { cliProvider, cliModel, cliThinking, modelRuntime } = options;\n\n\tif (!cliModel) {\n\t\treturn { model: undefined, warning: undefined, error: undefined };\n\t}\n\n\t// Important: use *all* models here, not just models with pre-configured auth.\n\t// This allows \"--api-key\" to be used for first-time setup.\n\tconst availableModels = [...modelRuntime.getModels()];\n\tif (availableModels.length === 0) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: \"No models available. Check your installation or add models to models.json.\",\n\t\t};\n\t}\n\n\t// Build canonical provider lookup (case-insensitive)\n\tconst providerMap = new Map();\n\tfor (const m of availableModels) {\n\t\tproviderMap.set(m.provider.toLowerCase(), m.provider);\n\t}\n\n\tlet provider = cliProvider ? providerMap.get(cliProvider.toLowerCase()) : undefined;\n\tif (cliProvider && !provider) {\n\t\treturn {\n\t\t\tmodel: undefined,\n\t\t\twarning: undefined,\n\t\t\terror: `Unknown provider \"${cliProvider}\". Use --list-models to see available providers/models.`,\n\t\t};\n\t}\n\n\t// If no explicit --provider, try to interpret \"provider/model\" format first.\n\t// When the prefix before the first slash matches a known provider, prefer that\n\t// interpretation over matching models whose IDs literally contain slashes\n\t// (e.g. \"zai/glm-5\" should resolve to provider=zai, model=glm-5, not to a\n\t// vercel-ai-gateway model with id \"zai/glm-5\").\n\tlet pattern = cliModel;\n\tlet inferredProvider = false;\n\n\tif (!provider) {\n\t\tconst slashIndex = cliModel.indexOf(\"/\");\n\t\tif (slashIndex !== -1) {\n\t\t\tconst maybeProvider = cliModel.substring(0, slashIndex);\n\t\t\tconst canonical = providerMap.get(maybeProvider.toLowerCase());\n\t\t\tif (canonical) {\n\t\t\t\tprovider = canonical;\n\t\t\t\tpattern = cliModel.substring(slashIndex + 1);\n\t\t\t\tinferredProvider = true;\n\t\t\t}\n\t\t}\n\t}\n\n\t// If no provider was inferred from the slash, try exact matches without provider inference.\n\t// This handles models whose IDs naturally contain slashes (e.g. OpenRouter-style IDs).\n\tif (!provider) {\n\t\tconst lower = cliModel.toLowerCase();\n\t\tconst exact = availableModels.find(\n\t\t\t(m) => m.id.toLowerCase() === lower || `${m.provider}/${m.id}`.toLowerCase() === lower,\n\t\t);\n\t\tif (exact) {\n\t\t\treturn { model: exact, warning: undefined, thinkingLevel: undefined, error: undefined };\n\t\t}\n\t}\n\n\tif (cliProvider && provider) {\n\t\t// If both were provided, tolerate --model / by stripping the provider prefix\n\t\tconst prefix = `${provider}/`;\n\t\tif (cliModel.toLowerCase().startsWith(prefix.toLowerCase())) {\n\t\t\tpattern = cliModel.substring(prefix.length);\n\t\t}\n\t}\n\n\tconst candidates = provider ? availableModels.filter((m) => m.provider === provider) : availableModels;\n\tconst { model, thinkingLevel, warning } = parseModelPattern(pattern, candidates, {\n\t\tallowInvalidThinkingLevelFallback: false,\n\t});\n\n\tif (model) {\n\t\t// If provider inference matched an unauthenticated provider/model pair, prefer\n\t\t// one exact raw model-id match that is authenticated. This keeps\n\t\t// \"provider/model\" syntax preferred when usable, but handles models whose\n\t\t// literal id starts with a known provider name (for example\n\t\t// commandcode model id \"xiaomi/mimo-v2.5-pro\").\n\t\tif (inferredProvider) {\n\t\t\tconst rawExactMatches = availableModels.filter(\n\t\t\t\t(m) => m.id.toLowerCase() === cliModel.toLowerCase() && !modelsAreEqual(m, model),\n\t\t\t);\n\t\t\tif (rawExactMatches.length > 0 && !modelRuntime.hasConfiguredAuth(model.provider)) {\n\t\t\t\tconst authenticatedRawMatches = rawExactMatches.filter((m) => modelRuntime.hasConfiguredAuth(m.provider));\n\t\t\t\tif (authenticatedRawMatches.length === 1) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tmodel: authenticatedRawMatches[0],\n\t\t\t\t\t\tthinkingLevel: undefined,\n\t\t\t\t\t\twarning: undefined,\n\t\t\t\t\t\terror: undefined,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn { model, thinkingLevel, warning, error: undefined };\n\t}\n\n\t// If we inferred a provider from the slash but found no match within that provider,\n\t// fall back to matching the full input as a raw model id across all models.\n\t// This handles OpenRouter-style IDs like \"openai/gpt-4o:extended\" where \"openai\"\n\t// looks like a provider but the full string is actually a model id on openrouter.\n\tif (inferredProvider) {\n\t\tconst lower = cliModel.toLowerCase();\n\t\tconst exact = availableModels.find(\n\t\t\t(m) => m.id.toLowerCase() === lower || `${m.provider}/${m.id}`.toLowerCase() === lower,\n\t\t);\n\t\tif (exact) {\n\t\t\treturn { model: exact, warning: undefined, thinkingLevel: undefined, error: undefined };\n\t\t}\n\t\t// Also try parseModelPattern on the full input against all models\n\t\tconst fallback = parseModelPattern(cliModel, availableModels, {\n\t\t\tallowInvalidThinkingLevelFallback: false,\n\t\t});\n\t\tif (fallback.model) {\n\t\t\treturn {\n\t\t\t\tmodel: fallback.model,\n\t\t\t\tthinkingLevel: fallback.thinkingLevel,\n\t\t\t\twarning: fallback.warning,\n\t\t\t\terror: undefined,\n\t\t\t};\n\t\t}\n\t}\n\n\tif (provider) {\n\t\t// Parse thinking level suffix from the pattern before building the fallback model,\n\t\t// but only when --thinking is not explicitly provided.\n\t\t// e.g. \"zai-org/GLM-5.1-FP8:high\" → modelId=\"zai-org/GLM-5.1-FP8\", fallbackThinking=\"high\"\n\t\tlet fallbackPattern = pattern;\n\t\tlet fallbackThinking: ThinkingLevel | undefined;\n\t\tif (!cliThinking) {\n\t\t\tconst lastColon = pattern.lastIndexOf(\":\");\n\t\t\tif (lastColon !== -1) {\n\t\t\t\tconst suffix = pattern.substring(lastColon + 1);\n\t\t\t\tif (isValidThinkingLevel(suffix)) {\n\t\t\t\t\tfallbackPattern = pattern.substring(0, lastColon);\n\t\t\t\t\tfallbackThinking = suffix;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst fallbackModel = buildFallbackModel(provider, fallbackPattern, availableModels);\n\t\tif (fallbackModel) {\n\t\t\tconst requestedThinking = cliThinking ?? fallbackThinking;\n\t\t\tconst model =\n\t\t\t\trequestedThinking && requestedThinking !== \"off\" ? { ...fallbackModel, reasoning: true } : fallbackModel;\n\t\t\tconst fallbackWarning = warning\n\t\t\t\t? `${warning} Model \"${fallbackPattern}\" not found for provider \"${provider}\". Using custom model id.`\n\t\t\t\t: `Model \"${fallbackPattern}\" not found for provider \"${provider}\". Using custom model id.`;\n\t\t\treturn { model, thinkingLevel: fallbackThinking, warning: fallbackWarning, error: undefined };\n\t\t}\n\t}\n\n\tconst display = provider ? `${provider}/${pattern}` : cliModel;\n\treturn {\n\t\tmodel: undefined,\n\t\tthinkingLevel: undefined,\n\t\twarning,\n\t\terror: `Model \"${display}\" not found. Use --list-models to see available models.`,\n\t};\n}\n\nexport interface InitialModelResult {\n\tmodel: Model | undefined;\n\tthinkingLevel: ThinkingLevel;\n\tfallbackMessage: string | undefined;\n}\n\n/**\n * Find the initial model to use based on priority:\n * 1. CLI args (provider + model)\n * 2. First model from scoped models (if not continuing/resuming)\n * 3. Restored from session (if continuing/resuming)\n * 4. Saved default from settings\n * 5. First available model with valid API key\n */\nexport async function findInitialModel(options: {\n\tcliProvider?: string;\n\tcliModel?: string;\n\tscopedModels: ScopedModel[];\n\tisContinuing: boolean;\n\tdefaultProvider?: string;\n\tdefaultModelId?: string;\n\tdefaultThinkingLevel?: ThinkingLevel;\n\tmodelRuntime: ModelRuntime;\n}): Promise {\n\tconst {\n\t\tcliProvider,\n\t\tcliModel,\n\t\tscopedModels,\n\t\tisContinuing,\n\t\tdefaultProvider,\n\t\tdefaultModelId,\n\t\tdefaultThinkingLevel,\n\t\tmodelRuntime,\n\t} = options;\n\n\tlet model: Model | undefined;\n\tlet thinkingLevel: ThinkingLevel = DEFAULT_THINKING_LEVEL;\n\n\t// 1. CLI args take priority\n\tif (cliProvider && cliModel) {\n\t\tconst resolved = resolveCliModel({\n\t\t\tcliProvider,\n\t\t\tcliModel,\n\t\t\tmodelRuntime,\n\t\t});\n\t\tif (resolved.error) {\n\t\t\tconsole.error(chalk.red(resolved.error));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tif (resolved.model) {\n\t\t\treturn { model: resolved.model, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t\t}\n\t}\n\n\t// 2. Use first model from scoped models (skip if continuing/resuming)\n\tif (scopedModels.length > 0 && !isContinuing) {\n\t\treturn {\n\t\t\tmodel: scopedModels[0].model,\n\t\t\tthinkingLevel: scopedModels[0].thinkingLevel ?? defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL,\n\t\t\tfallbackMessage: undefined,\n\t\t};\n\t}\n\n\t// 3. Try saved default from settings if auth is configured.\n\tif (defaultProvider && defaultModelId) {\n\t\tconst found = modelRuntime.getModel(defaultProvider, defaultModelId);\n\t\tif (found && modelRuntime.hasConfiguredAuth(found.provider)) {\n\t\t\tmodel = found;\n\t\t\tif (defaultThinkingLevel) {\n\t\t\t\tthinkingLevel = defaultThinkingLevel;\n\t\t\t}\n\t\t\treturn { model, thinkingLevel, fallbackMessage: undefined };\n\t\t}\n\t}\n\n\t// 4. Try first available model with valid API key\n\tconst availableModels = [...(await modelRuntime.getAvailable())];\n\n\tif (availableModels.length > 0) {\n\t\t// Try to find a default model from known providers\n\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\tconst defaultId = defaultModelPerProvider[provider];\n\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultId);\n\t\t\tif (match) {\n\t\t\t\treturn { model: match, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t\t\t}\n\t\t}\n\n\t\t// If no default found, use first available\n\t\treturn { model: availableModels[0], thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n\t}\n\n\t// 5. No model found\n\treturn { model: undefined, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };\n}\n\n/**\n * Restore model from session, with fallback to available models\n */\nexport async function restoreModelFromSession(\n\tsavedProvider: string,\n\tsavedModelId: string,\n\tcurrentModel: Model | undefined,\n\tshouldPrintMessages: boolean,\n\tmodelRuntime: ModelRuntime,\n): Promise<{ model: Model | undefined; fallbackMessage: string | undefined }> {\n\tconst restoredModel = modelRuntime.getModel(savedProvider, savedModelId);\n\n\t// Check if restored model exists and still has auth configured\n\tconst hasConfiguredAuth = restoredModel ? modelRuntime.hasConfiguredAuth(restoredModel.provider) : false;\n\n\tif (restoredModel && hasConfiguredAuth) {\n\t\tif (shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Restored model: ${savedProvider}/${savedModelId}`));\n\t\t}\n\t\treturn { model: restoredModel, fallbackMessage: undefined };\n\t}\n\n\t// Model not found or no API key - fall back\n\tconst reason = !restoredModel ? \"model no longer exists\" : \"no auth configured\";\n\n\tif (shouldPrintMessages) {\n\t\tconsole.error(chalk.yellow(`Warning: Could not restore model ${savedProvider}/${savedModelId} (${reason}).`));\n\t}\n\n\t// If we already have a model, use it as fallback\n\tif (currentModel) {\n\t\tif (shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Falling back to: ${currentModel.provider}/${currentModel.id}`));\n\t\t}\n\t\treturn {\n\t\t\tmodel: currentModel,\n\t\t\tfallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${currentModel.provider}/${currentModel.id}.`,\n\t\t};\n\t}\n\n\t// Try to find any available model\n\tconst availableModels = [...(await modelRuntime.getAvailable())];\n\n\tif (availableModels.length > 0) {\n\t\t// Try to find a default model from known providers\n\t\tlet fallbackModel: Model | undefined;\n\t\tfor (const provider of Object.keys(defaultModelPerProvider) as KnownProvider[]) {\n\t\t\tconst defaultId = defaultModelPerProvider[provider];\n\t\t\tconst match = availableModels.find((m) => m.provider === provider && m.id === defaultId);\n\t\t\tif (match) {\n\t\t\t\tfallbackModel = match;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// If no default found, use first available\n\t\tif (!fallbackModel) {\n\t\t\tfallbackModel = availableModels[0];\n\t\t}\n\n\t\tif (shouldPrintMessages) {\n\t\t\tconsole.log(chalk.dim(`Falling back to: ${fallbackModel.provider}/${fallbackModel.id}`));\n\t\t}\n\n\t\treturn {\n\t\t\tmodel: fallbackModel,\n\t\t\tfallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${fallbackModel.provider}/${fallbackModel.id}.`,\n\t\t};\n\t}\n\n\t// No models available\n\treturn { model: undefined, fallbackMessage: undefined };\n}\n"]} \ No newline at end of file diff --git a/dist/core/model-runtime.d.ts b/dist/core/model-runtime.d.ts new file mode 100644 index 0000000..8c5fc5e --- /dev/null +++ b/dist/core/model-runtime.d.ts @@ -0,0 +1,83 @@ +import { type Api, type AssistantMessage, type AssistantMessageEventStream, type AuthCheck, type AuthInteraction, type AuthResult, type AuthType, type Context, type Credential, type CredentialInfo, type CredentialStore, type Model, type Models, type ModelsApiStreamOptions, type ModelsRefreshOptions, type ModelsRefreshResult, type ModelsSimpleStreamOptions, type ModelsStore, type Provider } from "@earendil-works/pi-ai"; +import { type AuthStatus, type CompatibilityRequestConfig, type ProviderConfigInput } from "./provider-composer.ts"; +export interface CreateModelRuntimeOptions { + /** Credential storage. Defaults to the file at authPath. */ + credentials?: CredentialStore; + authPath?: string; + modelsPath?: string | null; + modelsStore?: ModelsStore; + modelsStorePath?: string; + /** Allow create() to refresh model catalogs over the network. Defaults to false. */ + allowModelNetwork?: boolean; + /** Timeout for the create-time network model refresh. */ + modelRefreshTimeoutMs?: number; + catalogBaseUrl?: string; +} +export interface ModelRuntimeAuthOverrides { + apiKey?: string; + env?: Record; + /** Require this much remaining OAuth-token validity; defaults to five minutes. */ + minOAuthValidityMs?: number; +} +/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */ +export declare class ModelRuntime implements Models { + private readonly models; + private readonly credentials; + private readonly defaultBuiltins; + private readonly builtins; + private readonly nativeExtensionProviders; + private readonly extensionProviders; + private readonly compositionErrors; + private readonly modelsPath; + private readonly modelNetworkEnabled; + private config; + private snapshot; + private availabilityRefresh; + private availabilityError; + private constructor(); + static create(options?: CreateModelRuntimeOptions): Promise; + private configureRadiusProviders; + private providerIds; + private recomposeProvider; + private rebuildProviders; + private updateModelSnapshot; + private runAvailabilityRefresh; + private queueAvailabilityRefresh; + /** Coalesce concurrent readers onto the pending refresh. */ + private refreshAvailability; + /** Mutations must not observe an in-flight refresh started before them. */ + private forceRefreshAvailability; + getProviders(): readonly Provider[]; + getProvider(providerId: string): Provider | undefined; + getModels(providerId?: string): readonly Model[]; + getModel(providerId: string, modelId: string): Model | undefined; + checkAuth(providerId: string): Promise; + getAvailable(providerId?: string): Promise[]>; + getAvailableSnapshot(): readonly Model[]; + getError(): string | undefined; + getRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined; + getRegisteredProviderIds(): readonly string[]; + getRegisteredNativeProvider(providerId: string): Provider | undefined; + /** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */ + getCompatibilityRequestConfig(model: Model): CompatibilityRequestConfig; + isUsingOAuth(providerId: string): boolean; + hasConfiguredAuth(providerId: string): boolean; + getAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise; + getAuth(model: Model, overrides?: ModelRuntimeAuthOverrides): Promise; + setRuntimeApiKey(providerId: string, apiKey: string, refreshOptions?: ModelsRefreshOptions): Promise; + removeRuntimeApiKey(providerId: string): Promise; + listCredentials(): Promise; + getProviderAuthStatus(providerId: string): AuthStatus; + private prepareRequest; + stream(model: Model, context: Context, options?: ModelsApiStreamOptions): AssistantMessageEventStream; + complete(model: Model, context: Context, options?: ModelsApiStreamOptions): Promise; + streamSimple(model: Model, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream; + completeSimple(model: Model, context: Context, options?: ModelsSimpleStreamOptions): Promise; + login(providerId: string, type: AuthType, interaction: AuthInteraction): Promise; + logout(providerId: string): Promise; + refresh(options?: ModelsRefreshOptions): Promise; + registerNativeProvider(provider: Provider): void; + registerProvider(providerId: string, config: ProviderConfigInput): void; + unregisterProvider(providerId: string): void; +} +//# sourceMappingURL=model-runtime.d.ts.map \ No newline at end of file diff --git a/dist/core/model-runtime.d.ts.map b/dist/core/model-runtime.d.ts.map new file mode 100644 index 0000000..d731c0b --- /dev/null +++ b/dist/core/model-runtime.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"model-runtime.d.ts","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,GAAG,EAER,KAAK,gBAAgB,EACrB,KAAK,2BAA2B,EAChC,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,OAAO,EACZ,KAAK,UAAU,EACf,KAAK,cAAc,EACnB,KAAK,eAAe,EAGpB,KAAK,KAAK,EACV,KAAK,MAAM,EACX,KAAK,sBAAsB,EAE3B,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,yBAAyB,EAC9B,KAAK,WAAW,EAGhB,KAAK,QAAQ,EAIb,MAAM,uBAAuB,CAAC;AAM/B,OAAO,EACN,KAAK,UAAU,EACf,KAAK,0BAA0B,EAG/B,KAAK,mBAAmB,EAIxB,MAAM,wBAAwB,CAAC;AAYhC,MAAM,WAAW,yBAAyB;IACzC,4DAA4D;IAC5D,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,oFAAoF;IACpF,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,yDAAyD;IACzD,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,yBAAyB;IACzC,MAA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AAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAoCtE;IAED,kBAAkB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAM3C;CACD","sourcesContent":["import { dirname, join } from \"node:path\";\nimport {\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tcreateModels,\n\tlazyStream,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\tModelsError,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype ModelsStreamTransforms,\n\ttype MutableModels,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport * as builtinProviderCatalog from \"@earendil-works/pi-ai/providers/all\";\nimport { getAgentDir } from \"../config.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\ttype AuthStatus,\n\ttype CompatibilityRequestConfig,\n\tcomposeModelProvider,\n\tconfiguredRequestAuthStatus,\n\ttype ProviderConfigInput,\n\tresolveCompatibilityRequestConfig,\n\tresolveConfiguredModelHeaders,\n\tvalidateExtensionProvider,\n} from \"./provider-composer.ts\";\nimport { withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\n\ninterface ModelRuntimeSnapshot {\n\tall: readonly Model[];\n\tavailable: readonly Model[];\n\tconfiguredProviders: ReadonlySet;\n\tstoredProviders: ReadonlySet;\n\tauth: ReadonlyMap;\n}\n\nexport interface CreateModelRuntimeOptions {\n\t/** Credential storage. Defaults to the file at authPath. */\n\tcredentials?: CredentialStore;\n\tauthPath?: string;\n\tmodelsPath?: string | null;\n\tmodelsStore?: ModelsStore;\n\tmodelsStorePath?: string;\n\t/** Allow create() to refresh model catalogs over the network. Defaults to false. */\n\tallowModelNetwork?: boolean;\n\t/** Timeout for the create-time network model refresh. */\n\tmodelRefreshTimeoutMs?: number;\n\tcatalogBaseUrl?: string;\n}\n\nexport interface ModelRuntimeAuthOverrides {\n\tapiKey?: string;\n\tenv?: Record;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n}\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\n/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */\nexport class ModelRuntime implements Models {\n\tprivate readonly models: MutableModels;\n\tprivate readonly credentials: RuntimeCredentials;\n\tprivate readonly defaultBuiltins: ReadonlyMap;\n\tprivate readonly builtins = new Map();\n\tprivate readonly nativeExtensionProviders = new Map();\n\tprivate readonly extensionProviders = new Map();\n\tprivate readonly compositionErrors = new Map();\n\tprivate readonly modelsPath: string | undefined;\n\tprivate readonly modelNetworkEnabled: boolean;\n\tprivate config: ModelConfig;\n\tprivate snapshot: ModelRuntimeSnapshot = {\n\t\tall: [],\n\t\tavailable: [],\n\t\tconfiguredProviders: new Set(),\n\t\tstoredProviders: new Set(),\n\t\tauth: new Map(),\n\t};\n\tprivate availabilityRefresh: Promise | undefined;\n\tprivate availabilityError: string | undefined;\n\n\tprivate constructor(\n\t\tcredentials: RuntimeCredentials,\n\t\tconfig: ModelConfig,\n\t\tmodelsPath: string | undefined,\n\t\tmodelsStore: ModelsStore,\n\t\tproviders: readonly Provider[],\n\t\tmodelNetworkEnabled: boolean,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\n\t\tthis.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tthis.models = createModels({ credentials, modelsStore });\n\t\tthis.rebuildProviders();\n\t}\n\n\tstatic async create(options: CreateModelRuntimeOptions = {}): Promise {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = await ModelConfig.load(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.id === \"radius\"\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\tprocess.env.PI_OFFLINE === undefined,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller = refreshFromNetwork ? new AbortController() : undefined;\n\t\tconst timeout = controller\n\t\t\t? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs ?? 15_000)\n\t\t\t: undefined;\n\t\ttry {\n\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal: controller?.signal });\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tprivate configureRadiusProviders(): void {\n\t\tthis.builtins.clear();\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tfor (const providerId of this.config.getProviderIds()) {\n\t\t\tconst config = this.config.getProvider(providerId);\n\t\t\tif (config?.oauth !== \"radius\" || !config.baseUrl) continue;\n\t\t\tthis.builtins.set(\n\t\t\t\tproviderId,\n\t\t\t\tbuiltinProviderCatalog.radiusProvider({\n\t\t\t\t\tid: providerId,\n\t\t\t\t\tname: config.name ?? providerId,\n\t\t\t\t\tgateway: config.baseUrl.replace(/\\/v1\\/?$/u, \"\"),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate providerIds(): Set {\n\t\treturn new Set([\n\t\t\t...this.builtins.keys(),\n\t\t\t...this.nativeExtensionProviders.keys(),\n\t\t\t...this.config.getProviderIds(),\n\t\t\t...this.extensionProviders.keys(),\n\t\t]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tconst base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);\n\t\tconst extension = this.extensionProviders.get(providerId);\n\t\tif (!base && !this.config.getProvider(providerId) && !extension) {\n\t\t\tthis.models.deleteProvider(providerId);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\tif (base && !this.config.getProvider(providerId) && !extension) {\n\t\t\t// No overlays: use the builtin untouched so its auth/login/stream behavior is exact.\n\t\t\tthis.models.setProvider(base);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(composeModelProvider(providerId, base, this.config, extension));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t} catch (error) {\n\t\t\tthis.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));\n\t\t\tif (base) this.models.setProvider(base);\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate rebuildProviders(): void {\n\t\tthis.models.clearProviders();\n\t\tthis.compositionErrors.clear();\n\t\tfor (const providerId of this.providerIds()) this.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate updateModelSnapshot(): void {\n\t\tconst all = [...this.models.getModels()];\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tall,\n\t\t\tavailable: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tprivate async runAvailabilityRefresh(): Promise {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(),\n\t\t\tPromise.all(\n\t\t\t\tproviders.map(\n\t\t\t\t\tasync (provider): Promise<[string, AuthCheck | undefined]> => [\n\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\tawait this.models.checkAuth(provider.id),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list(),\n\t\t]);\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = new Set(\n\t\t\tchecks\n\t\t\t\t.filter((entry): entry is [string, AuthCheck] => entry[1] !== undefined)\n\t\t\t\t.map(([providerId]) => providerId),\n\t\t);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: [...available],\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders: new Set(credentials.map((entry) => entry.providerId)),\n\t\t\tauth,\n\t\t};\n\t\tthis.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(after: Promise | undefined): Promise {\n\t\tconst refresh = (after ?? Promise.resolve()).catch(() => {}).then(() => this.runAvailabilityRefresh());\n\t\tconst recorded = refresh.catch((error) => {\n\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\tthrow error;\n\t\t});\n\t\tconst tracked = recorded.finally(() => {\n\t\t\tif (this.availabilityRefresh === tracked) this.availabilityRefresh = undefined;\n\t\t});\n\t\tthis.availabilityRefresh = tracked;\n\t\treturn tracked;\n\t}\n\n\t/** Coalesce concurrent readers onto the pending refresh. */\n\tprivate refreshAvailability(): Promise {\n\t\treturn this.availabilityRefresh ?? this.queueAvailabilityRefresh(undefined);\n\t}\n\n\t/** Mutations must not observe an in-flight refresh started before them. */\n\tprivate forceRefreshAvailability(): Promise {\n\t\treturn this.queueAvailabilityRefresh(this.availabilityRefresh);\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\n\tgetModels(providerId?: string): readonly Model[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\n\tgetModel(providerId: string, modelId: string): Model | undefined {\n\t\treturn this.models.getModel(providerId, modelId);\n\t}\n\n\tasync checkAuth(providerId: string): Promise {\n\t\treturn this.models.checkAuth(providerId);\n\t}\n\n\tasync getAvailable(providerId?: string): Promise[]> {\n\t\tif (providerId) {\n\t\t\tif (this.availabilityRefresh) {\n\t\t\t\tawait this.availabilityRefresh;\n\t\t\t\treturn this.snapshot.available.filter((model) => model.provider === providerId);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await this.models.getAvailable(providerId);\n\t\t\t} catch (error) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.refreshAvailability();\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model[] {\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetError(): string | undefined {\n\t\tconst errors: string[] = [];\n\t\tconst configError = this.config.getError();\n\t\tif (configError) errors.push(configError);\n\t\tfor (const [providerId, error] of this.compositionErrors) {\n\t\t\terrors.push(`Provider \"${providerId}\": ${error}`);\n\t\t}\n\t\tif (this.availabilityError) errors.push(`Availability refresh: ${this.availabilityError}`);\n\t\treturn errors.length > 0 ? errors.join(\"\\n\\n\") : undefined;\n\t}\n\n\tgetRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined {\n\t\treturn this.extensionProviders.get(providerId);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];\n\t}\n\n\tgetRegisteredNativeProvider(providerId: string): Provider | undefined {\n\t\treturn this.nativeExtensionProviders.get(providerId);\n\t}\n\n\t/** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */\n\tgetCompatibilityRequestConfig(model: Model): CompatibilityRequestConfig {\n\t\treturn resolveCompatibilityRequestConfig(\n\t\t\tmodel,\n\t\t\tthis.config.getProvider(model.provider),\n\t\t\tthis.extensionProviders.get(model.provider),\n\t\t);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\n\t}\n\n\tgetAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise;\n\tgetAuth(model: Model, overrides?: ModelRuntimeAuthOverrides): Promise;\n\tasync getAuth(\n\t\tproviderOrModel: string | Model,\n\t\toverrides: ModelRuntimeAuthOverrides = {},\n\t): Promise {\n\t\tif (typeof providerOrModel === \"string\") return this.models.getAuth(providerOrModel, overrides);\n\t\tconst resolution = await this.models.getAuth(providerOrModel, overrides);\n\t\tif (!resolution) return undefined;\n\t\tconst configuredHeaders = resolveConfiguredModelHeaders(\n\t\t\tproviderOrModel,\n\t\t\tthis.config.getProvider(providerOrModel.provider),\n\t\t\tthis.extensionProviders.get(providerOrModel.provider),\n\t\t\t{ ...(resolution.env ?? {}), ...(overrides.env ?? {}) },\n\t\t);\n\t\treturn {\n\t\t\t...resolution,\n\t\t\tauth: {\n\t\t\t\t...resolution.auth,\n\t\t\t\theaders: mergeHeaders(resolution.auth.headers, configuredHeaders),\n\t\t\t},\n\t\t};\n\t}\n\n\tasync setRuntimeApiKey(\n\t\tproviderId: string,\n\t\tapiKey: string,\n\t\trefreshOptions: ModelsRefreshOptions = {},\n\t): Promise {\n\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\tconst auth = new Map(this.snapshot.auth).set(providerId, { type: \"api_key\", source: \"runtime API key\" });\n\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\tconst storedProviders = new Set(this.snapshot.storedProviders).add(providerId);\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tauth,\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders,\n\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t};\n\t\tawait this.refresh(refreshOptions);\n\t}\n\n\tasync removeRuntimeApiKey(providerId: string): Promise {\n\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tlistCredentials(): Promise {\n\t\treturn this.credentials.list();\n\t}\n\n\tgetProviderAuthStatus(providerId: string): AuthStatus {\n\t\tif (this.credentials.hasRuntimeApiKey(providerId)) return { configured: true, source: \"runtime\" };\n\t\tif (this.snapshot.storedProviders.has(providerId)) return { configured: true, source: \"stored\" };\n\t\tconst configured = configuredRequestAuthStatus(\n\t\t\tthis.config.getProvider(providerId),\n\t\t\tthis.extensionProviders.get(providerId),\n\t\t);\n\t\tif (configured) return configured;\n\t\tconst check = this.snapshot.auth.get(providerId);\n\t\treturn check ? { configured: true, source: \"environment\", label: check.source } : { configured: false };\n\t}\n\n\tprivate async prepareRequest(\n\t\tmodel: Model,\n\t\toptions: (StreamOptions & ModelsStreamTransforms) | undefined,\n\t): Promise<{ provider: Provider; model: Model; options: StreamOptions }> {\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst resolution = await this.getAuth(model, { apiKey: options?.apiKey, env: options?.env });\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...providerOptions } = options ?? {};\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\tconst env =\n\t\t\tresolution.env || providerOptions.env\n\t\t\t\t? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }\n\t\t\t\t: undefined;\n\t\treturn {\n\t\t\tprovider,\n\t\t\tmodel: resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t},\n\t\t};\n\t}\n\n\tstream(\n\t\tmodel: Model,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\tmodel,\n\t\t\t\toptions as (StreamOptions & ModelsStreamTransforms) | undefined,\n\t\t\t);\n\t\t\treturn prepared.provider.stream(\n\t\t\t\tprepared.model as Model,\n\t\t\t\tcontext,\n\t\t\t\tprepared.options as ApiStreamOptions,\n\t\t\t);\n\t\t});\n\t}\n\n\tcomplete(\n\t\tmodel: Model,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions,\n\t): Promise {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\treturn prepared.provider.streamSimple(prepared.model, context, prepared.options as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tcompleteSimple(model: Model, context: Context, options?: ModelsSimpleStreamOptions): Promise {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tasync login(providerId: string, type: AuthType, interaction: AuthInteraction): Promise {\n\t\tconst credential = await this.models.login(providerId, type, interaction);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string): Promise {\n\t\tawait this.models.logout(providerId);\n\t\t// Reset credential-dependent compatibility projections before the unconfigured provider is skipped by refresh.\n\t\tthis.recomposeProvider(providerId);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tthis.rebuildProviders();\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,\n\t\t};\n\t\t// Published pi-ai builds before ModelsStore returned void and accepted a provider ID.\n\t\t// The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.\n\t\tconst result = ((await this.models.refresh(refreshOptions)) as ModelsRefreshResult | undefined) ?? {\n\t\t\taborted: refreshOptions.signal?.aborted ?? false,\n\t\t\terrors: new Map(),\n\t\t};\n\t\tthis.updateModelSnapshot();\n\t\ttry {\n\t\t\tawait this.forceRefreshAvailability();\n\t\t} catch {\n\t\t\t// Availability errors are recorded by forceRefreshAvailability; refreshed models remain usable.\n\t\t}\n\t\treturn result;\n\t}\n\n\tregisterNativeProvider(provider: Provider): void {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tregisterProvider(providerId: string, config: ProviderConfigInput): void {\n\t\t// Validate the incoming registration on its own, like the legacy registry:\n\t\t// a broken re-registration must throw without touching the stored config.\n\t\tvalidateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\t// Re-registration merges defined values over the previous registration and\n\t\t// preserves undefined ones, matching the legacy ModelRegistry contract.\n\t\tconst previous = this.extensionProviders.get(providerId);\n\t\tconst effective: ProviderConfigInput = { ...previous };\n\t\tfor (const [key, value] of Object.entries(config)) {\n\t\t\tif (value !== undefined) (effective as Record)[key] = value;\n\t\t}\n\t\tthis.extensionProviders.set(providerId, effective);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tif (\n\t\t\tthis.snapshot.storedProviders.has(providerId) ||\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(providerId), effective)?.configured\n\t\t) {\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\t\tconst auth = new Map(this.snapshot.auth);\n\t\t\t// Provisional entry until the async refresh lands; never clobber a real check result.\n\t\t\tif (!auth.get(providerId)) {\n\t\t\t\tauth.set(providerId, {\n\t\t\t\t\ttype: effective.oauth && !effective.apiKey ? \"oauth\" : \"api_key\",\n\t\t\t\t\tsource: \"configured provider\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.snapshot = {\n\t\t\t\t...this.snapshot,\n\t\t\t\tauth,\n\t\t\t\tconfiguredProviders,\n\t\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t\t};\n\t\t}\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tunregisterProvider(providerId: string): void {\n\t\tthis.extensionProviders.delete(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/model-runtime.js b/dist/core/model-runtime.js new file mode 100644 index 0000000..e81a536 --- /dev/null +++ b/dist/core/model-runtime.js @@ -0,0 +1,439 @@ +import { dirname, join } from "node:path"; +import { createModels, lazyStream, ModelsError, } from "@earendil-works/pi-ai"; +import * as builtinProviderCatalog from "@earendil-works/pi-ai/providers/all"; +import { getAgentDir } from "../config.js"; +import { AuthStorage as DefaultAuthStorage } from "./auth-storage.js"; +import { ModelConfig } from "./model-config.js"; +import { FileModelsStore, InMemoryCodingAgentModelsStore } from "./models-store.js"; +import { composeModelProvider, configuredRequestAuthStatus, resolveCompatibilityRequestConfig, resolveConfiguredModelHeaders, validateExtensionProvider, } from "./provider-composer.js"; +import { withRemoteCatalog } from "./remote-catalog-provider.js"; +import { RuntimeCredentials } from "./runtime-credentials.js"; +function mergeHeaders(base, override) { + if (!base && !override) + return undefined; + const merged = { ...base }; + for (const [name, value] of Object.entries(override ?? {})) { + const lowerName = name.toLowerCase(); + for (const existingName of Object.keys(merged)) { + if (existingName.toLowerCase() === lowerName) + delete merged[existingName]; + } + merged[name] = value; + } + return merged; +} +/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */ +export class ModelRuntime { + models; + credentials; + defaultBuiltins; + builtins = new Map(); + nativeExtensionProviders = new Map(); + extensionProviders = new Map(); + compositionErrors = new Map(); + modelsPath; + modelNetworkEnabled; + config; + snapshot = { + all: [], + available: [], + configuredProviders: new Set(), + storedProviders: new Set(), + auth: new Map(), + }; + availabilityRefresh; + availabilityError; + constructor(credentials, config, modelsPath, modelsStore, providers, modelNetworkEnabled) { + this.credentials = credentials; + this.config = config; + this.modelsPath = modelsPath; + this.modelNetworkEnabled = modelNetworkEnabled; + this.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider])); + for (const [providerId, provider] of this.defaultBuiltins) + this.builtins.set(providerId, provider); + this.models = createModels({ credentials, modelsStore }); + this.rebuildProviders(); + } + static async create(options = {}) { + const credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath)); + const modelsPath = options.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), "models.json")); + const config = await ModelConfig.load(modelsPath); + const modelsStore = options.modelsStore ?? + (modelsPath + ? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), "models-store.json")) + : new InMemoryCodingAgentModelsStore()); + const builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt(); + const providers = builtinProviderCatalog + .builtinProviders() + .map((provider) => provider.id === "radius" + ? provider + : withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt)); + const runtime = new ModelRuntime(credentials, config, modelsPath, modelsStore, providers, process.env.PI_OFFLINE === undefined); + runtime.configureRadiusProviders(); + runtime.rebuildProviders(); + const refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true; + const controller = refreshFromNetwork ? new AbortController() : undefined; + const timeout = controller + ? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs ?? 15_000) + : undefined; + try { + await runtime.refresh({ allowNetwork: refreshFromNetwork, signal: controller?.signal }); + } + finally { + if (timeout) + clearTimeout(timeout); + } + return runtime; + } + configureRadiusProviders() { + this.builtins.clear(); + for (const [providerId, provider] of this.defaultBuiltins) + this.builtins.set(providerId, provider); + for (const providerId of this.config.getProviderIds()) { + const config = this.config.getProvider(providerId); + if (config?.oauth !== "radius" || !config.baseUrl) + continue; + this.builtins.set(providerId, builtinProviderCatalog.radiusProvider({ + id: providerId, + name: config.name ?? providerId, + gateway: config.baseUrl.replace(/\/v1\/?$/u, ""), + })); + } + } + providerIds() { + return new Set([ + ...this.builtins.keys(), + ...this.nativeExtensionProviders.keys(), + ...this.config.getProviderIds(), + ...this.extensionProviders.keys(), + ]); + } + recomposeProvider(providerId) { + const base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId); + const extension = this.extensionProviders.get(providerId); + if (!base && !this.config.getProvider(providerId) && !extension) { + this.models.deleteProvider(providerId); + this.compositionErrors.delete(providerId); + return; + } + if (base && !this.config.getProvider(providerId) && !extension) { + // No overlays: use the builtin untouched so its auth/login/stream behavior is exact. + this.models.setProvider(base); + this.compositionErrors.delete(providerId); + return; + } + try { + this.models.setProvider(composeModelProvider(providerId, base, this.config, extension)); + this.compositionErrors.delete(providerId); + } + catch (error) { + this.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error)); + if (base) + this.models.setProvider(base); + else + this.models.deleteProvider(providerId); + } + } + rebuildProviders() { + this.models.clearProviders(); + this.compositionErrors.clear(); + for (const providerId of this.providerIds()) + this.recomposeProvider(providerId); + this.updateModelSnapshot(); + } + updateModelSnapshot() { + const all = [...this.models.getModels()]; + this.snapshot = { + ...this.snapshot, + all, + available: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)), + }; + } + async runAvailabilityRefresh() { + const providers = this.models.getProviders(); + const [available, checks, credentials] = await Promise.all([ + this.models.getAvailable(), + Promise.all(providers.map(async (provider) => [ + provider.id, + await this.models.checkAuth(provider.id), + ])), + this.credentials.list(), + ]); + const auth = new Map(checks); + const configuredProviders = new Set(checks + .filter((entry) => entry[1] !== undefined) + .map(([providerId]) => providerId)); + this.snapshot = { + all: [...this.models.getModels()], + available: [...available], + configuredProviders, + storedProviders: new Set(credentials.map((entry) => entry.providerId)), + auth, + }; + this.availabilityError = undefined; + } + queueAvailabilityRefresh(after) { + const refresh = (after ?? Promise.resolve()).catch(() => { }).then(() => this.runAvailabilityRefresh()); + const recorded = refresh.catch((error) => { + this.availabilityError = error instanceof Error ? error.message : String(error); + throw error; + }); + const tracked = recorded.finally(() => { + if (this.availabilityRefresh === tracked) + this.availabilityRefresh = undefined; + }); + this.availabilityRefresh = tracked; + return tracked; + } + /** Coalesce concurrent readers onto the pending refresh. */ + refreshAvailability() { + return this.availabilityRefresh ?? this.queueAvailabilityRefresh(undefined); + } + /** Mutations must not observe an in-flight refresh started before them. */ + forceRefreshAvailability() { + return this.queueAvailabilityRefresh(this.availabilityRefresh); + } + getProviders() { + return this.models.getProviders(); + } + getProvider(providerId) { + return this.models.getProvider(providerId); + } + getModels(providerId) { + return this.models.getModels(providerId); + } + getModel(providerId, modelId) { + return this.models.getModel(providerId, modelId); + } + async checkAuth(providerId) { + return this.models.checkAuth(providerId); + } + async getAvailable(providerId) { + if (providerId) { + if (this.availabilityRefresh) { + await this.availabilityRefresh; + return this.snapshot.available.filter((model) => model.provider === providerId); + } + try { + return await this.models.getAvailable(providerId); + } + catch (error) { + this.availabilityError = error instanceof Error ? error.message : String(error); + throw error; + } + } + await this.refreshAvailability(); + return this.snapshot.available; + } + getAvailableSnapshot() { + return this.snapshot.available; + } + getError() { + const errors = []; + const configError = this.config.getError(); + if (configError) + errors.push(configError); + for (const [providerId, error] of this.compositionErrors) { + errors.push(`Provider "${providerId}": ${error}`); + } + if (this.availabilityError) + errors.push(`Availability refresh: ${this.availabilityError}`); + return errors.length > 0 ? errors.join("\n\n") : undefined; + } + getRegisteredProviderConfig(providerId) { + return this.extensionProviders.get(providerId); + } + getRegisteredProviderIds() { + return [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])]; + } + getRegisteredNativeProvider(providerId) { + return this.nativeExtensionProviders.get(providerId); + } + /** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */ + getCompatibilityRequestConfig(model) { + return resolveCompatibilityRequestConfig(model, this.config.getProvider(model.provider), this.extensionProviders.get(model.provider)); + } + isUsingOAuth(providerId) { + return this.snapshot.auth.get(providerId)?.type === "oauth"; + } + hasConfiguredAuth(providerId) { + return this.snapshot.configuredProviders.has(providerId); + } + async getAuth(providerOrModel, overrides = {}) { + if (typeof providerOrModel === "string") + return this.models.getAuth(providerOrModel, overrides); + const resolution = await this.models.getAuth(providerOrModel, overrides); + if (!resolution) + return undefined; + const configuredHeaders = resolveConfiguredModelHeaders(providerOrModel, this.config.getProvider(providerOrModel.provider), this.extensionProviders.get(providerOrModel.provider), { ...(resolution.env ?? {}), ...(overrides.env ?? {}) }); + return { + ...resolution, + auth: { + ...resolution.auth, + headers: mergeHeaders(resolution.auth.headers, configuredHeaders), + }, + }; + } + async setRuntimeApiKey(providerId, apiKey, refreshOptions = {}) { + this.credentials.setRuntimeApiKey(providerId, apiKey); + const auth = new Map(this.snapshot.auth).set(providerId, { type: "api_key", source: "runtime API key" }); + const configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId); + const storedProviders = new Set(this.snapshot.storedProviders).add(providerId); + this.snapshot = { + ...this.snapshot, + auth, + configuredProviders, + storedProviders, + available: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)), + }; + await this.refresh(refreshOptions); + } + async removeRuntimeApiKey(providerId) { + this.credentials.removeRuntimeApiKey(providerId); + await this.refresh({ allowNetwork: this.modelNetworkEnabled }); + } + listCredentials() { + return this.credentials.list(); + } + getProviderAuthStatus(providerId) { + if (this.credentials.hasRuntimeApiKey(providerId)) + return { configured: true, source: "runtime" }; + if (this.snapshot.storedProviders.has(providerId)) + return { configured: true, source: "stored" }; + const configured = configuredRequestAuthStatus(this.config.getProvider(providerId), this.extensionProviders.get(providerId)); + if (configured) + return configured; + const check = this.snapshot.auth.get(providerId); + return check ? { configured: true, source: "environment", label: check.source } : { configured: false }; + } + async prepareRequest(model, options) { + const provider = this.models.getProvider(model.provider); + if (!provider) + throw new ModelsError("provider", `Unknown provider: ${model.provider}`); + const resolution = await this.getAuth(model, { apiKey: options?.apiKey, env: options?.env }); + if (!resolution) + throw new ModelsError("auth", `Provider is not configured: ${model.provider}`); + const { transformHeaders, ...providerOptions } = options ?? {}; + let headers = mergeHeaders(resolution.auth.headers, providerOptions.headers); + if (transformHeaders) + headers = await transformHeaders(headers ?? {}); + const env = resolution.env || providerOptions.env + ? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) } + : undefined; + return { + provider, + model: resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model, + options: { + ...providerOptions, + apiKey: providerOptions.apiKey ?? resolution.auth.apiKey, + headers, + env, + }, + }; + } + stream(model, context, options) { + return lazyStream(model, async () => { + const prepared = await this.prepareRequest(model, options); + return prepared.provider.stream(prepared.model, context, prepared.options); + }); + } + complete(model, context, options) { + return this.stream(model, context, options).result(); + } + streamSimple(model, context, options) { + return lazyStream(model, async () => { + const prepared = await this.prepareRequest(model, options); + return prepared.provider.streamSimple(prepared.model, context, prepared.options); + }); + } + completeSimple(model, context, options) { + return this.streamSimple(model, context, options).result(); + } + async login(providerId, type, interaction) { + const credential = await this.models.login(providerId, type, interaction); + await this.refresh({ allowNetwork: this.modelNetworkEnabled }); + return credential; + } + async logout(providerId) { + await this.models.logout(providerId); + // Reset credential-dependent compatibility projections before the unconfigured provider is skipped by refresh. + this.recomposeProvider(providerId); + await this.refresh({ allowNetwork: this.modelNetworkEnabled }); + } + async refresh(options = {}) { + this.config = await ModelConfig.load(this.modelsPath); + this.configureRadiusProviders(); + this.rebuildProviders(); + const refreshOptions = { + ...options, + allowNetwork: options.allowNetwork ?? this.modelNetworkEnabled, + }; + // Published pi-ai builds before ModelsStore returned void and accepted a provider ID. + // The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies. + const result = (await this.models.refresh(refreshOptions)) ?? { + aborted: refreshOptions.signal?.aborted ?? false, + errors: new Map(), + }; + this.updateModelSnapshot(); + try { + await this.forceRefreshAvailability(); + } + catch { + // Availability errors are recorded by forceRefreshAvailability; refreshed models remain usable. + } + return result; + } + registerNativeProvider(provider) { + if (!provider.id.trim()) + throw new Error("Provider id must not be empty."); + this.extensionProviders.delete(provider.id); + this.nativeExtensionProviders.set(provider.id, provider); + this.recomposeProvider(provider.id); + this.updateModelSnapshot(); + void this.refresh({ allowNetwork: false }); + } + registerProvider(providerId, config) { + // Validate the incoming registration on its own, like the legacy registry: + // a broken re-registration must throw without touching the stored config. + validateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config); + this.nativeExtensionProviders.delete(providerId); + // Re-registration merges defined values over the previous registration and + // preserves undefined ones, matching the legacy ModelRegistry contract. + const previous = this.extensionProviders.get(providerId); + const effective = { ...previous }; + for (const [key, value] of Object.entries(config)) { + if (value !== undefined) + effective[key] = value; + } + this.extensionProviders.set(providerId, effective); + this.recomposeProvider(providerId); + this.updateModelSnapshot(); + if (this.snapshot.storedProviders.has(providerId) || + configuredRequestAuthStatus(this.config.getProvider(providerId), effective)?.configured) { + const configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId); + const auth = new Map(this.snapshot.auth); + // Provisional entry until the async refresh lands; never clobber a real check result. + if (!auth.get(providerId)) { + auth.set(providerId, { + type: effective.oauth && !effective.apiKey ? "oauth" : "api_key", + source: "configured provider", + }); + } + this.snapshot = { + ...this.snapshot, + auth, + configuredProviders, + available: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)), + }; + } + void this.refresh({ allowNetwork: false }); + } + unregisterProvider(providerId) { + this.extensionProviders.delete(providerId); + this.nativeExtensionProviders.delete(providerId); + this.recomposeProvider(providerId); + this.updateModelSnapshot(); + void this.refresh({ allowNetwork: false }); + } +} +//# sourceMappingURL=model-runtime.js.map \ No newline at end of file diff --git a/dist/core/model-runtime.js.map b/dist/core/model-runtime.js.map new file mode 100644 index 0000000..0d9ed6e --- /dev/null +++ b/dist/core/model-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"file":"model-runtime.js","sourceRoot":"","sources":["../../src/core/model-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAaN,YAAY,EACZ,UAAU,EAIV,WAAW,GAWX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,sBAAsB,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EA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;YACJ,CAAC;YACD,IAAI,CAAC,QAAQ,GAAG;gBACf,GAAG,IAAI,CAAC,QAAQ;gBAChB,IAAI;gBACJ,mBAAmB;gBACnB,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,mBAAmB,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;aACvF,CAAC;QACH,CAAC;QACD,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CAC3C;IAED,kBAAkB,CAAC,UAAkB,EAAQ;QAC5C,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACjD,IAAI,CAAC,iBAAiB,CAAC,UAAU,CAAC,CAAC;QACnC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAAA,CAC3C;CACD","sourcesContent":["import { dirname, join } from \"node:path\";\nimport {\n\ttype Api,\n\ttype ApiStreamOptions,\n\ttype AssistantMessage,\n\ttype AssistantMessageEventStream,\n\ttype AuthCheck,\n\ttype AuthInteraction,\n\ttype AuthResult,\n\ttype AuthType,\n\ttype Context,\n\ttype Credential,\n\ttype CredentialInfo,\n\ttype CredentialStore,\n\tcreateModels,\n\tlazyStream,\n\ttype Model,\n\ttype Models,\n\ttype ModelsApiStreamOptions,\n\tModelsError,\n\ttype ModelsRefreshOptions,\n\ttype ModelsRefreshResult,\n\ttype ModelsSimpleStreamOptions,\n\ttype ModelsStore,\n\ttype ModelsStreamTransforms,\n\ttype MutableModels,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport * as builtinProviderCatalog from \"@earendil-works/pi-ai/providers/all\";\nimport { getAgentDir } from \"../config.ts\";\nimport { AuthStorage as DefaultAuthStorage } from \"./auth-storage.ts\";\nimport { ModelConfig } from \"./model-config.ts\";\nimport { FileModelsStore, InMemoryCodingAgentModelsStore } from \"./models-store.ts\";\nimport {\n\ttype AuthStatus,\n\ttype CompatibilityRequestConfig,\n\tcomposeModelProvider,\n\tconfiguredRequestAuthStatus,\n\ttype ProviderConfigInput,\n\tresolveCompatibilityRequestConfig,\n\tresolveConfiguredModelHeaders,\n\tvalidateExtensionProvider,\n} from \"./provider-composer.ts\";\nimport { withRemoteCatalog } from \"./remote-catalog-provider.ts\";\nimport { RuntimeCredentials } from \"./runtime-credentials.ts\";\n\ninterface ModelRuntimeSnapshot {\n\tall: readonly Model[];\n\tavailable: readonly Model[];\n\tconfiguredProviders: ReadonlySet;\n\tstoredProviders: ReadonlySet;\n\tauth: ReadonlyMap;\n}\n\nexport interface CreateModelRuntimeOptions {\n\t/** Credential storage. Defaults to the file at authPath. */\n\tcredentials?: CredentialStore;\n\tauthPath?: string;\n\tmodelsPath?: string | null;\n\tmodelsStore?: ModelsStore;\n\tmodelsStorePath?: string;\n\t/** Allow create() to refresh model catalogs over the network. Defaults to false. */\n\tallowModelNetwork?: boolean;\n\t/** Timeout for the create-time network model refresh. */\n\tmodelRefreshTimeoutMs?: number;\n\tcatalogBaseUrl?: string;\n}\n\nexport interface ModelRuntimeAuthOverrides {\n\tapiKey?: string;\n\tenv?: Record;\n\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n}\n\nfunction mergeHeaders(\n\tbase: ProviderHeaders | undefined,\n\toverride: ProviderHeaders | undefined,\n): ProviderHeaders | undefined {\n\tif (!base && !override) return undefined;\n\tconst merged = { ...base };\n\tfor (const [name, value] of Object.entries(override ?? {})) {\n\t\tconst lowerName = name.toLowerCase();\n\t\tfor (const existingName of Object.keys(merged)) {\n\t\t\tif (existingName.toLowerCase() === lowerName) delete merged[existingName];\n\t\t}\n\t\tmerged[name] = value;\n\t}\n\treturn merged;\n}\n\n/** Configured pi-ai Models collection used by coding-agent and SDK consumers. */\nexport class ModelRuntime implements Models {\n\tprivate readonly models: MutableModels;\n\tprivate readonly credentials: RuntimeCredentials;\n\tprivate readonly defaultBuiltins: ReadonlyMap;\n\tprivate readonly builtins = new Map();\n\tprivate readonly nativeExtensionProviders = new Map();\n\tprivate readonly extensionProviders = new Map();\n\tprivate readonly compositionErrors = new Map();\n\tprivate readonly modelsPath: string | undefined;\n\tprivate readonly modelNetworkEnabled: boolean;\n\tprivate config: ModelConfig;\n\tprivate snapshot: ModelRuntimeSnapshot = {\n\t\tall: [],\n\t\tavailable: [],\n\t\tconfiguredProviders: new Set(),\n\t\tstoredProviders: new Set(),\n\t\tauth: new Map(),\n\t};\n\tprivate availabilityRefresh: Promise | undefined;\n\tprivate availabilityError: string | undefined;\n\n\tprivate constructor(\n\t\tcredentials: RuntimeCredentials,\n\t\tconfig: ModelConfig,\n\t\tmodelsPath: string | undefined,\n\t\tmodelsStore: ModelsStore,\n\t\tproviders: readonly Provider[],\n\t\tmodelNetworkEnabled: boolean,\n\t) {\n\t\tthis.credentials = credentials;\n\t\tthis.config = config;\n\t\tthis.modelsPath = modelsPath;\n\t\tthis.modelNetworkEnabled = modelNetworkEnabled;\n\t\tthis.defaultBuiltins = new Map(providers.map((provider) => [provider.id, provider]));\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tthis.models = createModels({ credentials, modelsStore });\n\t\tthis.rebuildProviders();\n\t}\n\n\tstatic async create(options: CreateModelRuntimeOptions = {}): Promise {\n\t\tconst credentials = new RuntimeCredentials(options.credentials ?? DefaultAuthStorage.create(options.authPath));\n\t\tconst modelsPath =\n\t\t\toptions.modelsPath === null ? undefined : (options.modelsPath ?? join(getAgentDir(), \"models.json\"));\n\t\tconst config = await ModelConfig.load(modelsPath);\n\t\tconst modelsStore =\n\t\t\toptions.modelsStore ??\n\t\t\t(modelsPath\n\t\t\t\t? new FileModelsStore(options.modelsStorePath ?? join(dirname(modelsPath), \"models-store.json\"))\n\t\t\t\t: new InMemoryCodingAgentModelsStore());\n\t\tconst builtinModelDataGeneratedAt = builtinProviderCatalog.getBuiltinModelDataGeneratedAt();\n\t\tconst providers = builtinProviderCatalog\n\t\t\t.builtinProviders()\n\t\t\t.map((provider) =>\n\t\t\t\tprovider.id === \"radius\"\n\t\t\t\t\t? provider\n\t\t\t\t\t: withRemoteCatalog(provider, options.catalogBaseUrl, builtinModelDataGeneratedAt),\n\t\t\t);\n\t\tconst runtime = new ModelRuntime(\n\t\t\tcredentials,\n\t\t\tconfig,\n\t\t\tmodelsPath,\n\t\t\tmodelsStore,\n\t\t\tproviders,\n\t\t\tprocess.env.PI_OFFLINE === undefined,\n\t\t);\n\t\truntime.configureRadiusProviders();\n\t\truntime.rebuildProviders();\n\t\tconst refreshFromNetwork = runtime.modelNetworkEnabled && options.allowModelNetwork === true;\n\t\tconst controller = refreshFromNetwork ? new AbortController() : undefined;\n\t\tconst timeout = controller\n\t\t\t? setTimeout(() => controller.abort(), options.modelRefreshTimeoutMs ?? 15_000)\n\t\t\t: undefined;\n\t\ttry {\n\t\t\tawait runtime.refresh({ allowNetwork: refreshFromNetwork, signal: controller?.signal });\n\t\t} finally {\n\t\t\tif (timeout) clearTimeout(timeout);\n\t\t}\n\t\treturn runtime;\n\t}\n\n\tprivate configureRadiusProviders(): void {\n\t\tthis.builtins.clear();\n\t\tfor (const [providerId, provider] of this.defaultBuiltins) this.builtins.set(providerId, provider);\n\t\tfor (const providerId of this.config.getProviderIds()) {\n\t\t\tconst config = this.config.getProvider(providerId);\n\t\t\tif (config?.oauth !== \"radius\" || !config.baseUrl) continue;\n\t\t\tthis.builtins.set(\n\t\t\t\tproviderId,\n\t\t\t\tbuiltinProviderCatalog.radiusProvider({\n\t\t\t\t\tid: providerId,\n\t\t\t\t\tname: config.name ?? providerId,\n\t\t\t\t\tgateway: config.baseUrl.replace(/\\/v1\\/?$/u, \"\"),\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate providerIds(): Set {\n\t\treturn new Set([\n\t\t\t...this.builtins.keys(),\n\t\t\t...this.nativeExtensionProviders.keys(),\n\t\t\t...this.config.getProviderIds(),\n\t\t\t...this.extensionProviders.keys(),\n\t\t]);\n\t}\n\n\tprivate recomposeProvider(providerId: string): void {\n\t\tconst base = this.nativeExtensionProviders.get(providerId) ?? this.builtins.get(providerId);\n\t\tconst extension = this.extensionProviders.get(providerId);\n\t\tif (!base && !this.config.getProvider(providerId) && !extension) {\n\t\t\tthis.models.deleteProvider(providerId);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\tif (base && !this.config.getProvider(providerId) && !extension) {\n\t\t\t// No overlays: use the builtin untouched so its auth/login/stream behavior is exact.\n\t\t\tthis.models.setProvider(base);\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.models.setProvider(composeModelProvider(providerId, base, this.config, extension));\n\t\t\tthis.compositionErrors.delete(providerId);\n\t\t} catch (error) {\n\t\t\tthis.compositionErrors.set(providerId, error instanceof Error ? error.message : String(error));\n\t\t\tif (base) this.models.setProvider(base);\n\t\t\telse this.models.deleteProvider(providerId);\n\t\t}\n\t}\n\n\tprivate rebuildProviders(): void {\n\t\tthis.models.clearProviders();\n\t\tthis.compositionErrors.clear();\n\t\tfor (const providerId of this.providerIds()) this.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t}\n\n\tprivate updateModelSnapshot(): void {\n\t\tconst all = [...this.models.getModels()];\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tall,\n\t\t\tavailable: all.filter((model) => this.snapshot.configuredProviders.has(model.provider)),\n\t\t};\n\t}\n\n\tprivate async runAvailabilityRefresh(): Promise {\n\t\tconst providers = this.models.getProviders();\n\t\tconst [available, checks, credentials] = await Promise.all([\n\t\t\tthis.models.getAvailable(),\n\t\t\tPromise.all(\n\t\t\t\tproviders.map(\n\t\t\t\t\tasync (provider): Promise<[string, AuthCheck | undefined]> => [\n\t\t\t\t\t\tprovider.id,\n\t\t\t\t\t\tawait this.models.checkAuth(provider.id),\n\t\t\t\t\t],\n\t\t\t\t),\n\t\t\t),\n\t\t\tthis.credentials.list(),\n\t\t]);\n\t\tconst auth = new Map(checks);\n\t\tconst configuredProviders = new Set(\n\t\t\tchecks\n\t\t\t\t.filter((entry): entry is [string, AuthCheck] => entry[1] !== undefined)\n\t\t\t\t.map(([providerId]) => providerId),\n\t\t);\n\t\tthis.snapshot = {\n\t\t\tall: [...this.models.getModels()],\n\t\t\tavailable: [...available],\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders: new Set(credentials.map((entry) => entry.providerId)),\n\t\t\tauth,\n\t\t};\n\t\tthis.availabilityError = undefined;\n\t}\n\n\tprivate queueAvailabilityRefresh(after: Promise | undefined): Promise {\n\t\tconst refresh = (after ?? Promise.resolve()).catch(() => {}).then(() => this.runAvailabilityRefresh());\n\t\tconst recorded = refresh.catch((error) => {\n\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\tthrow error;\n\t\t});\n\t\tconst tracked = recorded.finally(() => {\n\t\t\tif (this.availabilityRefresh === tracked) this.availabilityRefresh = undefined;\n\t\t});\n\t\tthis.availabilityRefresh = tracked;\n\t\treturn tracked;\n\t}\n\n\t/** Coalesce concurrent readers onto the pending refresh. */\n\tprivate refreshAvailability(): Promise {\n\t\treturn this.availabilityRefresh ?? this.queueAvailabilityRefresh(undefined);\n\t}\n\n\t/** Mutations must not observe an in-flight refresh started before them. */\n\tprivate forceRefreshAvailability(): Promise {\n\t\treturn this.queueAvailabilityRefresh(this.availabilityRefresh);\n\t}\n\n\tgetProviders(): readonly Provider[] {\n\t\treturn this.models.getProviders();\n\t}\n\n\tgetProvider(providerId: string): Provider | undefined {\n\t\treturn this.models.getProvider(providerId);\n\t}\n\n\tgetModels(providerId?: string): readonly Model[] {\n\t\treturn this.models.getModels(providerId);\n\t}\n\n\tgetModel(providerId: string, modelId: string): Model | undefined {\n\t\treturn this.models.getModel(providerId, modelId);\n\t}\n\n\tasync checkAuth(providerId: string): Promise {\n\t\treturn this.models.checkAuth(providerId);\n\t}\n\n\tasync getAvailable(providerId?: string): Promise[]> {\n\t\tif (providerId) {\n\t\t\tif (this.availabilityRefresh) {\n\t\t\t\tawait this.availabilityRefresh;\n\t\t\t\treturn this.snapshot.available.filter((model) => model.provider === providerId);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await this.models.getAvailable(providerId);\n\t\t\t} catch (error) {\n\t\t\t\tthis.availabilityError = error instanceof Error ? error.message : String(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tawait this.refreshAvailability();\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetAvailableSnapshot(): readonly Model[] {\n\t\treturn this.snapshot.available;\n\t}\n\n\tgetError(): string | undefined {\n\t\tconst errors: string[] = [];\n\t\tconst configError = this.config.getError();\n\t\tif (configError) errors.push(configError);\n\t\tfor (const [providerId, error] of this.compositionErrors) {\n\t\t\terrors.push(`Provider \"${providerId}\": ${error}`);\n\t\t}\n\t\tif (this.availabilityError) errors.push(`Availability refresh: ${this.availabilityError}`);\n\t\treturn errors.length > 0 ? errors.join(\"\\n\\n\") : undefined;\n\t}\n\n\tgetRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined {\n\t\treturn this.extensionProviders.get(providerId);\n\t}\n\n\tgetRegisteredProviderIds(): readonly string[] {\n\t\treturn [...new Set([...this.extensionProviders.keys(), ...this.nativeExtensionProviders.keys()])];\n\t}\n\n\tgetRegisteredNativeProvider(providerId: string): Provider | undefined {\n\t\treturn this.nativeExtensionProviders.get(providerId);\n\t}\n\n\t/** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */\n\tgetCompatibilityRequestConfig(model: Model): CompatibilityRequestConfig {\n\t\treturn resolveCompatibilityRequestConfig(\n\t\t\tmodel,\n\t\t\tthis.config.getProvider(model.provider),\n\t\t\tthis.extensionProviders.get(model.provider),\n\t\t);\n\t}\n\n\tisUsingOAuth(providerId: string): boolean {\n\t\treturn this.snapshot.auth.get(providerId)?.type === \"oauth\";\n\t}\n\n\thasConfiguredAuth(providerId: string): boolean {\n\t\treturn this.snapshot.configuredProviders.has(providerId);\n\t}\n\n\tgetAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise;\n\tgetAuth(model: Model, overrides?: ModelRuntimeAuthOverrides): Promise;\n\tasync getAuth(\n\t\tproviderOrModel: string | Model,\n\t\toverrides: ModelRuntimeAuthOverrides = {},\n\t): Promise {\n\t\tif (typeof providerOrModel === \"string\") return this.models.getAuth(providerOrModel, overrides);\n\t\tconst resolution = await this.models.getAuth(providerOrModel, overrides);\n\t\tif (!resolution) return undefined;\n\t\tconst configuredHeaders = resolveConfiguredModelHeaders(\n\t\t\tproviderOrModel,\n\t\t\tthis.config.getProvider(providerOrModel.provider),\n\t\t\tthis.extensionProviders.get(providerOrModel.provider),\n\t\t\t{ ...(resolution.env ?? {}), ...(overrides.env ?? {}) },\n\t\t);\n\t\treturn {\n\t\t\t...resolution,\n\t\t\tauth: {\n\t\t\t\t...resolution.auth,\n\t\t\t\theaders: mergeHeaders(resolution.auth.headers, configuredHeaders),\n\t\t\t},\n\t\t};\n\t}\n\n\tasync setRuntimeApiKey(\n\t\tproviderId: string,\n\t\tapiKey: string,\n\t\trefreshOptions: ModelsRefreshOptions = {},\n\t): Promise {\n\t\tthis.credentials.setRuntimeApiKey(providerId, apiKey);\n\t\tconst auth = new Map(this.snapshot.auth).set(providerId, { type: \"api_key\", source: \"runtime API key\" });\n\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\tconst storedProviders = new Set(this.snapshot.storedProviders).add(providerId);\n\t\tthis.snapshot = {\n\t\t\t...this.snapshot,\n\t\t\tauth,\n\t\t\tconfiguredProviders,\n\t\t\tstoredProviders,\n\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t};\n\t\tawait this.refresh(refreshOptions);\n\t}\n\n\tasync removeRuntimeApiKey(providerId: string): Promise {\n\t\tthis.credentials.removeRuntimeApiKey(providerId);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tlistCredentials(): Promise {\n\t\treturn this.credentials.list();\n\t}\n\n\tgetProviderAuthStatus(providerId: string): AuthStatus {\n\t\tif (this.credentials.hasRuntimeApiKey(providerId)) return { configured: true, source: \"runtime\" };\n\t\tif (this.snapshot.storedProviders.has(providerId)) return { configured: true, source: \"stored\" };\n\t\tconst configured = configuredRequestAuthStatus(\n\t\t\tthis.config.getProvider(providerId),\n\t\t\tthis.extensionProviders.get(providerId),\n\t\t);\n\t\tif (configured) return configured;\n\t\tconst check = this.snapshot.auth.get(providerId);\n\t\treturn check ? { configured: true, source: \"environment\", label: check.source } : { configured: false };\n\t}\n\n\tprivate async prepareRequest(\n\t\tmodel: Model,\n\t\toptions: (StreamOptions & ModelsStreamTransforms) | undefined,\n\t): Promise<{ provider: Provider; model: Model; options: StreamOptions }> {\n\t\tconst provider = this.models.getProvider(model.provider);\n\t\tif (!provider) throw new ModelsError(\"provider\", `Unknown provider: ${model.provider}`);\n\t\tconst resolution = await this.getAuth(model, { apiKey: options?.apiKey, env: options?.env });\n\t\tif (!resolution) throw new ModelsError(\"auth\", `Provider is not configured: ${model.provider}`);\n\n\t\tconst { transformHeaders, ...providerOptions } = options ?? {};\n\t\tlet headers = mergeHeaders(resolution.auth.headers, providerOptions.headers);\n\t\tif (transformHeaders) headers = await transformHeaders(headers ?? {});\n\t\tconst env =\n\t\t\tresolution.env || providerOptions.env\n\t\t\t\t? { ...(resolution.env ?? {}), ...(providerOptions.env ?? {}) }\n\t\t\t\t: undefined;\n\t\treturn {\n\t\t\tprovider,\n\t\t\tmodel: resolution.auth.baseUrl ? { ...model, baseUrl: resolution.auth.baseUrl } : model,\n\t\t\toptions: {\n\t\t\t\t...providerOptions,\n\t\t\t\tapiKey: providerOptions.apiKey ?? resolution.auth.apiKey,\n\t\t\t\theaders,\n\t\t\t\tenv,\n\t\t\t},\n\t\t};\n\t}\n\n\tstream(\n\t\tmodel: Model,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions,\n\t): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(\n\t\t\t\tmodel,\n\t\t\t\toptions as (StreamOptions & ModelsStreamTransforms) | undefined,\n\t\t\t);\n\t\t\treturn prepared.provider.stream(\n\t\t\t\tprepared.model as Model,\n\t\t\t\tcontext,\n\t\t\t\tprepared.options as ApiStreamOptions,\n\t\t\t);\n\t\t});\n\t}\n\n\tcomplete(\n\t\tmodel: Model,\n\t\tcontext: Context,\n\t\toptions?: ModelsApiStreamOptions,\n\t): Promise {\n\t\treturn this.stream(model, context, options).result();\n\t}\n\n\tstreamSimple(model: Model, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream {\n\t\treturn lazyStream(model, async () => {\n\t\t\tconst prepared = await this.prepareRequest(model, options);\n\t\t\treturn prepared.provider.streamSimple(prepared.model, context, prepared.options as SimpleStreamOptions);\n\t\t});\n\t}\n\n\tcompleteSimple(model: Model, context: Context, options?: ModelsSimpleStreamOptions): Promise {\n\t\treturn this.streamSimple(model, context, options).result();\n\t}\n\n\tasync login(providerId: string, type: AuthType, interaction: AuthInteraction): Promise {\n\t\tconst credential = await this.models.login(providerId, type, interaction);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t\treturn credential;\n\t}\n\n\tasync logout(providerId: string): Promise {\n\t\tawait this.models.logout(providerId);\n\t\t// Reset credential-dependent compatibility projections before the unconfigured provider is skipped by refresh.\n\t\tthis.recomposeProvider(providerId);\n\t\tawait this.refresh({ allowNetwork: this.modelNetworkEnabled });\n\t}\n\n\tasync refresh(options: ModelsRefreshOptions = {}): Promise {\n\t\tthis.config = await ModelConfig.load(this.modelsPath);\n\t\tthis.configureRadiusProviders();\n\t\tthis.rebuildProviders();\n\t\tconst refreshOptions = {\n\t\t\t...options,\n\t\t\tallowNetwork: options.allowNetwork ?? this.modelNetworkEnabled,\n\t\t};\n\t\t// Published pi-ai builds before ModelsStore returned void and accepted a provider ID.\n\t\t// The fallback keeps source-mode CLI tests working without rebuilding workspace dependencies.\n\t\tconst result = ((await this.models.refresh(refreshOptions)) as ModelsRefreshResult | undefined) ?? {\n\t\t\taborted: refreshOptions.signal?.aborted ?? false,\n\t\t\terrors: new Map(),\n\t\t};\n\t\tthis.updateModelSnapshot();\n\t\ttry {\n\t\t\tawait this.forceRefreshAvailability();\n\t\t} catch {\n\t\t\t// Availability errors are recorded by forceRefreshAvailability; refreshed models remain usable.\n\t\t}\n\t\treturn result;\n\t}\n\n\tregisterNativeProvider(provider: Provider): void {\n\t\tif (!provider.id.trim()) throw new Error(\"Provider id must not be empty.\");\n\t\tthis.extensionProviders.delete(provider.id);\n\t\tthis.nativeExtensionProviders.set(provider.id, provider);\n\t\tthis.recomposeProvider(provider.id);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tregisterProvider(providerId: string, config: ProviderConfigInput): void {\n\t\t// Validate the incoming registration on its own, like the legacy registry:\n\t\t// a broken re-registration must throw without touching the stored config.\n\t\tvalidateExtensionProvider(providerId, this.builtins.get(providerId), this.config.getProvider(providerId), config);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\t// Re-registration merges defined values over the previous registration and\n\t\t// preserves undefined ones, matching the legacy ModelRegistry contract.\n\t\tconst previous = this.extensionProviders.get(providerId);\n\t\tconst effective: ProviderConfigInput = { ...previous };\n\t\tfor (const [key, value] of Object.entries(config)) {\n\t\t\tif (value !== undefined) (effective as Record)[key] = value;\n\t\t}\n\t\tthis.extensionProviders.set(providerId, effective);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tif (\n\t\t\tthis.snapshot.storedProviders.has(providerId) ||\n\t\t\tconfiguredRequestAuthStatus(this.config.getProvider(providerId), effective)?.configured\n\t\t) {\n\t\t\tconst configuredProviders = new Set(this.snapshot.configuredProviders).add(providerId);\n\t\t\tconst auth = new Map(this.snapshot.auth);\n\t\t\t// Provisional entry until the async refresh lands; never clobber a real check result.\n\t\t\tif (!auth.get(providerId)) {\n\t\t\t\tauth.set(providerId, {\n\t\t\t\t\ttype: effective.oauth && !effective.apiKey ? \"oauth\" : \"api_key\",\n\t\t\t\t\tsource: \"configured provider\",\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.snapshot = {\n\t\t\t\t...this.snapshot,\n\t\t\t\tauth,\n\t\t\t\tconfiguredProviders,\n\t\t\t\tavailable: this.snapshot.all.filter((model) => configuredProviders.has(model.provider)),\n\t\t\t};\n\t\t}\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n\n\tunregisterProvider(providerId: string): void {\n\t\tthis.extensionProviders.delete(providerId);\n\t\tthis.nativeExtensionProviders.delete(providerId);\n\t\tthis.recomposeProvider(providerId);\n\t\tthis.updateModelSnapshot();\n\t\tvoid this.refresh({ allowNetwork: false });\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/models-store.d.ts b/dist/core/models-store.d.ts new file mode 100644 index 0000000..c710509 --- /dev/null +++ b/dist/core/models-store.d.ts @@ -0,0 +1,17 @@ +import type { ModelsStore, ModelsStoreEntry } from "@earendil-works/pi-ai"; +export declare class InMemoryCodingAgentModelsStore implements ModelsStore { + private readonly entries; + read(providerId: string): Promise; + write(providerId: string, entry: ModelsStoreEntry): Promise; + delete(providerId: string): Promise; +} +/** Locked JSON-backed storage for dynamically refreshed provider catalogs. */ +export declare class FileModelsStore implements ModelsStore { + private readonly storage; + constructor(path?: string); + private parse; + read(providerId: string): Promise; + write(providerId: string, entry: ModelsStoreEntry): Promise; + delete(providerId: string): Promise; +} +//# sourceMappingURL=models-store.d.ts.map \ No newline at end of file diff --git a/dist/core/models-store.d.ts.map b/dist/core/models-store.d.ts.map new file mode 100644 index 0000000..af6488b --- /dev/null +++ b/dist/core/models-store.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"models-store.d.ts","sourceRoot":"","sources":["../../src/core/models-store.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAM3E,qBAAa,8BAA+B,YAAW,WAAW;IACjE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAuC;IAEzD,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAEpE;IAEK,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAEtE;IAEK,MAAM,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAE9C;CACD;AAED,8EAA8E;AAC9E,qBAAa,eAAgB,YAAW,WAAW;IAClD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAE7C,YAAY,IAAI,GAAE,MAAiD,EAElE;IAED,OAAO,CAAC,KAAK;IAIP,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAIpE;IAEK,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAMtE;IAEK,MAAM,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAM9C;CACD","sourcesContent":["import { join } from \"node:path\";\nimport type { ModelsStore, ModelsStoreEntry } from \"@earendil-works/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { type AuthStorageBackend, FileAuthStorageBackend } from \"./auth-storage.ts\";\n\ntype StoredModels = Record;\n\nexport class InMemoryCodingAgentModelsStore implements ModelsStore {\n\tprivate readonly entries = new Map();\n\n\tasync read(providerId: string): Promise {\n\t\treturn this.entries.get(providerId);\n\t}\n\n\tasync write(providerId: string, entry: ModelsStoreEntry): Promise {\n\t\tthis.entries.set(providerId, entry);\n\t}\n\n\tasync delete(providerId: string): Promise {\n\t\tthis.entries.delete(providerId);\n\t}\n}\n\n/** Locked JSON-backed storage for dynamically refreshed provider catalogs. */\nexport class FileModelsStore implements ModelsStore {\n\tprivate readonly storage: AuthStorageBackend;\n\n\tconstructor(path: string = join(getAgentDir(), \"models-store.json\")) {\n\t\tthis.storage = new FileAuthStorageBackend(path);\n\t}\n\n\tprivate parse(content: string | undefined): StoredModels {\n\t\treturn content ? (JSON.parse(content) as StoredModels) : {};\n\t}\n\n\tasync read(providerId: string): Promise {\n\t\treturn this.storage.withLock((content) => ({\n\t\t\tresult: structuredClone(this.parse(content)[providerId]),\n\t\t}));\n\t}\n\n\tasync write(providerId: string, entry: ModelsStoreEntry): Promise {\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst current = this.parse(content);\n\t\t\tcurrent[providerId] = structuredClone(entry);\n\t\t\treturn { result: undefined, next: JSON.stringify(current, null, 2) };\n\t\t});\n\t}\n\n\tasync delete(providerId: string): Promise {\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst current = this.parse(content);\n\t\t\tdelete current[providerId];\n\t\t\treturn { result: undefined, next: JSON.stringify(current, null, 2) };\n\t\t});\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/models-store.js b/dist/core/models-store.js new file mode 100644 index 0000000..d810aa1 --- /dev/null +++ b/dist/core/models-store.js @@ -0,0 +1,45 @@ +import { join } from "node:path"; +import { getAgentDir } from "../config.js"; +import { FileAuthStorageBackend } from "./auth-storage.js"; +export class InMemoryCodingAgentModelsStore { + entries = new Map(); + async read(providerId) { + return this.entries.get(providerId); + } + async write(providerId, entry) { + this.entries.set(providerId, entry); + } + async delete(providerId) { + this.entries.delete(providerId); + } +} +/** Locked JSON-backed storage for dynamically refreshed provider catalogs. */ +export class FileModelsStore { + storage; + constructor(path = join(getAgentDir(), "models-store.json")) { + this.storage = new FileAuthStorageBackend(path); + } + parse(content) { + return content ? JSON.parse(content) : {}; + } + async read(providerId) { + return this.storage.withLock((content) => ({ + result: structuredClone(this.parse(content)[providerId]), + })); + } + async write(providerId, entry) { + await this.storage.withLockAsync(async (content) => { + const current = this.parse(content); + current[providerId] = structuredClone(entry); + return { result: undefined, next: JSON.stringify(current, null, 2) }; + }); + } + async delete(providerId) { + await this.storage.withLockAsync(async (content) => { + const current = this.parse(content); + delete current[providerId]; + return { result: undefined, next: JSON.stringify(current, null, 2) }; + }); + } +} +//# sourceMappingURL=models-store.js.map \ No newline at end of file diff --git a/dist/core/models-store.js.map b/dist/core/models-store.js.map new file mode 100644 index 0000000..ea9ed09 --- /dev/null +++ b/dist/core/models-store.js.map @@ -0,0 +1 @@ +{"version":3,"file":"models-store.js","sourceRoot":"","sources":["../../src/core/models-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAA2B,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAIpF,MAAM,OAAO,8BAA8B;IACzB,OAAO,GAAG,IAAI,GAAG,EAA4B,CAAC;IAE/D,KAAK,CAAC,IAAI,CAAC,UAAkB,EAAyC;QACrE,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IAAA,CACpC;IAED,KAAK,CAAC,KAAK,CAAC,UAAkB,EAAE,KAAuB,EAAiB;QACvE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IAAA,CACpC;IAED,KAAK,CAAC,MAAM,CAAC,UAAkB,EAAiB;QAC/C,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,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AI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACpC,OAAO,OAAO,CAAC,UAAU,CAAC,CAAC;YAC3B,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;QAAA,CACrE,CAAC,CAAC;IAAA,CACH;CACD","sourcesContent":["import { join } from \"node:path\";\nimport type { ModelsStore, ModelsStoreEntry } from \"@earendil-works/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { type AuthStorageBackend, FileAuthStorageBackend } from \"./auth-storage.ts\";\n\ntype StoredModels = Record;\n\nexport class InMemoryCodingAgentModelsStore implements ModelsStore {\n\tprivate readonly entries = new Map();\n\n\tasync read(providerId: string): Promise {\n\t\treturn this.entries.get(providerId);\n\t}\n\n\tasync write(providerId: string, entry: ModelsStoreEntry): Promise {\n\t\tthis.entries.set(providerId, entry);\n\t}\n\n\tasync delete(providerId: string): Promise {\n\t\tthis.entries.delete(providerId);\n\t}\n}\n\n/** Locked JSON-backed storage for dynamically refreshed provider catalogs. */\nexport class FileModelsStore implements ModelsStore {\n\tprivate readonly storage: AuthStorageBackend;\n\n\tconstructor(path: string = join(getAgentDir(), \"models-store.json\")) {\n\t\tthis.storage = new FileAuthStorageBackend(path);\n\t}\n\n\tprivate parse(content: string | undefined): StoredModels {\n\t\treturn content ? (JSON.parse(content) as StoredModels) : {};\n\t}\n\n\tasync read(providerId: string): Promise {\n\t\treturn this.storage.withLock((content) => ({\n\t\t\tresult: structuredClone(this.parse(content)[providerId]),\n\t\t}));\n\t}\n\n\tasync write(providerId: string, entry: ModelsStoreEntry): Promise {\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst current = this.parse(content);\n\t\t\tcurrent[providerId] = structuredClone(entry);\n\t\t\treturn { result: undefined, next: JSON.stringify(current, null, 2) };\n\t\t});\n\t}\n\n\tasync delete(providerId: string): Promise {\n\t\tawait this.storage.withLockAsync(async (content) => {\n\t\t\tconst current = this.parse(content);\n\t\t\tdelete current[providerId];\n\t\t\treturn { result: undefined, next: JSON.stringify(current, null, 2) };\n\t\t});\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/output-guard.d.ts b/dist/core/output-guard.d.ts new file mode 100644 index 0000000..3dfe100 --- /dev/null +++ b/dist/core/output-guard.d.ts @@ -0,0 +1,7 @@ +export declare function takeOverStdout(): void; +export declare function restoreStdout(): void; +export declare function isStdoutTakenOver(): boolean; +export declare function writeRawStdout(text: string): void; +export declare function waitForRawStdoutBackpressure(): Promise; +export declare function flushRawStdout(): Promise; +//# sourceMappingURL=output-guard.d.ts.map \ No newline at end of file diff --git a/dist/core/output-guard.d.ts.map b/dist/core/output-guard.d.ts.map new file mode 100644 index 0000000..2a8c411 --- /dev/null +++ b/dist/core/output-guard.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"output-guard.d.ts","sourceRoot":"","sources":["../../src/core/output-guard.ts"],"names":[],"mappings":"AA4CA,wBAAgB,cAAc,IAAI,IAAI,CAyBrC;AAED,wBAAgB,aAAa,IAAI,IAAI,CAOpC;AAED,wBAAgB,iBAAiB,IAAI,OAAO,CAE3C;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAQjD;AAED,wBAAsB,4BAA4B,IAAI,OAAO,CAAC,IAAI,CAAC,CAQlE;AAED,wBAAsB,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,CAGpD","sourcesContent":["interface StdoutTakeoverState {\n\trawStdoutWrite: (chunk: string, callback?: (error?: Error | null) => void) => boolean;\n\trawStderrWrite: (chunk: string, callback?: (error?: Error | null) => void) => boolean;\n\toriginalStdoutWrite: typeof process.stdout.write;\n}\n\nlet stdoutTakeoverState: StdoutTakeoverState | undefined;\n\nconst RAW_STDOUT_RETRY_DELAY_MS = 10;\n\nlet rawStdoutWriteTail: Promise = Promise.resolve();\n\nfunction getRawStdoutWrite(): StdoutTakeoverState[\"rawStdoutWrite\"] {\n\tif (stdoutTakeoverState) {\n\t\treturn stdoutTakeoverState.rawStdoutWrite;\n\t}\n\treturn process.stdout.write.bind(process.stdout) as StdoutTakeoverState[\"rawStdoutWrite\"];\n}\n\nasync function writeRawStdoutChunk(text: string): Promise {\n\twhile (true) {\n\t\ttry {\n\t\t\tawait new Promise((resolve, reject) => {\n\t\t\t\ttry {\n\t\t\t\t\tgetRawStdoutWrite()(text, (error) => {\n\t\t\t\t\t\tif (error) reject(error);\n\t\t\t\t\t\telse resolve();\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn;\n\t\t} catch (error) {\n\t\t\tconst writeError = error instanceof Error ? error : new Error(String(error));\n\t\t\tconst code = (writeError as Error & { code?: unknown }).code;\n\t\t\tif (code !== \"ENOBUFS\" && code !== \"EAGAIN\" && code !== \"EWOULDBLOCK\") {\n\t\t\t\tthrow writeError;\n\t\t\t}\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, RAW_STDOUT_RETRY_DELAY_MS));\n\t\t}\n\t}\n}\n\nexport function takeOverStdout(): void {\n\tif (stdoutTakeoverState) {\n\t\treturn;\n\t}\n\n\tconst rawStdoutWrite = process.stdout.write.bind(process.stdout) as StdoutTakeoverState[\"rawStdoutWrite\"];\n\tconst rawStderrWrite = process.stderr.write.bind(process.stderr) as StdoutTakeoverState[\"rawStderrWrite\"];\n\tconst originalStdoutWrite = process.stdout.write;\n\n\tprocess.stdout.write = ((\n\t\tchunk: string | Uint8Array,\n\t\tencodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),\n\t\tcallback?: (error?: Error | null) => void,\n\t): boolean => {\n\t\tif (typeof encodingOrCallback === \"function\") {\n\t\t\treturn rawStderrWrite(String(chunk), encodingOrCallback);\n\t\t}\n\t\treturn rawStderrWrite(String(chunk), callback);\n\t}) as typeof process.stdout.write;\n\n\tstdoutTakeoverState = {\n\t\trawStdoutWrite,\n\t\trawStderrWrite,\n\t\toriginalStdoutWrite,\n\t};\n}\n\nexport function restoreStdout(): void {\n\tif (!stdoutTakeoverState) {\n\t\treturn;\n\t}\n\n\tprocess.stdout.write = stdoutTakeoverState.originalStdoutWrite;\n\tstdoutTakeoverState = undefined;\n}\n\nexport function isStdoutTakenOver(): boolean {\n\treturn stdoutTakeoverState !== undefined;\n}\n\nexport function writeRawStdout(text: string): void {\n\tif (text.length === 0) {\n\t\treturn;\n\t}\n\trawStdoutWriteTail = rawStdoutWriteTail.then(() => writeRawStdoutChunk(text));\n\tvoid rawStdoutWriteTail.catch(() => {\n\t\tprocess.exit(1);\n\t});\n}\n\nexport async function waitForRawStdoutBackpressure(): Promise {\n\twhile (true) {\n\t\tconst tail = rawStdoutWriteTail;\n\t\tawait tail;\n\t\tif (tail === rawStdoutWriteTail) {\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nexport async function flushRawStdout(): Promise {\n\tawait waitForRawStdoutBackpressure();\n\tawait writeRawStdoutChunk(\"\");\n}\n"]} \ No newline at end of file diff --git a/dist/core/output-guard.js b/dist/core/output-guard.js new file mode 100644 index 0000000..0b7e20a --- /dev/null +++ b/dist/core/output-guard.js @@ -0,0 +1,89 @@ +let stdoutTakeoverState; +const RAW_STDOUT_RETRY_DELAY_MS = 10; +let rawStdoutWriteTail = Promise.resolve(); +function getRawStdoutWrite() { + if (stdoutTakeoverState) { + return stdoutTakeoverState.rawStdoutWrite; + } + return process.stdout.write.bind(process.stdout); +} +async function writeRawStdoutChunk(text) { + while (true) { + try { + await new Promise((resolve, reject) => { + try { + getRawStdoutWrite()(text, (error) => { + if (error) + reject(error); + else + resolve(); + }); + } + catch (error) { + reject(error instanceof Error ? error : new Error(String(error))); + } + }); + return; + } + catch (error) { + const writeError = error instanceof Error ? error : new Error(String(error)); + const code = writeError.code; + if (code !== "ENOBUFS" && code !== "EAGAIN" && code !== "EWOULDBLOCK") { + throw writeError; + } + await new Promise((resolve) => setTimeout(resolve, RAW_STDOUT_RETRY_DELAY_MS)); + } + } +} +export function takeOverStdout() { + if (stdoutTakeoverState) { + return; + } + const rawStdoutWrite = process.stdout.write.bind(process.stdout); + const rawStderrWrite = process.stderr.write.bind(process.stderr); + const originalStdoutWrite = process.stdout.write; + process.stdout.write = ((chunk, encodingOrCallback, callback) => { + if (typeof encodingOrCallback === "function") { + return rawStderrWrite(String(chunk), encodingOrCallback); + } + return rawStderrWrite(String(chunk), callback); + }); + stdoutTakeoverState = { + rawStdoutWrite, + rawStderrWrite, + originalStdoutWrite, + }; +} +export function restoreStdout() { + if (!stdoutTakeoverState) { + return; + } + process.stdout.write = stdoutTakeoverState.originalStdoutWrite; + stdoutTakeoverState = undefined; +} +export function isStdoutTakenOver() { + return stdoutTakeoverState !== undefined; +} +export function writeRawStdout(text) { + if (text.length === 0) { + return; + } + rawStdoutWriteTail = rawStdoutWriteTail.then(() => writeRawStdoutChunk(text)); + void rawStdoutWriteTail.catch(() => { + process.exit(1); + }); +} +export async function waitForRawStdoutBackpressure() { + while (true) { + const tail = rawStdoutWriteTail; + await tail; + if (tail === rawStdoutWriteTail) { + return; + } + } +} +export async function flushRawStdout() { + await waitForRawStdoutBackpressure(); + await writeRawStdoutChunk(""); +} +//# sourceMappingURL=output-guard.js.map \ No newline at end of file diff --git a/dist/core/output-guard.js.map b/dist/core/output-guard.js.map new file mode 100644 index 0000000..7336a40 --- /dev/null +++ b/dist/core/output-guard.js.map @@ -0,0 +1 @@ +{"version":3,"file":"output-guard.js","sourceRoot":"","sources":["../../src/core/output-guard.ts"],"names":[],"mappings":"AAMA,IAAI,mBAAoD,CAAC;AAEzD,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAErC,IAAI,kBAAkB,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;AAE1D,SAAS,iBAAiB,GAA0C;IACnE,IAAI,mBAAmB,EAAE,CAAC;QACzB,OAAO,mBAAmB,CAAC,cAAc,CAAC;IAC3C,CAAC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CAAC,IAAI,CAAC,CAAC,CAAC;IAC9E,KAAK,kBAAkB,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC;QACnC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAAA,CAChB,CAAC,CAAC;AAAA,CACH;AAED,MAAM,CAAC,KAAK,UAAU,4BAA4B,GAAkB;IACnE,OAAO,IAAI,EAAE,CAAC;QACb,MAAM,IAAI,GAAG,kBAAkB,CAAC;QAChC,MAAM,IAAI,CAAC;QACX,IAAI,IAAI,KAAK,kBAAkB,EAAE,CAAC;YACjC,OAAO;QACR,CAAC;IACF,CAAC;AAAA,CACD;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,GAAkB;IACrD,MAAM,4BAA4B,EAAE,CAAC;IACrC,MAAM,mBAAmB,CAAC,EAAE,CAAC,CAAC;AAAA,CAC9B","sourcesContent":["interface StdoutTakeoverState {\n\trawStdoutWrite: (chunk: string, callback?: (error?: Error | null) => void) => boolean;\n\trawStderrWrite: (chunk: string, callback?: (error?: Error | null) => void) => boolean;\n\toriginalStdoutWrite: typeof process.stdout.write;\n}\n\nlet stdoutTakeoverState: StdoutTakeoverState | undefined;\n\nconst RAW_STDOUT_RETRY_DELAY_MS = 10;\n\nlet rawStdoutWriteTail: Promise = Promise.resolve();\n\nfunction getRawStdoutWrite(): StdoutTakeoverState[\"rawStdoutWrite\"] {\n\tif (stdoutTakeoverState) {\n\t\treturn stdoutTakeoverState.rawStdoutWrite;\n\t}\n\treturn process.stdout.write.bind(process.stdout) as StdoutTakeoverState[\"rawStdoutWrite\"];\n}\n\nasync function writeRawStdoutChunk(text: string): Promise {\n\twhile (true) {\n\t\ttry {\n\t\t\tawait new Promise((resolve, reject) => {\n\t\t\t\ttry {\n\t\t\t\t\tgetRawStdoutWrite()(text, (error) => {\n\t\t\t\t\t\tif (error) reject(error);\n\t\t\t\t\t\telse resolve();\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn;\n\t\t} catch (error) {\n\t\t\tconst writeError = error instanceof Error ? error : new Error(String(error));\n\t\t\tconst code = (writeError as Error & { code?: unknown }).code;\n\t\t\tif (code !== \"ENOBUFS\" && code !== \"EAGAIN\" && code !== \"EWOULDBLOCK\") {\n\t\t\t\tthrow writeError;\n\t\t\t}\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, RAW_STDOUT_RETRY_DELAY_MS));\n\t\t}\n\t}\n}\n\nexport function takeOverStdout(): void {\n\tif (stdoutTakeoverState) {\n\t\treturn;\n\t}\n\n\tconst rawStdoutWrite = process.stdout.write.bind(process.stdout) as StdoutTakeoverState[\"rawStdoutWrite\"];\n\tconst rawStderrWrite = process.stderr.write.bind(process.stderr) as StdoutTakeoverState[\"rawStderrWrite\"];\n\tconst originalStdoutWrite = process.stdout.write;\n\n\tprocess.stdout.write = ((\n\t\tchunk: string | Uint8Array,\n\t\tencodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),\n\t\tcallback?: (error?: Error | null) => void,\n\t): boolean => {\n\t\tif (typeof encodingOrCallback === \"function\") {\n\t\t\treturn rawStderrWrite(String(chunk), encodingOrCallback);\n\t\t}\n\t\treturn rawStderrWrite(String(chunk), callback);\n\t}) as typeof process.stdout.write;\n\n\tstdoutTakeoverState = {\n\t\trawStdoutWrite,\n\t\trawStderrWrite,\n\t\toriginalStdoutWrite,\n\t};\n}\n\nexport function restoreStdout(): void {\n\tif (!stdoutTakeoverState) {\n\t\treturn;\n\t}\n\n\tprocess.stdout.write = stdoutTakeoverState.originalStdoutWrite;\n\tstdoutTakeoverState = undefined;\n}\n\nexport function isStdoutTakenOver(): boolean {\n\treturn stdoutTakeoverState !== undefined;\n}\n\nexport function writeRawStdout(text: string): void {\n\tif (text.length === 0) {\n\t\treturn;\n\t}\n\trawStdoutWriteTail = rawStdoutWriteTail.then(() => writeRawStdoutChunk(text));\n\tvoid rawStdoutWriteTail.catch(() => {\n\t\tprocess.exit(1);\n\t});\n}\n\nexport async function waitForRawStdoutBackpressure(): Promise {\n\twhile (true) {\n\t\tconst tail = rawStdoutWriteTail;\n\t\tawait tail;\n\t\tif (tail === rawStdoutWriteTail) {\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nexport async function flushRawStdout(): Promise {\n\tawait waitForRawStdoutBackpressure();\n\tawait writeRawStdoutChunk(\"\");\n}\n"]} \ No newline at end of file diff --git a/dist/core/package-manager.d.ts b/dist/core/package-manager.d.ts new file mode 100644 index 0000000..ec83cef --- /dev/null +++ b/dist/core/package-manager.d.ts @@ -0,0 +1,210 @@ +import type { SettingsManager } from "./settings-manager.ts"; +export interface PathMetadata { + source: string; + scope: SourceScope; + origin: "package" | "top-level"; + baseDir?: string; +} +export interface ResolvedResource { + path: string; + enabled: boolean; + metadata: PathMetadata; +} +export interface ResolvedPaths { + extensions: ResolvedResource[]; + skills: ResolvedResource[]; + prompts: ResolvedResource[]; + themes: ResolvedResource[]; +} +export type MissingSourceAction = "install" | "skip" | "error"; +export interface ProgressEvent { + type: "start" | "progress" | "complete" | "error"; + action: "install" | "remove" | "update" | "clone" | "pull"; + source: string; + message?: string; +} +export type ProgressCallback = (event: ProgressEvent) => void; +export interface PackageUpdate { + source: string; + displayName: string; + type: "npm" | "git"; + scope: Exclude; +} +export interface ConfiguredPackage { + source: string; + scope: "user" | "project"; + filtered: boolean; + installedPath?: string; +} +export interface PackageManager { + resolve(onMissing?: (source: string) => Promise): Promise; + install(source: string, options?: { + local?: boolean; + }): Promise; + installAndPersist(source: string, options?: { + local?: boolean; + }): Promise; + remove(source: string, options?: { + local?: boolean; + }): Promise; + removeAndPersist(source: string, options?: { + local?: boolean; + }): Promise; + update(source?: string): Promise; + listConfiguredPackages(): ConfiguredPackage[]; + resolveExtensionSources(sources: string[], options?: { + local?: boolean; + temporary?: boolean; + }): Promise; + addSourceToSettings(source: string, options?: { + local?: boolean; + }): boolean; + removeSourceFromSettings(source: string, options?: { + local?: boolean; + }): boolean; + setProgressCallback(callback: ProgressCallback | undefined): void; + getInstalledPath(source: string, scope: "user" | "project"): string | undefined; +} +interface PackageManagerOptions { + cwd: string; + agentDir: string; + settingsManager: SettingsManager; +} +type SourceScope = "user" | "project" | "temporary"; +export declare function getExtensionTempFolder(agentDir: string): string; +export declare class DefaultPackageManager implements PackageManager { + private cwd; + private agentDir; + private settingsManager; + private globalNpmRoot; + private globalNpmRootCommandKey; + private progressCallback; + constructor(options: PackageManagerOptions); + setProgressCallback(callback: ProgressCallback | undefined): void; + addSourceToSettings(source: string, options?: { + local?: boolean; + }): boolean; + removeSourceFromSettings(source: string, options?: { + local?: boolean; + }): boolean; + getInstalledPath(source: string, scope: "user" | "project"): string | undefined; + private emitProgress; + private withProgress; + resolve(onMissing?: (source: string) => Promise): Promise; + resolveExtensionSources(sources: string[], options?: { + local?: boolean; + temporary?: boolean; + }): Promise; + listConfiguredPackages(): ConfiguredPackage[]; + install(source: string, options?: { + local?: boolean; + }): Promise; + installAndPersist(source: string, options?: { + local?: boolean; + }): Promise; + remove(source: string, options?: { + local?: boolean; + }): Promise; + removeAndPersist(source: string, options?: { + local?: boolean; + }): Promise; + update(source?: string): Promise; + private updateConfiguredSources; + private shouldUpdateNpmSource; + private updateNpmBatch; + private installNpmBatch; + checkForAvailableUpdates(): Promise; + private resolvePackageSources; + private findAutoloadDeltaBase; + private resolveLocalExtensionSource; + private installParsedSource; + private getPackageSourceString; + private getSourceMatchKeyForInput; + private getSourceMatchKeyForSettings; + private buildNoMatchingPackageMessage; + private findSuggestedConfiguredSource; + private packageSourcesMatch; + private normalizePackageSourceForSettings; + private parseSource; + private installedNpmMatchesConfiguredVersion; + private npmHasAvailableUpdate; + private getInstalledNpmVersion; + private getLatestNpmVersion; + private gitHasAvailableUpdate; + private getRemoteGitHead; + private getLocalGitUpdateTarget; + private getGitUpstreamRef; + private runGitRemoteCommand; + private runWithConcurrency; + /** + * Get a unique identity for a package, ignoring version/ref. + * Used to detect when the same package is in both global and project settings. + * For git packages, uses normalized host/path to ensure SSH and HTTPS URLs + * for the same repository are treated as identical. + */ + private getPackageIdentity; + /** + * Dedupe packages: if same package identity appears in both global and project, + * keep only the project one (project wins). A project entry with autoload=false + * is a delta over the global entry, so both are kept (delta first). + */ + private dedupePackages; + private parseNpmSpec; + private assertProjectTrustedForScope; + private getNpmCommand; + private getPackageManagerName; + private runNpmCommand; + private getGitDependencyInstallArgs; + private runNpmCommandSync; + private getNpmInstallArgs; + private installNpm; + private uninstallNpm; + private installGit; + private updateGit; + private ensureGitRef; + private refreshTemporaryGitSource; + private removeGit; + private pruneEmptyGitParents; + private ensureNpmProject; + private ensureGitIgnore; + private getNpmInstallRoot; + private getGlobalNpmRoot; + private getPnpmGlobalPackagePath; + private getManagedNpmInstallPath; + private getLegacyGlobalNpmInstallPath; + private getNpmInstallPath; + private getGitInstallPath; + private getGitInstallRoot; + private getTemporaryDir; + private resolveManagedPath; + private getBaseDirForScope; + private resolvePath; + private resolvePathFromBase; + private collectPackageResources; + private collectDefaultResources; + private applyPackageFilter; + private applyPackageDeltaFilter; + /** + * Collect all files from a package for a resource type, applying manifest patterns. + * Returns { allFiles, enabledByManifest } where enabledByManifest is the set of files + * that pass the manifest's own patterns. + */ + private collectManifestFiles; + private readPiManifest; + private addManifestEntries; + private collectFilesFromManifestEntries; + private resolveLocalEntries; + private addAutoDiscoveredResources; + private collectFilesFromPaths; + private getTargetMap; + private addResource; + private createAccumulator; + private toResolvedPaths; + private spawnCommand; + private spawnCaptureCommand; + private runCommandCapture; + private runCommand; + private runCommandSync; +} +export {}; +//# sourceMappingURL=package-manager.d.ts.map \ No newline at end of file diff --git a/dist/core/package-manager.d.ts.map b/dist/core/package-manager.d.ts.map new file mode 100644 index 0000000..807ae09 --- /dev/null +++ b/dist/core/package-manager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"package-manager.d.ts","sourceRoot":"","sources":["../../src/core/package-manager.ts"],"names":[],"mappings":"AAmCA,OAAO,KAAK,E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mD/B,OAAO,CAAC,uBAAuB;IAsB/B,OAAO,CAAC,kBAAkB;IA0B1B,OAAO,CAAC,uBAAuB;IAkB/B;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAsB5B,OAAO,CAAC,cAAc;IAetB,OAAO,CAAC,kBAAkB;IAoB1B,OAAO,CAAC,+BAA+B;IAiBvC,OAAO,CAAC,mBAAmB;IAuB3B,OAAO,CAAC,0BAA0B;IAsKlC,OAAO,CAAC,qBAAqB;IAmB7B,OAAO,CAAC,YAAY;IAkBpB,OAAO,CAAC,WAAW;IAYnB,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,eAAe;IA4BvB,OAAO,CAAC,YAAY;IASpB,OAAO,CAAC,mBAAmB;IAc3B,OAAO,CAAC,iBAAiB;IA4CzB,OAAO,CAAC,UAAU;IAclB,OAAO,CAAC,cAAc;CActB","sourcesContent":["import type { ChildProcess, ChildProcessByStdio } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\n\nfunction getEnv(): NodeJS.ProcessEnv {\n\tif (process.platform !== \"linux\" || Object.keys(process.env).length > 0) {\n\t\treturn process.env;\n\t}\n\ttry {\n\t\tconst data = readFileSync(\"/proc/self/environ\", \"utf-8\");\n\t\tconst env: NodeJS.ProcessEnv = {};\n\t\tfor (const entry of data.split(\"\\0\")) {\n\t\t\tconst idx = entry.indexOf(\"=\");\n\t\t\tif (idx > 0) {\n\t\t\t\tenv[entry.slice(0, idx)] = entry.slice(idx + 1);\n\t\t\t}\n\t\t}\n\t\treturn env;\n\t} catch {\n\t\treturn process.env;\n\t}\n}\n\nimport { basename, dirname, join, relative, resolve, sep } from \"node:path\";\nimport type { Readable } from \"node:stream\";\nimport { globSync } from \"glob\";\nimport ignore from \"ignore\";\nimport { minimatch } from \"minimatch\";\nimport { maxSatisfying, rcompare, satisfies, valid, validRange } from \"semver\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { spawnProcess, spawnProcessSync } from \"../utils/child-process.ts\";\nimport { type GitSource, parseGitUrl } from \"../utils/git.ts\";\nimport { canonicalizePath, isLocalPath, markPathIgnoredByCloudSync, resolvePath } from \"../utils/paths.ts\";\nimport { isStdoutTakenOver } from \"./output-guard.ts\";\nimport type { PackageSource, SettingsManager } from \"./settings-manager.ts\";\n\nconst NETWORK_TIMEOUT_MS = 10000;\nconst UPDATE_CHECK_CONCURRENCY = 4;\nconst GIT_UPDATE_CONCURRENCY = 4;\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.PI_OFFLINE;\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\nfunction isExactNpmVersion(version: string | undefined): boolean {\n\treturn valid(version ?? \"\") !== null;\n}\n\nfunction getNpmVersionRange(version: string | undefined): string | undefined {\n\treturn version ? (validRange(version) ?? undefined) : undefined;\n}\n\nexport interface PathMetadata {\n\tsource: string;\n\tscope: SourceScope;\n\torigin: \"package\" | \"top-level\";\n\tbaseDir?: string;\n}\n\nexport interface ResolvedResource {\n\tpath: string;\n\tenabled: boolean;\n\tmetadata: PathMetadata;\n}\n\nexport interface ResolvedPaths {\n\textensions: ResolvedResource[];\n\tskills: ResolvedResource[];\n\tprompts: ResolvedResource[];\n\tthemes: ResolvedResource[];\n}\n\nexport type MissingSourceAction = \"install\" | \"skip\" | \"error\";\n\nexport interface ProgressEvent {\n\ttype: \"start\" | \"progress\" | \"complete\" | \"error\";\n\taction: \"install\" | \"remove\" | \"update\" | \"clone\" | \"pull\";\n\tsource: string;\n\tmessage?: string;\n}\n\nexport type ProgressCallback = (event: ProgressEvent) => void;\n\nexport interface PackageUpdate {\n\tsource: string;\n\tdisplayName: string;\n\ttype: \"npm\" | \"git\";\n\tscope: Exclude;\n}\n\nexport interface ConfiguredPackage {\n\tsource: string;\n\tscope: \"user\" | \"project\";\n\tfiltered: boolean;\n\tinstalledPath?: string;\n}\n\nexport interface PackageManager {\n\tresolve(onMissing?: (source: string) => Promise): Promise;\n\tinstall(source: string, options?: { local?: boolean }): Promise;\n\tinstallAndPersist(source: string, options?: { local?: boolean }): Promise;\n\tremove(source: string, options?: { local?: boolean }): Promise;\n\tremoveAndPersist(source: string, options?: { local?: boolean }): Promise;\n\tupdate(source?: string): Promise;\n\tlistConfiguredPackages(): ConfiguredPackage[];\n\tresolveExtensionSources(\n\t\tsources: string[],\n\t\toptions?: { local?: boolean; temporary?: boolean },\n\t): Promise;\n\taddSourceToSettings(source: string, options?: { local?: boolean }): boolean;\n\tremoveSourceFromSettings(source: string, options?: { local?: boolean }): boolean;\n\tsetProgressCallback(callback: ProgressCallback | undefined): void;\n\tgetInstalledPath(source: string, scope: \"user\" | \"project\"): string | undefined;\n}\n\ninterface PackageManagerOptions {\n\tcwd: string;\n\tagentDir: string;\n\tsettingsManager: SettingsManager;\n}\n\ntype SourceScope = \"user\" | \"project\" | \"temporary\";\n\ntype NpmSource = {\n\ttype: \"npm\";\n\tspec: string;\n\tname: string;\n\tversion?: string;\n\trange?: string;\n\tpinned: boolean;\n};\n\ntype LocalSource = {\n\ttype: \"local\";\n\tpath: string;\n};\n\ntype ParsedSource = NpmSource | GitSource | LocalSource;\n\ntype InstalledSourceScope = Exclude;\n\ninterface ConfiguredUpdateSource {\n\tsource: string;\n\tscope: InstalledSourceScope;\n}\n\ninterface NpmUpdateTarget extends ConfiguredUpdateSource {\n\tparsed: NpmSource;\n}\n\ninterface GitUpdateTarget extends ConfiguredUpdateSource {\n\tparsed: GitSource;\n}\n\ninterface PiManifest {\n\textensions?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n\tthemes?: string[];\n}\n\ninterface ResourceAccumulator {\n\textensions: Map;\n\tskills: Map;\n\tprompts: Map;\n\tthemes: Map;\n}\n\n/**\n * Compute a numeric precedence rank for a resource based on its metadata.\n * Lower rank = higher precedence. Used to sort resolved resources so that\n * name-collision resolution (\"first wins\") produces the correct outcome.\n *\n * Precedence (highest to lowest):\n * 0 project + settings entry (source: \"local\", scope: \"project\")\n * 1 project + auto-discovered (source: \"auto\", scope: \"project\")\n * 2 user + settings entry (source: \"local\", scope: \"user\")\n * 3 user + auto-discovered (source: \"auto\", scope: \"user\")\n * 4 package resource (origin: \"package\")\n */\nfunction resourcePrecedenceRank(m: PathMetadata): number {\n\tif (m.origin === \"package\") return 4;\n\tconst scopeBase = m.scope === \"project\" ? 0 : 2;\n\treturn scopeBase + (m.source === \"local\" ? 0 : 1);\n}\n\ninterface PackageFilter {\n\tautoload?: boolean;\n\textensions?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n\tthemes?: string[];\n}\n\ntype ResourceType = \"extensions\" | \"skills\" | \"prompts\" | \"themes\";\n\nconst RESOURCE_TYPES: ResourceType[] = [\"extensions\", \"skills\", \"prompts\", \"themes\"];\n\nconst FILE_PATTERNS: Record = {\n\textensions: /\\.(ts|js)$/,\n\tskills: /\\.md$/,\n\tprompts: /\\.md$/,\n\tthemes: /\\.json$/,\n};\n\nconst IGNORE_FILE_NAMES = [\".gitignore\", \".ignore\", \".fdignore\"];\n\ntype IgnoreMatcher = ReturnType;\n\nfunction toPosixPath(p: string): string {\n\treturn p.split(sep).join(\"/\");\n}\n\nfunction getHomeDir(): string {\n\treturn process.env.HOME || homedir();\n}\n\nexport function getExtensionTempFolder(agentDir: string): string {\n\tconst tempFolder = join(agentDir, \"tmp\", \"extensions\");\n\tmkdirSync(tempFolder, { recursive: true, mode: 0o700 });\n\tchmodSync(tempFolder, 0o700);\n\treturn tempFolder;\n}\n\nfunction prefixIgnorePattern(line: string, prefix: string): string | null {\n\tconst trimmed = line.trim();\n\tif (!trimmed) return null;\n\tif (trimmed.startsWith(\"#\") && !trimmed.startsWith(\"\\\\#\")) return null;\n\n\tlet pattern = line;\n\tlet negated = false;\n\n\tif (pattern.startsWith(\"!\")) {\n\t\tnegated = true;\n\t\tpattern = pattern.slice(1);\n\t} else if (pattern.startsWith(\"\\\\!\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tif (pattern.startsWith(\"/\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tconst prefixed = prefix ? `${prefix}${pattern}` : pattern;\n\treturn negated ? `!${prefixed}` : prefixed;\n}\n\nfunction addIgnoreRules(ig: IgnoreMatcher, dir: string, rootDir: string): void {\n\tconst relativeDir = relative(rootDir, dir);\n\tconst prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : \"\";\n\n\tfor (const filename of IGNORE_FILE_NAMES) {\n\t\tconst ignorePath = join(dir, filename);\n\t\tif (!existsSync(ignorePath)) continue;\n\t\ttry {\n\t\t\tconst content = readFileSync(ignorePath, \"utf-8\");\n\t\t\tconst patterns = content\n\t\t\t\t.split(/\\r?\\n/)\n\t\t\t\t.map((line) => prefixIgnorePattern(line, prefix))\n\t\t\t\t.filter((line): line is string => Boolean(line));\n\t\t\tif (patterns.length > 0) {\n\t\t\t\tig.add(patterns);\n\t\t\t}\n\t\t} catch {}\n\t}\n}\n\nfunction isPattern(s: string): boolean {\n\treturn s.startsWith(\"!\") || s.startsWith(\"+\") || s.startsWith(\"-\") || s.includes(\"*\") || s.includes(\"?\");\n}\n\nfunction isOverridePattern(s: string): boolean {\n\treturn s.startsWith(\"!\") || s.startsWith(\"+\") || s.startsWith(\"-\");\n}\n\nfunction hasGlobPattern(s: string): boolean {\n\treturn s.includes(\"*\") || s.includes(\"?\");\n}\n\nfunction splitPatterns(entries: string[]): { plain: string[]; patterns: string[] } {\n\tconst plain: string[] = [];\n\tconst patterns: string[] = [];\n\tfor (const entry of entries) {\n\t\tif (isPattern(entry)) {\n\t\t\tpatterns.push(entry);\n\t\t} else {\n\t\t\tplain.push(entry);\n\t\t}\n\t}\n\treturn { plain, patterns };\n}\n\nfunction collectFiles(\n\tdir: string,\n\tfilePattern: RegExp,\n\tskipNodeModules = true,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): string[] {\n\tconst files: string[] = [];\n\tif (!existsSync(dir)) return files;\n\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\taddIgnoreRules(ig, dir, root);\n\n\ttry {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (skipNodeModules && entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDir = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDir = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tconst ignorePath = isDir ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) continue;\n\n\t\t\tif (isDir) {\n\t\t\t\tfiles.push(...collectFiles(fullPath, filePattern, skipNodeModules, ig, root));\n\t\t\t} else if (isFile && filePattern.test(entry.name)) {\n\t\t\t\tfiles.push(fullPath);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn files;\n}\n\ntype SkillDiscoveryMode = \"pi\" | \"agents\";\n\nfunction collectSkillEntries(\n\tdir: string,\n\tmode: SkillDiscoveryMode,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\taddIgnoreRules(ig, dir, root);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name !== \"SKILL.md\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tif (isFile && !ig.ignores(relPath)) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t\treturn entries;\n\t\t\t}\n\t\t}\n\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDir = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDir = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tif (mode === \"pi\" && dir === root && isFile && entry.name.endsWith(\".md\") && !ig.ignores(relPath)) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!isDir) continue;\n\t\t\tif (ig.ignores(`${relPath}/`)) continue;\n\n\t\t\tentries.push(...collectSkillEntries(fullPath, mode, ig, root));\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\nfunction collectAutoSkillEntries(dir: string, mode: SkillDiscoveryMode): string[] {\n\treturn collectSkillEntries(dir, mode);\n}\n\nfunction findGitRepoRoot(startDir: string): string | null {\n\tlet dir = resolve(startDir);\n\twhile (true) {\n\t\tif (existsSync(join(dir, \".git\"))) {\n\t\t\treturn dir;\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) {\n\t\t\treturn null;\n\t\t}\n\t\tdir = parent;\n\t}\n}\n\nfunction collectAncestorAgentsSkillDirs(startDir: string): string[] {\n\tconst skillDirs: string[] = [];\n\tconst resolvedStartDir = resolve(startDir);\n\tconst gitRepoRoot = findGitRepoRoot(resolvedStartDir);\n\n\tlet dir = resolvedStartDir;\n\twhile (true) {\n\t\tskillDirs.push(join(dir, \".agents\", \"skills\"));\n\t\tif (gitRepoRoot && dir === gitRepoRoot) {\n\t\t\tbreak;\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) {\n\t\t\tbreak;\n\t\t}\n\t\tdir = parent;\n\t}\n\n\treturn skillDirs;\n}\n\nfunction collectAutoPromptEntries(dir: string): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\tconst ig = ignore();\n\taddIgnoreRules(ig, dir, dir);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(dir, fullPath));\n\t\t\tif (ig.ignores(relPath)) continue;\n\n\t\t\tif (isFile && entry.name.endsWith(\".md\")) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\nfunction collectAutoThemeEntries(dir: string): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\tconst ig = ignore();\n\taddIgnoreRules(ig, dir, dir);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(dir, fullPath));\n\t\t\tif (ig.ignores(relPath)) continue;\n\n\t\t\tif (isFile && entry.name.endsWith(\".json\")) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\nfunction readPiManifestFile(packageJsonPath: string): PiManifest | null {\n\ttry {\n\t\tconst content = readFileSync(packageJsonPath, \"utf-8\");\n\t\tconst pkg = JSON.parse(content) as { pi?: PiManifest };\n\t\treturn pkg.pi ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction resolveExtensionEntries(dir: string): string[] | null {\n\tconst packageJsonPath = join(dir, \"package.json\");\n\tif (existsSync(packageJsonPath)) {\n\t\tconst manifest = readPiManifestFile(packageJsonPath);\n\t\tif (manifest?.extensions?.length) {\n\t\t\tconst entries: string[] = [];\n\t\t\tfor (const extPath of manifest.extensions) {\n\t\t\t\tconst resolvedExtPath = resolve(dir, extPath);\n\t\t\t\tif (existsSync(resolvedExtPath)) {\n\t\t\t\t\tentries.push(resolvedExtPath);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (entries.length > 0) {\n\t\t\t\treturn entries;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst indexTs = join(dir, \"index.ts\");\n\tconst indexJs = join(dir, \"index.js\");\n\tif (existsSync(indexTs)) {\n\t\treturn [indexTs];\n\t}\n\tif (existsSync(indexJs)) {\n\t\treturn [indexJs];\n\t}\n\n\treturn null;\n}\n\nfunction collectAutoExtensionEntries(dir: string): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\t// First check if this directory itself has explicit extension entries (package.json or index)\n\tconst rootEntries = resolveExtensionEntries(dir);\n\tif (rootEntries) {\n\t\treturn rootEntries;\n\t}\n\n\t// Otherwise, discover extensions from directory contents\n\tconst ig = ignore();\n\taddIgnoreRules(ig, dir, dir);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDir = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDir = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(dir, fullPath));\n\t\t\tconst ignorePath = isDir ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) continue;\n\n\t\t\tif (isFile && (entry.name.endsWith(\".ts\") || entry.name.endsWith(\".js\"))) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t} else if (isDir) {\n\t\t\t\tconst resolvedEntries = resolveExtensionEntries(fullPath);\n\t\t\t\tif (resolvedEntries) {\n\t\t\t\t\tentries.push(...resolvedEntries);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\n/**\n * Collect resource files from a directory based on resource type.\n * Extensions use smart discovery (index.ts in subdirs), others use recursive collection.\n */\nfunction collectResourceFiles(dir: string, resourceType: ResourceType): string[] {\n\tif (resourceType === \"skills\") {\n\t\treturn collectSkillEntries(dir, \"pi\");\n\t}\n\tif (resourceType === \"extensions\") {\n\t\treturn collectAutoExtensionEntries(dir);\n\t}\n\treturn collectFiles(dir, FILE_PATTERNS[resourceType]);\n}\n\nfunction matchesAnyPattern(filePath: string, patterns: string[], baseDir: string): boolean {\n\tconst rel = toPosixPath(relative(baseDir, filePath));\n\tconst name = basename(filePath);\n\tconst filePathPosix = toPosixPath(filePath);\n\tconst isSkillFile = name === \"SKILL.md\";\n\tconst parentDir = isSkillFile ? dirname(filePath) : undefined;\n\tconst parentRel = isSkillFile ? toPosixPath(relative(baseDir, parentDir!)) : undefined;\n\tconst parentName = isSkillFile ? basename(parentDir!) : undefined;\n\tconst parentDirPosix = isSkillFile ? toPosixPath(parentDir!) : undefined;\n\n\treturn patterns.some((pattern) => {\n\t\tconst normalizedPattern = toPosixPath(pattern);\n\t\tif (\n\t\t\tminimatch(rel, normalizedPattern) ||\n\t\t\tminimatch(name, normalizedPattern) ||\n\t\t\tminimatch(filePathPosix, normalizedPattern)\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!isSkillFile) return false;\n\t\treturn (\n\t\t\tminimatch(parentRel!, normalizedPattern) ||\n\t\t\tminimatch(parentName!, normalizedPattern) ||\n\t\t\tminimatch(parentDirPosix!, normalizedPattern)\n\t\t);\n\t});\n}\n\nfunction normalizeExactPattern(pattern: string): string {\n\tconst normalized = pattern.startsWith(\"./\") || pattern.startsWith(\".\\\\\") ? pattern.slice(2) : pattern;\n\treturn toPosixPath(normalized);\n}\n\nfunction matchesAnyExactPattern(filePath: string, patterns: string[], baseDir: string): boolean {\n\tif (patterns.length === 0) return false;\n\tconst rel = toPosixPath(relative(baseDir, filePath));\n\tconst name = basename(filePath);\n\tconst filePathPosix = toPosixPath(filePath);\n\tconst isSkillFile = name === \"SKILL.md\";\n\tconst parentDir = isSkillFile ? dirname(filePath) : undefined;\n\tconst parentRel = isSkillFile ? toPosixPath(relative(baseDir, parentDir!)) : undefined;\n\tconst parentDirPosix = isSkillFile ? toPosixPath(parentDir!) : undefined;\n\n\treturn patterns.some((pattern) => {\n\t\tconst normalized = normalizeExactPattern(pattern);\n\t\tif (normalized === rel || normalized === filePathPosix) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!isSkillFile) return false;\n\t\treturn normalized === parentRel || normalized === parentDirPosix;\n\t});\n}\n\nfunction getOverridePatterns(entries: string[]): string[] {\n\treturn entries.filter((pattern) => pattern.startsWith(\"!\") || pattern.startsWith(\"+\") || pattern.startsWith(\"-\"));\n}\n\nfunction isEnabledByOverrides(filePath: string, patterns: string[], baseDir: string): boolean {\n\tconst overrides = getOverridePatterns(patterns);\n\tconst excludes = overrides.filter((pattern) => pattern.startsWith(\"!\")).map((pattern) => pattern.slice(1));\n\tconst forceIncludes = overrides.filter((pattern) => pattern.startsWith(\"+\")).map((pattern) => pattern.slice(1));\n\tconst forceExcludes = overrides.filter((pattern) => pattern.startsWith(\"-\")).map((pattern) => pattern.slice(1));\n\n\tlet enabled = true;\n\tif (excludes.length > 0 && matchesAnyPattern(filePath, excludes, baseDir)) {\n\t\tenabled = false;\n\t}\n\tif (forceIncludes.length > 0 && matchesAnyExactPattern(filePath, forceIncludes, baseDir)) {\n\t\tenabled = true;\n\t}\n\tif (forceExcludes.length > 0 && matchesAnyExactPattern(filePath, forceExcludes, baseDir)) {\n\t\tenabled = false;\n\t}\n\treturn enabled;\n}\n\n/**\n * Apply patterns to paths and return a Set of enabled paths.\n * Pattern types:\n * - Plain patterns: include matching paths\n * - `!pattern`: exclude matching paths\n * - `+path`: force-include exact path (overrides exclusions)\n * - `-path`: force-exclude exact path (overrides force-includes)\n */\nfunction applyPatterns(allPaths: string[], patterns: string[], baseDir: string): Set {\n\tconst includes: string[] = [];\n\tconst excludes: string[] = [];\n\tconst forceIncludes: string[] = [];\n\tconst forceExcludes: string[] = [];\n\n\tfor (const p of patterns) {\n\t\tif (p.startsWith(\"+\")) {\n\t\t\tforceIncludes.push(p.slice(1));\n\t\t} else if (p.startsWith(\"-\")) {\n\t\t\tforceExcludes.push(p.slice(1));\n\t\t} else if (p.startsWith(\"!\")) {\n\t\t\texcludes.push(p.slice(1));\n\t\t} else {\n\t\t\tincludes.push(p);\n\t\t}\n\t}\n\n\t// Step 1: Apply includes (or all if no includes)\n\tlet result: string[];\n\tif (includes.length === 0) {\n\t\tresult = [...allPaths];\n\t} else {\n\t\tresult = allPaths.filter((filePath) => matchesAnyPattern(filePath, includes, baseDir));\n\t}\n\n\t// Step 2: Apply excludes\n\tif (excludes.length > 0) {\n\t\tresult = result.filter((filePath) => !matchesAnyPattern(filePath, excludes, baseDir));\n\t}\n\n\t// Step 3: Force-include (add back from allPaths, overriding exclusions)\n\tif (forceIncludes.length > 0) {\n\t\tfor (const filePath of allPaths) {\n\t\t\tif (!result.includes(filePath) && matchesAnyExactPattern(filePath, forceIncludes, baseDir)) {\n\t\t\t\tresult.push(filePath);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Step 4: Force-exclude (remove even if included or force-included)\n\tif (forceExcludes.length > 0) {\n\t\tresult = result.filter((filePath) => !matchesAnyExactPattern(filePath, forceExcludes, baseDir));\n\t}\n\n\treturn new Set(result);\n}\n\nfunction applyAutoloadDisabledPatterns(allPaths: string[], patterns: string[], baseDir: string): Map {\n\tconst result = new Map();\n\tfor (const pattern of patterns) {\n\t\tconst target = pattern.slice(\n\t\t\tpattern.startsWith(\"+\") || pattern.startsWith(\"-\") || pattern.startsWith(\"!\") ? 1 : 0,\n\t\t);\n\t\tconst enabled = !pattern.startsWith(\"-\") && !pattern.startsWith(\"!\");\n\t\tconst exact = pattern.startsWith(\"+\") || pattern.startsWith(\"-\");\n\t\tfor (const filePath of allPaths) {\n\t\t\tif (\n\t\t\t\texact ? matchesAnyExactPattern(filePath, [target], baseDir) : matchesAnyPattern(filePath, [target], baseDir)\n\t\t\t) {\n\t\t\t\tresult.set(filePath, enabled);\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nexport class DefaultPackageManager implements PackageManager {\n\tprivate cwd: string;\n\tprivate agentDir: string;\n\tprivate settingsManager: SettingsManager;\n\tprivate globalNpmRoot: string | undefined;\n\tprivate globalNpmRootCommandKey: string | undefined;\n\tprivate progressCallback: ProgressCallback | undefined;\n\n\tconstructor(options: PackageManagerOptions) {\n\t\tthis.cwd = resolvePath(options.cwd);\n\t\tthis.agentDir = resolvePath(options.agentDir);\n\t\tthis.settingsManager = options.settingsManager;\n\t}\n\n\tsetProgressCallback(callback: ProgressCallback | undefined): void {\n\t\tthis.progressCallback = callback;\n\t}\n\n\taddSourceToSettings(source: string, options?: { local?: boolean }): boolean {\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tconst currentSettings =\n\t\t\tscope === \"project\" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings();\n\t\tconst currentPackages = currentSettings.packages ?? [];\n\t\tconst normalizedSource = this.normalizePackageSourceForSettings(source, scope);\n\t\tconst matchIndex = currentPackages.findIndex((existing) => this.packageSourcesMatch(existing, source, scope));\n\t\tif (matchIndex !== -1) {\n\t\t\tconst existing = currentPackages[matchIndex];\n\t\t\tif (this.getPackageSourceString(existing) === normalizedSource) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst nextPackages = [...currentPackages];\n\t\t\tnextPackages[matchIndex] =\n\t\t\t\ttypeof existing === \"string\" ? normalizedSource : { ...existing, source: normalizedSource };\n\t\t\tif (scope === \"project\") {\n\t\t\t\tthis.settingsManager.setProjectPackages(nextPackages);\n\t\t\t} else {\n\t\t\t\tthis.settingsManager.setPackages(nextPackages);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tconst nextPackages = [...currentPackages, normalizedSource];\n\t\tif (scope === \"project\") {\n\t\t\tthis.settingsManager.setProjectPackages(nextPackages);\n\t\t} else {\n\t\t\tthis.settingsManager.setPackages(nextPackages);\n\t\t}\n\t\treturn true;\n\t}\n\n\tremoveSourceFromSettings(source: string, options?: { local?: boolean }): boolean {\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tconst currentSettings =\n\t\t\tscope === \"project\" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings();\n\t\tconst currentPackages = currentSettings.packages ?? [];\n\t\tconst nextPackages = currentPackages.filter((existing) => !this.packageSourcesMatch(existing, source, scope));\n\t\tconst changed = nextPackages.length !== currentPackages.length;\n\t\tif (!changed) {\n\t\t\treturn false;\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\tthis.settingsManager.setProjectPackages(nextPackages);\n\t\t} else {\n\t\t\tthis.settingsManager.setPackages(nextPackages);\n\t\t}\n\t\treturn true;\n\t}\n\n\tgetInstalledPath(source: string, scope: \"user\" | \"project\"): string | undefined {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\tconst path = this.getNpmInstallPath(parsed, scope);\n\t\t\treturn existsSync(path) ? path : undefined;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\tconst path = this.getGitInstallPath(parsed, scope);\n\t\t\treturn existsSync(path) ? path : undefined;\n\t\t}\n\t\tif (parsed.type === \"local\") {\n\t\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\t\tconst path = this.resolvePathFromBase(parsed.path, baseDir);\n\t\t\treturn existsSync(path) ? path : undefined;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate emitProgress(event: ProgressEvent): void {\n\t\tthis.progressCallback?.(event);\n\t}\n\n\tprivate async withProgress(\n\t\taction: ProgressEvent[\"action\"],\n\t\tsource: string,\n\t\tmessage: string,\n\t\toperation: () => Promise,\n\t): Promise {\n\t\tthis.emitProgress({ type: \"start\", action, source, message });\n\t\ttry {\n\t\t\tawait operation();\n\t\t\tthis.emitProgress({ type: \"complete\", action, source });\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tthis.emitProgress({ type: \"error\", action, source, message: errorMessage });\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync resolve(onMissing?: (source: string) => Promise): Promise {\n\t\tconst accumulator = this.createAccumulator();\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\n\t\t// Collect all packages with scope (project first so cwd resources win collisions)\n\t\tconst allPackages: Array<{ pkg: PackageSource; scope: SourceScope }> = [];\n\t\tfor (const pkg of projectSettings.packages ?? []) {\n\t\t\tallPackages.push({ pkg, scope: \"project\" });\n\t\t}\n\t\tfor (const pkg of globalSettings.packages ?? []) {\n\t\t\tallPackages.push({ pkg, scope: \"user\" });\n\t\t}\n\n\t\t// Dedupe: project scope wins over global for same package identity\n\t\tconst packageSources = this.dedupePackages(allPackages);\n\t\tawait this.resolvePackageSources(packageSources, accumulator, onMissing);\n\n\t\tconst globalBaseDir = this.agentDir;\n\t\tconst projectBaseDir = join(this.cwd, CONFIG_DIR_NAME);\n\n\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\tconst target = this.getTargetMap(accumulator, resourceType);\n\t\t\tconst globalEntries = (globalSettings[resourceType] ?? []) as string[];\n\t\t\tconst projectEntries = (projectSettings[resourceType] ?? []) as string[];\n\t\t\tthis.resolveLocalEntries(\n\t\t\t\tprojectEntries,\n\t\t\t\tresourceType,\n\t\t\t\ttarget,\n\t\t\t\t{\n\t\t\t\t\tsource: \"local\",\n\t\t\t\t\tscope: \"project\",\n\t\t\t\t\torigin: \"top-level\",\n\t\t\t\t},\n\t\t\t\tprojectBaseDir,\n\t\t\t);\n\t\t\tthis.resolveLocalEntries(\n\t\t\t\tglobalEntries,\n\t\t\t\tresourceType,\n\t\t\t\ttarget,\n\t\t\t\t{\n\t\t\t\t\tsource: \"local\",\n\t\t\t\t\tscope: \"user\",\n\t\t\t\t\torigin: \"top-level\",\n\t\t\t\t},\n\t\t\t\tglobalBaseDir,\n\t\t\t);\n\t\t}\n\n\t\tthis.addAutoDiscoveredResources(accumulator, globalSettings, projectSettings, globalBaseDir, projectBaseDir);\n\n\t\treturn this.toResolvedPaths(accumulator);\n\t}\n\n\tasync resolveExtensionSources(\n\t\tsources: string[],\n\t\toptions?: { local?: boolean; temporary?: boolean },\n\t): Promise {\n\t\tconst accumulator = this.createAccumulator();\n\t\tconst scope: SourceScope = options?.temporary ? \"temporary\" : options?.local ? \"project\" : \"user\";\n\t\tconst packageSources = sources.map((source) => ({ pkg: source as PackageSource, scope }));\n\t\tawait this.resolvePackageSources(packageSources, accumulator);\n\t\treturn this.toResolvedPaths(accumulator);\n\t}\n\n\tlistConfiguredPackages(): ConfiguredPackage[] {\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\t\tconst configuredPackages: ConfiguredPackage[] = [];\n\n\t\tfor (const pkg of globalSettings.packages ?? []) {\n\t\t\tconst source = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tconfiguredPackages.push({\n\t\t\t\tsource,\n\t\t\t\tscope: \"user\",\n\t\t\t\tfiltered: typeof pkg === \"object\",\n\t\t\t\tinstalledPath: this.getInstalledPath(source, \"user\"),\n\t\t\t});\n\t\t}\n\n\t\tfor (const pkg of projectSettings.packages ?? []) {\n\t\t\tconst source = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tconfiguredPackages.push({\n\t\t\t\tsource,\n\t\t\t\tscope: \"project\",\n\t\t\t\tfiltered: typeof pkg === \"object\",\n\t\t\t\tinstalledPath: this.getInstalledPath(source, \"project\"),\n\t\t\t});\n\t\t}\n\n\t\treturn configuredPackages;\n\t}\n\n\tasync install(source: string, options?: { local?: boolean }): Promise {\n\t\tconst parsed = this.parseSource(source);\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tthis.assertProjectTrustedForScope(scope);\n\t\tawait this.withProgress(\"install\", source, `Installing ${source}...`, async () => {\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tawait this.installNpm(parsed, scope, false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tawait this.installGit(parsed, scope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"local\") {\n\t\t\t\tconst resolved = this.resolvePath(parsed.path);\n\t\t\t\tif (!existsSync(resolved)) {\n\t\t\t\t\tthrow new Error(`Path does not exist: ${resolved}`);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported install source: ${source}`);\n\t\t});\n\t}\n\n\tasync installAndPersist(source: string, options?: { local?: boolean }): Promise {\n\t\tawait this.install(source, options);\n\t\tthis.addSourceToSettings(source, options);\n\t}\n\n\tasync remove(source: string, options?: { local?: boolean }): Promise {\n\t\tconst parsed = this.parseSource(source);\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tthis.assertProjectTrustedForScope(scope);\n\t\tawait this.withProgress(\"remove\", source, `Removing ${source}...`, async () => {\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tawait this.uninstallNpm(parsed, scope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tawait this.removeGit(parsed, scope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"local\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported remove source: ${source}`);\n\t\t});\n\t}\n\n\tasync removeAndPersist(source: string, options?: { local?: boolean }): Promise {\n\t\tawait this.remove(source, options);\n\t\treturn this.removeSourceFromSettings(source, options);\n\t}\n\n\tasync update(source?: string): Promise {\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\t\tconst identity = source ? this.getPackageIdentity(source) : undefined;\n\t\tlet matched = false;\n\t\tconst updateSources: ConfiguredUpdateSource[] = [];\n\n\t\tfor (const pkg of globalSettings.packages ?? []) {\n\t\t\tconst sourceStr = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tif (identity && this.getPackageIdentity(sourceStr, \"user\") !== identity) continue;\n\t\t\tmatched = true;\n\t\t\tupdateSources.push({ source: sourceStr, scope: \"user\" });\n\t\t}\n\t\tfor (const pkg of projectSettings.packages ?? []) {\n\t\t\tconst sourceStr = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tif (identity && this.getPackageIdentity(sourceStr, \"project\") !== identity) continue;\n\t\t\tmatched = true;\n\t\t\tupdateSources.push({ source: sourceStr, scope: \"project\" });\n\t\t}\n\n\t\tif (source && !matched) {\n\t\t\tthrow new Error(\n\t\t\t\tthis.buildNoMatchingPackageMessage(source, [\n\t\t\t\t\t...(globalSettings.packages ?? []),\n\t\t\t\t\t...(projectSettings.packages ?? []),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tawait this.updateConfiguredSources(updateSources);\n\t}\n\n\tprivate async updateConfiguredSources(sources: ConfiguredUpdateSource[]): Promise {\n\t\tif (isOfflineModeEnabled() || sources.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst npmCandidates: NpmUpdateTarget[] = [];\n\t\tconst gitCandidates: GitUpdateTarget[] = [];\n\n\t\tfor (const entry of sources) {\n\t\t\tconst parsed = this.parseSource(entry.source);\n\t\t\t// Pinned npm versions are fixed. Pinned git refs are configured checkout targets,\n\t\t\t// so include them to reconcile an existing clone when the configured ref changes.\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tif (!parsed.pinned) {\n\t\t\t\t\tnpmCandidates.push({ ...entry, parsed });\n\t\t\t\t}\n\t\t\t} else if (parsed.type === \"git\") {\n\t\t\t\tgitCandidates.push({ ...entry, parsed });\n\t\t\t}\n\t\t}\n\n\t\tconst npmCheckTasks = npmCandidates.map((entry) => async () => ({\n\t\t\tentry,\n\t\t\tshouldUpdate: await this.shouldUpdateNpmSource(entry.parsed, entry.scope),\n\t\t}));\n\t\tconst npmCheckResults = await this.runWithConcurrency(npmCheckTasks, UPDATE_CHECK_CONCURRENCY);\n\t\tconst userNpmUpdates: NpmUpdateTarget[] = [];\n\t\tconst projectNpmUpdates: NpmUpdateTarget[] = [];\n\t\tfor (const result of npmCheckResults) {\n\t\t\tif (!result.shouldUpdate) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (result.entry.scope === \"user\") {\n\t\t\t\tuserNpmUpdates.push(result.entry);\n\t\t\t} else {\n\t\t\t\tprojectNpmUpdates.push(result.entry);\n\t\t\t}\n\t\t}\n\n\t\tconst tasks: Promise[] = [];\n\t\tif (userNpmUpdates.length > 0) {\n\t\t\ttasks.push(this.updateNpmBatch(userNpmUpdates, \"user\"));\n\t\t}\n\t\tif (projectNpmUpdates.length > 0) {\n\t\t\ttasks.push(this.updateNpmBatch(projectNpmUpdates, \"project\"));\n\t\t}\n\t\tif (gitCandidates.length > 0) {\n\t\t\tconst gitTasks = gitCandidates.map(\n\t\t\t\t(entry) => async () =>\n\t\t\t\t\tthis.withProgress(\"update\", entry.source, `Updating ${entry.source}...`, async () => {\n\t\t\t\t\t\tawait this.updateGit(entry.parsed, entry.scope);\n\t\t\t\t\t}),\n\t\t\t);\n\t\t\ttasks.push(this.runWithConcurrency(gitTasks, GIT_UPDATE_CONCURRENCY).then(() => {}));\n\t\t}\n\n\t\tawait Promise.all(tasks);\n\t}\n\n\tprivate async shouldUpdateNpmSource(source: NpmSource, scope: InstalledSourceScope): Promise {\n\t\tconst installedPath = this.getManagedNpmInstallPath(source, scope);\n\t\tconst installedVersion = existsSync(installedPath) ? this.getInstalledNpmVersion(installedPath) : undefined;\n\t\tif (!installedVersion) {\n\t\t\treturn true;\n\t\t}\n\n\t\ttry {\n\t\t\tconst targetVersion = await this.getLatestNpmVersion(source.version ? source.spec : source.name, source.range);\n\t\t\treturn targetVersion !== installedVersion;\n\t\t} catch {\n\t\t\t// Preserve existing update behavior when version lookup fails.\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tprivate async updateNpmBatch(sources: NpmUpdateTarget[], scope: InstalledSourceScope): Promise {\n\t\tif (sources.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst sourceLabel = sources.length === 1 ? sources[0].source : `${scope} npm packages`;\n\t\tconst message = sources.length === 1 ? `Updating ${sources[0].source}...` : `Updating ${scope} npm packages...`;\n\t\tconst specs = sources.map((entry) => (entry.parsed.version ? entry.parsed.spec : `${entry.parsed.name}@latest`));\n\n\t\tawait this.withProgress(\"update\", sourceLabel, message, async () => {\n\t\t\tawait this.installNpmBatch(specs, scope);\n\t\t});\n\t}\n\n\tprivate async installNpmBatch(specs: string[], scope: InstalledSourceScope): Promise {\n\t\tconst installRoot = this.getNpmInstallRoot(scope, false);\n\t\tthis.ensureNpmProject(installRoot);\n\t\tawait this.runNpmCommand(this.getNpmInstallArgs(specs, installRoot));\n\t}\n\n\tasync checkForAvailableUpdates(): Promise {\n\t\tif (isOfflineModeEnabled()) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\t\tconst allPackages: Array<{ pkg: PackageSource; scope: SourceScope }> = [];\n\t\tfor (const pkg of projectSettings.packages ?? []) {\n\t\t\tallPackages.push({ pkg, scope: \"project\" });\n\t\t}\n\t\tfor (const pkg of globalSettings.packages ?? []) {\n\t\t\tallPackages.push({ pkg, scope: \"user\" });\n\t\t}\n\n\t\tconst packageSources = this.dedupePackages(allPackages);\n\t\tconst checks = packageSources\n\t\t\t.filter(\n\t\t\t\t(entry): entry is { pkg: PackageSource; scope: Exclude } =>\n\t\t\t\t\tentry.scope !== \"temporary\",\n\t\t\t)\n\t\t\t.map((entry) => async (): Promise => {\n\t\t\t\tconst source = typeof entry.pkg === \"string\" ? entry.pkg : entry.pkg.source;\n\t\t\t\tconst parsed = this.parseSource(source);\n\t\t\t\tif (parsed.type === \"local\" || parsed.pinned) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\t\tconst installedPath = this.getNpmInstallPath(parsed, entry.scope);\n\t\t\t\t\tif (!existsSync(installedPath)) {\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\tconst hasUpdate = await this.npmHasAvailableUpdate(parsed, installedPath);\n\t\t\t\t\tif (!hasUpdate) {\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tdisplayName: parsed.name,\n\t\t\t\t\t\ttype: \"npm\",\n\t\t\t\t\t\tscope: entry.scope,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst installedPath = this.getGitInstallPath(parsed, entry.scope);\n\t\t\t\tif (!existsSync(installedPath)) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\tconst hasUpdate = await this.gitHasAvailableUpdate(installedPath);\n\t\t\t\tif (!hasUpdate) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tsource,\n\t\t\t\t\tdisplayName: `${parsed.host}/${parsed.path}`,\n\t\t\t\t\ttype: \"git\",\n\t\t\t\t\tscope: entry.scope,\n\t\t\t\t};\n\t\t\t});\n\n\t\tconst results = await this.runWithConcurrency(checks, UPDATE_CHECK_CONCURRENCY);\n\t\treturn results.filter((result): result is PackageUpdate => result !== undefined);\n\t}\n\n\tprivate async resolvePackageSources(\n\t\tsources: Array<{ pkg: PackageSource; scope: SourceScope }>,\n\t\taccumulator: ResourceAccumulator,\n\t\tonMissing?: (source: string) => Promise,\n\t): Promise {\n\t\tfor (const { pkg, scope } of sources) {\n\t\t\tconst sourceStr = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tconst filter = typeof pkg === \"object\" ? pkg : undefined;\n\t\t\tconst deltaBase = this.findAutoloadDeltaBase(pkg, scope, sources);\n\t\t\tconst resolvedSource = deltaBase?.source ?? sourceStr;\n\t\t\tconst resolvedScope = deltaBase?.scope ?? scope;\n\t\t\tconst parsed = this.parseSource(resolvedSource);\n\t\t\tconst metadata: PathMetadata = { source: sourceStr, scope, origin: \"package\" };\n\n\t\t\tif (parsed.type === \"local\") {\n\t\t\t\tconst baseDir = this.getBaseDirForScope(resolvedScope);\n\t\t\t\tthis.resolveLocalExtensionSource(parsed, accumulator, filter, metadata, baseDir);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst installMissing = async (): Promise => {\n\t\t\t\tif (isOfflineModeEnabled()) return false;\n\t\t\t\tif (!onMissing) {\n\t\t\t\t\tawait this.installParsedSource(parsed, resolvedScope);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tconst action = await onMissing(resolvedSource);\n\t\t\t\tif (action === \"skip\") return false;\n\t\t\t\tif (action === \"error\") throw new Error(`Missing source: ${resolvedSource}`);\n\t\t\t\tawait this.installParsedSource(parsed, resolvedScope);\n\t\t\t\treturn true;\n\t\t\t};\n\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tlet installedPath = this.getNpmInstallPath(parsed, resolvedScope);\n\t\t\t\tconst needsInstall =\n\t\t\t\t\t!existsSync(installedPath) || !(await this.installedNpmMatchesConfiguredVersion(parsed, installedPath));\n\t\t\t\tif (needsInstall) {\n\t\t\t\t\tconst installed = await installMissing();\n\t\t\t\t\tif (!installed) continue;\n\t\t\t\t\tinstalledPath = this.getNpmInstallPath(parsed, resolvedScope);\n\t\t\t\t}\n\t\t\t\tmetadata.baseDir = installedPath;\n\t\t\t\tthis.collectPackageResources(installedPath, accumulator, filter, metadata);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tconst installedPath = this.getGitInstallPath(parsed, resolvedScope);\n\t\t\t\tif (!existsSync(installedPath)) {\n\t\t\t\t\tconst installed = await installMissing();\n\t\t\t\t\tif (!installed) continue;\n\t\t\t\t} else if (resolvedScope === \"temporary\" && !parsed.pinned && !isOfflineModeEnabled()) {\n\t\t\t\t\tawait this.refreshTemporaryGitSource(parsed, resolvedSource);\n\t\t\t\t}\n\t\t\t\tmetadata.baseDir = installedPath;\n\t\t\t\tthis.collectPackageResources(installedPath, accumulator, filter, metadata);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate findAutoloadDeltaBase(\n\t\tpkg: PackageSource,\n\t\tscope: SourceScope,\n\t\tsources: Array<{ pkg: PackageSource; scope: SourceScope }>,\n\t): { source: string; scope: SourceScope } | undefined {\n\t\tif (scope !== \"project\" || typeof pkg !== \"object\" || pkg.autoload !== false) return undefined;\n\t\tconst identity = this.getPackageIdentity(pkg.source, scope);\n\t\tconst userEntry = sources.find(\n\t\t\t(entry) =>\n\t\t\t\tentry.scope === \"user\" &&\n\t\t\t\tthis.getPackageIdentity(this.getPackageSourceString(entry.pkg), \"user\") === identity,\n\t\t);\n\t\treturn userEntry ? { source: this.getPackageSourceString(userEntry.pkg), scope: \"user\" } : undefined;\n\t}\n\n\tprivate resolveLocalExtensionSource(\n\t\tsource: LocalSource,\n\t\taccumulator: ResourceAccumulator,\n\t\tfilter: PackageFilter | undefined,\n\t\tmetadata: PathMetadata,\n\t\tbaseDir: string,\n\t): void {\n\t\tconst resolved = this.resolvePathFromBase(source.path, baseDir);\n\t\tif (!existsSync(resolved)) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stats = statSync(resolved);\n\t\t\tif (stats.isFile()) {\n\t\t\t\tmetadata.baseDir = dirname(resolved);\n\t\t\t\tthis.addResource(accumulator.extensions, resolved, metadata, true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\tmetadata.baseDir = resolved;\n\t\t\t\tconst resources = this.collectPackageResources(resolved, accumulator, filter, metadata);\n\t\t\t\tif (!resources) {\n\t\t\t\t\tthis.addResource(accumulator.extensions, resolved, metadata, true);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprivate async installParsedSource(parsed: ParsedSource, scope: SourceScope): Promise {\n\t\tif (parsed.type === \"npm\") {\n\t\t\tawait this.installNpm(parsed, scope, scope === \"temporary\");\n\t\t\treturn;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\tawait this.installGit(parsed, scope);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprivate getPackageSourceString(pkg: PackageSource): string {\n\t\treturn typeof pkg === \"string\" ? pkg : pkg.source;\n\t}\n\n\tprivate getSourceMatchKeyForInput(source: string): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\treturn `npm:${parsed.name}`;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\treturn `git:${parsed.host}/${parsed.path}`;\n\t\t}\n\t\treturn `local:${this.resolvePath(parsed.path)}`;\n\t}\n\n\tprivate getSourceMatchKeyForSettings(source: string, scope: SourceScope): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\treturn `npm:${parsed.name}`;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\treturn `git:${parsed.host}/${parsed.path}`;\n\t\t}\n\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\treturn `local:${this.resolvePathFromBase(parsed.path, baseDir)}`;\n\t}\n\n\tprivate buildNoMatchingPackageMessage(source: string, configuredPackages: PackageSource[]): string {\n\t\tconst suggestion = this.findSuggestedConfiguredSource(source, configuredPackages);\n\t\tif (!suggestion) {\n\t\t\treturn `No matching package found for ${source}`;\n\t\t}\n\t\treturn `No matching package found for ${source}. Did you mean ${suggestion}?`;\n\t}\n\n\tprivate findSuggestedConfiguredSource(source: string, configuredPackages: PackageSource[]): string | undefined {\n\t\tconst trimmedSource = source.trim();\n\t\tconst suggestions = new Set();\n\n\t\tfor (const pkg of configuredPackages) {\n\t\t\tconst sourceStr = this.getPackageSourceString(pkg);\n\t\t\tconst parsed = this.parseSource(sourceStr);\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tif (trimmedSource === parsed.name || trimmedSource === parsed.spec) {\n\t\t\t\t\tsuggestions.add(sourceStr);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tconst shorthand = `${parsed.host}/${parsed.path}`;\n\t\t\t\tconst shorthandWithRef = parsed.ref ? `${shorthand}@${parsed.ref}` : undefined;\n\t\t\t\tif (trimmedSource === shorthand || (shorthandWithRef && trimmedSource === shorthandWithRef)) {\n\t\t\t\t\tsuggestions.add(sourceStr);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn suggestions.values().next().value;\n\t}\n\n\tprivate packageSourcesMatch(existing: PackageSource, inputSource: string, scope: SourceScope): boolean {\n\t\tconst left = this.getSourceMatchKeyForSettings(this.getPackageSourceString(existing), scope);\n\t\tconst right = this.getSourceMatchKeyForInput(inputSource);\n\t\treturn left === right;\n\t}\n\n\tprivate normalizePackageSourceForSettings(source: string, scope: SourceScope): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type !== \"local\") {\n\t\t\treturn source;\n\t\t}\n\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\tconst resolved = this.resolvePath(parsed.path);\n\t\tconst rel = relative(baseDir, resolved);\n\t\treturn rel || \".\";\n\t}\n\n\tprivate parseSource(source: string): ParsedSource {\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\tconst spec = source.slice(\"npm:\".length).trim();\n\t\t\tconst { name, version } = this.parseNpmSpec(spec);\n\t\t\treturn {\n\t\t\t\ttype: \"npm\",\n\t\t\t\tspec,\n\t\t\t\tname,\n\t\t\t\tversion,\n\t\t\t\trange: getNpmVersionRange(version),\n\t\t\t\tpinned: isExactNpmVersion(version),\n\t\t\t};\n\t\t}\n\n\t\tif (isLocalPath(source)) {\n\t\t\treturn { type: \"local\", path: source };\n\t\t}\n\n\t\t// Try parsing as git URL\n\t\tconst gitParsed = parseGitUrl(source);\n\t\tif (gitParsed) {\n\t\t\treturn gitParsed;\n\t\t}\n\n\t\treturn { type: \"local\", path: source };\n\t}\n\n\tprivate async installedNpmMatchesConfiguredVersion(source: NpmSource, installedPath: string): Promise {\n\t\tconst installedVersion = this.getInstalledNpmVersion(installedPath);\n\t\tif (!installedVersion) {\n\t\t\treturn false;\n\t\t}\n\t\treturn source.range ? satisfies(installedVersion, source.range) : true;\n\t}\n\n\tprivate async npmHasAvailableUpdate(source: NpmSource, installedPath: string): Promise {\n\t\tif (isOfflineModeEnabled()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst installedVersion = this.getInstalledNpmVersion(installedPath);\n\t\tif (!installedVersion) {\n\t\t\treturn false;\n\t\t}\n\n\t\ttry {\n\t\t\tconst targetVersion = await this.getLatestNpmVersion(source.version ? source.spec : source.name, source.range);\n\t\t\treturn targetVersion !== installedVersion;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate getInstalledNpmVersion(installedPath: string): string | undefined {\n\t\tconst packageJsonPath = join(installedPath, \"package.json\");\n\t\tif (!existsSync(packageJsonPath)) return undefined;\n\t\ttry {\n\t\t\tconst content = readFileSync(packageJsonPath, \"utf-8\");\n\t\t\tconst pkg = JSON.parse(content) as { version?: string };\n\t\t\treturn pkg.version;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate async getLatestNpmVersion(packageSpec: string, range?: string): Promise {\n\t\tconst npmCommand = this.getNpmCommand();\n\t\tconst stdout = await this.runCommandCapture(\n\t\t\tnpmCommand.command,\n\t\t\t[...npmCommand.args, \"view\", packageSpec, \"version\", \"--json\"],\n\t\t\t{ cwd: this.cwd, timeoutMs: NETWORK_TIMEOUT_MS },\n\t\t);\n\t\tconst raw = stdout.trim();\n\t\tif (!raw) throw new Error(\"Empty response from npm view\");\n\t\tconst parsed = JSON.parse(raw) as unknown;\n\t\tif (typeof parsed === \"string\") {\n\t\t\treturn parsed;\n\t\t}\n\t\tif (Array.isArray(parsed)) {\n\t\t\tconst versions = parsed.filter((value): value is string => typeof value === \"string\" && value.length > 0);\n\t\t\tconst latest = range ? maxSatisfying(versions, range) : [...versions].sort(rcompare)[0];\n\t\t\tif (latest) return latest;\n\t\t}\n\t\tthrow new Error(\"Unexpected response from npm view\");\n\t}\n\n\tprivate async gitHasAvailableUpdate(installedPath: string): Promise {\n\t\tif (isOfflineModeEnabled()) {\n\t\t\treturn false;\n\t\t}\n\n\t\ttry {\n\t\t\tconst localHead = await this.runCommandCapture(\"git\", [\"rev-parse\", \"HEAD\"], {\n\t\t\t\tcwd: installedPath,\n\t\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\t});\n\t\t\tconst remoteHead = await this.getRemoteGitHead(installedPath);\n\t\t\treturn localHead.trim() !== remoteHead.trim();\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate async getRemoteGitHead(installedPath: string): Promise {\n\t\tconst upstreamRef = await this.getGitUpstreamRef(installedPath);\n\t\tif (upstreamRef) {\n\t\t\tconst remoteHead = await this.runGitRemoteCommand(installedPath, [\"ls-remote\", \"origin\", upstreamRef]);\n\t\t\tconst match = remoteHead.match(/^([0-9a-f]{40})\\s+/m);\n\t\t\tif (match?.[1]) {\n\t\t\t\treturn match[1];\n\t\t\t}\n\t\t}\n\n\t\tconst remoteHead = await this.runGitRemoteCommand(installedPath, [\"ls-remote\", \"origin\", \"HEAD\"]);\n\t\tconst match = remoteHead.match(/^([0-9a-f]{40})\\s+HEAD$/m);\n\t\tif (!match?.[1]) {\n\t\t\tthrow new Error(\"Failed to determine remote HEAD\");\n\t\t}\n\t\treturn match[1];\n\t}\n\n\tprivate async getLocalGitUpdateTarget(\n\t\tinstalledPath: string,\n\t): Promise<{ ref: string; head: string; fetchArgs: string[] }> {\n\t\ttry {\n\t\t\tconst upstream = await this.runCommandCapture(\"git\", [\"rev-parse\", \"--abbrev-ref\", \"@{upstream}\"], {\n\t\t\t\tcwd: installedPath,\n\t\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\t});\n\t\t\tconst trimmedUpstream = upstream.trim();\n\t\t\tif (!trimmedUpstream.startsWith(\"origin/\")) {\n\t\t\t\tthrow new Error(`Unsupported upstream remote: ${trimmedUpstream}`);\n\t\t\t}\n\t\t\tconst branch = trimmedUpstream.slice(\"origin/\".length);\n\t\t\tif (!branch) {\n\t\t\t\tthrow new Error(\"Missing upstream branch name\");\n\t\t\t}\n\t\t\tconst head = await this.runCommandCapture(\"git\", [\"rev-parse\", \"@{upstream}\"], {\n\t\t\t\tcwd: installedPath,\n\t\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tref: \"@{upstream}\",\n\t\t\t\thead,\n\t\t\t\tfetchArgs: [\n\t\t\t\t\t\"fetch\",\n\t\t\t\t\t\"--prune\",\n\t\t\t\t\t\"--no-tags\",\n\t\t\t\t\t\"origin\",\n\t\t\t\t\t`+refs/heads/${branch}:refs/remotes/origin/${branch}`,\n\t\t\t\t],\n\t\t\t};\n\t\t} catch {\n\t\t\tawait this.runCommand(\"git\", [\"remote\", \"set-head\", \"origin\", \"-a\"], { cwd: installedPath }).catch(() => {});\n\t\t\tconst head = await this.runCommandCapture(\"git\", [\"rev-parse\", \"origin/HEAD\"], {\n\t\t\t\tcwd: installedPath,\n\t\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\t});\n\t\t\tconst originHeadRef = await this.runCommandCapture(\"git\", [\"symbolic-ref\", \"refs/remotes/origin/HEAD\"], {\n\t\t\t\tcwd: installedPath,\n\t\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\t}).catch(() => \"\");\n\t\t\tconst branch = originHeadRef.trim().replace(/^refs\\/remotes\\/origin\\//, \"\");\n\t\t\tif (branch) {\n\t\t\t\treturn {\n\t\t\t\t\tref: \"origin/HEAD\",\n\t\t\t\t\thead,\n\t\t\t\t\tfetchArgs: [\n\t\t\t\t\t\t\"fetch\",\n\t\t\t\t\t\t\"--prune\",\n\t\t\t\t\t\t\"--no-tags\",\n\t\t\t\t\t\t\"origin\",\n\t\t\t\t\t\t`+refs/heads/${branch}:refs/remotes/origin/${branch}`,\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tref: \"origin/HEAD\",\n\t\t\t\thead,\n\t\t\t\tfetchArgs: [\"fetch\", \"--prune\", \"--no-tags\", \"origin\", \"+HEAD:refs/remotes/origin/HEAD\"],\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate async getGitUpstreamRef(installedPath: string): Promise {\n\t\ttry {\n\t\t\tconst upstream = await this.runCommandCapture(\"git\", [\"rev-parse\", \"--abbrev-ref\", \"@{upstream}\"], {\n\t\t\t\tcwd: installedPath,\n\t\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\t});\n\t\t\tconst trimmed = upstream.trim();\n\t\t\tif (!trimmed.startsWith(\"origin/\")) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst branch = trimmed.slice(\"origin/\".length);\n\t\t\treturn branch ? `refs/heads/${branch}` : undefined;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate runGitRemoteCommand(installedPath: string, args: string[]): Promise {\n\t\treturn this.runCommandCapture(\"git\", args, {\n\t\t\tcwd: installedPath,\n\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\tenv: {\n\t\t\t\tGIT_TERMINAL_PROMPT: \"0\",\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate async runWithConcurrency(tasks: Array<() => Promise>, limit: number): Promise {\n\t\tif (tasks.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst results: T[] = new Array(tasks.length);\n\t\tlet nextIndex = 0;\n\t\tconst workerCount = Math.max(1, Math.min(limit, tasks.length));\n\n\t\tconst worker = async () => {\n\t\t\twhile (true) {\n\t\t\t\tconst index = nextIndex;\n\t\t\t\tnextIndex += 1;\n\t\t\t\tif (index >= tasks.length) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresults[index] = await tasks[index]();\n\t\t\t}\n\t\t};\n\n\t\tawait Promise.all(Array.from({ length: workerCount }, () => worker()));\n\t\treturn results;\n\t}\n\n\t/**\n\t * Get a unique identity for a package, ignoring version/ref.\n\t * Used to detect when the same package is in both global and project settings.\n\t * For git packages, uses normalized host/path to ensure SSH and HTTPS URLs\n\t * for the same repository are treated as identical.\n\t */\n\tprivate getPackageIdentity(source: string, scope?: SourceScope): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\treturn `npm:${parsed.name}`;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\t// Use host/path for identity to normalize SSH and HTTPS\n\t\t\treturn `git:${parsed.host}/${parsed.path}`;\n\t\t}\n\t\tif (scope) {\n\t\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\t\treturn `local:${this.resolvePathFromBase(parsed.path, baseDir)}`;\n\t\t}\n\t\treturn `local:${this.resolvePath(parsed.path)}`;\n\t}\n\n\t/**\n\t * Dedupe packages: if same package identity appears in both global and project,\n\t * keep only the project one (project wins). A project entry with autoload=false\n\t * is a delta over the global entry, so both are kept (delta first).\n\t */\n\tprivate dedupePackages(\n\t\tpackages: Array<{ pkg: PackageSource; scope: SourceScope }>,\n\t): Array<{ pkg: PackageSource; scope: SourceScope }> {\n\t\tconst result: Array<{ pkg: PackageSource; scope: SourceScope }> = [];\n\t\tconst seen = new Map();\n\t\tfor (const entry of packages) {\n\t\t\tconst identity = this.getPackageIdentity(this.getPackageSourceString(entry.pkg), entry.scope);\n\t\t\tconst index = seen.get(identity);\n\t\t\tif (index === undefined) {\n\t\t\t\tseen.set(identity, result.length);\n\t\t\t\tresult.push(entry);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst existing = result[index];\n\t\t\tif (existing?.scope === \"project\" && entry.scope === \"user\") {\n\t\t\t\tif (typeof existing.pkg === \"object\" && existing.pkg.autoload === false) result.push(entry);\n\t\t\t} else if (entry.scope === \"project\") {\n\t\t\t\tresult[index] = entry;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate parseNpmSpec(spec: string): { name: string; version?: string } {\n\t\tconst match = spec.match(/^(@?[^@]+(?:\\/[^@]+)?)(?:@(.+))?$/);\n\t\tif (!match) {\n\t\t\treturn { name: spec };\n\t\t}\n\t\tconst name = match[1] ?? spec;\n\t\tconst version = match[2];\n\t\treturn { name, version };\n\t}\n\n\tprivate assertProjectTrustedForScope(scope: SourceScope): void {\n\t\tif (scope === \"project\" && !this.settingsManager.isProjectTrusted()) {\n\t\t\tthrow new Error(\"Project is not trusted; refusing to access project package storage\");\n\t\t}\n\t}\n\n\tprivate getNpmCommand(): { command: string; args: string[] } {\n\t\tconst configuredCommand = this.settingsManager.getNpmCommand();\n\t\tif (!configuredCommand || configuredCommand.length === 0) {\n\t\t\treturn { command: \"npm\", args: [] };\n\t\t}\n\t\tconst [command, ...args] = configuredCommand;\n\t\tif (!command) {\n\t\t\tthrow new Error(\"Invalid npmCommand: first array entry must be a non-empty command\");\n\t\t}\n\t\treturn { command, args };\n\t}\n\n\tprivate getPackageManagerName(): string {\n\t\tconst npmCommand = this.getNpmCommand();\n\t\tconst commandParts = [npmCommand.command, ...npmCommand.args];\n\t\tconst separatorIndex = commandParts.lastIndexOf(\"--\");\n\t\tconst packageManagerCommand = separatorIndex >= 0 ? commandParts[separatorIndex + 1] : npmCommand.command;\n\t\treturn packageManagerCommand ? basename(packageManagerCommand).replace(/\\.(cmd|exe)$/i, \"\") : \"\";\n\t}\n\n\tprivate async runNpmCommand(args: string[], options?: { cwd?: string }): Promise {\n\t\tconst npmCommand = this.getNpmCommand();\n\t\tawait this.runCommand(npmCommand.command, [...npmCommand.args, ...args], options);\n\t}\n\n\tprivate getGitDependencyInstallArgs(): string[] {\n\t\tconst configuredCommand = this.settingsManager.getNpmCommand();\n\t\tif (configuredCommand && configuredCommand.length > 0) {\n\t\t\treturn [\"install\"];\n\t\t}\n\t\treturn [\"install\", \"--omit=dev\"];\n\t}\n\n\tprivate runNpmCommandSync(args: string[]): string {\n\t\tconst npmCommand = this.getNpmCommand();\n\t\treturn this.runCommandSync(npmCommand.command, [...npmCommand.args, ...args]);\n\t}\n\n\tprivate getNpmInstallArgs(specs: string[], installRoot: string): string[] {\n\t\tconst packageManagerName = this.getPackageManagerName();\n\t\t// Extension packages run inside pi and resolve pi APIs through loader aliases/virtual modules.\n\t\t// Disable peer dependency resolution for managed installs (npm's --legacy-peer-deps, and\n\t\t// equivalent bun/pnpm settings) so package managers do not install or solve host-provided\n\t\t// @earendil-works/pi-* peers. Stale auto-installed pi peers can otherwise block updates.\n\t\tif (packageManagerName === \"bun\") {\n\t\t\treturn [\"install\", ...specs, \"--cwd\", installRoot, \"--omit=peer\"];\n\t\t}\n\t\tif (packageManagerName === \"pnpm\") {\n\t\t\treturn [\n\t\t\t\t\"install\",\n\t\t\t\t...specs,\n\t\t\t\t\"--prefix\",\n\t\t\t\tinstallRoot,\n\t\t\t\t\"--config.auto-install-peers=false\",\n\t\t\t\t\"--config.strict-peer-dependencies=false\",\n\t\t\t\t\"--config.strict-dep-builds=false\",\n\t\t\t];\n\t\t}\n\t\treturn [\"install\", ...specs, \"--prefix\", installRoot, \"--legacy-peer-deps\"];\n\t}\n\n\tprivate async installNpm(source: NpmSource, scope: SourceScope, temporary: boolean): Promise {\n\t\tconst installRoot = this.getNpmInstallRoot(scope, temporary);\n\t\tthis.ensureNpmProject(installRoot);\n\t\tawait this.runNpmCommand(this.getNpmInstallArgs([source.spec], installRoot));\n\t}\n\n\tprivate async uninstallNpm(source: NpmSource, scope: SourceScope): Promise {\n\t\tconst installRoot = this.getNpmInstallRoot(scope, false);\n\t\tif (!existsSync(installRoot)) {\n\t\t\treturn;\n\t\t}\n\t\tconst packageManagerName = this.getPackageManagerName();\n\t\tif (packageManagerName === \"bun\") {\n\t\t\tawait this.runNpmCommand([\"uninstall\", source.name, \"--cwd\", installRoot]);\n\t\t\treturn;\n\t\t}\n\t\tconst args = [\"uninstall\", source.name, \"--prefix\", installRoot];\n\t\tif (packageManagerName !== \"pnpm\") {\n\t\t\targs.push(\"--legacy-peer-deps\");\n\t\t}\n\t\tawait this.runNpmCommand(args);\n\t}\n\n\tprivate async installGit(source: GitSource, scope: SourceScope): Promise {\n\t\tconst targetDir = this.getGitInstallPath(source, scope);\n\t\tif (existsSync(targetDir)) {\n\t\t\tif (source.ref) {\n\t\t\t\tawait this.ensureGitRef(targetDir, [\"fetch\", \"origin\", source.ref], \"FETCH_HEAD\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst target = await this.getLocalGitUpdateTarget(targetDir);\n\t\t\tawait this.ensureGitRef(targetDir, target.fetchArgs, target.ref);\n\t\t\treturn;\n\t\t}\n\t\tconst gitRoot = this.getGitInstallRoot(scope);\n\t\tif (gitRoot) {\n\t\t\tthis.ensureGitIgnore(gitRoot);\n\t\t}\n\t\tmkdirSync(dirname(targetDir), { recursive: true });\n\n\t\ttry {\n\t\t\tawait this.runCommand(\"git\", [\"clone\", source.repo, targetDir]);\n\t\t\tif (source.ref) {\n\t\t\t\tawait this.runCommand(\"git\", [\"checkout\", source.ref], { cwd: targetDir });\n\t\t\t}\n\t\t\tconst packageJsonPath = join(targetDir, \"package.json\");\n\t\t\tif (existsSync(packageJsonPath)) {\n\t\t\t\tawait this.runNpmCommand(this.getGitDependencyInstallArgs(), { cwd: targetDir });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\trmSync(targetDir, { recursive: true, force: true });\n\t\t\tthis.pruneEmptyGitParents(targetDir, gitRoot);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async updateGit(source: GitSource, scope: SourceScope): Promise {\n\t\tconst targetDir = this.getGitInstallPath(source, scope);\n\t\tif (!existsSync(targetDir)) {\n\t\t\tawait this.installGit(source, scope);\n\t\t\treturn;\n\t\t}\n\n\t\tif (source.ref) {\n\t\t\tawait this.ensureGitRef(targetDir, [\"fetch\", \"origin\", source.ref], \"FETCH_HEAD\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst target = await this.getLocalGitUpdateTarget(targetDir);\n\t\tawait this.ensureGitRef(targetDir, target.fetchArgs, target.ref);\n\t}\n\n\tprivate async ensureGitRef(targetDir: string, fetchArgs: string[], ref: string): Promise {\n\t\t// Fetch only the ref we will reset to, avoiding unrelated branch/tag noise.\n\t\tawait this.runCommand(\"git\", fetchArgs, { cwd: targetDir });\n\n\t\tconst localHead = await this.runCommandCapture(\"git\", [\"rev-parse\", \"HEAD\"], {\n\t\t\tcwd: targetDir,\n\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t});\n\t\tconst commitRef = `${ref}^{commit}`;\n\t\tconst targetHead = await this.runCommandCapture(\"git\", [\"rev-parse\", commitRef], {\n\t\t\tcwd: targetDir,\n\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t});\n\t\tif (localHead.trim() === targetHead.trim()) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runCommand(\"git\", [\"reset\", \"--hard\", commitRef], { cwd: targetDir });\n\n\t\t// Clean untracked files (extensions should be pristine)\n\t\tawait this.runCommand(\"git\", [\"clean\", \"-fdx\"], { cwd: targetDir });\n\n\t\tconst packageJsonPath = join(targetDir, \"package.json\");\n\t\tif (existsSync(packageJsonPath)) {\n\t\t\tawait this.runNpmCommand(this.getGitDependencyInstallArgs(), { cwd: targetDir });\n\t\t}\n\t}\n\n\tprivate async refreshTemporaryGitSource(source: GitSource, sourceStr: string): Promise {\n\t\tif (isOfflineModeEnabled()) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait this.withProgress(\"pull\", sourceStr, `Refreshing ${sourceStr}...`, async () => {\n\t\t\t\tawait this.updateGit(source, \"temporary\");\n\t\t\t});\n\t\t} catch {\n\t\t\t// Keep cached temporary checkout if refresh fails.\n\t\t}\n\t}\n\n\tprivate async removeGit(source: GitSource, scope: SourceScope): Promise {\n\t\tconst targetDir = this.getGitInstallPath(source, scope);\n\t\tif (!existsSync(targetDir)) return;\n\t\trmSync(targetDir, { recursive: true, force: true });\n\t\tthis.pruneEmptyGitParents(targetDir, this.getGitInstallRoot(scope));\n\t}\n\n\tprivate pruneEmptyGitParents(targetDir: string, installRoot: string | undefined): void {\n\t\tif (!installRoot) return;\n\t\tconst resolvedRoot = resolve(installRoot);\n\t\tlet current = dirname(targetDir);\n\t\twhile (current.startsWith(resolvedRoot) && current !== resolvedRoot) {\n\t\t\tif (!existsSync(current)) {\n\t\t\t\tcurrent = dirname(current);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst entries = readdirSync(current);\n\t\t\tif (entries.length > 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\trmSync(current, { recursive: true, force: true });\n\t\t\t} catch {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcurrent = dirname(current);\n\t\t}\n\t}\n\n\tprivate ensureNpmProject(installRoot: string): void {\n\t\tif (!existsSync(installRoot)) {\n\t\t\tmkdirSync(installRoot, { recursive: true });\n\t\t}\n\t\tmarkPathIgnoredByCloudSync(installRoot);\n\t\tthis.ensureGitIgnore(installRoot);\n\t\tconst packageJsonPath = join(installRoot, \"package.json\");\n\t\tif (!existsSync(packageJsonPath)) {\n\t\t\tconst pkgJson = { name: \"pi-extensions\", private: true };\n\t\t\twriteFileSync(packageJsonPath, JSON.stringify(pkgJson, null, 2), \"utf-8\");\n\t\t}\n\t}\n\n\tprivate ensureGitIgnore(dir: string): void {\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t}\n\t\tconst ignorePath = join(dir, \".gitignore\");\n\t\tif (!existsSync(ignorePath)) {\n\t\t\twriteFileSync(ignorePath, \"*\\n!.gitignore\\n\", \"utf-8\");\n\t\t}\n\t}\n\n\tprivate getNpmInstallRoot(scope: SourceScope, temporary: boolean): string {\n\t\tif (temporary) {\n\t\t\treturn this.getTemporaryDir(\"npm\");\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\tthis.assertProjectTrustedForScope(scope);\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"npm\");\n\t\t}\n\t\treturn join(this.agentDir, \"npm\");\n\t}\n\n\tprivate getGlobalNpmRoot(): string {\n\t\tconst npmCommand = this.getNpmCommand();\n\t\tconst commandKey = [npmCommand.command, ...npmCommand.args].join(\"\\0\");\n\t\tif (this.globalNpmRoot && this.globalNpmRootCommandKey === commandKey) {\n\t\t\treturn this.globalNpmRoot;\n\t\t}\n\t\tif (this.getPackageManagerName() === \"bun\") {\n\t\t\tconst binDir = this.runNpmCommandSync([\"pm\", \"bin\", \"-g\"]).trim();\n\t\t\tthis.globalNpmRoot = join(dirname(binDir), \"install\", \"global\", \"node_modules\");\n\t\t} else {\n\t\t\tthis.globalNpmRoot = this.runNpmCommandSync([\"root\", \"-g\"]).trim();\n\t\t}\n\t\tthis.globalNpmRootCommandKey = commandKey;\n\t\treturn this.globalNpmRoot;\n\t}\n\n\tprivate getPnpmGlobalPackagePath(packageName: string): string | undefined {\n\t\tif (this.getPackageManagerName() !== \"pnpm\") {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst output = this.runNpmCommandSync([\"list\", \"-g\", \"--depth\", \"0\", \"--json\"]);\n\t\tconst entries = JSON.parse(output) as Array<{ dependencies?: Record }>;\n\t\tfor (const entry of entries) {\n\t\t\tconst path = entry.dependencies?.[packageName]?.path;\n\t\t\tif (path) return path;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate getManagedNpmInstallPath(source: NpmSource, scope: SourceScope): string {\n\t\tif (scope === \"temporary\") {\n\t\t\treturn join(this.getTemporaryDir(\"npm\"), \"node_modules\", source.name);\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\tthis.assertProjectTrustedForScope(scope);\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"npm\", \"node_modules\", source.name);\n\t\t}\n\t\treturn join(this.agentDir, \"npm\", \"node_modules\", source.name);\n\t}\n\n\tprivate getLegacyGlobalNpmInstallPath(source: NpmSource): string | undefined {\n\t\ttry {\n\t\t\treturn this.getPnpmGlobalPackagePath(source.name) ?? join(this.getGlobalNpmRoot(), source.name);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate getNpmInstallPath(source: NpmSource, scope: SourceScope): string {\n\t\tconst managedPath = this.getManagedNpmInstallPath(source, scope);\n\t\tif (scope !== \"user\" || existsSync(managedPath)) {\n\t\t\treturn managedPath;\n\t\t}\n\t\tconst legacyPath = this.getLegacyGlobalNpmInstallPath(source);\n\t\treturn legacyPath && existsSync(legacyPath) ? legacyPath : managedPath;\n\t}\n\n\tprivate getGitInstallPath(source: GitSource, scope: SourceScope): string {\n\t\tif (scope === \"temporary\") {\n\t\t\treturn this.getTemporaryDir(`git-${source.host}`, source.path);\n\t\t}\n\t\tconst installRoot = this.getGitInstallRoot(scope);\n\t\tif (!installRoot) {\n\t\t\tthrow new Error(\"Missing git install root\");\n\t\t}\n\t\treturn this.resolveManagedPath(installRoot, source.host, source.path);\n\t}\n\n\tprivate getGitInstallRoot(scope: SourceScope): string | undefined {\n\t\tif (scope === \"temporary\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\tthis.assertProjectTrustedForScope(scope);\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"git\");\n\t\t}\n\t\treturn join(this.agentDir, \"git\");\n\t}\n\n\tprivate getTemporaryDir(prefix: string, suffix?: string): string {\n\t\tconst root = this.resolveManagedPath(getExtensionTempFolder(this.agentDir), prefix);\n\t\tconst hash = createHash(\"sha256\")\n\t\t\t.update(`${prefix}-${suffix ?? \"\"}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 8);\n\t\treturn this.resolveManagedPath(root, hash, suffix ?? \"\");\n\t}\n\n\tprivate resolveManagedPath(root: string, ...parts: string[]): string {\n\t\tconst resolvedRoot = resolve(root);\n\t\tconst resolvedPath = resolve(resolvedRoot, ...parts);\n\t\tif (resolvedPath !== resolvedRoot && !resolvedPath.startsWith(`${resolvedRoot}${sep}`)) {\n\t\t\tthrow new Error(`Refusing to use path outside package install root: ${resolvedPath}`);\n\t\t}\n\t\treturn resolvedPath;\n\t}\n\n\tprivate getBaseDirForScope(scope: SourceScope): string {\n\t\tif (scope === \"project\") {\n\t\t\tthis.assertProjectTrustedForScope(scope);\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME);\n\t\t}\n\t\tif (scope === \"user\") {\n\t\t\treturn this.agentDir;\n\t\t}\n\t\treturn this.cwd;\n\t}\n\n\tprivate resolvePath(input: string): string {\n\t\treturn resolvePath(input, this.cwd, { homeDir: getHomeDir(), trim: true });\n\t}\n\n\tprivate resolvePathFromBase(input: string, baseDir: string): string {\n\t\treturn resolvePath(input, baseDir, { homeDir: getHomeDir(), trim: true });\n\t}\n\n\tprivate collectPackageResources(\n\t\tpackageRoot: string,\n\t\taccumulator: ResourceAccumulator,\n\t\tfilter: PackageFilter | undefined,\n\t\tmetadata: PathMetadata,\n\t): boolean {\n\t\tif (filter) {\n\t\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\t\tconst patterns = filter[resourceType];\n\t\t\t\tconst target = this.getTargetMap(accumulator, resourceType);\n\t\t\t\tif (filter.autoload === false) {\n\t\t\t\t\tthis.applyPackageDeltaFilter(packageRoot, patterns ?? [], resourceType, target, metadata);\n\t\t\t\t} else if (patterns !== undefined) {\n\t\t\t\t\tthis.applyPackageFilter(packageRoot, patterns, resourceType, target, metadata);\n\t\t\t\t} else {\n\t\t\t\t\tthis.collectDefaultResources(packageRoot, resourceType, target, metadata);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tconst manifest = this.readPiManifest(packageRoot);\n\t\tif (manifest) {\n\t\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\t\tconst entries = manifest[resourceType as keyof PiManifest];\n\t\t\t\tthis.addManifestEntries(\n\t\t\t\t\tentries,\n\t\t\t\t\tpackageRoot,\n\t\t\t\t\tresourceType,\n\t\t\t\t\tthis.getTargetMap(accumulator, resourceType),\n\t\t\t\t\tmetadata,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tlet hasAnyDir = false;\n\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\tconst dir = join(packageRoot, resourceType);\n\t\t\tif (existsSync(dir)) {\n\t\t\t\t// Collect all files from the directory (all enabled by default)\n\t\t\t\tconst files = collectResourceFiles(dir, resourceType);\n\t\t\t\tfor (const f of files) {\n\t\t\t\t\tthis.addResource(this.getTargetMap(accumulator, resourceType), f, metadata, true);\n\t\t\t\t}\n\t\t\t\thasAnyDir = true;\n\t\t\t}\n\t\t}\n\t\treturn hasAnyDir;\n\t}\n\n\tprivate collectDefaultResources(\n\t\tpackageRoot: string,\n\t\tresourceType: ResourceType,\n\t\ttarget: Map,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tconst manifest = this.readPiManifest(packageRoot);\n\t\tconst entries = manifest?.[resourceType as keyof PiManifest];\n\t\tif (entries) {\n\t\t\tthis.addManifestEntries(entries, packageRoot, resourceType, target, metadata);\n\t\t\treturn;\n\t\t}\n\t\tconst dir = join(packageRoot, resourceType);\n\t\tif (existsSync(dir)) {\n\t\t\t// Collect all files from the directory (all enabled by default)\n\t\t\tconst files = collectResourceFiles(dir, resourceType);\n\t\t\tfor (const f of files) {\n\t\t\t\tthis.addResource(target, f, metadata, true);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate applyPackageFilter(\n\t\tpackageRoot: string,\n\t\tuserPatterns: string[],\n\t\tresourceType: ResourceType,\n\t\ttarget: Map,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tconst { allFiles } = this.collectManifestFiles(packageRoot, resourceType);\n\n\t\tif (userPatterns.length === 0) {\n\t\t\t// Empty array explicitly disables all resources of this type\n\t\t\tfor (const f of allFiles) {\n\t\t\t\tthis.addResource(target, f, metadata, false);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Apply user patterns\n\t\tconst enabledByUser = applyPatterns(allFiles, userPatterns, packageRoot);\n\n\t\tfor (const f of allFiles) {\n\t\t\tconst enabled = enabledByUser.has(f);\n\t\t\tthis.addResource(target, f, metadata, enabled);\n\t\t}\n\t}\n\n\tprivate applyPackageDeltaFilter(\n\t\tpackageRoot: string,\n\t\tuserPatterns: string[],\n\t\tresourceType: ResourceType,\n\t\ttarget: Map,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tif (userPatterns.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst { allFiles } = this.collectManifestFiles(packageRoot, resourceType);\n\t\tconst enabledByUser = applyAutoloadDisabledPatterns(allFiles, userPatterns, packageRoot);\n\t\tfor (const [filePath, enabled] of enabledByUser) {\n\t\t\tthis.addResource(target, filePath, metadata, enabled);\n\t\t}\n\t}\n\n\t/**\n\t * Collect all files from a package for a resource type, applying manifest patterns.\n\t * Returns { allFiles, enabledByManifest } where enabledByManifest is the set of files\n\t * that pass the manifest's own patterns.\n\t */\n\tprivate collectManifestFiles(\n\t\tpackageRoot: string,\n\t\tresourceType: ResourceType,\n\t): { allFiles: string[]; enabledByManifest: Set } {\n\t\tconst manifest = this.readPiManifest(packageRoot);\n\t\tconst entries = manifest?.[resourceType as keyof PiManifest];\n\t\tif (entries && entries.length > 0) {\n\t\t\tconst allFiles = this.collectFilesFromManifestEntries(entries, packageRoot, resourceType);\n\t\t\tconst manifestPatterns = entries.filter(isOverridePattern);\n\t\t\tconst enabledByManifest =\n\t\t\t\tmanifestPatterns.length > 0 ? applyPatterns(allFiles, manifestPatterns, packageRoot) : new Set(allFiles);\n\t\t\treturn { allFiles: Array.from(enabledByManifest), enabledByManifest };\n\t\t}\n\n\t\tconst conventionDir = join(packageRoot, resourceType);\n\t\tif (!existsSync(conventionDir)) {\n\t\t\treturn { allFiles: [], enabledByManifest: new Set() };\n\t\t}\n\t\tconst allFiles = collectResourceFiles(conventionDir, resourceType);\n\t\treturn { allFiles, enabledByManifest: new Set(allFiles) };\n\t}\n\n\tprivate readPiManifest(packageRoot: string): PiManifest | null {\n\t\tconst packageJsonPath = join(packageRoot, \"package.json\");\n\t\tif (!existsSync(packageJsonPath)) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\tconst content = readFileSync(packageJsonPath, \"utf-8\");\n\t\t\tconst pkg = JSON.parse(content) as { pi?: PiManifest };\n\t\t\treturn pkg.pi ?? null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate addManifestEntries(\n\t\tentries: string[] | undefined,\n\t\troot: string,\n\t\tresourceType: ResourceType,\n\t\ttarget: Map,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tif (!entries) return;\n\n\t\tconst allFiles = this.collectFilesFromManifestEntries(entries, root, resourceType);\n\t\tconst patterns = entries.filter(isOverridePattern);\n\t\tconst enabledPaths = applyPatterns(allFiles, patterns, root);\n\n\t\tfor (const f of allFiles) {\n\t\t\tif (enabledPaths.has(f)) {\n\t\t\t\tthis.addResource(target, f, metadata, true);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate collectFilesFromManifestEntries(entries: string[], root: string, resourceType: ResourceType): string[] {\n\t\tconst sourceEntries = entries.filter((entry) => !isOverridePattern(entry));\n\t\tconst resolved = sourceEntries.flatMap((entry) => {\n\t\t\tif (!hasGlobPattern(entry)) {\n\t\t\t\treturn [resolve(root, entry)];\n\t\t\t}\n\n\t\t\treturn globSync(entry, {\n\t\t\t\tcwd: root,\n\t\t\t\tabsolute: true,\n\t\t\t\tdot: false,\n\t\t\t\tnodir: false,\n\t\t\t}).map((match) => resolve(match));\n\t\t});\n\t\treturn this.collectFilesFromPaths(resolved, resourceType);\n\t}\n\n\tprivate resolveLocalEntries(\n\t\tentries: string[],\n\t\tresourceType: ResourceType,\n\t\ttarget: Map,\n\t\tmetadata: PathMetadata,\n\t\tbaseDir: string,\n\t): void {\n\t\tif (entries.length === 0) return;\n\n\t\t// Collect all files from plain entries (non-pattern entries)\n\t\tconst { plain, patterns } = splitPatterns(entries);\n\t\tconst resolvedPlain = plain.map((p) => this.resolvePathFromBase(p, baseDir));\n\t\tconst allFiles = this.collectFilesFromPaths(resolvedPlain, resourceType);\n\n\t\t// Determine which files are enabled based on patterns\n\t\tconst enabledPaths = applyPatterns(allFiles, patterns, baseDir);\n\n\t\t// Add all files with their enabled state\n\t\tfor (const f of allFiles) {\n\t\t\tthis.addResource(target, f, metadata, enabledPaths.has(f));\n\t\t}\n\t}\n\n\tprivate addAutoDiscoveredResources(\n\t\taccumulator: ResourceAccumulator,\n\t\tglobalSettings: ReturnType,\n\t\tprojectSettings: ReturnType,\n\t\tglobalBaseDir: string,\n\t\tprojectBaseDir: string,\n\t): void {\n\t\tconst userMetadata: PathMetadata = {\n\t\t\tsource: \"auto\",\n\t\t\tscope: \"user\",\n\t\t\torigin: \"top-level\",\n\t\t\tbaseDir: globalBaseDir,\n\t\t};\n\t\tconst projectMetadata: PathMetadata = {\n\t\t\tsource: \"auto\",\n\t\t\tscope: \"project\",\n\t\t\torigin: \"top-level\",\n\t\t\tbaseDir: projectBaseDir,\n\t\t};\n\n\t\tconst userOverrides = {\n\t\t\textensions: (globalSettings.extensions ?? []) as string[],\n\t\t\tskills: (globalSettings.skills ?? []) as string[],\n\t\t\tprompts: (globalSettings.prompts ?? []) as string[],\n\t\t\tthemes: (globalSettings.themes ?? []) as string[],\n\t\t};\n\t\tconst projectOverrides = {\n\t\t\textensions: (projectSettings.extensions ?? []) as string[],\n\t\t\tskills: (projectSettings.skills ?? []) as string[],\n\t\t\tprompts: (projectSettings.prompts ?? []) as string[],\n\t\t\tthemes: (projectSettings.themes ?? []) as string[],\n\t\t};\n\n\t\tconst userDirs = {\n\t\t\textensions: join(globalBaseDir, \"extensions\"),\n\t\t\tskills: join(globalBaseDir, \"skills\"),\n\t\t\tprompts: join(globalBaseDir, \"prompts\"),\n\t\t\tthemes: join(globalBaseDir, \"themes\"),\n\t\t};\n\t\tconst projectDirs = {\n\t\t\textensions: join(projectBaseDir, \"extensions\"),\n\t\t\tskills: join(projectBaseDir, \"skills\"),\n\t\t\tprompts: join(projectBaseDir, \"prompts\"),\n\t\t\tthemes: join(projectBaseDir, \"themes\"),\n\t\t};\n\t\tconst userAgentsSkillsDir = join(getHomeDir(), \".agents\", \"skills\");\n\t\tconst projectTrusted = this.settingsManager.isProjectTrusted();\n\t\tconst projectAgentsSkillDirs = projectTrusted\n\t\t\t? collectAncestorAgentsSkillDirs(this.cwd).filter((dir) => resolve(dir) !== resolve(userAgentsSkillsDir))\n\t\t\t: [];\n\n\t\tconst addResources = (\n\t\t\tresourceType: ResourceType,\n\t\t\tpaths: string[],\n\t\t\tmetadata: PathMetadata,\n\t\t\toverrides: string[],\n\t\t\tbaseDir: string,\n\t\t) => {\n\t\t\tconst target = this.getTargetMap(accumulator, resourceType);\n\t\t\tfor (const path of paths) {\n\t\t\t\tconst enabled = isEnabledByOverrides(path, overrides, baseDir);\n\t\t\t\tthis.addResource(target, path, metadata, enabled);\n\t\t\t}\n\t\t};\n\n\t\tif (projectTrusted) {\n\t\t\t// Project extensions from .pi/\n\t\t\taddResources(\n\t\t\t\t\"extensions\",\n\t\t\t\tcollectAutoExtensionEntries(projectDirs.extensions),\n\t\t\t\tprojectMetadata,\n\t\t\t\tprojectOverrides.extensions,\n\t\t\t\tprojectBaseDir,\n\t\t\t);\n\n\t\t\t// Project skills from .pi/\n\t\t\taddResources(\n\t\t\t\t\"skills\",\n\t\t\t\tcollectAutoSkillEntries(projectDirs.skills, \"pi\"),\n\t\t\t\tprojectMetadata,\n\t\t\t\tprojectOverrides.skills,\n\t\t\t\tprojectBaseDir,\n\t\t\t);\n\t\t}\n\n\t\t// Project skills from .agents/ (each with its own baseDir)\n\t\tfor (const agentsSkillsDir of projectAgentsSkillDirs) {\n\t\t\tconst agentsBaseDir = dirname(agentsSkillsDir); // the .agents directory\n\t\t\tconst agentsMetadata: PathMetadata = {\n\t\t\t\t...projectMetadata,\n\t\t\t\tbaseDir: agentsBaseDir,\n\t\t\t};\n\t\t\taddResources(\n\t\t\t\t\"skills\",\n\t\t\t\tcollectAutoSkillEntries(agentsSkillsDir, \"agents\"),\n\t\t\t\tagentsMetadata,\n\t\t\t\tprojectOverrides.skills,\n\t\t\t\tagentsBaseDir,\n\t\t\t);\n\t\t}\n\n\t\tif (projectTrusted) {\n\t\t\taddResources(\n\t\t\t\t\"prompts\",\n\t\t\t\tcollectAutoPromptEntries(projectDirs.prompts),\n\t\t\t\tprojectMetadata,\n\t\t\t\tprojectOverrides.prompts,\n\t\t\t\tprojectBaseDir,\n\t\t\t);\n\t\t\taddResources(\n\t\t\t\t\"themes\",\n\t\t\t\tcollectAutoThemeEntries(projectDirs.themes),\n\t\t\t\tprojectMetadata,\n\t\t\t\tprojectOverrides.themes,\n\t\t\t\tprojectBaseDir,\n\t\t\t);\n\t\t}\n\n\t\t// User extensions from ~/.pi/agent/\n\t\taddResources(\n\t\t\t\"extensions\",\n\t\t\tcollectAutoExtensionEntries(userDirs.extensions),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.extensions,\n\t\t\tglobalBaseDir,\n\t\t);\n\n\t\t// User skills from ~/.pi/agent/\n\t\taddResources(\n\t\t\t\"skills\",\n\t\t\tcollectAutoSkillEntries(userDirs.skills, \"pi\"),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.skills,\n\t\t\tglobalBaseDir,\n\t\t);\n\n\t\t// User skills from ~/.agents/ (with its own baseDir)\n\t\tconst userAgentsBaseDir = dirname(userAgentsSkillsDir);\n\t\tconst userAgentsMetadata: PathMetadata = {\n\t\t\t...userMetadata,\n\t\t\tbaseDir: userAgentsBaseDir,\n\t\t};\n\t\taddResources(\n\t\t\t\"skills\",\n\t\t\tcollectAutoSkillEntries(userAgentsSkillsDir, \"agents\"),\n\t\t\tuserAgentsMetadata,\n\t\t\tuserOverrides.skills,\n\t\t\tuserAgentsBaseDir,\n\t\t);\n\n\t\taddResources(\n\t\t\t\"prompts\",\n\t\t\tcollectAutoPromptEntries(userDirs.prompts),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.prompts,\n\t\t\tglobalBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"themes\",\n\t\t\tcollectAutoThemeEntries(userDirs.themes),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.themes,\n\t\t\tglobalBaseDir,\n\t\t);\n\t}\n\n\tprivate collectFilesFromPaths(paths: string[], resourceType: ResourceType): string[] {\n\t\tconst files: string[] = [];\n\t\tfor (const p of paths) {\n\t\t\tif (!existsSync(p)) continue;\n\n\t\t\ttry {\n\t\t\t\tconst stats = statSync(p);\n\t\t\t\tif (stats.isFile()) {\n\t\t\t\t\tfiles.push(p);\n\t\t\t\t} else if (stats.isDirectory()) {\n\t\t\t\t\tfiles.push(...collectResourceFiles(p, resourceType));\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Ignore errors\n\t\t\t}\n\t\t}\n\t\treturn files;\n\t}\n\n\tprivate getTargetMap(\n\t\taccumulator: ResourceAccumulator,\n\t\tresourceType: ResourceType,\n\t): Map {\n\t\tswitch (resourceType) {\n\t\t\tcase \"extensions\":\n\t\t\t\treturn accumulator.extensions;\n\t\t\tcase \"skills\":\n\t\t\t\treturn accumulator.skills;\n\t\t\tcase \"prompts\":\n\t\t\t\treturn accumulator.prompts;\n\t\t\tcase \"themes\":\n\t\t\t\treturn accumulator.themes;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unknown resource type: ${resourceType}`);\n\t\t}\n\t}\n\n\tprivate addResource(\n\t\tmap: Map,\n\t\tpath: string,\n\t\tmetadata: PathMetadata,\n\t\tenabled: boolean,\n\t): void {\n\t\tif (!path) return;\n\t\tif (!map.has(path)) {\n\t\t\tmap.set(path, { metadata, enabled });\n\t\t}\n\t}\n\n\tprivate createAccumulator(): ResourceAccumulator {\n\t\treturn {\n\t\t\textensions: new Map(),\n\t\t\tskills: new Map(),\n\t\t\tprompts: new Map(),\n\t\t\tthemes: new Map(),\n\t\t};\n\t}\n\n\tprivate toResolvedPaths(accumulator: ResourceAccumulator): ResolvedPaths {\n\t\tconst mapToResolved = (\n\t\t\tentries: Map,\n\t\t): ResolvedResource[] => {\n\t\t\tconst resolved = Array.from(entries.entries()).map(([path, { metadata, enabled }]) => ({\n\t\t\t\tpath,\n\t\t\t\tenabled,\n\t\t\t\tmetadata,\n\t\t\t}));\n\t\t\tresolved.sort((a, b) => resourcePrecedenceRank(a.metadata) - resourcePrecedenceRank(b.metadata));\n\n\t\t\tconst seen = new Set();\n\t\t\treturn resolved.filter((entry) => {\n\t\t\t\tconst canonicalPath = canonicalizePath(entry.path);\n\t\t\t\tif (seen.has(canonicalPath)) return false;\n\t\t\t\tseen.add(canonicalPath);\n\t\t\t\treturn true;\n\t\t\t});\n\t\t};\n\n\t\treturn {\n\t\t\textensions: mapToResolved(accumulator.extensions),\n\t\t\tskills: mapToResolved(accumulator.skills),\n\t\t\tprompts: mapToResolved(accumulator.prompts),\n\t\t\tthemes: mapToResolved(accumulator.themes),\n\t\t};\n\t}\n\n\tprivate spawnCommand(command: string, args: string[], options?: { cwd?: string }): ChildProcess {\n\t\tconst env = getEnv();\n\t\treturn spawnProcess(command, args, {\n\t\t\tcwd: options?.cwd,\n\t\t\tstdio: isStdoutTakenOver() ? [\"ignore\", 2, 2] : \"inherit\",\n\t\t\tenv,\n\t\t});\n\t}\n\n\tprivate spawnCaptureCommand(\n\t\tcommand: string,\n\t\targs: string[],\n\t\toptions?: { cwd?: string; env?: Record },\n\t): ChildProcessByStdio {\n\t\tconst baseEnv = getEnv();\n\t\tconst env = options?.env ? { ...baseEnv, ...options.env } : baseEnv;\n\t\treturn spawnProcess(command, args, {\n\t\t\tcwd: options?.cwd,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tenv,\n\t\t});\n\t}\n\n\tprivate runCommandCapture(\n\t\tcommand: string,\n\t\targs: string[],\n\t\toptions?: { cwd?: string; timeoutMs?: number; env?: Record },\n\t): Promise {\n\t\treturn new Promise((resolvePromise, reject) => {\n\t\t\tconst child = this.spawnCaptureCommand(command, args, options);\n\t\t\tlet stdout = \"\";\n\t\t\tlet stderr = \"\";\n\t\t\tlet timedOut = false;\n\t\t\tconst timeout =\n\t\t\t\ttypeof options?.timeoutMs === \"number\"\n\t\t\t\t\t? setTimeout(() => {\n\t\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t}, options.timeoutMs)\n\t\t\t\t\t: undefined;\n\n\t\t\tchild.stdout?.on(\"data\", (data) => {\n\t\t\t\tstdout += data.toString();\n\t\t\t});\n\t\t\tchild.stderr?.on(\"data\", (data) => {\n\t\t\t\tstderr += data.toString();\n\t\t\t});\n\t\t\tchild.once(\"error\", (error) => {\n\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t\treject(error);\n\t\t\t});\n\t\t\tchild.once(\"close\", (code, signal) => {\n\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t\tif (timedOut) {\n\t\t\t\t\treject(new Error(`${command} ${args.join(\" \")} timed out after ${options?.timeoutMs}ms`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (code === 0) {\n\t\t\t\t\tresolvePromise(stdout.trim());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst exitStatus = code === null ? `signal ${signal ?? \"unknown\"}` : `code ${code}`;\n\t\t\t\treject(new Error(`${command} ${args.join(\" \")} failed with ${exitStatus}: ${stderr || stdout}`));\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate runCommand(command: string, args: string[], options?: { cwd?: string }): Promise {\n\t\treturn new Promise((resolvePromise, reject) => {\n\t\t\tconst child = this.spawnCommand(command, args, options);\n\t\t\tchild.on(\"error\", reject);\n\t\t\tchild.on(\"exit\", (code) => {\n\t\t\t\tif (code === 0) {\n\t\t\t\t\tresolvePromise();\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(`${command} ${args.join(\" \")} failed with code ${code}`));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate runCommandSync(command: string, args: string[]): string {\n\t\tconst env = getEnv();\n\t\tconst result = spawnProcessSync(command, args, {\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tencoding: \"utf-8\",\n\t\t\tenv,\n\t\t});\n\t\tif (result.error || result.status !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to run ${command} ${args.join(\" \")}: ${result.error?.message || result.stderr || result.stdout}`,\n\t\t\t);\n\t\t}\n\t\treturn (result.stdout || result.stderr || \"\").trim();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/package-manager.js b/dist/core/package-manager.js new file mode 100644 index 0000000..54b3a1f --- /dev/null +++ b/dist/core/package-manager.js @@ -0,0 +1,2142 @@ +import { createHash } from "node:crypto"; +import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +function getEnv() { + if (process.platform !== "linux" || Object.keys(process.env).length > 0) { + return process.env; + } + try { + const data = readFileSync("/proc/self/environ", "utf-8"); + const env = {}; + for (const entry of data.split("\0")) { + const idx = entry.indexOf("="); + if (idx > 0) { + env[entry.slice(0, idx)] = entry.slice(idx + 1); + } + } + return env; + } + catch { + return process.env; + } +} +import { basename, dirname, join, relative, resolve, sep } from "node:path"; +import { globSync } from "glob"; +import ignore from "ignore"; +import { minimatch } from "minimatch"; +import { maxSatisfying, rcompare, satisfies, valid, validRange } from "semver"; +import { CONFIG_DIR_NAME } from "../config.js"; +import { spawnProcess, spawnProcessSync } from "../utils/child-process.js"; +import { parseGitUrl } from "../utils/git.js"; +import { canonicalizePath, isLocalPath, markPathIgnoredByCloudSync, resolvePath } from "../utils/paths.js"; +import { isStdoutTakenOver } from "./output-guard.js"; +const NETWORK_TIMEOUT_MS = 10000; +const UPDATE_CHECK_CONCURRENCY = 4; +const GIT_UPDATE_CONCURRENCY = 4; +function isOfflineModeEnabled() { + const value = process.env.PI_OFFLINE; + if (!value) + return false; + return value === "1" || value.toLowerCase() === "true" || value.toLowerCase() === "yes"; +} +function isExactNpmVersion(version) { + return valid(version ?? "") !== null; +} +function getNpmVersionRange(version) { + return version ? (validRange(version) ?? undefined) : undefined; +} +/** + * Compute a numeric precedence rank for a resource based on its metadata. + * Lower rank = higher precedence. Used to sort resolved resources so that + * name-collision resolution ("first wins") produces the correct outcome. + * + * Precedence (highest to lowest): + * 0 project + settings entry (source: "local", scope: "project") + * 1 project + auto-discovered (source: "auto", scope: "project") + * 2 user + settings entry (source: "local", scope: "user") + * 3 user + auto-discovered (source: "auto", scope: "user") + * 4 package resource (origin: "package") + */ +function resourcePrecedenceRank(m) { + if (m.origin === "package") + return 4; + const scopeBase = m.scope === "project" ? 0 : 2; + return scopeBase + (m.source === "local" ? 0 : 1); +} +const RESOURCE_TYPES = ["extensions", "skills", "prompts", "themes"]; +const FILE_PATTERNS = { + extensions: /\.(ts|js)$/, + skills: /\.md$/, + prompts: /\.md$/, + themes: /\.json$/, +}; +const IGNORE_FILE_NAMES = [".gitignore", ".ignore", ".fdignore"]; +function toPosixPath(p) { + return p.split(sep).join("/"); +} +function getHomeDir() { + return process.env.HOME || homedir(); +} +export function getExtensionTempFolder(agentDir) { + const tempFolder = join(agentDir, "tmp", "extensions"); + mkdirSync(tempFolder, { recursive: true, mode: 0o700 }); + chmodSync(tempFolder, 0o700); + return tempFolder; +} +function prefixIgnorePattern(line, prefix) { + const trimmed = line.trim(); + if (!trimmed) + return null; + if (trimmed.startsWith("#") && !trimmed.startsWith("\\#")) + return null; + let pattern = line; + let negated = false; + if (pattern.startsWith("!")) { + negated = true; + pattern = pattern.slice(1); + } + else if (pattern.startsWith("\\!")) { + pattern = pattern.slice(1); + } + if (pattern.startsWith("/")) { + pattern = pattern.slice(1); + } + const prefixed = prefix ? `${prefix}${pattern}` : pattern; + return negated ? `!${prefixed}` : prefixed; +} +function addIgnoreRules(ig, dir, rootDir) { + const relativeDir = relative(rootDir, dir); + const prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : ""; + for (const filename of IGNORE_FILE_NAMES) { + const ignorePath = join(dir, filename); + if (!existsSync(ignorePath)) + continue; + try { + const content = readFileSync(ignorePath, "utf-8"); + const patterns = content + .split(/\r?\n/) + .map((line) => prefixIgnorePattern(line, prefix)) + .filter((line) => Boolean(line)); + if (patterns.length > 0) { + ig.add(patterns); + } + } + catch { } + } +} +function isPattern(s) { + return s.startsWith("!") || s.startsWith("+") || s.startsWith("-") || s.includes("*") || s.includes("?"); +} +function isOverridePattern(s) { + return s.startsWith("!") || s.startsWith("+") || s.startsWith("-"); +} +function hasGlobPattern(s) { + return s.includes("*") || s.includes("?"); +} +function splitPatterns(entries) { + const plain = []; + const patterns = []; + for (const entry of entries) { + if (isPattern(entry)) { + patterns.push(entry); + } + else { + plain.push(entry); + } + } + return { plain, patterns }; +} +function collectFiles(dir, filePattern, skipNodeModules = true, ignoreMatcher, rootDir) { + const files = []; + if (!existsSync(dir)) + return files; + const root = rootDir ?? dir; + const ig = ignoreMatcher ?? ignore(); + addIgnoreRules(ig, dir, root); + try { + const entries = readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + if (entry.name.startsWith(".")) + continue; + if (skipNodeModules && entry.name === "node_modules") + continue; + const fullPath = join(dir, entry.name); + let isDir = entry.isDirectory(); + let isFile = entry.isFile(); + if (entry.isSymbolicLink()) { + try { + const stats = statSync(fullPath); + isDir = stats.isDirectory(); + isFile = stats.isFile(); + } + catch { + continue; + } + } + const relPath = toPosixPath(relative(root, fullPath)); + const ignorePath = isDir ? `${relPath}/` : relPath; + if (ig.ignores(ignorePath)) + continue; + if (isDir) { + files.push(...collectFiles(fullPath, filePattern, skipNodeModules, ig, root)); + } + else if (isFile && filePattern.test(entry.name)) { + files.push(fullPath); + } + } + } + catch { + // Ignore errors + } + return files; +} +function collectSkillEntries(dir, mode, ignoreMatcher, rootDir) { + const entries = []; + if (!existsSync(dir)) + return entries; + const root = rootDir ?? dir; + const ig = ignoreMatcher ?? ignore(); + addIgnoreRules(ig, dir, root); + try { + const dirEntries = readdirSync(dir, { withFileTypes: true }); + for (const entry of dirEntries) { + if (entry.name !== "SKILL.md") { + continue; + } + const fullPath = join(dir, entry.name); + let isFile = entry.isFile(); + if (entry.isSymbolicLink()) { + try { + isFile = statSync(fullPath).isFile(); + } + catch { + continue; + } + } + const relPath = toPosixPath(relative(root, fullPath)); + if (isFile && !ig.ignores(relPath)) { + entries.push(fullPath); + return entries; + } + } + for (const entry of dirEntries) { + if (entry.name.startsWith(".")) + continue; + if (entry.name === "node_modules") + continue; + const fullPath = join(dir, entry.name); + let isDir = entry.isDirectory(); + let isFile = entry.isFile(); + if (entry.isSymbolicLink()) { + try { + const stats = statSync(fullPath); + isDir = stats.isDirectory(); + isFile = stats.isFile(); + } + catch { + continue; + } + } + const relPath = toPosixPath(relative(root, fullPath)); + if (mode === "pi" && dir === root && isFile && entry.name.endsWith(".md") && !ig.ignores(relPath)) { + entries.push(fullPath); + continue; + } + if (!isDir) + continue; + if (ig.ignores(`${relPath}/`)) + continue; + entries.push(...collectSkillEntries(fullPath, mode, ig, root)); + } + } + catch { + // Ignore errors + } + return entries; +} +function collectAutoSkillEntries(dir, mode) { + return collectSkillEntries(dir, mode); +} +function findGitRepoRoot(startDir) { + let dir = resolve(startDir); + while (true) { + if (existsSync(join(dir, ".git"))) { + return dir; + } + const parent = dirname(dir); + if (parent === dir) { + return null; + } + dir = parent; + } +} +function collectAncestorAgentsSkillDirs(startDir) { + const skillDirs = []; + const resolvedStartDir = resolve(startDir); + const gitRepoRoot = findGitRepoRoot(resolvedStartDir); + let dir = resolvedStartDir; + while (true) { + skillDirs.push(join(dir, ".agents", "skills")); + if (gitRepoRoot && dir === gitRepoRoot) { + break; + } + const parent = dirname(dir); + if (parent === dir) { + break; + } + dir = parent; + } + return skillDirs; +} +function collectAutoPromptEntries(dir) { + const entries = []; + if (!existsSync(dir)) + return entries; + const ig = ignore(); + addIgnoreRules(ig, dir, dir); + try { + const dirEntries = readdirSync(dir, { withFileTypes: true }); + for (const entry of dirEntries) { + if (entry.name.startsWith(".")) + continue; + if (entry.name === "node_modules") + continue; + const fullPath = join(dir, entry.name); + let isFile = entry.isFile(); + if (entry.isSymbolicLink()) { + try { + isFile = statSync(fullPath).isFile(); + } + catch { + continue; + } + } + const relPath = toPosixPath(relative(dir, fullPath)); + if (ig.ignores(relPath)) + continue; + if (isFile && entry.name.endsWith(".md")) { + entries.push(fullPath); + } + } + } + catch { + // Ignore errors + } + return entries; +} +function collectAutoThemeEntries(dir) { + const entries = []; + if (!existsSync(dir)) + return entries; + const ig = ignore(); + addIgnoreRules(ig, dir, dir); + try { + const dirEntries = readdirSync(dir, { withFileTypes: true }); + for (const entry of dirEntries) { + if (entry.name.startsWith(".")) + continue; + if (entry.name === "node_modules") + continue; + const fullPath = join(dir, entry.name); + let isFile = entry.isFile(); + if (entry.isSymbolicLink()) { + try { + isFile = statSync(fullPath).isFile(); + } + catch { + continue; + } + } + const relPath = toPosixPath(relative(dir, fullPath)); + if (ig.ignores(relPath)) + continue; + if (isFile && entry.name.endsWith(".json")) { + entries.push(fullPath); + } + } + } + catch { + // Ignore errors + } + return entries; +} +function readPiManifestFile(packageJsonPath) { + try { + const content = readFileSync(packageJsonPath, "utf-8"); + const pkg = JSON.parse(content); + return pkg.pi ?? null; + } + catch { + return null; + } +} +function resolveExtensionEntries(dir) { + const packageJsonPath = join(dir, "package.json"); + if (existsSync(packageJsonPath)) { + const manifest = readPiManifestFile(packageJsonPath); + if (manifest?.extensions?.length) { + const entries = []; + for (const extPath of manifest.extensions) { + const resolvedExtPath = resolve(dir, extPath); + if (existsSync(resolvedExtPath)) { + entries.push(resolvedExtPath); + } + } + if (entries.length > 0) { + return entries; + } + } + } + const indexTs = join(dir, "index.ts"); + const indexJs = join(dir, "index.js"); + if (existsSync(indexTs)) { + return [indexTs]; + } + if (existsSync(indexJs)) { + return [indexJs]; + } + return null; +} +function collectAutoExtensionEntries(dir) { + const entries = []; + if (!existsSync(dir)) + return entries; + // First check if this directory itself has explicit extension entries (package.json or index) + const rootEntries = resolveExtensionEntries(dir); + if (rootEntries) { + return rootEntries; + } + // Otherwise, discover extensions from directory contents + const ig = ignore(); + addIgnoreRules(ig, dir, dir); + try { + const dirEntries = readdirSync(dir, { withFileTypes: true }); + for (const entry of dirEntries) { + if (entry.name.startsWith(".")) + continue; + if (entry.name === "node_modules") + continue; + const fullPath = join(dir, entry.name); + let isDir = entry.isDirectory(); + let isFile = entry.isFile(); + if (entry.isSymbolicLink()) { + try { + const stats = statSync(fullPath); + isDir = stats.isDirectory(); + isFile = stats.isFile(); + } + catch { + continue; + } + } + const relPath = toPosixPath(relative(dir, fullPath)); + const ignorePath = isDir ? `${relPath}/` : relPath; + if (ig.ignores(ignorePath)) + continue; + if (isFile && (entry.name.endsWith(".ts") || entry.name.endsWith(".js"))) { + entries.push(fullPath); + } + else if (isDir) { + const resolvedEntries = resolveExtensionEntries(fullPath); + if (resolvedEntries) { + entries.push(...resolvedEntries); + } + } + } + } + catch { + // Ignore errors + } + return entries; +} +/** + * Collect resource files from a directory based on resource type. + * Extensions use smart discovery (index.ts in subdirs), others use recursive collection. + */ +function collectResourceFiles(dir, resourceType) { + if (resourceType === "skills") { + return collectSkillEntries(dir, "pi"); + } + if (resourceType === "extensions") { + return collectAutoExtensionEntries(dir); + } + return collectFiles(dir, FILE_PATTERNS[resourceType]); +} +function matchesAnyPattern(filePath, patterns, baseDir) { + const rel = toPosixPath(relative(baseDir, filePath)); + const name = basename(filePath); + const filePathPosix = toPosixPath(filePath); + const isSkillFile = name === "SKILL.md"; + const parentDir = isSkillFile ? dirname(filePath) : undefined; + const parentRel = isSkillFile ? toPosixPath(relative(baseDir, parentDir)) : undefined; + const parentName = isSkillFile ? basename(parentDir) : undefined; + const parentDirPosix = isSkillFile ? toPosixPath(parentDir) : undefined; + return patterns.some((pattern) => { + const normalizedPattern = toPosixPath(pattern); + if (minimatch(rel, normalizedPattern) || + minimatch(name, normalizedPattern) || + minimatch(filePathPosix, normalizedPattern)) { + return true; + } + if (!isSkillFile) + return false; + return (minimatch(parentRel, normalizedPattern) || + minimatch(parentName, normalizedPattern) || + minimatch(parentDirPosix, normalizedPattern)); + }); +} +function normalizeExactPattern(pattern) { + const normalized = pattern.startsWith("./") || pattern.startsWith(".\\") ? pattern.slice(2) : pattern; + return toPosixPath(normalized); +} +function matchesAnyExactPattern(filePath, patterns, baseDir) { + if (patterns.length === 0) + return false; + const rel = toPosixPath(relative(baseDir, filePath)); + const name = basename(filePath); + const filePathPosix = toPosixPath(filePath); + const isSkillFile = name === "SKILL.md"; + const parentDir = isSkillFile ? dirname(filePath) : undefined; + const parentRel = isSkillFile ? toPosixPath(relative(baseDir, parentDir)) : undefined; + const parentDirPosix = isSkillFile ? toPosixPath(parentDir) : undefined; + return patterns.some((pattern) => { + const normalized = normalizeExactPattern(pattern); + if (normalized === rel || normalized === filePathPosix) { + return true; + } + if (!isSkillFile) + return false; + return normalized === parentRel || normalized === parentDirPosix; + }); +} +function getOverridePatterns(entries) { + return entries.filter((pattern) => pattern.startsWith("!") || pattern.startsWith("+") || pattern.startsWith("-")); +} +function isEnabledByOverrides(filePath, patterns, baseDir) { + const overrides = getOverridePatterns(patterns); + const excludes = overrides.filter((pattern) => pattern.startsWith("!")).map((pattern) => pattern.slice(1)); + const forceIncludes = overrides.filter((pattern) => pattern.startsWith("+")).map((pattern) => pattern.slice(1)); + const forceExcludes = overrides.filter((pattern) => pattern.startsWith("-")).map((pattern) => pattern.slice(1)); + let enabled = true; + if (excludes.length > 0 && matchesAnyPattern(filePath, excludes, baseDir)) { + enabled = false; + } + if (forceIncludes.length > 0 && matchesAnyExactPattern(filePath, forceIncludes, baseDir)) { + enabled = true; + } + if (forceExcludes.length > 0 && matchesAnyExactPattern(filePath, forceExcludes, baseDir)) { + enabled = false; + } + return enabled; +} +/** + * Apply patterns to paths and return a Set of enabled paths. + * Pattern types: + * - Plain patterns: include matching paths + * - `!pattern`: exclude matching paths + * - `+path`: force-include exact path (overrides exclusions) + * - `-path`: force-exclude exact path (overrides force-includes) + */ +function applyPatterns(allPaths, patterns, baseDir) { + const includes = []; + const excludes = []; + const forceIncludes = []; + const forceExcludes = []; + for (const p of patterns) { + if (p.startsWith("+")) { + forceIncludes.push(p.slice(1)); + } + else if (p.startsWith("-")) { + forceExcludes.push(p.slice(1)); + } + else if (p.startsWith("!")) { + excludes.push(p.slice(1)); + } + else { + includes.push(p); + } + } + // Step 1: Apply includes (or all if no includes) + let result; + if (includes.length === 0) { + result = [...allPaths]; + } + else { + result = allPaths.filter((filePath) => matchesAnyPattern(filePath, includes, baseDir)); + } + // Step 2: Apply excludes + if (excludes.length > 0) { + result = result.filter((filePath) => !matchesAnyPattern(filePath, excludes, baseDir)); + } + // Step 3: Force-include (add back from allPaths, overriding exclusions) + if (forceIncludes.length > 0) { + for (const filePath of allPaths) { + if (!result.includes(filePath) && matchesAnyExactPattern(filePath, forceIncludes, baseDir)) { + result.push(filePath); + } + } + } + // Step 4: Force-exclude (remove even if included or force-included) + if (forceExcludes.length > 0) { + result = result.filter((filePath) => !matchesAnyExactPattern(filePath, forceExcludes, baseDir)); + } + return new Set(result); +} +function applyAutoloadDisabledPatterns(allPaths, patterns, baseDir) { + const result = new Map(); + for (const pattern of patterns) { + const target = pattern.slice(pattern.startsWith("+") || pattern.startsWith("-") || pattern.startsWith("!") ? 1 : 0); + const enabled = !pattern.startsWith("-") && !pattern.startsWith("!"); + const exact = pattern.startsWith("+") || pattern.startsWith("-"); + for (const filePath of allPaths) { + if (exact ? matchesAnyExactPattern(filePath, [target], baseDir) : matchesAnyPattern(filePath, [target], baseDir)) { + result.set(filePath, enabled); + } + } + } + return result; +} +export class DefaultPackageManager { + cwd; + agentDir; + settingsManager; + globalNpmRoot; + globalNpmRootCommandKey; + progressCallback; + constructor(options) { + this.cwd = resolvePath(options.cwd); + this.agentDir = resolvePath(options.agentDir); + this.settingsManager = options.settingsManager; + } + setProgressCallback(callback) { + this.progressCallback = callback; + } + addSourceToSettings(source, options) { + const scope = options?.local ? "project" : "user"; + const currentSettings = scope === "project" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings(); + const currentPackages = currentSettings.packages ?? []; + const normalizedSource = this.normalizePackageSourceForSettings(source, scope); + const matchIndex = currentPackages.findIndex((existing) => this.packageSourcesMatch(existing, source, scope)); + if (matchIndex !== -1) { + const existing = currentPackages[matchIndex]; + if (this.getPackageSourceString(existing) === normalizedSource) { + return false; + } + const nextPackages = [...currentPackages]; + nextPackages[matchIndex] = + typeof existing === "string" ? normalizedSource : { ...existing, source: normalizedSource }; + if (scope === "project") { + this.settingsManager.setProjectPackages(nextPackages); + } + else { + this.settingsManager.setPackages(nextPackages); + } + return true; + } + const nextPackages = [...currentPackages, normalizedSource]; + if (scope === "project") { + this.settingsManager.setProjectPackages(nextPackages); + } + else { + this.settingsManager.setPackages(nextPackages); + } + return true; + } + removeSourceFromSettings(source, options) { + const scope = options?.local ? "project" : "user"; + const currentSettings = scope === "project" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings(); + const currentPackages = currentSettings.packages ?? []; + const nextPackages = currentPackages.filter((existing) => !this.packageSourcesMatch(existing, source, scope)); + const changed = nextPackages.length !== currentPackages.length; + if (!changed) { + return false; + } + if (scope === "project") { + this.settingsManager.setProjectPackages(nextPackages); + } + else { + this.settingsManager.setPackages(nextPackages); + } + return true; + } + getInstalledPath(source, scope) { + const parsed = this.parseSource(source); + if (parsed.type === "npm") { + const path = this.getNpmInstallPath(parsed, scope); + return existsSync(path) ? path : undefined; + } + if (parsed.type === "git") { + const path = this.getGitInstallPath(parsed, scope); + return existsSync(path) ? path : undefined; + } + if (parsed.type === "local") { + const baseDir = this.getBaseDirForScope(scope); + const path = this.resolvePathFromBase(parsed.path, baseDir); + return existsSync(path) ? path : undefined; + } + return undefined; + } + emitProgress(event) { + this.progressCallback?.(event); + } + async withProgress(action, source, message, operation) { + this.emitProgress({ type: "start", action, source, message }); + try { + await operation(); + this.emitProgress({ type: "complete", action, source }); + } + catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + this.emitProgress({ type: "error", action, source, message: errorMessage }); + throw error; + } + } + async resolve(onMissing) { + const accumulator = this.createAccumulator(); + const globalSettings = this.settingsManager.getGlobalSettings(); + const projectSettings = this.settingsManager.getProjectSettings(); + // Collect all packages with scope (project first so cwd resources win collisions) + const allPackages = []; + for (const pkg of projectSettings.packages ?? []) { + allPackages.push({ pkg, scope: "project" }); + } + for (const pkg of globalSettings.packages ?? []) { + allPackages.push({ pkg, scope: "user" }); + } + // Dedupe: project scope wins over global for same package identity + const packageSources = this.dedupePackages(allPackages); + await this.resolvePackageSources(packageSources, accumulator, onMissing); + const globalBaseDir = this.agentDir; + const projectBaseDir = join(this.cwd, CONFIG_DIR_NAME); + for (const resourceType of RESOURCE_TYPES) { + const target = this.getTargetMap(accumulator, resourceType); + const globalEntries = (globalSettings[resourceType] ?? []); + const projectEntries = (projectSettings[resourceType] ?? []); + this.resolveLocalEntries(projectEntries, resourceType, target, { + source: "local", + scope: "project", + origin: "top-level", + }, projectBaseDir); + this.resolveLocalEntries(globalEntries, resourceType, target, { + source: "local", + scope: "user", + origin: "top-level", + }, globalBaseDir); + } + this.addAutoDiscoveredResources(accumulator, globalSettings, projectSettings, globalBaseDir, projectBaseDir); + return this.toResolvedPaths(accumulator); + } + async resolveExtensionSources(sources, options) { + const accumulator = this.createAccumulator(); + const scope = options?.temporary ? "temporary" : options?.local ? "project" : "user"; + const packageSources = sources.map((source) => ({ pkg: source, scope })); + await this.resolvePackageSources(packageSources, accumulator); + return this.toResolvedPaths(accumulator); + } + listConfiguredPackages() { + const globalSettings = this.settingsManager.getGlobalSettings(); + const projectSettings = this.settingsManager.getProjectSettings(); + const configuredPackages = []; + for (const pkg of globalSettings.packages ?? []) { + const source = typeof pkg === "string" ? pkg : pkg.source; + configuredPackages.push({ + source, + scope: "user", + filtered: typeof pkg === "object", + installedPath: this.getInstalledPath(source, "user"), + }); + } + for (const pkg of projectSettings.packages ?? []) { + const source = typeof pkg === "string" ? pkg : pkg.source; + configuredPackages.push({ + source, + scope: "project", + filtered: typeof pkg === "object", + installedPath: this.getInstalledPath(source, "project"), + }); + } + return configuredPackages; + } + async install(source, options) { + const parsed = this.parseSource(source); + const scope = options?.local ? "project" : "user"; + this.assertProjectTrustedForScope(scope); + await this.withProgress("install", source, `Installing ${source}...`, async () => { + if (parsed.type === "npm") { + await this.installNpm(parsed, scope, false); + return; + } + if (parsed.type === "git") { + await this.installGit(parsed, scope); + return; + } + if (parsed.type === "local") { + const resolved = this.resolvePath(parsed.path); + if (!existsSync(resolved)) { + throw new Error(`Path does not exist: ${resolved}`); + } + return; + } + throw new Error(`Unsupported install source: ${source}`); + }); + } + async installAndPersist(source, options) { + await this.install(source, options); + this.addSourceToSettings(source, options); + } + async remove(source, options) { + const parsed = this.parseSource(source); + const scope = options?.local ? "project" : "user"; + this.assertProjectTrustedForScope(scope); + await this.withProgress("remove", source, `Removing ${source}...`, async () => { + if (parsed.type === "npm") { + await this.uninstallNpm(parsed, scope); + return; + } + if (parsed.type === "git") { + await this.removeGit(parsed, scope); + return; + } + if (parsed.type === "local") { + return; + } + throw new Error(`Unsupported remove source: ${source}`); + }); + } + async removeAndPersist(source, options) { + await this.remove(source, options); + return this.removeSourceFromSettings(source, options); + } + async update(source) { + const globalSettings = this.settingsManager.getGlobalSettings(); + const projectSettings = this.settingsManager.getProjectSettings(); + const identity = source ? this.getPackageIdentity(source) : undefined; + let matched = false; + const updateSources = []; + for (const pkg of globalSettings.packages ?? []) { + const sourceStr = typeof pkg === "string" ? pkg : pkg.source; + if (identity && this.getPackageIdentity(sourceStr, "user") !== identity) + continue; + matched = true; + updateSources.push({ source: sourceStr, scope: "user" }); + } + for (const pkg of projectSettings.packages ?? []) { + const sourceStr = typeof pkg === "string" ? pkg : pkg.source; + if (identity && this.getPackageIdentity(sourceStr, "project") !== identity) + continue; + matched = true; + updateSources.push({ source: sourceStr, scope: "project" }); + } + if (source && !matched) { + throw new Error(this.buildNoMatchingPackageMessage(source, [ + ...(globalSettings.packages ?? []), + ...(projectSettings.packages ?? []), + ])); + } + await this.updateConfiguredSources(updateSources); + } + async updateConfiguredSources(sources) { + if (isOfflineModeEnabled() || sources.length === 0) { + return; + } + const npmCandidates = []; + const gitCandidates = []; + for (const entry of sources) { + const parsed = this.parseSource(entry.source); + // Pinned npm versions are fixed. Pinned git refs are configured checkout targets, + // so include them to reconcile an existing clone when the configured ref changes. + if (parsed.type === "npm") { + if (!parsed.pinned) { + npmCandidates.push({ ...entry, parsed }); + } + } + else if (parsed.type === "git") { + gitCandidates.push({ ...entry, parsed }); + } + } + const npmCheckTasks = npmCandidates.map((entry) => async () => ({ + entry, + shouldUpdate: await this.shouldUpdateNpmSource(entry.parsed, entry.scope), + })); + const npmCheckResults = await this.runWithConcurrency(npmCheckTasks, UPDATE_CHECK_CONCURRENCY); + const userNpmUpdates = []; + const projectNpmUpdates = []; + for (const result of npmCheckResults) { + if (!result.shouldUpdate) { + continue; + } + if (result.entry.scope === "user") { + userNpmUpdates.push(result.entry); + } + else { + projectNpmUpdates.push(result.entry); + } + } + const tasks = []; + if (userNpmUpdates.length > 0) { + tasks.push(this.updateNpmBatch(userNpmUpdates, "user")); + } + if (projectNpmUpdates.length > 0) { + tasks.push(this.updateNpmBatch(projectNpmUpdates, "project")); + } + if (gitCandidates.length > 0) { + const gitTasks = gitCandidates.map((entry) => async () => this.withProgress("update", entry.source, `Updating ${entry.source}...`, async () => { + await this.updateGit(entry.parsed, entry.scope); + })); + tasks.push(this.runWithConcurrency(gitTasks, GIT_UPDATE_CONCURRENCY).then(() => { })); + } + await Promise.all(tasks); + } + async shouldUpdateNpmSource(source, scope) { + const installedPath = this.getManagedNpmInstallPath(source, scope); + const installedVersion = existsSync(installedPath) ? this.getInstalledNpmVersion(installedPath) : undefined; + if (!installedVersion) { + return true; + } + try { + const targetVersion = await this.getLatestNpmVersion(source.version ? source.spec : source.name, source.range); + return targetVersion !== installedVersion; + } + catch { + // Preserve existing update behavior when version lookup fails. + return true; + } + } + async updateNpmBatch(sources, scope) { + if (sources.length === 0) { + return; + } + const sourceLabel = sources.length === 1 ? sources[0].source : `${scope} npm packages`; + const message = sources.length === 1 ? `Updating ${sources[0].source}...` : `Updating ${scope} npm packages...`; + const specs = sources.map((entry) => (entry.parsed.version ? entry.parsed.spec : `${entry.parsed.name}@latest`)); + await this.withProgress("update", sourceLabel, message, async () => { + await this.installNpmBatch(specs, scope); + }); + } + async installNpmBatch(specs, scope) { + const installRoot = this.getNpmInstallRoot(scope, false); + this.ensureNpmProject(installRoot); + await this.runNpmCommand(this.getNpmInstallArgs(specs, installRoot)); + } + async checkForAvailableUpdates() { + if (isOfflineModeEnabled()) { + return []; + } + const globalSettings = this.settingsManager.getGlobalSettings(); + const projectSettings = this.settingsManager.getProjectSettings(); + const allPackages = []; + for (const pkg of projectSettings.packages ?? []) { + allPackages.push({ pkg, scope: "project" }); + } + for (const pkg of globalSettings.packages ?? []) { + allPackages.push({ pkg, scope: "user" }); + } + const packageSources = this.dedupePackages(allPackages); + const checks = packageSources + .filter((entry) => entry.scope !== "temporary") + .map((entry) => async () => { + const source = typeof entry.pkg === "string" ? entry.pkg : entry.pkg.source; + const parsed = this.parseSource(source); + if (parsed.type === "local" || parsed.pinned) { + return undefined; + } + if (parsed.type === "npm") { + const installedPath = this.getNpmInstallPath(parsed, entry.scope); + if (!existsSync(installedPath)) { + return undefined; + } + const hasUpdate = await this.npmHasAvailableUpdate(parsed, installedPath); + if (!hasUpdate) { + return undefined; + } + return { + source, + displayName: parsed.name, + type: "npm", + scope: entry.scope, + }; + } + const installedPath = this.getGitInstallPath(parsed, entry.scope); + if (!existsSync(installedPath)) { + return undefined; + } + const hasUpdate = await this.gitHasAvailableUpdate(installedPath); + if (!hasUpdate) { + return undefined; + } + return { + source, + displayName: `${parsed.host}/${parsed.path}`, + type: "git", + scope: entry.scope, + }; + }); + const results = await this.runWithConcurrency(checks, UPDATE_CHECK_CONCURRENCY); + return results.filter((result) => result !== undefined); + } + async resolvePackageSources(sources, accumulator, onMissing) { + for (const { pkg, scope } of sources) { + const sourceStr = typeof pkg === "string" ? pkg : pkg.source; + const filter = typeof pkg === "object" ? pkg : undefined; + const deltaBase = this.findAutoloadDeltaBase(pkg, scope, sources); + const resolvedSource = deltaBase?.source ?? sourceStr; + const resolvedScope = deltaBase?.scope ?? scope; + const parsed = this.parseSource(resolvedSource); + const metadata = { source: sourceStr, scope, origin: "package" }; + if (parsed.type === "local") { + const baseDir = this.getBaseDirForScope(resolvedScope); + this.resolveLocalExtensionSource(parsed, accumulator, filter, metadata, baseDir); + continue; + } + const installMissing = async () => { + if (isOfflineModeEnabled()) + return false; + if (!onMissing) { + await this.installParsedSource(parsed, resolvedScope); + return true; + } + const action = await onMissing(resolvedSource); + if (action === "skip") + return false; + if (action === "error") + throw new Error(`Missing source: ${resolvedSource}`); + await this.installParsedSource(parsed, resolvedScope); + return true; + }; + if (parsed.type === "npm") { + let installedPath = this.getNpmInstallPath(parsed, resolvedScope); + const needsInstall = !existsSync(installedPath) || !(await this.installedNpmMatchesConfiguredVersion(parsed, installedPath)); + if (needsInstall) { + const installed = await installMissing(); + if (!installed) + continue; + installedPath = this.getNpmInstallPath(parsed, resolvedScope); + } + metadata.baseDir = installedPath; + this.collectPackageResources(installedPath, accumulator, filter, metadata); + continue; + } + if (parsed.type === "git") { + const installedPath = this.getGitInstallPath(parsed, resolvedScope); + if (!existsSync(installedPath)) { + const installed = await installMissing(); + if (!installed) + continue; + } + else if (resolvedScope === "temporary" && !parsed.pinned && !isOfflineModeEnabled()) { + await this.refreshTemporaryGitSource(parsed, resolvedSource); + } + metadata.baseDir = installedPath; + this.collectPackageResources(installedPath, accumulator, filter, metadata); + } + } + } + findAutoloadDeltaBase(pkg, scope, sources) { + if (scope !== "project" || typeof pkg !== "object" || pkg.autoload !== false) + return undefined; + const identity = this.getPackageIdentity(pkg.source, scope); + const userEntry = sources.find((entry) => entry.scope === "user" && + this.getPackageIdentity(this.getPackageSourceString(entry.pkg), "user") === identity); + return userEntry ? { source: this.getPackageSourceString(userEntry.pkg), scope: "user" } : undefined; + } + resolveLocalExtensionSource(source, accumulator, filter, metadata, baseDir) { + const resolved = this.resolvePathFromBase(source.path, baseDir); + if (!existsSync(resolved)) { + return; + } + try { + const stats = statSync(resolved); + if (stats.isFile()) { + metadata.baseDir = dirname(resolved); + this.addResource(accumulator.extensions, resolved, metadata, true); + return; + } + if (stats.isDirectory()) { + metadata.baseDir = resolved; + const resources = this.collectPackageResources(resolved, accumulator, filter, metadata); + if (!resources) { + this.addResource(accumulator.extensions, resolved, metadata, true); + } + } + } + catch { + return; + } + } + async installParsedSource(parsed, scope) { + if (parsed.type === "npm") { + await this.installNpm(parsed, scope, scope === "temporary"); + return; + } + if (parsed.type === "git") { + await this.installGit(parsed, scope); + return; + } + } + getPackageSourceString(pkg) { + return typeof pkg === "string" ? pkg : pkg.source; + } + getSourceMatchKeyForInput(source) { + const parsed = this.parseSource(source); + if (parsed.type === "npm") { + return `npm:${parsed.name}`; + } + if (parsed.type === "git") { + return `git:${parsed.host}/${parsed.path}`; + } + return `local:${this.resolvePath(parsed.path)}`; + } + getSourceMatchKeyForSettings(source, scope) { + const parsed = this.parseSource(source); + if (parsed.type === "npm") { + return `npm:${parsed.name}`; + } + if (parsed.type === "git") { + return `git:${parsed.host}/${parsed.path}`; + } + const baseDir = this.getBaseDirForScope(scope); + return `local:${this.resolvePathFromBase(parsed.path, baseDir)}`; + } + buildNoMatchingPackageMessage(source, configuredPackages) { + const suggestion = this.findSuggestedConfiguredSource(source, configuredPackages); + if (!suggestion) { + return `No matching package found for ${source}`; + } + return `No matching package found for ${source}. Did you mean ${suggestion}?`; + } + findSuggestedConfiguredSource(source, configuredPackages) { + const trimmedSource = source.trim(); + const suggestions = new Set(); + for (const pkg of configuredPackages) { + const sourceStr = this.getPackageSourceString(pkg); + const parsed = this.parseSource(sourceStr); + if (parsed.type === "npm") { + if (trimmedSource === parsed.name || trimmedSource === parsed.spec) { + suggestions.add(sourceStr); + } + continue; + } + if (parsed.type === "git") { + const shorthand = `${parsed.host}/${parsed.path}`; + const shorthandWithRef = parsed.ref ? `${shorthand}@${parsed.ref}` : undefined; + if (trimmedSource === shorthand || (shorthandWithRef && trimmedSource === shorthandWithRef)) { + suggestions.add(sourceStr); + } + } + } + return suggestions.values().next().value; + } + packageSourcesMatch(existing, inputSource, scope) { + const left = this.getSourceMatchKeyForSettings(this.getPackageSourceString(existing), scope); + const right = this.getSourceMatchKeyForInput(inputSource); + return left === right; + } + normalizePackageSourceForSettings(source, scope) { + const parsed = this.parseSource(source); + if (parsed.type !== "local") { + return source; + } + const baseDir = this.getBaseDirForScope(scope); + const resolved = this.resolvePath(parsed.path); + const rel = relative(baseDir, resolved); + return rel || "."; + } + parseSource(source) { + if (source.startsWith("npm:")) { + const spec = source.slice("npm:".length).trim(); + const { name, version } = this.parseNpmSpec(spec); + return { + type: "npm", + spec, + name, + version, + range: getNpmVersionRange(version), + pinned: isExactNpmVersion(version), + }; + } + if (isLocalPath(source)) { + return { type: "local", path: source }; + } + // Try parsing as git URL + const gitParsed = parseGitUrl(source); + if (gitParsed) { + return gitParsed; + } + return { type: "local", path: source }; + } + async installedNpmMatchesConfiguredVersion(source, installedPath) { + const installedVersion = this.getInstalledNpmVersion(installedPath); + if (!installedVersion) { + return false; + } + return source.range ? satisfies(installedVersion, source.range) : true; + } + async npmHasAvailableUpdate(source, installedPath) { + if (isOfflineModeEnabled()) { + return false; + } + const installedVersion = this.getInstalledNpmVersion(installedPath); + if (!installedVersion) { + return false; + } + try { + const targetVersion = await this.getLatestNpmVersion(source.version ? source.spec : source.name, source.range); + return targetVersion !== installedVersion; + } + catch { + return false; + } + } + getInstalledNpmVersion(installedPath) { + const packageJsonPath = join(installedPath, "package.json"); + if (!existsSync(packageJsonPath)) + return undefined; + try { + const content = readFileSync(packageJsonPath, "utf-8"); + const pkg = JSON.parse(content); + return pkg.version; + } + catch { + return undefined; + } + } + async getLatestNpmVersion(packageSpec, range) { + const npmCommand = this.getNpmCommand(); + const stdout = await this.runCommandCapture(npmCommand.command, [...npmCommand.args, "view", packageSpec, "version", "--json"], { cwd: this.cwd, timeoutMs: NETWORK_TIMEOUT_MS }); + const raw = stdout.trim(); + if (!raw) + throw new Error("Empty response from npm view"); + const parsed = JSON.parse(raw); + if (typeof parsed === "string") { + return parsed; + } + if (Array.isArray(parsed)) { + const versions = parsed.filter((value) => typeof value === "string" && value.length > 0); + const latest = range ? maxSatisfying(versions, range) : [...versions].sort(rcompare)[0]; + if (latest) + return latest; + } + throw new Error("Unexpected response from npm view"); + } + async gitHasAvailableUpdate(installedPath) { + if (isOfflineModeEnabled()) { + return false; + } + try { + const localHead = await this.runCommandCapture("git", ["rev-parse", "HEAD"], { + cwd: installedPath, + timeoutMs: NETWORK_TIMEOUT_MS, + }); + const remoteHead = await this.getRemoteGitHead(installedPath); + return localHead.trim() !== remoteHead.trim(); + } + catch { + return false; + } + } + async getRemoteGitHead(installedPath) { + const upstreamRef = await this.getGitUpstreamRef(installedPath); + if (upstreamRef) { + const remoteHead = await this.runGitRemoteCommand(installedPath, ["ls-remote", "origin", upstreamRef]); + const match = remoteHead.match(/^([0-9a-f]{40})\s+/m); + if (match?.[1]) { + return match[1]; + } + } + const remoteHead = await this.runGitRemoteCommand(installedPath, ["ls-remote", "origin", "HEAD"]); + const match = remoteHead.match(/^([0-9a-f]{40})\s+HEAD$/m); + if (!match?.[1]) { + throw new Error("Failed to determine remote HEAD"); + } + return match[1]; + } + async getLocalGitUpdateTarget(installedPath) { + try { + const upstream = await this.runCommandCapture("git", ["rev-parse", "--abbrev-ref", "@{upstream}"], { + cwd: installedPath, + timeoutMs: NETWORK_TIMEOUT_MS, + }); + const trimmedUpstream = upstream.trim(); + if (!trimmedUpstream.startsWith("origin/")) { + throw new Error(`Unsupported upstream remote: ${trimmedUpstream}`); + } + const branch = trimmedUpstream.slice("origin/".length); + if (!branch) { + throw new Error("Missing upstream branch name"); + } + const head = await this.runCommandCapture("git", ["rev-parse", "@{upstream}"], { + cwd: installedPath, + timeoutMs: NETWORK_TIMEOUT_MS, + }); + return { + ref: "@{upstream}", + head, + fetchArgs: [ + "fetch", + "--prune", + "--no-tags", + "origin", + `+refs/heads/${branch}:refs/remotes/origin/${branch}`, + ], + }; + } + catch { + await this.runCommand("git", ["remote", "set-head", "origin", "-a"], { cwd: installedPath }).catch(() => { }); + const head = await this.runCommandCapture("git", ["rev-parse", "origin/HEAD"], { + cwd: installedPath, + timeoutMs: NETWORK_TIMEOUT_MS, + }); + const originHeadRef = await this.runCommandCapture("git", ["symbolic-ref", "refs/remotes/origin/HEAD"], { + cwd: installedPath, + timeoutMs: NETWORK_TIMEOUT_MS, + }).catch(() => ""); + const branch = originHeadRef.trim().replace(/^refs\/remotes\/origin\//, ""); + if (branch) { + return { + ref: "origin/HEAD", + head, + fetchArgs: [ + "fetch", + "--prune", + "--no-tags", + "origin", + `+refs/heads/${branch}:refs/remotes/origin/${branch}`, + ], + }; + } + return { + ref: "origin/HEAD", + head, + fetchArgs: ["fetch", "--prune", "--no-tags", "origin", "+HEAD:refs/remotes/origin/HEAD"], + }; + } + } + async getGitUpstreamRef(installedPath) { + try { + const upstream = await this.runCommandCapture("git", ["rev-parse", "--abbrev-ref", "@{upstream}"], { + cwd: installedPath, + timeoutMs: NETWORK_TIMEOUT_MS, + }); + const trimmed = upstream.trim(); + if (!trimmed.startsWith("origin/")) { + return undefined; + } + const branch = trimmed.slice("origin/".length); + return branch ? `refs/heads/${branch}` : undefined; + } + catch { + return undefined; + } + } + runGitRemoteCommand(installedPath, args) { + return this.runCommandCapture("git", args, { + cwd: installedPath, + timeoutMs: NETWORK_TIMEOUT_MS, + env: { + GIT_TERMINAL_PROMPT: "0", + }, + }); + } + async runWithConcurrency(tasks, limit) { + if (tasks.length === 0) { + return []; + } + const results = new Array(tasks.length); + let nextIndex = 0; + const workerCount = Math.max(1, Math.min(limit, tasks.length)); + const worker = async () => { + while (true) { + const index = nextIndex; + nextIndex += 1; + if (index >= tasks.length) { + return; + } + results[index] = await tasks[index](); + } + }; + await Promise.all(Array.from({ length: workerCount }, () => worker())); + return results; + } + /** + * Get a unique identity for a package, ignoring version/ref. + * Used to detect when the same package is in both global and project settings. + * For git packages, uses normalized host/path to ensure SSH and HTTPS URLs + * for the same repository are treated as identical. + */ + getPackageIdentity(source, scope) { + const parsed = this.parseSource(source); + if (parsed.type === "npm") { + return `npm:${parsed.name}`; + } + if (parsed.type === "git") { + // Use host/path for identity to normalize SSH and HTTPS + return `git:${parsed.host}/${parsed.path}`; + } + if (scope) { + const baseDir = this.getBaseDirForScope(scope); + return `local:${this.resolvePathFromBase(parsed.path, baseDir)}`; + } + return `local:${this.resolvePath(parsed.path)}`; + } + /** + * Dedupe packages: if same package identity appears in both global and project, + * keep only the project one (project wins). A project entry with autoload=false + * is a delta over the global entry, so both are kept (delta first). + */ + dedupePackages(packages) { + const result = []; + const seen = new Map(); + for (const entry of packages) { + const identity = this.getPackageIdentity(this.getPackageSourceString(entry.pkg), entry.scope); + const index = seen.get(identity); + if (index === undefined) { + seen.set(identity, result.length); + result.push(entry); + continue; + } + const existing = result[index]; + if (existing?.scope === "project" && entry.scope === "user") { + if (typeof existing.pkg === "object" && existing.pkg.autoload === false) + result.push(entry); + } + else if (entry.scope === "project") { + result[index] = entry; + } + } + return result; + } + parseNpmSpec(spec) { + const match = spec.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/); + if (!match) { + return { name: spec }; + } + const name = match[1] ?? spec; + const version = match[2]; + return { name, version }; + } + assertProjectTrustedForScope(scope) { + if (scope === "project" && !this.settingsManager.isProjectTrusted()) { + throw new Error("Project is not trusted; refusing to access project package storage"); + } + } + getNpmCommand() { + const configuredCommand = this.settingsManager.getNpmCommand(); + if (!configuredCommand || configuredCommand.length === 0) { + return { command: "npm", args: [] }; + } + const [command, ...args] = configuredCommand; + if (!command) { + throw new Error("Invalid npmCommand: first array entry must be a non-empty command"); + } + return { command, args }; + } + getPackageManagerName() { + const npmCommand = this.getNpmCommand(); + const commandParts = [npmCommand.command, ...npmCommand.args]; + const separatorIndex = commandParts.lastIndexOf("--"); + const packageManagerCommand = separatorIndex >= 0 ? commandParts[separatorIndex + 1] : npmCommand.command; + return packageManagerCommand ? basename(packageManagerCommand).replace(/\.(cmd|exe)$/i, "") : ""; + } + async runNpmCommand(args, options) { + const npmCommand = this.getNpmCommand(); + await this.runCommand(npmCommand.command, [...npmCommand.args, ...args], options); + } + getGitDependencyInstallArgs() { + const configuredCommand = this.settingsManager.getNpmCommand(); + if (configuredCommand && configuredCommand.length > 0) { + return ["install"]; + } + return ["install", "--omit=dev"]; + } + runNpmCommandSync(args) { + const npmCommand = this.getNpmCommand(); + return this.runCommandSync(npmCommand.command, [...npmCommand.args, ...args]); + } + getNpmInstallArgs(specs, installRoot) { + const packageManagerName = this.getPackageManagerName(); + // Extension packages run inside pi and resolve pi APIs through loader aliases/virtual modules. + // Disable peer dependency resolution for managed installs (npm's --legacy-peer-deps, and + // equivalent bun/pnpm settings) so package managers do not install or solve host-provided + // @earendil-works/pi-* peers. Stale auto-installed pi peers can otherwise block updates. + if (packageManagerName === "bun") { + return ["install", ...specs, "--cwd", installRoot, "--omit=peer"]; + } + if (packageManagerName === "pnpm") { + return [ + "install", + ...specs, + "--prefix", + installRoot, + "--config.auto-install-peers=false", + "--config.strict-peer-dependencies=false", + "--config.strict-dep-builds=false", + ]; + } + return ["install", ...specs, "--prefix", installRoot, "--legacy-peer-deps"]; + } + async installNpm(source, scope, temporary) { + const installRoot = this.getNpmInstallRoot(scope, temporary); + this.ensureNpmProject(installRoot); + await this.runNpmCommand(this.getNpmInstallArgs([source.spec], installRoot)); + } + async uninstallNpm(source, scope) { + const installRoot = this.getNpmInstallRoot(scope, false); + if (!existsSync(installRoot)) { + return; + } + const packageManagerName = this.getPackageManagerName(); + if (packageManagerName === "bun") { + await this.runNpmCommand(["uninstall", source.name, "--cwd", installRoot]); + return; + } + const args = ["uninstall", source.name, "--prefix", installRoot]; + if (packageManagerName !== "pnpm") { + args.push("--legacy-peer-deps"); + } + await this.runNpmCommand(args); + } + async installGit(source, scope) { + const targetDir = this.getGitInstallPath(source, scope); + if (existsSync(targetDir)) { + if (source.ref) { + await this.ensureGitRef(targetDir, ["fetch", "origin", source.ref], "FETCH_HEAD"); + return; + } + const target = await this.getLocalGitUpdateTarget(targetDir); + await this.ensureGitRef(targetDir, target.fetchArgs, target.ref); + return; + } + const gitRoot = this.getGitInstallRoot(scope); + if (gitRoot) { + this.ensureGitIgnore(gitRoot); + } + mkdirSync(dirname(targetDir), { recursive: true }); + try { + await this.runCommand("git", ["clone", source.repo, targetDir]); + if (source.ref) { + await this.runCommand("git", ["checkout", source.ref], { cwd: targetDir }); + } + const packageJsonPath = join(targetDir, "package.json"); + if (existsSync(packageJsonPath)) { + await this.runNpmCommand(this.getGitDependencyInstallArgs(), { cwd: targetDir }); + } + } + catch (error) { + rmSync(targetDir, { recursive: true, force: true }); + this.pruneEmptyGitParents(targetDir, gitRoot); + throw error; + } + } + async updateGit(source, scope) { + const targetDir = this.getGitInstallPath(source, scope); + if (!existsSync(targetDir)) { + await this.installGit(source, scope); + return; + } + if (source.ref) { + await this.ensureGitRef(targetDir, ["fetch", "origin", source.ref], "FETCH_HEAD"); + return; + } + const target = await this.getLocalGitUpdateTarget(targetDir); + await this.ensureGitRef(targetDir, target.fetchArgs, target.ref); + } + async ensureGitRef(targetDir, fetchArgs, ref) { + // Fetch only the ref we will reset to, avoiding unrelated branch/tag noise. + await this.runCommand("git", fetchArgs, { cwd: targetDir }); + const localHead = await this.runCommandCapture("git", ["rev-parse", "HEAD"], { + cwd: targetDir, + timeoutMs: NETWORK_TIMEOUT_MS, + }); + const commitRef = `${ref}^{commit}`; + const targetHead = await this.runCommandCapture("git", ["rev-parse", commitRef], { + cwd: targetDir, + timeoutMs: NETWORK_TIMEOUT_MS, + }); + if (localHead.trim() === targetHead.trim()) { + return; + } + await this.runCommand("git", ["reset", "--hard", commitRef], { cwd: targetDir }); + // Clean untracked files (extensions should be pristine) + await this.runCommand("git", ["clean", "-fdx"], { cwd: targetDir }); + const packageJsonPath = join(targetDir, "package.json"); + if (existsSync(packageJsonPath)) { + await this.runNpmCommand(this.getGitDependencyInstallArgs(), { cwd: targetDir }); + } + } + async refreshTemporaryGitSource(source, sourceStr) { + if (isOfflineModeEnabled()) { + return; + } + try { + await this.withProgress("pull", sourceStr, `Refreshing ${sourceStr}...`, async () => { + await this.updateGit(source, "temporary"); + }); + } + catch { + // Keep cached temporary checkout if refresh fails. + } + } + async removeGit(source, scope) { + const targetDir = this.getGitInstallPath(source, scope); + if (!existsSync(targetDir)) + return; + rmSync(targetDir, { recursive: true, force: true }); + this.pruneEmptyGitParents(targetDir, this.getGitInstallRoot(scope)); + } + pruneEmptyGitParents(targetDir, installRoot) { + if (!installRoot) + return; + const resolvedRoot = resolve(installRoot); + let current = dirname(targetDir); + while (current.startsWith(resolvedRoot) && current !== resolvedRoot) { + if (!existsSync(current)) { + current = dirname(current); + continue; + } + const entries = readdirSync(current); + if (entries.length > 0) { + break; + } + try { + rmSync(current, { recursive: true, force: true }); + } + catch { + break; + } + current = dirname(current); + } + } + ensureNpmProject(installRoot) { + if (!existsSync(installRoot)) { + mkdirSync(installRoot, { recursive: true }); + } + markPathIgnoredByCloudSync(installRoot); + this.ensureGitIgnore(installRoot); + const packageJsonPath = join(installRoot, "package.json"); + if (!existsSync(packageJsonPath)) { + const pkgJson = { name: "pi-extensions", private: true }; + writeFileSync(packageJsonPath, JSON.stringify(pkgJson, null, 2), "utf-8"); + } + } + ensureGitIgnore(dir) { + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } + const ignorePath = join(dir, ".gitignore"); + if (!existsSync(ignorePath)) { + writeFileSync(ignorePath, "*\n!.gitignore\n", "utf-8"); + } + } + getNpmInstallRoot(scope, temporary) { + if (temporary) { + return this.getTemporaryDir("npm"); + } + if (scope === "project") { + this.assertProjectTrustedForScope(scope); + return join(this.cwd, CONFIG_DIR_NAME, "npm"); + } + return join(this.agentDir, "npm"); + } + getGlobalNpmRoot() { + const npmCommand = this.getNpmCommand(); + const commandKey = [npmCommand.command, ...npmCommand.args].join("\0"); + if (this.globalNpmRoot && this.globalNpmRootCommandKey === commandKey) { + return this.globalNpmRoot; + } + if (this.getPackageManagerName() === "bun") { + const binDir = this.runNpmCommandSync(["pm", "bin", "-g"]).trim(); + this.globalNpmRoot = join(dirname(binDir), "install", "global", "node_modules"); + } + else { + this.globalNpmRoot = this.runNpmCommandSync(["root", "-g"]).trim(); + } + this.globalNpmRootCommandKey = commandKey; + return this.globalNpmRoot; + } + getPnpmGlobalPackagePath(packageName) { + if (this.getPackageManagerName() !== "pnpm") { + return undefined; + } + const output = this.runNpmCommandSync(["list", "-g", "--depth", "0", "--json"]); + const entries = JSON.parse(output); + for (const entry of entries) { + const path = entry.dependencies?.[packageName]?.path; + if (path) + return path; + } + return undefined; + } + getManagedNpmInstallPath(source, scope) { + if (scope === "temporary") { + return join(this.getTemporaryDir("npm"), "node_modules", source.name); + } + if (scope === "project") { + this.assertProjectTrustedForScope(scope); + return join(this.cwd, CONFIG_DIR_NAME, "npm", "node_modules", source.name); + } + return join(this.agentDir, "npm", "node_modules", source.name); + } + getLegacyGlobalNpmInstallPath(source) { + try { + return this.getPnpmGlobalPackagePath(source.name) ?? join(this.getGlobalNpmRoot(), source.name); + } + catch { + return undefined; + } + } + getNpmInstallPath(source, scope) { + const managedPath = this.getManagedNpmInstallPath(source, scope); + if (scope !== "user" || existsSync(managedPath)) { + return managedPath; + } + const legacyPath = this.getLegacyGlobalNpmInstallPath(source); + return legacyPath && existsSync(legacyPath) ? legacyPath : managedPath; + } + getGitInstallPath(source, scope) { + if (scope === "temporary") { + return this.getTemporaryDir(`git-${source.host}`, source.path); + } + const installRoot = this.getGitInstallRoot(scope); + if (!installRoot) { + throw new Error("Missing git install root"); + } + return this.resolveManagedPath(installRoot, source.host, source.path); + } + getGitInstallRoot(scope) { + if (scope === "temporary") { + return undefined; + } + if (scope === "project") { + this.assertProjectTrustedForScope(scope); + return join(this.cwd, CONFIG_DIR_NAME, "git"); + } + return join(this.agentDir, "git"); + } + getTemporaryDir(prefix, suffix) { + const root = this.resolveManagedPath(getExtensionTempFolder(this.agentDir), prefix); + const hash = createHash("sha256") + .update(`${prefix}-${suffix ?? ""}`) + .digest("hex") + .slice(0, 8); + return this.resolveManagedPath(root, hash, suffix ?? ""); + } + resolveManagedPath(root, ...parts) { + const resolvedRoot = resolve(root); + const resolvedPath = resolve(resolvedRoot, ...parts); + if (resolvedPath !== resolvedRoot && !resolvedPath.startsWith(`${resolvedRoot}${sep}`)) { + throw new Error(`Refusing to use path outside package install root: ${resolvedPath}`); + } + return resolvedPath; + } + getBaseDirForScope(scope) { + if (scope === "project") { + this.assertProjectTrustedForScope(scope); + return join(this.cwd, CONFIG_DIR_NAME); + } + if (scope === "user") { + return this.agentDir; + } + return this.cwd; + } + resolvePath(input) { + return resolvePath(input, this.cwd, { homeDir: getHomeDir(), trim: true }); + } + resolvePathFromBase(input, baseDir) { + return resolvePath(input, baseDir, { homeDir: getHomeDir(), trim: true }); + } + collectPackageResources(packageRoot, accumulator, filter, metadata) { + if (filter) { + for (const resourceType of RESOURCE_TYPES) { + const patterns = filter[resourceType]; + const target = this.getTargetMap(accumulator, resourceType); + if (filter.autoload === false) { + this.applyPackageDeltaFilter(packageRoot, patterns ?? [], resourceType, target, metadata); + } + else if (patterns !== undefined) { + this.applyPackageFilter(packageRoot, patterns, resourceType, target, metadata); + } + else { + this.collectDefaultResources(packageRoot, resourceType, target, metadata); + } + } + return true; + } + const manifest = this.readPiManifest(packageRoot); + if (manifest) { + for (const resourceType of RESOURCE_TYPES) { + const entries = manifest[resourceType]; + this.addManifestEntries(entries, packageRoot, resourceType, this.getTargetMap(accumulator, resourceType), metadata); + } + return true; + } + let hasAnyDir = false; + for (const resourceType of RESOURCE_TYPES) { + const dir = join(packageRoot, resourceType); + if (existsSync(dir)) { + // Collect all files from the directory (all enabled by default) + const files = collectResourceFiles(dir, resourceType); + for (const f of files) { + this.addResource(this.getTargetMap(accumulator, resourceType), f, metadata, true); + } + hasAnyDir = true; + } + } + return hasAnyDir; + } + collectDefaultResources(packageRoot, resourceType, target, metadata) { + const manifest = this.readPiManifest(packageRoot); + const entries = manifest?.[resourceType]; + if (entries) { + this.addManifestEntries(entries, packageRoot, resourceType, target, metadata); + return; + } + const dir = join(packageRoot, resourceType); + if (existsSync(dir)) { + // Collect all files from the directory (all enabled by default) + const files = collectResourceFiles(dir, resourceType); + for (const f of files) { + this.addResource(target, f, metadata, true); + } + } + } + applyPackageFilter(packageRoot, userPatterns, resourceType, target, metadata) { + const { allFiles } = this.collectManifestFiles(packageRoot, resourceType); + if (userPatterns.length === 0) { + // Empty array explicitly disables all resources of this type + for (const f of allFiles) { + this.addResource(target, f, metadata, false); + } + return; + } + // Apply user patterns + const enabledByUser = applyPatterns(allFiles, userPatterns, packageRoot); + for (const f of allFiles) { + const enabled = enabledByUser.has(f); + this.addResource(target, f, metadata, enabled); + } + } + applyPackageDeltaFilter(packageRoot, userPatterns, resourceType, target, metadata) { + if (userPatterns.length === 0) { + return; + } + const { allFiles } = this.collectManifestFiles(packageRoot, resourceType); + const enabledByUser = applyAutoloadDisabledPatterns(allFiles, userPatterns, packageRoot); + for (const [filePath, enabled] of enabledByUser) { + this.addResource(target, filePath, metadata, enabled); + } + } + /** + * Collect all files from a package for a resource type, applying manifest patterns. + * Returns { allFiles, enabledByManifest } where enabledByManifest is the set of files + * that pass the manifest's own patterns. + */ + collectManifestFiles(packageRoot, resourceType) { + const manifest = this.readPiManifest(packageRoot); + const entries = manifest?.[resourceType]; + if (entries && entries.length > 0) { + const allFiles = this.collectFilesFromManifestEntries(entries, packageRoot, resourceType); + const manifestPatterns = entries.filter(isOverridePattern); + const enabledByManifest = manifestPatterns.length > 0 ? applyPatterns(allFiles, manifestPatterns, packageRoot) : new Set(allFiles); + return { allFiles: Array.from(enabledByManifest), enabledByManifest }; + } + const conventionDir = join(packageRoot, resourceType); + if (!existsSync(conventionDir)) { + return { allFiles: [], enabledByManifest: new Set() }; + } + const allFiles = collectResourceFiles(conventionDir, resourceType); + return { allFiles, enabledByManifest: new Set(allFiles) }; + } + readPiManifest(packageRoot) { + const packageJsonPath = join(packageRoot, "package.json"); + if (!existsSync(packageJsonPath)) { + return null; + } + try { + const content = readFileSync(packageJsonPath, "utf-8"); + const pkg = JSON.parse(content); + return pkg.pi ?? null; + } + catch { + return null; + } + } + addManifestEntries(entries, root, resourceType, target, metadata) { + if (!entries) + return; + const allFiles = this.collectFilesFromManifestEntries(entries, root, resourceType); + const patterns = entries.filter(isOverridePattern); + const enabledPaths = applyPatterns(allFiles, patterns, root); + for (const f of allFiles) { + if (enabledPaths.has(f)) { + this.addResource(target, f, metadata, true); + } + } + } + collectFilesFromManifestEntries(entries, root, resourceType) { + const sourceEntries = entries.filter((entry) => !isOverridePattern(entry)); + const resolved = sourceEntries.flatMap((entry) => { + if (!hasGlobPattern(entry)) { + return [resolve(root, entry)]; + } + return globSync(entry, { + cwd: root, + absolute: true, + dot: false, + nodir: false, + }).map((match) => resolve(match)); + }); + return this.collectFilesFromPaths(resolved, resourceType); + } + resolveLocalEntries(entries, resourceType, target, metadata, baseDir) { + if (entries.length === 0) + return; + // Collect all files from plain entries (non-pattern entries) + const { plain, patterns } = splitPatterns(entries); + const resolvedPlain = plain.map((p) => this.resolvePathFromBase(p, baseDir)); + const allFiles = this.collectFilesFromPaths(resolvedPlain, resourceType); + // Determine which files are enabled based on patterns + const enabledPaths = applyPatterns(allFiles, patterns, baseDir); + // Add all files with their enabled state + for (const f of allFiles) { + this.addResource(target, f, metadata, enabledPaths.has(f)); + } + } + addAutoDiscoveredResources(accumulator, globalSettings, projectSettings, globalBaseDir, projectBaseDir) { + const userMetadata = { + source: "auto", + scope: "user", + origin: "top-level", + baseDir: globalBaseDir, + }; + const projectMetadata = { + source: "auto", + scope: "project", + origin: "top-level", + baseDir: projectBaseDir, + }; + const userOverrides = { + extensions: (globalSettings.extensions ?? []), + skills: (globalSettings.skills ?? []), + prompts: (globalSettings.prompts ?? []), + themes: (globalSettings.themes ?? []), + }; + const projectOverrides = { + extensions: (projectSettings.extensions ?? []), + skills: (projectSettings.skills ?? []), + prompts: (projectSettings.prompts ?? []), + themes: (projectSettings.themes ?? []), + }; + const userDirs = { + extensions: join(globalBaseDir, "extensions"), + skills: join(globalBaseDir, "skills"), + prompts: join(globalBaseDir, "prompts"), + themes: join(globalBaseDir, "themes"), + }; + const projectDirs = { + extensions: join(projectBaseDir, "extensions"), + skills: join(projectBaseDir, "skills"), + prompts: join(projectBaseDir, "prompts"), + themes: join(projectBaseDir, "themes"), + }; + const userAgentsSkillsDir = join(getHomeDir(), ".agents", "skills"); + const projectTrusted = this.settingsManager.isProjectTrusted(); + const projectAgentsSkillDirs = projectTrusted + ? collectAncestorAgentsSkillDirs(this.cwd).filter((dir) => resolve(dir) !== resolve(userAgentsSkillsDir)) + : []; + const addResources = (resourceType, paths, metadata, overrides, baseDir) => { + const target = this.getTargetMap(accumulator, resourceType); + for (const path of paths) { + const enabled = isEnabledByOverrides(path, overrides, baseDir); + this.addResource(target, path, metadata, enabled); + } + }; + if (projectTrusted) { + // Project extensions from .pi/ + addResources("extensions", collectAutoExtensionEntries(projectDirs.extensions), projectMetadata, projectOverrides.extensions, projectBaseDir); + // Project skills from .pi/ + addResources("skills", collectAutoSkillEntries(projectDirs.skills, "pi"), projectMetadata, projectOverrides.skills, projectBaseDir); + } + // Project skills from .agents/ (each with its own baseDir) + for (const agentsSkillsDir of projectAgentsSkillDirs) { + const agentsBaseDir = dirname(agentsSkillsDir); // the .agents directory + const agentsMetadata = { + ...projectMetadata, + baseDir: agentsBaseDir, + }; + addResources("skills", collectAutoSkillEntries(agentsSkillsDir, "agents"), agentsMetadata, projectOverrides.skills, agentsBaseDir); + } + if (projectTrusted) { + addResources("prompts", collectAutoPromptEntries(projectDirs.prompts), projectMetadata, projectOverrides.prompts, projectBaseDir); + addResources("themes", collectAutoThemeEntries(projectDirs.themes), projectMetadata, projectOverrides.themes, projectBaseDir); + } + // User extensions from ~/.pi/agent/ + addResources("extensions", collectAutoExtensionEntries(userDirs.extensions), userMetadata, userOverrides.extensions, globalBaseDir); + // User skills from ~/.pi/agent/ + addResources("skills", collectAutoSkillEntries(userDirs.skills, "pi"), userMetadata, userOverrides.skills, globalBaseDir); + // User skills from ~/.agents/ (with its own baseDir) + const userAgentsBaseDir = dirname(userAgentsSkillsDir); + const userAgentsMetadata = { + ...userMetadata, + baseDir: userAgentsBaseDir, + }; + addResources("skills", collectAutoSkillEntries(userAgentsSkillsDir, "agents"), userAgentsMetadata, userOverrides.skills, userAgentsBaseDir); + addResources("prompts", collectAutoPromptEntries(userDirs.prompts), userMetadata, userOverrides.prompts, globalBaseDir); + addResources("themes", collectAutoThemeEntries(userDirs.themes), userMetadata, userOverrides.themes, globalBaseDir); + } + collectFilesFromPaths(paths, resourceType) { + const files = []; + for (const p of paths) { + if (!existsSync(p)) + continue; + try { + const stats = statSync(p); + if (stats.isFile()) { + files.push(p); + } + else if (stats.isDirectory()) { + files.push(...collectResourceFiles(p, resourceType)); + } + } + catch { + // Ignore errors + } + } + return files; + } + getTargetMap(accumulator, resourceType) { + switch (resourceType) { + case "extensions": + return accumulator.extensions; + case "skills": + return accumulator.skills; + case "prompts": + return accumulator.prompts; + case "themes": + return accumulator.themes; + default: + throw new Error(`Unknown resource type: ${resourceType}`); + } + } + addResource(map, path, metadata, enabled) { + if (!path) + return; + if (!map.has(path)) { + map.set(path, { metadata, enabled }); + } + } + createAccumulator() { + return { + extensions: new Map(), + skills: new Map(), + prompts: new Map(), + themes: new Map(), + }; + } + toResolvedPaths(accumulator) { + const mapToResolved = (entries) => { + const resolved = Array.from(entries.entries()).map(([path, { metadata, enabled }]) => ({ + path, + enabled, + metadata, + })); + resolved.sort((a, b) => resourcePrecedenceRank(a.metadata) - resourcePrecedenceRank(b.metadata)); + const seen = new Set(); + return resolved.filter((entry) => { + const canonicalPath = canonicalizePath(entry.path); + if (seen.has(canonicalPath)) + return false; + seen.add(canonicalPath); + return true; + }); + }; + return { + extensions: mapToResolved(accumulator.extensions), + skills: mapToResolved(accumulator.skills), + prompts: mapToResolved(accumulator.prompts), + themes: mapToResolved(accumulator.themes), + }; + } + spawnCommand(command, args, options) { + const env = getEnv(); + return spawnProcess(command, args, { + cwd: options?.cwd, + stdio: isStdoutTakenOver() ? ["ignore", 2, 2] : "inherit", + env, + }); + } + spawnCaptureCommand(command, args, options) { + const baseEnv = getEnv(); + const env = options?.env ? { ...baseEnv, ...options.env } : baseEnv; + return spawnProcess(command, args, { + cwd: options?.cwd, + stdio: ["ignore", "pipe", "pipe"], + env, + }); + } + runCommandCapture(command, args, options) { + return new Promise((resolvePromise, reject) => { + const child = this.spawnCaptureCommand(command, args, options); + let stdout = ""; + let stderr = ""; + let timedOut = false; + const timeout = typeof options?.timeoutMs === "number" + ? setTimeout(() => { + timedOut = true; + child.kill(); + }, options.timeoutMs) + : undefined; + child.stdout?.on("data", (data) => { + stdout += data.toString(); + }); + child.stderr?.on("data", (data) => { + stderr += data.toString(); + }); + child.once("error", (error) => { + if (timeout) + clearTimeout(timeout); + reject(error); + }); + child.once("close", (code, signal) => { + if (timeout) + clearTimeout(timeout); + if (timedOut) { + reject(new Error(`${command} ${args.join(" ")} timed out after ${options?.timeoutMs}ms`)); + return; + } + if (code === 0) { + resolvePromise(stdout.trim()); + return; + } + const exitStatus = code === null ? `signal ${signal ?? "unknown"}` : `code ${code}`; + reject(new Error(`${command} ${args.join(" ")} failed with ${exitStatus}: ${stderr || stdout}`)); + }); + }); + } + runCommand(command, args, options) { + return new Promise((resolvePromise, reject) => { + const child = this.spawnCommand(command, args, options); + child.on("error", reject); + child.on("exit", (code) => { + if (code === 0) { + resolvePromise(); + } + else { + reject(new Error(`${command} ${args.join(" ")} failed with code ${code}`)); + } + }); + }); + } + runCommandSync(command, args) { + const env = getEnv(); + const result = spawnProcessSync(command, args, { + stdio: ["ignore", "pipe", "pipe"], + encoding: "utf-8", + env, + }); + if (result.error || result.status !== 0) { + throw new Error(`Failed to run ${command} ${args.join(" ")}: ${result.error?.message || result.stderr || result.stdout}`); + } + return (result.stdout || result.stderr || "").trim(); + } +} +//# sourceMappingURL=package-manager.js.map \ No newline at end of file diff --git a/dist/core/package-manager.js.map b/dist/core/package-manager.js.map new file mode 100644 index 0000000..f8a43a8 --- /dev/null +++ b/dist/core/package-manager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"package-manager.js","sourceRoot":"","sources":["../../src/core/package-manager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACvH,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC,SAAS,MAAM,GAAsB;IACpC,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC;IACpB,CAAC;IACD,IAAI,CAAC;QACJ,MAAM,IAAI,GAAG,YAAY,CAAC,oBAAoB,EAAE,OAAO,CAAC,CAAC;QACzD,MAAM,GAAG,GAAsB,EAAE,CAAC;QAClC,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;YACtC,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AAC,IAAI,KAAK,CAAC,GAAG,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,qBAAqB,IAAI,EAAE,CAAC,CAAC,CAAC;gBAC5E,CAAC;YAAA,CACD,CAAC,CAAC;QAAA,CACH,CAAC,CAAC;IAAA,CACH;IAEO,cAAc,CAAC,OAAe,EAAE,IAAc,EAAU;QAC/D,MAAM,GAAG,GAAG,MAAM,EAAE,CAAC;QACrB,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,EAAE,IAAI,EAAE;YAC9C,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC;YACjC,QAAQ,EAAE,OAAO;YACjB,GAAG;SACH,CAAC,CAAC;QACH,IAAI,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACzC,MAAM,IAAI,KAAK,CACd,iBAAiB,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,MAAM,CAAC,KAAK,EAAE,OAAO,IAAI,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE,CACxG,CAAC;QACH,CAAC;QACD,OAAO,CAAC,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAAA,CACrD;CACD","sourcesContent":["import type { ChildProcess, ChildProcessByStdio } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\n\nfunction getEnv(): NodeJS.ProcessEnv {\n\tif (process.platform !== \"linux\" || Object.keys(process.env).length > 0) {\n\t\treturn process.env;\n\t}\n\ttry {\n\t\tconst data = readFileSync(\"/proc/self/environ\", \"utf-8\");\n\t\tconst env: NodeJS.ProcessEnv = {};\n\t\tfor (const entry of data.split(\"\\0\")) {\n\t\t\tconst idx = entry.indexOf(\"=\");\n\t\t\tif (idx > 0) {\n\t\t\t\tenv[entry.slice(0, idx)] = entry.slice(idx + 1);\n\t\t\t}\n\t\t}\n\t\treturn env;\n\t} catch {\n\t\treturn process.env;\n\t}\n}\n\nimport { basename, dirname, join, relative, resolve, sep } from \"node:path\";\nimport type { Readable } from \"node:stream\";\nimport { globSync } from \"glob\";\nimport ignore from \"ignore\";\nimport { minimatch } from \"minimatch\";\nimport { maxSatisfying, rcompare, satisfies, valid, validRange } from \"semver\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { spawnProcess, spawnProcessSync } from \"../utils/child-process.ts\";\nimport { type GitSource, parseGitUrl } from \"../utils/git.ts\";\nimport { canonicalizePath, isLocalPath, markPathIgnoredByCloudSync, resolvePath } from \"../utils/paths.ts\";\nimport { isStdoutTakenOver } from \"./output-guard.ts\";\nimport type { PackageSource, SettingsManager } from \"./settings-manager.ts\";\n\nconst NETWORK_TIMEOUT_MS = 10000;\nconst UPDATE_CHECK_CONCURRENCY = 4;\nconst GIT_UPDATE_CONCURRENCY = 4;\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.PI_OFFLINE;\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\nfunction isExactNpmVersion(version: string | undefined): boolean {\n\treturn valid(version ?? \"\") !== null;\n}\n\nfunction getNpmVersionRange(version: string | undefined): string | undefined {\n\treturn version ? (validRange(version) ?? undefined) : undefined;\n}\n\nexport interface PathMetadata {\n\tsource: string;\n\tscope: SourceScope;\n\torigin: \"package\" | \"top-level\";\n\tbaseDir?: string;\n}\n\nexport interface ResolvedResource {\n\tpath: string;\n\tenabled: boolean;\n\tmetadata: PathMetadata;\n}\n\nexport interface ResolvedPaths {\n\textensions: ResolvedResource[];\n\tskills: ResolvedResource[];\n\tprompts: ResolvedResource[];\n\tthemes: ResolvedResource[];\n}\n\nexport type MissingSourceAction = \"install\" | \"skip\" | \"error\";\n\nexport interface ProgressEvent {\n\ttype: \"start\" | \"progress\" | \"complete\" | \"error\";\n\taction: \"install\" | \"remove\" | \"update\" | \"clone\" | \"pull\";\n\tsource: string;\n\tmessage?: string;\n}\n\nexport type ProgressCallback = (event: ProgressEvent) => void;\n\nexport interface PackageUpdate {\n\tsource: string;\n\tdisplayName: string;\n\ttype: \"npm\" | \"git\";\n\tscope: Exclude;\n}\n\nexport interface ConfiguredPackage {\n\tsource: string;\n\tscope: \"user\" | \"project\";\n\tfiltered: boolean;\n\tinstalledPath?: string;\n}\n\nexport interface PackageManager {\n\tresolve(onMissing?: (source: string) => Promise): Promise;\n\tinstall(source: string, options?: { local?: boolean }): Promise;\n\tinstallAndPersist(source: string, options?: { local?: boolean }): Promise;\n\tremove(source: string, options?: { local?: boolean }): Promise;\n\tremoveAndPersist(source: string, options?: { local?: boolean }): Promise;\n\tupdate(source?: string): Promise;\n\tlistConfiguredPackages(): ConfiguredPackage[];\n\tresolveExtensionSources(\n\t\tsources: string[],\n\t\toptions?: { local?: boolean; temporary?: boolean },\n\t): Promise;\n\taddSourceToSettings(source: string, options?: { local?: boolean }): boolean;\n\tremoveSourceFromSettings(source: string, options?: { local?: boolean }): boolean;\n\tsetProgressCallback(callback: ProgressCallback | undefined): void;\n\tgetInstalledPath(source: string, scope: \"user\" | \"project\"): string | undefined;\n}\n\ninterface PackageManagerOptions {\n\tcwd: string;\n\tagentDir: string;\n\tsettingsManager: SettingsManager;\n}\n\ntype SourceScope = \"user\" | \"project\" | \"temporary\";\n\ntype NpmSource = {\n\ttype: \"npm\";\n\tspec: string;\n\tname: string;\n\tversion?: string;\n\trange?: string;\n\tpinned: boolean;\n};\n\ntype LocalSource = {\n\ttype: \"local\";\n\tpath: string;\n};\n\ntype ParsedSource = NpmSource | GitSource | LocalSource;\n\ntype InstalledSourceScope = Exclude;\n\ninterface ConfiguredUpdateSource {\n\tsource: string;\n\tscope: InstalledSourceScope;\n}\n\ninterface NpmUpdateTarget extends ConfiguredUpdateSource {\n\tparsed: NpmSource;\n}\n\ninterface GitUpdateTarget extends ConfiguredUpdateSource {\n\tparsed: GitSource;\n}\n\ninterface PiManifest {\n\textensions?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n\tthemes?: string[];\n}\n\ninterface ResourceAccumulator {\n\textensions: Map;\n\tskills: Map;\n\tprompts: Map;\n\tthemes: Map;\n}\n\n/**\n * Compute a numeric precedence rank for a resource based on its metadata.\n * Lower rank = higher precedence. Used to sort resolved resources so that\n * name-collision resolution (\"first wins\") produces the correct outcome.\n *\n * Precedence (highest to lowest):\n * 0 project + settings entry (source: \"local\", scope: \"project\")\n * 1 project + auto-discovered (source: \"auto\", scope: \"project\")\n * 2 user + settings entry (source: \"local\", scope: \"user\")\n * 3 user + auto-discovered (source: \"auto\", scope: \"user\")\n * 4 package resource (origin: \"package\")\n */\nfunction resourcePrecedenceRank(m: PathMetadata): number {\n\tif (m.origin === \"package\") return 4;\n\tconst scopeBase = m.scope === \"project\" ? 0 : 2;\n\treturn scopeBase + (m.source === \"local\" ? 0 : 1);\n}\n\ninterface PackageFilter {\n\tautoload?: boolean;\n\textensions?: string[];\n\tskills?: string[];\n\tprompts?: string[];\n\tthemes?: string[];\n}\n\ntype ResourceType = \"extensions\" | \"skills\" | \"prompts\" | \"themes\";\n\nconst RESOURCE_TYPES: ResourceType[] = [\"extensions\", \"skills\", \"prompts\", \"themes\"];\n\nconst FILE_PATTERNS: Record = {\n\textensions: /\\.(ts|js)$/,\n\tskills: /\\.md$/,\n\tprompts: /\\.md$/,\n\tthemes: /\\.json$/,\n};\n\nconst IGNORE_FILE_NAMES = [\".gitignore\", \".ignore\", \".fdignore\"];\n\ntype IgnoreMatcher = ReturnType;\n\nfunction toPosixPath(p: string): string {\n\treturn p.split(sep).join(\"/\");\n}\n\nfunction getHomeDir(): string {\n\treturn process.env.HOME || homedir();\n}\n\nexport function getExtensionTempFolder(agentDir: string): string {\n\tconst tempFolder = join(agentDir, \"tmp\", \"extensions\");\n\tmkdirSync(tempFolder, { recursive: true, mode: 0o700 });\n\tchmodSync(tempFolder, 0o700);\n\treturn tempFolder;\n}\n\nfunction prefixIgnorePattern(line: string, prefix: string): string | null {\n\tconst trimmed = line.trim();\n\tif (!trimmed) return null;\n\tif (trimmed.startsWith(\"#\") && !trimmed.startsWith(\"\\\\#\")) return null;\n\n\tlet pattern = line;\n\tlet negated = false;\n\n\tif (pattern.startsWith(\"!\")) {\n\t\tnegated = true;\n\t\tpattern = pattern.slice(1);\n\t} else if (pattern.startsWith(\"\\\\!\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tif (pattern.startsWith(\"/\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tconst prefixed = prefix ? `${prefix}${pattern}` : pattern;\n\treturn negated ? `!${prefixed}` : prefixed;\n}\n\nfunction addIgnoreRules(ig: IgnoreMatcher, dir: string, rootDir: string): void {\n\tconst relativeDir = relative(rootDir, dir);\n\tconst prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : \"\";\n\n\tfor (const filename of IGNORE_FILE_NAMES) {\n\t\tconst ignorePath = join(dir, filename);\n\t\tif (!existsSync(ignorePath)) continue;\n\t\ttry {\n\t\t\tconst content = readFileSync(ignorePath, \"utf-8\");\n\t\t\tconst patterns = content\n\t\t\t\t.split(/\\r?\\n/)\n\t\t\t\t.map((line) => prefixIgnorePattern(line, prefix))\n\t\t\t\t.filter((line): line is string => Boolean(line));\n\t\t\tif (patterns.length > 0) {\n\t\t\t\tig.add(patterns);\n\t\t\t}\n\t\t} catch {}\n\t}\n}\n\nfunction isPattern(s: string): boolean {\n\treturn s.startsWith(\"!\") || s.startsWith(\"+\") || s.startsWith(\"-\") || s.includes(\"*\") || s.includes(\"?\");\n}\n\nfunction isOverridePattern(s: string): boolean {\n\treturn s.startsWith(\"!\") || s.startsWith(\"+\") || s.startsWith(\"-\");\n}\n\nfunction hasGlobPattern(s: string): boolean {\n\treturn s.includes(\"*\") || s.includes(\"?\");\n}\n\nfunction splitPatterns(entries: string[]): { plain: string[]; patterns: string[] } {\n\tconst plain: string[] = [];\n\tconst patterns: string[] = [];\n\tfor (const entry of entries) {\n\t\tif (isPattern(entry)) {\n\t\t\tpatterns.push(entry);\n\t\t} else {\n\t\t\tplain.push(entry);\n\t\t}\n\t}\n\treturn { plain, patterns };\n}\n\nfunction collectFiles(\n\tdir: string,\n\tfilePattern: RegExp,\n\tskipNodeModules = true,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): string[] {\n\tconst files: string[] = [];\n\tif (!existsSync(dir)) return files;\n\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\taddIgnoreRules(ig, dir, root);\n\n\ttry {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (skipNodeModules && entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDir = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDir = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tconst ignorePath = isDir ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) continue;\n\n\t\t\tif (isDir) {\n\t\t\t\tfiles.push(...collectFiles(fullPath, filePattern, skipNodeModules, ig, root));\n\t\t\t} else if (isFile && filePattern.test(entry.name)) {\n\t\t\t\tfiles.push(fullPath);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn files;\n}\n\ntype SkillDiscoveryMode = \"pi\" | \"agents\";\n\nfunction collectSkillEntries(\n\tdir: string,\n\tmode: SkillDiscoveryMode,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\taddIgnoreRules(ig, dir, root);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name !== \"SKILL.md\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tif (isFile && !ig.ignores(relPath)) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t\treturn entries;\n\t\t\t}\n\t\t}\n\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDir = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDir = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tif (mode === \"pi\" && dir === root && isFile && entry.name.endsWith(\".md\") && !ig.ignores(relPath)) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!isDir) continue;\n\t\t\tif (ig.ignores(`${relPath}/`)) continue;\n\n\t\t\tentries.push(...collectSkillEntries(fullPath, mode, ig, root));\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\nfunction collectAutoSkillEntries(dir: string, mode: SkillDiscoveryMode): string[] {\n\treturn collectSkillEntries(dir, mode);\n}\n\nfunction findGitRepoRoot(startDir: string): string | null {\n\tlet dir = resolve(startDir);\n\twhile (true) {\n\t\tif (existsSync(join(dir, \".git\"))) {\n\t\t\treturn dir;\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) {\n\t\t\treturn null;\n\t\t}\n\t\tdir = parent;\n\t}\n}\n\nfunction collectAncestorAgentsSkillDirs(startDir: string): string[] {\n\tconst skillDirs: string[] = [];\n\tconst resolvedStartDir = resolve(startDir);\n\tconst gitRepoRoot = findGitRepoRoot(resolvedStartDir);\n\n\tlet dir = resolvedStartDir;\n\twhile (true) {\n\t\tskillDirs.push(join(dir, \".agents\", \"skills\"));\n\t\tif (gitRepoRoot && dir === gitRepoRoot) {\n\t\t\tbreak;\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) {\n\t\t\tbreak;\n\t\t}\n\t\tdir = parent;\n\t}\n\n\treturn skillDirs;\n}\n\nfunction collectAutoPromptEntries(dir: string): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\tconst ig = ignore();\n\taddIgnoreRules(ig, dir, dir);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(dir, fullPath));\n\t\t\tif (ig.ignores(relPath)) continue;\n\n\t\t\tif (isFile && entry.name.endsWith(\".md\")) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\nfunction collectAutoThemeEntries(dir: string): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\tconst ig = ignore();\n\taddIgnoreRules(ig, dir, dir);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(dir, fullPath));\n\t\t\tif (ig.ignores(relPath)) continue;\n\n\t\t\tif (isFile && entry.name.endsWith(\".json\")) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\nfunction readPiManifestFile(packageJsonPath: string): PiManifest | null {\n\ttry {\n\t\tconst content = readFileSync(packageJsonPath, \"utf-8\");\n\t\tconst pkg = JSON.parse(content) as { pi?: PiManifest };\n\t\treturn pkg.pi ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction resolveExtensionEntries(dir: string): string[] | null {\n\tconst packageJsonPath = join(dir, \"package.json\");\n\tif (existsSync(packageJsonPath)) {\n\t\tconst manifest = readPiManifestFile(packageJsonPath);\n\t\tif (manifest?.extensions?.length) {\n\t\t\tconst entries: string[] = [];\n\t\t\tfor (const extPath of manifest.extensions) {\n\t\t\t\tconst resolvedExtPath = resolve(dir, extPath);\n\t\t\t\tif (existsSync(resolvedExtPath)) {\n\t\t\t\t\tentries.push(resolvedExtPath);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (entries.length > 0) {\n\t\t\t\treturn entries;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst indexTs = join(dir, \"index.ts\");\n\tconst indexJs = join(dir, \"index.js\");\n\tif (existsSync(indexTs)) {\n\t\treturn [indexTs];\n\t}\n\tif (existsSync(indexJs)) {\n\t\treturn [indexJs];\n\t}\n\n\treturn null;\n}\n\nfunction collectAutoExtensionEntries(dir: string): string[] {\n\tconst entries: string[] = [];\n\tif (!existsSync(dir)) return entries;\n\n\t// First check if this directory itself has explicit extension entries (package.json or index)\n\tconst rootEntries = resolveExtensionEntries(dir);\n\tif (rootEntries) {\n\t\treturn rootEntries;\n\t}\n\n\t// Otherwise, discover extensions from directory contents\n\tconst ig = ignore();\n\taddIgnoreRules(ig, dir, dir);\n\n\ttry {\n\t\tconst dirEntries = readdirSync(dir, { withFileTypes: true });\n\t\tfor (const entry of dirEntries) {\n\t\t\tif (entry.name.startsWith(\".\")) continue;\n\t\t\tif (entry.name === \"node_modules\") continue;\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\t\t\tlet isDir = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDir = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(dir, fullPath));\n\t\t\tconst ignorePath = isDir ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) continue;\n\n\t\t\tif (isFile && (entry.name.endsWith(\".ts\") || entry.name.endsWith(\".js\"))) {\n\t\t\t\tentries.push(fullPath);\n\t\t\t} else if (isDir) {\n\t\t\t\tconst resolvedEntries = resolveExtensionEntries(fullPath);\n\t\t\t\tif (resolvedEntries) {\n\t\t\t\t\tentries.push(...resolvedEntries);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\n\treturn entries;\n}\n\n/**\n * Collect resource files from a directory based on resource type.\n * Extensions use smart discovery (index.ts in subdirs), others use recursive collection.\n */\nfunction collectResourceFiles(dir: string, resourceType: ResourceType): string[] {\n\tif (resourceType === \"skills\") {\n\t\treturn collectSkillEntries(dir, \"pi\");\n\t}\n\tif (resourceType === \"extensions\") {\n\t\treturn collectAutoExtensionEntries(dir);\n\t}\n\treturn collectFiles(dir, FILE_PATTERNS[resourceType]);\n}\n\nfunction matchesAnyPattern(filePath: string, patterns: string[], baseDir: string): boolean {\n\tconst rel = toPosixPath(relative(baseDir, filePath));\n\tconst name = basename(filePath);\n\tconst filePathPosix = toPosixPath(filePath);\n\tconst isSkillFile = name === \"SKILL.md\";\n\tconst parentDir = isSkillFile ? dirname(filePath) : undefined;\n\tconst parentRel = isSkillFile ? toPosixPath(relative(baseDir, parentDir!)) : undefined;\n\tconst parentName = isSkillFile ? basename(parentDir!) : undefined;\n\tconst parentDirPosix = isSkillFile ? toPosixPath(parentDir!) : undefined;\n\n\treturn patterns.some((pattern) => {\n\t\tconst normalizedPattern = toPosixPath(pattern);\n\t\tif (\n\t\t\tminimatch(rel, normalizedPattern) ||\n\t\t\tminimatch(name, normalizedPattern) ||\n\t\t\tminimatch(filePathPosix, normalizedPattern)\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!isSkillFile) return false;\n\t\treturn (\n\t\t\tminimatch(parentRel!, normalizedPattern) ||\n\t\t\tminimatch(parentName!, normalizedPattern) ||\n\t\t\tminimatch(parentDirPosix!, normalizedPattern)\n\t\t);\n\t});\n}\n\nfunction normalizeExactPattern(pattern: string): string {\n\tconst normalized = pattern.startsWith(\"./\") || pattern.startsWith(\".\\\\\") ? pattern.slice(2) : pattern;\n\treturn toPosixPath(normalized);\n}\n\nfunction matchesAnyExactPattern(filePath: string, patterns: string[], baseDir: string): boolean {\n\tif (patterns.length === 0) return false;\n\tconst rel = toPosixPath(relative(baseDir, filePath));\n\tconst name = basename(filePath);\n\tconst filePathPosix = toPosixPath(filePath);\n\tconst isSkillFile = name === \"SKILL.md\";\n\tconst parentDir = isSkillFile ? dirname(filePath) : undefined;\n\tconst parentRel = isSkillFile ? toPosixPath(relative(baseDir, parentDir!)) : undefined;\n\tconst parentDirPosix = isSkillFile ? toPosixPath(parentDir!) : undefined;\n\n\treturn patterns.some((pattern) => {\n\t\tconst normalized = normalizeExactPattern(pattern);\n\t\tif (normalized === rel || normalized === filePathPosix) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!isSkillFile) return false;\n\t\treturn normalized === parentRel || normalized === parentDirPosix;\n\t});\n}\n\nfunction getOverridePatterns(entries: string[]): string[] {\n\treturn entries.filter((pattern) => pattern.startsWith(\"!\") || pattern.startsWith(\"+\") || pattern.startsWith(\"-\"));\n}\n\nfunction isEnabledByOverrides(filePath: string, patterns: string[], baseDir: string): boolean {\n\tconst overrides = getOverridePatterns(patterns);\n\tconst excludes = overrides.filter((pattern) => pattern.startsWith(\"!\")).map((pattern) => pattern.slice(1));\n\tconst forceIncludes = overrides.filter((pattern) => pattern.startsWith(\"+\")).map((pattern) => pattern.slice(1));\n\tconst forceExcludes = overrides.filter((pattern) => pattern.startsWith(\"-\")).map((pattern) => pattern.slice(1));\n\n\tlet enabled = true;\n\tif (excludes.length > 0 && matchesAnyPattern(filePath, excludes, baseDir)) {\n\t\tenabled = false;\n\t}\n\tif (forceIncludes.length > 0 && matchesAnyExactPattern(filePath, forceIncludes, baseDir)) {\n\t\tenabled = true;\n\t}\n\tif (forceExcludes.length > 0 && matchesAnyExactPattern(filePath, forceExcludes, baseDir)) {\n\t\tenabled = false;\n\t}\n\treturn enabled;\n}\n\n/**\n * Apply patterns to paths and return a Set of enabled paths.\n * Pattern types:\n * - Plain patterns: include matching paths\n * - `!pattern`: exclude matching paths\n * - `+path`: force-include exact path (overrides exclusions)\n * - `-path`: force-exclude exact path (overrides force-includes)\n */\nfunction applyPatterns(allPaths: string[], patterns: string[], baseDir: string): Set {\n\tconst includes: string[] = [];\n\tconst excludes: string[] = [];\n\tconst forceIncludes: string[] = [];\n\tconst forceExcludes: string[] = [];\n\n\tfor (const p of patterns) {\n\t\tif (p.startsWith(\"+\")) {\n\t\t\tforceIncludes.push(p.slice(1));\n\t\t} else if (p.startsWith(\"-\")) {\n\t\t\tforceExcludes.push(p.slice(1));\n\t\t} else if (p.startsWith(\"!\")) {\n\t\t\texcludes.push(p.slice(1));\n\t\t} else {\n\t\t\tincludes.push(p);\n\t\t}\n\t}\n\n\t// Step 1: Apply includes (or all if no includes)\n\tlet result: string[];\n\tif (includes.length === 0) {\n\t\tresult = [...allPaths];\n\t} else {\n\t\tresult = allPaths.filter((filePath) => matchesAnyPattern(filePath, includes, baseDir));\n\t}\n\n\t// Step 2: Apply excludes\n\tif (excludes.length > 0) {\n\t\tresult = result.filter((filePath) => !matchesAnyPattern(filePath, excludes, baseDir));\n\t}\n\n\t// Step 3: Force-include (add back from allPaths, overriding exclusions)\n\tif (forceIncludes.length > 0) {\n\t\tfor (const filePath of allPaths) {\n\t\t\tif (!result.includes(filePath) && matchesAnyExactPattern(filePath, forceIncludes, baseDir)) {\n\t\t\t\tresult.push(filePath);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Step 4: Force-exclude (remove even if included or force-included)\n\tif (forceExcludes.length > 0) {\n\t\tresult = result.filter((filePath) => !matchesAnyExactPattern(filePath, forceExcludes, baseDir));\n\t}\n\n\treturn new Set(result);\n}\n\nfunction applyAutoloadDisabledPatterns(allPaths: string[], patterns: string[], baseDir: string): Map {\n\tconst result = new Map();\n\tfor (const pattern of patterns) {\n\t\tconst target = pattern.slice(\n\t\t\tpattern.startsWith(\"+\") || pattern.startsWith(\"-\") || pattern.startsWith(\"!\") ? 1 : 0,\n\t\t);\n\t\tconst enabled = !pattern.startsWith(\"-\") && !pattern.startsWith(\"!\");\n\t\tconst exact = pattern.startsWith(\"+\") || pattern.startsWith(\"-\");\n\t\tfor (const filePath of allPaths) {\n\t\t\tif (\n\t\t\t\texact ? matchesAnyExactPattern(filePath, [target], baseDir) : matchesAnyPattern(filePath, [target], baseDir)\n\t\t\t) {\n\t\t\t\tresult.set(filePath, enabled);\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nexport class DefaultPackageManager implements PackageManager {\n\tprivate cwd: string;\n\tprivate agentDir: string;\n\tprivate settingsManager: SettingsManager;\n\tprivate globalNpmRoot: string | undefined;\n\tprivate globalNpmRootCommandKey: string | undefined;\n\tprivate progressCallback: ProgressCallback | undefined;\n\n\tconstructor(options: PackageManagerOptions) {\n\t\tthis.cwd = resolvePath(options.cwd);\n\t\tthis.agentDir = resolvePath(options.agentDir);\n\t\tthis.settingsManager = options.settingsManager;\n\t}\n\n\tsetProgressCallback(callback: ProgressCallback | undefined): void {\n\t\tthis.progressCallback = callback;\n\t}\n\n\taddSourceToSettings(source: string, options?: { local?: boolean }): boolean {\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tconst currentSettings =\n\t\t\tscope === \"project\" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings();\n\t\tconst currentPackages = currentSettings.packages ?? [];\n\t\tconst normalizedSource = this.normalizePackageSourceForSettings(source, scope);\n\t\tconst matchIndex = currentPackages.findIndex((existing) => this.packageSourcesMatch(existing, source, scope));\n\t\tif (matchIndex !== -1) {\n\t\t\tconst existing = currentPackages[matchIndex];\n\t\t\tif (this.getPackageSourceString(existing) === normalizedSource) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst nextPackages = [...currentPackages];\n\t\t\tnextPackages[matchIndex] =\n\t\t\t\ttypeof existing === \"string\" ? normalizedSource : { ...existing, source: normalizedSource };\n\t\t\tif (scope === \"project\") {\n\t\t\t\tthis.settingsManager.setProjectPackages(nextPackages);\n\t\t\t} else {\n\t\t\t\tthis.settingsManager.setPackages(nextPackages);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tconst nextPackages = [...currentPackages, normalizedSource];\n\t\tif (scope === \"project\") {\n\t\t\tthis.settingsManager.setProjectPackages(nextPackages);\n\t\t} else {\n\t\t\tthis.settingsManager.setPackages(nextPackages);\n\t\t}\n\t\treturn true;\n\t}\n\n\tremoveSourceFromSettings(source: string, options?: { local?: boolean }): boolean {\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tconst currentSettings =\n\t\t\tscope === \"project\" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings();\n\t\tconst currentPackages = currentSettings.packages ?? [];\n\t\tconst nextPackages = currentPackages.filter((existing) => !this.packageSourcesMatch(existing, source, scope));\n\t\tconst changed = nextPackages.length !== currentPackages.length;\n\t\tif (!changed) {\n\t\t\treturn false;\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\tthis.settingsManager.setProjectPackages(nextPackages);\n\t\t} else {\n\t\t\tthis.settingsManager.setPackages(nextPackages);\n\t\t}\n\t\treturn true;\n\t}\n\n\tgetInstalledPath(source: string, scope: \"user\" | \"project\"): string | undefined {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\tconst path = this.getNpmInstallPath(parsed, scope);\n\t\t\treturn existsSync(path) ? path : undefined;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\tconst path = this.getGitInstallPath(parsed, scope);\n\t\t\treturn existsSync(path) ? path : undefined;\n\t\t}\n\t\tif (parsed.type === \"local\") {\n\t\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\t\tconst path = this.resolvePathFromBase(parsed.path, baseDir);\n\t\t\treturn existsSync(path) ? path : undefined;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate emitProgress(event: ProgressEvent): void {\n\t\tthis.progressCallback?.(event);\n\t}\n\n\tprivate async withProgress(\n\t\taction: ProgressEvent[\"action\"],\n\t\tsource: string,\n\t\tmessage: string,\n\t\toperation: () => Promise,\n\t): Promise {\n\t\tthis.emitProgress({ type: \"start\", action, source, message });\n\t\ttry {\n\t\t\tawait operation();\n\t\t\tthis.emitProgress({ type: \"complete\", action, source });\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tthis.emitProgress({ type: \"error\", action, source, message: errorMessage });\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync resolve(onMissing?: (source: string) => Promise): Promise {\n\t\tconst accumulator = this.createAccumulator();\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\n\t\t// Collect all packages with scope (project first so cwd resources win collisions)\n\t\tconst allPackages: Array<{ pkg: PackageSource; scope: SourceScope }> = [];\n\t\tfor (const pkg of projectSettings.packages ?? []) {\n\t\t\tallPackages.push({ pkg, scope: \"project\" });\n\t\t}\n\t\tfor (const pkg of globalSettings.packages ?? []) {\n\t\t\tallPackages.push({ pkg, scope: \"user\" });\n\t\t}\n\n\t\t// Dedupe: project scope wins over global for same package identity\n\t\tconst packageSources = this.dedupePackages(allPackages);\n\t\tawait this.resolvePackageSources(packageSources, accumulator, onMissing);\n\n\t\tconst globalBaseDir = this.agentDir;\n\t\tconst projectBaseDir = join(this.cwd, CONFIG_DIR_NAME);\n\n\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\tconst target = this.getTargetMap(accumulator, resourceType);\n\t\t\tconst globalEntries = (globalSettings[resourceType] ?? []) as string[];\n\t\t\tconst projectEntries = (projectSettings[resourceType] ?? []) as string[];\n\t\t\tthis.resolveLocalEntries(\n\t\t\t\tprojectEntries,\n\t\t\t\tresourceType,\n\t\t\t\ttarget,\n\t\t\t\t{\n\t\t\t\t\tsource: \"local\",\n\t\t\t\t\tscope: \"project\",\n\t\t\t\t\torigin: \"top-level\",\n\t\t\t\t},\n\t\t\t\tprojectBaseDir,\n\t\t\t);\n\t\t\tthis.resolveLocalEntries(\n\t\t\t\tglobalEntries,\n\t\t\t\tresourceType,\n\t\t\t\ttarget,\n\t\t\t\t{\n\t\t\t\t\tsource: \"local\",\n\t\t\t\t\tscope: \"user\",\n\t\t\t\t\torigin: \"top-level\",\n\t\t\t\t},\n\t\t\t\tglobalBaseDir,\n\t\t\t);\n\t\t}\n\n\t\tthis.addAutoDiscoveredResources(accumulator, globalSettings, projectSettings, globalBaseDir, projectBaseDir);\n\n\t\treturn this.toResolvedPaths(accumulator);\n\t}\n\n\tasync resolveExtensionSources(\n\t\tsources: string[],\n\t\toptions?: { local?: boolean; temporary?: boolean },\n\t): Promise {\n\t\tconst accumulator = this.createAccumulator();\n\t\tconst scope: SourceScope = options?.temporary ? \"temporary\" : options?.local ? \"project\" : \"user\";\n\t\tconst packageSources = sources.map((source) => ({ pkg: source as PackageSource, scope }));\n\t\tawait this.resolvePackageSources(packageSources, accumulator);\n\t\treturn this.toResolvedPaths(accumulator);\n\t}\n\n\tlistConfiguredPackages(): ConfiguredPackage[] {\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\t\tconst configuredPackages: ConfiguredPackage[] = [];\n\n\t\tfor (const pkg of globalSettings.packages ?? []) {\n\t\t\tconst source = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tconfiguredPackages.push({\n\t\t\t\tsource,\n\t\t\t\tscope: \"user\",\n\t\t\t\tfiltered: typeof pkg === \"object\",\n\t\t\t\tinstalledPath: this.getInstalledPath(source, \"user\"),\n\t\t\t});\n\t\t}\n\n\t\tfor (const pkg of projectSettings.packages ?? []) {\n\t\t\tconst source = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tconfiguredPackages.push({\n\t\t\t\tsource,\n\t\t\t\tscope: \"project\",\n\t\t\t\tfiltered: typeof pkg === \"object\",\n\t\t\t\tinstalledPath: this.getInstalledPath(source, \"project\"),\n\t\t\t});\n\t\t}\n\n\t\treturn configuredPackages;\n\t}\n\n\tasync install(source: string, options?: { local?: boolean }): Promise {\n\t\tconst parsed = this.parseSource(source);\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tthis.assertProjectTrustedForScope(scope);\n\t\tawait this.withProgress(\"install\", source, `Installing ${source}...`, async () => {\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tawait this.installNpm(parsed, scope, false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tawait this.installGit(parsed, scope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"local\") {\n\t\t\t\tconst resolved = this.resolvePath(parsed.path);\n\t\t\t\tif (!existsSync(resolved)) {\n\t\t\t\t\tthrow new Error(`Path does not exist: ${resolved}`);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported install source: ${source}`);\n\t\t});\n\t}\n\n\tasync installAndPersist(source: string, options?: { local?: boolean }): Promise {\n\t\tawait this.install(source, options);\n\t\tthis.addSourceToSettings(source, options);\n\t}\n\n\tasync remove(source: string, options?: { local?: boolean }): Promise {\n\t\tconst parsed = this.parseSource(source);\n\t\tconst scope: SourceScope = options?.local ? \"project\" : \"user\";\n\t\tthis.assertProjectTrustedForScope(scope);\n\t\tawait this.withProgress(\"remove\", source, `Removing ${source}...`, async () => {\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tawait this.uninstallNpm(parsed, scope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tawait this.removeGit(parsed, scope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"local\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported remove source: ${source}`);\n\t\t});\n\t}\n\n\tasync removeAndPersist(source: string, options?: { local?: boolean }): Promise {\n\t\tawait this.remove(source, options);\n\t\treturn this.removeSourceFromSettings(source, options);\n\t}\n\n\tasync update(source?: string): Promise {\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\t\tconst identity = source ? this.getPackageIdentity(source) : undefined;\n\t\tlet matched = false;\n\t\tconst updateSources: ConfiguredUpdateSource[] = [];\n\n\t\tfor (const pkg of globalSettings.packages ?? []) {\n\t\t\tconst sourceStr = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tif (identity && this.getPackageIdentity(sourceStr, \"user\") !== identity) continue;\n\t\t\tmatched = true;\n\t\t\tupdateSources.push({ source: sourceStr, scope: \"user\" });\n\t\t}\n\t\tfor (const pkg of projectSettings.packages ?? []) {\n\t\t\tconst sourceStr = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tif (identity && this.getPackageIdentity(sourceStr, \"project\") !== identity) continue;\n\t\t\tmatched = true;\n\t\t\tupdateSources.push({ source: sourceStr, scope: \"project\" });\n\t\t}\n\n\t\tif (source && !matched) {\n\t\t\tthrow new Error(\n\t\t\t\tthis.buildNoMatchingPackageMessage(source, [\n\t\t\t\t\t...(globalSettings.packages ?? []),\n\t\t\t\t\t...(projectSettings.packages ?? []),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tawait this.updateConfiguredSources(updateSources);\n\t}\n\n\tprivate async updateConfiguredSources(sources: ConfiguredUpdateSource[]): Promise {\n\t\tif (isOfflineModeEnabled() || sources.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst npmCandidates: NpmUpdateTarget[] = [];\n\t\tconst gitCandidates: GitUpdateTarget[] = [];\n\n\t\tfor (const entry of sources) {\n\t\t\tconst parsed = this.parseSource(entry.source);\n\t\t\t// Pinned npm versions are fixed. Pinned git refs are configured checkout targets,\n\t\t\t// so include them to reconcile an existing clone when the configured ref changes.\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tif (!parsed.pinned) {\n\t\t\t\t\tnpmCandidates.push({ ...entry, parsed });\n\t\t\t\t}\n\t\t\t} else if (parsed.type === \"git\") {\n\t\t\t\tgitCandidates.push({ ...entry, parsed });\n\t\t\t}\n\t\t}\n\n\t\tconst npmCheckTasks = npmCandidates.map((entry) => async () => ({\n\t\t\tentry,\n\t\t\tshouldUpdate: await this.shouldUpdateNpmSource(entry.parsed, entry.scope),\n\t\t}));\n\t\tconst npmCheckResults = await this.runWithConcurrency(npmCheckTasks, UPDATE_CHECK_CONCURRENCY);\n\t\tconst userNpmUpdates: NpmUpdateTarget[] = [];\n\t\tconst projectNpmUpdates: NpmUpdateTarget[] = [];\n\t\tfor (const result of npmCheckResults) {\n\t\t\tif (!result.shouldUpdate) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (result.entry.scope === \"user\") {\n\t\t\t\tuserNpmUpdates.push(result.entry);\n\t\t\t} else {\n\t\t\t\tprojectNpmUpdates.push(result.entry);\n\t\t\t}\n\t\t}\n\n\t\tconst tasks: Promise[] = [];\n\t\tif (userNpmUpdates.length > 0) {\n\t\t\ttasks.push(this.updateNpmBatch(userNpmUpdates, \"user\"));\n\t\t}\n\t\tif (projectNpmUpdates.length > 0) {\n\t\t\ttasks.push(this.updateNpmBatch(projectNpmUpdates, \"project\"));\n\t\t}\n\t\tif (gitCandidates.length > 0) {\n\t\t\tconst gitTasks = gitCandidates.map(\n\t\t\t\t(entry) => async () =>\n\t\t\t\t\tthis.withProgress(\"update\", entry.source, `Updating ${entry.source}...`, async () => {\n\t\t\t\t\t\tawait this.updateGit(entry.parsed, entry.scope);\n\t\t\t\t\t}),\n\t\t\t);\n\t\t\ttasks.push(this.runWithConcurrency(gitTasks, GIT_UPDATE_CONCURRENCY).then(() => {}));\n\t\t}\n\n\t\tawait Promise.all(tasks);\n\t}\n\n\tprivate async shouldUpdateNpmSource(source: NpmSource, scope: InstalledSourceScope): Promise {\n\t\tconst installedPath = this.getManagedNpmInstallPath(source, scope);\n\t\tconst installedVersion = existsSync(installedPath) ? this.getInstalledNpmVersion(installedPath) : undefined;\n\t\tif (!installedVersion) {\n\t\t\treturn true;\n\t\t}\n\n\t\ttry {\n\t\t\tconst targetVersion = await this.getLatestNpmVersion(source.version ? source.spec : source.name, source.range);\n\t\t\treturn targetVersion !== installedVersion;\n\t\t} catch {\n\t\t\t// Preserve existing update behavior when version lookup fails.\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tprivate async updateNpmBatch(sources: NpmUpdateTarget[], scope: InstalledSourceScope): Promise {\n\t\tif (sources.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst sourceLabel = sources.length === 1 ? sources[0].source : `${scope} npm packages`;\n\t\tconst message = sources.length === 1 ? `Updating ${sources[0].source}...` : `Updating ${scope} npm packages...`;\n\t\tconst specs = sources.map((entry) => (entry.parsed.version ? entry.parsed.spec : `${entry.parsed.name}@latest`));\n\n\t\tawait this.withProgress(\"update\", sourceLabel, message, async () => {\n\t\t\tawait this.installNpmBatch(specs, scope);\n\t\t});\n\t}\n\n\tprivate async installNpmBatch(specs: string[], scope: InstalledSourceScope): Promise {\n\t\tconst installRoot = this.getNpmInstallRoot(scope, false);\n\t\tthis.ensureNpmProject(installRoot);\n\t\tawait this.runNpmCommand(this.getNpmInstallArgs(specs, installRoot));\n\t}\n\n\tasync checkForAvailableUpdates(): Promise {\n\t\tif (isOfflineModeEnabled()) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst globalSettings = this.settingsManager.getGlobalSettings();\n\t\tconst projectSettings = this.settingsManager.getProjectSettings();\n\t\tconst allPackages: Array<{ pkg: PackageSource; scope: SourceScope }> = [];\n\t\tfor (const pkg of projectSettings.packages ?? []) {\n\t\t\tallPackages.push({ pkg, scope: \"project\" });\n\t\t}\n\t\tfor (const pkg of globalSettings.packages ?? []) {\n\t\t\tallPackages.push({ pkg, scope: \"user\" });\n\t\t}\n\n\t\tconst packageSources = this.dedupePackages(allPackages);\n\t\tconst checks = packageSources\n\t\t\t.filter(\n\t\t\t\t(entry): entry is { pkg: PackageSource; scope: Exclude } =>\n\t\t\t\t\tentry.scope !== \"temporary\",\n\t\t\t)\n\t\t\t.map((entry) => async (): Promise => {\n\t\t\t\tconst source = typeof entry.pkg === \"string\" ? entry.pkg : entry.pkg.source;\n\t\t\t\tconst parsed = this.parseSource(source);\n\t\t\t\tif (parsed.type === \"local\" || parsed.pinned) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\t\tconst installedPath = this.getNpmInstallPath(parsed, entry.scope);\n\t\t\t\t\tif (!existsSync(installedPath)) {\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\tconst hasUpdate = await this.npmHasAvailableUpdate(parsed, installedPath);\n\t\t\t\t\tif (!hasUpdate) {\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tdisplayName: parsed.name,\n\t\t\t\t\t\ttype: \"npm\",\n\t\t\t\t\t\tscope: entry.scope,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tconst installedPath = this.getGitInstallPath(parsed, entry.scope);\n\t\t\t\tif (!existsSync(installedPath)) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\tconst hasUpdate = await this.gitHasAvailableUpdate(installedPath);\n\t\t\t\tif (!hasUpdate) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tsource,\n\t\t\t\t\tdisplayName: `${parsed.host}/${parsed.path}`,\n\t\t\t\t\ttype: \"git\",\n\t\t\t\t\tscope: entry.scope,\n\t\t\t\t};\n\t\t\t});\n\n\t\tconst results = await this.runWithConcurrency(checks, UPDATE_CHECK_CONCURRENCY);\n\t\treturn results.filter((result): result is PackageUpdate => result !== undefined);\n\t}\n\n\tprivate async resolvePackageSources(\n\t\tsources: Array<{ pkg: PackageSource; scope: SourceScope }>,\n\t\taccumulator: ResourceAccumulator,\n\t\tonMissing?: (source: string) => Promise,\n\t): Promise {\n\t\tfor (const { pkg, scope } of sources) {\n\t\t\tconst sourceStr = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\tconst filter = typeof pkg === \"object\" ? pkg : undefined;\n\t\t\tconst deltaBase = this.findAutoloadDeltaBase(pkg, scope, sources);\n\t\t\tconst resolvedSource = deltaBase?.source ?? sourceStr;\n\t\t\tconst resolvedScope = deltaBase?.scope ?? scope;\n\t\t\tconst parsed = this.parseSource(resolvedSource);\n\t\t\tconst metadata: PathMetadata = { source: sourceStr, scope, origin: \"package\" };\n\n\t\t\tif (parsed.type === \"local\") {\n\t\t\t\tconst baseDir = this.getBaseDirForScope(resolvedScope);\n\t\t\t\tthis.resolveLocalExtensionSource(parsed, accumulator, filter, metadata, baseDir);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst installMissing = async (): Promise => {\n\t\t\t\tif (isOfflineModeEnabled()) return false;\n\t\t\t\tif (!onMissing) {\n\t\t\t\t\tawait this.installParsedSource(parsed, resolvedScope);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tconst action = await onMissing(resolvedSource);\n\t\t\t\tif (action === \"skip\") return false;\n\t\t\t\tif (action === \"error\") throw new Error(`Missing source: ${resolvedSource}`);\n\t\t\t\tawait this.installParsedSource(parsed, resolvedScope);\n\t\t\t\treturn true;\n\t\t\t};\n\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tlet installedPath = this.getNpmInstallPath(parsed, resolvedScope);\n\t\t\t\tconst needsInstall =\n\t\t\t\t\t!existsSync(installedPath) || !(await this.installedNpmMatchesConfiguredVersion(parsed, installedPath));\n\t\t\t\tif (needsInstall) {\n\t\t\t\t\tconst installed = await installMissing();\n\t\t\t\t\tif (!installed) continue;\n\t\t\t\t\tinstalledPath = this.getNpmInstallPath(parsed, resolvedScope);\n\t\t\t\t}\n\t\t\t\tmetadata.baseDir = installedPath;\n\t\t\t\tthis.collectPackageResources(installedPath, accumulator, filter, metadata);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tconst installedPath = this.getGitInstallPath(parsed, resolvedScope);\n\t\t\t\tif (!existsSync(installedPath)) {\n\t\t\t\t\tconst installed = await installMissing();\n\t\t\t\t\tif (!installed) continue;\n\t\t\t\t} else if (resolvedScope === \"temporary\" && !parsed.pinned && !isOfflineModeEnabled()) {\n\t\t\t\t\tawait this.refreshTemporaryGitSource(parsed, resolvedSource);\n\t\t\t\t}\n\t\t\t\tmetadata.baseDir = installedPath;\n\t\t\t\tthis.collectPackageResources(installedPath, accumulator, filter, metadata);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate findAutoloadDeltaBase(\n\t\tpkg: PackageSource,\n\t\tscope: SourceScope,\n\t\tsources: Array<{ pkg: PackageSource; scope: SourceScope }>,\n\t): { source: string; scope: SourceScope } | undefined {\n\t\tif (scope !== \"project\" || typeof pkg !== \"object\" || pkg.autoload !== false) return undefined;\n\t\tconst identity = this.getPackageIdentity(pkg.source, scope);\n\t\tconst userEntry = sources.find(\n\t\t\t(entry) =>\n\t\t\t\tentry.scope === \"user\" &&\n\t\t\t\tthis.getPackageIdentity(this.getPackageSourceString(entry.pkg), \"user\") === identity,\n\t\t);\n\t\treturn userEntry ? { source: this.getPackageSourceString(userEntry.pkg), scope: \"user\" } : undefined;\n\t}\n\n\tprivate resolveLocalExtensionSource(\n\t\tsource: LocalSource,\n\t\taccumulator: ResourceAccumulator,\n\t\tfilter: PackageFilter | undefined,\n\t\tmetadata: PathMetadata,\n\t\tbaseDir: string,\n\t): void {\n\t\tconst resolved = this.resolvePathFromBase(source.path, baseDir);\n\t\tif (!existsSync(resolved)) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stats = statSync(resolved);\n\t\t\tif (stats.isFile()) {\n\t\t\t\tmetadata.baseDir = dirname(resolved);\n\t\t\t\tthis.addResource(accumulator.extensions, resolved, metadata, true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\tmetadata.baseDir = resolved;\n\t\t\t\tconst resources = this.collectPackageResources(resolved, accumulator, filter, metadata);\n\t\t\t\tif (!resources) {\n\t\t\t\t\tthis.addResource(accumulator.extensions, resolved, metadata, true);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprivate async installParsedSource(parsed: ParsedSource, scope: SourceScope): Promise {\n\t\tif (parsed.type === \"npm\") {\n\t\t\tawait this.installNpm(parsed, scope, scope === \"temporary\");\n\t\t\treturn;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\tawait this.installGit(parsed, scope);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprivate getPackageSourceString(pkg: PackageSource): string {\n\t\treturn typeof pkg === \"string\" ? pkg : pkg.source;\n\t}\n\n\tprivate getSourceMatchKeyForInput(source: string): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\treturn `npm:${parsed.name}`;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\treturn `git:${parsed.host}/${parsed.path}`;\n\t\t}\n\t\treturn `local:${this.resolvePath(parsed.path)}`;\n\t}\n\n\tprivate getSourceMatchKeyForSettings(source: string, scope: SourceScope): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\treturn `npm:${parsed.name}`;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\treturn `git:${parsed.host}/${parsed.path}`;\n\t\t}\n\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\treturn `local:${this.resolvePathFromBase(parsed.path, baseDir)}`;\n\t}\n\n\tprivate buildNoMatchingPackageMessage(source: string, configuredPackages: PackageSource[]): string {\n\t\tconst suggestion = this.findSuggestedConfiguredSource(source, configuredPackages);\n\t\tif (!suggestion) {\n\t\t\treturn `No matching package found for ${source}`;\n\t\t}\n\t\treturn `No matching package found for ${source}. Did you mean ${suggestion}?`;\n\t}\n\n\tprivate findSuggestedConfiguredSource(source: string, configuredPackages: PackageSource[]): string | undefined {\n\t\tconst trimmedSource = source.trim();\n\t\tconst suggestions = new Set();\n\n\t\tfor (const pkg of configuredPackages) {\n\t\t\tconst sourceStr = this.getPackageSourceString(pkg);\n\t\t\tconst parsed = this.parseSource(sourceStr);\n\t\t\tif (parsed.type === \"npm\") {\n\t\t\t\tif (trimmedSource === parsed.name || trimmedSource === parsed.spec) {\n\t\t\t\t\tsuggestions.add(sourceStr);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (parsed.type === \"git\") {\n\t\t\t\tconst shorthand = `${parsed.host}/${parsed.path}`;\n\t\t\t\tconst shorthandWithRef = parsed.ref ? `${shorthand}@${parsed.ref}` : undefined;\n\t\t\t\tif (trimmedSource === shorthand || (shorthandWithRef && trimmedSource === shorthandWithRef)) {\n\t\t\t\t\tsuggestions.add(sourceStr);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn suggestions.values().next().value;\n\t}\n\n\tprivate packageSourcesMatch(existing: PackageSource, inputSource: string, scope: SourceScope): boolean {\n\t\tconst left = this.getSourceMatchKeyForSettings(this.getPackageSourceString(existing), scope);\n\t\tconst right = this.getSourceMatchKeyForInput(inputSource);\n\t\treturn left === right;\n\t}\n\n\tprivate normalizePackageSourceForSettings(source: string, scope: SourceScope): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type !== \"local\") {\n\t\t\treturn source;\n\t\t}\n\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\tconst resolved = this.resolvePath(parsed.path);\n\t\tconst rel = relative(baseDir, resolved);\n\t\treturn rel || \".\";\n\t}\n\n\tprivate parseSource(source: string): ParsedSource {\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\tconst spec = source.slice(\"npm:\".length).trim();\n\t\t\tconst { name, version } = this.parseNpmSpec(spec);\n\t\t\treturn {\n\t\t\t\ttype: \"npm\",\n\t\t\t\tspec,\n\t\t\t\tname,\n\t\t\t\tversion,\n\t\t\t\trange: getNpmVersionRange(version),\n\t\t\t\tpinned: isExactNpmVersion(version),\n\t\t\t};\n\t\t}\n\n\t\tif (isLocalPath(source)) {\n\t\t\treturn { type: \"local\", path: source };\n\t\t}\n\n\t\t// Try parsing as git URL\n\t\tconst gitParsed = parseGitUrl(source);\n\t\tif (gitParsed) {\n\t\t\treturn gitParsed;\n\t\t}\n\n\t\treturn { type: \"local\", path: source };\n\t}\n\n\tprivate async installedNpmMatchesConfiguredVersion(source: NpmSource, installedPath: string): Promise {\n\t\tconst installedVersion = this.getInstalledNpmVersion(installedPath);\n\t\tif (!installedVersion) {\n\t\t\treturn false;\n\t\t}\n\t\treturn source.range ? satisfies(installedVersion, source.range) : true;\n\t}\n\n\tprivate async npmHasAvailableUpdate(source: NpmSource, installedPath: string): Promise {\n\t\tif (isOfflineModeEnabled()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst installedVersion = this.getInstalledNpmVersion(installedPath);\n\t\tif (!installedVersion) {\n\t\t\treturn false;\n\t\t}\n\n\t\ttry {\n\t\t\tconst targetVersion = await this.getLatestNpmVersion(source.version ? source.spec : source.name, source.range);\n\t\t\treturn targetVersion !== installedVersion;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate getInstalledNpmVersion(installedPath: string): string | undefined {\n\t\tconst packageJsonPath = join(installedPath, \"package.json\");\n\t\tif (!existsSync(packageJsonPath)) return undefined;\n\t\ttry {\n\t\t\tconst content = readFileSync(packageJsonPath, \"utf-8\");\n\t\t\tconst pkg = JSON.parse(content) as { version?: string };\n\t\t\treturn pkg.version;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate async getLatestNpmVersion(packageSpec: string, range?: string): Promise {\n\t\tconst npmCommand = this.getNpmCommand();\n\t\tconst stdout = await this.runCommandCapture(\n\t\t\tnpmCommand.command,\n\t\t\t[...npmCommand.args, \"view\", packageSpec, \"version\", \"--json\"],\n\t\t\t{ cwd: this.cwd, timeoutMs: NETWORK_TIMEOUT_MS },\n\t\t);\n\t\tconst raw = stdout.trim();\n\t\tif (!raw) throw new Error(\"Empty response from npm view\");\n\t\tconst parsed = JSON.parse(raw) as unknown;\n\t\tif (typeof parsed === \"string\") {\n\t\t\treturn parsed;\n\t\t}\n\t\tif (Array.isArray(parsed)) {\n\t\t\tconst versions = parsed.filter((value): value is string => typeof value === \"string\" && value.length > 0);\n\t\t\tconst latest = range ? maxSatisfying(versions, range) : [...versions].sort(rcompare)[0];\n\t\t\tif (latest) return latest;\n\t\t}\n\t\tthrow new Error(\"Unexpected response from npm view\");\n\t}\n\n\tprivate async gitHasAvailableUpdate(installedPath: string): Promise {\n\t\tif (isOfflineModeEnabled()) {\n\t\t\treturn false;\n\t\t}\n\n\t\ttry {\n\t\t\tconst localHead = await this.runCommandCapture(\"git\", [\"rev-parse\", \"HEAD\"], {\n\t\t\t\tcwd: installedPath,\n\t\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\t});\n\t\t\tconst remoteHead = await this.getRemoteGitHead(installedPath);\n\t\t\treturn localHead.trim() !== remoteHead.trim();\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate async getRemoteGitHead(installedPath: string): Promise {\n\t\tconst upstreamRef = await this.getGitUpstreamRef(installedPath);\n\t\tif (upstreamRef) {\n\t\t\tconst remoteHead = await this.runGitRemoteCommand(installedPath, [\"ls-remote\", \"origin\", upstreamRef]);\n\t\t\tconst match = remoteHead.match(/^([0-9a-f]{40})\\s+/m);\n\t\t\tif (match?.[1]) {\n\t\t\t\treturn match[1];\n\t\t\t}\n\t\t}\n\n\t\tconst remoteHead = await this.runGitRemoteCommand(installedPath, [\"ls-remote\", \"origin\", \"HEAD\"]);\n\t\tconst match = remoteHead.match(/^([0-9a-f]{40})\\s+HEAD$/m);\n\t\tif (!match?.[1]) {\n\t\t\tthrow new Error(\"Failed to determine remote HEAD\");\n\t\t}\n\t\treturn match[1];\n\t}\n\n\tprivate async getLocalGitUpdateTarget(\n\t\tinstalledPath: string,\n\t): Promise<{ ref: string; head: string; fetchArgs: string[] }> {\n\t\ttry {\n\t\t\tconst upstream = await this.runCommandCapture(\"git\", [\"rev-parse\", \"--abbrev-ref\", \"@{upstream}\"], {\n\t\t\t\tcwd: installedPath,\n\t\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\t});\n\t\t\tconst trimmedUpstream = upstream.trim();\n\t\t\tif (!trimmedUpstream.startsWith(\"origin/\")) {\n\t\t\t\tthrow new Error(`Unsupported upstream remote: ${trimmedUpstream}`);\n\t\t\t}\n\t\t\tconst branch = trimmedUpstream.slice(\"origin/\".length);\n\t\t\tif (!branch) {\n\t\t\t\tthrow new Error(\"Missing upstream branch name\");\n\t\t\t}\n\t\t\tconst head = await this.runCommandCapture(\"git\", [\"rev-parse\", \"@{upstream}\"], {\n\t\t\t\tcwd: installedPath,\n\t\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tref: \"@{upstream}\",\n\t\t\t\thead,\n\t\t\t\tfetchArgs: [\n\t\t\t\t\t\"fetch\",\n\t\t\t\t\t\"--prune\",\n\t\t\t\t\t\"--no-tags\",\n\t\t\t\t\t\"origin\",\n\t\t\t\t\t`+refs/heads/${branch}:refs/remotes/origin/${branch}`,\n\t\t\t\t],\n\t\t\t};\n\t\t} catch {\n\t\t\tawait this.runCommand(\"git\", [\"remote\", \"set-head\", \"origin\", \"-a\"], { cwd: installedPath }).catch(() => {});\n\t\t\tconst head = await this.runCommandCapture(\"git\", [\"rev-parse\", \"origin/HEAD\"], {\n\t\t\t\tcwd: installedPath,\n\t\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\t});\n\t\t\tconst originHeadRef = await this.runCommandCapture(\"git\", [\"symbolic-ref\", \"refs/remotes/origin/HEAD\"], {\n\t\t\t\tcwd: installedPath,\n\t\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\t}).catch(() => \"\");\n\t\t\tconst branch = originHeadRef.trim().replace(/^refs\\/remotes\\/origin\\//, \"\");\n\t\t\tif (branch) {\n\t\t\t\treturn {\n\t\t\t\t\tref: \"origin/HEAD\",\n\t\t\t\t\thead,\n\t\t\t\t\tfetchArgs: [\n\t\t\t\t\t\t\"fetch\",\n\t\t\t\t\t\t\"--prune\",\n\t\t\t\t\t\t\"--no-tags\",\n\t\t\t\t\t\t\"origin\",\n\t\t\t\t\t\t`+refs/heads/${branch}:refs/remotes/origin/${branch}`,\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tref: \"origin/HEAD\",\n\t\t\t\thead,\n\t\t\t\tfetchArgs: [\"fetch\", \"--prune\", \"--no-tags\", \"origin\", \"+HEAD:refs/remotes/origin/HEAD\"],\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate async getGitUpstreamRef(installedPath: string): Promise {\n\t\ttry {\n\t\t\tconst upstream = await this.runCommandCapture(\"git\", [\"rev-parse\", \"--abbrev-ref\", \"@{upstream}\"], {\n\t\t\t\tcwd: installedPath,\n\t\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\t});\n\t\t\tconst trimmed = upstream.trim();\n\t\t\tif (!trimmed.startsWith(\"origin/\")) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst branch = trimmed.slice(\"origin/\".length);\n\t\t\treturn branch ? `refs/heads/${branch}` : undefined;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate runGitRemoteCommand(installedPath: string, args: string[]): Promise {\n\t\treturn this.runCommandCapture(\"git\", args, {\n\t\t\tcwd: installedPath,\n\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t\tenv: {\n\t\t\t\tGIT_TERMINAL_PROMPT: \"0\",\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate async runWithConcurrency(tasks: Array<() => Promise>, limit: number): Promise {\n\t\tif (tasks.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst results: T[] = new Array(tasks.length);\n\t\tlet nextIndex = 0;\n\t\tconst workerCount = Math.max(1, Math.min(limit, tasks.length));\n\n\t\tconst worker = async () => {\n\t\t\twhile (true) {\n\t\t\t\tconst index = nextIndex;\n\t\t\t\tnextIndex += 1;\n\t\t\t\tif (index >= tasks.length) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tresults[index] = await tasks[index]();\n\t\t\t}\n\t\t};\n\n\t\tawait Promise.all(Array.from({ length: workerCount }, () => worker()));\n\t\treturn results;\n\t}\n\n\t/**\n\t * Get a unique identity for a package, ignoring version/ref.\n\t * Used to detect when the same package is in both global and project settings.\n\t * For git packages, uses normalized host/path to ensure SSH and HTTPS URLs\n\t * for the same repository are treated as identical.\n\t */\n\tprivate getPackageIdentity(source: string, scope?: SourceScope): string {\n\t\tconst parsed = this.parseSource(source);\n\t\tif (parsed.type === \"npm\") {\n\t\t\treturn `npm:${parsed.name}`;\n\t\t}\n\t\tif (parsed.type === \"git\") {\n\t\t\t// Use host/path for identity to normalize SSH and HTTPS\n\t\t\treturn `git:${parsed.host}/${parsed.path}`;\n\t\t}\n\t\tif (scope) {\n\t\t\tconst baseDir = this.getBaseDirForScope(scope);\n\t\t\treturn `local:${this.resolvePathFromBase(parsed.path, baseDir)}`;\n\t\t}\n\t\treturn `local:${this.resolvePath(parsed.path)}`;\n\t}\n\n\t/**\n\t * Dedupe packages: if same package identity appears in both global and project,\n\t * keep only the project one (project wins). A project entry with autoload=false\n\t * is a delta over the global entry, so both are kept (delta first).\n\t */\n\tprivate dedupePackages(\n\t\tpackages: Array<{ pkg: PackageSource; scope: SourceScope }>,\n\t): Array<{ pkg: PackageSource; scope: SourceScope }> {\n\t\tconst result: Array<{ pkg: PackageSource; scope: SourceScope }> = [];\n\t\tconst seen = new Map();\n\t\tfor (const entry of packages) {\n\t\t\tconst identity = this.getPackageIdentity(this.getPackageSourceString(entry.pkg), entry.scope);\n\t\t\tconst index = seen.get(identity);\n\t\t\tif (index === undefined) {\n\t\t\t\tseen.set(identity, result.length);\n\t\t\t\tresult.push(entry);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst existing = result[index];\n\t\t\tif (existing?.scope === \"project\" && entry.scope === \"user\") {\n\t\t\t\tif (typeof existing.pkg === \"object\" && existing.pkg.autoload === false) result.push(entry);\n\t\t\t} else if (entry.scope === \"project\") {\n\t\t\t\tresult[index] = entry;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate parseNpmSpec(spec: string): { name: string; version?: string } {\n\t\tconst match = spec.match(/^(@?[^@]+(?:\\/[^@]+)?)(?:@(.+))?$/);\n\t\tif (!match) {\n\t\t\treturn { name: spec };\n\t\t}\n\t\tconst name = match[1] ?? spec;\n\t\tconst version = match[2];\n\t\treturn { name, version };\n\t}\n\n\tprivate assertProjectTrustedForScope(scope: SourceScope): void {\n\t\tif (scope === \"project\" && !this.settingsManager.isProjectTrusted()) {\n\t\t\tthrow new Error(\"Project is not trusted; refusing to access project package storage\");\n\t\t}\n\t}\n\n\tprivate getNpmCommand(): { command: string; args: string[] } {\n\t\tconst configuredCommand = this.settingsManager.getNpmCommand();\n\t\tif (!configuredCommand || configuredCommand.length === 0) {\n\t\t\treturn { command: \"npm\", args: [] };\n\t\t}\n\t\tconst [command, ...args] = configuredCommand;\n\t\tif (!command) {\n\t\t\tthrow new Error(\"Invalid npmCommand: first array entry must be a non-empty command\");\n\t\t}\n\t\treturn { command, args };\n\t}\n\n\tprivate getPackageManagerName(): string {\n\t\tconst npmCommand = this.getNpmCommand();\n\t\tconst commandParts = [npmCommand.command, ...npmCommand.args];\n\t\tconst separatorIndex = commandParts.lastIndexOf(\"--\");\n\t\tconst packageManagerCommand = separatorIndex >= 0 ? commandParts[separatorIndex + 1] : npmCommand.command;\n\t\treturn packageManagerCommand ? basename(packageManagerCommand).replace(/\\.(cmd|exe)$/i, \"\") : \"\";\n\t}\n\n\tprivate async runNpmCommand(args: string[], options?: { cwd?: string }): Promise {\n\t\tconst npmCommand = this.getNpmCommand();\n\t\tawait this.runCommand(npmCommand.command, [...npmCommand.args, ...args], options);\n\t}\n\n\tprivate getGitDependencyInstallArgs(): string[] {\n\t\tconst configuredCommand = this.settingsManager.getNpmCommand();\n\t\tif (configuredCommand && configuredCommand.length > 0) {\n\t\t\treturn [\"install\"];\n\t\t}\n\t\treturn [\"install\", \"--omit=dev\"];\n\t}\n\n\tprivate runNpmCommandSync(args: string[]): string {\n\t\tconst npmCommand = this.getNpmCommand();\n\t\treturn this.runCommandSync(npmCommand.command, [...npmCommand.args, ...args]);\n\t}\n\n\tprivate getNpmInstallArgs(specs: string[], installRoot: string): string[] {\n\t\tconst packageManagerName = this.getPackageManagerName();\n\t\t// Extension packages run inside pi and resolve pi APIs through loader aliases/virtual modules.\n\t\t// Disable peer dependency resolution for managed installs (npm's --legacy-peer-deps, and\n\t\t// equivalent bun/pnpm settings) so package managers do not install or solve host-provided\n\t\t// @earendil-works/pi-* peers. Stale auto-installed pi peers can otherwise block updates.\n\t\tif (packageManagerName === \"bun\") {\n\t\t\treturn [\"install\", ...specs, \"--cwd\", installRoot, \"--omit=peer\"];\n\t\t}\n\t\tif (packageManagerName === \"pnpm\") {\n\t\t\treturn [\n\t\t\t\t\"install\",\n\t\t\t\t...specs,\n\t\t\t\t\"--prefix\",\n\t\t\t\tinstallRoot,\n\t\t\t\t\"--config.auto-install-peers=false\",\n\t\t\t\t\"--config.strict-peer-dependencies=false\",\n\t\t\t\t\"--config.strict-dep-builds=false\",\n\t\t\t];\n\t\t}\n\t\treturn [\"install\", ...specs, \"--prefix\", installRoot, \"--legacy-peer-deps\"];\n\t}\n\n\tprivate async installNpm(source: NpmSource, scope: SourceScope, temporary: boolean): Promise {\n\t\tconst installRoot = this.getNpmInstallRoot(scope, temporary);\n\t\tthis.ensureNpmProject(installRoot);\n\t\tawait this.runNpmCommand(this.getNpmInstallArgs([source.spec], installRoot));\n\t}\n\n\tprivate async uninstallNpm(source: NpmSource, scope: SourceScope): Promise {\n\t\tconst installRoot = this.getNpmInstallRoot(scope, false);\n\t\tif (!existsSync(installRoot)) {\n\t\t\treturn;\n\t\t}\n\t\tconst packageManagerName = this.getPackageManagerName();\n\t\tif (packageManagerName === \"bun\") {\n\t\t\tawait this.runNpmCommand([\"uninstall\", source.name, \"--cwd\", installRoot]);\n\t\t\treturn;\n\t\t}\n\t\tconst args = [\"uninstall\", source.name, \"--prefix\", installRoot];\n\t\tif (packageManagerName !== \"pnpm\") {\n\t\t\targs.push(\"--legacy-peer-deps\");\n\t\t}\n\t\tawait this.runNpmCommand(args);\n\t}\n\n\tprivate async installGit(source: GitSource, scope: SourceScope): Promise {\n\t\tconst targetDir = this.getGitInstallPath(source, scope);\n\t\tif (existsSync(targetDir)) {\n\t\t\tif (source.ref) {\n\t\t\t\tawait this.ensureGitRef(targetDir, [\"fetch\", \"origin\", source.ref], \"FETCH_HEAD\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst target = await this.getLocalGitUpdateTarget(targetDir);\n\t\t\tawait this.ensureGitRef(targetDir, target.fetchArgs, target.ref);\n\t\t\treturn;\n\t\t}\n\t\tconst gitRoot = this.getGitInstallRoot(scope);\n\t\tif (gitRoot) {\n\t\t\tthis.ensureGitIgnore(gitRoot);\n\t\t}\n\t\tmkdirSync(dirname(targetDir), { recursive: true });\n\n\t\ttry {\n\t\t\tawait this.runCommand(\"git\", [\"clone\", source.repo, targetDir]);\n\t\t\tif (source.ref) {\n\t\t\t\tawait this.runCommand(\"git\", [\"checkout\", source.ref], { cwd: targetDir });\n\t\t\t}\n\t\t\tconst packageJsonPath = join(targetDir, \"package.json\");\n\t\t\tif (existsSync(packageJsonPath)) {\n\t\t\t\tawait this.runNpmCommand(this.getGitDependencyInstallArgs(), { cwd: targetDir });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\trmSync(targetDir, { recursive: true, force: true });\n\t\t\tthis.pruneEmptyGitParents(targetDir, gitRoot);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async updateGit(source: GitSource, scope: SourceScope): Promise {\n\t\tconst targetDir = this.getGitInstallPath(source, scope);\n\t\tif (!existsSync(targetDir)) {\n\t\t\tawait this.installGit(source, scope);\n\t\t\treturn;\n\t\t}\n\n\t\tif (source.ref) {\n\t\t\tawait this.ensureGitRef(targetDir, [\"fetch\", \"origin\", source.ref], \"FETCH_HEAD\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst target = await this.getLocalGitUpdateTarget(targetDir);\n\t\tawait this.ensureGitRef(targetDir, target.fetchArgs, target.ref);\n\t}\n\n\tprivate async ensureGitRef(targetDir: string, fetchArgs: string[], ref: string): Promise {\n\t\t// Fetch only the ref we will reset to, avoiding unrelated branch/tag noise.\n\t\tawait this.runCommand(\"git\", fetchArgs, { cwd: targetDir });\n\n\t\tconst localHead = await this.runCommandCapture(\"git\", [\"rev-parse\", \"HEAD\"], {\n\t\t\tcwd: targetDir,\n\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t});\n\t\tconst commitRef = `${ref}^{commit}`;\n\t\tconst targetHead = await this.runCommandCapture(\"git\", [\"rev-parse\", commitRef], {\n\t\t\tcwd: targetDir,\n\t\t\ttimeoutMs: NETWORK_TIMEOUT_MS,\n\t\t});\n\t\tif (localHead.trim() === targetHead.trim()) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.runCommand(\"git\", [\"reset\", \"--hard\", commitRef], { cwd: targetDir });\n\n\t\t// Clean untracked files (extensions should be pristine)\n\t\tawait this.runCommand(\"git\", [\"clean\", \"-fdx\"], { cwd: targetDir });\n\n\t\tconst packageJsonPath = join(targetDir, \"package.json\");\n\t\tif (existsSync(packageJsonPath)) {\n\t\t\tawait this.runNpmCommand(this.getGitDependencyInstallArgs(), { cwd: targetDir });\n\t\t}\n\t}\n\n\tprivate async refreshTemporaryGitSource(source: GitSource, sourceStr: string): Promise {\n\t\tif (isOfflineModeEnabled()) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait this.withProgress(\"pull\", sourceStr, `Refreshing ${sourceStr}...`, async () => {\n\t\t\t\tawait this.updateGit(source, \"temporary\");\n\t\t\t});\n\t\t} catch {\n\t\t\t// Keep cached temporary checkout if refresh fails.\n\t\t}\n\t}\n\n\tprivate async removeGit(source: GitSource, scope: SourceScope): Promise {\n\t\tconst targetDir = this.getGitInstallPath(source, scope);\n\t\tif (!existsSync(targetDir)) return;\n\t\trmSync(targetDir, { recursive: true, force: true });\n\t\tthis.pruneEmptyGitParents(targetDir, this.getGitInstallRoot(scope));\n\t}\n\n\tprivate pruneEmptyGitParents(targetDir: string, installRoot: string | undefined): void {\n\t\tif (!installRoot) return;\n\t\tconst resolvedRoot = resolve(installRoot);\n\t\tlet current = dirname(targetDir);\n\t\twhile (current.startsWith(resolvedRoot) && current !== resolvedRoot) {\n\t\t\tif (!existsSync(current)) {\n\t\t\t\tcurrent = dirname(current);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst entries = readdirSync(current);\n\t\t\tif (entries.length > 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\trmSync(current, { recursive: true, force: true });\n\t\t\t} catch {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcurrent = dirname(current);\n\t\t}\n\t}\n\n\tprivate ensureNpmProject(installRoot: string): void {\n\t\tif (!existsSync(installRoot)) {\n\t\t\tmkdirSync(installRoot, { recursive: true });\n\t\t}\n\t\tmarkPathIgnoredByCloudSync(installRoot);\n\t\tthis.ensureGitIgnore(installRoot);\n\t\tconst packageJsonPath = join(installRoot, \"package.json\");\n\t\tif (!existsSync(packageJsonPath)) {\n\t\t\tconst pkgJson = { name: \"pi-extensions\", private: true };\n\t\t\twriteFileSync(packageJsonPath, JSON.stringify(pkgJson, null, 2), \"utf-8\");\n\t\t}\n\t}\n\n\tprivate ensureGitIgnore(dir: string): void {\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t}\n\t\tconst ignorePath = join(dir, \".gitignore\");\n\t\tif (!existsSync(ignorePath)) {\n\t\t\twriteFileSync(ignorePath, \"*\\n!.gitignore\\n\", \"utf-8\");\n\t\t}\n\t}\n\n\tprivate getNpmInstallRoot(scope: SourceScope, temporary: boolean): string {\n\t\tif (temporary) {\n\t\t\treturn this.getTemporaryDir(\"npm\");\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\tthis.assertProjectTrustedForScope(scope);\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"npm\");\n\t\t}\n\t\treturn join(this.agentDir, \"npm\");\n\t}\n\n\tprivate getGlobalNpmRoot(): string {\n\t\tconst npmCommand = this.getNpmCommand();\n\t\tconst commandKey = [npmCommand.command, ...npmCommand.args].join(\"\\0\");\n\t\tif (this.globalNpmRoot && this.globalNpmRootCommandKey === commandKey) {\n\t\t\treturn this.globalNpmRoot;\n\t\t}\n\t\tif (this.getPackageManagerName() === \"bun\") {\n\t\t\tconst binDir = this.runNpmCommandSync([\"pm\", \"bin\", \"-g\"]).trim();\n\t\t\tthis.globalNpmRoot = join(dirname(binDir), \"install\", \"global\", \"node_modules\");\n\t\t} else {\n\t\t\tthis.globalNpmRoot = this.runNpmCommandSync([\"root\", \"-g\"]).trim();\n\t\t}\n\t\tthis.globalNpmRootCommandKey = commandKey;\n\t\treturn this.globalNpmRoot;\n\t}\n\n\tprivate getPnpmGlobalPackagePath(packageName: string): string | undefined {\n\t\tif (this.getPackageManagerName() !== \"pnpm\") {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst output = this.runNpmCommandSync([\"list\", \"-g\", \"--depth\", \"0\", \"--json\"]);\n\t\tconst entries = JSON.parse(output) as Array<{ dependencies?: Record }>;\n\t\tfor (const entry of entries) {\n\t\t\tconst path = entry.dependencies?.[packageName]?.path;\n\t\t\tif (path) return path;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate getManagedNpmInstallPath(source: NpmSource, scope: SourceScope): string {\n\t\tif (scope === \"temporary\") {\n\t\t\treturn join(this.getTemporaryDir(\"npm\"), \"node_modules\", source.name);\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\tthis.assertProjectTrustedForScope(scope);\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"npm\", \"node_modules\", source.name);\n\t\t}\n\t\treturn join(this.agentDir, \"npm\", \"node_modules\", source.name);\n\t}\n\n\tprivate getLegacyGlobalNpmInstallPath(source: NpmSource): string | undefined {\n\t\ttry {\n\t\t\treturn this.getPnpmGlobalPackagePath(source.name) ?? join(this.getGlobalNpmRoot(), source.name);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate getNpmInstallPath(source: NpmSource, scope: SourceScope): string {\n\t\tconst managedPath = this.getManagedNpmInstallPath(source, scope);\n\t\tif (scope !== \"user\" || existsSync(managedPath)) {\n\t\t\treturn managedPath;\n\t\t}\n\t\tconst legacyPath = this.getLegacyGlobalNpmInstallPath(source);\n\t\treturn legacyPath && existsSync(legacyPath) ? legacyPath : managedPath;\n\t}\n\n\tprivate getGitInstallPath(source: GitSource, scope: SourceScope): string {\n\t\tif (scope === \"temporary\") {\n\t\t\treturn this.getTemporaryDir(`git-${source.host}`, source.path);\n\t\t}\n\t\tconst installRoot = this.getGitInstallRoot(scope);\n\t\tif (!installRoot) {\n\t\t\tthrow new Error(\"Missing git install root\");\n\t\t}\n\t\treturn this.resolveManagedPath(installRoot, source.host, source.path);\n\t}\n\n\tprivate getGitInstallRoot(scope: SourceScope): string | undefined {\n\t\tif (scope === \"temporary\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\tthis.assertProjectTrustedForScope(scope);\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME, \"git\");\n\t\t}\n\t\treturn join(this.agentDir, \"git\");\n\t}\n\n\tprivate getTemporaryDir(prefix: string, suffix?: string): string {\n\t\tconst root = this.resolveManagedPath(getExtensionTempFolder(this.agentDir), prefix);\n\t\tconst hash = createHash(\"sha256\")\n\t\t\t.update(`${prefix}-${suffix ?? \"\"}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 8);\n\t\treturn this.resolveManagedPath(root, hash, suffix ?? \"\");\n\t}\n\n\tprivate resolveManagedPath(root: string, ...parts: string[]): string {\n\t\tconst resolvedRoot = resolve(root);\n\t\tconst resolvedPath = resolve(resolvedRoot, ...parts);\n\t\tif (resolvedPath !== resolvedRoot && !resolvedPath.startsWith(`${resolvedRoot}${sep}`)) {\n\t\t\tthrow new Error(`Refusing to use path outside package install root: ${resolvedPath}`);\n\t\t}\n\t\treturn resolvedPath;\n\t}\n\n\tprivate getBaseDirForScope(scope: SourceScope): string {\n\t\tif (scope === \"project\") {\n\t\t\tthis.assertProjectTrustedForScope(scope);\n\t\t\treturn join(this.cwd, CONFIG_DIR_NAME);\n\t\t}\n\t\tif (scope === \"user\") {\n\t\t\treturn this.agentDir;\n\t\t}\n\t\treturn this.cwd;\n\t}\n\n\tprivate resolvePath(input: string): string {\n\t\treturn resolvePath(input, this.cwd, { homeDir: getHomeDir(), trim: true });\n\t}\n\n\tprivate resolvePathFromBase(input: string, baseDir: string): string {\n\t\treturn resolvePath(input, baseDir, { homeDir: getHomeDir(), trim: true });\n\t}\n\n\tprivate collectPackageResources(\n\t\tpackageRoot: string,\n\t\taccumulator: ResourceAccumulator,\n\t\tfilter: PackageFilter | undefined,\n\t\tmetadata: PathMetadata,\n\t): boolean {\n\t\tif (filter) {\n\t\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\t\tconst patterns = filter[resourceType];\n\t\t\t\tconst target = this.getTargetMap(accumulator, resourceType);\n\t\t\t\tif (filter.autoload === false) {\n\t\t\t\t\tthis.applyPackageDeltaFilter(packageRoot, patterns ?? [], resourceType, target, metadata);\n\t\t\t\t} else if (patterns !== undefined) {\n\t\t\t\t\tthis.applyPackageFilter(packageRoot, patterns, resourceType, target, metadata);\n\t\t\t\t} else {\n\t\t\t\t\tthis.collectDefaultResources(packageRoot, resourceType, target, metadata);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tconst manifest = this.readPiManifest(packageRoot);\n\t\tif (manifest) {\n\t\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\t\tconst entries = manifest[resourceType as keyof PiManifest];\n\t\t\t\tthis.addManifestEntries(\n\t\t\t\t\tentries,\n\t\t\t\t\tpackageRoot,\n\t\t\t\t\tresourceType,\n\t\t\t\t\tthis.getTargetMap(accumulator, resourceType),\n\t\t\t\t\tmetadata,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tlet hasAnyDir = false;\n\t\tfor (const resourceType of RESOURCE_TYPES) {\n\t\t\tconst dir = join(packageRoot, resourceType);\n\t\t\tif (existsSync(dir)) {\n\t\t\t\t// Collect all files from the directory (all enabled by default)\n\t\t\t\tconst files = collectResourceFiles(dir, resourceType);\n\t\t\t\tfor (const f of files) {\n\t\t\t\t\tthis.addResource(this.getTargetMap(accumulator, resourceType), f, metadata, true);\n\t\t\t\t}\n\t\t\t\thasAnyDir = true;\n\t\t\t}\n\t\t}\n\t\treturn hasAnyDir;\n\t}\n\n\tprivate collectDefaultResources(\n\t\tpackageRoot: string,\n\t\tresourceType: ResourceType,\n\t\ttarget: Map,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tconst manifest = this.readPiManifest(packageRoot);\n\t\tconst entries = manifest?.[resourceType as keyof PiManifest];\n\t\tif (entries) {\n\t\t\tthis.addManifestEntries(entries, packageRoot, resourceType, target, metadata);\n\t\t\treturn;\n\t\t}\n\t\tconst dir = join(packageRoot, resourceType);\n\t\tif (existsSync(dir)) {\n\t\t\t// Collect all files from the directory (all enabled by default)\n\t\t\tconst files = collectResourceFiles(dir, resourceType);\n\t\t\tfor (const f of files) {\n\t\t\t\tthis.addResource(target, f, metadata, true);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate applyPackageFilter(\n\t\tpackageRoot: string,\n\t\tuserPatterns: string[],\n\t\tresourceType: ResourceType,\n\t\ttarget: Map,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tconst { allFiles } = this.collectManifestFiles(packageRoot, resourceType);\n\n\t\tif (userPatterns.length === 0) {\n\t\t\t// Empty array explicitly disables all resources of this type\n\t\t\tfor (const f of allFiles) {\n\t\t\t\tthis.addResource(target, f, metadata, false);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Apply user patterns\n\t\tconst enabledByUser = applyPatterns(allFiles, userPatterns, packageRoot);\n\n\t\tfor (const f of allFiles) {\n\t\t\tconst enabled = enabledByUser.has(f);\n\t\t\tthis.addResource(target, f, metadata, enabled);\n\t\t}\n\t}\n\n\tprivate applyPackageDeltaFilter(\n\t\tpackageRoot: string,\n\t\tuserPatterns: string[],\n\t\tresourceType: ResourceType,\n\t\ttarget: Map,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tif (userPatterns.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst { allFiles } = this.collectManifestFiles(packageRoot, resourceType);\n\t\tconst enabledByUser = applyAutoloadDisabledPatterns(allFiles, userPatterns, packageRoot);\n\t\tfor (const [filePath, enabled] of enabledByUser) {\n\t\t\tthis.addResource(target, filePath, metadata, enabled);\n\t\t}\n\t}\n\n\t/**\n\t * Collect all files from a package for a resource type, applying manifest patterns.\n\t * Returns { allFiles, enabledByManifest } where enabledByManifest is the set of files\n\t * that pass the manifest's own patterns.\n\t */\n\tprivate collectManifestFiles(\n\t\tpackageRoot: string,\n\t\tresourceType: ResourceType,\n\t): { allFiles: string[]; enabledByManifest: Set } {\n\t\tconst manifest = this.readPiManifest(packageRoot);\n\t\tconst entries = manifest?.[resourceType as keyof PiManifest];\n\t\tif (entries && entries.length > 0) {\n\t\t\tconst allFiles = this.collectFilesFromManifestEntries(entries, packageRoot, resourceType);\n\t\t\tconst manifestPatterns = entries.filter(isOverridePattern);\n\t\t\tconst enabledByManifest =\n\t\t\t\tmanifestPatterns.length > 0 ? applyPatterns(allFiles, manifestPatterns, packageRoot) : new Set(allFiles);\n\t\t\treturn { allFiles: Array.from(enabledByManifest), enabledByManifest };\n\t\t}\n\n\t\tconst conventionDir = join(packageRoot, resourceType);\n\t\tif (!existsSync(conventionDir)) {\n\t\t\treturn { allFiles: [], enabledByManifest: new Set() };\n\t\t}\n\t\tconst allFiles = collectResourceFiles(conventionDir, resourceType);\n\t\treturn { allFiles, enabledByManifest: new Set(allFiles) };\n\t}\n\n\tprivate readPiManifest(packageRoot: string): PiManifest | null {\n\t\tconst packageJsonPath = join(packageRoot, \"package.json\");\n\t\tif (!existsSync(packageJsonPath)) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\tconst content = readFileSync(packageJsonPath, \"utf-8\");\n\t\t\tconst pkg = JSON.parse(content) as { pi?: PiManifest };\n\t\t\treturn pkg.pi ?? null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate addManifestEntries(\n\t\tentries: string[] | undefined,\n\t\troot: string,\n\t\tresourceType: ResourceType,\n\t\ttarget: Map,\n\t\tmetadata: PathMetadata,\n\t): void {\n\t\tif (!entries) return;\n\n\t\tconst allFiles = this.collectFilesFromManifestEntries(entries, root, resourceType);\n\t\tconst patterns = entries.filter(isOverridePattern);\n\t\tconst enabledPaths = applyPatterns(allFiles, patterns, root);\n\n\t\tfor (const f of allFiles) {\n\t\t\tif (enabledPaths.has(f)) {\n\t\t\t\tthis.addResource(target, f, metadata, true);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate collectFilesFromManifestEntries(entries: string[], root: string, resourceType: ResourceType): string[] {\n\t\tconst sourceEntries = entries.filter((entry) => !isOverridePattern(entry));\n\t\tconst resolved = sourceEntries.flatMap((entry) => {\n\t\t\tif (!hasGlobPattern(entry)) {\n\t\t\t\treturn [resolve(root, entry)];\n\t\t\t}\n\n\t\t\treturn globSync(entry, {\n\t\t\t\tcwd: root,\n\t\t\t\tabsolute: true,\n\t\t\t\tdot: false,\n\t\t\t\tnodir: false,\n\t\t\t}).map((match) => resolve(match));\n\t\t});\n\t\treturn this.collectFilesFromPaths(resolved, resourceType);\n\t}\n\n\tprivate resolveLocalEntries(\n\t\tentries: string[],\n\t\tresourceType: ResourceType,\n\t\ttarget: Map,\n\t\tmetadata: PathMetadata,\n\t\tbaseDir: string,\n\t): void {\n\t\tif (entries.length === 0) return;\n\n\t\t// Collect all files from plain entries (non-pattern entries)\n\t\tconst { plain, patterns } = splitPatterns(entries);\n\t\tconst resolvedPlain = plain.map((p) => this.resolvePathFromBase(p, baseDir));\n\t\tconst allFiles = this.collectFilesFromPaths(resolvedPlain, resourceType);\n\n\t\t// Determine which files are enabled based on patterns\n\t\tconst enabledPaths = applyPatterns(allFiles, patterns, baseDir);\n\n\t\t// Add all files with their enabled state\n\t\tfor (const f of allFiles) {\n\t\t\tthis.addResource(target, f, metadata, enabledPaths.has(f));\n\t\t}\n\t}\n\n\tprivate addAutoDiscoveredResources(\n\t\taccumulator: ResourceAccumulator,\n\t\tglobalSettings: ReturnType,\n\t\tprojectSettings: ReturnType,\n\t\tglobalBaseDir: string,\n\t\tprojectBaseDir: string,\n\t): void {\n\t\tconst userMetadata: PathMetadata = {\n\t\t\tsource: \"auto\",\n\t\t\tscope: \"user\",\n\t\t\torigin: \"top-level\",\n\t\t\tbaseDir: globalBaseDir,\n\t\t};\n\t\tconst projectMetadata: PathMetadata = {\n\t\t\tsource: \"auto\",\n\t\t\tscope: \"project\",\n\t\t\torigin: \"top-level\",\n\t\t\tbaseDir: projectBaseDir,\n\t\t};\n\n\t\tconst userOverrides = {\n\t\t\textensions: (globalSettings.extensions ?? []) as string[],\n\t\t\tskills: (globalSettings.skills ?? []) as string[],\n\t\t\tprompts: (globalSettings.prompts ?? []) as string[],\n\t\t\tthemes: (globalSettings.themes ?? []) as string[],\n\t\t};\n\t\tconst projectOverrides = {\n\t\t\textensions: (projectSettings.extensions ?? []) as string[],\n\t\t\tskills: (projectSettings.skills ?? []) as string[],\n\t\t\tprompts: (projectSettings.prompts ?? []) as string[],\n\t\t\tthemes: (projectSettings.themes ?? []) as string[],\n\t\t};\n\n\t\tconst userDirs = {\n\t\t\textensions: join(globalBaseDir, \"extensions\"),\n\t\t\tskills: join(globalBaseDir, \"skills\"),\n\t\t\tprompts: join(globalBaseDir, \"prompts\"),\n\t\t\tthemes: join(globalBaseDir, \"themes\"),\n\t\t};\n\t\tconst projectDirs = {\n\t\t\textensions: join(projectBaseDir, \"extensions\"),\n\t\t\tskills: join(projectBaseDir, \"skills\"),\n\t\t\tprompts: join(projectBaseDir, \"prompts\"),\n\t\t\tthemes: join(projectBaseDir, \"themes\"),\n\t\t};\n\t\tconst userAgentsSkillsDir = join(getHomeDir(), \".agents\", \"skills\");\n\t\tconst projectTrusted = this.settingsManager.isProjectTrusted();\n\t\tconst projectAgentsSkillDirs = projectTrusted\n\t\t\t? collectAncestorAgentsSkillDirs(this.cwd).filter((dir) => resolve(dir) !== resolve(userAgentsSkillsDir))\n\t\t\t: [];\n\n\t\tconst addResources = (\n\t\t\tresourceType: ResourceType,\n\t\t\tpaths: string[],\n\t\t\tmetadata: PathMetadata,\n\t\t\toverrides: string[],\n\t\t\tbaseDir: string,\n\t\t) => {\n\t\t\tconst target = this.getTargetMap(accumulator, resourceType);\n\t\t\tfor (const path of paths) {\n\t\t\t\tconst enabled = isEnabledByOverrides(path, overrides, baseDir);\n\t\t\t\tthis.addResource(target, path, metadata, enabled);\n\t\t\t}\n\t\t};\n\n\t\tif (projectTrusted) {\n\t\t\t// Project extensions from .pi/\n\t\t\taddResources(\n\t\t\t\t\"extensions\",\n\t\t\t\tcollectAutoExtensionEntries(projectDirs.extensions),\n\t\t\t\tprojectMetadata,\n\t\t\t\tprojectOverrides.extensions,\n\t\t\t\tprojectBaseDir,\n\t\t\t);\n\n\t\t\t// Project skills from .pi/\n\t\t\taddResources(\n\t\t\t\t\"skills\",\n\t\t\t\tcollectAutoSkillEntries(projectDirs.skills, \"pi\"),\n\t\t\t\tprojectMetadata,\n\t\t\t\tprojectOverrides.skills,\n\t\t\t\tprojectBaseDir,\n\t\t\t);\n\t\t}\n\n\t\t// Project skills from .agents/ (each with its own baseDir)\n\t\tfor (const agentsSkillsDir of projectAgentsSkillDirs) {\n\t\t\tconst agentsBaseDir = dirname(agentsSkillsDir); // the .agents directory\n\t\t\tconst agentsMetadata: PathMetadata = {\n\t\t\t\t...projectMetadata,\n\t\t\t\tbaseDir: agentsBaseDir,\n\t\t\t};\n\t\t\taddResources(\n\t\t\t\t\"skills\",\n\t\t\t\tcollectAutoSkillEntries(agentsSkillsDir, \"agents\"),\n\t\t\t\tagentsMetadata,\n\t\t\t\tprojectOverrides.skills,\n\t\t\t\tagentsBaseDir,\n\t\t\t);\n\t\t}\n\n\t\tif (projectTrusted) {\n\t\t\taddResources(\n\t\t\t\t\"prompts\",\n\t\t\t\tcollectAutoPromptEntries(projectDirs.prompts),\n\t\t\t\tprojectMetadata,\n\t\t\t\tprojectOverrides.prompts,\n\t\t\t\tprojectBaseDir,\n\t\t\t);\n\t\t\taddResources(\n\t\t\t\t\"themes\",\n\t\t\t\tcollectAutoThemeEntries(projectDirs.themes),\n\t\t\t\tprojectMetadata,\n\t\t\t\tprojectOverrides.themes,\n\t\t\t\tprojectBaseDir,\n\t\t\t);\n\t\t}\n\n\t\t// User extensions from ~/.pi/agent/\n\t\taddResources(\n\t\t\t\"extensions\",\n\t\t\tcollectAutoExtensionEntries(userDirs.extensions),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.extensions,\n\t\t\tglobalBaseDir,\n\t\t);\n\n\t\t// User skills from ~/.pi/agent/\n\t\taddResources(\n\t\t\t\"skills\",\n\t\t\tcollectAutoSkillEntries(userDirs.skills, \"pi\"),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.skills,\n\t\t\tglobalBaseDir,\n\t\t);\n\n\t\t// User skills from ~/.agents/ (with its own baseDir)\n\t\tconst userAgentsBaseDir = dirname(userAgentsSkillsDir);\n\t\tconst userAgentsMetadata: PathMetadata = {\n\t\t\t...userMetadata,\n\t\t\tbaseDir: userAgentsBaseDir,\n\t\t};\n\t\taddResources(\n\t\t\t\"skills\",\n\t\t\tcollectAutoSkillEntries(userAgentsSkillsDir, \"agents\"),\n\t\t\tuserAgentsMetadata,\n\t\t\tuserOverrides.skills,\n\t\t\tuserAgentsBaseDir,\n\t\t);\n\n\t\taddResources(\n\t\t\t\"prompts\",\n\t\t\tcollectAutoPromptEntries(userDirs.prompts),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.prompts,\n\t\t\tglobalBaseDir,\n\t\t);\n\t\taddResources(\n\t\t\t\"themes\",\n\t\t\tcollectAutoThemeEntries(userDirs.themes),\n\t\t\tuserMetadata,\n\t\t\tuserOverrides.themes,\n\t\t\tglobalBaseDir,\n\t\t);\n\t}\n\n\tprivate collectFilesFromPaths(paths: string[], resourceType: ResourceType): string[] {\n\t\tconst files: string[] = [];\n\t\tfor (const p of paths) {\n\t\t\tif (!existsSync(p)) continue;\n\n\t\t\ttry {\n\t\t\t\tconst stats = statSync(p);\n\t\t\t\tif (stats.isFile()) {\n\t\t\t\t\tfiles.push(p);\n\t\t\t\t} else if (stats.isDirectory()) {\n\t\t\t\t\tfiles.push(...collectResourceFiles(p, resourceType));\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Ignore errors\n\t\t\t}\n\t\t}\n\t\treturn files;\n\t}\n\n\tprivate getTargetMap(\n\t\taccumulator: ResourceAccumulator,\n\t\tresourceType: ResourceType,\n\t): Map {\n\t\tswitch (resourceType) {\n\t\t\tcase \"extensions\":\n\t\t\t\treturn accumulator.extensions;\n\t\t\tcase \"skills\":\n\t\t\t\treturn accumulator.skills;\n\t\t\tcase \"prompts\":\n\t\t\t\treturn accumulator.prompts;\n\t\t\tcase \"themes\":\n\t\t\t\treturn accumulator.themes;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unknown resource type: ${resourceType}`);\n\t\t}\n\t}\n\n\tprivate addResource(\n\t\tmap: Map,\n\t\tpath: string,\n\t\tmetadata: PathMetadata,\n\t\tenabled: boolean,\n\t): void {\n\t\tif (!path) return;\n\t\tif (!map.has(path)) {\n\t\t\tmap.set(path, { metadata, enabled });\n\t\t}\n\t}\n\n\tprivate createAccumulator(): ResourceAccumulator {\n\t\treturn {\n\t\t\textensions: new Map(),\n\t\t\tskills: new Map(),\n\t\t\tprompts: new Map(),\n\t\t\tthemes: new Map(),\n\t\t};\n\t}\n\n\tprivate toResolvedPaths(accumulator: ResourceAccumulator): ResolvedPaths {\n\t\tconst mapToResolved = (\n\t\t\tentries: Map,\n\t\t): ResolvedResource[] => {\n\t\t\tconst resolved = Array.from(entries.entries()).map(([path, { metadata, enabled }]) => ({\n\t\t\t\tpath,\n\t\t\t\tenabled,\n\t\t\t\tmetadata,\n\t\t\t}));\n\t\t\tresolved.sort((a, b) => resourcePrecedenceRank(a.metadata) - resourcePrecedenceRank(b.metadata));\n\n\t\t\tconst seen = new Set();\n\t\t\treturn resolved.filter((entry) => {\n\t\t\t\tconst canonicalPath = canonicalizePath(entry.path);\n\t\t\t\tif (seen.has(canonicalPath)) return false;\n\t\t\t\tseen.add(canonicalPath);\n\t\t\t\treturn true;\n\t\t\t});\n\t\t};\n\n\t\treturn {\n\t\t\textensions: mapToResolved(accumulator.extensions),\n\t\t\tskills: mapToResolved(accumulator.skills),\n\t\t\tprompts: mapToResolved(accumulator.prompts),\n\t\t\tthemes: mapToResolved(accumulator.themes),\n\t\t};\n\t}\n\n\tprivate spawnCommand(command: string, args: string[], options?: { cwd?: string }): ChildProcess {\n\t\tconst env = getEnv();\n\t\treturn spawnProcess(command, args, {\n\t\t\tcwd: options?.cwd,\n\t\t\tstdio: isStdoutTakenOver() ? [\"ignore\", 2, 2] : \"inherit\",\n\t\t\tenv,\n\t\t});\n\t}\n\n\tprivate spawnCaptureCommand(\n\t\tcommand: string,\n\t\targs: string[],\n\t\toptions?: { cwd?: string; env?: Record },\n\t): ChildProcessByStdio {\n\t\tconst baseEnv = getEnv();\n\t\tconst env = options?.env ? { ...baseEnv, ...options.env } : baseEnv;\n\t\treturn spawnProcess(command, args, {\n\t\t\tcwd: options?.cwd,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tenv,\n\t\t});\n\t}\n\n\tprivate runCommandCapture(\n\t\tcommand: string,\n\t\targs: string[],\n\t\toptions?: { cwd?: string; timeoutMs?: number; env?: Record },\n\t): Promise {\n\t\treturn new Promise((resolvePromise, reject) => {\n\t\t\tconst child = this.spawnCaptureCommand(command, args, options);\n\t\t\tlet stdout = \"\";\n\t\t\tlet stderr = \"\";\n\t\t\tlet timedOut = false;\n\t\t\tconst timeout =\n\t\t\t\ttypeof options?.timeoutMs === \"number\"\n\t\t\t\t\t? setTimeout(() => {\n\t\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t}, options.timeoutMs)\n\t\t\t\t\t: undefined;\n\n\t\t\tchild.stdout?.on(\"data\", (data) => {\n\t\t\t\tstdout += data.toString();\n\t\t\t});\n\t\t\tchild.stderr?.on(\"data\", (data) => {\n\t\t\t\tstderr += data.toString();\n\t\t\t});\n\t\t\tchild.once(\"error\", (error) => {\n\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t\treject(error);\n\t\t\t});\n\t\t\tchild.once(\"close\", (code, signal) => {\n\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t\tif (timedOut) {\n\t\t\t\t\treject(new Error(`${command} ${args.join(\" \")} timed out after ${options?.timeoutMs}ms`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (code === 0) {\n\t\t\t\t\tresolvePromise(stdout.trim());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst exitStatus = code === null ? `signal ${signal ?? \"unknown\"}` : `code ${code}`;\n\t\t\t\treject(new Error(`${command} ${args.join(\" \")} failed with ${exitStatus}: ${stderr || stdout}`));\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate runCommand(command: string, args: string[], options?: { cwd?: string }): Promise {\n\t\treturn new Promise((resolvePromise, reject) => {\n\t\t\tconst child = this.spawnCommand(command, args, options);\n\t\t\tchild.on(\"error\", reject);\n\t\t\tchild.on(\"exit\", (code) => {\n\t\t\t\tif (code === 0) {\n\t\t\t\t\tresolvePromise();\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(`${command} ${args.join(\" \")} failed with code ${code}`));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate runCommandSync(command: string, args: string[]): string {\n\t\tconst env = getEnv();\n\t\tconst result = spawnProcessSync(command, args, {\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tencoding: \"utf-8\",\n\t\t\tenv,\n\t\t});\n\t\tif (result.error || result.status !== 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to run ${command} ${args.join(\" \")}: ${result.error?.message || result.stderr || result.stdout}`,\n\t\t\t);\n\t\t}\n\t\treturn (result.stdout || result.stderr || \"\").trim();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/project-trust.d.ts b/dist/core/project-trust.d.ts new file mode 100644 index 0000000..ab8d8a2 --- /dev/null +++ b/dist/core/project-trust.d.ts @@ -0,0 +1,15 @@ +import type { LoadExtensionsResult, ProjectTrustContext } from "./extensions/types.ts"; +import type { DefaultProjectTrust } from "./settings-manager.ts"; +import { type ProjectTrustStore } from "./trust-manager.ts"; +export type AppMode = "interactive" | "print" | "json" | "rpc"; +export interface ResolveProjectTrustedOptions { + cwd: string; + trustStore: ProjectTrustStore; + trustOverride?: boolean; + defaultProjectTrust?: DefaultProjectTrust; + extensionsResult?: LoadExtensionsResult; + projectTrustContext: ProjectTrustContext; + onExtensionError?: (message: string) => void; +} +export declare function resolveProjectTrusted(options: ResolveProjectTrustedOptions): Promise; +//# sourceMappingURL=project-trust.d.ts.map \ No newline at end of file diff --git a/dist/core/project-trust.d.ts.map b/dist/core/project-trust.d.ts.map new file mode 100644 index 0000000..f2a0482 --- /dev/null +++ b/dist/core/project-trust.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"project-trust.d.ts","sourceRoot":"","sources":["../../src/core/project-trust.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACvF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,EAIN,KAAK,iBAAiB,EACtB,MAAM,oBAAoB,CAAC;AAE5B,MAAM,MAAM,OAAO,GAAG,aAAa,GAAG,OAAO,GAAG,MAAM,GAAG,KAAK,CAAC;AAE/D,MAAM,WAAW,4BAA4B;IAC5C,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,iBAAiB,CAAC;IAC9B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,mBAAmB,CAAC,EAAE,mBAAmB,CAAC;IAC1C,gBAAgB,CAAC,EAAE,oBAAoB,CAAC;IACxC,mBAAmB,EAAE,mBAAmB,CAAC;IACzC,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CAC7C;AAwBD,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,4BAA4B,GAAG,OAAO,CAAC,OAAO,CAAC,CAkDnG","sourcesContent":["import { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { emitProjectTrustEvent } from \"./extensions/runner.ts\";\nimport type { LoadExtensionsResult, ProjectTrustContext } from \"./extensions/types.ts\";\nimport type { DefaultProjectTrust } from \"./settings-manager.ts\";\nimport {\n\tgetProjectTrustOptions,\n\thasTrustRequiringProjectResources,\n\ttype ProjectTrustOption,\n\ttype ProjectTrustStore,\n} from \"./trust-manager.ts\";\n\nexport type AppMode = \"interactive\" | \"print\" | \"json\" | \"rpc\";\n\nexport interface ResolveProjectTrustedOptions {\n\tcwd: string;\n\ttrustStore: ProjectTrustStore;\n\ttrustOverride?: boolean;\n\tdefaultProjectTrust?: DefaultProjectTrust;\n\textensionsResult?: LoadExtensionsResult;\n\tprojectTrustContext: ProjectTrustContext;\n\tonExtensionError?: (message: string) => void;\n}\n\nfunction formatProjectTrustPrompt(cwd: string): string {\n\treturn `Trust project folder?\\n${cwd}\\n\\nThis allows pi to load ${CONFIG_DIR_NAME} settings and resources, install missing project packages, and execute project extensions.`;\n}\n\nasync function selectProjectTrustOption(\n\tcwd: string,\n\tctx: ProjectTrustContext,\n): Promise {\n\tconst options = getProjectTrustOptions(cwd, { includeSessionOnly: true });\n\tconst selected = await ctx.ui.select(\n\t\tformatProjectTrustPrompt(cwd),\n\t\toptions.map((option) => option.label),\n\t);\n\treturn options.find((option) => option.label === selected);\n}\n\nfunction saveProjectTrustPromptResult(trustStore: ProjectTrustStore, result: ProjectTrustOption): void {\n\tif (result.updates.length > 0) {\n\t\ttrustStore.setMany(result.updates);\n\t}\n}\n\nexport async function resolveProjectTrusted(options: ResolveProjectTrustedOptions): Promise {\n\tif (options.trustOverride !== undefined) {\n\t\treturn options.trustOverride;\n\t}\n\tif (!hasTrustRequiringProjectResources(options.cwd)) {\n\t\treturn true;\n\t}\n\n\tif (options.extensionsResult) {\n\t\tconst { result, errors } = await emitProjectTrustEvent(\n\t\t\toptions.extensionsResult,\n\t\t\t{ type: \"project_trust\", cwd: options.cwd },\n\t\t\toptions.projectTrustContext,\n\t\t);\n\t\tfor (const error of errors) {\n\t\t\toptions.onExtensionError?.(`Extension \"${error.extensionPath}\" project_trust error: ${error.error}`);\n\t\t}\n\t\tif (result) {\n\t\t\tconst trusted = result.trusted === \"yes\";\n\t\t\tif (result.remember === true) {\n\t\t\t\toptions.trustStore.set(options.cwd, trusted);\n\t\t\t}\n\t\t\treturn trusted;\n\t\t}\n\t}\n\n\tconst decision = options.trustStore.get(options.cwd);\n\tif (decision !== null) {\n\t\treturn decision;\n\t}\n\n\tswitch (options.defaultProjectTrust ?? \"ask\") {\n\t\tcase \"always\":\n\t\t\treturn true;\n\t\tcase \"never\":\n\t\t\treturn false;\n\t\tcase \"ask\":\n\t\t\tbreak;\n\t}\n\n\tif (!options.projectTrustContext.hasUI) {\n\t\treturn false;\n\t}\n\n\tconst selected = await selectProjectTrustOption(options.cwd, options.projectTrustContext);\n\tif (selected !== undefined) {\n\t\tsaveProjectTrustPromptResult(options.trustStore, selected);\n\t\treturn selected.trusted;\n\t}\n\treturn false;\n}\n"]} \ No newline at end of file diff --git a/dist/core/project-trust.js b/dist/core/project-trust.js new file mode 100644 index 0000000..c4f2509 --- /dev/null +++ b/dist/core/project-trust.js @@ -0,0 +1,59 @@ +import { CONFIG_DIR_NAME } from "../config.js"; +import { emitProjectTrustEvent } from "./extensions/runner.js"; +import { getProjectTrustOptions, hasTrustRequiringProjectResources, } from "./trust-manager.js"; +function formatProjectTrustPrompt(cwd) { + return `Trust project folder?\n${cwd}\n\nThis allows pi to load ${CONFIG_DIR_NAME} settings and resources, install missing project packages, and execute project extensions.`; +} +async function selectProjectTrustOption(cwd, ctx) { + const options = getProjectTrustOptions(cwd, { includeSessionOnly: true }); + const selected = await ctx.ui.select(formatProjectTrustPrompt(cwd), options.map((option) => option.label)); + return options.find((option) => option.label === selected); +} +function saveProjectTrustPromptResult(trustStore, result) { + if (result.updates.length > 0) { + trustStore.setMany(result.updates); + } +} +export async function resolveProjectTrusted(options) { + if (options.trustOverride !== undefined) { + return options.trustOverride; + } + if (!hasTrustRequiringProjectResources(options.cwd)) { + return true; + } + if (options.extensionsResult) { + const { result, errors } = await emitProjectTrustEvent(options.extensionsResult, { type: "project_trust", cwd: options.cwd }, options.projectTrustContext); + for (const error of errors) { + options.onExtensionError?.(`Extension "${error.extensionPath}" project_trust error: ${error.error}`); + } + if (result) { + const trusted = result.trusted === "yes"; + if (result.remember === true) { + options.trustStore.set(options.cwd, trusted); + } + return trusted; + } + } + const decision = options.trustStore.get(options.cwd); + if (decision !== null) { + return decision; + } + switch (options.defaultProjectTrust ?? "ask") { + case "always": + return true; + case "never": + return false; + case "ask": + break; + } + if (!options.projectTrustContext.hasUI) { + return false; + } + const selected = await selectProjectTrustOption(options.cwd, options.projectTrustContext); + if (selected !== undefined) { + saveProjectTrustPromptResult(options.trustStore, selected); + return selected.trusted; + } + return false; +} +//# sourceMappingURL=project-trust.js.map \ No newline at end of file diff --git a/dist/core/project-trust.js.map b/dist/core/project-trust.js.map new file mode 100644 index 0000000..db26eeb --- /dev/null +++ b/dist/core/project-trust.js.map @@ -0,0 +1 @@ +{"version":3,"file":"project-trust.js","sourceRoot":"","sources":["../../src/core/project-trust.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAG/D,OAAO,EACN,sBAAsB,EACtB,iCAAiC,GAGjC,MAAM,oBAAoB,CAAC;AAc5B,SAAS,wBAAwB,CAAC,GAAW,EAAU;IACtD,OAAO,0BAA0B,GAAG,8BAA8B,eAAe,4FAA4F,CAAC;AAAA,CAC9K;AAED,KAAK,UAAU,wBAAwB,CACtC,GAAW,EACX,GAAwB,EACkB;IAC1C,MAAM,OAAO,GAAG,sBAAsB,CAAC,GAAG,EAAE,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1E,MAAM,QAAQ,GAAG,MAAM,GAAG,CAAC,EAAE,CAAC,MAAM,CACnC,wBAAwB,CAAC,GAAG,CAAC,EAC7B,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CACrC,CAAC;IACF,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,C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AAQ,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACrD,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACvB,OAAO,QAAQ,CAAC;IACjB,CAAC;IAED,QAAQ,OAAO,CAAC,mBAAmB,IAAI,KAAK,EAAE,CAAC;QAC9C,KAAK,QAAQ;YACZ,OAAO,IAAI,CAAC;QACb,KAAK,OAAO;YACX,OAAO,KAAK,CAAC;QACd,KAAK,KAAK;YACT,MAAM;IACR,CAAC;IAED,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,KAAK,EAAE,CAAC;QACxC,OAAO,KAAK,CAAC;IACd,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,wBAAwB,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,mBAAmB,CAAC,CAAC;IAC1F,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC5B,4BAA4B,CAAC,OAAO,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;QAC3D,OAAO,QAAQ,CAAC,OAAO,CAAC;IACzB,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["import { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { emitProjectTrustEvent } from \"./extensions/runner.ts\";\nimport type { LoadExtensionsResult, ProjectTrustContext } from \"./extensions/types.ts\";\nimport type { DefaultProjectTrust } from \"./settings-manager.ts\";\nimport {\n\tgetProjectTrustOptions,\n\thasTrustRequiringProjectResources,\n\ttype ProjectTrustOption,\n\ttype ProjectTrustStore,\n} from \"./trust-manager.ts\";\n\nexport type AppMode = \"interactive\" | \"print\" | \"json\" | \"rpc\";\n\nexport interface ResolveProjectTrustedOptions {\n\tcwd: string;\n\ttrustStore: ProjectTrustStore;\n\ttrustOverride?: boolean;\n\tdefaultProjectTrust?: DefaultProjectTrust;\n\textensionsResult?: LoadExtensionsResult;\n\tprojectTrustContext: ProjectTrustContext;\n\tonExtensionError?: (message: string) => void;\n}\n\nfunction formatProjectTrustPrompt(cwd: string): string {\n\treturn `Trust project folder?\\n${cwd}\\n\\nThis allows pi to load ${CONFIG_DIR_NAME} settings and resources, install missing project packages, and execute project extensions.`;\n}\n\nasync function selectProjectTrustOption(\n\tcwd: string,\n\tctx: ProjectTrustContext,\n): Promise {\n\tconst options = getProjectTrustOptions(cwd, { includeSessionOnly: true });\n\tconst selected = await ctx.ui.select(\n\t\tformatProjectTrustPrompt(cwd),\n\t\toptions.map((option) => option.label),\n\t);\n\treturn options.find((option) => option.label === selected);\n}\n\nfunction saveProjectTrustPromptResult(trustStore: ProjectTrustStore, result: ProjectTrustOption): void {\n\tif (result.updates.length > 0) {\n\t\ttrustStore.setMany(result.updates);\n\t}\n}\n\nexport async function resolveProjectTrusted(options: ResolveProjectTrustedOptions): Promise {\n\tif (options.trustOverride !== undefined) {\n\t\treturn options.trustOverride;\n\t}\n\tif (!hasTrustRequiringProjectResources(options.cwd)) {\n\t\treturn true;\n\t}\n\n\tif (options.extensionsResult) {\n\t\tconst { result, errors } = await emitProjectTrustEvent(\n\t\t\toptions.extensionsResult,\n\t\t\t{ type: \"project_trust\", cwd: options.cwd },\n\t\t\toptions.projectTrustContext,\n\t\t);\n\t\tfor (const error of errors) {\n\t\t\toptions.onExtensionError?.(`Extension \"${error.extensionPath}\" project_trust error: ${error.error}`);\n\t\t}\n\t\tif (result) {\n\t\t\tconst trusted = result.trusted === \"yes\";\n\t\t\tif (result.remember === true) {\n\t\t\t\toptions.trustStore.set(options.cwd, trusted);\n\t\t\t}\n\t\t\treturn trusted;\n\t\t}\n\t}\n\n\tconst decision = options.trustStore.get(options.cwd);\n\tif (decision !== null) {\n\t\treturn decision;\n\t}\n\n\tswitch (options.defaultProjectTrust ?? \"ask\") {\n\t\tcase \"always\":\n\t\t\treturn true;\n\t\tcase \"never\":\n\t\t\treturn false;\n\t\tcase \"ask\":\n\t\t\tbreak;\n\t}\n\n\tif (!options.projectTrustContext.hasUI) {\n\t\treturn false;\n\t}\n\n\tconst selected = await selectProjectTrustOption(options.cwd, options.projectTrustContext);\n\tif (selected !== undefined) {\n\t\tsaveProjectTrustPromptResult(options.trustStore, selected);\n\t\treturn selected.trusted;\n\t}\n\treturn false;\n}\n"]} \ No newline at end of file diff --git a/dist/core/prompt-templates.d.ts b/dist/core/prompt-templates.d.ts new file mode 100644 index 0000000..b9139f8 --- /dev/null +++ b/dist/core/prompt-templates.d.ts @@ -0,0 +1,54 @@ +import { type SourceInfo } from "./source-info.ts"; +/** + * Represents a prompt template loaded from a markdown file + */ +export interface PromptTemplate { + name: string; + description: string; + argumentHint?: string; + content: string; + sourceInfo: SourceInfo; + filePath: string; +} +/** + * Parse command arguments respecting quoted strings (bash-style) + * Returns array of arguments + */ +export declare function parseCommandArgs(argsString: string): string[]; +/** + * Substitute argument placeholders in template content + * Supports: + * - $1, $2, ... for positional args + * - $@ and $ARGUMENTS for all args + * - ${N:-default} for positional arg N with default when missing/empty + * - ${@:-default} and ${ARGUMENTS:-default} for all args with a default when empty + * - ${@:N} for args from Nth onwards (bash-style slicing) + * - ${@:N:L} for L args starting from Nth + * + * Note: Replacement happens on the template string only. Argument and default values + * containing patterns like $1, $@, or $ARGUMENTS are NOT recursively substituted. + */ +export declare function substituteArgs(content: string, args: string[]): string; +export interface LoadPromptTemplatesOptions { + /** Working directory for project-local templates. */ + cwd: string; + /** Agent config directory for global templates. */ + agentDir: string; + /** Explicit prompt template paths (files or directories). */ + promptPaths: string[]; + /** Include default prompt directories. */ + includeDefaults: boolean; +} +/** + * Load all prompt templates from: + * 1. Global: agentDir/prompts/ + * 2. Project: cwd/{CONFIG_DIR_NAME}/prompts/ + * 3. Explicit prompt paths + */ +export declare function loadPromptTemplates(options: LoadPromptTemplatesOptions): PromptTemplate[]; +/** + * Expand a prompt template if it matches a template name. + * Returns the expanded content or the original text if not a template. + */ +export declare function expandPromptTemplate(text: string, templates: PromptTemplate[]): string; +//# sourceMappingURL=prompt-templates.d.ts.map \ No newline at end of file diff --git a/dist/core/prompt-templates.d.ts.map b/dist/core/prompt-templates.d.ts.map new file mode 100644 index 0000000..6d14d54 --- /dev/null +++ b/dist/core/prompt-templates.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"prompt-templates.d.ts","sourceRoot":"","sources":["../../src/core/prompt-templates.ts"],"names":[],"mappings":"AAKA,OAAO,EAA6B,KAAK,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9E;;GAEG;AACH,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,UAAU,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,EAAE,CA+B7D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,MAAM,CAgCtE;AA2ED,MAAM,WAAW,0BAA0B;IAC1C,qDAAqD;IACrD,GAAG,EAAE,MAAM,CAAC;IACZ,mDAAmD;IACnD,QAAQ,EAAE,MAAM,CAAC;IACjB,6DAA6D;IAC7D,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,0CAA0C;IAC1C,eAAe,EAAE,OAAO,CAAC;CACzB;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,0BAA0B,GAAG,cAAc,EAAE,CAqEzF;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,cAAc,EAAE,GAAG,MAAM,CAgBtF","sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport { basename, dirname, join, resolve, sep } from \"path\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { parseFrontmatter } from \"../utils/frontmatter.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { createSyntheticSourceInfo, type SourceInfo } from \"./source-info.ts\";\n\n/**\n * Represents a prompt template loaded from a markdown file\n */\nexport interface PromptTemplate {\n\tname: string;\n\tdescription: string;\n\targumentHint?: string;\n\tcontent: string;\n\tsourceInfo: SourceInfo;\n\tfilePath: string; // Absolute path to the template file\n}\n\n/**\n * Parse command arguments respecting quoted strings (bash-style)\n * Returns array of arguments\n */\nexport function parseCommandArgs(argsString: string): string[] {\n\tconst args: string[] = [];\n\tlet current = \"\";\n\tlet inQuote: string | null = null;\n\n\tfor (let i = 0; i < argsString.length; i++) {\n\t\tconst char = argsString[i];\n\n\t\tif (inQuote) {\n\t\t\tif (char === inQuote) {\n\t\t\t\tinQuote = null;\n\t\t\t} else {\n\t\t\t\tcurrent += char;\n\t\t\t}\n\t\t} else if (char === '\"' || char === \"'\") {\n\t\t\tinQuote = char;\n\t\t} else if (/\\s/.test(char)) {\n\t\t\tif (current) {\n\t\t\t\targs.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t}\n\t\t} else {\n\t\t\tcurrent += char;\n\t\t}\n\t}\n\n\tif (current) {\n\t\targs.push(current);\n\t}\n\n\treturn args;\n}\n\n/**\n * Substitute argument placeholders in template content\n * Supports:\n * - $1, $2, ... for positional args\n * - $@ and $ARGUMENTS for all args\n * - ${N:-default} for positional arg N with default when missing/empty\n * - ${@:-default} and ${ARGUMENTS:-default} for all args with a default when empty\n * - ${@:N} for args from Nth onwards (bash-style slicing)\n * - ${@:N:L} for L args starting from Nth\n *\n * Note: Replacement happens on the template string only. Argument and default values\n * containing patterns like $1, $@, or $ARGUMENTS are NOT recursively substituted.\n */\nexport function substituteArgs(content: string, args: string[]): string {\n\tconst allArgs = args.join(\" \");\n\n\treturn content.replace(\n\t\t/\\$\\{(\\d+|ARGUMENTS|@):-([^}]*)\\}|\\$\\{@:(\\d+)(?::(\\d+))?\\}|\\$(ARGUMENTS|@|\\d+)/g,\n\t\t(_match, defaultTarget, defaultValue, sliceStart, sliceLength, simple) => {\n\t\t\tif (defaultTarget) {\n\t\t\t\tconst value =\n\t\t\t\t\tdefaultTarget === \"@\" || defaultTarget === \"ARGUMENTS\" ? allArgs : args[parseInt(defaultTarget, 10) - 1];\n\t\t\t\treturn value ? value : defaultValue;\n\t\t\t}\n\n\t\t\tif (sliceStart) {\n\t\t\t\tlet start = parseInt(sliceStart, 10) - 1; // Convert to 0-indexed (user provides 1-indexed)\n\t\t\t\t// Treat 0 as 1 (bash convention: args start at 1)\n\t\t\t\tif (start < 0) start = 0;\n\n\t\t\t\tif (sliceLength) {\n\t\t\t\t\tconst length = parseInt(sliceLength, 10);\n\t\t\t\t\treturn args.slice(start, start + length).join(\" \");\n\t\t\t\t}\n\t\t\t\treturn args.slice(start).join(\" \");\n\t\t\t}\n\n\t\t\tif (simple === \"ARGUMENTS\" || simple === \"@\") {\n\t\t\t\treturn allArgs;\n\t\t\t}\n\n\t\t\tconst index = parseInt(simple, 10) - 1;\n\t\t\treturn args[index] ?? \"\";\n\t\t},\n\t);\n}\n\nfunction loadTemplateFromFile(filePath: string, sourceInfo: SourceInfo): PromptTemplate | null {\n\ttry {\n\t\tconst rawContent = readFileSync(filePath, \"utf-8\");\n\t\tconst { frontmatter, body } = parseFrontmatter>(rawContent);\n\n\t\tconst name = basename(filePath).replace(/\\.md$/, \"\");\n\n\t\t// Get description from frontmatter or first non-empty line\n\t\tlet description = frontmatter.description || \"\";\n\t\tif (!description) {\n\t\t\tconst firstLine = body.split(\"\\n\").find((line) => line.trim());\n\t\t\tif (firstLine) {\n\t\t\t\t// Truncate if too long\n\t\t\t\tdescription = firstLine.slice(0, 60);\n\t\t\t\tif (firstLine.length > 60) description += \"...\";\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tname,\n\t\t\tdescription,\n\t\t\t...(frontmatter[\"argument-hint\"] && { argumentHint: frontmatter[\"argument-hint\"] }),\n\t\t\tcontent: body,\n\t\t\tsourceInfo,\n\t\t\tfilePath,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Scan a directory for .md files (non-recursive) and load them as prompt templates.\n */\nfunction loadTemplatesFromDir(dir: string, getSourceInfo: (filePath: string) => SourceInfo): PromptTemplate[] {\n\tconst templates: PromptTemplate[] = [];\n\n\tif (!existsSync(dir)) {\n\t\treturn templates;\n\t}\n\n\ttry {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(dir, entry.name);\n\n\t\t\t// For symlinks, check if they point to a file\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\t// Broken symlink, skip it\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isFile && entry.name.endsWith(\".md\")) {\n\t\t\t\tconst template = loadTemplateFromFile(fullPath, getSourceInfo(fullPath));\n\t\t\t\tif (template) {\n\t\t\t\t\ttemplates.push(template);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn templates;\n\t}\n\n\treturn templates;\n}\n\nexport interface LoadPromptTemplatesOptions {\n\t/** Working directory for project-local templates. */\n\tcwd: string;\n\t/** Agent config directory for global templates. */\n\tagentDir: string;\n\t/** Explicit prompt template paths (files or directories). */\n\tpromptPaths: string[];\n\t/** Include default prompt directories. */\n\tincludeDefaults: boolean;\n}\n\n/**\n * Load all prompt templates from:\n * 1. Global: agentDir/prompts/\n * 2. Project: cwd/{CONFIG_DIR_NAME}/prompts/\n * 3. Explicit prompt paths\n */\nexport function loadPromptTemplates(options: LoadPromptTemplatesOptions): PromptTemplate[] {\n\tconst resolvedCwd = resolvePath(options.cwd);\n\tconst resolvedAgentDir = resolvePath(options.agentDir);\n\tconst promptPaths = options.promptPaths;\n\tconst includeDefaults = options.includeDefaults;\n\n\tconst templates: PromptTemplate[] = [];\n\n\tconst globalPromptsDir = join(resolvedAgentDir, \"prompts\");\n\tconst projectPromptsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, \"prompts\");\n\n\tconst isUnderPath = (target: string, root: string): boolean => {\n\t\tconst normalizedRoot = resolve(root);\n\t\tif (target === normalizedRoot) {\n\t\t\treturn true;\n\t\t}\n\t\tconst prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;\n\t\treturn target.startsWith(prefix);\n\t};\n\n\tconst getSourceInfo = (resolvedPath: string): SourceInfo => {\n\t\tif (isUnderPath(resolvedPath, globalPromptsDir)) {\n\t\t\treturn createSyntheticSourceInfo(resolvedPath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"user\",\n\t\t\t\tbaseDir: globalPromptsDir,\n\t\t\t});\n\t\t}\n\t\tif (isUnderPath(resolvedPath, projectPromptsDir)) {\n\t\t\treturn createSyntheticSourceInfo(resolvedPath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"project\",\n\t\t\t\tbaseDir: projectPromptsDir,\n\t\t\t});\n\t\t}\n\t\treturn createSyntheticSourceInfo(resolvedPath, {\n\t\t\tsource: \"local\",\n\t\t\tbaseDir: statSync(resolvedPath).isDirectory() ? resolvedPath : dirname(resolvedPath),\n\t\t});\n\t};\n\n\tif (includeDefaults) {\n\t\ttemplates.push(...loadTemplatesFromDir(globalPromptsDir, getSourceInfo));\n\t\ttemplates.push(...loadTemplatesFromDir(projectPromptsDir, getSourceInfo));\n\t}\n\n\t// 3. Load explicit prompt paths\n\tfor (const rawPath of promptPaths) {\n\t\tconst resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true });\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stats = statSync(resolvedPath);\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\ttemplates.push(...loadTemplatesFromDir(resolvedPath, getSourceInfo));\n\t\t\t} else if (stats.isFile() && resolvedPath.endsWith(\".md\")) {\n\t\t\t\tconst template = loadTemplateFromFile(resolvedPath, getSourceInfo(resolvedPath));\n\t\t\t\tif (template) {\n\t\t\t\t\ttemplates.push(template);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore read failures\n\t\t}\n\t}\n\n\treturn templates;\n}\n\n/**\n * Expand a prompt template if it matches a template name.\n * Returns the expanded content or the original text if not a template.\n */\nexport function expandPromptTemplate(text: string, templates: PromptTemplate[]): string {\n\tif (!text.startsWith(\"/\")) return text;\n\n\tconst match = text.match(/^\\/([^\\s]+)(?:\\s+([\\s\\S]*))?$/);\n\tif (!match) return text;\n\n\tconst templateName = match[1];\n\tconst argsString = match[2] ?? \"\";\n\n\tconst template = templates.find((t) => t.name === templateName);\n\tif (template) {\n\t\tconst args = parseCommandArgs(argsString);\n\t\treturn substituteArgs(template.content, args);\n\t}\n\n\treturn text;\n}\n"]} \ No newline at end of file diff --git a/dist/core/prompt-templates.js b/dist/core/prompt-templates.js new file mode 100644 index 0000000..3700c08 --- /dev/null +++ b/dist/core/prompt-templates.js @@ -0,0 +1,236 @@ +import { existsSync, readdirSync, readFileSync, statSync } from "fs"; +import { basename, dirname, join, resolve, sep } from "path"; +import { CONFIG_DIR_NAME } from "../config.js"; +import { parseFrontmatter } from "../utils/frontmatter.js"; +import { resolvePath } from "../utils/paths.js"; +import { createSyntheticSourceInfo } from "./source-info.js"; +/** + * Parse command arguments respecting quoted strings (bash-style) + * Returns array of arguments + */ +export function parseCommandArgs(argsString) { + const args = []; + let current = ""; + let inQuote = null; + for (let i = 0; i < argsString.length; i++) { + const char = argsString[i]; + if (inQuote) { + if (char === inQuote) { + inQuote = null; + } + else { + current += char; + } + } + else if (char === '"' || char === "'") { + inQuote = char; + } + else if (/\s/.test(char)) { + if (current) { + args.push(current); + current = ""; + } + } + else { + current += char; + } + } + if (current) { + args.push(current); + } + return args; +} +/** + * Substitute argument placeholders in template content + * Supports: + * - $1, $2, ... for positional args + * - $@ and $ARGUMENTS for all args + * - ${N:-default} for positional arg N with default when missing/empty + * - ${@:-default} and ${ARGUMENTS:-default} for all args with a default when empty + * - ${@:N} for args from Nth onwards (bash-style slicing) + * - ${@:N:L} for L args starting from Nth + * + * Note: Replacement happens on the template string only. Argument and default values + * containing patterns like $1, $@, or $ARGUMENTS are NOT recursively substituted. + */ +export function substituteArgs(content, args) { + const allArgs = args.join(" "); + return content.replace(/\$\{(\d+|ARGUMENTS|@):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g, (_match, defaultTarget, defaultValue, sliceStart, sliceLength, simple) => { + if (defaultTarget) { + const value = defaultTarget === "@" || defaultTarget === "ARGUMENTS" ? allArgs : args[parseInt(defaultTarget, 10) - 1]; + return value ? value : defaultValue; + } + if (sliceStart) { + let start = parseInt(sliceStart, 10) - 1; // Convert to 0-indexed (user provides 1-indexed) + // Treat 0 as 1 (bash convention: args start at 1) + if (start < 0) + start = 0; + if (sliceLength) { + const length = parseInt(sliceLength, 10); + return args.slice(start, start + length).join(" "); + } + return args.slice(start).join(" "); + } + if (simple === "ARGUMENTS" || simple === "@") { + return allArgs; + } + const index = parseInt(simple, 10) - 1; + return args[index] ?? ""; + }); +} +function loadTemplateFromFile(filePath, sourceInfo) { + try { + const rawContent = readFileSync(filePath, "utf-8"); + const { frontmatter, body } = parseFrontmatter(rawContent); + const name = basename(filePath).replace(/\.md$/, ""); + // Get description from frontmatter or first non-empty line + let description = frontmatter.description || ""; + if (!description) { + const firstLine = body.split("\n").find((line) => line.trim()); + if (firstLine) { + // Truncate if too long + description = firstLine.slice(0, 60); + if (firstLine.length > 60) + description += "..."; + } + } + return { + name, + description, + ...(frontmatter["argument-hint"] && { argumentHint: frontmatter["argument-hint"] }), + content: body, + sourceInfo, + filePath, + }; + } + catch { + return null; + } +} +/** + * Scan a directory for .md files (non-recursive) and load them as prompt templates. + */ +function loadTemplatesFromDir(dir, getSourceInfo) { + const templates = []; + if (!existsSync(dir)) { + return templates; + } + try { + const entries = readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + const fullPath = join(dir, entry.name); + // For symlinks, check if they point to a file + let isFile = entry.isFile(); + if (entry.isSymbolicLink()) { + try { + const stats = statSync(fullPath); + isFile = stats.isFile(); + } + catch { + // Broken symlink, skip it + continue; + } + } + if (isFile && entry.name.endsWith(".md")) { + const template = loadTemplateFromFile(fullPath, getSourceInfo(fullPath)); + if (template) { + templates.push(template); + } + } + } + } + catch { + return templates; + } + return templates; +} +/** + * Load all prompt templates from: + * 1. Global: agentDir/prompts/ + * 2. Project: cwd/{CONFIG_DIR_NAME}/prompts/ + * 3. Explicit prompt paths + */ +export function loadPromptTemplates(options) { + const resolvedCwd = resolvePath(options.cwd); + const resolvedAgentDir = resolvePath(options.agentDir); + const promptPaths = options.promptPaths; + const includeDefaults = options.includeDefaults; + const templates = []; + const globalPromptsDir = join(resolvedAgentDir, "prompts"); + const projectPromptsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, "prompts"); + const isUnderPath = (target, root) => { + const normalizedRoot = resolve(root); + if (target === normalizedRoot) { + return true; + } + const prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`; + return target.startsWith(prefix); + }; + const getSourceInfo = (resolvedPath) => { + if (isUnderPath(resolvedPath, globalPromptsDir)) { + return createSyntheticSourceInfo(resolvedPath, { + source: "local", + scope: "user", + baseDir: globalPromptsDir, + }); + } + if (isUnderPath(resolvedPath, projectPromptsDir)) { + return createSyntheticSourceInfo(resolvedPath, { + source: "local", + scope: "project", + baseDir: projectPromptsDir, + }); + } + return createSyntheticSourceInfo(resolvedPath, { + source: "local", + baseDir: statSync(resolvedPath).isDirectory() ? resolvedPath : dirname(resolvedPath), + }); + }; + if (includeDefaults) { + templates.push(...loadTemplatesFromDir(globalPromptsDir, getSourceInfo)); + templates.push(...loadTemplatesFromDir(projectPromptsDir, getSourceInfo)); + } + // 3. Load explicit prompt paths + for (const rawPath of promptPaths) { + const resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true }); + if (!existsSync(resolvedPath)) { + continue; + } + try { + const stats = statSync(resolvedPath); + if (stats.isDirectory()) { + templates.push(...loadTemplatesFromDir(resolvedPath, getSourceInfo)); + } + else if (stats.isFile() && resolvedPath.endsWith(".md")) { + const template = loadTemplateFromFile(resolvedPath, getSourceInfo(resolvedPath)); + if (template) { + templates.push(template); + } + } + } + catch { + // Ignore read failures + } + } + return templates; +} +/** + * Expand a prompt template if it matches a template name. + * Returns the expanded content or the original text if not a template. + */ +export function expandPromptTemplate(text, templates) { + if (!text.startsWith("/")) + return text; + const match = text.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/); + if (!match) + return text; + const templateName = match[1]; + const argsString = match[2] ?? ""; + const template = templates.find((t) => t.name === templateName); + if (template) { + const args = parseCommandArgs(argsString); + return substituteArgs(template.content, args); + } + return text; +} +//# sourceMappingURL=prompt-templates.js.map \ No newline at end of file diff --git a/dist/core/prompt-templates.js.map b/dist/core/prompt-templates.js.map new file mode 100644 index 0000000..6de962d --- /dev/null +++ b/dist/core/prompt-templates.js.map @@ -0,0 +1 @@ +{"version":3,"file":"prompt-templates.js","sourceRoot":"","sources":["../../src/core/prompt-templates.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACrE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,yB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CAAC,GAAG,CAAC;QAAE,OAAO,IAAI,CAAC;IAEvC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAC;IAC1D,IAAI,CAAC,KAAK;QAAE,OAAO,IAAI,CAAC;IAExB,MAAM,YAAY,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC9B,MAAM,UAAU,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAElC,MAAM,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,YAAY,CAAC,CAAC;IAChE,IAAI,QAAQ,EAAE,CAAC;QACd,MAAM,IAAI,GAAG,gBAAgB,CAAC,UAAU,CAAC,CAAC;QAC1C,OAAO,cAAc,CAAC,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC/C,CAAC;IAED,OAAO,IAAI,CAAC;AAAA,CACZ","sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport { basename, dirname, join, resolve, sep } from \"path\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { parseFrontmatter } from \"../utils/frontmatter.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { createSyntheticSourceInfo, type SourceInfo } from \"./source-info.ts\";\n\n/**\n * Represents a prompt template loaded from a markdown file\n */\nexport interface PromptTemplate {\n\tname: string;\n\tdescription: string;\n\targumentHint?: string;\n\tcontent: string;\n\tsourceInfo: SourceInfo;\n\tfilePath: string; // Absolute path to the template file\n}\n\n/**\n * Parse command arguments respecting quoted strings (bash-style)\n * Returns array of arguments\n */\nexport function parseCommandArgs(argsString: string): string[] {\n\tconst args: string[] = [];\n\tlet current = \"\";\n\tlet inQuote: string | null = null;\n\n\tfor (let i = 0; i < argsString.length; i++) {\n\t\tconst char = argsString[i];\n\n\t\tif (inQuote) {\n\t\t\tif (char === inQuote) {\n\t\t\t\tinQuote = null;\n\t\t\t} else {\n\t\t\t\tcurrent += char;\n\t\t\t}\n\t\t} else if (char === '\"' || char === \"'\") {\n\t\t\tinQuote = char;\n\t\t} else if (/\\s/.test(char)) {\n\t\t\tif (current) {\n\t\t\t\targs.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t}\n\t\t} else {\n\t\t\tcurrent += char;\n\t\t}\n\t}\n\n\tif (current) {\n\t\targs.push(current);\n\t}\n\n\treturn args;\n}\n\n/**\n * Substitute argument placeholders in template content\n * Supports:\n * - $1, $2, ... for positional args\n * - $@ and $ARGUMENTS for all args\n * - ${N:-default} for positional arg N with default when missing/empty\n * - ${@:-default} and ${ARGUMENTS:-default} for all args with a default when empty\n * - ${@:N} for args from Nth onwards (bash-style slicing)\n * - ${@:N:L} for L args starting from Nth\n *\n * Note: Replacement happens on the template string only. Argument and default values\n * containing patterns like $1, $@, or $ARGUMENTS are NOT recursively substituted.\n */\nexport function substituteArgs(content: string, args: string[]): string {\n\tconst allArgs = args.join(\" \");\n\n\treturn content.replace(\n\t\t/\\$\\{(\\d+|ARGUMENTS|@):-([^}]*)\\}|\\$\\{@:(\\d+)(?::(\\d+))?\\}|\\$(ARGUMENTS|@|\\d+)/g,\n\t\t(_match, defaultTarget, defaultValue, sliceStart, sliceLength, simple) => {\n\t\t\tif (defaultTarget) {\n\t\t\t\tconst value =\n\t\t\t\t\tdefaultTarget === \"@\" || defaultTarget === \"ARGUMENTS\" ? allArgs : args[parseInt(defaultTarget, 10) - 1];\n\t\t\t\treturn value ? value : defaultValue;\n\t\t\t}\n\n\t\t\tif (sliceStart) {\n\t\t\t\tlet start = parseInt(sliceStart, 10) - 1; // Convert to 0-indexed (user provides 1-indexed)\n\t\t\t\t// Treat 0 as 1 (bash convention: args start at 1)\n\t\t\t\tif (start < 0) start = 0;\n\n\t\t\t\tif (sliceLength) {\n\t\t\t\t\tconst length = parseInt(sliceLength, 10);\n\t\t\t\t\treturn args.slice(start, start + length).join(\" \");\n\t\t\t\t}\n\t\t\t\treturn args.slice(start).join(\" \");\n\t\t\t}\n\n\t\t\tif (simple === \"ARGUMENTS\" || simple === \"@\") {\n\t\t\t\treturn allArgs;\n\t\t\t}\n\n\t\t\tconst index = parseInt(simple, 10) - 1;\n\t\t\treturn args[index] ?? \"\";\n\t\t},\n\t);\n}\n\nfunction loadTemplateFromFile(filePath: string, sourceInfo: SourceInfo): PromptTemplate | null {\n\ttry {\n\t\tconst rawContent = readFileSync(filePath, \"utf-8\");\n\t\tconst { frontmatter, body } = parseFrontmatter>(rawContent);\n\n\t\tconst name = basename(filePath).replace(/\\.md$/, \"\");\n\n\t\t// Get description from frontmatter or first non-empty line\n\t\tlet description = frontmatter.description || \"\";\n\t\tif (!description) {\n\t\t\tconst firstLine = body.split(\"\\n\").find((line) => line.trim());\n\t\t\tif (firstLine) {\n\t\t\t\t// Truncate if too long\n\t\t\t\tdescription = firstLine.slice(0, 60);\n\t\t\t\tif (firstLine.length > 60) description += \"...\";\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tname,\n\t\t\tdescription,\n\t\t\t...(frontmatter[\"argument-hint\"] && { argumentHint: frontmatter[\"argument-hint\"] }),\n\t\t\tcontent: body,\n\t\t\tsourceInfo,\n\t\t\tfilePath,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Scan a directory for .md files (non-recursive) and load them as prompt templates.\n */\nfunction loadTemplatesFromDir(dir: string, getSourceInfo: (filePath: string) => SourceInfo): PromptTemplate[] {\n\tconst templates: PromptTemplate[] = [];\n\n\tif (!existsSync(dir)) {\n\t\treturn templates;\n\t}\n\n\ttry {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(dir, entry.name);\n\n\t\t\t// For symlinks, check if they point to a file\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\t// Broken symlink, skip it\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isFile && entry.name.endsWith(\".md\")) {\n\t\t\t\tconst template = loadTemplateFromFile(fullPath, getSourceInfo(fullPath));\n\t\t\t\tif (template) {\n\t\t\t\t\ttemplates.push(template);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn templates;\n\t}\n\n\treturn templates;\n}\n\nexport interface LoadPromptTemplatesOptions {\n\t/** Working directory for project-local templates. */\n\tcwd: string;\n\t/** Agent config directory for global templates. */\n\tagentDir: string;\n\t/** Explicit prompt template paths (files or directories). */\n\tpromptPaths: string[];\n\t/** Include default prompt directories. */\n\tincludeDefaults: boolean;\n}\n\n/**\n * Load all prompt templates from:\n * 1. Global: agentDir/prompts/\n * 2. Project: cwd/{CONFIG_DIR_NAME}/prompts/\n * 3. Explicit prompt paths\n */\nexport function loadPromptTemplates(options: LoadPromptTemplatesOptions): PromptTemplate[] {\n\tconst resolvedCwd = resolvePath(options.cwd);\n\tconst resolvedAgentDir = resolvePath(options.agentDir);\n\tconst promptPaths = options.promptPaths;\n\tconst includeDefaults = options.includeDefaults;\n\n\tconst templates: PromptTemplate[] = [];\n\n\tconst globalPromptsDir = join(resolvedAgentDir, \"prompts\");\n\tconst projectPromptsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, \"prompts\");\n\n\tconst isUnderPath = (target: string, root: string): boolean => {\n\t\tconst normalizedRoot = resolve(root);\n\t\tif (target === normalizedRoot) {\n\t\t\treturn true;\n\t\t}\n\t\tconst prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;\n\t\treturn target.startsWith(prefix);\n\t};\n\n\tconst getSourceInfo = (resolvedPath: string): SourceInfo => {\n\t\tif (isUnderPath(resolvedPath, globalPromptsDir)) {\n\t\t\treturn createSyntheticSourceInfo(resolvedPath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"user\",\n\t\t\t\tbaseDir: globalPromptsDir,\n\t\t\t});\n\t\t}\n\t\tif (isUnderPath(resolvedPath, projectPromptsDir)) {\n\t\t\treturn createSyntheticSourceInfo(resolvedPath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"project\",\n\t\t\t\tbaseDir: projectPromptsDir,\n\t\t\t});\n\t\t}\n\t\treturn createSyntheticSourceInfo(resolvedPath, {\n\t\t\tsource: \"local\",\n\t\t\tbaseDir: statSync(resolvedPath).isDirectory() ? resolvedPath : dirname(resolvedPath),\n\t\t});\n\t};\n\n\tif (includeDefaults) {\n\t\ttemplates.push(...loadTemplatesFromDir(globalPromptsDir, getSourceInfo));\n\t\ttemplates.push(...loadTemplatesFromDir(projectPromptsDir, getSourceInfo));\n\t}\n\n\t// 3. Load explicit prompt paths\n\tfor (const rawPath of promptPaths) {\n\t\tconst resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true });\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stats = statSync(resolvedPath);\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\ttemplates.push(...loadTemplatesFromDir(resolvedPath, getSourceInfo));\n\t\t\t} else if (stats.isFile() && resolvedPath.endsWith(\".md\")) {\n\t\t\t\tconst template = loadTemplateFromFile(resolvedPath, getSourceInfo(resolvedPath));\n\t\t\t\tif (template) {\n\t\t\t\t\ttemplates.push(template);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore read failures\n\t\t}\n\t}\n\n\treturn templates;\n}\n\n/**\n * Expand a prompt template if it matches a template name.\n * Returns the expanded content or the original text if not a template.\n */\nexport function expandPromptTemplate(text: string, templates: PromptTemplate[]): string {\n\tif (!text.startsWith(\"/\")) return text;\n\n\tconst match = text.match(/^\\/([^\\s]+)(?:\\s+([\\s\\S]*))?$/);\n\tif (!match) return text;\n\n\tconst templateName = match[1];\n\tconst argsString = match[2] ?? \"\";\n\n\tconst template = templates.find((t) => t.name === templateName);\n\tif (template) {\n\t\tconst args = parseCommandArgs(argsString);\n\t\treturn substituteArgs(template.content, args);\n\t}\n\n\treturn text;\n}\n"]} \ No newline at end of file diff --git a/dist/core/provider-attribution.d.ts b/dist/core/provider-attribution.d.ts new file mode 100644 index 0000000..e5c5635 --- /dev/null +++ b/dist/core/provider-attribution.d.ts @@ -0,0 +1,4 @@ +import type { Api, Model, ProviderHeaders } from "@earendil-works/pi-ai"; +import type { SettingsManager } from "./settings-manager.ts"; +export declare function mergeProviderAttributionHeaders(model: Model, settingsManager: SettingsManager, sessionId: string | undefined, ...headerSources: Array): ProviderHeaders | undefined; +//# sourceMappingURL=provider-attribution.d.ts.map \ No newline at end of file diff --git a/dist/core/provider-attribution.d.ts.map b/dist/core/provider-attribution.d.ts.map new file mode 100644 index 0000000..912fa17 --- /dev/null +++ b/dist/core/provider-attribution.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-attribution.d.ts","sourceRoot":"","sources":["../../src/core/provider-attribution.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AA6E7D,wBAAgB,+BAA+B,CAC9C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,eAAe,EAAE,eAAe,EAChC,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,GAAG,aAAa,EAAE,KAAK,CAAC,eAAe,GAAG,SAAS,CAAC,GAClD,eAAe,GAAG,SAAS,CAa7B","sourcesContent":["import type { Api, Model, ProviderHeaders } from \"@earendil-works/pi-ai\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\n\nconst OPENROUTER_HOST = \"openrouter.ai\";\nconst NVIDIA_NIM_HOST = \"integrate.api.nvidia.com\";\nconst CLOUDFLARE_API_HOST = \"api.cloudflare.com\";\nconst CLOUDFLARE_AI_GATEWAY_HOST = \"gateway.ai.cloudflare.com\";\nconst OPENCODE_HOST = \"opencode.ai\";\n\nfunction matchesHost(baseUrl: string, expectedHost: string): boolean {\n\ttry {\n\t\treturn new URL(baseUrl).hostname === expectedHost;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction isOpenRouterModel(model: Model): boolean {\n\treturn model.provider === \"openrouter\" || model.baseUrl.includes(OPENROUTER_HOST);\n}\n\nfunction isNvidiaNimModel(model: Model): boolean {\n\treturn model.provider === \"nvidia\" || matchesHost(model.baseUrl, NVIDIA_NIM_HOST);\n}\n\nfunction isCloudflareModel(model: Model): boolean {\n\treturn (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmatchesHost(model.baseUrl, CLOUDFLARE_API_HOST) ||\n\t\tmatchesHost(model.baseUrl, CLOUDFLARE_AI_GATEWAY_HOST)\n\t);\n}\n\nfunction getDefaultAttributionHeaders(\n\tmodel: Model,\n\tsettingsManager: SettingsManager,\n): Record | undefined {\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (isOpenRouterModel(model)) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (isNvidiaNimModel(model)) {\n\t\treturn {\n\t\t\t\"X-BILLING-INVOKE-ORIGIN\": \"Pi\",\n\t\t};\n\t}\n\n\tif (isCloudflareModel(model)) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\nfunction getSessionHeaders(model: Model, sessionId: string | undefined): Record | undefined {\n\tif (!sessionId) return undefined;\n\tif (\n\t\tmodel.provider !== \"opencode\" &&\n\t\tmodel.provider !== \"opencode-go\" &&\n\t\t!matchesHost(model.baseUrl, OPENCODE_HOST)\n\t) {\n\t\treturn undefined;\n\t}\n\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n}\n\nexport function mergeProviderAttributionHeaders(\n\tmodel: Model,\n\tsettingsManager: SettingsManager,\n\tsessionId: string | undefined,\n\t...headerSources: Array\n): ProviderHeaders | undefined {\n\tconst merged: ProviderHeaders = {\n\t\t...getSessionHeaders(model, sessionId),\n\t\t...getDefaultAttributionHeaders(model, settingsManager),\n\t};\n\n\tfor (const headers of headerSources) {\n\t\tif (headers) {\n\t\t\tObject.assign(merged, headers);\n\t\t}\n\t}\n\n\treturn Object.keys(merged).length > 0 ? merged : undefined;\n}\n"]} \ No newline at end of file diff --git a/dist/core/provider-attribution.js b/dist/core/provider-attribution.js new file mode 100644 index 0000000..096be37 --- /dev/null +++ b/dist/core/provider-attribution.js @@ -0,0 +1,72 @@ +import { isInstallTelemetryEnabled } from "./telemetry.js"; +const OPENROUTER_HOST = "openrouter.ai"; +const NVIDIA_NIM_HOST = "integrate.api.nvidia.com"; +const CLOUDFLARE_API_HOST = "api.cloudflare.com"; +const CLOUDFLARE_AI_GATEWAY_HOST = "gateway.ai.cloudflare.com"; +const OPENCODE_HOST = "opencode.ai"; +function matchesHost(baseUrl, expectedHost) { + try { + return new URL(baseUrl).hostname === expectedHost; + } + catch { + return false; + } +} +function isOpenRouterModel(model) { + return model.provider === "openrouter" || model.baseUrl.includes(OPENROUTER_HOST); +} +function isNvidiaNimModel(model) { + return model.provider === "nvidia" || matchesHost(model.baseUrl, NVIDIA_NIM_HOST); +} +function isCloudflareModel(model) { + return (model.provider === "cloudflare-workers-ai" || + model.provider === "cloudflare-ai-gateway" || + matchesHost(model.baseUrl, CLOUDFLARE_API_HOST) || + matchesHost(model.baseUrl, CLOUDFLARE_AI_GATEWAY_HOST)); +} +function getDefaultAttributionHeaders(model, settingsManager) { + if (!isInstallTelemetryEnabled(settingsManager)) { + return undefined; + } + if (isOpenRouterModel(model)) { + return { + "HTTP-Referer": "https://pi.dev", + "X-OpenRouter-Title": "pi", + "X-OpenRouter-Categories": "cli-agent", + }; + } + if (isNvidiaNimModel(model)) { + return { + "X-BILLING-INVOKE-ORIGIN": "Pi", + }; + } + if (isCloudflareModel(model)) { + return { + "User-Agent": "pi-coding-agent", + }; + } + return undefined; +} +function getSessionHeaders(model, sessionId) { + if (!sessionId) + return undefined; + if (model.provider !== "opencode" && + model.provider !== "opencode-go" && + !matchesHost(model.baseUrl, OPENCODE_HOST)) { + return undefined; + } + return { "x-opencode-session": sessionId, "x-opencode-client": "pi" }; +} +export function mergeProviderAttributionHeaders(model, settingsManager, sessionId, ...headerSources) { + const merged = { + ...getSessionHeaders(model, sessionId), + ...getDefaultAttributionHeaders(model, settingsManager), + }; + for (const headers of headerSources) { + if (headers) { + Object.assign(merged, headers); + } + } + return Object.keys(merged).length > 0 ? merged : undefined; +} +//# sourceMappingURL=provider-attribution.js.map \ No newline at end of file diff --git a/dist/core/provider-attribution.js.map b/dist/core/provider-attribution.js.map new file mode 100644 index 0000000..748168c --- /dev/null +++ b/dist/core/provider-attribution.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-attribution.js","sourceRoot":"","sources":["../../src/core/provider-attribution.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAE3D,MAAM,eAAe,GAAG,eAAe,CAAC;AACxC,MAAM,eAAe,GAAG,0BAA0B,CAAC;AACnD,MAAM,mBAAmB,GAAG,oBAAoB,CAAC;AACjD,MAAM,0BAA0B,GAAG,2BAA2B,CAAC;AAC/D,MAAM,aAAa,GAAG,aAAa,CAAC;AAEpC,SAAS,WAAW,CAAC,OAAe,EAAE,YAAoB,EAAW;IACpE,IAAI,CAAC;QACJ,OAAO,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,QAAQ,KAAK,YAAY,CAAC;IAC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AiB,CAAC,KAAiB,EAAE,SAA6B,EAAsC;IAChH,IAAI,CAAC,SAAS;QAAE,OAAO,SAAS,CAAC;IACjC,IACC,KAAK,CAAC,QAAQ,KAAK,UAAU;QAC7B,KAAK,CAAC,QAAQ,KAAK,aAAa;QAChC,CAAC,WAAW,CAAC,KAAK,CAAC,OAAO,EAAE,aAAa,CAAC,EACzC,CAAC;QACF,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,OAAO,EAAE,oBAAoB,EAAE,SAAS,EAAE,mBAAmB,EAAE,IAAI,EAAE,CAAC;AAAA,CACtE;AAED,MAAM,UAAU,+BAA+B,CAC9C,KAAiB,EACjB,eAAgC,EAChC,SAA6B,EAC7B,GAAG,aAAiD,EACtB;IAC9B,MAAM,MAAM,GAAoB;QAC/B,GAAG,iBAAiB,CAAC,KAAK,EAAE,SAAS,CAAC;QACtC,GAAG,4BAA4B,CAAC,KAAK,EAAE,eAAe,CAAC;KACvD,CAAC;IAEF,KAAK,MAAM,OAAO,IAAI,aAAa,EAAE,CAAC;QACrC,IAAI,OAAO,EAAE,CAAC;YACb,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAChC,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CAC3D","sourcesContent":["import type { Api, Model, ProviderHeaders } from \"@earendil-works/pi-ai\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\n\nconst OPENROUTER_HOST = \"openrouter.ai\";\nconst NVIDIA_NIM_HOST = \"integrate.api.nvidia.com\";\nconst CLOUDFLARE_API_HOST = \"api.cloudflare.com\";\nconst CLOUDFLARE_AI_GATEWAY_HOST = \"gateway.ai.cloudflare.com\";\nconst OPENCODE_HOST = \"opencode.ai\";\n\nfunction matchesHost(baseUrl: string, expectedHost: string): boolean {\n\ttry {\n\t\treturn new URL(baseUrl).hostname === expectedHost;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction isOpenRouterModel(model: Model): boolean {\n\treturn model.provider === \"openrouter\" || model.baseUrl.includes(OPENROUTER_HOST);\n}\n\nfunction isNvidiaNimModel(model: Model): boolean {\n\treturn model.provider === \"nvidia\" || matchesHost(model.baseUrl, NVIDIA_NIM_HOST);\n}\n\nfunction isCloudflareModel(model: Model): boolean {\n\treturn (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmatchesHost(model.baseUrl, CLOUDFLARE_API_HOST) ||\n\t\tmatchesHost(model.baseUrl, CLOUDFLARE_AI_GATEWAY_HOST)\n\t);\n}\n\nfunction getDefaultAttributionHeaders(\n\tmodel: Model,\n\tsettingsManager: SettingsManager,\n): Record | undefined {\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (isOpenRouterModel(model)) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (isNvidiaNimModel(model)) {\n\t\treturn {\n\t\t\t\"X-BILLING-INVOKE-ORIGIN\": \"Pi\",\n\t\t};\n\t}\n\n\tif (isCloudflareModel(model)) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\nfunction getSessionHeaders(model: Model, sessionId: string | undefined): Record | undefined {\n\tif (!sessionId) return undefined;\n\tif (\n\t\tmodel.provider !== \"opencode\" &&\n\t\tmodel.provider !== \"opencode-go\" &&\n\t\t!matchesHost(model.baseUrl, OPENCODE_HOST)\n\t) {\n\t\treturn undefined;\n\t}\n\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n}\n\nexport function mergeProviderAttributionHeaders(\n\tmodel: Model,\n\tsettingsManager: SettingsManager,\n\tsessionId: string | undefined,\n\t...headerSources: Array\n): ProviderHeaders | undefined {\n\tconst merged: ProviderHeaders = {\n\t\t...getSessionHeaders(model, sessionId),\n\t\t...getDefaultAttributionHeaders(model, settingsManager),\n\t};\n\n\tfor (const headers of headerSources) {\n\t\tif (headers) {\n\t\t\tObject.assign(merged, headers);\n\t\t}\n\t}\n\n\treturn Object.keys(merged).length > 0 ? merged : undefined;\n}\n"]} \ No newline at end of file diff --git a/dist/core/provider-composer.d.ts b/dist/core/provider-composer.d.ts new file mode 100644 index 0000000..30f450d --- /dev/null +++ b/dist/core/provider-composer.d.ts @@ -0,0 +1,55 @@ +import { type Api, type AssistantMessageEventStream, type Context, type Model, type OAuthCredentials, type OAuthLoginCallbacks, type Provider, type ProviderHeaders, type RefreshModelsContext, type SimpleStreamOptions } from "@earendil-works/pi-ai"; +import type { ModelConfig, ModelsJsonProvider } from "./model-config.ts"; +import { clearConfigValueCache } from "./resolve-config-value.ts"; +export interface ExtensionOAuthConfig { + name: string; + /** @deprecated Retained for extension source compatibility; ignored by canonical auth flows. */ + usesCallbackServer?: boolean; + login(callbacks: OAuthLoginCallbacks): Promise; + refreshToken(credentials: OAuthCredentials): Promise; + getApiKey(credentials: OAuthCredentials): string; + modifyModels?(models: Model[], credentials: OAuthCredentials): Model[]; +} +/** Input type for the extension registerProvider API. */ +export interface ProviderConfigInput { + name?: string; + baseUrl?: string; + apiKey?: string; + api?: Api; + streamSimple?: (model: Model, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream; + headers?: Record; + authHeader?: boolean; + oauth?: ExtensionOAuthConfig; + models?: Array<{ + id: string; + name: string; + api?: Api; + baseUrl?: string; + reasoning: boolean; + thinkingLevelMap?: Model["thinkingLevelMap"]; + input: ("text" | "image")[]; + cost: Model["cost"]; + contextWindow: number; + maxTokens: number; + headers?: Record; + compat?: Model["compat"]; + }>; + refreshModels?(context: RefreshModelsContext): Promise>; +} +export type AuthStatus = { + configured: boolean; + source?: "stored" | "runtime" | "environment" | "fallback" | "models_json_key" | "models_json_command"; + label?: string; +}; +export declare const clearApiKeyCache: typeof clearConfigValueCache; +export declare function validateExtensionProvider(providerId: string, base: Provider | undefined, modelsConfig: ModelsJsonProvider | undefined, extension: ProviderConfigInput): void; +/** Compose built-in, models.json, and extension layers without reading credentials. */ +export declare function composeModelProvider(providerId: string, base: Provider | undefined, modelConfig: ModelConfig, extension: ProviderConfigInput | undefined): Provider; +export declare function resolveConfiguredModelHeaders(model: Model, config: ModelsJsonProvider | undefined, extension: ProviderConfigInput | undefined, env?: Record): Record | undefined; +export interface CompatibilityRequestConfig { + headers?: ProviderHeaders; + authHeader: boolean; +} +export declare function resolveCompatibilityRequestConfig(model: Model, config: ModelsJsonProvider | undefined, extension: ProviderConfigInput | undefined): CompatibilityRequestConfig; +export declare function configuredRequestAuthStatus(config: ModelsJsonProvider | undefined, extension: ProviderConfigInput | undefined): AuthStatus | undefined; +//# sourceMappingURL=provider-composer.d.ts.map \ No newline at end of file diff --git a/dist/core/provider-composer.d.ts.map b/dist/core/provider-composer.d.ts.map new file mode 100644 index 0000000..ea79581 --- /dev/null +++ b/dist/core/provider-composer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-composer.d.ts","sourceRoot":"","sources":["../../src/core/provider-composer.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,GAAG,EAER,KAAK,2BAA2B,EAIhC,KAAK,OAAO,EAGZ,KAAK,KAAK,EAGV,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACxB,KAAK,QAAQ,EACb,KAAK,eAAe,EACpB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EAExB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,WAAW,EAA4C,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACnH,OAAO,EACN,qBAAqB,EAMrB,MAAM,2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AC,MAAM,EAAE,MAAM,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAMpC;AAED,MAAM,WAAW,0BAA0B;IAC1C,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,UAAU,EAAE,OAAO,CAAC;CACpB;AAED,wBAAgB,iCAAiC,CAChD,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,MAAM,EAAE,kBAAkB,GAAG,SAAS,EACtC,SAAS,EAAE,mBAAmB,GAAG,SAAS,GACxC,0BAA0B,CAS5B;AAED,wBAAgB,2BAA2B,CAC1C,MAAM,EAAE,kBAAkB,GAAG,SAAS,EACtC,SAAS,EAAE,mBAAmB,GAAG,SAAS,GACxC,UAAU,GAAG,SAAS,CAWxB","sourcesContent":["import {\n\ttype Api,\n\ttype ApiKeyAuth,\n\ttype AssistantMessageEventStream,\n\ttype AuthContext,\n\ttype AuthInteraction,\n\ttype AuthResult,\n\ttype Context,\n\ttype Credential,\n\tlazyStream,\n\ttype Model,\n\ttype ModelAuth,\n\ttype OAuthAuth,\n\ttype OAuthCredentials,\n\ttype OAuthLoginCallbacks,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype RefreshModelsContext,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport { getApiProvider } from \"@earendil-works/pi-ai/compat\";\nimport type { ModelConfig, ModelsJsonModel, ModelsJsonModelOverride, ModelsJsonProvider } from \"./model-config.ts\";\nimport {\n\tclearConfigValueCache,\n\tgetConfigValueEnvVarNames,\n\tisCommandConfigValue,\n\tisConfigValueConfigured,\n\tresolveConfigValueOrThrow,\n\tresolveHeadersOrThrow,\n} from \"./resolve-config-value.ts\";\n\nexport interface ExtensionOAuthConfig {\n\tname: string;\n\t/** @deprecated Retained for extension source compatibility; ignored by canonical auth flows. */\n\tusesCallbackServer?: boolean;\n\tlogin(callbacks: OAuthLoginCallbacks): Promise;\n\trefreshToken(credentials: OAuthCredentials): Promise;\n\tgetApiKey(credentials: OAuthCredentials): string;\n\tmodifyModels?(models: Model[], credentials: OAuthCredentials): Model[];\n}\n\n/** Input type for the extension registerProvider API. */\nexport interface ProviderConfigInput {\n\tname?: string;\n\tbaseUrl?: string;\n\tapiKey?: string;\n\tapi?: Api;\n\tstreamSimple?: (model: Model, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\theaders?: Record;\n\tauthHeader?: boolean;\n\toauth?: ExtensionOAuthConfig;\n\tmodels?: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tapi?: Api;\n\t\tbaseUrl?: string;\n\t\treasoning: boolean;\n\t\tthinkingLevelMap?: Model[\"thinkingLevelMap\"];\n\t\tinput: (\"text\" | \"image\")[];\n\t\tcost: Model[\"cost\"];\n\t\tcontextWindow: number;\n\t\tmaxTokens: number;\n\t\theaders?: Record;\n\t\tcompat?: Model[\"compat\"];\n\t}>;\n\trefreshModels?(context: RefreshModelsContext): Promise>;\n}\n\nexport type AuthStatus = {\n\tconfigured: boolean;\n\tsource?: \"stored\" | \"runtime\" | \"environment\" | \"fallback\" | \"models_json_key\" | \"models_json_command\";\n\tlabel?: string;\n};\n\nexport const clearApiKeyCache = clearConfigValueCache;\n\nfunction mergeCompat(\n\tbase: Model[\"compat\"],\n\toverride: Model[\"compat\"] | ModelsJsonModelOverride[\"compat\"],\n): Model[\"compat\"] {\n\tif (!override) return base;\n\tconst merged = { ...base, ...override } as NonNullable[\"compat\"]>;\n\tconst baseNested = base as Record | undefined;\n\tconst overrideNested = override as Record;\n\tconst mergedNested = merged as Record;\n\tfor (const key of [\"openRouterRouting\", \"vercelGatewayRouting\", \"chatTemplateKwargs\"] as const) {\n\t\tconst baseValue = baseNested?.[key];\n\t\tconst overrideValue = overrideNested[key];\n\t\tif (\n\t\t\t(typeof baseValue === \"object\" && baseValue !== null) ||\n\t\t\t(typeof overrideValue === \"object\" && overrideValue !== null)\n\t\t) {\n\t\t\tmergedNested[key] = { ...(baseValue as object | undefined), ...(overrideValue as object | undefined) };\n\t\t}\n\t}\n\treturn merged;\n}\n\nfunction applyModelOverride(model: Model, override: ModelsJsonModelOverride): Model {\n\treturn {\n\t\t...model,\n\t\tname: override.name ?? model.name,\n\t\treasoning: override.reasoning ?? model.reasoning,\n\t\tthinkingLevelMap: override.thinkingLevelMap\n\t\t\t? { ...model.thinkingLevelMap, ...override.thinkingLevelMap }\n\t\t\t: model.thinkingLevelMap,\n\t\tinput: (override.input as (\"text\" | \"image\")[] | undefined) ?? model.input,\n\t\tcost: override.cost\n\t\t\t? {\n\t\t\t\t\tinput: override.cost.input ?? model.cost.input,\n\t\t\t\t\toutput: override.cost.output ?? model.cost.output,\n\t\t\t\t\tcacheRead: override.cost.cacheRead ?? model.cost.cacheRead,\n\t\t\t\t\tcacheWrite: override.cost.cacheWrite ?? model.cost.cacheWrite,\n\t\t\t\t\ttiers: override.cost.tiers ?? model.cost.tiers,\n\t\t\t\t}\n\t\t\t: model.cost,\n\t\tcontextWindow: override.contextWindow ?? model.contextWindow,\n\t\tmaxTokens: override.maxTokens ?? model.maxTokens,\n\t\tcompat: mergeCompat(model.compat, override.compat),\n\t};\n}\n\nfunction modelFromJson(\n\tproviderId: string,\n\tdefinition: ModelsJsonModel,\n\tproviderConfig: ModelsJsonProvider,\n\tdefaults: Model | undefined,\n): Model {\n\tconst api = definition.api ?? providerConfig.api ?? defaults?.api;\n\tif (!api) {\n\t\tthrow new Error(\n\t\t\t`Provider ${providerId}, model ${definition.id}: no \"api\" specified. Set at provider or model level.`,\n\t\t);\n\t}\n\tconst baseUrl = definition.baseUrl ?? providerConfig.baseUrl ?? defaults?.baseUrl;\n\tif (!baseUrl) throw new Error(`Provider ${providerId}: \"baseUrl\" is required when defining custom models.`);\n\tif (definition.contextWindow !== undefined && definition.contextWindow <= 0) {\n\t\tthrow new Error(`Provider ${providerId}, model ${definition.id}: invalid contextWindow`);\n\t}\n\tif (definition.maxTokens !== undefined && definition.maxTokens <= 0) {\n\t\tthrow new Error(`Provider ${providerId}, model ${definition.id}: invalid maxTokens`);\n\t}\n\treturn {\n\t\tid: definition.id,\n\t\tname: definition.name ?? definition.id,\n\t\tapi: api as Api,\n\t\tprovider: providerId,\n\t\tbaseUrl,\n\t\treasoning: definition.reasoning ?? false,\n\t\tthinkingLevelMap: definition.thinkingLevelMap,\n\t\tinput: (definition.input ?? [\"text\"]) as (\"text\" | \"image\")[],\n\t\tcost: definition.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: definition.contextWindow ?? 128000,\n\t\tmaxTokens: definition.maxTokens ?? 16384,\n\t\theaders: undefined,\n\t\tcompat: mergeCompat(providerConfig.compat, definition.compat),\n\t};\n}\n\nfunction applyModelsJson(\n\tproviderId: string,\n\tbaseModels: readonly Model[],\n\tconfig: ModelsJsonProvider | undefined,\n): Model[] {\n\tif (!config) return [...baseModels];\n\tif (config.oauth && !config.baseUrl) {\n\t\tthrow new Error(`Provider ${providerId}: \"baseUrl\" is required when \"oauth\" is set.`);\n\t}\n\tconst hasOverrides = config.modelOverrides && Object.keys(config.modelOverrides).length > 0;\n\tif (\n\t\t!config.models?.length &&\n\t\t!config.baseUrl &&\n\t\t!config.headers &&\n\t\t!config.compat &&\n\t\t!hasOverrides &&\n\t\t!config.apiKey &&\n\t\t!config.oauth &&\n\t\tconfig.authHeader === undefined\n\t) {\n\t\tthrow new Error(\n\t\t\t`Provider ${providerId}: must specify \"baseUrl\", \"headers\", \"compat\", \"modelOverrides\", or \"models\".`,\n\t\t);\n\t}\n\n\tconst models: Model[] = baseModels.map((model) => ({\n\t\t...model,\n\t\tbaseUrl: config.oauth === \"radius\" ? model.baseUrl : (config.baseUrl ?? model.baseUrl),\n\t\tcompat: mergeCompat(model.compat, config.compat),\n\t}));\n\tfor (const definition of config.models ?? []) {\n\t\tconst existingIndex = models.findIndex((model) => model.id === definition.id);\n\t\tconst defaults = existingIndex >= 0 ? models[existingIndex] : models[0];\n\t\tconst model = modelFromJson(providerId, definition, config, defaults);\n\t\tif (existingIndex >= 0) models[existingIndex] = model;\n\t\telse models.push(model);\n\t}\n\treturn models;\n}\n\nfunction applyExtension(\n\tproviderId: string,\n\tmodels: readonly Model[],\n\tconfig: ProviderConfigInput | undefined,\n): Model[] {\n\tif (!config) return [...models];\n\tif (!config.models) {\n\t\treturn config.baseUrl ? models.map((model) => ({ ...model, baseUrl: config.baseUrl! })) : [...models];\n\t}\n\treturn config.models.map((definition) => {\n\t\tconst defaults = models.find((model) => model.id === definition.id) ?? models[0];\n\t\tconst api = definition.api ?? config.api ?? defaults?.api;\n\t\tif (!api) {\n\t\t\tthrow new Error(\n\t\t\t\t`Provider ${providerId}, model ${definition.id}: no \"api\" specified. Set at provider or model level.`,\n\t\t\t);\n\t\t}\n\t\tconst baseUrl = definition.baseUrl ?? config.baseUrl ?? defaults?.baseUrl;\n\t\tif (!baseUrl) throw new Error(`Provider ${providerId}: \"baseUrl\" is required when defining custom models.`);\n\t\treturn {\n\t\t\t...definition,\n\t\t\tapi,\n\t\t\tprovider: providerId,\n\t\t\tbaseUrl,\n\t\t\theaders: undefined,\n\t\t};\n\t});\n}\n\nfunction adaptOAuth(config: ExtensionOAuthConfig): OAuthAuth {\n\treturn {\n\t\tname: config.name,\n\t\tlogin: async (callbacks) => {\n\t\t\tconst credential = await config.login({\n\t\t\t\tonAuth: (info) => callbacks.notify({ type: \"auth_url\", ...info }),\n\t\t\t\tonDeviceCode: (info) => callbacks.notify({ type: \"device_code\", ...info }),\n\t\t\t\tonPrompt: (prompt) => callbacks.prompt({ type: \"text\", ...prompt }),\n\t\t\t\tonProgress: (message) => callbacks.notify({ type: \"progress\", message }),\n\t\t\t\tonManualCodeInput: () => callbacks.prompt({ type: \"manual_code\", message: \"Paste the authorization code\" }),\n\t\t\t\tonSelect: (prompt) => callbacks.prompt({ type: \"select\", ...prompt }),\n\t\t\t\tsignal: callbacks.signal,\n\t\t\t});\n\t\t\treturn { ...credential, type: \"oauth\" };\n\t\t},\n\t\trefresh: async (credential) => ({ ...(await config.refreshToken(credential)), type: \"oauth\" }),\n\t\ttoAuth: async (credential) => ({ apiKey: config.getApiKey(credential) }),\n\t};\n}\n\nfunction withConfiguredAuth(\n\tauth: ModelAuth,\n\theaders: Record | undefined,\n\tauthHeader: boolean,\n): ModelAuth {\n\tlet mergedHeaders: ProviderHeaders | undefined =\n\t\tauth.headers || headers ? { ...auth.headers, ...headers } : undefined;\n\tif (authHeader) {\n\t\tif (!auth.apiKey) throw new Error(\"authHeader requires a resolved API key\");\n\t\tmergedHeaders = { ...mergedHeaders, Authorization: `Bearer ${auth.apiKey}` };\n\t}\n\treturn { ...auth, headers: mergedHeaders };\n}\n\nfunction configuredApiKey(\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): string | undefined {\n\treturn extension?.apiKey ?? config?.apiKey;\n}\n\nfunction configuredHeaders(\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): Record | undefined {\n\tif (!config?.headers && !extension?.headers) return undefined;\n\treturn { ...config?.headers, ...extension?.headers };\n}\n\nasync function configContextEnv(\n\tvalues: readonly string[],\n\tctx: AuthContext,\n\texplicit?: Record,\n): Promise | undefined> {\n\tconst env = { ...explicit };\n\tfor (const name of new Set(values.flatMap(getConfigValueEnvVarNames))) {\n\t\tif (env[name] !== undefined) continue;\n\t\tconst value = await ctx.env(name);\n\t\tif (value !== undefined) env[name] = value;\n\t}\n\treturn Object.keys(env).length > 0 ? env : undefined;\n}\n\nfunction composeApiKeyAuth(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): ApiKeyAuth | undefined {\n\tconst inherited = base?.auth.apiKey;\n\tconst rawKey = configuredApiKey(config, extension);\n\tconst oauth = extension?.oauth ?? base?.auth.oauth;\n\t// OAuth-only providers get no fabricated API-key login method.\n\tif (!inherited && rawKey === undefined && oauth) return undefined;\n\tconst rawHeaders = configuredHeaders(config, extension);\n\tconst authHeader = extension?.authHeader ?? config?.authHeader ?? false;\n\treturn {\n\t\tname: inherited?.name ?? \"API key\",\n\t\tlogin:\n\t\t\tinherited?.login ??\n\t\t\t(async (interaction: AuthInteraction) => ({\n\t\t\t\ttype: \"api_key\",\n\t\t\t\tkey: await interaction.prompt({ type: \"secret\", message: \"Enter API key\" }),\n\t\t\t})),\n\t\tcheck: async (input) => {\n\t\t\tif (input.credential) {\n\t\t\t\tif (inherited?.check) return inherited.check(input);\n\t\t\t\tif (input.credential.key) return { type: \"api_key\", source: \"stored credential\" };\n\t\t\t\tconst resolved = await inherited?.resolve(input);\n\t\t\t\treturn resolved ? { type: \"api_key\", source: resolved.source } : undefined;\n\t\t\t}\n\t\t\tif (rawKey !== undefined) {\n\t\t\t\tif (isCommandConfigValue(rawKey)) return { type: \"api_key\", source: \"configured API key\" };\n\t\t\t\tconst envNames = getConfigValueEnvVarNames(rawKey);\n\t\t\t\tfor (const name of envNames) {\n\t\t\t\t\tif ((await input.ctx.env(name)) === undefined) return undefined;\n\t\t\t\t}\n\t\t\t\treturn { type: \"api_key\", source: \"configured API key\" };\n\t\t\t}\n\t\t\tif (inherited?.check) return inherited.check(input);\n\t\t\tconst resolved = await inherited?.resolve(input);\n\t\t\treturn resolved ? { type: \"api_key\", source: resolved.source } : undefined;\n\t\t},\n\t\tresolve: async (input) => {\n\t\t\tlet result: AuthResult | undefined;\n\t\t\tif (input.credential) {\n\t\t\t\tresult = inherited\n\t\t\t\t\t? await inherited.resolve(input)\n\t\t\t\t\t: input.credential.key\n\t\t\t\t\t\t? { auth: { apiKey: input.credential.key }, env: input.credential.env, source: \"stored credential\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t} else if (rawKey !== undefined) {\n\t\t\t\tconst env = await configContextEnv([rawKey], input.ctx);\n\t\t\t\tconst key = resolveConfigValueOrThrow(rawKey, `API key for provider \"${providerId}\"`, env);\n\t\t\t\tresult = inherited\n\t\t\t\t\t? await inherited.resolve({ ...input, credential: { type: \"api_key\", key } })\n\t\t\t\t\t: { auth: { apiKey: key }, source: \"configured API key\" };\n\t\t\t} else {\n\t\t\t\tresult = await inherited?.resolve(input);\n\t\t\t}\n\t\t\tif (!result) return undefined;\n\t\t\tconst explicitEnv = { ...(input.credential?.env ?? {}), ...(result.env ?? {}) };\n\t\t\tconst headerEnv = await configContextEnv(Object.values(rawHeaders ?? {}), input.ctx, explicitEnv);\n\t\t\tconst headers = resolveHeadersOrThrow(rawHeaders, `provider \"${providerId}\"`, headerEnv);\n\t\t\treturn { ...result, auth: withConfiguredAuth(result.auth, headers, authHeader) };\n\t\t},\n\t};\n}\n\nfunction composeOAuthAuth(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): OAuthAuth | undefined {\n\tconst oauth = extension?.oauth ? adaptOAuth(extension.oauth) : base?.auth.oauth;\n\tif (!oauth) return undefined;\n\tconst rawHeaders = configuredHeaders(config, extension);\n\tconst authHeader = extension?.authHeader ?? config?.authHeader ?? false;\n\treturn {\n\t\t...oauth,\n\t\ttoAuth: async (credential) => {\n\t\t\tconst auth = await oauth.toAuth(credential);\n\t\t\tconst env = credential.env;\n\t\t\tconst headers = resolveHeadersOrThrow(\n\t\t\t\trawHeaders,\n\t\t\t\t`provider \"${providerId}\"`,\n\t\t\t\ttypeof env === \"object\" && env !== null ? (env as Record) : undefined,\n\t\t\t);\n\t\t\treturn withConfiguredAuth(auth, headers, authHeader);\n\t\t},\n\t};\n}\n\nfunction rawModelHeaders(\n\tmodel: Model,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): Record | undefined {\n\tconst definition = config?.models?.find((entry) => entry.id === model.id);\n\tconst extensionModel = extension?.models?.find((entry) => entry.id === model.id);\n\tconst headers = {\n\t\t...config?.modelOverrides?.[model.id]?.headers,\n\t\t...definition?.headers,\n\t\t...extensionModel?.headers,\n\t};\n\treturn Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nexport function validateExtensionProvider(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tmodelsConfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput,\n): void {\n\tif (extension.streamSimple && !extension.api) {\n\t\tthrow new Error(`Provider ${providerId}: \"api\" is required when registering streamSimple.`);\n\t}\n\tapplyExtension(providerId, applyModelsJson(providerId, base?.getModels() ?? [], modelsConfig), extension);\n}\n\n/** Compose built-in, models.json, and extension layers without reading credentials. */\nexport function composeModelProvider(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tmodelConfig: ModelConfig,\n\textension: ProviderConfigInput | undefined,\n): Provider {\n\tconst config = modelConfig.getProvider(providerId);\n\tlet extensionOAuthCredential: OAuthCredentials | undefined;\n\tlet refreshedExtensionModels: ProviderConfigInput[\"models\"];\n\tconst currentExtension = (): ProviderConfigInput | undefined =>\n\t\textension && refreshedExtensionModels ? { ...extension, models: refreshedExtensionModels } : extension;\n\t// models.json modelOverrides are the topmost user-config layer: they apply once,\n\t// after custom-model upserts, extension model replacement, and legacy OAuth projection.\n\tconst getModels = () => {\n\t\tlet models = applyExtension(\n\t\t\tproviderId,\n\t\t\tapplyModelsJson(providerId, base?.getModels() ?? [], config),\n\t\t\tcurrentExtension(),\n\t\t);\n\t\tif (extensionOAuthCredential && extension?.oauth?.modifyModels) {\n\t\t\tmodels = extension.oauth.modifyModels(models, extensionOAuthCredential);\n\t\t}\n\t\treturn models.map((model) => {\n\t\t\tconst override = config?.modelOverrides?.[model.id];\n\t\t\treturn override ? applyModelOverride(model, override) : model;\n\t\t});\n\t};\n\t// Validate eagerly so registration/reload reports structural errors immediately.\n\tgetModels();\n\tconst apiKey = composeApiKeyAuth(providerId, base, config, extension);\n\tconst oauth = composeOAuthAuth(providerId, base, config, extension);\n\tif (!apiKey && !oauth) throw new Error(`Provider ${providerId}: no authentication method configured.`);\n\n\tconst supportsBaseApi = (model: Model) => base?.getModels().some((entry) => entry.api === model.api) ?? false;\n\tconst streamWith = (\n\t\tmodel: Model,\n\t\tcontext: Context,\n\t\toptions: StreamOptions | undefined,\n\t\tsimple: boolean,\n\t): AssistantMessageEventStream =>\n\t\tlazyStream(model, async () => {\n\t\t\tif (extension?.streamSimple && model.api === extension.api) {\n\t\t\t\treturn extension.streamSimple(model, context, options as SimpleStreamOptions);\n\t\t\t}\n\t\t\tif (base && supportsBaseApi(model)) {\n\t\t\t\treturn simple\n\t\t\t\t\t? base.streamSimple(model, context, options as SimpleStreamOptions)\n\t\t\t\t\t: base.stream(model, context, options);\n\t\t\t}\n\t\t\tconst api = getApiProvider(model.api);\n\t\t\tif (!api) throw new Error(`No API provider registered for api: ${model.api}`);\n\t\t\treturn simple\n\t\t\t\t? api.streamSimple(model, context, options as SimpleStreamOptions)\n\t\t\t\t: api.stream(model, context, options);\n\t\t});\n\n\treturn {\n\t\tid: providerId,\n\t\tname: extension?.name ?? config?.name ?? base?.name ?? extension?.oauth?.name ?? providerId,\n\t\tbaseUrl: extension?.baseUrl ?? config?.baseUrl ?? base?.baseUrl,\n\t\theaders: base?.headers,\n\t\tauth: { ...(apiKey ? { apiKey } : {}), ...(oauth ? { oauth } : {}) },\n\t\tgetModels,\n\t\trefreshModels:\n\t\t\tbase?.refreshModels || extension?.refreshModels || extension?.oauth?.modifyModels\n\t\t\t\t? async (context) => {\n\t\t\t\t\t\tawait base?.refreshModels?.(context);\n\t\t\t\t\t\tif (extension?.refreshModels) {\n\t\t\t\t\t\t\tconst refreshed = await extension.refreshModels(context);\n\t\t\t\t\t\t\tif (!context.signal?.aborted) {\n\t\t\t\t\t\t\t\t// Validate before publishing the new synchronous list.\n\t\t\t\t\t\t\t\tapplyExtension(providerId, applyModelsJson(providerId, base?.getModels() ?? [], config), {\n\t\t\t\t\t\t\t\t\t...extension,\n\t\t\t\t\t\t\t\t\tmodels: refreshed,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\trefreshedExtensionModels = refreshed;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\textensionOAuthCredential = context.credential?.type === \"oauth\" ? context.credential : undefined;\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\tfilterModels: base?.filterModels\n\t\t\t? (models, credential: Credential | undefined) => base.filterModels!(models, credential)\n\t\t\t: undefined,\n\t\tstream: (model, context, options) => streamWith(model, context, options, false),\n\t\tstreamSimple: (model, context, options) => streamWith(model, context, options, true),\n\t};\n}\n\nexport function resolveConfiguredModelHeaders(\n\tmodel: Model,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n\tenv?: Record,\n): Record | undefined {\n\treturn resolveHeadersOrThrow(\n\t\trawModelHeaders(model, config, extension),\n\t\t`model \"${model.provider}/${model.id}\"`,\n\t\tenv,\n\t);\n}\n\nexport interface CompatibilityRequestConfig {\n\theaders?: ProviderHeaders;\n\tauthHeader: boolean;\n}\n\nexport function resolveCompatibilityRequestConfig(\n\tmodel: Model,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): CompatibilityRequestConfig {\n\tconst configured = resolveHeadersOrThrow(\n\t\t{ ...configuredHeaders(config, extension), ...rawModelHeaders(model, config, extension) },\n\t\t`model \"${model.provider}/${model.id}\"`,\n\t);\n\treturn {\n\t\theaders: model.headers || configured ? { ...model.headers, ...configured } : undefined,\n\t\tauthHeader: extension?.authHeader ?? config?.authHeader ?? false,\n\t};\n}\n\nexport function configuredRequestAuthStatus(\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): AuthStatus | undefined {\n\tconst value = configuredApiKey(config, extension);\n\tif (value === undefined) return undefined;\n\tif (isCommandConfigValue(value)) return { configured: true, source: \"models_json_command\" };\n\tconst names = getConfigValueEnvVarNames(value);\n\tif (names.length > 0) {\n\t\treturn isConfigValueConfigured(value)\n\t\t\t? { configured: true, source: \"environment\", label: names.join(\", \") }\n\t\t\t: { configured: false };\n\t}\n\treturn { configured: true, source: extension?.apiKey !== undefined ? \"fallback\" : \"models_json_key\" };\n}\n"]} \ No newline at end of file diff --git a/dist/core/provider-composer.js b/dist/core/provider-composer.js new file mode 100644 index 0000000..6a9e2ef --- /dev/null +++ b/dist/core/provider-composer.js @@ -0,0 +1,375 @@ +import { lazyStream, } from "@earendil-works/pi-ai"; +import { getApiProvider } from "@earendil-works/pi-ai/compat"; +import { clearConfigValueCache, getConfigValueEnvVarNames, isCommandConfigValue, isConfigValueConfigured, resolveConfigValueOrThrow, resolveHeadersOrThrow, } from "./resolve-config-value.js"; +export const clearApiKeyCache = clearConfigValueCache; +function mergeCompat(base, override) { + if (!override) + return base; + const merged = { ...base, ...override }; + const baseNested = base; + const overrideNested = override; + const mergedNested = merged; + for (const key of ["openRouterRouting", "vercelGatewayRouting", "chatTemplateKwargs"]) { + const baseValue = baseNested?.[key]; + const overrideValue = overrideNested[key]; + if ((typeof baseValue === "object" && baseValue !== null) || + (typeof overrideValue === "object" && overrideValue !== null)) { + mergedNested[key] = { ...baseValue, ...overrideValue }; + } + } + return merged; +} +function applyModelOverride(model, override) { + return { + ...model, + name: override.name ?? model.name, + reasoning: override.reasoning ?? model.reasoning, + thinkingLevelMap: override.thinkingLevelMap + ? { ...model.thinkingLevelMap, ...override.thinkingLevelMap } + : model.thinkingLevelMap, + input: override.input ?? model.input, + cost: override.cost + ? { + input: override.cost.input ?? model.cost.input, + output: override.cost.output ?? model.cost.output, + cacheRead: override.cost.cacheRead ?? model.cost.cacheRead, + cacheWrite: override.cost.cacheWrite ?? model.cost.cacheWrite, + tiers: override.cost.tiers ?? model.cost.tiers, + } + : model.cost, + contextWindow: override.contextWindow ?? model.contextWindow, + maxTokens: override.maxTokens ?? model.maxTokens, + compat: mergeCompat(model.compat, override.compat), + }; +} +function modelFromJson(providerId, definition, providerConfig, defaults) { + const api = definition.api ?? providerConfig.api ?? defaults?.api; + if (!api) { + throw new Error(`Provider ${providerId}, model ${definition.id}: no "api" specified. Set at provider or model level.`); + } + const baseUrl = definition.baseUrl ?? providerConfig.baseUrl ?? defaults?.baseUrl; + if (!baseUrl) + throw new Error(`Provider ${providerId}: "baseUrl" is required when defining custom models.`); + if (definition.contextWindow !== undefined && definition.contextWindow <= 0) { + throw new Error(`Provider ${providerId}, model ${definition.id}: invalid contextWindow`); + } + if (definition.maxTokens !== undefined && definition.maxTokens <= 0) { + throw new Error(`Provider ${providerId}, model ${definition.id}: invalid maxTokens`); + } + return { + id: definition.id, + name: definition.name ?? definition.id, + api: api, + provider: providerId, + baseUrl, + reasoning: definition.reasoning ?? false, + thinkingLevelMap: definition.thinkingLevelMap, + input: (definition.input ?? ["text"]), + cost: definition.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: definition.contextWindow ?? 128000, + maxTokens: definition.maxTokens ?? 16384, + headers: undefined, + compat: mergeCompat(providerConfig.compat, definition.compat), + }; +} +function applyModelsJson(providerId, baseModels, config) { + if (!config) + return [...baseModels]; + if (config.oauth && !config.baseUrl) { + throw new Error(`Provider ${providerId}: "baseUrl" is required when "oauth" is set.`); + } + const hasOverrides = config.modelOverrides && Object.keys(config.modelOverrides).length > 0; + if (!config.models?.length && + !config.baseUrl && + !config.headers && + !config.compat && + !hasOverrides && + !config.apiKey && + !config.oauth && + config.authHeader === undefined) { + throw new Error(`Provider ${providerId}: must specify "baseUrl", "headers", "compat", "modelOverrides", or "models".`); + } + const models = baseModels.map((model) => ({ + ...model, + baseUrl: config.oauth === "radius" ? model.baseUrl : (config.baseUrl ?? model.baseUrl), + compat: mergeCompat(model.compat, config.compat), + })); + for (const definition of config.models ?? []) { + const existingIndex = models.findIndex((model) => model.id === definition.id); + const defaults = existingIndex >= 0 ? models[existingIndex] : models[0]; + const model = modelFromJson(providerId, definition, config, defaults); + if (existingIndex >= 0) + models[existingIndex] = model; + else + models.push(model); + } + return models; +} +function applyExtension(providerId, models, config) { + if (!config) + return [...models]; + if (!config.models) { + return config.baseUrl ? models.map((model) => ({ ...model, baseUrl: config.baseUrl })) : [...models]; + } + return config.models.map((definition) => { + const defaults = models.find((model) => model.id === definition.id) ?? models[0]; + const api = definition.api ?? config.api ?? defaults?.api; + if (!api) { + throw new Error(`Provider ${providerId}, model ${definition.id}: no "api" specified. Set at provider or model level.`); + } + const baseUrl = definition.baseUrl ?? config.baseUrl ?? defaults?.baseUrl; + if (!baseUrl) + throw new Error(`Provider ${providerId}: "baseUrl" is required when defining custom models.`); + return { + ...definition, + api, + provider: providerId, + baseUrl, + headers: undefined, + }; + }); +} +function adaptOAuth(config) { + return { + name: config.name, + login: async (callbacks) => { + const credential = await config.login({ + onAuth: (info) => callbacks.notify({ type: "auth_url", ...info }), + onDeviceCode: (info) => callbacks.notify({ type: "device_code", ...info }), + onPrompt: (prompt) => callbacks.prompt({ type: "text", ...prompt }), + onProgress: (message) => callbacks.notify({ type: "progress", message }), + onManualCodeInput: () => callbacks.prompt({ type: "manual_code", message: "Paste the authorization code" }), + onSelect: (prompt) => callbacks.prompt({ type: "select", ...prompt }), + signal: callbacks.signal, + }); + return { ...credential, type: "oauth" }; + }, + refresh: async (credential) => ({ ...(await config.refreshToken(credential)), type: "oauth" }), + toAuth: async (credential) => ({ apiKey: config.getApiKey(credential) }), + }; +} +function withConfiguredAuth(auth, headers, authHeader) { + let mergedHeaders = auth.headers || headers ? { ...auth.headers, ...headers } : undefined; + if (authHeader) { + if (!auth.apiKey) + throw new Error("authHeader requires a resolved API key"); + mergedHeaders = { ...mergedHeaders, Authorization: `Bearer ${auth.apiKey}` }; + } + return { ...auth, headers: mergedHeaders }; +} +function configuredApiKey(config, extension) { + return extension?.apiKey ?? config?.apiKey; +} +function configuredHeaders(config, extension) { + if (!config?.headers && !extension?.headers) + return undefined; + return { ...config?.headers, ...extension?.headers }; +} +async function configContextEnv(values, ctx, explicit) { + const env = { ...explicit }; + for (const name of new Set(values.flatMap(getConfigValueEnvVarNames))) { + if (env[name] !== undefined) + continue; + const value = await ctx.env(name); + if (value !== undefined) + env[name] = value; + } + return Object.keys(env).length > 0 ? env : undefined; +} +function composeApiKeyAuth(providerId, base, config, extension) { + const inherited = base?.auth.apiKey; + const rawKey = configuredApiKey(config, extension); + const oauth = extension?.oauth ?? base?.auth.oauth; + // OAuth-only providers get no fabricated API-key login method. + if (!inherited && rawKey === undefined && oauth) + return undefined; + const rawHeaders = configuredHeaders(config, extension); + const authHeader = extension?.authHeader ?? config?.authHeader ?? false; + return { + name: inherited?.name ?? "API key", + login: inherited?.login ?? + (async (interaction) => ({ + type: "api_key", + key: await interaction.prompt({ type: "secret", message: "Enter API key" }), + })), + check: async (input) => { + if (input.credential) { + if (inherited?.check) + return inherited.check(input); + if (input.credential.key) + return { type: "api_key", source: "stored credential" }; + const resolved = await inherited?.resolve(input); + return resolved ? { type: "api_key", source: resolved.source } : undefined; + } + if (rawKey !== undefined) { + if (isCommandConfigValue(rawKey)) + return { type: "api_key", source: "configured API key" }; + const envNames = getConfigValueEnvVarNames(rawKey); + for (const name of envNames) { + if ((await input.ctx.env(name)) === undefined) + return undefined; + } + return { type: "api_key", source: "configured API key" }; + } + if (inherited?.check) + return inherited.check(input); + const resolved = await inherited?.resolve(input); + return resolved ? { type: "api_key", source: resolved.source } : undefined; + }, + resolve: async (input) => { + let result; + if (input.credential) { + result = inherited + ? await inherited.resolve(input) + : input.credential.key + ? { auth: { apiKey: input.credential.key }, env: input.credential.env, source: "stored credential" } + : undefined; + } + else if (rawKey !== undefined) { + const env = await configContextEnv([rawKey], input.ctx); + const key = resolveConfigValueOrThrow(rawKey, `API key for provider "${providerId}"`, env); + result = inherited + ? await inherited.resolve({ ...input, credential: { type: "api_key", key } }) + : { auth: { apiKey: key }, source: "configured API key" }; + } + else { + result = await inherited?.resolve(input); + } + if (!result) + return undefined; + const explicitEnv = { ...(input.credential?.env ?? {}), ...(result.env ?? {}) }; + const headerEnv = await configContextEnv(Object.values(rawHeaders ?? {}), input.ctx, explicitEnv); + const headers = resolveHeadersOrThrow(rawHeaders, `provider "${providerId}"`, headerEnv); + return { ...result, auth: withConfiguredAuth(result.auth, headers, authHeader) }; + }, + }; +} +function composeOAuthAuth(providerId, base, config, extension) { + const oauth = extension?.oauth ? adaptOAuth(extension.oauth) : base?.auth.oauth; + if (!oauth) + return undefined; + const rawHeaders = configuredHeaders(config, extension); + const authHeader = extension?.authHeader ?? config?.authHeader ?? false; + return { + ...oauth, + toAuth: async (credential) => { + const auth = await oauth.toAuth(credential); + const env = credential.env; + const headers = resolveHeadersOrThrow(rawHeaders, `provider "${providerId}"`, typeof env === "object" && env !== null ? env : undefined); + return withConfiguredAuth(auth, headers, authHeader); + }, + }; +} +function rawModelHeaders(model, config, extension) { + const definition = config?.models?.find((entry) => entry.id === model.id); + const extensionModel = extension?.models?.find((entry) => entry.id === model.id); + const headers = { + ...config?.modelOverrides?.[model.id]?.headers, + ...definition?.headers, + ...extensionModel?.headers, + }; + return Object.keys(headers).length > 0 ? headers : undefined; +} +export function validateExtensionProvider(providerId, base, modelsConfig, extension) { + if (extension.streamSimple && !extension.api) { + throw new Error(`Provider ${providerId}: "api" is required when registering streamSimple.`); + } + applyExtension(providerId, applyModelsJson(providerId, base?.getModels() ?? [], modelsConfig), extension); +} +/** Compose built-in, models.json, and extension layers without reading credentials. */ +export function composeModelProvider(providerId, base, modelConfig, extension) { + const config = modelConfig.getProvider(providerId); + let extensionOAuthCredential; + let refreshedExtensionModels; + const currentExtension = () => extension && refreshedExtensionModels ? { ...extension, models: refreshedExtensionModels } : extension; + // models.json modelOverrides are the topmost user-config layer: they apply once, + // after custom-model upserts, extension model replacement, and legacy OAuth projection. + const getModels = () => { + let models = applyExtension(providerId, applyModelsJson(providerId, base?.getModels() ?? [], config), currentExtension()); + if (extensionOAuthCredential && extension?.oauth?.modifyModels) { + models = extension.oauth.modifyModels(models, extensionOAuthCredential); + } + return models.map((model) => { + const override = config?.modelOverrides?.[model.id]; + return override ? applyModelOverride(model, override) : model; + }); + }; + // Validate eagerly so registration/reload reports structural errors immediately. + getModels(); + const apiKey = composeApiKeyAuth(providerId, base, config, extension); + const oauth = composeOAuthAuth(providerId, base, config, extension); + if (!apiKey && !oauth) + throw new Error(`Provider ${providerId}: no authentication method configured.`); + const supportsBaseApi = (model) => base?.getModels().some((entry) => entry.api === model.api) ?? false; + const streamWith = (model, context, options, simple) => lazyStream(model, async () => { + if (extension?.streamSimple && model.api === extension.api) { + return extension.streamSimple(model, context, options); + } + if (base && supportsBaseApi(model)) { + return simple + ? base.streamSimple(model, context, options) + : base.stream(model, context, options); + } + const api = getApiProvider(model.api); + if (!api) + throw new Error(`No API provider registered for api: ${model.api}`); + return simple + ? api.streamSimple(model, context, options) + : api.stream(model, context, options); + }); + return { + id: providerId, + name: extension?.name ?? config?.name ?? base?.name ?? extension?.oauth?.name ?? providerId, + baseUrl: extension?.baseUrl ?? config?.baseUrl ?? base?.baseUrl, + headers: base?.headers, + auth: { ...(apiKey ? { apiKey } : {}), ...(oauth ? { oauth } : {}) }, + getModels, + refreshModels: base?.refreshModels || extension?.refreshModels || extension?.oauth?.modifyModels + ? async (context) => { + await base?.refreshModels?.(context); + if (extension?.refreshModels) { + const refreshed = await extension.refreshModels(context); + if (!context.signal?.aborted) { + // Validate before publishing the new synchronous list. + applyExtension(providerId, applyModelsJson(providerId, base?.getModels() ?? [], config), { + ...extension, + models: refreshed, + }); + refreshedExtensionModels = refreshed; + } + } + extensionOAuthCredential = context.credential?.type === "oauth" ? context.credential : undefined; + } + : undefined, + filterModels: base?.filterModels + ? (models, credential) => base.filterModels(models, credential) + : undefined, + stream: (model, context, options) => streamWith(model, context, options, false), + streamSimple: (model, context, options) => streamWith(model, context, options, true), + }; +} +export function resolveConfiguredModelHeaders(model, config, extension, env) { + return resolveHeadersOrThrow(rawModelHeaders(model, config, extension), `model "${model.provider}/${model.id}"`, env); +} +export function resolveCompatibilityRequestConfig(model, config, extension) { + const configured = resolveHeadersOrThrow({ ...configuredHeaders(config, extension), ...rawModelHeaders(model, config, extension) }, `model "${model.provider}/${model.id}"`); + return { + headers: model.headers || configured ? { ...model.headers, ...configured } : undefined, + authHeader: extension?.authHeader ?? config?.authHeader ?? false, + }; +} +export function configuredRequestAuthStatus(config, extension) { + const value = configuredApiKey(config, extension); + if (value === undefined) + return undefined; + if (isCommandConfigValue(value)) + return { configured: true, source: "models_json_command" }; + const names = getConfigValueEnvVarNames(value); + if (names.length > 0) { + return isConfigValueConfigured(value) + ? { configured: true, source: "environment", label: names.join(", ") } + : { configured: false }; + } + return { configured: true, source: extension?.apiKey !== undefined ? "fallback" : "models_json_key" }; +} +//# sourceMappingURL=provider-composer.js.map \ No newline at end of file diff --git a/dist/core/provider-composer.js.map b/dist/core/provider-composer.js.map new file mode 100644 index 0000000..59f014c --- /dev/null +++ b/dist/core/provider-composer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider-composer.js","sourceRoot":"","sources":["../../src/core/provider-composer.ts"],"names":[],"mappings":"AAAA,OAAO,EASN,UAAU,GAWV,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,EACN,qBAAqB,EACrB,yBAAyB,EACzB,oBAAoB,EACpB,uBAAuB,EACvB,yBAAyB,EACzB,qBAAqB,GACrB,MAAM,2BAA2B,CAAC;AA6CnC,MAAM,CAAC,MAAM,gBAAgB,GAAG,qBAAqB,CAAC;AAEtD,SAAS,WAAW,CACnB,IAA0B,EAC1B,QAAkE,EAC3C;IACvB,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC3B,MAAM,MAAM,GAAG,EAAE,GAAG,IAAI,EAAE,GAAG,QAAQ,EAAuC,CAAC;IAC7E,MAAM,UAAU,GAAG,IAA2C,CAAC;IAC/D,MAAM,cAAc,GAAG,QAAmC,CAAC;IAC3D,MAAM,YAAY,GAAG,MAAiC,CAAC;IACvD,KAAK,MAAM,GAAG,IAAI,CAAC,mBAAmB,EAAE,sBAAsB,EAAE,oBAAoB,CAAU,EAAE,CAAC;QAChG,MAAM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AAO,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,CAAC,OAAO,EAAE,GAAG,UAAU,EAAE,CAAC,CAAC,CAAC,SAAS;QACtF,UAAU,EAAE,SAAS,EAAE,UAAU,IAAI,MAAM,EAAE,UAAU,IAAI,KAAK;KAChE,CAAC;AAAA,CACF;AAED,MAAM,UAAU,2BAA2B,CAC1C,MAAsC,EACtC,SAA0C,EACjB;IACzB,MAAM,KAAK,GAAG,gBAAgB,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IAClD,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC1C,IAAI,oBAAoB,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,qBAAqB,EAAE,CAAC;IAC5F,MAAM,KAAK,GAAG,yBAAyB,CAAC,KAAK,CAAC,CAAC;IAC/C,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACtB,OAAO,uBAAuB,CAAC,KAAK,CAAC;YACpC,CAAC,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,aAAa,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;YACtE,CAAC,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;IAC1B,CAAC;IACD,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,iBAAiB,EAAE,CAAC;AAAA,CACtG","sourcesContent":["import {\n\ttype Api,\n\ttype ApiKeyAuth,\n\ttype AssistantMessageEventStream,\n\ttype AuthContext,\n\ttype AuthInteraction,\n\ttype AuthResult,\n\ttype Context,\n\ttype Credential,\n\tlazyStream,\n\ttype Model,\n\ttype ModelAuth,\n\ttype OAuthAuth,\n\ttype OAuthCredentials,\n\ttype OAuthLoginCallbacks,\n\ttype Provider,\n\ttype ProviderHeaders,\n\ttype RefreshModelsContext,\n\ttype SimpleStreamOptions,\n\ttype StreamOptions,\n} from \"@earendil-works/pi-ai\";\nimport { getApiProvider } from \"@earendil-works/pi-ai/compat\";\nimport type { ModelConfig, ModelsJsonModel, ModelsJsonModelOverride, ModelsJsonProvider } from \"./model-config.ts\";\nimport {\n\tclearConfigValueCache,\n\tgetConfigValueEnvVarNames,\n\tisCommandConfigValue,\n\tisConfigValueConfigured,\n\tresolveConfigValueOrThrow,\n\tresolveHeadersOrThrow,\n} from \"./resolve-config-value.ts\";\n\nexport interface ExtensionOAuthConfig {\n\tname: string;\n\t/** @deprecated Retained for extension source compatibility; ignored by canonical auth flows. */\n\tusesCallbackServer?: boolean;\n\tlogin(callbacks: OAuthLoginCallbacks): Promise;\n\trefreshToken(credentials: OAuthCredentials): Promise;\n\tgetApiKey(credentials: OAuthCredentials): string;\n\tmodifyModels?(models: Model[], credentials: OAuthCredentials): Model[];\n}\n\n/** Input type for the extension registerProvider API. */\nexport interface ProviderConfigInput {\n\tname?: string;\n\tbaseUrl?: string;\n\tapiKey?: string;\n\tapi?: Api;\n\tstreamSimple?: (model: Model, context: Context, options?: SimpleStreamOptions) => AssistantMessageEventStream;\n\theaders?: Record;\n\tauthHeader?: boolean;\n\toauth?: ExtensionOAuthConfig;\n\tmodels?: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tapi?: Api;\n\t\tbaseUrl?: string;\n\t\treasoning: boolean;\n\t\tthinkingLevelMap?: Model[\"thinkingLevelMap\"];\n\t\tinput: (\"text\" | \"image\")[];\n\t\tcost: Model[\"cost\"];\n\t\tcontextWindow: number;\n\t\tmaxTokens: number;\n\t\theaders?: Record;\n\t\tcompat?: Model[\"compat\"];\n\t}>;\n\trefreshModels?(context: RefreshModelsContext): Promise>;\n}\n\nexport type AuthStatus = {\n\tconfigured: boolean;\n\tsource?: \"stored\" | \"runtime\" | \"environment\" | \"fallback\" | \"models_json_key\" | \"models_json_command\";\n\tlabel?: string;\n};\n\nexport const clearApiKeyCache = clearConfigValueCache;\n\nfunction mergeCompat(\n\tbase: Model[\"compat\"],\n\toverride: Model[\"compat\"] | ModelsJsonModelOverride[\"compat\"],\n): Model[\"compat\"] {\n\tif (!override) return base;\n\tconst merged = { ...base, ...override } as NonNullable[\"compat\"]>;\n\tconst baseNested = base as Record | undefined;\n\tconst overrideNested = override as Record;\n\tconst mergedNested = merged as Record;\n\tfor (const key of [\"openRouterRouting\", \"vercelGatewayRouting\", \"chatTemplateKwargs\"] as const) {\n\t\tconst baseValue = baseNested?.[key];\n\t\tconst overrideValue = overrideNested[key];\n\t\tif (\n\t\t\t(typeof baseValue === \"object\" && baseValue !== null) ||\n\t\t\t(typeof overrideValue === \"object\" && overrideValue !== null)\n\t\t) {\n\t\t\tmergedNested[key] = { ...(baseValue as object | undefined), ...(overrideValue as object | undefined) };\n\t\t}\n\t}\n\treturn merged;\n}\n\nfunction applyModelOverride(model: Model, override: ModelsJsonModelOverride): Model {\n\treturn {\n\t\t...model,\n\t\tname: override.name ?? model.name,\n\t\treasoning: override.reasoning ?? model.reasoning,\n\t\tthinkingLevelMap: override.thinkingLevelMap\n\t\t\t? { ...model.thinkingLevelMap, ...override.thinkingLevelMap }\n\t\t\t: model.thinkingLevelMap,\n\t\tinput: (override.input as (\"text\" | \"image\")[] | undefined) ?? model.input,\n\t\tcost: override.cost\n\t\t\t? {\n\t\t\t\t\tinput: override.cost.input ?? model.cost.input,\n\t\t\t\t\toutput: override.cost.output ?? model.cost.output,\n\t\t\t\t\tcacheRead: override.cost.cacheRead ?? model.cost.cacheRead,\n\t\t\t\t\tcacheWrite: override.cost.cacheWrite ?? model.cost.cacheWrite,\n\t\t\t\t\ttiers: override.cost.tiers ?? model.cost.tiers,\n\t\t\t\t}\n\t\t\t: model.cost,\n\t\tcontextWindow: override.contextWindow ?? model.contextWindow,\n\t\tmaxTokens: override.maxTokens ?? model.maxTokens,\n\t\tcompat: mergeCompat(model.compat, override.compat),\n\t};\n}\n\nfunction modelFromJson(\n\tproviderId: string,\n\tdefinition: ModelsJsonModel,\n\tproviderConfig: ModelsJsonProvider,\n\tdefaults: Model | undefined,\n): Model {\n\tconst api = definition.api ?? providerConfig.api ?? defaults?.api;\n\tif (!api) {\n\t\tthrow new Error(\n\t\t\t`Provider ${providerId}, model ${definition.id}: no \"api\" specified. Set at provider or model level.`,\n\t\t);\n\t}\n\tconst baseUrl = definition.baseUrl ?? providerConfig.baseUrl ?? defaults?.baseUrl;\n\tif (!baseUrl) throw new Error(`Provider ${providerId}: \"baseUrl\" is required when defining custom models.`);\n\tif (definition.contextWindow !== undefined && definition.contextWindow <= 0) {\n\t\tthrow new Error(`Provider ${providerId}, model ${definition.id}: invalid contextWindow`);\n\t}\n\tif (definition.maxTokens !== undefined && definition.maxTokens <= 0) {\n\t\tthrow new Error(`Provider ${providerId}, model ${definition.id}: invalid maxTokens`);\n\t}\n\treturn {\n\t\tid: definition.id,\n\t\tname: definition.name ?? definition.id,\n\t\tapi: api as Api,\n\t\tprovider: providerId,\n\t\tbaseUrl,\n\t\treasoning: definition.reasoning ?? false,\n\t\tthinkingLevelMap: definition.thinkingLevelMap,\n\t\tinput: (definition.input ?? [\"text\"]) as (\"text\" | \"image\")[],\n\t\tcost: definition.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: definition.contextWindow ?? 128000,\n\t\tmaxTokens: definition.maxTokens ?? 16384,\n\t\theaders: undefined,\n\t\tcompat: mergeCompat(providerConfig.compat, definition.compat),\n\t};\n}\n\nfunction applyModelsJson(\n\tproviderId: string,\n\tbaseModels: readonly Model[],\n\tconfig: ModelsJsonProvider | undefined,\n): Model[] {\n\tif (!config) return [...baseModels];\n\tif (config.oauth && !config.baseUrl) {\n\t\tthrow new Error(`Provider ${providerId}: \"baseUrl\" is required when \"oauth\" is set.`);\n\t}\n\tconst hasOverrides = config.modelOverrides && Object.keys(config.modelOverrides).length > 0;\n\tif (\n\t\t!config.models?.length &&\n\t\t!config.baseUrl &&\n\t\t!config.headers &&\n\t\t!config.compat &&\n\t\t!hasOverrides &&\n\t\t!config.apiKey &&\n\t\t!config.oauth &&\n\t\tconfig.authHeader === undefined\n\t) {\n\t\tthrow new Error(\n\t\t\t`Provider ${providerId}: must specify \"baseUrl\", \"headers\", \"compat\", \"modelOverrides\", or \"models\".`,\n\t\t);\n\t}\n\n\tconst models: Model[] = baseModels.map((model) => ({\n\t\t...model,\n\t\tbaseUrl: config.oauth === \"radius\" ? model.baseUrl : (config.baseUrl ?? model.baseUrl),\n\t\tcompat: mergeCompat(model.compat, config.compat),\n\t}));\n\tfor (const definition of config.models ?? []) {\n\t\tconst existingIndex = models.findIndex((model) => model.id === definition.id);\n\t\tconst defaults = existingIndex >= 0 ? models[existingIndex] : models[0];\n\t\tconst model = modelFromJson(providerId, definition, config, defaults);\n\t\tif (existingIndex >= 0) models[existingIndex] = model;\n\t\telse models.push(model);\n\t}\n\treturn models;\n}\n\nfunction applyExtension(\n\tproviderId: string,\n\tmodels: readonly Model[],\n\tconfig: ProviderConfigInput | undefined,\n): Model[] {\n\tif (!config) return [...models];\n\tif (!config.models) {\n\t\treturn config.baseUrl ? models.map((model) => ({ ...model, baseUrl: config.baseUrl! })) : [...models];\n\t}\n\treturn config.models.map((definition) => {\n\t\tconst defaults = models.find((model) => model.id === definition.id) ?? models[0];\n\t\tconst api = definition.api ?? config.api ?? defaults?.api;\n\t\tif (!api) {\n\t\t\tthrow new Error(\n\t\t\t\t`Provider ${providerId}, model ${definition.id}: no \"api\" specified. Set at provider or model level.`,\n\t\t\t);\n\t\t}\n\t\tconst baseUrl = definition.baseUrl ?? config.baseUrl ?? defaults?.baseUrl;\n\t\tif (!baseUrl) throw new Error(`Provider ${providerId}: \"baseUrl\" is required when defining custom models.`);\n\t\treturn {\n\t\t\t...definition,\n\t\t\tapi,\n\t\t\tprovider: providerId,\n\t\t\tbaseUrl,\n\t\t\theaders: undefined,\n\t\t};\n\t});\n}\n\nfunction adaptOAuth(config: ExtensionOAuthConfig): OAuthAuth {\n\treturn {\n\t\tname: config.name,\n\t\tlogin: async (callbacks) => {\n\t\t\tconst credential = await config.login({\n\t\t\t\tonAuth: (info) => callbacks.notify({ type: \"auth_url\", ...info }),\n\t\t\t\tonDeviceCode: (info) => callbacks.notify({ type: \"device_code\", ...info }),\n\t\t\t\tonPrompt: (prompt) => callbacks.prompt({ type: \"text\", ...prompt }),\n\t\t\t\tonProgress: (message) => callbacks.notify({ type: \"progress\", message }),\n\t\t\t\tonManualCodeInput: () => callbacks.prompt({ type: \"manual_code\", message: \"Paste the authorization code\" }),\n\t\t\t\tonSelect: (prompt) => callbacks.prompt({ type: \"select\", ...prompt }),\n\t\t\t\tsignal: callbacks.signal,\n\t\t\t});\n\t\t\treturn { ...credential, type: \"oauth\" };\n\t\t},\n\t\trefresh: async (credential) => ({ ...(await config.refreshToken(credential)), type: \"oauth\" }),\n\t\ttoAuth: async (credential) => ({ apiKey: config.getApiKey(credential) }),\n\t};\n}\n\nfunction withConfiguredAuth(\n\tauth: ModelAuth,\n\theaders: Record | undefined,\n\tauthHeader: boolean,\n): ModelAuth {\n\tlet mergedHeaders: ProviderHeaders | undefined =\n\t\tauth.headers || headers ? { ...auth.headers, ...headers } : undefined;\n\tif (authHeader) {\n\t\tif (!auth.apiKey) throw new Error(\"authHeader requires a resolved API key\");\n\t\tmergedHeaders = { ...mergedHeaders, Authorization: `Bearer ${auth.apiKey}` };\n\t}\n\treturn { ...auth, headers: mergedHeaders };\n}\n\nfunction configuredApiKey(\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): string | undefined {\n\treturn extension?.apiKey ?? config?.apiKey;\n}\n\nfunction configuredHeaders(\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): Record | undefined {\n\tif (!config?.headers && !extension?.headers) return undefined;\n\treturn { ...config?.headers, ...extension?.headers };\n}\n\nasync function configContextEnv(\n\tvalues: readonly string[],\n\tctx: AuthContext,\n\texplicit?: Record,\n): Promise | undefined> {\n\tconst env = { ...explicit };\n\tfor (const name of new Set(values.flatMap(getConfigValueEnvVarNames))) {\n\t\tif (env[name] !== undefined) continue;\n\t\tconst value = await ctx.env(name);\n\t\tif (value !== undefined) env[name] = value;\n\t}\n\treturn Object.keys(env).length > 0 ? env : undefined;\n}\n\nfunction composeApiKeyAuth(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): ApiKeyAuth | undefined {\n\tconst inherited = base?.auth.apiKey;\n\tconst rawKey = configuredApiKey(config, extension);\n\tconst oauth = extension?.oauth ?? base?.auth.oauth;\n\t// OAuth-only providers get no fabricated API-key login method.\n\tif (!inherited && rawKey === undefined && oauth) return undefined;\n\tconst rawHeaders = configuredHeaders(config, extension);\n\tconst authHeader = extension?.authHeader ?? config?.authHeader ?? false;\n\treturn {\n\t\tname: inherited?.name ?? \"API key\",\n\t\tlogin:\n\t\t\tinherited?.login ??\n\t\t\t(async (interaction: AuthInteraction) => ({\n\t\t\t\ttype: \"api_key\",\n\t\t\t\tkey: await interaction.prompt({ type: \"secret\", message: \"Enter API key\" }),\n\t\t\t})),\n\t\tcheck: async (input) => {\n\t\t\tif (input.credential) {\n\t\t\t\tif (inherited?.check) return inherited.check(input);\n\t\t\t\tif (input.credential.key) return { type: \"api_key\", source: \"stored credential\" };\n\t\t\t\tconst resolved = await inherited?.resolve(input);\n\t\t\t\treturn resolved ? { type: \"api_key\", source: resolved.source } : undefined;\n\t\t\t}\n\t\t\tif (rawKey !== undefined) {\n\t\t\t\tif (isCommandConfigValue(rawKey)) return { type: \"api_key\", source: \"configured API key\" };\n\t\t\t\tconst envNames = getConfigValueEnvVarNames(rawKey);\n\t\t\t\tfor (const name of envNames) {\n\t\t\t\t\tif ((await input.ctx.env(name)) === undefined) return undefined;\n\t\t\t\t}\n\t\t\t\treturn { type: \"api_key\", source: \"configured API key\" };\n\t\t\t}\n\t\t\tif (inherited?.check) return inherited.check(input);\n\t\t\tconst resolved = await inherited?.resolve(input);\n\t\t\treturn resolved ? { type: \"api_key\", source: resolved.source } : undefined;\n\t\t},\n\t\tresolve: async (input) => {\n\t\t\tlet result: AuthResult | undefined;\n\t\t\tif (input.credential) {\n\t\t\t\tresult = inherited\n\t\t\t\t\t? await inherited.resolve(input)\n\t\t\t\t\t: input.credential.key\n\t\t\t\t\t\t? { auth: { apiKey: input.credential.key }, env: input.credential.env, source: \"stored credential\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t} else if (rawKey !== undefined) {\n\t\t\t\tconst env = await configContextEnv([rawKey], input.ctx);\n\t\t\t\tconst key = resolveConfigValueOrThrow(rawKey, `API key for provider \"${providerId}\"`, env);\n\t\t\t\tresult = inherited\n\t\t\t\t\t? await inherited.resolve({ ...input, credential: { type: \"api_key\", key } })\n\t\t\t\t\t: { auth: { apiKey: key }, source: \"configured API key\" };\n\t\t\t} else {\n\t\t\t\tresult = await inherited?.resolve(input);\n\t\t\t}\n\t\t\tif (!result) return undefined;\n\t\t\tconst explicitEnv = { ...(input.credential?.env ?? {}), ...(result.env ?? {}) };\n\t\t\tconst headerEnv = await configContextEnv(Object.values(rawHeaders ?? {}), input.ctx, explicitEnv);\n\t\t\tconst headers = resolveHeadersOrThrow(rawHeaders, `provider \"${providerId}\"`, headerEnv);\n\t\t\treturn { ...result, auth: withConfiguredAuth(result.auth, headers, authHeader) };\n\t\t},\n\t};\n}\n\nfunction composeOAuthAuth(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): OAuthAuth | undefined {\n\tconst oauth = extension?.oauth ? adaptOAuth(extension.oauth) : base?.auth.oauth;\n\tif (!oauth) return undefined;\n\tconst rawHeaders = configuredHeaders(config, extension);\n\tconst authHeader = extension?.authHeader ?? config?.authHeader ?? false;\n\treturn {\n\t\t...oauth,\n\t\ttoAuth: async (credential) => {\n\t\t\tconst auth = await oauth.toAuth(credential);\n\t\t\tconst env = credential.env;\n\t\t\tconst headers = resolveHeadersOrThrow(\n\t\t\t\trawHeaders,\n\t\t\t\t`provider \"${providerId}\"`,\n\t\t\t\ttypeof env === \"object\" && env !== null ? (env as Record) : undefined,\n\t\t\t);\n\t\t\treturn withConfiguredAuth(auth, headers, authHeader);\n\t\t},\n\t};\n}\n\nfunction rawModelHeaders(\n\tmodel: Model,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): Record | undefined {\n\tconst definition = config?.models?.find((entry) => entry.id === model.id);\n\tconst extensionModel = extension?.models?.find((entry) => entry.id === model.id);\n\tconst headers = {\n\t\t...config?.modelOverrides?.[model.id]?.headers,\n\t\t...definition?.headers,\n\t\t...extensionModel?.headers,\n\t};\n\treturn Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nexport function validateExtensionProvider(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tmodelsConfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput,\n): void {\n\tif (extension.streamSimple && !extension.api) {\n\t\tthrow new Error(`Provider ${providerId}: \"api\" is required when registering streamSimple.`);\n\t}\n\tapplyExtension(providerId, applyModelsJson(providerId, base?.getModels() ?? [], modelsConfig), extension);\n}\n\n/** Compose built-in, models.json, and extension layers without reading credentials. */\nexport function composeModelProvider(\n\tproviderId: string,\n\tbase: Provider | undefined,\n\tmodelConfig: ModelConfig,\n\textension: ProviderConfigInput | undefined,\n): Provider {\n\tconst config = modelConfig.getProvider(providerId);\n\tlet extensionOAuthCredential: OAuthCredentials | undefined;\n\tlet refreshedExtensionModels: ProviderConfigInput[\"models\"];\n\tconst currentExtension = (): ProviderConfigInput | undefined =>\n\t\textension && refreshedExtensionModels ? { ...extension, models: refreshedExtensionModels } : extension;\n\t// models.json modelOverrides are the topmost user-config layer: they apply once,\n\t// after custom-model upserts, extension model replacement, and legacy OAuth projection.\n\tconst getModels = () => {\n\t\tlet models = applyExtension(\n\t\t\tproviderId,\n\t\t\tapplyModelsJson(providerId, base?.getModels() ?? [], config),\n\t\t\tcurrentExtension(),\n\t\t);\n\t\tif (extensionOAuthCredential && extension?.oauth?.modifyModels) {\n\t\t\tmodels = extension.oauth.modifyModels(models, extensionOAuthCredential);\n\t\t}\n\t\treturn models.map((model) => {\n\t\t\tconst override = config?.modelOverrides?.[model.id];\n\t\t\treturn override ? applyModelOverride(model, override) : model;\n\t\t});\n\t};\n\t// Validate eagerly so registration/reload reports structural errors immediately.\n\tgetModels();\n\tconst apiKey = composeApiKeyAuth(providerId, base, config, extension);\n\tconst oauth = composeOAuthAuth(providerId, base, config, extension);\n\tif (!apiKey && !oauth) throw new Error(`Provider ${providerId}: no authentication method configured.`);\n\n\tconst supportsBaseApi = (model: Model) => base?.getModels().some((entry) => entry.api === model.api) ?? false;\n\tconst streamWith = (\n\t\tmodel: Model,\n\t\tcontext: Context,\n\t\toptions: StreamOptions | undefined,\n\t\tsimple: boolean,\n\t): AssistantMessageEventStream =>\n\t\tlazyStream(model, async () => {\n\t\t\tif (extension?.streamSimple && model.api === extension.api) {\n\t\t\t\treturn extension.streamSimple(model, context, options as SimpleStreamOptions);\n\t\t\t}\n\t\t\tif (base && supportsBaseApi(model)) {\n\t\t\t\treturn simple\n\t\t\t\t\t? base.streamSimple(model, context, options as SimpleStreamOptions)\n\t\t\t\t\t: base.stream(model, context, options);\n\t\t\t}\n\t\t\tconst api = getApiProvider(model.api);\n\t\t\tif (!api) throw new Error(`No API provider registered for api: ${model.api}`);\n\t\t\treturn simple\n\t\t\t\t? api.streamSimple(model, context, options as SimpleStreamOptions)\n\t\t\t\t: api.stream(model, context, options);\n\t\t});\n\n\treturn {\n\t\tid: providerId,\n\t\tname: extension?.name ?? config?.name ?? base?.name ?? extension?.oauth?.name ?? providerId,\n\t\tbaseUrl: extension?.baseUrl ?? config?.baseUrl ?? base?.baseUrl,\n\t\theaders: base?.headers,\n\t\tauth: { ...(apiKey ? { apiKey } : {}), ...(oauth ? { oauth } : {}) },\n\t\tgetModels,\n\t\trefreshModels:\n\t\t\tbase?.refreshModels || extension?.refreshModels || extension?.oauth?.modifyModels\n\t\t\t\t? async (context) => {\n\t\t\t\t\t\tawait base?.refreshModels?.(context);\n\t\t\t\t\t\tif (extension?.refreshModels) {\n\t\t\t\t\t\t\tconst refreshed = await extension.refreshModels(context);\n\t\t\t\t\t\t\tif (!context.signal?.aborted) {\n\t\t\t\t\t\t\t\t// Validate before publishing the new synchronous list.\n\t\t\t\t\t\t\t\tapplyExtension(providerId, applyModelsJson(providerId, base?.getModels() ?? [], config), {\n\t\t\t\t\t\t\t\t\t...extension,\n\t\t\t\t\t\t\t\t\tmodels: refreshed,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\trefreshedExtensionModels = refreshed;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\textensionOAuthCredential = context.credential?.type === \"oauth\" ? context.credential : undefined;\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\tfilterModels: base?.filterModels\n\t\t\t? (models, credential: Credential | undefined) => base.filterModels!(models, credential)\n\t\t\t: undefined,\n\t\tstream: (model, context, options) => streamWith(model, context, options, false),\n\t\tstreamSimple: (model, context, options) => streamWith(model, context, options, true),\n\t};\n}\n\nexport function resolveConfiguredModelHeaders(\n\tmodel: Model,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n\tenv?: Record,\n): Record | undefined {\n\treturn resolveHeadersOrThrow(\n\t\trawModelHeaders(model, config, extension),\n\t\t`model \"${model.provider}/${model.id}\"`,\n\t\tenv,\n\t);\n}\n\nexport interface CompatibilityRequestConfig {\n\theaders?: ProviderHeaders;\n\tauthHeader: boolean;\n}\n\nexport function resolveCompatibilityRequestConfig(\n\tmodel: Model,\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): CompatibilityRequestConfig {\n\tconst configured = resolveHeadersOrThrow(\n\t\t{ ...configuredHeaders(config, extension), ...rawModelHeaders(model, config, extension) },\n\t\t`model \"${model.provider}/${model.id}\"`,\n\t);\n\treturn {\n\t\theaders: model.headers || configured ? { ...model.headers, ...configured } : undefined,\n\t\tauthHeader: extension?.authHeader ?? config?.authHeader ?? false,\n\t};\n}\n\nexport function configuredRequestAuthStatus(\n\tconfig: ModelsJsonProvider | undefined,\n\textension: ProviderConfigInput | undefined,\n): AuthStatus | undefined {\n\tconst value = configuredApiKey(config, extension);\n\tif (value === undefined) return undefined;\n\tif (isCommandConfigValue(value)) return { configured: true, source: \"models_json_command\" };\n\tconst names = getConfigValueEnvVarNames(value);\n\tif (names.length > 0) {\n\t\treturn isConfigValueConfigured(value)\n\t\t\t? { configured: true, source: \"environment\", label: names.join(\", \") }\n\t\t\t: { configured: false };\n\t}\n\treturn { configured: true, source: extension?.apiKey !== undefined ? \"fallback\" : \"models_json_key\" };\n}\n"]} \ No newline at end of file diff --git a/dist/core/radius.d.ts b/dist/core/radius.d.ts new file mode 100644 index 0000000..9cfb445 --- /dev/null +++ b/dist/core/radius.d.ts @@ -0,0 +1,2 @@ +export declare const RADIUS_PROVIDER_ID = "radius"; +//# sourceMappingURL=radius.d.ts.map \ No newline at end of file diff --git a/dist/core/radius.d.ts.map b/dist/core/radius.d.ts.map new file mode 100644 index 0000000..0e9c048 --- /dev/null +++ b/dist/core/radius.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"radius.d.ts","sourceRoot":"","sources":["../../src/core/radius.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,kBAAkB,WAAW,CAAC","sourcesContent":["export const RADIUS_PROVIDER_ID = \"radius\";\n"]} \ No newline at end of file diff --git a/dist/core/radius.js b/dist/core/radius.js new file mode 100644 index 0000000..3f6fe07 --- /dev/null +++ b/dist/core/radius.js @@ -0,0 +1,2 @@ +export const RADIUS_PROVIDER_ID = "radius"; +//# sourceMappingURL=radius.js.map \ No newline at end of file diff --git a/dist/core/radius.js.map b/dist/core/radius.js.map new file mode 100644 index 0000000..7cc7e42 --- /dev/null +++ b/dist/core/radius.js.map @@ -0,0 +1 @@ +{"version":3,"file":"radius.js","sourceRoot":"","sources":["../../src/core/radius.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,kBAAkB,GAAG,QAAQ,CAAC","sourcesContent":["export const RADIUS_PROVIDER_ID = \"radius\";\n"]} \ No newline at end of file diff --git a/dist/core/remote-catalog-provider.d.ts b/dist/core/remote-catalog-provider.d.ts new file mode 100644 index 0000000..53b3bda --- /dev/null +++ b/dist/core/remote-catalog-provider.d.ts @@ -0,0 +1,5 @@ +import type { Provider } from "@earendil-works/pi-ai"; +export declare const REMOTE_CATALOG_REFRESH_INTERVAL_MS: number; +/** Add a persisted pi.dev catalog overlay to a static built-in provider. */ +export declare function withRemoteCatalog(provider: Provider, catalogBaseUrl?: string, localGeneratedAt?: number): Provider; +//# sourceMappingURL=remote-catalog-provider.d.ts.map \ No newline at end of file diff --git a/dist/core/remote-catalog-provider.d.ts.map b/dist/core/remote-catalog-provider.d.ts.map new file mode 100644 index 0000000..06e4f42 --- /dev/null +++ b/dist/core/remote-catalog-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"remote-catalog-provider.d.ts","sourceRoot":"","sources":["../../src/core/remote-catalog-provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgC,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAKpF,eAAO,MAAM,kCAAkC,QAAqB,CAAC;AAqCrE,4EAA4E;AAC5E,wBAAgB,iBAAiB,CAChC,QAAQ,EAAE,QAAQ,EAClB,cAAc,GAAE,MAAiC,EACjD,gBAAgB,CAAC,EAAE,MAAM,GACvB,QAAQ,CA2EV","sourcesContent":["import type { Api, Model, ModelsStoreEntry, Provider } from \"@earendil-works/pi-ai\";\nimport { VERSION } from \"../config.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\n\nconst DEFAULT_CATALOG_BASE_URL = \"https://pi.dev\";\nexport const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000;\n\nfunction mergeModels(baseline: readonly Model[], dynamic: readonly Model[]): Model[] {\n\tconst merged = [...baseline];\n\tfor (const model of dynamic) {\n\t\tconst index = merged.findIndex((entry) => entry.id === model.id);\n\t\tif (index >= 0) merged[index] = model;\n\t\telse merged.push(model);\n\t}\n\treturn merged;\n}\n\nfunction parseCatalog(providerId: string, value: unknown): Model[] {\n\tconst entries = Array.isArray(value)\n\t\t? value\n\t\t: typeof value === \"object\" && value !== null && \"models\" in value && Array.isArray(value.models)\n\t\t\t? value.models\n\t\t\t: typeof value === \"object\" && value !== null\n\t\t\t\t? Object.values(value)\n\t\t\t\t: undefined;\n\tif (!entries) throw new Error(`Invalid model catalog for provider \"${providerId}\"`);\n\treturn entries\n\t\t.filter((entry): entry is Model => typeof entry === \"object\" && entry !== null && \"id\" in entry)\n\t\t.map((model) => ({ ...model, provider: providerId }));\n}\n\nfunction remoteModels(\n\tentry: ModelsStoreEntry | undefined,\n\tlocalGeneratedAt: number | undefined,\n): readonly Model[] {\n\tif (!entry) return [];\n\tif (localGeneratedAt !== undefined && (entry.lastModified === undefined || entry.lastModified <= localGeneratedAt)) {\n\t\treturn [];\n\t}\n\treturn entry.models;\n}\n\n/** Add a persisted pi.dev catalog overlay to a static built-in provider. */\nexport function withRemoteCatalog(\n\tprovider: Provider,\n\tcatalogBaseUrl: string = DEFAULT_CATALOG_BASE_URL,\n\tlocalGeneratedAt?: number,\n): Provider {\n\tlet dynamicModels: readonly Model[] = [];\n\tlet inflightRefresh: Promise | undefined;\n\n\treturn {\n\t\t...provider,\n\t\tgetModels: () => mergeModels(provider.getModels(), dynamicModels),\n\t\trefreshModels: (context) => {\n\t\t\tinflightRefresh ??= (async () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst stored = await context.store.read();\n\t\t\t\t\tdynamicModels = remoteModels(stored, localGeneratedAt).filter((model) => model.provider === provider.id);\n\t\t\t\t\tif (!context.allowNetwork || context.signal?.aborted) return;\n\t\t\t\t\tif (\n\t\t\t\t\t\t!context.force &&\n\t\t\t\t\t\tstored?.checkedAt !== undefined &&\n\t\t\t\t\t\tstored.lastModified !== undefined &&\n\t\t\t\t\t\tDate.now() - stored.checkedAt < REMOTE_CATALOG_REFRESH_INTERVAL_MS\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Only revalidate when a cached body backs the validator, so a 304 can never\n\t\t\t\t\t// leave the overlay empty.\n\t\t\t\t\tconst validator = stored?.models.length ? stored.etag : undefined;\n\t\t\t\t\tconst url = new URL(`/api/models/providers/${encodeURIComponent(provider.id)}`, catalogBaseUrl);\n\t\t\t\t\tconst response = await fetch(url, {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\t\t\"User-Agent\": getPiUserAgent(VERSION),\n\t\t\t\t\t\t\t...(validator ? { \"if-none-match\": validator } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsignal: context.signal,\n\t\t\t\t\t});\n\t\t\t\t\tif (context.signal?.aborted) return;\n\t\t\t\t\tconst checkedAt = Date.now();\n\t\t\t\t\t// Unchanged: dynamicModels already holds the stored overlay, so only the\n\t\t\t\t\t// freshness window moves.\n\t\t\t\t\tif (response.status === 304 && stored) {\n\t\t\t\t\t\tawait context.store.write({ ...stored, checkedAt });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (response.status === 404 || response.status === 501) {\n\t\t\t\t\t\tawait context.store.write({\n\t\t\t\t\t\t\t...(stored ?? { models: [] }),\n\t\t\t\t\t\t\tcheckedAt,\n\t\t\t\t\t\t\tlastModified: 0,\n\t\t\t\t\t\t\tetag: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t// Transient failure: the cached body and its validator stay valid, so keep the\n\t\t\t\t\t\t// etag and let the next refresh revalidate instead of downloading the catalog.\n\t\t\t\t\t\tawait context.store.write({ ...(stored ?? { models: [] }), checkedAt });\n\t\t\t\t\t\tthrow new Error(`Model catalog request failed for ${provider.id}: ${response.status}`);\n\t\t\t\t\t}\n\t\t\t\t\tconst refreshed = parseCatalog(provider.id, await response.json());\n\t\t\t\t\tconst lastModified = Date.parse(response.headers.get(\"last-modified\") ?? \"\");\n\t\t\t\t\tif (context.signal?.aborted) return;\n\t\t\t\t\tconst entry = {\n\t\t\t\t\t\tmodels: refreshed,\n\t\t\t\t\t\tcheckedAt,\n\t\t\t\t\t\tlastModified: Number.isNaN(lastModified) ? 0 : lastModified,\n\t\t\t\t\t\tetag: response.headers.get(\"etag\") ?? undefined,\n\t\t\t\t\t};\n\t\t\t\t\tdynamicModels = remoteModels(entry, localGeneratedAt);\n\t\t\t\t\tawait context.store.write(entry);\n\t\t\t\t} finally {\n\t\t\t\t\tinflightRefresh = undefined;\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn inflightRefresh;\n\t\t},\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/remote-catalog-provider.js b/dist/core/remote-catalog-provider.js new file mode 100644 index 0000000..b24ad98 --- /dev/null +++ b/dist/core/remote-catalog-provider.js @@ -0,0 +1,115 @@ +import { VERSION } from "../config.js"; +import { getPiUserAgent } from "../utils/pi-user-agent.js"; +const DEFAULT_CATALOG_BASE_URL = "https://pi.dev"; +export const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000; +function mergeModels(baseline, dynamic) { + const merged = [...baseline]; + for (const model of dynamic) { + const index = merged.findIndex((entry) => entry.id === model.id); + if (index >= 0) + merged[index] = model; + else + merged.push(model); + } + return merged; +} +function parseCatalog(providerId, value) { + const entries = Array.isArray(value) + ? value + : typeof value === "object" && value !== null && "models" in value && Array.isArray(value.models) + ? value.models + : typeof value === "object" && value !== null + ? Object.values(value) + : undefined; + if (!entries) + throw new Error(`Invalid model catalog for provider "${providerId}"`); + return entries + .filter((entry) => typeof entry === "object" && entry !== null && "id" in entry) + .map((model) => ({ ...model, provider: providerId })); +} +function remoteModels(entry, localGeneratedAt) { + if (!entry) + return []; + if (localGeneratedAt !== undefined && (entry.lastModified === undefined || entry.lastModified <= localGeneratedAt)) { + return []; + } + return entry.models; +} +/** Add a persisted pi.dev catalog overlay to a static built-in provider. */ +export function withRemoteCatalog(provider, catalogBaseUrl = DEFAULT_CATALOG_BASE_URL, localGeneratedAt) { + let dynamicModels = []; + let inflightRefresh; + return { + ...provider, + getModels: () => mergeModels(provider.getModels(), dynamicModels), + refreshModels: (context) => { + inflightRefresh ??= (async () => { + try { + const stored = await context.store.read(); + dynamicModels = remoteModels(stored, localGeneratedAt).filter((model) => model.provider === provider.id); + if (!context.allowNetwork || context.signal?.aborted) + return; + if (!context.force && + stored?.checkedAt !== undefined && + stored.lastModified !== undefined && + Date.now() - stored.checkedAt < REMOTE_CATALOG_REFRESH_INTERVAL_MS) { + return; + } + // Only revalidate when a cached body backs the validator, so a 304 can never + // leave the overlay empty. + const validator = stored?.models.length ? stored.etag : undefined; + const url = new URL(`/api/models/providers/${encodeURIComponent(provider.id)}`, catalogBaseUrl); + const response = await fetch(url, { + headers: { + accept: "application/json", + "User-Agent": getPiUserAgent(VERSION), + ...(validator ? { "if-none-match": validator } : {}), + }, + signal: context.signal, + }); + if (context.signal?.aborted) + return; + const checkedAt = Date.now(); + // Unchanged: dynamicModels already holds the stored overlay, so only the + // freshness window moves. + if (response.status === 304 && stored) { + await context.store.write({ ...stored, checkedAt }); + return; + } + if (response.status === 404 || response.status === 501) { + await context.store.write({ + ...(stored ?? { models: [] }), + checkedAt, + lastModified: 0, + etag: undefined, + }); + return; + } + if (!response.ok) { + // Transient failure: the cached body and its validator stay valid, so keep the + // etag and let the next refresh revalidate instead of downloading the catalog. + await context.store.write({ ...(stored ?? { models: [] }), checkedAt }); + throw new Error(`Model catalog request failed for ${provider.id}: ${response.status}`); + } + const refreshed = parseCatalog(provider.id, await response.json()); + const lastModified = Date.parse(response.headers.get("last-modified") ?? ""); + if (context.signal?.aborted) + return; + const entry = { + models: refreshed, + checkedAt, + lastModified: Number.isNaN(lastModified) ? 0 : lastModified, + etag: response.headers.get("etag") ?? undefined, + }; + dynamicModels = remoteModels(entry, localGeneratedAt); + await context.store.write(entry); + } + finally { + inflightRefresh = undefined; + } + })(); + return inflightRefresh; + }, + }; +} +//# sourceMappingURL=remote-catalog-provider.js.map \ No newline at end of file diff --git a/dist/core/remote-catalog-provider.js.map b/dist/core/remote-catalog-provider.js.map new file mode 100644 index 0000000..173a53c --- /dev/null +++ b/dist/core/remote-catalog-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remote-catalog-provider.js","sourceRoot":"","sources":["../../src/core/remote-catalog-provider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAE3D,MAAM,wBAAwB,GAAG,gBAAgB,CAAC;AAClD,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAErE,SAAS,WAAW,CAAC,QAA+B,EAAE,OAA8B,EAAgB;IACnG,MAAM,MAAM,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAC;IAC7B,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,KAAK,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,KAAK,CAAC,EAAE,CAAC,CAAC;QACjE,IAAI,KAAK,IAAI,CAAC;YAAE,MAAM,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;;YACjC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IACD,OAAO,MAAM,CAAC;AAAA,CACd;AAED,SAAS,YAAY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,CAAC,EAAE,EAAE,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;oBACnE,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,EAAE,CAAC,CAAC;oBAC7E,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO;wBAAE,OAAO;oBACpC,MAAM,KAAK,GAAG;wBACb,MAAM,EAAE,SAAS;wBACjB,SAAS;wBACT,YAAY,EAAE,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY;wBAC3D,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,SAAS;qBAC/C,CAAC;oBACF,aAAa,GAAG,YAAY,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC;oBACtD,MAAM,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBAClC,CAAC;wBAAS,CAAC;oBACV,eAAe,GAAG,SAAS,CAAC;gBAC7B,CAAC;YAAA,CACD,CAAC,EAAE,CAAC;YACL,OAAO,eAAe,CAAC;QAAA,CACvB;KACD,CAAC;AAAA,CACF","sourcesContent":["import type { Api, Model, ModelsStoreEntry, Provider } from \"@earendil-works/pi-ai\";\nimport { VERSION } from \"../config.ts\";\nimport { getPiUserAgent } from \"../utils/pi-user-agent.ts\";\n\nconst DEFAULT_CATALOG_BASE_URL = \"https://pi.dev\";\nexport const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000;\n\nfunction mergeModels(baseline: readonly Model[], dynamic: readonly Model[]): Model[] {\n\tconst merged = [...baseline];\n\tfor (const model of dynamic) {\n\t\tconst index = merged.findIndex((entry) => entry.id === model.id);\n\t\tif (index >= 0) merged[index] = model;\n\t\telse merged.push(model);\n\t}\n\treturn merged;\n}\n\nfunction parseCatalog(providerId: string, value: unknown): Model[] {\n\tconst entries = Array.isArray(value)\n\t\t? value\n\t\t: typeof value === \"object\" && value !== null && \"models\" in value && Array.isArray(value.models)\n\t\t\t? value.models\n\t\t\t: typeof value === \"object\" && value !== null\n\t\t\t\t? Object.values(value)\n\t\t\t\t: undefined;\n\tif (!entries) throw new Error(`Invalid model catalog for provider \"${providerId}\"`);\n\treturn entries\n\t\t.filter((entry): entry is Model => typeof entry === \"object\" && entry !== null && \"id\" in entry)\n\t\t.map((model) => ({ ...model, provider: providerId }));\n}\n\nfunction remoteModels(\n\tentry: ModelsStoreEntry | undefined,\n\tlocalGeneratedAt: number | undefined,\n): readonly Model[] {\n\tif (!entry) return [];\n\tif (localGeneratedAt !== undefined && (entry.lastModified === undefined || entry.lastModified <= localGeneratedAt)) {\n\t\treturn [];\n\t}\n\treturn entry.models;\n}\n\n/** Add a persisted pi.dev catalog overlay to a static built-in provider. */\nexport function withRemoteCatalog(\n\tprovider: Provider,\n\tcatalogBaseUrl: string = DEFAULT_CATALOG_BASE_URL,\n\tlocalGeneratedAt?: number,\n): Provider {\n\tlet dynamicModels: readonly Model[] = [];\n\tlet inflightRefresh: Promise | undefined;\n\n\treturn {\n\t\t...provider,\n\t\tgetModels: () => mergeModels(provider.getModels(), dynamicModels),\n\t\trefreshModels: (context) => {\n\t\t\tinflightRefresh ??= (async () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst stored = await context.store.read();\n\t\t\t\t\tdynamicModels = remoteModels(stored, localGeneratedAt).filter((model) => model.provider === provider.id);\n\t\t\t\t\tif (!context.allowNetwork || context.signal?.aborted) return;\n\t\t\t\t\tif (\n\t\t\t\t\t\t!context.force &&\n\t\t\t\t\t\tstored?.checkedAt !== undefined &&\n\t\t\t\t\t\tstored.lastModified !== undefined &&\n\t\t\t\t\t\tDate.now() - stored.checkedAt < REMOTE_CATALOG_REFRESH_INTERVAL_MS\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Only revalidate when a cached body backs the validator, so a 304 can never\n\t\t\t\t\t// leave the overlay empty.\n\t\t\t\t\tconst validator = stored?.models.length ? stored.etag : undefined;\n\t\t\t\t\tconst url = new URL(`/api/models/providers/${encodeURIComponent(provider.id)}`, catalogBaseUrl);\n\t\t\t\t\tconst response = await fetch(url, {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\t\t\"User-Agent\": getPiUserAgent(VERSION),\n\t\t\t\t\t\t\t...(validator ? { \"if-none-match\": validator } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsignal: context.signal,\n\t\t\t\t\t});\n\t\t\t\t\tif (context.signal?.aborted) return;\n\t\t\t\t\tconst checkedAt = Date.now();\n\t\t\t\t\t// Unchanged: dynamicModels already holds the stored overlay, so only the\n\t\t\t\t\t// freshness window moves.\n\t\t\t\t\tif (response.status === 304 && stored) {\n\t\t\t\t\t\tawait context.store.write({ ...stored, checkedAt });\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (response.status === 404 || response.status === 501) {\n\t\t\t\t\t\tawait context.store.write({\n\t\t\t\t\t\t\t...(stored ?? { models: [] }),\n\t\t\t\t\t\t\tcheckedAt,\n\t\t\t\t\t\t\tlastModified: 0,\n\t\t\t\t\t\t\tetag: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t// Transient failure: the cached body and its validator stay valid, so keep the\n\t\t\t\t\t\t// etag and let the next refresh revalidate instead of downloading the catalog.\n\t\t\t\t\t\tawait context.store.write({ ...(stored ?? { models: [] }), checkedAt });\n\t\t\t\t\t\tthrow new Error(`Model catalog request failed for ${provider.id}: ${response.status}`);\n\t\t\t\t\t}\n\t\t\t\t\tconst refreshed = parseCatalog(provider.id, await response.json());\n\t\t\t\t\tconst lastModified = Date.parse(response.headers.get(\"last-modified\") ?? \"\");\n\t\t\t\t\tif (context.signal?.aborted) return;\n\t\t\t\t\tconst entry = {\n\t\t\t\t\t\tmodels: refreshed,\n\t\t\t\t\t\tcheckedAt,\n\t\t\t\t\t\tlastModified: Number.isNaN(lastModified) ? 0 : lastModified,\n\t\t\t\t\t\tetag: response.headers.get(\"etag\") ?? undefined,\n\t\t\t\t\t};\n\t\t\t\t\tdynamicModels = remoteModels(entry, localGeneratedAt);\n\t\t\t\t\tawait context.store.write(entry);\n\t\t\t\t} finally {\n\t\t\t\t\tinflightRefresh = undefined;\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn inflightRefresh;\n\t\t},\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/resolve-config-value.d.ts b/dist/core/resolve-config-value.d.ts new file mode 100644 index 0000000..ecb4722 --- /dev/null +++ b/dist/core/resolve-config-value.d.ts @@ -0,0 +1,30 @@ +/** + * Resolve configuration values that may be shell commands, environment variables, or literals. + * Used by auth-storage.ts and model-registry.ts. + */ +export declare function getConfigValueEnvVarName(config: string): string | undefined; +export declare function getConfigValueEnvVarNames(config: string): string[]; +export declare function getMissingConfigValueEnvVarNames(config: string, env?: Record): string[]; +export declare function isCommandConfigValue(config: string): boolean; +export declare function isConfigValueConfigured(config: string, env?: Record): boolean; +/** + * Resolve a config value (API key, header value, etc.) to an actual value. + * - If starts with "!", executes the rest as a shell command and uses stdout (cached) + * - Interpolates "$ENV_VAR" or "${ENV_VAR}" references with the named environment variable + * - In non-command values, "$$" escapes a literal "$" and "$!" escapes a literal "!" + * - Otherwise treats the value as a literal + */ +export declare function resolveConfigValue(config: string, env?: Record): string | undefined; +/** + * Resolve all header values using the same resolution logic as API keys. + */ +export declare function resolveConfigValueUncached(config: string, env?: Record): string | undefined; +export declare function resolveConfigValueOrThrow(config: string, description: string, env?: Record): string; +/** + * Resolve all header values using the same resolution logic as API keys. + */ +export declare function resolveHeaders(headers: Record | undefined, env?: Record): Record | undefined; +export declare function resolveHeadersOrThrow(headers: Record | undefined, description: string, env?: Record): Record | undefined; +/** Clear the config value command cache. Exported for testing. */ +export declare function clearConfigValueCache(): void; +//# sourceMappingURL=resolve-config-value.d.ts.map \ No newline at end of file diff --git a/dist/core/resolve-config-value.d.ts.map b/dist/core/resolve-config-value.d.ts.map new file mode 100644 index 0000000..78726f2 --- /dev/null +++ b/dist/core/resolve-config-value.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-config-value.d.ts","sourceRoot":"","sources":["../../src/core/resolve-config-value.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA+GH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAI3E;AAED,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAGlE;AAED,wBAAgB,gCAAgC,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,EAAE,CAEvG;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAE5D;AAED,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,OAAO,CAE7F;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,GAAG,SAAS,CAMnG;AAmED;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,GAAG,SAAS,CAM3G;AAED,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAsBnH;AAED;;GAEG;AACH,wBAAgB,cAAc,CAC7B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,EAC3C,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAUpC;AAED,wBAAgB,qBAAqB,CACpC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,EAC3C,WAAW,EAAE,MAAM,EACnB,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC1B,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAOpC;AAED,kEAAkE;AAClE,wBAAgB,qBAAqB,IAAI,IAAI,CAE5C","sourcesContent":["/**\n * Resolve configuration values that may be shell commands, environment variables, or literals.\n * Used by auth-storage.ts and model-registry.ts.\n */\n\nimport { execSync, spawnSync } from \"child_process\";\nimport { getShellConfig } from \"../utils/shell.ts\";\n\n// Cache for shell command results (persists for process lifetime)\nconst commandResultCache = new Map();\nconst ENV_VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst ENV_VAR_NAME_PREFIX_RE = /^[A-Za-z_][A-Za-z0-9_]*/;\n\ntype TemplatePart = { type: \"literal\"; value: string } | { type: \"env\"; name: string };\n\ntype ConfigValueReference = { type: \"command\"; config: string } | { type: \"template\"; parts: TemplatePart[] };\n\nfunction appendLiteral(parts: TemplatePart[], value: string): void {\n\tif (!value) return;\n\tconst previousPart = parts[parts.length - 1];\n\tif (previousPart?.type === \"literal\") {\n\t\tpreviousPart.value += value;\n\t\treturn;\n\t}\n\tparts.push({ type: \"literal\", value });\n}\n\nfunction parseConfigValueTemplate(config: string): TemplatePart[] {\n\tconst parts: TemplatePart[] = [];\n\tlet index = 0;\n\n\twhile (index < config.length) {\n\t\tconst dollarIndex = config.indexOf(\"$\", index);\n\t\tif (dollarIndex < 0) {\n\t\t\tappendLiteral(parts, config.slice(index));\n\t\t\tbreak;\n\t\t}\n\n\t\tappendLiteral(parts, config.slice(index, dollarIndex));\n\t\tconst nextChar = config[dollarIndex + 1];\n\n\t\tif (nextChar === \"$\" || nextChar === \"!\") {\n\t\t\tappendLiteral(parts, nextChar);\n\t\t\tindex = dollarIndex + 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (nextChar === \"{\") {\n\t\t\tconst endIndex = config.indexOf(\"}\", dollarIndex + 2);\n\t\t\tif (endIndex < 0) {\n\t\t\t\tappendLiteral(parts, \"$\");\n\t\t\t\tindex = dollarIndex + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst name = config.slice(dollarIndex + 2, endIndex);\n\t\t\tif (ENV_VAR_NAME_RE.test(name)) {\n\t\t\t\tparts.push({ type: \"env\", name });\n\t\t\t} else {\n\t\t\t\tappendLiteral(parts, config.slice(dollarIndex, endIndex + 1));\n\t\t\t}\n\t\t\tindex = endIndex + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst match = config.slice(dollarIndex + 1).match(ENV_VAR_NAME_PREFIX_RE);\n\t\tif (match) {\n\t\t\tparts.push({ type: \"env\", name: match[0] });\n\t\t\tindex = dollarIndex + 1 + match[0].length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tappendLiteral(parts, \"$\");\n\t\tindex = dollarIndex + 1;\n\t}\n\n\treturn parts;\n}\n\nfunction parseConfigValueReference(config: string): ConfigValueReference {\n\tif (config.startsWith(\"!\")) {\n\t\treturn { type: \"command\", config };\n\t}\n\n\treturn { type: \"template\", parts: parseConfigValueTemplate(config) };\n}\n\nfunction resolveEnvConfigValue(name: string, env?: Record): string | undefined {\n\treturn env?.[name] || process.env[name] || undefined;\n}\n\nfunction getTemplateEnvVarNames(parts: TemplatePart[]): string[] {\n\tconst names: string[] = [];\n\tfor (const part of parts) {\n\t\tif (part.type !== \"env\" || names.includes(part.name)) continue;\n\t\tnames.push(part.name);\n\t}\n\treturn names;\n}\n\nfunction resolveTemplate(parts: TemplatePart[], env?: Record): string | undefined {\n\tlet resolved = \"\";\n\tfor (const part of parts) {\n\t\tif (part.type === \"literal\") {\n\t\t\tresolved += part.value;\n\t\t\tcontinue;\n\t\t}\n\t\tconst envValue = resolveEnvConfigValue(part.name, env);\n\t\tif (envValue === undefined) return undefined;\n\t\tresolved += envValue;\n\t}\n\treturn resolved;\n}\n\nexport function getConfigValueEnvVarName(config: string): string | undefined {\n\tconst reference = parseConfigValueReference(config);\n\tif (reference.type !== \"template\") return undefined;\n\treturn reference.parts.length === 1 && reference.parts[0]?.type === \"env\" ? reference.parts[0].name : undefined;\n}\n\nexport function getConfigValueEnvVarNames(config: string): string[] {\n\tconst reference = parseConfigValueReference(config);\n\treturn reference.type === \"template\" ? getTemplateEnvVarNames(reference.parts) : [];\n}\n\nexport function getMissingConfigValueEnvVarNames(config: string, env?: Record): string[] {\n\treturn getConfigValueEnvVarNames(config).filter((name) => resolveEnvConfigValue(name, env) === undefined);\n}\n\nexport function isCommandConfigValue(config: string): boolean {\n\treturn parseConfigValueReference(config).type === \"command\";\n}\n\nexport function isConfigValueConfigured(config: string, env?: Record): boolean {\n\treturn getMissingConfigValueEnvVarNames(config, env).length === 0;\n}\n\n/**\n * Resolve a config value (API key, header value, etc.) to an actual value.\n * - If starts with \"!\", executes the rest as a shell command and uses stdout (cached)\n * - Interpolates \"$ENV_VAR\" or \"${ENV_VAR}\" references with the named environment variable\n * - In non-command values, \"$$\" escapes a literal \"$\" and \"$!\" escapes a literal \"!\"\n * - Otherwise treats the value as a literal\n */\nexport function resolveConfigValue(config: string, env?: Record): string | undefined {\n\tconst reference = parseConfigValueReference(config);\n\tif (reference.type === \"command\") {\n\t\treturn executeCommand(reference.config);\n\t}\n\treturn resolveTemplate(reference.parts, env);\n}\n\nfunction executeWithConfiguredShell(command: string): { executed: boolean; value: string | undefined } {\n\ttry {\n\t\tconst { shell, args, commandTransport } = getShellConfig();\n\t\tconst commandFromStdin = commandTransport === \"stdin\";\n\t\tconst result = spawnSync(shell, commandFromStdin ? args : [...args, command], {\n\t\t\tencoding: \"utf-8\",\n\t\t\tinput: commandFromStdin ? command : undefined,\n\t\t\ttimeout: 10000,\n\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"ignore\"],\n\t\t\tshell: false,\n\t\t\twindowsHide: true,\n\t\t});\n\n\t\tif (result.error) {\n\t\t\tconst error = result.error as NodeJS.ErrnoException;\n\t\t\tif (error.code === \"ENOENT\") {\n\t\t\t\treturn { executed: false, value: undefined };\n\t\t\t}\n\t\t\treturn { executed: true, value: undefined };\n\t\t}\n\n\t\tif (result.status !== 0) {\n\t\t\treturn { executed: true, value: undefined };\n\t\t}\n\n\t\tconst value = (result.stdout ?? \"\").trim();\n\t\treturn { executed: true, value: value || undefined };\n\t} catch {\n\t\treturn { executed: false, value: undefined };\n\t}\n}\n\nfunction executeWithDefaultShell(command: string): string | undefined {\n\ttry {\n\t\tconst output = execSync(command, {\n\t\t\tencoding: \"utf-8\",\n\t\t\ttimeout: 10000,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t});\n\t\treturn output.trim() || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction executeCommandUncached(commandConfig: string): string | undefined {\n\tconst command = commandConfig.slice(1);\n\treturn process.platform === \"win32\"\n\t\t? (() => {\n\t\t\t\tconst configuredResult = executeWithConfiguredShell(command);\n\t\t\t\treturn configuredResult.executed ? configuredResult.value : executeWithDefaultShell(command);\n\t\t\t})()\n\t\t: executeWithDefaultShell(command);\n}\n\nfunction executeCommand(commandConfig: string): string | undefined {\n\tif (commandResultCache.has(commandConfig)) {\n\t\treturn commandResultCache.get(commandConfig);\n\t}\n\n\tconst result = executeCommandUncached(commandConfig);\n\tcommandResultCache.set(commandConfig, result);\n\treturn result;\n}\n\n/**\n * Resolve all header values using the same resolution logic as API keys.\n */\nexport function resolveConfigValueUncached(config: string, env?: Record): string | undefined {\n\tconst reference = parseConfigValueReference(config);\n\tif (reference.type === \"command\") {\n\t\treturn executeCommandUncached(reference.config);\n\t}\n\treturn resolveTemplate(reference.parts, env);\n}\n\nexport function resolveConfigValueOrThrow(config: string, description: string, env?: Record): string {\n\tconst resolvedValue = resolveConfigValueUncached(config, env);\n\tif (resolvedValue !== undefined) {\n\t\treturn resolvedValue;\n\t}\n\n\tconst reference = parseConfigValueReference(config);\n\tif (reference.type === \"command\") {\n\t\tthrow new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`);\n\t}\n\n\tif (reference.type === \"template\") {\n\t\tconst missingEnvVars = getMissingConfigValueEnvVarNames(config, env);\n\t\tif (missingEnvVars.length === 1) {\n\t\t\tthrow new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`);\n\t\t}\n\t\tif (missingEnvVars.length > 1) {\n\t\t\tthrow new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(\", \")}`);\n\t\t}\n\t}\n\n\tthrow new Error(`Failed to resolve ${description}`);\n}\n\n/**\n * Resolve all header values using the same resolution logic as API keys.\n */\nexport function resolveHeaders(\n\theaders: Record | undefined,\n\tenv?: Record,\n): Record | undefined {\n\tif (!headers) return undefined;\n\tconst resolved: Record = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tconst resolvedValue = resolveConfigValue(value, env);\n\t\tif (resolvedValue) {\n\t\t\tresolved[key] = resolvedValue;\n\t\t}\n\t}\n\treturn Object.keys(resolved).length > 0 ? resolved : undefined;\n}\n\nexport function resolveHeadersOrThrow(\n\theaders: Record | undefined,\n\tdescription: string,\n\tenv?: Record,\n): Record | undefined {\n\tif (!headers) return undefined;\n\tconst resolved: Record = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tresolved[key] = resolveConfigValueOrThrow(value, `${description} header \"${key}\"`, env);\n\t}\n\treturn Object.keys(resolved).length > 0 ? resolved : undefined;\n}\n\n/** Clear the config value command cache. Exported for testing. */\nexport function clearConfigValueCache(): void {\n\tcommandResultCache.clear();\n}\n"]} \ No newline at end of file diff --git a/dist/core/resolve-config-value.js b/dist/core/resolve-config-value.js new file mode 100644 index 0000000..9075eb6 --- /dev/null +++ b/dist/core/resolve-config-value.js @@ -0,0 +1,247 @@ +/** + * Resolve configuration values that may be shell commands, environment variables, or literals. + * Used by auth-storage.ts and model-registry.ts. + */ +import { execSync, spawnSync } from "child_process"; +import { getShellConfig } from "../utils/shell.js"; +// Cache for shell command results (persists for process lifetime) +const commandResultCache = new Map(); +const ENV_VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/; +const ENV_VAR_NAME_PREFIX_RE = /^[A-Za-z_][A-Za-z0-9_]*/; +function appendLiteral(parts, value) { + if (!value) + return; + const previousPart = parts[parts.length - 1]; + if (previousPart?.type === "literal") { + previousPart.value += value; + return; + } + parts.push({ type: "literal", value }); +} +function parseConfigValueTemplate(config) { + const parts = []; + let index = 0; + while (index < config.length) { + const dollarIndex = config.indexOf("$", index); + if (dollarIndex < 0) { + appendLiteral(parts, config.slice(index)); + break; + } + appendLiteral(parts, config.slice(index, dollarIndex)); + const nextChar = config[dollarIndex + 1]; + if (nextChar === "$" || nextChar === "!") { + appendLiteral(parts, nextChar); + index = dollarIndex + 2; + continue; + } + if (nextChar === "{") { + const endIndex = config.indexOf("}", dollarIndex + 2); + if (endIndex < 0) { + appendLiteral(parts, "$"); + index = dollarIndex + 1; + continue; + } + const name = config.slice(dollarIndex + 2, endIndex); + if (ENV_VAR_NAME_RE.test(name)) { + parts.push({ type: "env", name }); + } + else { + appendLiteral(parts, config.slice(dollarIndex, endIndex + 1)); + } + index = endIndex + 1; + continue; + } + const match = config.slice(dollarIndex + 1).match(ENV_VAR_NAME_PREFIX_RE); + if (match) { + parts.push({ type: "env", name: match[0] }); + index = dollarIndex + 1 + match[0].length; + continue; + } + appendLiteral(parts, "$"); + index = dollarIndex + 1; + } + return parts; +} +function parseConfigValueReference(config) { + if (config.startsWith("!")) { + return { type: "command", config }; + } + return { type: "template", parts: parseConfigValueTemplate(config) }; +} +function resolveEnvConfigValue(name, env) { + return env?.[name] || process.env[name] || undefined; +} +function getTemplateEnvVarNames(parts) { + const names = []; + for (const part of parts) { + if (part.type !== "env" || names.includes(part.name)) + continue; + names.push(part.name); + } + return names; +} +function resolveTemplate(parts, env) { + let resolved = ""; + for (const part of parts) { + if (part.type === "literal") { + resolved += part.value; + continue; + } + const envValue = resolveEnvConfigValue(part.name, env); + if (envValue === undefined) + return undefined; + resolved += envValue; + } + return resolved; +} +export function getConfigValueEnvVarName(config) { + const reference = parseConfigValueReference(config); + if (reference.type !== "template") + return undefined; + return reference.parts.length === 1 && reference.parts[0]?.type === "env" ? reference.parts[0].name : undefined; +} +export function getConfigValueEnvVarNames(config) { + const reference = parseConfigValueReference(config); + return reference.type === "template" ? getTemplateEnvVarNames(reference.parts) : []; +} +export function getMissingConfigValueEnvVarNames(config, env) { + return getConfigValueEnvVarNames(config).filter((name) => resolveEnvConfigValue(name, env) === undefined); +} +export function isCommandConfigValue(config) { + return parseConfigValueReference(config).type === "command"; +} +export function isConfigValueConfigured(config, env) { + return getMissingConfigValueEnvVarNames(config, env).length === 0; +} +/** + * Resolve a config value (API key, header value, etc.) to an actual value. + * - If starts with "!", executes the rest as a shell command and uses stdout (cached) + * - Interpolates "$ENV_VAR" or "${ENV_VAR}" references with the named environment variable + * - In non-command values, "$$" escapes a literal "$" and "$!" escapes a literal "!" + * - Otherwise treats the value as a literal + */ +export function resolveConfigValue(config, env) { + const reference = parseConfigValueReference(config); + if (reference.type === "command") { + return executeCommand(reference.config); + } + return resolveTemplate(reference.parts, env); +} +function executeWithConfiguredShell(command) { + try { + const { shell, args, commandTransport } = getShellConfig(); + const commandFromStdin = commandTransport === "stdin"; + const result = spawnSync(shell, commandFromStdin ? args : [...args, command], { + encoding: "utf-8", + input: commandFromStdin ? command : undefined, + timeout: 10000, + stdio: [commandFromStdin ? "pipe" : "ignore", "pipe", "ignore"], + shell: false, + windowsHide: true, + }); + if (result.error) { + const error = result.error; + if (error.code === "ENOENT") { + return { executed: false, value: undefined }; + } + return { executed: true, value: undefined }; + } + if (result.status !== 0) { + return { executed: true, value: undefined }; + } + const value = (result.stdout ?? "").trim(); + return { executed: true, value: value || undefined }; + } + catch { + return { executed: false, value: undefined }; + } +} +function executeWithDefaultShell(command) { + try { + const output = execSync(command, { + encoding: "utf-8", + timeout: 10000, + stdio: ["ignore", "pipe", "ignore"], + }); + return output.trim() || undefined; + } + catch { + return undefined; + } +} +function executeCommandUncached(commandConfig) { + const command = commandConfig.slice(1); + return process.platform === "win32" + ? (() => { + const configuredResult = executeWithConfiguredShell(command); + return configuredResult.executed ? configuredResult.value : executeWithDefaultShell(command); + })() + : executeWithDefaultShell(command); +} +function executeCommand(commandConfig) { + if (commandResultCache.has(commandConfig)) { + return commandResultCache.get(commandConfig); + } + const result = executeCommandUncached(commandConfig); + commandResultCache.set(commandConfig, result); + return result; +} +/** + * Resolve all header values using the same resolution logic as API keys. + */ +export function resolveConfigValueUncached(config, env) { + const reference = parseConfigValueReference(config); + if (reference.type === "command") { + return executeCommandUncached(reference.config); + } + return resolveTemplate(reference.parts, env); +} +export function resolveConfigValueOrThrow(config, description, env) { + const resolvedValue = resolveConfigValueUncached(config, env); + if (resolvedValue !== undefined) { + return resolvedValue; + } + const reference = parseConfigValueReference(config); + if (reference.type === "command") { + throw new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`); + } + if (reference.type === "template") { + const missingEnvVars = getMissingConfigValueEnvVarNames(config, env); + if (missingEnvVars.length === 1) { + throw new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`); + } + if (missingEnvVars.length > 1) { + throw new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(", ")}`); + } + } + throw new Error(`Failed to resolve ${description}`); +} +/** + * Resolve all header values using the same resolution logic as API keys. + */ +export function resolveHeaders(headers, env) { + if (!headers) + return undefined; + const resolved = {}; + for (const [key, value] of Object.entries(headers)) { + const resolvedValue = resolveConfigValue(value, env); + if (resolvedValue) { + resolved[key] = resolvedValue; + } + } + return Object.keys(resolved).length > 0 ? resolved : undefined; +} +export function resolveHeadersOrThrow(headers, description, env) { + if (!headers) + return undefined; + const resolved = {}; + for (const [key, value] of Object.entries(headers)) { + resolved[key] = resolveConfigValueOrThrow(value, `${description} header "${key}"`, env); + } + return Object.keys(resolved).length > 0 ? resolved : undefined; +} +/** Clear the config value command cache. Exported for testing. */ +export function clearConfigValueCache() { + commandResultCache.clear(); +} +//# sourceMappingURL=resolve-config-value.js.map \ No newline at end of file diff --git a/dist/core/resolve-config-value.js.map b/dist/core/resolve-config-value.js.map new file mode 100644 index 0000000..3b641f3 --- /dev/null +++ b/dist/core/resolve-config-value.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-config-value.js","sourceRoot":"","sources":["../../src/core/resolve-config-value.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD,kEAAkE;AAClE,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAA8B,CAAC;AACjE,MAAM,eAAe,GAAG,0BAA0B,CAAC;AACnD,MAAM,sBAAsB,GAAG,yBAAyB,CAAC;AAMzD,SAAS,aAAa,CAAC,KAAqB,EAAE,KAAa,EAAQ;IAClE,IAAI,CAAC,KAAK;QAAE,OAAO;IACnB,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC7C,IAAI,YAAY,EAAE,IAAI,KAAK,SAAS,EAAE,CAAC;QACtC,YAAY,CAAC,KAAK,IAAI,KAAK,CAAC;QAC5B,OAAO;IACR,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAA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C7B,OAA2C,EAC3C,GAA4B,EACS;IACrC,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,MAAM,QAAQ,GAA2B,EAAE,CAAC;IAC5C,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACpD,MAAM,aAAa,GAAG,kBAAkB,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;QACrD,IAAI,aAAa,EAAE,CAAC;YACnB,QAAQ,CAAC,GAAG,CAAC,GAAG,aAAa,CAAC;QAC/B,CAAC;IACF,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CAC/D;AAED,MAAM,UAAU,qBAAqB,CACpC,OAA2C,EAC3C,WAAmB,EACnB,GAA4B,EACS;IACrC,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,MAAM,QAAQ,GAA2B,EAAE,CAAC;IAC5C,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACpD,QAAQ,CAAC,GAAG,CAAC,GAAG,yBAAyB,CAAC,KAAK,EAAE,GAAG,WAAW,YAAY,GAAG,GAAG,EAAE,GAAG,CAAC,CAAC;IACzF,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CAC/D;AAED,kEAAkE;AAClE,MAAM,UAAU,qBAAqB,GAAS;IAC7C,kBAAkB,CAAC,KAAK,EAAE,CAAC;AAAA,CAC3B","sourcesContent":["/**\n * Resolve configuration values that may be shell commands, environment variables, or literals.\n * Used by auth-storage.ts and model-registry.ts.\n */\n\nimport { execSync, spawnSync } from \"child_process\";\nimport { getShellConfig } from \"../utils/shell.ts\";\n\n// Cache for shell command results (persists for process lifetime)\nconst commandResultCache = new Map();\nconst ENV_VAR_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst ENV_VAR_NAME_PREFIX_RE = /^[A-Za-z_][A-Za-z0-9_]*/;\n\ntype TemplatePart = { type: \"literal\"; value: string } | { type: \"env\"; name: string };\n\ntype ConfigValueReference = { type: \"command\"; config: string } | { type: \"template\"; parts: TemplatePart[] };\n\nfunction appendLiteral(parts: TemplatePart[], value: string): void {\n\tif (!value) return;\n\tconst previousPart = parts[parts.length - 1];\n\tif (previousPart?.type === \"literal\") {\n\t\tpreviousPart.value += value;\n\t\treturn;\n\t}\n\tparts.push({ type: \"literal\", value });\n}\n\nfunction parseConfigValueTemplate(config: string): TemplatePart[] {\n\tconst parts: TemplatePart[] = [];\n\tlet index = 0;\n\n\twhile (index < config.length) {\n\t\tconst dollarIndex = config.indexOf(\"$\", index);\n\t\tif (dollarIndex < 0) {\n\t\t\tappendLiteral(parts, config.slice(index));\n\t\t\tbreak;\n\t\t}\n\n\t\tappendLiteral(parts, config.slice(index, dollarIndex));\n\t\tconst nextChar = config[dollarIndex + 1];\n\n\t\tif (nextChar === \"$\" || nextChar === \"!\") {\n\t\t\tappendLiteral(parts, nextChar);\n\t\t\tindex = dollarIndex + 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (nextChar === \"{\") {\n\t\t\tconst endIndex = config.indexOf(\"}\", dollarIndex + 2);\n\t\t\tif (endIndex < 0) {\n\t\t\t\tappendLiteral(parts, \"$\");\n\t\t\t\tindex = dollarIndex + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst name = config.slice(dollarIndex + 2, endIndex);\n\t\t\tif (ENV_VAR_NAME_RE.test(name)) {\n\t\t\t\tparts.push({ type: \"env\", name });\n\t\t\t} else {\n\t\t\t\tappendLiteral(parts, config.slice(dollarIndex, endIndex + 1));\n\t\t\t}\n\t\t\tindex = endIndex + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst match = config.slice(dollarIndex + 1).match(ENV_VAR_NAME_PREFIX_RE);\n\t\tif (match) {\n\t\t\tparts.push({ type: \"env\", name: match[0] });\n\t\t\tindex = dollarIndex + 1 + match[0].length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tappendLiteral(parts, \"$\");\n\t\tindex = dollarIndex + 1;\n\t}\n\n\treturn parts;\n}\n\nfunction parseConfigValueReference(config: string): ConfigValueReference {\n\tif (config.startsWith(\"!\")) {\n\t\treturn { type: \"command\", config };\n\t}\n\n\treturn { type: \"template\", parts: parseConfigValueTemplate(config) };\n}\n\nfunction resolveEnvConfigValue(name: string, env?: Record): string | undefined {\n\treturn env?.[name] || process.env[name] || undefined;\n}\n\nfunction getTemplateEnvVarNames(parts: TemplatePart[]): string[] {\n\tconst names: string[] = [];\n\tfor (const part of parts) {\n\t\tif (part.type !== \"env\" || names.includes(part.name)) continue;\n\t\tnames.push(part.name);\n\t}\n\treturn names;\n}\n\nfunction resolveTemplate(parts: TemplatePart[], env?: Record): string | undefined {\n\tlet resolved = \"\";\n\tfor (const part of parts) {\n\t\tif (part.type === \"literal\") {\n\t\t\tresolved += part.value;\n\t\t\tcontinue;\n\t\t}\n\t\tconst envValue = resolveEnvConfigValue(part.name, env);\n\t\tif (envValue === undefined) return undefined;\n\t\tresolved += envValue;\n\t}\n\treturn resolved;\n}\n\nexport function getConfigValueEnvVarName(config: string): string | undefined {\n\tconst reference = parseConfigValueReference(config);\n\tif (reference.type !== \"template\") return undefined;\n\treturn reference.parts.length === 1 && reference.parts[0]?.type === \"env\" ? reference.parts[0].name : undefined;\n}\n\nexport function getConfigValueEnvVarNames(config: string): string[] {\n\tconst reference = parseConfigValueReference(config);\n\treturn reference.type === \"template\" ? getTemplateEnvVarNames(reference.parts) : [];\n}\n\nexport function getMissingConfigValueEnvVarNames(config: string, env?: Record): string[] {\n\treturn getConfigValueEnvVarNames(config).filter((name) => resolveEnvConfigValue(name, env) === undefined);\n}\n\nexport function isCommandConfigValue(config: string): boolean {\n\treturn parseConfigValueReference(config).type === \"command\";\n}\n\nexport function isConfigValueConfigured(config: string, env?: Record): boolean {\n\treturn getMissingConfigValueEnvVarNames(config, env).length === 0;\n}\n\n/**\n * Resolve a config value (API key, header value, etc.) to an actual value.\n * - If starts with \"!\", executes the rest as a shell command and uses stdout (cached)\n * - Interpolates \"$ENV_VAR\" or \"${ENV_VAR}\" references with the named environment variable\n * - In non-command values, \"$$\" escapes a literal \"$\" and \"$!\" escapes a literal \"!\"\n * - Otherwise treats the value as a literal\n */\nexport function resolveConfigValue(config: string, env?: Record): string | undefined {\n\tconst reference = parseConfigValueReference(config);\n\tif (reference.type === \"command\") {\n\t\treturn executeCommand(reference.config);\n\t}\n\treturn resolveTemplate(reference.parts, env);\n}\n\nfunction executeWithConfiguredShell(command: string): { executed: boolean; value: string | undefined } {\n\ttry {\n\t\tconst { shell, args, commandTransport } = getShellConfig();\n\t\tconst commandFromStdin = commandTransport === \"stdin\";\n\t\tconst result = spawnSync(shell, commandFromStdin ? args : [...args, command], {\n\t\t\tencoding: \"utf-8\",\n\t\t\tinput: commandFromStdin ? command : undefined,\n\t\t\ttimeout: 10000,\n\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"ignore\"],\n\t\t\tshell: false,\n\t\t\twindowsHide: true,\n\t\t});\n\n\t\tif (result.error) {\n\t\t\tconst error = result.error as NodeJS.ErrnoException;\n\t\t\tif (error.code === \"ENOENT\") {\n\t\t\t\treturn { executed: false, value: undefined };\n\t\t\t}\n\t\t\treturn { executed: true, value: undefined };\n\t\t}\n\n\t\tif (result.status !== 0) {\n\t\t\treturn { executed: true, value: undefined };\n\t\t}\n\n\t\tconst value = (result.stdout ?? \"\").trim();\n\t\treturn { executed: true, value: value || undefined };\n\t} catch {\n\t\treturn { executed: false, value: undefined };\n\t}\n}\n\nfunction executeWithDefaultShell(command: string): string | undefined {\n\ttry {\n\t\tconst output = execSync(command, {\n\t\t\tencoding: \"utf-8\",\n\t\t\ttimeout: 10000,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t});\n\t\treturn output.trim() || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction executeCommandUncached(commandConfig: string): string | undefined {\n\tconst command = commandConfig.slice(1);\n\treturn process.platform === \"win32\"\n\t\t? (() => {\n\t\t\t\tconst configuredResult = executeWithConfiguredShell(command);\n\t\t\t\treturn configuredResult.executed ? configuredResult.value : executeWithDefaultShell(command);\n\t\t\t})()\n\t\t: executeWithDefaultShell(command);\n}\n\nfunction executeCommand(commandConfig: string): string | undefined {\n\tif (commandResultCache.has(commandConfig)) {\n\t\treturn commandResultCache.get(commandConfig);\n\t}\n\n\tconst result = executeCommandUncached(commandConfig);\n\tcommandResultCache.set(commandConfig, result);\n\treturn result;\n}\n\n/**\n * Resolve all header values using the same resolution logic as API keys.\n */\nexport function resolveConfigValueUncached(config: string, env?: Record): string | undefined {\n\tconst reference = parseConfigValueReference(config);\n\tif (reference.type === \"command\") {\n\t\treturn executeCommandUncached(reference.config);\n\t}\n\treturn resolveTemplate(reference.parts, env);\n}\n\nexport function resolveConfigValueOrThrow(config: string, description: string, env?: Record): string {\n\tconst resolvedValue = resolveConfigValueUncached(config, env);\n\tif (resolvedValue !== undefined) {\n\t\treturn resolvedValue;\n\t}\n\n\tconst reference = parseConfigValueReference(config);\n\tif (reference.type === \"command\") {\n\t\tthrow new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`);\n\t}\n\n\tif (reference.type === \"template\") {\n\t\tconst missingEnvVars = getMissingConfigValueEnvVarNames(config, env);\n\t\tif (missingEnvVars.length === 1) {\n\t\t\tthrow new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`);\n\t\t}\n\t\tif (missingEnvVars.length > 1) {\n\t\t\tthrow new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(\", \")}`);\n\t\t}\n\t}\n\n\tthrow new Error(`Failed to resolve ${description}`);\n}\n\n/**\n * Resolve all header values using the same resolution logic as API keys.\n */\nexport function resolveHeaders(\n\theaders: Record | undefined,\n\tenv?: Record,\n): Record | undefined {\n\tif (!headers) return undefined;\n\tconst resolved: Record = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tconst resolvedValue = resolveConfigValue(value, env);\n\t\tif (resolvedValue) {\n\t\t\tresolved[key] = resolvedValue;\n\t\t}\n\t}\n\treturn Object.keys(resolved).length > 0 ? resolved : undefined;\n}\n\nexport function resolveHeadersOrThrow(\n\theaders: Record | undefined,\n\tdescription: string,\n\tenv?: Record,\n): Record | undefined {\n\tif (!headers) return undefined;\n\tconst resolved: Record = {};\n\tfor (const [key, value] of Object.entries(headers)) {\n\t\tresolved[key] = resolveConfigValueOrThrow(value, `${description} header \"${key}\"`, env);\n\t}\n\treturn Object.keys(resolved).length > 0 ? resolved : undefined;\n}\n\n/** Clear the config value command cache. Exported for testing. */\nexport function clearConfigValueCache(): void {\n\tcommandResultCache.clear();\n}\n"]} \ No newline at end of file diff --git a/dist/core/resource-loader.d.ts b/dist/core/resource-loader.d.ts new file mode 100644 index 0000000..0a908d3 --- /dev/null +++ b/dist/core/resource-loader.d.ts @@ -0,0 +1,221 @@ +import { type Theme } from "../modes/interactive/theme/theme.ts"; +import type { ResourceDiagnostic } from "./diagnostics.ts"; +export type { ResourceCollision, ResourceDiagnostic } from "./diagnostics.ts"; +import { type EventBus } from "./event-bus.ts"; +import type { InlineExtension, LoadExtensionsResult } from "./extensions/types.ts"; +import { type PathMetadata } from "./package-manager.ts"; +import type { PromptTemplate } from "./prompt-templates.ts"; +import { SettingsManager } from "./settings-manager.ts"; +import type { Skill } from "./skills.ts"; +export interface ResourceExtensionPaths { + skillPaths?: Array<{ + path: string; + metadata: PathMetadata; + }>; + promptPaths?: Array<{ + path: string; + metadata: PathMetadata; + }>; + themePaths?: Array<{ + path: string; + metadata: PathMetadata; + }>; +} +export interface ResourceLoaderReloadOptions { + resolveProjectTrust?: (input: { + extensionsResult: LoadExtensionsResult; + }) => Promise; +} +export interface ResourceLoader { + getExtensions(): LoadExtensionsResult; + getSkills(): { + skills: Skill[]; + diagnostics: ResourceDiagnostic[]; + }; + getPrompts(): { + prompts: PromptTemplate[]; + diagnostics: ResourceDiagnostic[]; + }; + getThemes(): { + themes: Theme[]; + diagnostics: ResourceDiagnostic[]; + }; + getAgentsFiles(): { + agentsFiles: Array<{ + path: string; + content: string; + }>; + }; + getSystemPrompt(): string | undefined; + getSystemPromptSource(): { + path: string; + } | undefined; + getAppendSystemPrompt(): string[]; + getAppendSystemPromptSources(): Array<{ + path: string; + }>; + extendResources(paths: ResourceExtensionPaths): void; + reload(options?: ResourceLoaderReloadOptions): Promise; +} +export declare function loadProjectContextFiles(options: { + cwd: string; + agentDir: string; +}): Array<{ + path: string; + content: string; +}>; +export interface DefaultResourceLoaderOptions { + cwd: string; + agentDir: string; + settingsManager?: SettingsManager; + eventBus?: EventBus; + additionalExtensionPaths?: string[]; + additionalSkillPaths?: string[]; + additionalPromptTemplatePaths?: string[]; + additionalThemePaths?: string[]; + extensionFactories?: InlineExtension[]; + noExtensions?: boolean; + noSkills?: boolean; + noPromptTemplates?: boolean; + noThemes?: boolean; + noContextFiles?: boolean; + systemPrompt?: string; + appendSystemPrompt?: string[]; + extensionsOverride?: (base: LoadExtensionsResult) => LoadExtensionsResult; + skillsOverride?: (base: { + skills: Skill[]; + diagnostics: ResourceDiagnostic[]; + }) => { + skills: Skill[]; + diagnostics: ResourceDiagnostic[]; + }; + promptsOverride?: (base: { + prompts: PromptTemplate[]; + diagnostics: ResourceDiagnostic[]; + }) => { + prompts: PromptTemplate[]; + diagnostics: ResourceDiagnostic[]; + }; + themesOverride?: (base: { + themes: Theme[]; + diagnostics: ResourceDiagnostic[]; + }) => { + themes: Theme[]; + diagnostics: ResourceDiagnostic[]; + }; + agentsFilesOverride?: (base: { + agentsFiles: Array<{ + path: string; + content: string; + }>; + }) => { + agentsFiles: Array<{ + path: string; + content: string; + }>; + }; + systemPromptOverride?: (base: string | undefined) => string | undefined; + appendSystemPromptOverride?: (base: string[]) => string[]; +} +export declare class DefaultResourceLoader implements ResourceLoader { + private cwd; + private agentDir; + private settingsManager; + private eventBus; + private packageManager; + private additionalExtensionPaths; + private additionalSkillPaths; + private additionalPromptTemplatePaths; + private additionalThemePaths; + private extensionFactories; + private noExtensions; + private noSkills; + private noPromptTemplates; + private noThemes; + private noContextFiles; + private systemPromptSource?; + private appendSystemPromptSource?; + private extensionsOverride?; + private skillsOverride?; + private promptsOverride?; + private themesOverride?; + private agentsFilesOverride?; + private systemPromptOverride?; + private appendSystemPromptOverride?; + private extensionsResult; + private skills; + private skillDiagnostics; + private prompts; + private promptDiagnostics; + private themes; + private themeDiagnostics; + private agentsFiles; + private systemPrompt?; + private systemPromptSourcePath?; + private appendSystemPrompt; + private appendSystemPromptSourcePaths; + private lastSkillPaths; + private extensionSkillSourceInfos; + private extensionPromptSourceInfos; + private extensionThemeSourceInfos; + private resourceMetadataByPath; + private lastPromptPaths; + private lastThemePaths; + private loaded; + constructor(options: DefaultResourceLoaderOptions); + getExtensions(): LoadExtensionsResult; + getSkills(): { + skills: Skill[]; + diagnostics: ResourceDiagnostic[]; + }; + getPrompts(): { + prompts: PromptTemplate[]; + diagnostics: ResourceDiagnostic[]; + }; + getThemes(): { + themes: Theme[]; + diagnostics: ResourceDiagnostic[]; + }; + getAgentsFiles(): { + agentsFiles: Array<{ + path: string; + content: string; + }>; + }; + getSystemPrompt(): string | undefined; + getSystemPromptSource(): { + path: string; + } | undefined; + getAppendSystemPrompt(): string[]; + getAppendSystemPromptSources(): Array<{ + path: string; + }>; + extendResources(paths: ResourceExtensionPaths): void; + loadProjectTrustExtensions(): Promise; + reload(options?: ResourceLoaderReloadOptions): Promise; + private loadCurrentExtensionSet; + private resolveExtensionLoadPath; + private loadFinalExtensionSet; + private addExtensionConflictDiagnostics; + private mapSkillPath; + private normalizeExtensionPaths; + private updateSkillsFromPaths; + private updatePromptsFromPaths; + private updateThemesFromPaths; + private applyExtensionSourceInfo; + private findSourceInfoForPath; + private getDefaultSourceInfoForPath; + private mergePaths; + private resolveResourcePath; + private loadThemes; + private loadThemesFromDir; + private loadThemeFromFile; + private loadExtensionFactories; + private dedupePrompts; + private dedupeThemes; + private discoverSystemPromptFile; + private discoverAppendSystemPromptFile; + private isUnderPath; + private detectExtensionConflicts; +} +//# sourceMappingURL=resource-loader.d.ts.map \ No newline at end of file diff --git a/dist/core/resource-loader.d.ts.map b/dist/core/resource-loader.d.ts.map new file mode 100644 index 0000000..817b44b --- /dev/null +++ b/dist/core/resource-loader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"resource-loader.d.ts","sourceRoot":"","sources":["../../src/core/resource-loader.ts"],"names":[],"mappings":"AAIA,OAAO,EAAqB,KAAK,KAAK,EAAE,MAAM,qCAAqC,CAAC;AACpF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,YAAY,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAG9E,OAAO,EAAkB,KAAK,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAO/D,OAAO,KAAK,EAA+B,eAAe,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAEhH,OAAO,EAAyB,KAAK,YAAY,EAAyB,MAAM,sBAAsB,CAAC;AACvG,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE5D,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAKzC,MAAM,WAAW,sBAAsB;IACtC,UAAU,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,YAAY,CAAA;KAAE,CAAC,CAAC;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AAC,mBAAmB;IAI3B,OAAO,CAAC,UAAU;IA0ClB,OAAO,CAAC,iBAAiB;IA8BzB,OAAO,CAAC,iBAAiB;YASX,sBAAsB;IAwBpC,OAAO,CAAC,aAAa;IA0BrB,OAAO,CAAC,YAAY;IA2BpB,OAAO,CAAC,wBAAwB;IAchC,OAAO,CAAC,8BAA8B;IActC,OAAO,CAAC,WAAW;IASnB,OAAO,CAAC,wBAAwB;CAqChC","sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\nimport chalk from \"chalk\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { loadThemeFromPath, type Theme } from \"../modes/interactive/theme/theme.ts\";\nimport type { ResourceDiagnostic } from \"./diagnostics.ts\";\n\nexport type { ResourceCollision, ResourceDiagnostic } from \"./diagnostics.ts\";\n\nimport { canonicalizePath, isLocalPath, resolvePath } from \"../utils/paths.ts\";\nimport { createEventBus, type EventBus } from \"./event-bus.ts\";\nimport {\n\tclearExtensionCache,\n\tcreateExtensionRuntime,\n\tloadExtensionFromFactory,\n\tloadExtensionsCached,\n} from \"./extensions/loader.ts\";\nimport type { Extension, ExtensionRuntime, InlineExtension, LoadExtensionsResult } from \"./extensions/types.ts\";\nimport { findGitPaths } from \"./footer-data-provider.ts\";\nimport { DefaultPackageManager, type PathMetadata, type ResolvedResource } from \"./package-manager.ts\";\nimport type { PromptTemplate } from \"./prompt-templates.ts\";\nimport { loadPromptTemplates } from \"./prompt-templates.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport type { Skill } from \"./skills.ts\";\nimport { loadSkills } from \"./skills.ts\";\nimport { createSourceInfo, type SourceInfo } from \"./source-info.ts\";\nimport { resetTimings } from \"./timings.ts\";\n\nexport interface ResourceExtensionPaths {\n\tskillPaths?: Array<{ path: string; metadata: PathMetadata }>;\n\tpromptPaths?: Array<{ path: string; metadata: PathMetadata }>;\n\tthemePaths?: Array<{ path: string; metadata: PathMetadata }>;\n}\n\nexport interface ResourceLoaderReloadOptions {\n\tresolveProjectTrust?: (input: { extensionsResult: LoadExtensionsResult }) => Promise;\n}\n\nexport interface ResourceLoader {\n\tgetExtensions(): LoadExtensionsResult;\n\tgetSkills(): { skills: Skill[]; diagnostics: ResourceDiagnostic[] };\n\tgetPrompts(): { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] };\n\tgetThemes(): { themes: Theme[]; diagnostics: ResourceDiagnostic[] };\n\tgetAgentsFiles(): { agentsFiles: Array<{ path: string; content: string }> };\n\tgetSystemPrompt(): string | undefined;\n\tgetSystemPromptSource(): { path: string } | undefined;\n\tgetAppendSystemPrompt(): string[];\n\tgetAppendSystemPromptSources(): Array<{ path: string }>;\n\textendResources(paths: ResourceExtensionPaths): void;\n\treload(options?: ResourceLoaderReloadOptions): Promise;\n}\n\nfunction resolvePromptInput(input: string | undefined, description: string): string | undefined {\n\tif (!input) {\n\t\treturn undefined;\n\t}\n\n\tif (existsSync(input)) {\n\t\ttry {\n\t\t\treturn readFileSync(input, \"utf-8\");\n\t\t} catch (error) {\n\t\t\tconsole.error(chalk.yellow(`Warning: Could not read ${description} file ${input}: ${error}`));\n\t\t\treturn input;\n\t\t}\n\t}\n\n\treturn input;\n}\n\nfunction loadContextFileFromDir(dir: string): { path: string; content: string } | null {\n\tconst candidates = [\"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"];\n\tfor (const filename of candidates) {\n\t\tconst filePath = join(dir, filename);\n\t\tif (existsSync(filePath)) {\n\t\t\ttry {\n\t\t\t\tif (!statSync(filePath).isFile()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tpath: filePath,\n\t\t\t\t\tcontent: readFileSync(filePath, \"utf-8\"),\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(chalk.yellow(`Warning: Could not read ${filePath}: ${error}`));\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * The main repo's context file that a nested linked worktree's own copy shadows: both\n * are the same tracked AGENTS.md/CLAUDE.md, so loading both loads it twice. Returns\n * undefined when nothing is shadowed, leaving normal ancestor inheritance alone.\n *\n * Returned canonicalized (realpath), because `git worktree add` writes the `.git`\n * file's `gitdir:` target in realpath form while cwd may still be symlinked\n * (macOS `/tmp` -> `/private/tmp`).\n */\nfunction findShadowedContextFile(cwd: string): string | undefined {\n\tconst gitPaths = findGitPaths(cwd);\n\tif (!gitPaths) return undefined;\n\tconst commonGitDir = canonicalizePath(gitPaths.commonGitDir);\n\tconst worktreeRoot = canonicalizePath(gitPaths.repoDir);\n\tconst mainRepoRoot = dirname(commonGitDir);\n\t// False for an ordinary repo, where the two are the same dir, and for a sibling\n\t// worktree (`git worktree add ../feat`), whose main repo is not an ancestor.\n\tif (!worktreeRoot.startsWith(`${mainRepoRoot}${sep}`)) return undefined;\n\t// dirname of the common git dir is the main worktree root only when that dir is\n\t// itself checked out from the same repo. In a bare layout (`proj/.bare` +\n\t// `proj/main`) it is just the directory holding `.bare`, which tracks nothing; a\n\t// submodule's gitdir has no `commondir`, so it lands under `.git/modules`.\n\tif (canonicalizePath(join(mainRepoRoot, \".git\")) !== commonGitDir) return undefined;\n\tconst worktreeContextFile = loadContextFileFromDir(worktreeRoot);\n\treturn worktreeContextFile ? join(mainRepoRoot, basename(worktreeContextFile.path)) : undefined;\n}\n\nexport function loadProjectContextFiles(options: {\n\tcwd: string;\n\tagentDir: string;\n}): Array<{ path: string; content: string }> {\n\tconst resolvedCwd = resolvePath(options.cwd);\n\tconst resolvedAgentDir = resolvePath(options.agentDir);\n\n\tconst contextFiles: Array<{ path: string; content: string }> = [];\n\tconst seenPaths = new Set();\n\n\tconst globalContext = loadContextFileFromDir(resolvedAgentDir);\n\tif (globalContext) {\n\t\tcontextFiles.push(globalContext);\n\t\tseenPaths.add(globalContext.path);\n\t}\n\n\tconst ancestorContextFiles: Array<{ path: string; content: string }> = [];\n\n\tconst shadowedContextFile = findShadowedContextFile(resolvedCwd);\n\tlet currentDir = resolvedCwd;\n\n\twhile (true) {\n\t\tconst contextFile = loadContextFileFromDir(currentDir);\n\t\tconst isShadowed =\n\t\t\tshadowedContextFile !== undefined && canonicalizePath(contextFile?.path ?? \"\") === shadowedContextFile;\n\t\tif (contextFile && !isShadowed && !seenPaths.has(contextFile.path)) {\n\t\t\tancestorContextFiles.unshift(contextFile);\n\t\t\tseenPaths.add(contextFile.path);\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) break;\n\t\tcurrentDir = parentDir;\n\t}\n\n\tcontextFiles.push(...ancestorContextFiles);\n\n\treturn contextFiles;\n}\n\nexport interface DefaultResourceLoaderOptions {\n\tcwd: string;\n\tagentDir: string;\n\tsettingsManager?: SettingsManager;\n\teventBus?: EventBus;\n\tadditionalExtensionPaths?: string[];\n\tadditionalSkillPaths?: string[];\n\tadditionalPromptTemplatePaths?: string[];\n\tadditionalThemePaths?: string[];\n\textensionFactories?: InlineExtension[];\n\tnoExtensions?: boolean;\n\tnoSkills?: boolean;\n\tnoPromptTemplates?: boolean;\n\tnoThemes?: boolean;\n\tnoContextFiles?: boolean;\n\tsystemPrompt?: string;\n\tappendSystemPrompt?: string[];\n\textensionsOverride?: (base: LoadExtensionsResult) => LoadExtensionsResult;\n\tskillsOverride?: (base: { skills: Skill[]; diagnostics: ResourceDiagnostic[] }) => {\n\t\tskills: Skill[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t};\n\tpromptsOverride?: (base: { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] }) => {\n\t\tprompts: PromptTemplate[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t};\n\tthemesOverride?: (base: { themes: Theme[]; diagnostics: ResourceDiagnostic[] }) => {\n\t\tthemes: Theme[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t};\n\tagentsFilesOverride?: (base: { agentsFiles: Array<{ path: string; content: string }> }) => {\n\t\tagentsFiles: Array<{ path: string; content: string }>;\n\t};\n\tsystemPromptOverride?: (base: string | undefined) => string | undefined;\n\tappendSystemPromptOverride?: (base: string[]) => string[];\n}\n\nexport class DefaultResourceLoader implements ResourceLoader {\n\tprivate cwd: string;\n\tprivate agentDir: string;\n\tprivate settingsManager: SettingsManager;\n\tprivate eventBus: EventBus;\n\tprivate packageManager: DefaultPackageManager;\n\tprivate additionalExtensionPaths: string[];\n\tprivate additionalSkillPaths: string[];\n\tprivate additionalPromptTemplatePaths: string[];\n\tprivate additionalThemePaths: string[];\n\tprivate extensionFactories: InlineExtension[];\n\tprivate noExtensions: boolean;\n\tprivate noSkills: boolean;\n\tprivate noPromptTemplates: boolean;\n\tprivate noThemes: boolean;\n\tprivate noContextFiles: boolean;\n\tprivate systemPromptSource?: string;\n\tprivate appendSystemPromptSource?: string[];\n\tprivate extensionsOverride?: (base: LoadExtensionsResult) => LoadExtensionsResult;\n\tprivate skillsOverride?: (base: { skills: Skill[]; diagnostics: ResourceDiagnostic[] }) => {\n\t\tskills: Skill[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t};\n\tprivate promptsOverride?: (base: { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] }) => {\n\t\tprompts: PromptTemplate[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t};\n\tprivate themesOverride?: (base: { themes: Theme[]; diagnostics: ResourceDiagnostic[] }) => {\n\t\tthemes: Theme[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t};\n\tprivate agentsFilesOverride?: (base: { agentsFiles: Array<{ path: string; content: string }> }) => {\n\t\tagentsFiles: Array<{ path: string; content: string }>;\n\t};\n\tprivate systemPromptOverride?: (base: string | undefined) => string | undefined;\n\tprivate appendSystemPromptOverride?: (base: string[]) => string[];\n\n\tprivate extensionsResult: LoadExtensionsResult;\n\tprivate skills: Skill[];\n\tprivate skillDiagnostics: ResourceDiagnostic[];\n\tprivate prompts: PromptTemplate[];\n\tprivate promptDiagnostics: ResourceDiagnostic[];\n\tprivate themes: Theme[];\n\tprivate themeDiagnostics: ResourceDiagnostic[];\n\tprivate agentsFiles: Array<{ path: string; content: string }>;\n\tprivate systemPrompt?: string;\n\tprivate systemPromptSourcePath?: string;\n\tprivate appendSystemPrompt: string[];\n\tprivate appendSystemPromptSourcePaths: string[];\n\tprivate lastSkillPaths: string[];\n\tprivate extensionSkillSourceInfos: Map;\n\tprivate extensionPromptSourceInfos: Map;\n\tprivate extensionThemeSourceInfos: Map;\n\tprivate resourceMetadataByPath: Map;\n\tprivate lastPromptPaths: string[];\n\tprivate lastThemePaths: string[];\n\tprivate loaded: boolean;\n\n\tconstructor(options: DefaultResourceLoaderOptions) {\n\t\tthis.cwd = resolvePath(options.cwd);\n\t\tthis.agentDir = resolvePath(options.agentDir);\n\t\tthis.settingsManager = options.settingsManager ?? SettingsManager.create(this.cwd, this.agentDir);\n\t\tthis.eventBus = options.eventBus ?? createEventBus();\n\t\tthis.packageManager = new DefaultPackageManager({\n\t\t\tcwd: this.cwd,\n\t\t\tagentDir: this.agentDir,\n\t\t\tsettingsManager: this.settingsManager,\n\t\t});\n\t\tthis.additionalExtensionPaths = options.additionalExtensionPaths ?? [];\n\t\tthis.additionalSkillPaths = options.additionalSkillPaths ?? [];\n\t\tthis.additionalPromptTemplatePaths = options.additionalPromptTemplatePaths ?? [];\n\t\tthis.additionalThemePaths = options.additionalThemePaths ?? [];\n\t\tthis.extensionFactories = options.extensionFactories ?? [];\n\t\tthis.noExtensions = options.noExtensions ?? false;\n\t\tthis.noSkills = options.noSkills ?? false;\n\t\tthis.noPromptTemplates = options.noPromptTemplates ?? false;\n\t\tthis.noThemes = options.noThemes ?? false;\n\t\tthis.noContextFiles = options.noContextFiles ?? false;\n\t\tthis.systemPromptSource = options.systemPrompt;\n\t\tthis.appendSystemPromptSource = options.appendSystemPrompt;\n\t\tthis.extensionsOverride = options.extensionsOverride;\n\t\tthis.skillsOverride = options.skillsOverride;\n\t\tthis.promptsOverride = options.promptsOverride;\n\t\tthis.themesOverride = options.themesOverride;\n\t\tthis.agentsFilesOverride = options.agentsFilesOverride;\n\t\tthis.systemPromptOverride = options.systemPromptOverride;\n\t\tthis.appendSystemPromptOverride = options.appendSystemPromptOverride;\n\n\t\tthis.extensionsResult = { extensions: [], errors: [], runtime: createExtensionRuntime() };\n\t\tthis.skills = [];\n\t\tthis.skillDiagnostics = [];\n\t\tthis.prompts = [];\n\t\tthis.promptDiagnostics = [];\n\t\tthis.themes = [];\n\t\tthis.themeDiagnostics = [];\n\t\tthis.agentsFiles = [];\n\t\tthis.appendSystemPrompt = [];\n\t\tthis.appendSystemPromptSourcePaths = [];\n\t\tthis.lastSkillPaths = [];\n\t\tthis.extensionSkillSourceInfos = new Map();\n\t\tthis.extensionPromptSourceInfos = new Map();\n\t\tthis.extensionThemeSourceInfos = new Map();\n\t\tthis.resourceMetadataByPath = new Map();\n\t\tthis.lastPromptPaths = [];\n\t\tthis.lastThemePaths = [];\n\t\tthis.loaded = false;\n\t}\n\n\tgetExtensions(): LoadExtensionsResult {\n\t\treturn this.extensionsResult;\n\t}\n\n\tgetSkills(): { skills: Skill[]; diagnostics: ResourceDiagnostic[] } {\n\t\treturn { skills: this.skills, diagnostics: this.skillDiagnostics };\n\t}\n\n\tgetPrompts(): { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] } {\n\t\treturn { prompts: this.prompts, diagnostics: this.promptDiagnostics };\n\t}\n\n\tgetThemes(): { themes: Theme[]; diagnostics: ResourceDiagnostic[] } {\n\t\treturn { themes: this.themes, diagnostics: this.themeDiagnostics };\n\t}\n\n\tgetAgentsFiles(): { agentsFiles: Array<{ path: string; content: string }> } {\n\t\treturn { agentsFiles: this.agentsFiles };\n\t}\n\n\tgetSystemPrompt(): string | undefined {\n\t\treturn this.systemPrompt;\n\t}\n\n\tgetSystemPromptSource(): { path: string } | undefined {\n\t\treturn this.systemPromptSourcePath ? { path: this.systemPromptSourcePath } : undefined;\n\t}\n\n\tgetAppendSystemPrompt(): string[] {\n\t\treturn this.appendSystemPrompt;\n\t}\n\n\tgetAppendSystemPromptSources(): Array<{ path: string }> {\n\t\treturn this.appendSystemPromptSourcePaths.map((path) => ({ path }));\n\t}\n\n\textendResources(paths: ResourceExtensionPaths): void {\n\t\tconst skillPaths = this.normalizeExtensionPaths(paths.skillPaths ?? []);\n\t\tconst promptPaths = this.normalizeExtensionPaths(paths.promptPaths ?? []);\n\t\tconst themePaths = this.normalizeExtensionPaths(paths.themePaths ?? []);\n\n\t\tfor (const entry of skillPaths) {\n\t\t\tthis.extensionSkillSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata));\n\t\t}\n\t\tfor (const entry of promptPaths) {\n\t\t\tthis.extensionPromptSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata));\n\t\t}\n\t\tfor (const entry of themePaths) {\n\t\t\tthis.extensionThemeSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata));\n\t\t}\n\n\t\tif (skillPaths.length > 0) {\n\t\t\tthis.lastSkillPaths = this.mergePaths(\n\t\t\t\tthis.lastSkillPaths,\n\t\t\t\tskillPaths.map((entry) => entry.path),\n\t\t\t);\n\t\t\tthis.updateSkillsFromPaths(this.lastSkillPaths, this.resourceMetadataByPath);\n\t\t}\n\n\t\tif (promptPaths.length > 0) {\n\t\t\tthis.lastPromptPaths = this.mergePaths(\n\t\t\t\tthis.lastPromptPaths,\n\t\t\t\tpromptPaths.map((entry) => entry.path),\n\t\t\t);\n\t\t\tthis.updatePromptsFromPaths(this.lastPromptPaths, this.resourceMetadataByPath);\n\t\t}\n\n\t\tif (themePaths.length > 0) {\n\t\t\tthis.lastThemePaths = this.mergePaths(\n\t\t\t\tthis.lastThemePaths,\n\t\t\t\tthemePaths.map((entry) => entry.path),\n\t\t\t);\n\t\t\tthis.updateThemesFromPaths(this.lastThemePaths, this.resourceMetadataByPath);\n\t\t}\n\t}\n\n\tasync loadProjectTrustExtensions(): Promise {\n\t\t// Force untrusted project settings for the bootstrap pass. This keeps project-local\n\t\t// extensions/packages out while still loading user/global and temporary CLI extensions.\n\t\tthis.settingsManager.setProjectTrusted(false);\n\t\tawait this.settingsManager.reload();\n\t\treturn this.loadCurrentExtensionSet({ includeInlineFactories: true });\n\t}\n\n\tasync reload(options?: ResourceLoaderReloadOptions): Promise {\n\t\tresetTimings(\"extensions\");\n\n\t\tif (this.loaded) {\n\t\t\tclearExtensionCache();\n\t\t}\n\n\t\tlet preTrustExtensions: LoadExtensionsResult | undefined;\n\t\tif (options?.resolveProjectTrust) {\n\t\t\tpreTrustExtensions = await this.loadProjectTrustExtensions();\n\t\t\tconst projectTrusted = await options.resolveProjectTrust({ extensionsResult: preTrustExtensions });\n\t\t\tthis.settingsManager.setProjectTrusted(projectTrusted);\n\t\t}\n\n\t\t// reload() preserves SettingsManager.projectTrusted and reloads settings for that trust state.\n\t\tawait this.settingsManager.reload();\n\t\tconst resolvedPaths = await this.packageManager.resolve();\n\t\tconst cliExtensionPaths = await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths, {\n\t\t\ttemporary: true,\n\t\t});\n\t\t// Kept on the instance so post-reload passes (extendResources) can still resolve package metadata.\n\t\tthis.resourceMetadataByPath = new Map();\n\t\tconst metadataByPath = this.resourceMetadataByPath;\n\n\t\tthis.extensionSkillSourceInfos = new Map();\n\t\tthis.extensionPromptSourceInfos = new Map();\n\t\tthis.extensionThemeSourceInfos = new Map();\n\n\t\t// Helper to extract enabled paths and store metadata\n\t\tconst getEnabledResources = (resources: ResolvedResource[]): ResolvedResource[] => {\n\t\t\tfor (const r of resources) {\n\t\t\t\tif (!metadataByPath.has(r.path)) {\n\t\t\t\t\tmetadataByPath.set(r.path, r.metadata);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn resources.filter((r) => r.enabled);\n\t\t};\n\n\t\tconst getEnabledPaths = (resources: ResolvedResource[]): string[] =>\n\t\t\tgetEnabledResources(resources).map((r) => r.path);\n\t\tconst enabledExtensions = getEnabledPaths(resolvedPaths.extensions);\n\t\tconst enabledSkillResources = getEnabledResources(resolvedPaths.skills);\n\t\tconst enabledPrompts = getEnabledPaths(resolvedPaths.prompts);\n\t\tconst enabledThemes = getEnabledPaths(resolvedPaths.themes);\n\n\t\tconst enabledSkills = enabledSkillResources.map((resource) => this.mapSkillPath(resource, metadataByPath));\n\n\t\t// Add CLI paths metadata\n\t\tfor (const r of cliExtensionPaths.extensions) {\n\t\t\tif (!metadataByPath.has(r.path)) {\n\t\t\t\tmetadataByPath.set(r.path, { source: \"cli\", scope: \"temporary\", origin: \"top-level\" });\n\t\t\t}\n\t\t}\n\t\tfor (const r of cliExtensionPaths.skills) {\n\t\t\tif (!metadataByPath.has(r.path)) {\n\t\t\t\tmetadataByPath.set(r.path, { source: \"cli\", scope: \"temporary\", origin: \"top-level\" });\n\t\t\t}\n\t\t}\n\n\t\tconst cliEnabledExtensions = getEnabledPaths(cliExtensionPaths.extensions);\n\t\tconst cliEnabledSkills = getEnabledPaths(cliExtensionPaths.skills);\n\t\tconst cliEnabledPrompts = getEnabledPaths(cliExtensionPaths.prompts);\n\t\tconst cliEnabledThemes = getEnabledPaths(cliExtensionPaths.themes);\n\n\t\tconst extensionPaths = this.noExtensions\n\t\t\t? cliEnabledExtensions\n\t\t\t: this.mergePaths(cliEnabledExtensions, enabledExtensions);\n\n\t\tconst extensionsResult = await this.loadFinalExtensionSet(extensionPaths, preTrustExtensions);\n\t\tfor (const p of this.additionalExtensionPaths) {\n\t\t\tif (isLocalPath(p)) {\n\t\t\t\tconst resolved = this.resolveResourcePath(p);\n\t\t\t\tif (!existsSync(resolved)) {\n\t\t\t\t\textensionsResult.errors.push({ path: resolved, error: `Extension path does not exist: ${resolved}` });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.extensionsResult = this.extensionsOverride ? this.extensionsOverride(extensionsResult) : extensionsResult;\n\t\tthis.applyExtensionSourceInfo(this.extensionsResult.extensions, metadataByPath);\n\n\t\tconst skillPaths = this.noSkills\n\t\t\t? this.mergePaths(cliEnabledSkills, this.additionalSkillPaths)\n\t\t\t: this.mergePaths([...cliEnabledSkills, ...enabledSkills], this.additionalSkillPaths);\n\n\t\tthis.lastSkillPaths = skillPaths;\n\t\tthis.updateSkillsFromPaths(skillPaths, metadataByPath);\n\t\tfor (const p of this.additionalSkillPaths) {\n\t\t\tif (isLocalPath(p)) {\n\t\t\t\tconst resolved = this.resolveResourcePath(p);\n\t\t\t\tif (!existsSync(resolved) && !this.skillDiagnostics.some((d) => d.path === resolved)) {\n\t\t\t\t\tthis.skillDiagnostics.push({ type: \"error\", message: \"Skill path does not exist\", path: resolved });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst promptPaths = this.noPromptTemplates\n\t\t\t? this.mergePaths(cliEnabledPrompts, this.additionalPromptTemplatePaths)\n\t\t\t: this.mergePaths([...cliEnabledPrompts, ...enabledPrompts], this.additionalPromptTemplatePaths);\n\n\t\tthis.lastPromptPaths = promptPaths;\n\t\tthis.updatePromptsFromPaths(promptPaths, metadataByPath);\n\t\tfor (const p of this.additionalPromptTemplatePaths) {\n\t\t\tif (isLocalPath(p)) {\n\t\t\t\tconst resolved = this.resolveResourcePath(p);\n\t\t\t\tif (!existsSync(resolved) && !this.promptDiagnostics.some((d) => d.path === resolved)) {\n\t\t\t\t\tthis.promptDiagnostics.push({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\tmessage: \"Prompt template path does not exist\",\n\t\t\t\t\t\tpath: resolved,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst themePaths = this.noThemes\n\t\t\t? this.mergePaths(cliEnabledThemes, this.additionalThemePaths)\n\t\t\t: this.mergePaths([...cliEnabledThemes, ...enabledThemes], this.additionalThemePaths);\n\n\t\tthis.lastThemePaths = themePaths;\n\t\tthis.updateThemesFromPaths(themePaths, metadataByPath);\n\t\tfor (const p of this.additionalThemePaths) {\n\t\t\tconst resolved = this.resolveResourcePath(p);\n\t\t\tif (!existsSync(resolved) && !this.themeDiagnostics.some((d) => d.path === resolved)) {\n\t\t\t\tthis.themeDiagnostics.push({ type: \"error\", message: \"Theme path does not exist\", path: resolved });\n\t\t\t}\n\t\t}\n\n\t\tconst agentsFiles = {\n\t\t\tagentsFiles: this.noContextFiles\n\t\t\t\t? []\n\t\t\t\t: loadProjectContextFiles({\n\t\t\t\t\t\tcwd: this.cwd,\n\t\t\t\t\t\tagentDir: this.agentDir,\n\t\t\t\t\t}),\n\t\t};\n\t\tconst resolvedAgentsFiles = this.agentsFilesOverride ? this.agentsFilesOverride(agentsFiles) : agentsFiles;\n\t\tthis.agentsFiles = resolvedAgentsFiles.agentsFiles;\n\n\t\tconst systemPromptSource = this.systemPromptSource ?? this.discoverSystemPromptFile();\n\t\tconst baseSystemPrompt = resolvePromptInput(systemPromptSource, \"system prompt\");\n\t\tthis.systemPrompt = this.systemPromptOverride ? this.systemPromptOverride(baseSystemPrompt) : baseSystemPrompt;\n\t\tthis.systemPromptSourcePath =\n\t\t\tsystemPromptSource && existsSync(systemPromptSource) ? resolvePath(systemPromptSource) : undefined;\n\n\t\tlet appendSources = this.appendSystemPromptSource;\n\t\tif (!appendSources) {\n\t\t\tconst discoveredAppendSystemPromptFile = this.discoverAppendSystemPromptFile();\n\t\t\tappendSources = discoveredAppendSystemPromptFile ? [discoveredAppendSystemPromptFile] : [];\n\t\t}\n\t\tconst baseAppend = appendSources\n\t\t\t.map((s) => resolvePromptInput(s, \"append system prompt\"))\n\t\t\t.filter((s): s is string => s !== undefined);\n\t\tthis.appendSystemPrompt = this.appendSystemPromptOverride\n\t\t\t? this.appendSystemPromptOverride(baseAppend)\n\t\t\t: baseAppend;\n\t\tthis.appendSystemPromptSourcePaths = appendSources\n\t\t\t.filter((source) => existsSync(source))\n\t\t\t.map((source) => resolvePath(source));\n\t\tthis.loaded = true;\n\t}\n\n\tprivate async loadCurrentExtensionSet(options: { includeInlineFactories: boolean }): Promise {\n\t\tconst resolvedPaths = await this.packageManager.resolve();\n\t\tconst cliExtensionPaths = await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths, {\n\t\t\ttemporary: true,\n\t\t});\n\t\tconst enabledExtensions = resolvedPaths.extensions.filter((r) => r.enabled).map((r) => r.path);\n\t\tconst cliEnabledExtensions = cliExtensionPaths.extensions.filter((r) => r.enabled).map((r) => r.path);\n\t\tconst extensionPaths = this.noExtensions\n\t\t\t? cliEnabledExtensions\n\t\t\t: this.mergePaths(cliEnabledExtensions, enabledExtensions);\n\t\tconst extensionsResult = await loadExtensionsCached(extensionPaths, this.cwd, this.eventBus);\n\t\tif (!options.includeInlineFactories) {\n\t\t\treturn extensionsResult;\n\t\t}\n\n\t\tconst inlineExtensions = await this.loadExtensionFactories(extensionsResult.runtime);\n\t\textensionsResult.extensions.push(...inlineExtensions.extensions);\n\t\textensionsResult.errors.push(...inlineExtensions.errors);\n\t\treturn extensionsResult;\n\t}\n\n\tprivate resolveExtensionLoadPath(path: string): string {\n\t\treturn resolvePath(path, this.cwd, { normalizeUnicodeSpaces: true });\n\t}\n\n\tprivate async loadFinalExtensionSet(\n\t\textensionPaths: string[],\n\t\tpreTrustExtensions: LoadExtensionsResult | undefined,\n\t): Promise {\n\t\tif (!preTrustExtensions) {\n\t\t\tconst extensionsResult = await loadExtensionsCached(extensionPaths, this.cwd, this.eventBus);\n\t\t\tconst inlineExtensions = await this.loadExtensionFactories(extensionsResult.runtime);\n\t\t\textensionsResult.extensions.push(...inlineExtensions.extensions);\n\t\t\textensionsResult.errors.push(...inlineExtensions.errors);\n\t\t\tthis.addExtensionConflictDiagnostics(extensionsResult);\n\t\t\treturn extensionsResult;\n\t\t}\n\n\t\tconst preloadedByPath = new Map(\n\t\t\tpreTrustExtensions.extensions\n\t\t\t\t.filter((extension) => !extension.path.startsWith(\" [extension.resolvedPath, extension]),\n\t\t);\n\t\tconst failedPreloadPaths = new Set(\n\t\t\tpreTrustExtensions.errors.map((error) => this.resolveExtensionLoadPath(error.path)),\n\t\t);\n\t\tconst remainingPaths = extensionPaths.filter((path) => {\n\t\t\tconst resolvedPath = this.resolveExtensionLoadPath(path);\n\t\t\treturn !preloadedByPath.has(resolvedPath) && !failedPreloadPaths.has(resolvedPath);\n\t\t});\n\t\tconst remainingExtensions = await loadExtensionsCached(\n\t\t\tremainingPaths,\n\t\t\tthis.cwd,\n\t\t\tthis.eventBus,\n\t\t\tpreTrustExtensions.runtime,\n\t\t);\n\t\tconst loadedByPath = new Map(preloadedByPath);\n\t\tfor (const extension of remainingExtensions.extensions) {\n\t\t\tloadedByPath.set(extension.resolvedPath, extension);\n\t\t}\n\n\t\tconst inlineExtensions = preTrustExtensions.extensions.filter((extension) =>\n\t\t\textension.path.startsWith(\" loadedByPath.get(this.resolveExtensionLoadPath(path)))\n\t\t\t.filter((extension): extension is Extension => extension !== undefined);\n\t\torderedExtensions.push(...inlineExtensions);\n\n\t\tconst extensionsResult: LoadExtensionsResult = {\n\t\t\textensions: orderedExtensions,\n\t\t\terrors: [...preTrustExtensions.errors, ...remainingExtensions.errors],\n\t\t\truntime: preTrustExtensions.runtime,\n\t\t};\n\t\tthis.addExtensionConflictDiagnostics(extensionsResult);\n\t\treturn extensionsResult;\n\t}\n\n\tprivate addExtensionConflictDiagnostics(extensionsResult: LoadExtensionsResult): void {\n\t\t// Detect extension conflicts (tools, commands, flags with same names from different extensions)\n\t\t// Keep all extensions loaded. Conflicts are reported as diagnostics, and precedence is handled by load order.\n\t\tconst conflicts = this.detectExtensionConflicts(extensionsResult.extensions);\n\t\tfor (const conflict of conflicts) {\n\t\t\textensionsResult.errors.push({ path: conflict.path, error: conflict.message });\n\t\t}\n\t}\n\n\tprivate mapSkillPath(resource: ResolvedResource, metadataByPath: Map): string {\n\t\tif (resource.metadata.source !== \"auto\" && resource.metadata.origin !== \"package\") {\n\t\t\treturn resource.path;\n\t\t}\n\t\ttry {\n\t\t\tconst stats = statSync(resource.path);\n\t\t\tif (!stats.isDirectory()) {\n\t\t\t\treturn resource.path;\n\t\t\t}\n\t\t} catch {\n\t\t\treturn resource.path;\n\t\t}\n\t\tconst skillFile = join(resource.path, \"SKILL.md\");\n\t\tif (existsSync(skillFile)) {\n\t\t\tif (!metadataByPath.has(skillFile)) {\n\t\t\t\tmetadataByPath.set(skillFile, resource.metadata);\n\t\t\t}\n\t\t\treturn skillFile;\n\t\t}\n\t\treturn resource.path;\n\t}\n\n\tprivate normalizeExtensionPaths(\n\t\tentries: Array<{ path: string; metadata: PathMetadata }>,\n\t): Array<{ path: string; metadata: PathMetadata }> {\n\t\treturn entries.map((entry) => {\n\t\t\tconst metadata = entry.metadata.baseDir\n\t\t\t\t? { ...entry.metadata, baseDir: this.resolveResourcePath(entry.metadata.baseDir) }\n\t\t\t\t: entry.metadata;\n\t\t\treturn {\n\t\t\t\tpath: this.resolveResourcePath(entry.path),\n\t\t\t\tmetadata,\n\t\t\t};\n\t\t});\n\t}\n\n\tprivate updateSkillsFromPaths(skillPaths: string[], metadataByPath?: Map): void {\n\t\tlet skillsResult: { skills: Skill[]; diagnostics: ResourceDiagnostic[] };\n\t\tif (this.noSkills && skillPaths.length === 0) {\n\t\t\tskillsResult = { skills: [], diagnostics: [] };\n\t\t} else {\n\t\t\tskillsResult = loadSkills({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.agentDir,\n\t\t\t\tskillPaths,\n\t\t\t\tincludeDefaults: false,\n\t\t\t});\n\t\t}\n\t\tconst resolvedSkills = this.skillsOverride ? this.skillsOverride(skillsResult) : skillsResult;\n\t\tthis.skills = resolvedSkills.skills.map((skill) => ({\n\t\t\t...skill,\n\t\t\tsourceInfo:\n\t\t\t\tthis.findSourceInfoForPath(skill.filePath, this.extensionSkillSourceInfos, metadataByPath) ??\n\t\t\t\tskill.sourceInfo ??\n\t\t\t\tthis.getDefaultSourceInfoForPath(skill.filePath),\n\t\t}));\n\t\tthis.skillDiagnostics = resolvedSkills.diagnostics;\n\t}\n\n\tprivate updatePromptsFromPaths(promptPaths: string[], metadataByPath?: Map): void {\n\t\tlet promptsResult: { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] };\n\t\tif (this.noPromptTemplates && promptPaths.length === 0) {\n\t\t\tpromptsResult = { prompts: [], diagnostics: [] };\n\t\t} else {\n\t\t\tconst allPrompts = loadPromptTemplates({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.agentDir,\n\t\t\t\tpromptPaths,\n\t\t\t\tincludeDefaults: false,\n\t\t\t});\n\t\t\tpromptsResult = this.dedupePrompts(allPrompts);\n\t\t}\n\t\tconst resolvedPrompts = this.promptsOverride ? this.promptsOverride(promptsResult) : promptsResult;\n\t\tthis.prompts = resolvedPrompts.prompts.map((prompt) => ({\n\t\t\t...prompt,\n\t\t\tsourceInfo:\n\t\t\t\tthis.findSourceInfoForPath(prompt.filePath, this.extensionPromptSourceInfos, metadataByPath) ??\n\t\t\t\tprompt.sourceInfo ??\n\t\t\t\tthis.getDefaultSourceInfoForPath(prompt.filePath),\n\t\t}));\n\t\tthis.promptDiagnostics = resolvedPrompts.diagnostics;\n\t}\n\n\tprivate updateThemesFromPaths(themePaths: string[], metadataByPath?: Map): void {\n\t\tlet themesResult: { themes: Theme[]; diagnostics: ResourceDiagnostic[] };\n\t\tif (this.noThemes && themePaths.length === 0) {\n\t\t\tthemesResult = { themes: [], diagnostics: [] };\n\t\t} else {\n\t\t\tconst loaded = this.loadThemes(themePaths, false);\n\t\t\tconst deduped = this.dedupeThemes(loaded.themes);\n\t\t\tthemesResult = { themes: deduped.themes, diagnostics: [...loaded.diagnostics, ...deduped.diagnostics] };\n\t\t}\n\t\tconst resolvedThemes = this.themesOverride ? this.themesOverride(themesResult) : themesResult;\n\t\tthis.themes = resolvedThemes.themes.map((theme) => {\n\t\t\tconst sourcePath = theme.sourcePath;\n\t\t\ttheme.sourceInfo = sourcePath\n\t\t\t\t? (this.findSourceInfoForPath(sourcePath, this.extensionThemeSourceInfos, metadataByPath) ??\n\t\t\t\t\ttheme.sourceInfo ??\n\t\t\t\t\tthis.getDefaultSourceInfoForPath(sourcePath))\n\t\t\t\t: theme.sourceInfo;\n\t\t\treturn theme;\n\t\t});\n\t\tthis.themeDiagnostics = resolvedThemes.diagnostics;\n\t}\n\n\tprivate applyExtensionSourceInfo(extensions: Extension[], metadataByPath: Map): void {\n\t\tfor (const extension of extensions) {\n\t\t\textension.sourceInfo =\n\t\t\t\tthis.findSourceInfoForPath(extension.path, undefined, metadataByPath) ??\n\t\t\t\tthis.getDefaultSourceInfoForPath(extension.path);\n\t\t\tfor (const command of extension.commands.values()) {\n\t\t\t\tcommand.sourceInfo = extension.sourceInfo;\n\t\t\t}\n\t\t\tfor (const tool of extension.tools.values()) {\n\t\t\t\ttool.sourceInfo = extension.sourceInfo;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate findSourceInfoForPath(\n\t\tresourcePath: string,\n\t\textraSourceInfos?: Map,\n\t\tmetadataByPath?: Map,\n\t): SourceInfo | undefined {\n\t\tif (!resourcePath) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (resourcePath.startsWith(\"<\")) {\n\t\t\treturn this.getDefaultSourceInfoForPath(resourcePath);\n\t\t}\n\n\t\tconst normalizedResourcePath = resolve(resourcePath);\n\t\tif (extraSourceInfos) {\n\t\t\tfor (const [sourcePath, sourceInfo] of extraSourceInfos.entries()) {\n\t\t\t\tconst normalizedSourcePath = resolve(sourcePath);\n\t\t\t\tif (\n\t\t\t\t\tnormalizedResourcePath === normalizedSourcePath ||\n\t\t\t\t\tnormalizedResourcePath.startsWith(`${normalizedSourcePath}${sep}`)\n\t\t\t\t) {\n\t\t\t\t\treturn { ...sourceInfo, path: resourcePath };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (metadataByPath) {\n\t\t\tconst exact = metadataByPath.get(normalizedResourcePath) ?? metadataByPath.get(resourcePath);\n\t\t\tif (exact) {\n\t\t\t\treturn createSourceInfo(resourcePath, exact);\n\t\t\t}\n\n\t\t\tfor (const [sourcePath, metadata] of metadataByPath.entries()) {\n\t\t\t\tconst normalizedSourcePath = resolve(sourcePath);\n\t\t\t\tif (\n\t\t\t\t\tnormalizedResourcePath === normalizedSourcePath ||\n\t\t\t\t\tnormalizedResourcePath.startsWith(`${normalizedSourcePath}${sep}`)\n\t\t\t\t) {\n\t\t\t\t\treturn createSourceInfo(resourcePath, metadata);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate getDefaultSourceInfoForPath(filePath: string): SourceInfo {\n\t\tif (filePath.startsWith(\"<\") && filePath.endsWith(\">\")) {\n\t\t\treturn {\n\t\t\t\tpath: filePath,\n\t\t\t\tsource: filePath.slice(1, -1).split(\":\")[0] || \"temporary\",\n\t\t\t\tscope: \"temporary\",\n\t\t\t\torigin: \"top-level\",\n\t\t\t};\n\t\t}\n\n\t\tconst normalizedPath = resolve(filePath);\n\t\tconst agentRoots = [\n\t\t\tjoin(this.agentDir, \"skills\"),\n\t\t\tjoin(this.agentDir, \"prompts\"),\n\t\t\tjoin(this.agentDir, \"themes\"),\n\t\t\tjoin(this.agentDir, \"extensions\"),\n\t\t];\n\t\tconst projectRoots = [\n\t\t\tjoin(this.cwd, CONFIG_DIR_NAME, \"skills\"),\n\t\t\tjoin(this.cwd, CONFIG_DIR_NAME, \"prompts\"),\n\t\t\tjoin(this.cwd, CONFIG_DIR_NAME, \"themes\"),\n\t\t\tjoin(this.cwd, CONFIG_DIR_NAME, \"extensions\"),\n\t\t];\n\n\t\tfor (const root of agentRoots) {\n\t\t\tif (this.isUnderPath(normalizedPath, root)) {\n\t\t\t\treturn { path: filePath, source: \"local\", scope: \"user\", origin: \"top-level\", baseDir: root };\n\t\t\t}\n\t\t}\n\n\t\tfor (const root of projectRoots) {\n\t\t\tif (this.isUnderPath(normalizedPath, root)) {\n\t\t\t\treturn { path: filePath, source: \"local\", scope: \"project\", origin: \"top-level\", baseDir: root };\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tpath: filePath,\n\t\t\tsource: \"local\",\n\t\t\tscope: \"temporary\",\n\t\t\torigin: \"top-level\",\n\t\t\tbaseDir: statSync(normalizedPath).isDirectory() ? normalizedPath : resolve(normalizedPath, \"..\"),\n\t\t};\n\t}\n\n\tprivate mergePaths(primary: string[], additional: string[]): string[] {\n\t\tconst merged: string[] = [];\n\t\tconst seen = new Set();\n\n\t\tfor (const p of [...primary, ...additional]) {\n\t\t\tconst resolved = this.resolveResourcePath(p);\n\t\t\tconst canonicalPath = canonicalizePath(resolved);\n\t\t\tif (seen.has(canonicalPath)) continue;\n\t\t\tseen.add(canonicalPath);\n\t\t\tmerged.push(resolved);\n\t\t}\n\n\t\treturn merged;\n\t}\n\n\tprivate resolveResourcePath(p: string): string {\n\t\treturn resolvePath(p, this.cwd, { trim: true });\n\t}\n\n\tprivate loadThemes(\n\t\tpaths: string[],\n\t\tincludeDefaults: boolean = true,\n\t): {\n\t\tthemes: Theme[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t} {\n\t\tconst themes: Theme[] = [];\n\t\tconst diagnostics: ResourceDiagnostic[] = [];\n\t\tif (includeDefaults) {\n\t\t\tconst defaultDirs = [join(this.agentDir, \"themes\"), join(this.cwd, CONFIG_DIR_NAME, \"themes\")];\n\n\t\t\tfor (const dir of defaultDirs) {\n\t\t\t\tthis.loadThemesFromDir(dir, themes, diagnostics);\n\t\t\t}\n\t\t}\n\n\t\tfor (const p of paths) {\n\t\t\tconst resolved = this.resolveResourcePath(p);\n\t\t\tif (!existsSync(resolved)) {\n\t\t\t\tdiagnostics.push({ type: \"warning\", message: \"theme path does not exist\", path: resolved });\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst stats = statSync(resolved);\n\t\t\t\tif (stats.isDirectory()) {\n\t\t\t\t\tthis.loadThemesFromDir(resolved, themes, diagnostics);\n\t\t\t\t} else if (stats.isFile() && resolved.endsWith(\".json\")) {\n\t\t\t\t\tthis.loadThemeFromFile(resolved, themes, diagnostics);\n\t\t\t\t} else {\n\t\t\t\t\tdiagnostics.push({ type: \"warning\", message: \"theme path is not a json file\", path: resolved });\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : \"failed to read theme path\";\n\t\t\t\tdiagnostics.push({ type: \"warning\", message, path: resolved });\n\t\t\t}\n\t\t}\n\n\t\treturn { themes, diagnostics };\n\t}\n\n\tprivate loadThemesFromDir(dir: string, themes: Theme[], diagnostics: ResourceDiagnostic[]): void {\n\t\tif (!existsSync(dir)) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst entries = readdirSync(dir, { withFileTypes: true });\n\t\t\tfor (const entry of entries) {\n\t\t\t\tlet isFile = entry.isFile();\n\t\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tisFile = statSync(join(dir, entry.name)).isFile();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!isFile) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!entry.name.endsWith(\".json\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis.loadThemeFromFile(join(dir, entry.name), themes, diagnostics);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read theme directory\";\n\t\t\tdiagnostics.push({ type: \"warning\", message, path: dir });\n\t\t}\n\t}\n\n\tprivate loadThemeFromFile(filePath: string, themes: Theme[], diagnostics: ResourceDiagnostic[]): void {\n\t\ttry {\n\t\t\tthemes.push(loadThemeFromPath(filePath));\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to load theme\";\n\t\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\t}\n\t}\n\n\tprivate async loadExtensionFactories(runtime: ExtensionRuntime): Promise<{\n\t\textensions: Extension[];\n\t\terrors: Array<{ path: string; error: string }>;\n\t}> {\n\t\tconst extensions: Extension[] = [];\n\t\tconst errors: Array<{ path: string; error: string }> = [];\n\n\t\tfor (const [index, input] of this.extensionFactories.entries()) {\n\t\t\tconst isNamed = typeof input !== \"function\";\n\t\t\tconst factory = isNamed ? input.factory : input;\n\t\t\tconst extensionPath = ``;\n\t\t\ttry {\n\t\t\t\tconst extension = await loadExtensionFromFactory(factory, this.cwd, this.eventBus, runtime, extensionPath);\n\t\t\t\textension.hidden = isNamed && input.hidden;\n\t\t\t\textensions.push(extension);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : \"failed to load extension\";\n\t\t\t\terrors.push({ path: extensionPath, error: message });\n\t\t\t}\n\t\t}\n\n\t\treturn { extensions, errors };\n\t}\n\n\tprivate dedupePrompts(prompts: PromptTemplate[]): { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] } {\n\t\tconst seen = new Map();\n\t\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\t\tfor (const prompt of prompts) {\n\t\t\tconst existing = seen.get(prompt.name);\n\t\t\tif (existing) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"collision\",\n\t\t\t\t\tmessage: `name \"/${prompt.name}\" collision`,\n\t\t\t\t\tpath: prompt.filePath,\n\t\t\t\t\tcollision: {\n\t\t\t\t\t\tresourceType: \"prompt\",\n\t\t\t\t\t\tname: prompt.name,\n\t\t\t\t\t\twinnerPath: existing.filePath,\n\t\t\t\t\t\tloserPath: prompt.filePath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tseen.set(prompt.name, prompt);\n\t\t\t}\n\t\t}\n\n\t\treturn { prompts: Array.from(seen.values()), diagnostics };\n\t}\n\n\tprivate dedupeThemes(themes: Theme[]): { themes: Theme[]; diagnostics: ResourceDiagnostic[] } {\n\t\tconst seen = new Map();\n\t\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\t\tfor (const t of themes) {\n\t\t\tconst name = t.name ?? \"unnamed\";\n\t\t\tconst existing = seen.get(name);\n\t\t\tif (existing) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"collision\",\n\t\t\t\t\tmessage: `name \"${name}\" collision`,\n\t\t\t\t\tpath: t.sourcePath,\n\t\t\t\t\tcollision: {\n\t\t\t\t\t\tresourceType: \"theme\",\n\t\t\t\t\t\tname,\n\t\t\t\t\t\twinnerPath: existing.sourcePath ?? \"\",\n\t\t\t\t\t\tloserPath: t.sourcePath ?? \"\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tseen.set(name, t);\n\t\t\t}\n\t\t}\n\n\t\treturn { themes: Array.from(seen.values()), diagnostics };\n\t}\n\n\tprivate discoverSystemPromptFile(): string | undefined {\n\t\tconst projectPath = join(this.cwd, CONFIG_DIR_NAME, \"SYSTEM.md\");\n\t\tif (this.settingsManager.isProjectTrusted() && existsSync(projectPath)) {\n\t\t\treturn projectPath;\n\t\t}\n\n\t\tconst globalPath = join(this.agentDir, \"SYSTEM.md\");\n\t\tif (existsSync(globalPath)) {\n\t\t\treturn globalPath;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate discoverAppendSystemPromptFile(): string | undefined {\n\t\tconst projectPath = join(this.cwd, CONFIG_DIR_NAME, \"APPEND_SYSTEM.md\");\n\t\tif (this.settingsManager.isProjectTrusted() && existsSync(projectPath)) {\n\t\t\treturn projectPath;\n\t\t}\n\n\t\tconst globalPath = join(this.agentDir, \"APPEND_SYSTEM.md\");\n\t\tif (existsSync(globalPath)) {\n\t\t\treturn globalPath;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate isUnderPath(target: string, root: string): boolean {\n\t\tconst normalizedRoot = resolve(root);\n\t\tif (target === normalizedRoot) {\n\t\t\treturn true;\n\t\t}\n\t\tconst prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;\n\t\treturn target.startsWith(prefix);\n\t}\n\n\tprivate detectExtensionConflicts(extensions: Extension[]): Array<{ path: string; message: string }> {\n\t\tconst conflicts: Array<{ path: string; message: string }> = [];\n\n\t\t// Track which extension registered each tool and flag\n\t\tconst toolOwners = new Map();\n\t\tconst flagOwners = new Map();\n\n\t\tfor (const ext of extensions) {\n\t\t\t// Check tools\n\t\t\tfor (const toolName of ext.tools.keys()) {\n\t\t\t\tconst existingOwner = toolOwners.get(toolName);\n\t\t\t\tif (existingOwner && existingOwner !== ext.path) {\n\t\t\t\t\tconflicts.push({\n\t\t\t\t\t\tpath: ext.path,\n\t\t\t\t\t\tmessage: `Tool \"${toolName}\" conflicts with ${existingOwner}`,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\ttoolOwners.set(toolName, ext.path);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check flags\n\t\t\tfor (const flagName of ext.flags.keys()) {\n\t\t\t\tconst existingOwner = flagOwners.get(flagName);\n\t\t\t\tif (existingOwner && existingOwner !== ext.path) {\n\t\t\t\t\tconflicts.push({\n\t\t\t\t\t\tpath: ext.path,\n\t\t\t\t\t\tmessage: `Flag \"--${flagName}\" conflicts with ${existingOwner}`,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tflagOwners.set(flagName, ext.path);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn conflicts;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/resource-loader.js b/dist/core/resource-loader.js new file mode 100644 index 0000000..1313dd9 --- /dev/null +++ b/dist/core/resource-loader.js @@ -0,0 +1,874 @@ +import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; +import { basename, dirname, join, resolve, sep } from "node:path"; +import chalk from "chalk"; +import { CONFIG_DIR_NAME } from "../config.js"; +import { loadThemeFromPath } from "../modes/interactive/theme/theme.js"; +import { canonicalizePath, isLocalPath, resolvePath } from "../utils/paths.js"; +import { createEventBus } from "./event-bus.js"; +import { clearExtensionCache, createExtensionRuntime, loadExtensionFromFactory, loadExtensionsCached, } from "./extensions/loader.js"; +import { findGitPaths } from "./footer-data-provider.js"; +import { DefaultPackageManager } from "./package-manager.js"; +import { loadPromptTemplates } from "./prompt-templates.js"; +import { SettingsManager } from "./settings-manager.js"; +import { loadSkills } from "./skills.js"; +import { createSourceInfo } from "./source-info.js"; +import { resetTimings } from "./timings.js"; +function resolvePromptInput(input, description) { + if (!input) { + return undefined; + } + if (existsSync(input)) { + try { + return readFileSync(input, "utf-8"); + } + catch (error) { + console.error(chalk.yellow(`Warning: Could not read ${description} file ${input}: ${error}`)); + return input; + } + } + return input; +} +function loadContextFileFromDir(dir) { + const candidates = ["AGENTS.md", "AGENTS.MD", "CLAUDE.md", "CLAUDE.MD"]; + for (const filename of candidates) { + const filePath = join(dir, filename); + if (existsSync(filePath)) { + try { + if (!statSync(filePath).isFile()) { + continue; + } + return { + path: filePath, + content: readFileSync(filePath, "utf-8"), + }; + } + catch (error) { + console.error(chalk.yellow(`Warning: Could not read ${filePath}: ${error}`)); + } + } + } + return null; +} +/** + * The main repo's context file that a nested linked worktree's own copy shadows: both + * are the same tracked AGENTS.md/CLAUDE.md, so loading both loads it twice. Returns + * undefined when nothing is shadowed, leaving normal ancestor inheritance alone. + * + * Returned canonicalized (realpath), because `git worktree add` writes the `.git` + * file's `gitdir:` target in realpath form while cwd may still be symlinked + * (macOS `/tmp` -> `/private/tmp`). + */ +function findShadowedContextFile(cwd) { + const gitPaths = findGitPaths(cwd); + if (!gitPaths) + return undefined; + const commonGitDir = canonicalizePath(gitPaths.commonGitDir); + const worktreeRoot = canonicalizePath(gitPaths.repoDir); + const mainRepoRoot = dirname(commonGitDir); + // False for an ordinary repo, where the two are the same dir, and for a sibling + // worktree (`git worktree add ../feat`), whose main repo is not an ancestor. + if (!worktreeRoot.startsWith(`${mainRepoRoot}${sep}`)) + return undefined; + // dirname of the common git dir is the main worktree root only when that dir is + // itself checked out from the same repo. In a bare layout (`proj/.bare` + + // `proj/main`) it is just the directory holding `.bare`, which tracks nothing; a + // submodule's gitdir has no `commondir`, so it lands under `.git/modules`. + if (canonicalizePath(join(mainRepoRoot, ".git")) !== commonGitDir) + return undefined; + const worktreeContextFile = loadContextFileFromDir(worktreeRoot); + return worktreeContextFile ? join(mainRepoRoot, basename(worktreeContextFile.path)) : undefined; +} +export function loadProjectContextFiles(options) { + const resolvedCwd = resolvePath(options.cwd); + const resolvedAgentDir = resolvePath(options.agentDir); + const contextFiles = []; + const seenPaths = new Set(); + const globalContext = loadContextFileFromDir(resolvedAgentDir); + if (globalContext) { + contextFiles.push(globalContext); + seenPaths.add(globalContext.path); + } + const ancestorContextFiles = []; + const shadowedContextFile = findShadowedContextFile(resolvedCwd); + let currentDir = resolvedCwd; + while (true) { + const contextFile = loadContextFileFromDir(currentDir); + const isShadowed = shadowedContextFile !== undefined && canonicalizePath(contextFile?.path ?? "") === shadowedContextFile; + if (contextFile && !isShadowed && !seenPaths.has(contextFile.path)) { + ancestorContextFiles.unshift(contextFile); + seenPaths.add(contextFile.path); + } + const parentDir = dirname(currentDir); + if (parentDir === currentDir) + break; + currentDir = parentDir; + } + contextFiles.push(...ancestorContextFiles); + return contextFiles; +} +export class DefaultResourceLoader { + cwd; + agentDir; + settingsManager; + eventBus; + packageManager; + additionalExtensionPaths; + additionalSkillPaths; + additionalPromptTemplatePaths; + additionalThemePaths; + extensionFactories; + noExtensions; + noSkills; + noPromptTemplates; + noThemes; + noContextFiles; + systemPromptSource; + appendSystemPromptSource; + extensionsOverride; + skillsOverride; + promptsOverride; + themesOverride; + agentsFilesOverride; + systemPromptOverride; + appendSystemPromptOverride; + extensionsResult; + skills; + skillDiagnostics; + prompts; + promptDiagnostics; + themes; + themeDiagnostics; + agentsFiles; + systemPrompt; + systemPromptSourcePath; + appendSystemPrompt; + appendSystemPromptSourcePaths; + lastSkillPaths; + extensionSkillSourceInfos; + extensionPromptSourceInfos; + extensionThemeSourceInfos; + resourceMetadataByPath; + lastPromptPaths; + lastThemePaths; + loaded; + constructor(options) { + this.cwd = resolvePath(options.cwd); + this.agentDir = resolvePath(options.agentDir); + this.settingsManager = options.settingsManager ?? SettingsManager.create(this.cwd, this.agentDir); + this.eventBus = options.eventBus ?? createEventBus(); + this.packageManager = new DefaultPackageManager({ + cwd: this.cwd, + agentDir: this.agentDir, + settingsManager: this.settingsManager, + }); + this.additionalExtensionPaths = options.additionalExtensionPaths ?? []; + this.additionalSkillPaths = options.additionalSkillPaths ?? []; + this.additionalPromptTemplatePaths = options.additionalPromptTemplatePaths ?? []; + this.additionalThemePaths = options.additionalThemePaths ?? []; + this.extensionFactories = options.extensionFactories ?? []; + this.noExtensions = options.noExtensions ?? false; + this.noSkills = options.noSkills ?? false; + this.noPromptTemplates = options.noPromptTemplates ?? false; + this.noThemes = options.noThemes ?? false; + this.noContextFiles = options.noContextFiles ?? false; + this.systemPromptSource = options.systemPrompt; + this.appendSystemPromptSource = options.appendSystemPrompt; + this.extensionsOverride = options.extensionsOverride; + this.skillsOverride = options.skillsOverride; + this.promptsOverride = options.promptsOverride; + this.themesOverride = options.themesOverride; + this.agentsFilesOverride = options.agentsFilesOverride; + this.systemPromptOverride = options.systemPromptOverride; + this.appendSystemPromptOverride = options.appendSystemPromptOverride; + this.extensionsResult = { extensions: [], errors: [], runtime: createExtensionRuntime() }; + this.skills = []; + this.skillDiagnostics = []; + this.prompts = []; + this.promptDiagnostics = []; + this.themes = []; + this.themeDiagnostics = []; + this.agentsFiles = []; + this.appendSystemPrompt = []; + this.appendSystemPromptSourcePaths = []; + this.lastSkillPaths = []; + this.extensionSkillSourceInfos = new Map(); + this.extensionPromptSourceInfos = new Map(); + this.extensionThemeSourceInfos = new Map(); + this.resourceMetadataByPath = new Map(); + this.lastPromptPaths = []; + this.lastThemePaths = []; + this.loaded = false; + } + getExtensions() { + return this.extensionsResult; + } + getSkills() { + return { skills: this.skills, diagnostics: this.skillDiagnostics }; + } + getPrompts() { + return { prompts: this.prompts, diagnostics: this.promptDiagnostics }; + } + getThemes() { + return { themes: this.themes, diagnostics: this.themeDiagnostics }; + } + getAgentsFiles() { + return { agentsFiles: this.agentsFiles }; + } + getSystemPrompt() { + return this.systemPrompt; + } + getSystemPromptSource() { + return this.systemPromptSourcePath ? { path: this.systemPromptSourcePath } : undefined; + } + getAppendSystemPrompt() { + return this.appendSystemPrompt; + } + getAppendSystemPromptSources() { + return this.appendSystemPromptSourcePaths.map((path) => ({ path })); + } + extendResources(paths) { + const skillPaths = this.normalizeExtensionPaths(paths.skillPaths ?? []); + const promptPaths = this.normalizeExtensionPaths(paths.promptPaths ?? []); + const themePaths = this.normalizeExtensionPaths(paths.themePaths ?? []); + for (const entry of skillPaths) { + this.extensionSkillSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata)); + } + for (const entry of promptPaths) { + this.extensionPromptSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata)); + } + for (const entry of themePaths) { + this.extensionThemeSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata)); + } + if (skillPaths.length > 0) { + this.lastSkillPaths = this.mergePaths(this.lastSkillPaths, skillPaths.map((entry) => entry.path)); + this.updateSkillsFromPaths(this.lastSkillPaths, this.resourceMetadataByPath); + } + if (promptPaths.length > 0) { + this.lastPromptPaths = this.mergePaths(this.lastPromptPaths, promptPaths.map((entry) => entry.path)); + this.updatePromptsFromPaths(this.lastPromptPaths, this.resourceMetadataByPath); + } + if (themePaths.length > 0) { + this.lastThemePaths = this.mergePaths(this.lastThemePaths, themePaths.map((entry) => entry.path)); + this.updateThemesFromPaths(this.lastThemePaths, this.resourceMetadataByPath); + } + } + async loadProjectTrustExtensions() { + // Force untrusted project settings for the bootstrap pass. This keeps project-local + // extensions/packages out while still loading user/global and temporary CLI extensions. + this.settingsManager.setProjectTrusted(false); + await this.settingsManager.reload(); + return this.loadCurrentExtensionSet({ includeInlineFactories: true }); + } + async reload(options) { + resetTimings("extensions"); + if (this.loaded) { + clearExtensionCache(); + } + let preTrustExtensions; + if (options?.resolveProjectTrust) { + preTrustExtensions = await this.loadProjectTrustExtensions(); + const projectTrusted = await options.resolveProjectTrust({ extensionsResult: preTrustExtensions }); + this.settingsManager.setProjectTrusted(projectTrusted); + } + // reload() preserves SettingsManager.projectTrusted and reloads settings for that trust state. + await this.settingsManager.reload(); + const resolvedPaths = await this.packageManager.resolve(); + const cliExtensionPaths = await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths, { + temporary: true, + }); + // Kept on the instance so post-reload passes (extendResources) can still resolve package metadata. + this.resourceMetadataByPath = new Map(); + const metadataByPath = this.resourceMetadataByPath; + this.extensionSkillSourceInfos = new Map(); + this.extensionPromptSourceInfos = new Map(); + this.extensionThemeSourceInfos = new Map(); + // Helper to extract enabled paths and store metadata + const getEnabledResources = (resources) => { + for (const r of resources) { + if (!metadataByPath.has(r.path)) { + metadataByPath.set(r.path, r.metadata); + } + } + return resources.filter((r) => r.enabled); + }; + const getEnabledPaths = (resources) => getEnabledResources(resources).map((r) => r.path); + const enabledExtensions = getEnabledPaths(resolvedPaths.extensions); + const enabledSkillResources = getEnabledResources(resolvedPaths.skills); + const enabledPrompts = getEnabledPaths(resolvedPaths.prompts); + const enabledThemes = getEnabledPaths(resolvedPaths.themes); + const enabledSkills = enabledSkillResources.map((resource) => this.mapSkillPath(resource, metadataByPath)); + // Add CLI paths metadata + for (const r of cliExtensionPaths.extensions) { + if (!metadataByPath.has(r.path)) { + metadataByPath.set(r.path, { source: "cli", scope: "temporary", origin: "top-level" }); + } + } + for (const r of cliExtensionPaths.skills) { + if (!metadataByPath.has(r.path)) { + metadataByPath.set(r.path, { source: "cli", scope: "temporary", origin: "top-level" }); + } + } + const cliEnabledExtensions = getEnabledPaths(cliExtensionPaths.extensions); + const cliEnabledSkills = getEnabledPaths(cliExtensionPaths.skills); + const cliEnabledPrompts = getEnabledPaths(cliExtensionPaths.prompts); + const cliEnabledThemes = getEnabledPaths(cliExtensionPaths.themes); + const extensionPaths = this.noExtensions + ? cliEnabledExtensions + : this.mergePaths(cliEnabledExtensions, enabledExtensions); + const extensionsResult = await this.loadFinalExtensionSet(extensionPaths, preTrustExtensions); + for (const p of this.additionalExtensionPaths) { + if (isLocalPath(p)) { + const resolved = this.resolveResourcePath(p); + if (!existsSync(resolved)) { + extensionsResult.errors.push({ path: resolved, error: `Extension path does not exist: ${resolved}` }); + } + } + } + this.extensionsResult = this.extensionsOverride ? this.extensionsOverride(extensionsResult) : extensionsResult; + this.applyExtensionSourceInfo(this.extensionsResult.extensions, metadataByPath); + const skillPaths = this.noSkills + ? this.mergePaths(cliEnabledSkills, this.additionalSkillPaths) + : this.mergePaths([...cliEnabledSkills, ...enabledSkills], this.additionalSkillPaths); + this.lastSkillPaths = skillPaths; + this.updateSkillsFromPaths(skillPaths, metadataByPath); + for (const p of this.additionalSkillPaths) { + if (isLocalPath(p)) { + const resolved = this.resolveResourcePath(p); + if (!existsSync(resolved) && !this.skillDiagnostics.some((d) => d.path === resolved)) { + this.skillDiagnostics.push({ type: "error", message: "Skill path does not exist", path: resolved }); + } + } + } + const promptPaths = this.noPromptTemplates + ? this.mergePaths(cliEnabledPrompts, this.additionalPromptTemplatePaths) + : this.mergePaths([...cliEnabledPrompts, ...enabledPrompts], this.additionalPromptTemplatePaths); + this.lastPromptPaths = promptPaths; + this.updatePromptsFromPaths(promptPaths, metadataByPath); + for (const p of this.additionalPromptTemplatePaths) { + if (isLocalPath(p)) { + const resolved = this.resolveResourcePath(p); + if (!existsSync(resolved) && !this.promptDiagnostics.some((d) => d.path === resolved)) { + this.promptDiagnostics.push({ + type: "error", + message: "Prompt template path does not exist", + path: resolved, + }); + } + } + } + const themePaths = this.noThemes + ? this.mergePaths(cliEnabledThemes, this.additionalThemePaths) + : this.mergePaths([...cliEnabledThemes, ...enabledThemes], this.additionalThemePaths); + this.lastThemePaths = themePaths; + this.updateThemesFromPaths(themePaths, metadataByPath); + for (const p of this.additionalThemePaths) { + const resolved = this.resolveResourcePath(p); + if (!existsSync(resolved) && !this.themeDiagnostics.some((d) => d.path === resolved)) { + this.themeDiagnostics.push({ type: "error", message: "Theme path does not exist", path: resolved }); + } + } + const agentsFiles = { + agentsFiles: this.noContextFiles + ? [] + : loadProjectContextFiles({ + cwd: this.cwd, + agentDir: this.agentDir, + }), + }; + const resolvedAgentsFiles = this.agentsFilesOverride ? this.agentsFilesOverride(agentsFiles) : agentsFiles; + this.agentsFiles = resolvedAgentsFiles.agentsFiles; + const systemPromptSource = this.systemPromptSource ?? this.discoverSystemPromptFile(); + const baseSystemPrompt = resolvePromptInput(systemPromptSource, "system prompt"); + this.systemPrompt = this.systemPromptOverride ? this.systemPromptOverride(baseSystemPrompt) : baseSystemPrompt; + this.systemPromptSourcePath = + systemPromptSource && existsSync(systemPromptSource) ? resolvePath(systemPromptSource) : undefined; + let appendSources = this.appendSystemPromptSource; + if (!appendSources) { + const discoveredAppendSystemPromptFile = this.discoverAppendSystemPromptFile(); + appendSources = discoveredAppendSystemPromptFile ? [discoveredAppendSystemPromptFile] : []; + } + const baseAppend = appendSources + .map((s) => resolvePromptInput(s, "append system prompt")) + .filter((s) => s !== undefined); + this.appendSystemPrompt = this.appendSystemPromptOverride + ? this.appendSystemPromptOverride(baseAppend) + : baseAppend; + this.appendSystemPromptSourcePaths = appendSources + .filter((source) => existsSync(source)) + .map((source) => resolvePath(source)); + this.loaded = true; + } + async loadCurrentExtensionSet(options) { + const resolvedPaths = await this.packageManager.resolve(); + const cliExtensionPaths = await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths, { + temporary: true, + }); + const enabledExtensions = resolvedPaths.extensions.filter((r) => r.enabled).map((r) => r.path); + const cliEnabledExtensions = cliExtensionPaths.extensions.filter((r) => r.enabled).map((r) => r.path); + const extensionPaths = this.noExtensions + ? cliEnabledExtensions + : this.mergePaths(cliEnabledExtensions, enabledExtensions); + const extensionsResult = await loadExtensionsCached(extensionPaths, this.cwd, this.eventBus); + if (!options.includeInlineFactories) { + return extensionsResult; + } + const inlineExtensions = await this.loadExtensionFactories(extensionsResult.runtime); + extensionsResult.extensions.push(...inlineExtensions.extensions); + extensionsResult.errors.push(...inlineExtensions.errors); + return extensionsResult; + } + resolveExtensionLoadPath(path) { + return resolvePath(path, this.cwd, { normalizeUnicodeSpaces: true }); + } + async loadFinalExtensionSet(extensionPaths, preTrustExtensions) { + if (!preTrustExtensions) { + const extensionsResult = await loadExtensionsCached(extensionPaths, this.cwd, this.eventBus); + const inlineExtensions = await this.loadExtensionFactories(extensionsResult.runtime); + extensionsResult.extensions.push(...inlineExtensions.extensions); + extensionsResult.errors.push(...inlineExtensions.errors); + this.addExtensionConflictDiagnostics(extensionsResult); + return extensionsResult; + } + const preloadedByPath = new Map(preTrustExtensions.extensions + .filter((extension) => !extension.path.startsWith(" [extension.resolvedPath, extension])); + const failedPreloadPaths = new Set(preTrustExtensions.errors.map((error) => this.resolveExtensionLoadPath(error.path))); + const remainingPaths = extensionPaths.filter((path) => { + const resolvedPath = this.resolveExtensionLoadPath(path); + return !preloadedByPath.has(resolvedPath) && !failedPreloadPaths.has(resolvedPath); + }); + const remainingExtensions = await loadExtensionsCached(remainingPaths, this.cwd, this.eventBus, preTrustExtensions.runtime); + const loadedByPath = new Map(preloadedByPath); + for (const extension of remainingExtensions.extensions) { + loadedByPath.set(extension.resolvedPath, extension); + } + const inlineExtensions = preTrustExtensions.extensions.filter((extension) => extension.path.startsWith(" loadedByPath.get(this.resolveExtensionLoadPath(path))) + .filter((extension) => extension !== undefined); + orderedExtensions.push(...inlineExtensions); + const extensionsResult = { + extensions: orderedExtensions, + errors: [...preTrustExtensions.errors, ...remainingExtensions.errors], + runtime: preTrustExtensions.runtime, + }; + this.addExtensionConflictDiagnostics(extensionsResult); + return extensionsResult; + } + addExtensionConflictDiagnostics(extensionsResult) { + // Detect extension conflicts (tools, commands, flags with same names from different extensions) + // Keep all extensions loaded. Conflicts are reported as diagnostics, and precedence is handled by load order. + const conflicts = this.detectExtensionConflicts(extensionsResult.extensions); + for (const conflict of conflicts) { + extensionsResult.errors.push({ path: conflict.path, error: conflict.message }); + } + } + mapSkillPath(resource, metadataByPath) { + if (resource.metadata.source !== "auto" && resource.metadata.origin !== "package") { + return resource.path; + } + try { + const stats = statSync(resource.path); + if (!stats.isDirectory()) { + return resource.path; + } + } + catch { + return resource.path; + } + const skillFile = join(resource.path, "SKILL.md"); + if (existsSync(skillFile)) { + if (!metadataByPath.has(skillFile)) { + metadataByPath.set(skillFile, resource.metadata); + } + return skillFile; + } + return resource.path; + } + normalizeExtensionPaths(entries) { + return entries.map((entry) => { + const metadata = entry.metadata.baseDir + ? { ...entry.metadata, baseDir: this.resolveResourcePath(entry.metadata.baseDir) } + : entry.metadata; + return { + path: this.resolveResourcePath(entry.path), + metadata, + }; + }); + } + updateSkillsFromPaths(skillPaths, metadataByPath) { + let skillsResult; + if (this.noSkills && skillPaths.length === 0) { + skillsResult = { skills: [], diagnostics: [] }; + } + else { + skillsResult = loadSkills({ + cwd: this.cwd, + agentDir: this.agentDir, + skillPaths, + includeDefaults: false, + }); + } + const resolvedSkills = this.skillsOverride ? this.skillsOverride(skillsResult) : skillsResult; + this.skills = resolvedSkills.skills.map((skill) => ({ + ...skill, + sourceInfo: this.findSourceInfoForPath(skill.filePath, this.extensionSkillSourceInfos, metadataByPath) ?? + skill.sourceInfo ?? + this.getDefaultSourceInfoForPath(skill.filePath), + })); + this.skillDiagnostics = resolvedSkills.diagnostics; + } + updatePromptsFromPaths(promptPaths, metadataByPath) { + let promptsResult; + if (this.noPromptTemplates && promptPaths.length === 0) { + promptsResult = { prompts: [], diagnostics: [] }; + } + else { + const allPrompts = loadPromptTemplates({ + cwd: this.cwd, + agentDir: this.agentDir, + promptPaths, + includeDefaults: false, + }); + promptsResult = this.dedupePrompts(allPrompts); + } + const resolvedPrompts = this.promptsOverride ? this.promptsOverride(promptsResult) : promptsResult; + this.prompts = resolvedPrompts.prompts.map((prompt) => ({ + ...prompt, + sourceInfo: this.findSourceInfoForPath(prompt.filePath, this.extensionPromptSourceInfos, metadataByPath) ?? + prompt.sourceInfo ?? + this.getDefaultSourceInfoForPath(prompt.filePath), + })); + this.promptDiagnostics = resolvedPrompts.diagnostics; + } + updateThemesFromPaths(themePaths, metadataByPath) { + let themesResult; + if (this.noThemes && themePaths.length === 0) { + themesResult = { themes: [], diagnostics: [] }; + } + else { + const loaded = this.loadThemes(themePaths, false); + const deduped = this.dedupeThemes(loaded.themes); + themesResult = { themes: deduped.themes, diagnostics: [...loaded.diagnostics, ...deduped.diagnostics] }; + } + const resolvedThemes = this.themesOverride ? this.themesOverride(themesResult) : themesResult; + this.themes = resolvedThemes.themes.map((theme) => { + const sourcePath = theme.sourcePath; + theme.sourceInfo = sourcePath + ? (this.findSourceInfoForPath(sourcePath, this.extensionThemeSourceInfos, metadataByPath) ?? + theme.sourceInfo ?? + this.getDefaultSourceInfoForPath(sourcePath)) + : theme.sourceInfo; + return theme; + }); + this.themeDiagnostics = resolvedThemes.diagnostics; + } + applyExtensionSourceInfo(extensions, metadataByPath) { + for (const extension of extensions) { + extension.sourceInfo = + this.findSourceInfoForPath(extension.path, undefined, metadataByPath) ?? + this.getDefaultSourceInfoForPath(extension.path); + for (const command of extension.commands.values()) { + command.sourceInfo = extension.sourceInfo; + } + for (const tool of extension.tools.values()) { + tool.sourceInfo = extension.sourceInfo; + } + } + } + findSourceInfoForPath(resourcePath, extraSourceInfos, metadataByPath) { + if (!resourcePath) { + return undefined; + } + if (resourcePath.startsWith("<")) { + return this.getDefaultSourceInfoForPath(resourcePath); + } + const normalizedResourcePath = resolve(resourcePath); + if (extraSourceInfos) { + for (const [sourcePath, sourceInfo] of extraSourceInfos.entries()) { + const normalizedSourcePath = resolve(sourcePath); + if (normalizedResourcePath === normalizedSourcePath || + normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep}`)) { + return { ...sourceInfo, path: resourcePath }; + } + } + } + if (metadataByPath) { + const exact = metadataByPath.get(normalizedResourcePath) ?? metadataByPath.get(resourcePath); + if (exact) { + return createSourceInfo(resourcePath, exact); + } + for (const [sourcePath, metadata] of metadataByPath.entries()) { + const normalizedSourcePath = resolve(sourcePath); + if (normalizedResourcePath === normalizedSourcePath || + normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep}`)) { + return createSourceInfo(resourcePath, metadata); + } + } + } + return undefined; + } + getDefaultSourceInfoForPath(filePath) { + if (filePath.startsWith("<") && filePath.endsWith(">")) { + return { + path: filePath, + source: filePath.slice(1, -1).split(":")[0] || "temporary", + scope: "temporary", + origin: "top-level", + }; + } + const normalizedPath = resolve(filePath); + const agentRoots = [ + join(this.agentDir, "skills"), + join(this.agentDir, "prompts"), + join(this.agentDir, "themes"), + join(this.agentDir, "extensions"), + ]; + const projectRoots = [ + join(this.cwd, CONFIG_DIR_NAME, "skills"), + join(this.cwd, CONFIG_DIR_NAME, "prompts"), + join(this.cwd, CONFIG_DIR_NAME, "themes"), + join(this.cwd, CONFIG_DIR_NAME, "extensions"), + ]; + for (const root of agentRoots) { + if (this.isUnderPath(normalizedPath, root)) { + return { path: filePath, source: "local", scope: "user", origin: "top-level", baseDir: root }; + } + } + for (const root of projectRoots) { + if (this.isUnderPath(normalizedPath, root)) { + return { path: filePath, source: "local", scope: "project", origin: "top-level", baseDir: root }; + } + } + return { + path: filePath, + source: "local", + scope: "temporary", + origin: "top-level", + baseDir: statSync(normalizedPath).isDirectory() ? normalizedPath : resolve(normalizedPath, ".."), + }; + } + mergePaths(primary, additional) { + const merged = []; + const seen = new Set(); + for (const p of [...primary, ...additional]) { + const resolved = this.resolveResourcePath(p); + const canonicalPath = canonicalizePath(resolved); + if (seen.has(canonicalPath)) + continue; + seen.add(canonicalPath); + merged.push(resolved); + } + return merged; + } + resolveResourcePath(p) { + return resolvePath(p, this.cwd, { trim: true }); + } + loadThemes(paths, includeDefaults = true) { + const themes = []; + const diagnostics = []; + if (includeDefaults) { + const defaultDirs = [join(this.agentDir, "themes"), join(this.cwd, CONFIG_DIR_NAME, "themes")]; + for (const dir of defaultDirs) { + this.loadThemesFromDir(dir, themes, diagnostics); + } + } + for (const p of paths) { + const resolved = this.resolveResourcePath(p); + if (!existsSync(resolved)) { + diagnostics.push({ type: "warning", message: "theme path does not exist", path: resolved }); + continue; + } + try { + const stats = statSync(resolved); + if (stats.isDirectory()) { + this.loadThemesFromDir(resolved, themes, diagnostics); + } + else if (stats.isFile() && resolved.endsWith(".json")) { + this.loadThemeFromFile(resolved, themes, diagnostics); + } + else { + diagnostics.push({ type: "warning", message: "theme path is not a json file", path: resolved }); + } + } + catch (error) { + const message = error instanceof Error ? error.message : "failed to read theme path"; + diagnostics.push({ type: "warning", message, path: resolved }); + } + } + return { themes, diagnostics }; + } + loadThemesFromDir(dir, themes, diagnostics) { + if (!existsSync(dir)) { + return; + } + try { + const entries = readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + let isFile = entry.isFile(); + if (entry.isSymbolicLink()) { + try { + isFile = statSync(join(dir, entry.name)).isFile(); + } + catch { + continue; + } + } + if (!isFile) { + continue; + } + if (!entry.name.endsWith(".json")) { + continue; + } + this.loadThemeFromFile(join(dir, entry.name), themes, diagnostics); + } + } + catch (error) { + const message = error instanceof Error ? error.message : "failed to read theme directory"; + diagnostics.push({ type: "warning", message, path: dir }); + } + } + loadThemeFromFile(filePath, themes, diagnostics) { + try { + themes.push(loadThemeFromPath(filePath)); + } + catch (error) { + const message = error instanceof Error ? error.message : "failed to load theme"; + diagnostics.push({ type: "warning", message, path: filePath }); + } + } + async loadExtensionFactories(runtime) { + const extensions = []; + const errors = []; + for (const [index, input] of this.extensionFactories.entries()) { + const isNamed = typeof input !== "function"; + const factory = isNamed ? input.factory : input; + const extensionPath = ``; + try { + const extension = await loadExtensionFromFactory(factory, this.cwd, this.eventBus, runtime, extensionPath); + extension.hidden = isNamed && input.hidden; + extensions.push(extension); + } + catch (error) { + const message = error instanceof Error ? error.message : "failed to load extension"; + errors.push({ path: extensionPath, error: message }); + } + } + return { extensions, errors }; + } + dedupePrompts(prompts) { + const seen = new Map(); + const diagnostics = []; + for (const prompt of prompts) { + const existing = seen.get(prompt.name); + if (existing) { + diagnostics.push({ + type: "collision", + message: `name "/${prompt.name}" collision`, + path: prompt.filePath, + collision: { + resourceType: "prompt", + name: prompt.name, + winnerPath: existing.filePath, + loserPath: prompt.filePath, + }, + }); + } + else { + seen.set(prompt.name, prompt); + } + } + return { prompts: Array.from(seen.values()), diagnostics }; + } + dedupeThemes(themes) { + const seen = new Map(); + const diagnostics = []; + for (const t of themes) { + const name = t.name ?? "unnamed"; + const existing = seen.get(name); + if (existing) { + diagnostics.push({ + type: "collision", + message: `name "${name}" collision`, + path: t.sourcePath, + collision: { + resourceType: "theme", + name, + winnerPath: existing.sourcePath ?? "", + loserPath: t.sourcePath ?? "", + }, + }); + } + else { + seen.set(name, t); + } + } + return { themes: Array.from(seen.values()), diagnostics }; + } + discoverSystemPromptFile() { + const projectPath = join(this.cwd, CONFIG_DIR_NAME, "SYSTEM.md"); + if (this.settingsManager.isProjectTrusted() && existsSync(projectPath)) { + return projectPath; + } + const globalPath = join(this.agentDir, "SYSTEM.md"); + if (existsSync(globalPath)) { + return globalPath; + } + return undefined; + } + discoverAppendSystemPromptFile() { + const projectPath = join(this.cwd, CONFIG_DIR_NAME, "APPEND_SYSTEM.md"); + if (this.settingsManager.isProjectTrusted() && existsSync(projectPath)) { + return projectPath; + } + const globalPath = join(this.agentDir, "APPEND_SYSTEM.md"); + if (existsSync(globalPath)) { + return globalPath; + } + return undefined; + } + isUnderPath(target, root) { + const normalizedRoot = resolve(root); + if (target === normalizedRoot) { + return true; + } + const prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`; + return target.startsWith(prefix); + } + detectExtensionConflicts(extensions) { + const conflicts = []; + // Track which extension registered each tool and flag + const toolOwners = new Map(); + const flagOwners = new Map(); + for (const ext of extensions) { + // Check tools + for (const toolName of ext.tools.keys()) { + const existingOwner = toolOwners.get(toolName); + if (existingOwner && existingOwner !== ext.path) { + conflicts.push({ + path: ext.path, + message: `Tool "${toolName}" conflicts with ${existingOwner}`, + }); + } + else { + toolOwners.set(toolName, ext.path); + } + } + // Check flags + for (const flagName of ext.flags.keys()) { + const existingOwner = flagOwners.get(flagName); + if (existingOwner && existingOwner !== ext.path) { + conflicts.push({ + path: ext.path, + message: `Flag "--${flagName}" conflicts with ${existingOwner}`, + }); + } + else { + flagOwners.set(flagName, ext.path); + } + } + } + return conflicts; + } +} +//# sourceMappingURL=resource-loader.js.map \ No newline at end of file diff --git a/dist/core/resource-loader.js.map b/dist/core/resource-loader.js.map new file mode 100644 index 0000000..e42d7c1 --- /dev/null +++ b/dist/core/resource-loader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resource-loader.js","sourceRoot":"","sources":["../../src/core/resource-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAClE,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAc,MAAM,qCAAqC,CAAC;AAKpF,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAiB,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EACN,mBAAmB,EACnB,sBAAsB,EACtB,wBAAwB,EACxB,oBAAoB,GACpB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,qBAAqB,EAA4C,MAAM,sBAAsB,CAAC;AAEvG,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EAAE,UAAU,EAAE,MAAM,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;gBACzC,MAAM,aAAa,GAAG,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;gBAC/C,IAAI,aAAa,IAAI,aAAa,KAAK,GAAG,CAAC,IAAI,EAAE,CAAC;oBACjD,SAAS,CAAC,IAAI,CAAC;wBACd,IAAI,EAAE,GAAG,CAAC,IAAI;wBACd,OAAO,EAAE,SAAS,QAAQ,oBAAoB,aAAa,EAAE;qBAC7D,CAAC,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACP,UAAU,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;gBACpC,CAAC;YACF,CAAC;YAED,cAAc;YACd,KAAK,MAAM,QAAQ,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC;gBACzC,MAAM,aAAa,GAAG,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;gBAC/C,IAAI,aAAa,IAAI,aAAa,KAAK,GAAG,CAAC,IAAI,EAAE,CAAC;oBACjD,SAAS,CAAC,IAAI,CAAC;wBACd,IAAI,EAAE,GAAG,CAAC,IAAI;wBACd,OAAO,EAAE,WAAW,QAAQ,oBAAoB,aAAa,EAAE;qBAC/D,CAAC,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACP,UAAU,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;gBACpC,CAAC;YACF,CAAC;QACF,CAAC;QAED,OAAO,SAAS,CAAC;IAAA,CACjB;CACD","sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\nimport chalk from \"chalk\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { loadThemeFromPath, type Theme } from \"../modes/interactive/theme/theme.ts\";\nimport type { ResourceDiagnostic } from \"./diagnostics.ts\";\n\nexport type { ResourceCollision, ResourceDiagnostic } from \"./diagnostics.ts\";\n\nimport { canonicalizePath, isLocalPath, resolvePath } from \"../utils/paths.ts\";\nimport { createEventBus, type EventBus } from \"./event-bus.ts\";\nimport {\n\tclearExtensionCache,\n\tcreateExtensionRuntime,\n\tloadExtensionFromFactory,\n\tloadExtensionsCached,\n} from \"./extensions/loader.ts\";\nimport type { Extension, ExtensionRuntime, InlineExtension, LoadExtensionsResult } from \"./extensions/types.ts\";\nimport { findGitPaths } from \"./footer-data-provider.ts\";\nimport { DefaultPackageManager, type PathMetadata, type ResolvedResource } from \"./package-manager.ts\";\nimport type { PromptTemplate } from \"./prompt-templates.ts\";\nimport { loadPromptTemplates } from \"./prompt-templates.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport type { Skill } from \"./skills.ts\";\nimport { loadSkills } from \"./skills.ts\";\nimport { createSourceInfo, type SourceInfo } from \"./source-info.ts\";\nimport { resetTimings } from \"./timings.ts\";\n\nexport interface ResourceExtensionPaths {\n\tskillPaths?: Array<{ path: string; metadata: PathMetadata }>;\n\tpromptPaths?: Array<{ path: string; metadata: PathMetadata }>;\n\tthemePaths?: Array<{ path: string; metadata: PathMetadata }>;\n}\n\nexport interface ResourceLoaderReloadOptions {\n\tresolveProjectTrust?: (input: { extensionsResult: LoadExtensionsResult }) => Promise;\n}\n\nexport interface ResourceLoader {\n\tgetExtensions(): LoadExtensionsResult;\n\tgetSkills(): { skills: Skill[]; diagnostics: ResourceDiagnostic[] };\n\tgetPrompts(): { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] };\n\tgetThemes(): { themes: Theme[]; diagnostics: ResourceDiagnostic[] };\n\tgetAgentsFiles(): { agentsFiles: Array<{ path: string; content: string }> };\n\tgetSystemPrompt(): string | undefined;\n\tgetSystemPromptSource(): { path: string } | undefined;\n\tgetAppendSystemPrompt(): string[];\n\tgetAppendSystemPromptSources(): Array<{ path: string }>;\n\textendResources(paths: ResourceExtensionPaths): void;\n\treload(options?: ResourceLoaderReloadOptions): Promise;\n}\n\nfunction resolvePromptInput(input: string | undefined, description: string): string | undefined {\n\tif (!input) {\n\t\treturn undefined;\n\t}\n\n\tif (existsSync(input)) {\n\t\ttry {\n\t\t\treturn readFileSync(input, \"utf-8\");\n\t\t} catch (error) {\n\t\t\tconsole.error(chalk.yellow(`Warning: Could not read ${description} file ${input}: ${error}`));\n\t\t\treturn input;\n\t\t}\n\t}\n\n\treturn input;\n}\n\nfunction loadContextFileFromDir(dir: string): { path: string; content: string } | null {\n\tconst candidates = [\"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"];\n\tfor (const filename of candidates) {\n\t\tconst filePath = join(dir, filename);\n\t\tif (existsSync(filePath)) {\n\t\t\ttry {\n\t\t\t\tif (!statSync(filePath).isFile()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tpath: filePath,\n\t\t\t\t\tcontent: readFileSync(filePath, \"utf-8\"),\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(chalk.yellow(`Warning: Could not read ${filePath}: ${error}`));\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * The main repo's context file that a nested linked worktree's own copy shadows: both\n * are the same tracked AGENTS.md/CLAUDE.md, so loading both loads it twice. Returns\n * undefined when nothing is shadowed, leaving normal ancestor inheritance alone.\n *\n * Returned canonicalized (realpath), because `git worktree add` writes the `.git`\n * file's `gitdir:` target in realpath form while cwd may still be symlinked\n * (macOS `/tmp` -> `/private/tmp`).\n */\nfunction findShadowedContextFile(cwd: string): string | undefined {\n\tconst gitPaths = findGitPaths(cwd);\n\tif (!gitPaths) return undefined;\n\tconst commonGitDir = canonicalizePath(gitPaths.commonGitDir);\n\tconst worktreeRoot = canonicalizePath(gitPaths.repoDir);\n\tconst mainRepoRoot = dirname(commonGitDir);\n\t// False for an ordinary repo, where the two are the same dir, and for a sibling\n\t// worktree (`git worktree add ../feat`), whose main repo is not an ancestor.\n\tif (!worktreeRoot.startsWith(`${mainRepoRoot}${sep}`)) return undefined;\n\t// dirname of the common git dir is the main worktree root only when that dir is\n\t// itself checked out from the same repo. In a bare layout (`proj/.bare` +\n\t// `proj/main`) it is just the directory holding `.bare`, which tracks nothing; a\n\t// submodule's gitdir has no `commondir`, so it lands under `.git/modules`.\n\tif (canonicalizePath(join(mainRepoRoot, \".git\")) !== commonGitDir) return undefined;\n\tconst worktreeContextFile = loadContextFileFromDir(worktreeRoot);\n\treturn worktreeContextFile ? join(mainRepoRoot, basename(worktreeContextFile.path)) : undefined;\n}\n\nexport function loadProjectContextFiles(options: {\n\tcwd: string;\n\tagentDir: string;\n}): Array<{ path: string; content: string }> {\n\tconst resolvedCwd = resolvePath(options.cwd);\n\tconst resolvedAgentDir = resolvePath(options.agentDir);\n\n\tconst contextFiles: Array<{ path: string; content: string }> = [];\n\tconst seenPaths = new Set();\n\n\tconst globalContext = loadContextFileFromDir(resolvedAgentDir);\n\tif (globalContext) {\n\t\tcontextFiles.push(globalContext);\n\t\tseenPaths.add(globalContext.path);\n\t}\n\n\tconst ancestorContextFiles: Array<{ path: string; content: string }> = [];\n\n\tconst shadowedContextFile = findShadowedContextFile(resolvedCwd);\n\tlet currentDir = resolvedCwd;\n\n\twhile (true) {\n\t\tconst contextFile = loadContextFileFromDir(currentDir);\n\t\tconst isShadowed =\n\t\t\tshadowedContextFile !== undefined && canonicalizePath(contextFile?.path ?? \"\") === shadowedContextFile;\n\t\tif (contextFile && !isShadowed && !seenPaths.has(contextFile.path)) {\n\t\t\tancestorContextFiles.unshift(contextFile);\n\t\t\tseenPaths.add(contextFile.path);\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) break;\n\t\tcurrentDir = parentDir;\n\t}\n\n\tcontextFiles.push(...ancestorContextFiles);\n\n\treturn contextFiles;\n}\n\nexport interface DefaultResourceLoaderOptions {\n\tcwd: string;\n\tagentDir: string;\n\tsettingsManager?: SettingsManager;\n\teventBus?: EventBus;\n\tadditionalExtensionPaths?: string[];\n\tadditionalSkillPaths?: string[];\n\tadditionalPromptTemplatePaths?: string[];\n\tadditionalThemePaths?: string[];\n\textensionFactories?: InlineExtension[];\n\tnoExtensions?: boolean;\n\tnoSkills?: boolean;\n\tnoPromptTemplates?: boolean;\n\tnoThemes?: boolean;\n\tnoContextFiles?: boolean;\n\tsystemPrompt?: string;\n\tappendSystemPrompt?: string[];\n\textensionsOverride?: (base: LoadExtensionsResult) => LoadExtensionsResult;\n\tskillsOverride?: (base: { skills: Skill[]; diagnostics: ResourceDiagnostic[] }) => {\n\t\tskills: Skill[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t};\n\tpromptsOverride?: (base: { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] }) => {\n\t\tprompts: PromptTemplate[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t};\n\tthemesOverride?: (base: { themes: Theme[]; diagnostics: ResourceDiagnostic[] }) => {\n\t\tthemes: Theme[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t};\n\tagentsFilesOverride?: (base: { agentsFiles: Array<{ path: string; content: string }> }) => {\n\t\tagentsFiles: Array<{ path: string; content: string }>;\n\t};\n\tsystemPromptOverride?: (base: string | undefined) => string | undefined;\n\tappendSystemPromptOverride?: (base: string[]) => string[];\n}\n\nexport class DefaultResourceLoader implements ResourceLoader {\n\tprivate cwd: string;\n\tprivate agentDir: string;\n\tprivate settingsManager: SettingsManager;\n\tprivate eventBus: EventBus;\n\tprivate packageManager: DefaultPackageManager;\n\tprivate additionalExtensionPaths: string[];\n\tprivate additionalSkillPaths: string[];\n\tprivate additionalPromptTemplatePaths: string[];\n\tprivate additionalThemePaths: string[];\n\tprivate extensionFactories: InlineExtension[];\n\tprivate noExtensions: boolean;\n\tprivate noSkills: boolean;\n\tprivate noPromptTemplates: boolean;\n\tprivate noThemes: boolean;\n\tprivate noContextFiles: boolean;\n\tprivate systemPromptSource?: string;\n\tprivate appendSystemPromptSource?: string[];\n\tprivate extensionsOverride?: (base: LoadExtensionsResult) => LoadExtensionsResult;\n\tprivate skillsOverride?: (base: { skills: Skill[]; diagnostics: ResourceDiagnostic[] }) => {\n\t\tskills: Skill[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t};\n\tprivate promptsOverride?: (base: { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] }) => {\n\t\tprompts: PromptTemplate[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t};\n\tprivate themesOverride?: (base: { themes: Theme[]; diagnostics: ResourceDiagnostic[] }) => {\n\t\tthemes: Theme[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t};\n\tprivate agentsFilesOverride?: (base: { agentsFiles: Array<{ path: string; content: string }> }) => {\n\t\tagentsFiles: Array<{ path: string; content: string }>;\n\t};\n\tprivate systemPromptOverride?: (base: string | undefined) => string | undefined;\n\tprivate appendSystemPromptOverride?: (base: string[]) => string[];\n\n\tprivate extensionsResult: LoadExtensionsResult;\n\tprivate skills: Skill[];\n\tprivate skillDiagnostics: ResourceDiagnostic[];\n\tprivate prompts: PromptTemplate[];\n\tprivate promptDiagnostics: ResourceDiagnostic[];\n\tprivate themes: Theme[];\n\tprivate themeDiagnostics: ResourceDiagnostic[];\n\tprivate agentsFiles: Array<{ path: string; content: string }>;\n\tprivate systemPrompt?: string;\n\tprivate systemPromptSourcePath?: string;\n\tprivate appendSystemPrompt: string[];\n\tprivate appendSystemPromptSourcePaths: string[];\n\tprivate lastSkillPaths: string[];\n\tprivate extensionSkillSourceInfos: Map;\n\tprivate extensionPromptSourceInfos: Map;\n\tprivate extensionThemeSourceInfos: Map;\n\tprivate resourceMetadataByPath: Map;\n\tprivate lastPromptPaths: string[];\n\tprivate lastThemePaths: string[];\n\tprivate loaded: boolean;\n\n\tconstructor(options: DefaultResourceLoaderOptions) {\n\t\tthis.cwd = resolvePath(options.cwd);\n\t\tthis.agentDir = resolvePath(options.agentDir);\n\t\tthis.settingsManager = options.settingsManager ?? SettingsManager.create(this.cwd, this.agentDir);\n\t\tthis.eventBus = options.eventBus ?? createEventBus();\n\t\tthis.packageManager = new DefaultPackageManager({\n\t\t\tcwd: this.cwd,\n\t\t\tagentDir: this.agentDir,\n\t\t\tsettingsManager: this.settingsManager,\n\t\t});\n\t\tthis.additionalExtensionPaths = options.additionalExtensionPaths ?? [];\n\t\tthis.additionalSkillPaths = options.additionalSkillPaths ?? [];\n\t\tthis.additionalPromptTemplatePaths = options.additionalPromptTemplatePaths ?? [];\n\t\tthis.additionalThemePaths = options.additionalThemePaths ?? [];\n\t\tthis.extensionFactories = options.extensionFactories ?? [];\n\t\tthis.noExtensions = options.noExtensions ?? false;\n\t\tthis.noSkills = options.noSkills ?? false;\n\t\tthis.noPromptTemplates = options.noPromptTemplates ?? false;\n\t\tthis.noThemes = options.noThemes ?? false;\n\t\tthis.noContextFiles = options.noContextFiles ?? false;\n\t\tthis.systemPromptSource = options.systemPrompt;\n\t\tthis.appendSystemPromptSource = options.appendSystemPrompt;\n\t\tthis.extensionsOverride = options.extensionsOverride;\n\t\tthis.skillsOverride = options.skillsOverride;\n\t\tthis.promptsOverride = options.promptsOverride;\n\t\tthis.themesOverride = options.themesOverride;\n\t\tthis.agentsFilesOverride = options.agentsFilesOverride;\n\t\tthis.systemPromptOverride = options.systemPromptOverride;\n\t\tthis.appendSystemPromptOverride = options.appendSystemPromptOverride;\n\n\t\tthis.extensionsResult = { extensions: [], errors: [], runtime: createExtensionRuntime() };\n\t\tthis.skills = [];\n\t\tthis.skillDiagnostics = [];\n\t\tthis.prompts = [];\n\t\tthis.promptDiagnostics = [];\n\t\tthis.themes = [];\n\t\tthis.themeDiagnostics = [];\n\t\tthis.agentsFiles = [];\n\t\tthis.appendSystemPrompt = [];\n\t\tthis.appendSystemPromptSourcePaths = [];\n\t\tthis.lastSkillPaths = [];\n\t\tthis.extensionSkillSourceInfos = new Map();\n\t\tthis.extensionPromptSourceInfos = new Map();\n\t\tthis.extensionThemeSourceInfos = new Map();\n\t\tthis.resourceMetadataByPath = new Map();\n\t\tthis.lastPromptPaths = [];\n\t\tthis.lastThemePaths = [];\n\t\tthis.loaded = false;\n\t}\n\n\tgetExtensions(): LoadExtensionsResult {\n\t\treturn this.extensionsResult;\n\t}\n\n\tgetSkills(): { skills: Skill[]; diagnostics: ResourceDiagnostic[] } {\n\t\treturn { skills: this.skills, diagnostics: this.skillDiagnostics };\n\t}\n\n\tgetPrompts(): { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] } {\n\t\treturn { prompts: this.prompts, diagnostics: this.promptDiagnostics };\n\t}\n\n\tgetThemes(): { themes: Theme[]; diagnostics: ResourceDiagnostic[] } {\n\t\treturn { themes: this.themes, diagnostics: this.themeDiagnostics };\n\t}\n\n\tgetAgentsFiles(): { agentsFiles: Array<{ path: string; content: string }> } {\n\t\treturn { agentsFiles: this.agentsFiles };\n\t}\n\n\tgetSystemPrompt(): string | undefined {\n\t\treturn this.systemPrompt;\n\t}\n\n\tgetSystemPromptSource(): { path: string } | undefined {\n\t\treturn this.systemPromptSourcePath ? { path: this.systemPromptSourcePath } : undefined;\n\t}\n\n\tgetAppendSystemPrompt(): string[] {\n\t\treturn this.appendSystemPrompt;\n\t}\n\n\tgetAppendSystemPromptSources(): Array<{ path: string }> {\n\t\treturn this.appendSystemPromptSourcePaths.map((path) => ({ path }));\n\t}\n\n\textendResources(paths: ResourceExtensionPaths): void {\n\t\tconst skillPaths = this.normalizeExtensionPaths(paths.skillPaths ?? []);\n\t\tconst promptPaths = this.normalizeExtensionPaths(paths.promptPaths ?? []);\n\t\tconst themePaths = this.normalizeExtensionPaths(paths.themePaths ?? []);\n\n\t\tfor (const entry of skillPaths) {\n\t\t\tthis.extensionSkillSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata));\n\t\t}\n\t\tfor (const entry of promptPaths) {\n\t\t\tthis.extensionPromptSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata));\n\t\t}\n\t\tfor (const entry of themePaths) {\n\t\t\tthis.extensionThemeSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata));\n\t\t}\n\n\t\tif (skillPaths.length > 0) {\n\t\t\tthis.lastSkillPaths = this.mergePaths(\n\t\t\t\tthis.lastSkillPaths,\n\t\t\t\tskillPaths.map((entry) => entry.path),\n\t\t\t);\n\t\t\tthis.updateSkillsFromPaths(this.lastSkillPaths, this.resourceMetadataByPath);\n\t\t}\n\n\t\tif (promptPaths.length > 0) {\n\t\t\tthis.lastPromptPaths = this.mergePaths(\n\t\t\t\tthis.lastPromptPaths,\n\t\t\t\tpromptPaths.map((entry) => entry.path),\n\t\t\t);\n\t\t\tthis.updatePromptsFromPaths(this.lastPromptPaths, this.resourceMetadataByPath);\n\t\t}\n\n\t\tif (themePaths.length > 0) {\n\t\t\tthis.lastThemePaths = this.mergePaths(\n\t\t\t\tthis.lastThemePaths,\n\t\t\t\tthemePaths.map((entry) => entry.path),\n\t\t\t);\n\t\t\tthis.updateThemesFromPaths(this.lastThemePaths, this.resourceMetadataByPath);\n\t\t}\n\t}\n\n\tasync loadProjectTrustExtensions(): Promise {\n\t\t// Force untrusted project settings for the bootstrap pass. This keeps project-local\n\t\t// extensions/packages out while still loading user/global and temporary CLI extensions.\n\t\tthis.settingsManager.setProjectTrusted(false);\n\t\tawait this.settingsManager.reload();\n\t\treturn this.loadCurrentExtensionSet({ includeInlineFactories: true });\n\t}\n\n\tasync reload(options?: ResourceLoaderReloadOptions): Promise {\n\t\tresetTimings(\"extensions\");\n\n\t\tif (this.loaded) {\n\t\t\tclearExtensionCache();\n\t\t}\n\n\t\tlet preTrustExtensions: LoadExtensionsResult | undefined;\n\t\tif (options?.resolveProjectTrust) {\n\t\t\tpreTrustExtensions = await this.loadProjectTrustExtensions();\n\t\t\tconst projectTrusted = await options.resolveProjectTrust({ extensionsResult: preTrustExtensions });\n\t\t\tthis.settingsManager.setProjectTrusted(projectTrusted);\n\t\t}\n\n\t\t// reload() preserves SettingsManager.projectTrusted and reloads settings for that trust state.\n\t\tawait this.settingsManager.reload();\n\t\tconst resolvedPaths = await this.packageManager.resolve();\n\t\tconst cliExtensionPaths = await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths, {\n\t\t\ttemporary: true,\n\t\t});\n\t\t// Kept on the instance so post-reload passes (extendResources) can still resolve package metadata.\n\t\tthis.resourceMetadataByPath = new Map();\n\t\tconst metadataByPath = this.resourceMetadataByPath;\n\n\t\tthis.extensionSkillSourceInfos = new Map();\n\t\tthis.extensionPromptSourceInfos = new Map();\n\t\tthis.extensionThemeSourceInfos = new Map();\n\n\t\t// Helper to extract enabled paths and store metadata\n\t\tconst getEnabledResources = (resources: ResolvedResource[]): ResolvedResource[] => {\n\t\t\tfor (const r of resources) {\n\t\t\t\tif (!metadataByPath.has(r.path)) {\n\t\t\t\t\tmetadataByPath.set(r.path, r.metadata);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn resources.filter((r) => r.enabled);\n\t\t};\n\n\t\tconst getEnabledPaths = (resources: ResolvedResource[]): string[] =>\n\t\t\tgetEnabledResources(resources).map((r) => r.path);\n\t\tconst enabledExtensions = getEnabledPaths(resolvedPaths.extensions);\n\t\tconst enabledSkillResources = getEnabledResources(resolvedPaths.skills);\n\t\tconst enabledPrompts = getEnabledPaths(resolvedPaths.prompts);\n\t\tconst enabledThemes = getEnabledPaths(resolvedPaths.themes);\n\n\t\tconst enabledSkills = enabledSkillResources.map((resource) => this.mapSkillPath(resource, metadataByPath));\n\n\t\t// Add CLI paths metadata\n\t\tfor (const r of cliExtensionPaths.extensions) {\n\t\t\tif (!metadataByPath.has(r.path)) {\n\t\t\t\tmetadataByPath.set(r.path, { source: \"cli\", scope: \"temporary\", origin: \"top-level\" });\n\t\t\t}\n\t\t}\n\t\tfor (const r of cliExtensionPaths.skills) {\n\t\t\tif (!metadataByPath.has(r.path)) {\n\t\t\t\tmetadataByPath.set(r.path, { source: \"cli\", scope: \"temporary\", origin: \"top-level\" });\n\t\t\t}\n\t\t}\n\n\t\tconst cliEnabledExtensions = getEnabledPaths(cliExtensionPaths.extensions);\n\t\tconst cliEnabledSkills = getEnabledPaths(cliExtensionPaths.skills);\n\t\tconst cliEnabledPrompts = getEnabledPaths(cliExtensionPaths.prompts);\n\t\tconst cliEnabledThemes = getEnabledPaths(cliExtensionPaths.themes);\n\n\t\tconst extensionPaths = this.noExtensions\n\t\t\t? cliEnabledExtensions\n\t\t\t: this.mergePaths(cliEnabledExtensions, enabledExtensions);\n\n\t\tconst extensionsResult = await this.loadFinalExtensionSet(extensionPaths, preTrustExtensions);\n\t\tfor (const p of this.additionalExtensionPaths) {\n\t\t\tif (isLocalPath(p)) {\n\t\t\t\tconst resolved = this.resolveResourcePath(p);\n\t\t\t\tif (!existsSync(resolved)) {\n\t\t\t\t\textensionsResult.errors.push({ path: resolved, error: `Extension path does not exist: ${resolved}` });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.extensionsResult = this.extensionsOverride ? this.extensionsOverride(extensionsResult) : extensionsResult;\n\t\tthis.applyExtensionSourceInfo(this.extensionsResult.extensions, metadataByPath);\n\n\t\tconst skillPaths = this.noSkills\n\t\t\t? this.mergePaths(cliEnabledSkills, this.additionalSkillPaths)\n\t\t\t: this.mergePaths([...cliEnabledSkills, ...enabledSkills], this.additionalSkillPaths);\n\n\t\tthis.lastSkillPaths = skillPaths;\n\t\tthis.updateSkillsFromPaths(skillPaths, metadataByPath);\n\t\tfor (const p of this.additionalSkillPaths) {\n\t\t\tif (isLocalPath(p)) {\n\t\t\t\tconst resolved = this.resolveResourcePath(p);\n\t\t\t\tif (!existsSync(resolved) && !this.skillDiagnostics.some((d) => d.path === resolved)) {\n\t\t\t\t\tthis.skillDiagnostics.push({ type: \"error\", message: \"Skill path does not exist\", path: resolved });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst promptPaths = this.noPromptTemplates\n\t\t\t? this.mergePaths(cliEnabledPrompts, this.additionalPromptTemplatePaths)\n\t\t\t: this.mergePaths([...cliEnabledPrompts, ...enabledPrompts], this.additionalPromptTemplatePaths);\n\n\t\tthis.lastPromptPaths = promptPaths;\n\t\tthis.updatePromptsFromPaths(promptPaths, metadataByPath);\n\t\tfor (const p of this.additionalPromptTemplatePaths) {\n\t\t\tif (isLocalPath(p)) {\n\t\t\t\tconst resolved = this.resolveResourcePath(p);\n\t\t\t\tif (!existsSync(resolved) && !this.promptDiagnostics.some((d) => d.path === resolved)) {\n\t\t\t\t\tthis.promptDiagnostics.push({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\tmessage: \"Prompt template path does not exist\",\n\t\t\t\t\t\tpath: resolved,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst themePaths = this.noThemes\n\t\t\t? this.mergePaths(cliEnabledThemes, this.additionalThemePaths)\n\t\t\t: this.mergePaths([...cliEnabledThemes, ...enabledThemes], this.additionalThemePaths);\n\n\t\tthis.lastThemePaths = themePaths;\n\t\tthis.updateThemesFromPaths(themePaths, metadataByPath);\n\t\tfor (const p of this.additionalThemePaths) {\n\t\t\tconst resolved = this.resolveResourcePath(p);\n\t\t\tif (!existsSync(resolved) && !this.themeDiagnostics.some((d) => d.path === resolved)) {\n\t\t\t\tthis.themeDiagnostics.push({ type: \"error\", message: \"Theme path does not exist\", path: resolved });\n\t\t\t}\n\t\t}\n\n\t\tconst agentsFiles = {\n\t\t\tagentsFiles: this.noContextFiles\n\t\t\t\t? []\n\t\t\t\t: loadProjectContextFiles({\n\t\t\t\t\t\tcwd: this.cwd,\n\t\t\t\t\t\tagentDir: this.agentDir,\n\t\t\t\t\t}),\n\t\t};\n\t\tconst resolvedAgentsFiles = this.agentsFilesOverride ? this.agentsFilesOverride(agentsFiles) : agentsFiles;\n\t\tthis.agentsFiles = resolvedAgentsFiles.agentsFiles;\n\n\t\tconst systemPromptSource = this.systemPromptSource ?? this.discoverSystemPromptFile();\n\t\tconst baseSystemPrompt = resolvePromptInput(systemPromptSource, \"system prompt\");\n\t\tthis.systemPrompt = this.systemPromptOverride ? this.systemPromptOverride(baseSystemPrompt) : baseSystemPrompt;\n\t\tthis.systemPromptSourcePath =\n\t\t\tsystemPromptSource && existsSync(systemPromptSource) ? resolvePath(systemPromptSource) : undefined;\n\n\t\tlet appendSources = this.appendSystemPromptSource;\n\t\tif (!appendSources) {\n\t\t\tconst discoveredAppendSystemPromptFile = this.discoverAppendSystemPromptFile();\n\t\t\tappendSources = discoveredAppendSystemPromptFile ? [discoveredAppendSystemPromptFile] : [];\n\t\t}\n\t\tconst baseAppend = appendSources\n\t\t\t.map((s) => resolvePromptInput(s, \"append system prompt\"))\n\t\t\t.filter((s): s is string => s !== undefined);\n\t\tthis.appendSystemPrompt = this.appendSystemPromptOverride\n\t\t\t? this.appendSystemPromptOverride(baseAppend)\n\t\t\t: baseAppend;\n\t\tthis.appendSystemPromptSourcePaths = appendSources\n\t\t\t.filter((source) => existsSync(source))\n\t\t\t.map((source) => resolvePath(source));\n\t\tthis.loaded = true;\n\t}\n\n\tprivate async loadCurrentExtensionSet(options: { includeInlineFactories: boolean }): Promise {\n\t\tconst resolvedPaths = await this.packageManager.resolve();\n\t\tconst cliExtensionPaths = await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths, {\n\t\t\ttemporary: true,\n\t\t});\n\t\tconst enabledExtensions = resolvedPaths.extensions.filter((r) => r.enabled).map((r) => r.path);\n\t\tconst cliEnabledExtensions = cliExtensionPaths.extensions.filter((r) => r.enabled).map((r) => r.path);\n\t\tconst extensionPaths = this.noExtensions\n\t\t\t? cliEnabledExtensions\n\t\t\t: this.mergePaths(cliEnabledExtensions, enabledExtensions);\n\t\tconst extensionsResult = await loadExtensionsCached(extensionPaths, this.cwd, this.eventBus);\n\t\tif (!options.includeInlineFactories) {\n\t\t\treturn extensionsResult;\n\t\t}\n\n\t\tconst inlineExtensions = await this.loadExtensionFactories(extensionsResult.runtime);\n\t\textensionsResult.extensions.push(...inlineExtensions.extensions);\n\t\textensionsResult.errors.push(...inlineExtensions.errors);\n\t\treturn extensionsResult;\n\t}\n\n\tprivate resolveExtensionLoadPath(path: string): string {\n\t\treturn resolvePath(path, this.cwd, { normalizeUnicodeSpaces: true });\n\t}\n\n\tprivate async loadFinalExtensionSet(\n\t\textensionPaths: string[],\n\t\tpreTrustExtensions: LoadExtensionsResult | undefined,\n\t): Promise {\n\t\tif (!preTrustExtensions) {\n\t\t\tconst extensionsResult = await loadExtensionsCached(extensionPaths, this.cwd, this.eventBus);\n\t\t\tconst inlineExtensions = await this.loadExtensionFactories(extensionsResult.runtime);\n\t\t\textensionsResult.extensions.push(...inlineExtensions.extensions);\n\t\t\textensionsResult.errors.push(...inlineExtensions.errors);\n\t\t\tthis.addExtensionConflictDiagnostics(extensionsResult);\n\t\t\treturn extensionsResult;\n\t\t}\n\n\t\tconst preloadedByPath = new Map(\n\t\t\tpreTrustExtensions.extensions\n\t\t\t\t.filter((extension) => !extension.path.startsWith(\" [extension.resolvedPath, extension]),\n\t\t);\n\t\tconst failedPreloadPaths = new Set(\n\t\t\tpreTrustExtensions.errors.map((error) => this.resolveExtensionLoadPath(error.path)),\n\t\t);\n\t\tconst remainingPaths = extensionPaths.filter((path) => {\n\t\t\tconst resolvedPath = this.resolveExtensionLoadPath(path);\n\t\t\treturn !preloadedByPath.has(resolvedPath) && !failedPreloadPaths.has(resolvedPath);\n\t\t});\n\t\tconst remainingExtensions = await loadExtensionsCached(\n\t\t\tremainingPaths,\n\t\t\tthis.cwd,\n\t\t\tthis.eventBus,\n\t\t\tpreTrustExtensions.runtime,\n\t\t);\n\t\tconst loadedByPath = new Map(preloadedByPath);\n\t\tfor (const extension of remainingExtensions.extensions) {\n\t\t\tloadedByPath.set(extension.resolvedPath, extension);\n\t\t}\n\n\t\tconst inlineExtensions = preTrustExtensions.extensions.filter((extension) =>\n\t\t\textension.path.startsWith(\" loadedByPath.get(this.resolveExtensionLoadPath(path)))\n\t\t\t.filter((extension): extension is Extension => extension !== undefined);\n\t\torderedExtensions.push(...inlineExtensions);\n\n\t\tconst extensionsResult: LoadExtensionsResult = {\n\t\t\textensions: orderedExtensions,\n\t\t\terrors: [...preTrustExtensions.errors, ...remainingExtensions.errors],\n\t\t\truntime: preTrustExtensions.runtime,\n\t\t};\n\t\tthis.addExtensionConflictDiagnostics(extensionsResult);\n\t\treturn extensionsResult;\n\t}\n\n\tprivate addExtensionConflictDiagnostics(extensionsResult: LoadExtensionsResult): void {\n\t\t// Detect extension conflicts (tools, commands, flags with same names from different extensions)\n\t\t// Keep all extensions loaded. Conflicts are reported as diagnostics, and precedence is handled by load order.\n\t\tconst conflicts = this.detectExtensionConflicts(extensionsResult.extensions);\n\t\tfor (const conflict of conflicts) {\n\t\t\textensionsResult.errors.push({ path: conflict.path, error: conflict.message });\n\t\t}\n\t}\n\n\tprivate mapSkillPath(resource: ResolvedResource, metadataByPath: Map): string {\n\t\tif (resource.metadata.source !== \"auto\" && resource.metadata.origin !== \"package\") {\n\t\t\treturn resource.path;\n\t\t}\n\t\ttry {\n\t\t\tconst stats = statSync(resource.path);\n\t\t\tif (!stats.isDirectory()) {\n\t\t\t\treturn resource.path;\n\t\t\t}\n\t\t} catch {\n\t\t\treturn resource.path;\n\t\t}\n\t\tconst skillFile = join(resource.path, \"SKILL.md\");\n\t\tif (existsSync(skillFile)) {\n\t\t\tif (!metadataByPath.has(skillFile)) {\n\t\t\t\tmetadataByPath.set(skillFile, resource.metadata);\n\t\t\t}\n\t\t\treturn skillFile;\n\t\t}\n\t\treturn resource.path;\n\t}\n\n\tprivate normalizeExtensionPaths(\n\t\tentries: Array<{ path: string; metadata: PathMetadata }>,\n\t): Array<{ path: string; metadata: PathMetadata }> {\n\t\treturn entries.map((entry) => {\n\t\t\tconst metadata = entry.metadata.baseDir\n\t\t\t\t? { ...entry.metadata, baseDir: this.resolveResourcePath(entry.metadata.baseDir) }\n\t\t\t\t: entry.metadata;\n\t\t\treturn {\n\t\t\t\tpath: this.resolveResourcePath(entry.path),\n\t\t\t\tmetadata,\n\t\t\t};\n\t\t});\n\t}\n\n\tprivate updateSkillsFromPaths(skillPaths: string[], metadataByPath?: Map): void {\n\t\tlet skillsResult: { skills: Skill[]; diagnostics: ResourceDiagnostic[] };\n\t\tif (this.noSkills && skillPaths.length === 0) {\n\t\t\tskillsResult = { skills: [], diagnostics: [] };\n\t\t} else {\n\t\t\tskillsResult = loadSkills({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.agentDir,\n\t\t\t\tskillPaths,\n\t\t\t\tincludeDefaults: false,\n\t\t\t});\n\t\t}\n\t\tconst resolvedSkills = this.skillsOverride ? this.skillsOverride(skillsResult) : skillsResult;\n\t\tthis.skills = resolvedSkills.skills.map((skill) => ({\n\t\t\t...skill,\n\t\t\tsourceInfo:\n\t\t\t\tthis.findSourceInfoForPath(skill.filePath, this.extensionSkillSourceInfos, metadataByPath) ??\n\t\t\t\tskill.sourceInfo ??\n\t\t\t\tthis.getDefaultSourceInfoForPath(skill.filePath),\n\t\t}));\n\t\tthis.skillDiagnostics = resolvedSkills.diagnostics;\n\t}\n\n\tprivate updatePromptsFromPaths(promptPaths: string[], metadataByPath?: Map): void {\n\t\tlet promptsResult: { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] };\n\t\tif (this.noPromptTemplates && promptPaths.length === 0) {\n\t\t\tpromptsResult = { prompts: [], diagnostics: [] };\n\t\t} else {\n\t\t\tconst allPrompts = loadPromptTemplates({\n\t\t\t\tcwd: this.cwd,\n\t\t\t\tagentDir: this.agentDir,\n\t\t\t\tpromptPaths,\n\t\t\t\tincludeDefaults: false,\n\t\t\t});\n\t\t\tpromptsResult = this.dedupePrompts(allPrompts);\n\t\t}\n\t\tconst resolvedPrompts = this.promptsOverride ? this.promptsOverride(promptsResult) : promptsResult;\n\t\tthis.prompts = resolvedPrompts.prompts.map((prompt) => ({\n\t\t\t...prompt,\n\t\t\tsourceInfo:\n\t\t\t\tthis.findSourceInfoForPath(prompt.filePath, this.extensionPromptSourceInfos, metadataByPath) ??\n\t\t\t\tprompt.sourceInfo ??\n\t\t\t\tthis.getDefaultSourceInfoForPath(prompt.filePath),\n\t\t}));\n\t\tthis.promptDiagnostics = resolvedPrompts.diagnostics;\n\t}\n\n\tprivate updateThemesFromPaths(themePaths: string[], metadataByPath?: Map): void {\n\t\tlet themesResult: { themes: Theme[]; diagnostics: ResourceDiagnostic[] };\n\t\tif (this.noThemes && themePaths.length === 0) {\n\t\t\tthemesResult = { themes: [], diagnostics: [] };\n\t\t} else {\n\t\t\tconst loaded = this.loadThemes(themePaths, false);\n\t\t\tconst deduped = this.dedupeThemes(loaded.themes);\n\t\t\tthemesResult = { themes: deduped.themes, diagnostics: [...loaded.diagnostics, ...deduped.diagnostics] };\n\t\t}\n\t\tconst resolvedThemes = this.themesOverride ? this.themesOverride(themesResult) : themesResult;\n\t\tthis.themes = resolvedThemes.themes.map((theme) => {\n\t\t\tconst sourcePath = theme.sourcePath;\n\t\t\ttheme.sourceInfo = sourcePath\n\t\t\t\t? (this.findSourceInfoForPath(sourcePath, this.extensionThemeSourceInfos, metadataByPath) ??\n\t\t\t\t\ttheme.sourceInfo ??\n\t\t\t\t\tthis.getDefaultSourceInfoForPath(sourcePath))\n\t\t\t\t: theme.sourceInfo;\n\t\t\treturn theme;\n\t\t});\n\t\tthis.themeDiagnostics = resolvedThemes.diagnostics;\n\t}\n\n\tprivate applyExtensionSourceInfo(extensions: Extension[], metadataByPath: Map): void {\n\t\tfor (const extension of extensions) {\n\t\t\textension.sourceInfo =\n\t\t\t\tthis.findSourceInfoForPath(extension.path, undefined, metadataByPath) ??\n\t\t\t\tthis.getDefaultSourceInfoForPath(extension.path);\n\t\t\tfor (const command of extension.commands.values()) {\n\t\t\t\tcommand.sourceInfo = extension.sourceInfo;\n\t\t\t}\n\t\t\tfor (const tool of extension.tools.values()) {\n\t\t\t\ttool.sourceInfo = extension.sourceInfo;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate findSourceInfoForPath(\n\t\tresourcePath: string,\n\t\textraSourceInfos?: Map,\n\t\tmetadataByPath?: Map,\n\t): SourceInfo | undefined {\n\t\tif (!resourcePath) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (resourcePath.startsWith(\"<\")) {\n\t\t\treturn this.getDefaultSourceInfoForPath(resourcePath);\n\t\t}\n\n\t\tconst normalizedResourcePath = resolve(resourcePath);\n\t\tif (extraSourceInfos) {\n\t\t\tfor (const [sourcePath, sourceInfo] of extraSourceInfos.entries()) {\n\t\t\t\tconst normalizedSourcePath = resolve(sourcePath);\n\t\t\t\tif (\n\t\t\t\t\tnormalizedResourcePath === normalizedSourcePath ||\n\t\t\t\t\tnormalizedResourcePath.startsWith(`${normalizedSourcePath}${sep}`)\n\t\t\t\t) {\n\t\t\t\t\treturn { ...sourceInfo, path: resourcePath };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (metadataByPath) {\n\t\t\tconst exact = metadataByPath.get(normalizedResourcePath) ?? metadataByPath.get(resourcePath);\n\t\t\tif (exact) {\n\t\t\t\treturn createSourceInfo(resourcePath, exact);\n\t\t\t}\n\n\t\t\tfor (const [sourcePath, metadata] of metadataByPath.entries()) {\n\t\t\t\tconst normalizedSourcePath = resolve(sourcePath);\n\t\t\t\tif (\n\t\t\t\t\tnormalizedResourcePath === normalizedSourcePath ||\n\t\t\t\t\tnormalizedResourcePath.startsWith(`${normalizedSourcePath}${sep}`)\n\t\t\t\t) {\n\t\t\t\t\treturn createSourceInfo(resourcePath, metadata);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate getDefaultSourceInfoForPath(filePath: string): SourceInfo {\n\t\tif (filePath.startsWith(\"<\") && filePath.endsWith(\">\")) {\n\t\t\treturn {\n\t\t\t\tpath: filePath,\n\t\t\t\tsource: filePath.slice(1, -1).split(\":\")[0] || \"temporary\",\n\t\t\t\tscope: \"temporary\",\n\t\t\t\torigin: \"top-level\",\n\t\t\t};\n\t\t}\n\n\t\tconst normalizedPath = resolve(filePath);\n\t\tconst agentRoots = [\n\t\t\tjoin(this.agentDir, \"skills\"),\n\t\t\tjoin(this.agentDir, \"prompts\"),\n\t\t\tjoin(this.agentDir, \"themes\"),\n\t\t\tjoin(this.agentDir, \"extensions\"),\n\t\t];\n\t\tconst projectRoots = [\n\t\t\tjoin(this.cwd, CONFIG_DIR_NAME, \"skills\"),\n\t\t\tjoin(this.cwd, CONFIG_DIR_NAME, \"prompts\"),\n\t\t\tjoin(this.cwd, CONFIG_DIR_NAME, \"themes\"),\n\t\t\tjoin(this.cwd, CONFIG_DIR_NAME, \"extensions\"),\n\t\t];\n\n\t\tfor (const root of agentRoots) {\n\t\t\tif (this.isUnderPath(normalizedPath, root)) {\n\t\t\t\treturn { path: filePath, source: \"local\", scope: \"user\", origin: \"top-level\", baseDir: root };\n\t\t\t}\n\t\t}\n\n\t\tfor (const root of projectRoots) {\n\t\t\tif (this.isUnderPath(normalizedPath, root)) {\n\t\t\t\treturn { path: filePath, source: \"local\", scope: \"project\", origin: \"top-level\", baseDir: root };\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tpath: filePath,\n\t\t\tsource: \"local\",\n\t\t\tscope: \"temporary\",\n\t\t\torigin: \"top-level\",\n\t\t\tbaseDir: statSync(normalizedPath).isDirectory() ? normalizedPath : resolve(normalizedPath, \"..\"),\n\t\t};\n\t}\n\n\tprivate mergePaths(primary: string[], additional: string[]): string[] {\n\t\tconst merged: string[] = [];\n\t\tconst seen = new Set();\n\n\t\tfor (const p of [...primary, ...additional]) {\n\t\t\tconst resolved = this.resolveResourcePath(p);\n\t\t\tconst canonicalPath = canonicalizePath(resolved);\n\t\t\tif (seen.has(canonicalPath)) continue;\n\t\t\tseen.add(canonicalPath);\n\t\t\tmerged.push(resolved);\n\t\t}\n\n\t\treturn merged;\n\t}\n\n\tprivate resolveResourcePath(p: string): string {\n\t\treturn resolvePath(p, this.cwd, { trim: true });\n\t}\n\n\tprivate loadThemes(\n\t\tpaths: string[],\n\t\tincludeDefaults: boolean = true,\n\t): {\n\t\tthemes: Theme[];\n\t\tdiagnostics: ResourceDiagnostic[];\n\t} {\n\t\tconst themes: Theme[] = [];\n\t\tconst diagnostics: ResourceDiagnostic[] = [];\n\t\tif (includeDefaults) {\n\t\t\tconst defaultDirs = [join(this.agentDir, \"themes\"), join(this.cwd, CONFIG_DIR_NAME, \"themes\")];\n\n\t\t\tfor (const dir of defaultDirs) {\n\t\t\t\tthis.loadThemesFromDir(dir, themes, diagnostics);\n\t\t\t}\n\t\t}\n\n\t\tfor (const p of paths) {\n\t\t\tconst resolved = this.resolveResourcePath(p);\n\t\t\tif (!existsSync(resolved)) {\n\t\t\t\tdiagnostics.push({ type: \"warning\", message: \"theme path does not exist\", path: resolved });\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst stats = statSync(resolved);\n\t\t\t\tif (stats.isDirectory()) {\n\t\t\t\t\tthis.loadThemesFromDir(resolved, themes, diagnostics);\n\t\t\t\t} else if (stats.isFile() && resolved.endsWith(\".json\")) {\n\t\t\t\t\tthis.loadThemeFromFile(resolved, themes, diagnostics);\n\t\t\t\t} else {\n\t\t\t\t\tdiagnostics.push({ type: \"warning\", message: \"theme path is not a json file\", path: resolved });\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : \"failed to read theme path\";\n\t\t\t\tdiagnostics.push({ type: \"warning\", message, path: resolved });\n\t\t\t}\n\t\t}\n\n\t\treturn { themes, diagnostics };\n\t}\n\n\tprivate loadThemesFromDir(dir: string, themes: Theme[], diagnostics: ResourceDiagnostic[]): void {\n\t\tif (!existsSync(dir)) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst entries = readdirSync(dir, { withFileTypes: true });\n\t\t\tfor (const entry of entries) {\n\t\t\t\tlet isFile = entry.isFile();\n\t\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tisFile = statSync(join(dir, entry.name)).isFile();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!isFile) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!entry.name.endsWith(\".json\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthis.loadThemeFromFile(join(dir, entry.name), themes, diagnostics);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read theme directory\";\n\t\t\tdiagnostics.push({ type: \"warning\", message, path: dir });\n\t\t}\n\t}\n\n\tprivate loadThemeFromFile(filePath: string, themes: Theme[], diagnostics: ResourceDiagnostic[]): void {\n\t\ttry {\n\t\t\tthemes.push(loadThemeFromPath(filePath));\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to load theme\";\n\t\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\t}\n\t}\n\n\tprivate async loadExtensionFactories(runtime: ExtensionRuntime): Promise<{\n\t\textensions: Extension[];\n\t\terrors: Array<{ path: string; error: string }>;\n\t}> {\n\t\tconst extensions: Extension[] = [];\n\t\tconst errors: Array<{ path: string; error: string }> = [];\n\n\t\tfor (const [index, input] of this.extensionFactories.entries()) {\n\t\t\tconst isNamed = typeof input !== \"function\";\n\t\t\tconst factory = isNamed ? input.factory : input;\n\t\t\tconst extensionPath = ``;\n\t\t\ttry {\n\t\t\t\tconst extension = await loadExtensionFromFactory(factory, this.cwd, this.eventBus, runtime, extensionPath);\n\t\t\t\textension.hidden = isNamed && input.hidden;\n\t\t\t\textensions.push(extension);\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : \"failed to load extension\";\n\t\t\t\terrors.push({ path: extensionPath, error: message });\n\t\t\t}\n\t\t}\n\n\t\treturn { extensions, errors };\n\t}\n\n\tprivate dedupePrompts(prompts: PromptTemplate[]): { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] } {\n\t\tconst seen = new Map();\n\t\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\t\tfor (const prompt of prompts) {\n\t\t\tconst existing = seen.get(prompt.name);\n\t\t\tif (existing) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"collision\",\n\t\t\t\t\tmessage: `name \"/${prompt.name}\" collision`,\n\t\t\t\t\tpath: prompt.filePath,\n\t\t\t\t\tcollision: {\n\t\t\t\t\t\tresourceType: \"prompt\",\n\t\t\t\t\t\tname: prompt.name,\n\t\t\t\t\t\twinnerPath: existing.filePath,\n\t\t\t\t\t\tloserPath: prompt.filePath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tseen.set(prompt.name, prompt);\n\t\t\t}\n\t\t}\n\n\t\treturn { prompts: Array.from(seen.values()), diagnostics };\n\t}\n\n\tprivate dedupeThemes(themes: Theme[]): { themes: Theme[]; diagnostics: ResourceDiagnostic[] } {\n\t\tconst seen = new Map();\n\t\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\t\tfor (const t of themes) {\n\t\t\tconst name = t.name ?? \"unnamed\";\n\t\t\tconst existing = seen.get(name);\n\t\t\tif (existing) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"collision\",\n\t\t\t\t\tmessage: `name \"${name}\" collision`,\n\t\t\t\t\tpath: t.sourcePath,\n\t\t\t\t\tcollision: {\n\t\t\t\t\t\tresourceType: \"theme\",\n\t\t\t\t\t\tname,\n\t\t\t\t\t\twinnerPath: existing.sourcePath ?? \"\",\n\t\t\t\t\t\tloserPath: t.sourcePath ?? \"\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tseen.set(name, t);\n\t\t\t}\n\t\t}\n\n\t\treturn { themes: Array.from(seen.values()), diagnostics };\n\t}\n\n\tprivate discoverSystemPromptFile(): string | undefined {\n\t\tconst projectPath = join(this.cwd, CONFIG_DIR_NAME, \"SYSTEM.md\");\n\t\tif (this.settingsManager.isProjectTrusted() && existsSync(projectPath)) {\n\t\t\treturn projectPath;\n\t\t}\n\n\t\tconst globalPath = join(this.agentDir, \"SYSTEM.md\");\n\t\tif (existsSync(globalPath)) {\n\t\t\treturn globalPath;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate discoverAppendSystemPromptFile(): string | undefined {\n\t\tconst projectPath = join(this.cwd, CONFIG_DIR_NAME, \"APPEND_SYSTEM.md\");\n\t\tif (this.settingsManager.isProjectTrusted() && existsSync(projectPath)) {\n\t\t\treturn projectPath;\n\t\t}\n\n\t\tconst globalPath = join(this.agentDir, \"APPEND_SYSTEM.md\");\n\t\tif (existsSync(globalPath)) {\n\t\t\treturn globalPath;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate isUnderPath(target: string, root: string): boolean {\n\t\tconst normalizedRoot = resolve(root);\n\t\tif (target === normalizedRoot) {\n\t\t\treturn true;\n\t\t}\n\t\tconst prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;\n\t\treturn target.startsWith(prefix);\n\t}\n\n\tprivate detectExtensionConflicts(extensions: Extension[]): Array<{ path: string; message: string }> {\n\t\tconst conflicts: Array<{ path: string; message: string }> = [];\n\n\t\t// Track which extension registered each tool and flag\n\t\tconst toolOwners = new Map();\n\t\tconst flagOwners = new Map();\n\n\t\tfor (const ext of extensions) {\n\t\t\t// Check tools\n\t\t\tfor (const toolName of ext.tools.keys()) {\n\t\t\t\tconst existingOwner = toolOwners.get(toolName);\n\t\t\t\tif (existingOwner && existingOwner !== ext.path) {\n\t\t\t\t\tconflicts.push({\n\t\t\t\t\t\tpath: ext.path,\n\t\t\t\t\t\tmessage: `Tool \"${toolName}\" conflicts with ${existingOwner}`,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\ttoolOwners.set(toolName, ext.path);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check flags\n\t\t\tfor (const flagName of ext.flags.keys()) {\n\t\t\t\tconst existingOwner = flagOwners.get(flagName);\n\t\t\t\tif (existingOwner && existingOwner !== ext.path) {\n\t\t\t\t\tconflicts.push({\n\t\t\t\t\t\tpath: ext.path,\n\t\t\t\t\t\tmessage: `Flag \"--${flagName}\" conflicts with ${existingOwner}`,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tflagOwners.set(flagName, ext.path);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn conflicts;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/runtime-credentials.d.ts b/dist/core/runtime-credentials.d.ts new file mode 100644 index 0000000..a9df5f2 --- /dev/null +++ b/dist/core/runtime-credentials.d.ts @@ -0,0 +1,15 @@ +import type { Credential, CredentialInfo, CredentialStore } from "@earendil-works/pi-ai"; +/** Async credential store overlay for non-persistent runtime API keys. */ +export declare class RuntimeCredentials implements CredentialStore { + private readonly store; + private readonly overrides; + constructor(store: CredentialStore); + setRuntimeApiKey(providerId: string, apiKey: string): void; + removeRuntimeApiKey(providerId: string): void; + hasRuntimeApiKey(providerId: string): boolean; + read(providerId: string): Promise; + list(): Promise; + modify(providerId: string, fn: (current: Credential | undefined) => Promise): Promise; + delete(providerId: string): Promise; +} +//# sourceMappingURL=runtime-credentials.d.ts.map \ No newline at end of file diff --git a/dist/core/runtime-credentials.d.ts.map b/dist/core/runtime-credentials.d.ts.map new file mode 100644 index 0000000..c6d87c6 --- /dev/null +++ b/dist/core/runtime-credentials.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-credentials.d.ts","sourceRoot":"","sources":["../../src/core/runtime-credentials.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAEzF,0EAA0E;AAC1E,qBAAa,kBAAmB,YAAW,eAAe;IACzD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAkB;IACxC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA6B;IAEvD,YAAY,KAAK,EAAE,eAAe,EAEjC;IAED,gBAAgB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAEzD;IAED,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAE5C;IAED,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAE5C;IAEK,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAG9D;IAEK,IAAI,IAAI,OAAO,CAAC,SAAS,cAAc,EAAE,CAAC,CAM/C;IAED,MAAM,CACL,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,CAAC,OAAO,EAAE,UAAU,GAAG,SAAS,KAAK,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,GACtE,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAEjC;IAEK,MAAM,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAG9C;CACD","sourcesContent":["import type { Credential, CredentialInfo, CredentialStore } from \"@earendil-works/pi-ai\";\n\n/** Async credential store overlay for non-persistent runtime API keys. */\nexport class RuntimeCredentials implements CredentialStore {\n\tprivate readonly store: CredentialStore;\n\tprivate readonly overrides = new Map();\n\n\tconstructor(store: CredentialStore) {\n\t\tthis.store = store;\n\t}\n\n\tsetRuntimeApiKey(providerId: string, apiKey: string): void {\n\t\tthis.overrides.set(providerId, apiKey);\n\t}\n\n\tremoveRuntimeApiKey(providerId: string): void {\n\t\tthis.overrides.delete(providerId);\n\t}\n\n\thasRuntimeApiKey(providerId: string): boolean {\n\t\treturn this.overrides.has(providerId);\n\t}\n\n\tasync read(providerId: string): Promise {\n\t\tconst override = this.overrides.get(providerId);\n\t\treturn override ? { type: \"api_key\", key: override } : this.store.read(providerId);\n\t}\n\n\tasync list(): Promise {\n\t\tconst entries = new Map((await this.store.list()).map((entry) => [entry.providerId, entry]));\n\t\tfor (const providerId of this.overrides.keys()) {\n\t\t\tentries.set(providerId, { providerId, type: \"api_key\" });\n\t\t}\n\t\treturn [...entries.values()];\n\t}\n\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise,\n\t): Promise {\n\t\treturn this.store.modify(providerId, fn);\n\t}\n\n\tasync delete(providerId: string): Promise {\n\t\tthis.overrides.delete(providerId);\n\t\tawait this.store.delete(providerId);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/runtime-credentials.js b/dist/core/runtime-credentials.js new file mode 100644 index 0000000..fe98870 --- /dev/null +++ b/dist/core/runtime-credentials.js @@ -0,0 +1,36 @@ +/** Async credential store overlay for non-persistent runtime API keys. */ +export class RuntimeCredentials { + store; + overrides = new Map(); + constructor(store) { + this.store = store; + } + setRuntimeApiKey(providerId, apiKey) { + this.overrides.set(providerId, apiKey); + } + removeRuntimeApiKey(providerId) { + this.overrides.delete(providerId); + } + hasRuntimeApiKey(providerId) { + return this.overrides.has(providerId); + } + async read(providerId) { + const override = this.overrides.get(providerId); + return override ? { type: "api_key", key: override } : this.store.read(providerId); + } + async list() { + const entries = new Map((await this.store.list()).map((entry) => [entry.providerId, entry])); + for (const providerId of this.overrides.keys()) { + entries.set(providerId, { providerId, type: "api_key" }); + } + return [...entries.values()]; + } + modify(providerId, fn) { + return this.store.modify(providerId, fn); + } + async delete(providerId) { + this.overrides.delete(providerId); + await this.store.delete(providerId); + } +} +//# sourceMappingURL=runtime-credentials.js.map \ No newline at end of file diff --git a/dist/core/runtime-credentials.js.map b/dist/core/runtime-credentials.js.map new file mode 100644 index 0000000..966a83c --- /dev/null +++ b/dist/core/runtime-credentials.js.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-credentials.js","sourceRoot":"","sources":["../../src/core/runtime-credentials.ts"],"names":[],"mappings":"AAEA,0EAA0E;AAC1E,MAAM,OAAO,kBAAkB;IACb,KAAK,CAAkB;IACvB,SAAS,GAAG,IAAI,GAAG,EAAkB,CAAC;IAEvD,YAAY,KAAsB,EAAE;QACnC,IA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C;QAClC,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IAAA,CACzC;IAED,KAAK,CAAC,MAAM,CAAC,UAAkB,EAAiB;QAC/C,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAClC,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAAA,CACpC;CACD","sourcesContent":["import type { Credential, CredentialInfo, CredentialStore } from \"@earendil-works/pi-ai\";\n\n/** Async credential store overlay for non-persistent runtime API keys. */\nexport class RuntimeCredentials implements CredentialStore {\n\tprivate readonly store: CredentialStore;\n\tprivate readonly overrides = new Map();\n\n\tconstructor(store: CredentialStore) {\n\t\tthis.store = store;\n\t}\n\n\tsetRuntimeApiKey(providerId: string, apiKey: string): void {\n\t\tthis.overrides.set(providerId, apiKey);\n\t}\n\n\tremoveRuntimeApiKey(providerId: string): void {\n\t\tthis.overrides.delete(providerId);\n\t}\n\n\thasRuntimeApiKey(providerId: string): boolean {\n\t\treturn this.overrides.has(providerId);\n\t}\n\n\tasync read(providerId: string): Promise {\n\t\tconst override = this.overrides.get(providerId);\n\t\treturn override ? { type: \"api_key\", key: override } : this.store.read(providerId);\n\t}\n\n\tasync list(): Promise {\n\t\tconst entries = new Map((await this.store.list()).map((entry) => [entry.providerId, entry]));\n\t\tfor (const providerId of this.overrides.keys()) {\n\t\t\tentries.set(providerId, { providerId, type: \"api_key\" });\n\t\t}\n\t\treturn [...entries.values()];\n\t}\n\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise,\n\t): Promise {\n\t\treturn this.store.modify(providerId, fn);\n\t}\n\n\tasync delete(providerId: string): Promise {\n\t\tthis.overrides.delete(providerId);\n\t\tawait this.store.delete(providerId);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/sdk.d.ts b/dist/core/sdk.d.ts new file mode 100644 index 0000000..7778619 --- /dev/null +++ b/dist/core/sdk.d.ts @@ -0,0 +1,106 @@ +import { type ThinkingLevel } from "@earendil-works/pi-agent-core"; +import { type Model } from "@earendil-works/pi-ai/compat"; +import { AgentSession } from "./agent-session.ts"; +import type { LoadExtensionsResult, SessionStartEvent, ToolDefinition } from "./extensions/index.ts"; +import { ModelRuntime } from "./model-runtime.ts"; +import type { ResourceLoader } from "./resource-loader.ts"; +import { SessionManager } from "./session-manager.ts"; +import { SettingsManager } from "./settings-manager.ts"; +import { createBashTool, createCodingTools, createEditTool, createFindTool, createGrepTool, createLsTool, createReadOnlyTools, createReadTool, createWriteTool, withFileMutationQueue } from "./tools/index.ts"; +export interface CreateAgentSessionOptions { + /** Working directory for project-local discovery. Default: process.cwd() */ + cwd?: string; + /** Global config directory. Default: ~/.pi/agent */ + agentDir?: string; + /** Canonical model/auth runtime. Defaults to a runtime using agentDir/auth.json and models.json. */ + modelRuntime?: ModelRuntime; + /** Model to use. Default: from settings, else first available */ + model?: Model; + /** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */ + thinkingLevel?: ThinkingLevel; + /** Models available for cycling (Ctrl+P in interactive mode) */ + scopedModels?: Array<{ + model: Model; + thinkingLevel?: ThinkingLevel; + }>; + /** + * Optional default tool suppression mode when no explicit allowlist is provided. + * + * - "all": start with no tools enabled + * - "builtin": disable the default built-in tools (read, bash, edit, write) + * but keep extension/custom tools enabled + */ + noTools?: "all" | "builtin"; + /** + * Optional allowlist of tool names. + * + * When omitted, pi enables the default built-in tools (read, bash, edit, write) + * and leaves extension/custom tools enabled unless `noTools` changes that default. + * When provided, only the listed tool names are enabled. + */ + tools?: string[]; + /** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */ + excludeTools?: string[]; + /** Custom tools to register (in addition to built-in tools). */ + customTools?: ToolDefinition[]; + /** Resource loader. When omitted, DefaultResourceLoader is used. */ + resourceLoader?: ResourceLoader; + /** Session manager. Default: SessionManager.create(cwd) */ + sessionManager?: SessionManager; + /** Settings manager. Default: SettingsManager.create(cwd, agentDir) */ + settingsManager?: SettingsManager; + /** Session start event metadata for extension runtime startup. */ + sessionStartEvent?: SessionStartEvent; +} +/** Result from createAgentSession */ +export interface CreateAgentSessionResult { + /** The created session */ + session: AgentSession; + /** Extensions result (for UI context setup in interactive mode) */ + extensionsResult: LoadExtensionsResult; + /** Warning if session was restored with a different model than saved */ + modelFallbackMessage?: string; +} +export * from "./agent-session-runtime.ts"; +export type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, ExtensionFactory, InlineExtension, SlashCommandInfo, SlashCommandSource, ToolDefinition, } from "./extensions/index.ts"; +export type { PromptTemplate } from "./prompt-templates.ts"; +export type { Skill } from "./skills.ts"; +export type { Tool } from "./tools/index.ts"; +export { withFileMutationQueue, createCodingTools, createReadOnlyTools, createReadTool, createBashTool, createEditTool, createWriteTool, createGrepTool, createFindTool, createLsTool, }; +/** + * Create an AgentSession with the specified options. + * + * @example + * ```typescript + * // Minimal - uses defaults + * const { session } = await createAgentSession(); + * + * // With explicit model + * import { getModel } from '@earendil-works/pi-ai'; + * const { session } = await createAgentSession({ + * model: getModel('anthropic', 'claude-opus-4-5'), + * thinkingLevel: 'high', + * }); + * + * // Continue previous session + * const { session, modelFallbackMessage } = await createAgentSession({ + * continueSession: true, + * }); + * + * // Full control + * const loader = new DefaultResourceLoader({ + * cwd: process.cwd(), + * agentDir: getAgentDir(), + * settingsManager: SettingsManager.create(), + * }); + * await loader.reload(); + * const { session } = await createAgentSession({ + * model: myModel, + * tools: ["read", "bash"], + * resourceLoader: loader, + * sessionManager: SessionManager.inMemory(), + * }); + * ``` + */ +export declare function createAgentSession(options?: CreateAgentSessionOptions): Promise; +//# sourceMappingURL=sdk.d.ts.map \ No newline at end of file diff --git a/dist/core/sdk.d.ts.map b/dist/core/sdk.d.ts.map new file mode 100644 index 0000000..a4900dc --- /dev/null +++ b/dist/core/sdk.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk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B,gGAAgG;IAChG,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,gEAAgE;IAChE,WAAW,CAAC,EAAE,cAAc,EAAE,CAAC;IAE/B,oEAAoE;IACpE,cAAc,CAAC,EAAE,cAAc,CAAC;IAEhC,2DAA2D;IAC3D,cAAc,CAAC,EAAE,cAAc,CAAC;IAEhC,uEAAuE;IACvE,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,kEAAkE;IAClE,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;CACtC;AAED,qCAAqC;AACrC,MAAM,WAAW,wBAAwB;IACxC,0BAA0B;IAC1B,OAAO,EAAE,YAAY,CAAC;IACtB,mEAAmE;IACnE,gBAAgB,EAAE,oBAAoB,CAAC;IACvC,wEAAwE;IACxE,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAID,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EACX,YAAY,EACZ,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,GACd,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,YAAY,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EACN,qBAAqB,EAErB,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,GACZ,CAAC;AAQF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAqOnH","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, setDefaultStreamFn, type ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { findInitialModel } from \"./model-resolver.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\n// Preserve the pre-0.81 fallback for extensions that construct Agent instances\n// or invoke low-level agent loops without supplying streamFn. Agent core remains\n// provider-agnostic and does not import pi-ai/compat itself.\nsetDefaultStreamFn(streamSimple);\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Canonical model/auth runtime. Defaults to a runtime using agentDir/auth.json and models.json. */\n\tmodelRuntime?: ModelRuntime;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tInlineExtension,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@earendil-works/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst modelRuntime = options.modelRuntime ?? (await ModelRuntime.create({ authPath, modelsPath }));\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRuntime.getModel(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRuntime.hasConfiguredAuth(restoredModel.provider)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRuntime,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst headerRunner = extensionRunnerRef.current;\n\t\t\treturn modelRuntime.streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\ttransformHeaders: async (requestHeaders) => {\n\t\t\t\t\tconst headers = mergeProviderAttributionHeaders(\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettingsManager,\n\t\t\t\t\t\toptions?.sessionId,\n\t\t\t\t\t\trequestHeaders,\n\t\t\t\t\t);\n\t\t\t\t\treturn headerRunner?.hasHandlers(\"before_provider_headers\")\n\t\t\t\t\t\t? headerRunner.emitBeforeProviderHeaders(headers ?? {})\n\t\t\t\t\t\t: (headers ?? {});\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRuntime,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/sdk.js b/dist/core/sdk.js new file mode 100644 index 0000000..2e8e67c --- /dev/null +++ b/dist/core/sdk.js @@ -0,0 +1,267 @@ +import { join } from "node:path"; +import { Agent, setDefaultStreamFn } from "@earendil-works/pi-agent-core"; +import { clampThinkingLevel, streamSimple } from "@earendil-works/pi-ai/compat"; +import { getAgentDir } from "../config.js"; +import { resolvePath } from "../utils/paths.js"; +import { AgentSession } from "./agent-session.js"; +import { formatNoModelsAvailableMessage } from "./auth-guidance.js"; +import { DEFAULT_THINKING_LEVEL } from "./defaults.js"; +import { convertToLlm } from "./messages.js"; +import { findInitialModel } from "./model-resolver.js"; +import { ModelRuntime } from "./model-runtime.js"; +import { mergeProviderAttributionHeaders } from "./provider-attribution.js"; +import { DefaultResourceLoader } from "./resource-loader.js"; +import { getDefaultSessionDir, SessionManager } from "./session-manager.js"; +import { SettingsManager } from "./settings-manager.js"; +import { time } from "./timings.js"; +import { createBashTool, createCodingTools, createEditTool, createFindTool, createGrepTool, createLsTool, createReadOnlyTools, createReadTool, createWriteTool, withFileMutationQueue, } from "./tools/index.js"; +// Preserve the pre-0.81 fallback for extensions that construct Agent instances +// or invoke low-level agent loops without supplying streamFn. Agent core remains +// provider-agnostic and does not import pi-ai/compat itself. +setDefaultStreamFn(streamSimple); +// Re-exports +export * from "./agent-session-runtime.js"; +export { withFileMutationQueue, +// Tool factories (for custom cwd) +createCodingTools, createReadOnlyTools, createReadTool, createBashTool, createEditTool, createWriteTool, createGrepTool, createFindTool, createLsTool, }; +// Helper Functions +function getDefaultAgentDir() { + return getAgentDir(); +} +/** + * Create an AgentSession with the specified options. + * + * @example + * ```typescript + * // Minimal - uses defaults + * const { session } = await createAgentSession(); + * + * // With explicit model + * import { getModel } from '@earendil-works/pi-ai'; + * const { session } = await createAgentSession({ + * model: getModel('anthropic', 'claude-opus-4-5'), + * thinkingLevel: 'high', + * }); + * + * // Continue previous session + * const { session, modelFallbackMessage } = await createAgentSession({ + * continueSession: true, + * }); + * + * // Full control + * const loader = new DefaultResourceLoader({ + * cwd: process.cwd(), + * agentDir: getAgentDir(), + * settingsManager: SettingsManager.create(), + * }); + * await loader.reload(); + * const { session } = await createAgentSession({ + * model: myModel, + * tools: ["read", "bash"], + * resourceLoader: loader, + * sessionManager: SessionManager.inMemory(), + * }); + * ``` + */ +export async function createAgentSession(options = {}) { + const cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd()); + const agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir(); + let resourceLoader = options.resourceLoader; + const authPath = options.agentDir ? join(agentDir, "auth.json") : undefined; + const modelsPath = options.agentDir ? join(agentDir, "models.json") : undefined; + const modelRuntime = options.modelRuntime ?? (await ModelRuntime.create({ authPath, modelsPath })); + const settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir); + const sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir)); + if (!resourceLoader) { + resourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager }); + await resourceLoader.reload(); + time("resourceLoader.reload"); + } + // Check if session has existing data to restore + const existingSession = sessionManager.buildSessionContext(); + const hasExistingSession = existingSession.messages.length > 0; + const hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === "thinking_level_change"); + let model = options.model; + let modelFallbackMessage; + // If session has data, try to restore model from it + if (!model && hasExistingSession && existingSession.model) { + const restoredModel = modelRuntime.getModel(existingSession.model.provider, existingSession.model.modelId); + if (restoredModel && modelRuntime.hasConfiguredAuth(restoredModel.provider)) { + model = restoredModel; + } + if (!model) { + modelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`; + } + } + // If still no model, use findInitialModel (checks settings default, then provider defaults) + if (!model) { + const result = await findInitialModel({ + scopedModels: [], + isContinuing: hasExistingSession, + defaultProvider: settingsManager.getDefaultProvider(), + defaultModelId: settingsManager.getDefaultModel(), + defaultThinkingLevel: settingsManager.getDefaultThinkingLevel(), + modelRuntime, + }); + model = result.model; + if (!model) { + modelFallbackMessage = formatNoModelsAvailableMessage(); + } + else if (modelFallbackMessage) { + modelFallbackMessage += `. Using ${model.provider}/${model.id}`; + } + } + let thinkingLevel = options.thinkingLevel; + // If session has data, restore thinking level from it + if (thinkingLevel === undefined && hasExistingSession) { + thinkingLevel = hasThinkingEntry + ? existingSession.thinkingLevel + : (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL); + } + // Fall back to settings default + if (thinkingLevel === undefined) { + thinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL; + } + // Clamp to model capabilities + if (!model) { + thinkingLevel = "off"; + } + else { + thinkingLevel = clampThinkingLevel(model, thinkingLevel); + } + const defaultActiveToolNames = ["read", "bash", "edit", "write"]; + const allowedToolNames = options.tools ?? (options.noTools === "all" ? [] : undefined); + const excludedToolNames = options.excludeTools; + const excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined; + const initialActiveToolNames = (options.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames).filter((name) => !excludedToolNameSet?.has(name)); + let agent; + // Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth) + const convertToLlmWithBlockImages = (messages) => { + const converted = convertToLlm(messages); + // Check setting dynamically so mid-session changes take effect + if (!settingsManager.getBlockImages()) { + return converted; + } + // Filter out ImageContent from all messages, replacing with text placeholder + return converted.map((msg) => { + if (msg.role === "user" || msg.role === "toolResult") { + const content = msg.content; + if (Array.isArray(content)) { + const hasImages = content.some((c) => c.type === "image"); + if (hasImages) { + const filteredContent = content + .map((c) => c.type === "image" ? { type: "text", text: "Image reading is disabled." } : c) + .filter((c, i, arr) => + // Dedupe consecutive "Image reading is disabled." texts + !(c.type === "text" && + c.text === "Image reading is disabled." && + i > 0 && + arr[i - 1].type === "text" && + arr[i - 1].text === "Image reading is disabled.")); + return { ...msg, content: filteredContent }; + } + } + } + return msg; + }); + }; + const extensionRunnerRef = {}; + agent = new Agent({ + initialState: { + systemPrompt: "", + model, + thinkingLevel, + tools: [], + }, + convertToLlm: convertToLlmWithBlockImages, + streamFn: async (model, context, options) => { + const providerRetrySettings = settingsManager.getProviderRetrySettings(); + const httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs(); + // SDKs treat timeout=0 as 0ms (immediate timeout), not "no timeout". + // Use max int32 to effectively disable the timeout. + const effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs; + const timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs; + const websocketConnectTimeoutMs = options?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs(); + const headerRunner = extensionRunnerRef.current; + return modelRuntime.streamSimple(model, context, { + ...options, + timeoutMs, + websocketConnectTimeoutMs, + maxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries, + maxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs, + transformHeaders: async (requestHeaders) => { + const headers = mergeProviderAttributionHeaders(model, settingsManager, options?.sessionId, requestHeaders); + return headerRunner?.hasHandlers("before_provider_headers") + ? headerRunner.emitBeforeProviderHeaders(headers ?? {}) + : (headers ?? {}); + }, + }); + }, + onPayload: async (payload, _model) => { + const runner = extensionRunnerRef.current; + if (!runner?.hasHandlers("before_provider_request")) { + return payload; + } + return runner.emitBeforeProviderRequest(payload); + }, + onResponse: async (response, _model) => { + const runner = extensionRunnerRef.current; + if (!runner?.hasHandlers("after_provider_response")) { + return; + } + await runner.emit({ + type: "after_provider_response", + status: response.status, + headers: response.headers, + }); + }, + sessionId: sessionManager.getSessionId(), + transformContext: async (messages) => { + const runner = extensionRunnerRef.current; + if (!runner) + return messages; + return runner.emitContext(messages); + }, + steeringMode: settingsManager.getSteeringMode(), + followUpMode: settingsManager.getFollowUpMode(), + transport: settingsManager.getTransport(), + thinkingBudgets: settingsManager.getThinkingBudgets(), + maxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs, + }); + // Restore messages if session has existing data + if (hasExistingSession) { + agent.state.messages = existingSession.messages; + if (!hasThinkingEntry) { + sessionManager.appendThinkingLevelChange(thinkingLevel); + } + } + else { + // Save initial model and thinking level for new sessions so they can be restored on resume + if (model) { + sessionManager.appendModelChange(model.provider, model.id); + } + sessionManager.appendThinkingLevelChange(thinkingLevel); + } + const session = new AgentSession({ + agent, + sessionManager, + settingsManager, + cwd, + scopedModels: options.scopedModels, + resourceLoader, + customTools: options.customTools, + modelRuntime, + initialActiveToolNames, + allowedToolNames, + excludedToolNames, + extensionRunnerRef, + sessionStartEvent: options.sessionStartEvent, + }); + const extensionsResult = resourceLoader.getExtensions(); + return { + session, + extensionsResult, + modelFallbackMessage, + }; +} +//# sourceMappingURL=sdk.js.map \ No newline at end of file diff --git a/dist/core/sdk.js.map b/dist/core/sdk.js.map new file mode 100644 index 0000000..68a39b0 --- /dev/null +++ b/dist/core/sdk.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,O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YAAY,CAAC;QAChC,KAAK;QACL,cAAc;QACd,eAAe;QACf,GAAG;QACH,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,cAAc;QACd,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,YAAY;QACZ,sBAAsB;QACtB,gBAAgB;QAChB,iBAAiB;QACjB,kBAAkB;QAClB,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;IACH,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, setDefaultStreamFn, type ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { convertToLlm } from \"./messages.ts\";\nimport { findInitialModel } from \"./model-resolver.ts\";\nimport { ModelRuntime } from \"./model-runtime.ts\";\nimport { mergeProviderAttributionHeaders } from \"./provider-attribution.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { getDefaultSessionDir, SessionManager } from \"./session-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype ToolName,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\n// Preserve the pre-0.81 fallback for extensions that construct Agent instances\n// or invoke low-level agent loops without supplying streamFn. Agent core remains\n// provider-agnostic and does not import pi-ai/compat itself.\nsetDefaultStreamFn(streamSimple);\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Canonical model/auth runtime. Defaults to a runtime using agentDir/auth.json and models.json. */\n\tmodelRuntime?: ModelRuntime;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the default built-in tools (read, bash, edit, write)\n\t * and leaves extension/custom tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tInlineExtension,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@earendil-works/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst modelRuntime = options.modelRuntime ?? (await ModelRuntime.create({ authPath, modelsPath }));\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRuntime.getModel(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRuntime.hasConfiguredAuth(restoredModel.provider)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRuntime,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to settings default\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames: ToolName[] = [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst headerRunner = extensionRunnerRef.current;\n\t\t\treturn modelRuntime.streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\ttransformHeaders: async (requestHeaders) => {\n\t\t\t\t\tconst headers = mergeProviderAttributionHeaders(\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsettingsManager,\n\t\t\t\t\t\toptions?.sessionId,\n\t\t\t\t\t\trequestHeaders,\n\t\t\t\t\t);\n\t\t\t\t\treturn headerRunner?.hasHandlers(\"before_provider_headers\")\n\t\t\t\t\t\t? headerRunner.emitBeforeProviderHeaders(headers ?? {})\n\t\t\t\t\t\t: (headers ?? {});\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRuntime,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/session-cwd.d.ts b/dist/core/session-cwd.d.ts new file mode 100644 index 0000000..e52b6d0 --- /dev/null +++ b/dist/core/session-cwd.d.ts @@ -0,0 +1,19 @@ +export interface SessionCwdIssue { + sessionFile?: string; + sessionCwd: string; + fallbackCwd: string; +} +interface SessionCwdSource { + getCwd(): string; + getSessionFile(): string | undefined; +} +export declare function getMissingSessionCwdIssue(sessionManager: SessionCwdSource, fallbackCwd: string): SessionCwdIssue | undefined; +export declare function formatMissingSessionCwdError(issue: SessionCwdIssue): string; +export declare function formatMissingSessionCwdPrompt(issue: SessionCwdIssue): string; +export declare class MissingSessionCwdError extends Error { + readonly issue: SessionCwdIssue; + constructor(issue: SessionCwdIssue); +} +export declare function assertSessionCwdExists(sessionManager: SessionCwdSource, fallbackCwd: string): void; +export {}; +//# sourceMappingURL=session-cwd.d.ts.map \ No newline at end of file diff --git a/dist/core/session-cwd.d.ts.map b/dist/core/session-cwd.d.ts.map new file mode 100644 index 0000000..a204c71 --- /dev/null +++ b/dist/core/session-cwd.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-cwd.d.ts","sourceRoot":"","sources":["../../src/core/session-cwd.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,eAAe;IAC/B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,UAAU,gBAAgB;IACzB,MAAM,IAAI,MAAM,CAAC;IACjB,cAAc,IAAI,MAAM,GAAG,SAAS,CAAC;CACrC;AAED,wBAAgB,yBAAyB,CACxC,cAAc,EAAE,gBAAgB,EAChC,WAAW,EAAE,MAAM,GACjB,eAAe,GAAG,SAAS,CAgB7B;AAED,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,eAAe,GAAG,MAAM,CAG3E;AAED,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,eAAe,GAAG,MAAM,CAE5E;AAED,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,KAAK,EAAE,eAAe,CAAC;IAEhC,YAAY,KAAK,EAAE,eAAe,EAIjC;CACD;AAED,wBAAgB,sBAAsB,CAAC,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,GAAG,IAAI,CAKlG","sourcesContent":["import { existsSync } from \"node:fs\";\n\nexport interface SessionCwdIssue {\n\tsessionFile?: string;\n\tsessionCwd: string;\n\tfallbackCwd: string;\n}\n\ninterface SessionCwdSource {\n\tgetCwd(): string;\n\tgetSessionFile(): string | undefined;\n}\n\nexport function getMissingSessionCwdIssue(\n\tsessionManager: SessionCwdSource,\n\tfallbackCwd: string,\n): SessionCwdIssue | undefined {\n\tconst sessionFile = sessionManager.getSessionFile();\n\tif (!sessionFile) {\n\t\treturn undefined;\n\t}\n\n\tconst sessionCwd = sessionManager.getCwd();\n\tif (!sessionCwd || existsSync(sessionCwd)) {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tsessionFile,\n\t\tsessionCwd,\n\t\tfallbackCwd,\n\t};\n}\n\nexport function formatMissingSessionCwdError(issue: SessionCwdIssue): string {\n\tconst sessionFile = issue.sessionFile ? `\\nSession file: ${issue.sessionFile}` : \"\";\n\treturn `Stored session working directory does not exist: ${issue.sessionCwd}${sessionFile}\\nCurrent working directory: ${issue.fallbackCwd}`;\n}\n\nexport function formatMissingSessionCwdPrompt(issue: SessionCwdIssue): string {\n\treturn `cwd from session file does not exist\\n${issue.sessionCwd}\\n\\ncontinue in current cwd\\n${issue.fallbackCwd}`;\n}\n\nexport class MissingSessionCwdError extends Error {\n\treadonly issue: SessionCwdIssue;\n\n\tconstructor(issue: SessionCwdIssue) {\n\t\tsuper(formatMissingSessionCwdError(issue));\n\t\tthis.name = \"MissingSessionCwdError\";\n\t\tthis.issue = issue;\n\t}\n}\n\nexport function assertSessionCwdExists(sessionManager: SessionCwdSource, fallbackCwd: string): void {\n\tconst issue = getMissingSessionCwdIssue(sessionManager, fallbackCwd);\n\tif (issue) {\n\t\tthrow new MissingSessionCwdError(issue);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/session-cwd.js b/dist/core/session-cwd.js new file mode 100644 index 0000000..287c109 --- /dev/null +++ b/dist/core/session-cwd.js @@ -0,0 +1,38 @@ +import { existsSync } from "node:fs"; +export function getMissingSessionCwdIssue(sessionManager, fallbackCwd) { + const sessionFile = sessionManager.getSessionFile(); + if (!sessionFile) { + return undefined; + } + const sessionCwd = sessionManager.getCwd(); + if (!sessionCwd || existsSync(sessionCwd)) { + return undefined; + } + return { + sessionFile, + sessionCwd, + fallbackCwd, + }; +} +export function formatMissingSessionCwdError(issue) { + const sessionFile = issue.sessionFile ? `\nSession file: ${issue.sessionFile}` : ""; + return `Stored session working directory does not exist: ${issue.sessionCwd}${sessionFile}\nCurrent working directory: ${issue.fallbackCwd}`; +} +export function formatMissingSessionCwdPrompt(issue) { + return `cwd from session file does not exist\n${issue.sessionCwd}\n\ncontinue in current cwd\n${issue.fallbackCwd}`; +} +export class MissingSessionCwdError extends Error { + issue; + constructor(issue) { + super(formatMissingSessionCwdError(issue)); + this.name = "MissingSessionCwdError"; + this.issue = issue; + } +} +export function assertSessionCwdExists(sessionManager, fallbackCwd) { + const issue = getMissingSessionCwdIssue(sessionManager, fallbackCwd); + if (issue) { + throw new MissingSessionCwdError(issue); + } +} +//# sourceMappingURL=session-cwd.js.map \ No newline at end of file diff --git a/dist/core/session-cwd.js.map b/dist/core/session-cwd.js.map new file mode 100644 index 0000000..801d8c4 --- /dev/null +++ b/dist/core/session-cwd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"session-cwd.js","sourceRoot":"","sources":["../../src/core/session-cwd.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAarC,MAAM,UAAU,yBAAyB,CACxC,cAAgC,EAChC,WAAmB,EACW;IAC9B,MAAM,WAAW,GAAG,cAAc,CAAC,cAAc,EAAE,CAAC;IACpD,IAAI,CAAC,WAAW,EAAE,CAAC;QAClB,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,MAAM,UAAU,GAAG,cAAc,CAAC,MAAM,EAAE,CAAC;IAC3C,IAAI,CAAC,UAAU,IAAI,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;QAC3C,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO;QACN,WAAW;QACX,UAAU;QACV,WAAW;KACX,CAAC;AAAA,CACF;AAED,MAAM,UAAU,4BAA4B,CAAC,KAAsB,EAAU;IAC5E,MAAM,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,mBAAmB,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACpF,OAAO,oDAAoD,KAAK,CAAC,UAAU,GAAG,WAAW,gCAAgC,KAAK,CAAC,WAAW,EAAE,CAAC;AAAA,CAC7I;AAED,MAAM,UAAU,6BAA6B,CAAC,KAAsB,EAAU;IAC7E,OAAO,yCAAyC,KAAK,CAAC,UAAU,gCAAgC,KAAK,CAAC,WAAW,EAAE,CAAC;AAAA,CACpH;AAED,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IACvC,KAAK,CAAkB;IAEhC,YAAY,KAAsB,EAAE;QACnC,KAAK,CAAC,4BAA4B,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3C,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;QACrC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IAAA,CACnB;CACD;AAED,MAAM,UAAU,sBAAsB,CAAC,cAAgC,EAAE,WAAmB,EAAQ;IACnG,MAAM,KAAK,GAAG,yBAAyB,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IACrE,IAAI,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,sBAAsB,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;AAAA,CACD","sourcesContent":["import { existsSync } from \"node:fs\";\n\nexport interface SessionCwdIssue {\n\tsessionFile?: string;\n\tsessionCwd: string;\n\tfallbackCwd: string;\n}\n\ninterface SessionCwdSource {\n\tgetCwd(): string;\n\tgetSessionFile(): string | undefined;\n}\n\nexport function getMissingSessionCwdIssue(\n\tsessionManager: SessionCwdSource,\n\tfallbackCwd: string,\n): SessionCwdIssue | undefined {\n\tconst sessionFile = sessionManager.getSessionFile();\n\tif (!sessionFile) {\n\t\treturn undefined;\n\t}\n\n\tconst sessionCwd = sessionManager.getCwd();\n\tif (!sessionCwd || existsSync(sessionCwd)) {\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tsessionFile,\n\t\tsessionCwd,\n\t\tfallbackCwd,\n\t};\n}\n\nexport function formatMissingSessionCwdError(issue: SessionCwdIssue): string {\n\tconst sessionFile = issue.sessionFile ? `\\nSession file: ${issue.sessionFile}` : \"\";\n\treturn `Stored session working directory does not exist: ${issue.sessionCwd}${sessionFile}\\nCurrent working directory: ${issue.fallbackCwd}`;\n}\n\nexport function formatMissingSessionCwdPrompt(issue: SessionCwdIssue): string {\n\treturn `cwd from session file does not exist\\n${issue.sessionCwd}\\n\\ncontinue in current cwd\\n${issue.fallbackCwd}`;\n}\n\nexport class MissingSessionCwdError extends Error {\n\treadonly issue: SessionCwdIssue;\n\n\tconstructor(issue: SessionCwdIssue) {\n\t\tsuper(formatMissingSessionCwdError(issue));\n\t\tthis.name = \"MissingSessionCwdError\";\n\t\tthis.issue = issue;\n\t}\n}\n\nexport function assertSessionCwdExists(sessionManager: SessionCwdSource, fallbackCwd: string): void {\n\tconst issue = getMissingSessionCwdIssue(sessionManager, fallbackCwd);\n\tif (issue) {\n\t\tthrow new MissingSessionCwdError(issue);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/session-manager.d.ts b/dist/core/session-manager.d.ts new file mode 100644 index 0000000..8cdfbde --- /dev/null +++ b/dist/core/session-manager.d.ts @@ -0,0 +1,356 @@ +import type { AgentMessage } from "@earendil-works/pi-agent-core"; +import { type ImageContent, type Message, type TextContent, type Usage } from "@earendil-works/pi-ai"; +import { type BashExecutionMessage, type CustomMessage } from "./messages.ts"; +export declare const CURRENT_SESSION_VERSION = 3; +export interface SessionHeader { + type: "session"; + version?: number; + id: string; + timestamp: string; + cwd: string; + parentSession?: string; +} +export interface NewSessionOptions { + id?: string; + parentSession?: string; +} +export interface SessionEntryBase { + type: string; + id: string; + parentId: string | null; + timestamp: string; +} +export interface SessionMessageEntry extends SessionEntryBase { + type: "message"; + message: AgentMessage; +} +export interface ThinkingLevelChangeEntry extends SessionEntryBase { + type: "thinking_level_change"; + thinkingLevel: string; +} +export interface ModelChangeEntry extends SessionEntryBase { + type: "model_change"; + provider: string; + modelId: string; +} +export interface CompactionEntry extends SessionEntryBase { + type: "compaction"; + summary: string; + firstKeptEntryId: string; + tokensBefore: number; + /** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */ + details?: T; + /** Usage from the LLM call(s) that generated this summary, if available */ + usage?: Usage; + /** True if generated by an extension, undefined/false if pi-generated (backward compatible) */ + fromHook?: boolean; +} +export interface BranchSummaryEntry extends SessionEntryBase { + type: "branch_summary"; + fromId: string; + summary: string; + /** Extension-specific data (not sent to LLM) */ + details?: T; + /** Usage from the LLM call that generated this summary, if available */ + usage?: Usage; + /** True if generated by an extension, false if pi-generated */ + fromHook?: boolean; +} +/** + * Custom entry for extensions to store extension-specific data in the session. + * Use customType to identify your extension's entries. + * + * Purpose: Persist extension state across session reloads. On reload, extensions can + * scan entries for their customType and reconstruct internal state. + * + * Does NOT participate in LLM context (ignored by buildSessionContext). + * For injecting content into context, see CustomMessageEntry. + */ +export interface CustomEntry extends SessionEntryBase { + type: "custom"; + customType: string; + data?: T; +} +/** Label entry for user-defined bookmarks/markers on entries. */ +export interface LabelEntry extends SessionEntryBase { + type: "label"; + targetId: string; + label: string | undefined; +} +/** Session metadata entry (e.g., user-defined display name). */ +export interface SessionInfoEntry extends SessionEntryBase { + type: "session_info"; + name?: string; +} +/** + * Custom message entry for extensions to inject messages into LLM context. + * Use customType to identify your extension's entries. + * + * Unlike CustomEntry, this DOES participate in LLM context. + * The content is converted to a user message in buildSessionContext(). + * Use details for extension-specific metadata (not sent to LLM). + * + * display controls TUI rendering: + * - false: hidden entirely + * - true: rendered with distinct styling (different from user messages) + */ +export interface CustomMessageEntry extends SessionEntryBase { + type: "custom_message"; + customType: string; + content: string | (TextContent | ImageContent)[]; + details?: T; + display: boolean; +} +/** Session entry - has id/parentId for tree structure (returned by "read" methods in SessionManager) */ +export type SessionEntry = SessionMessageEntry | ThinkingLevelChangeEntry | ModelChangeEntry | CompactionEntry | BranchSummaryEntry | CustomEntry | CustomMessageEntry | LabelEntry | SessionInfoEntry; +/** Raw file entry (includes header) */ +export type FileEntry = SessionHeader | SessionEntry; +/** Tree node for getTree() - defensive copy of session structure */ +export interface SessionTreeNode { + entry: SessionEntry; + children: SessionTreeNode[]; + /** Resolved label for this entry, if any */ + label?: string; + /** Timestamp of the latest label change for this entry, if any */ + labelTimestamp?: string; +} +export interface SessionContext { + messages: AgentMessage[]; + thinkingLevel: string; + model: { + provider: string; + modelId: string; + } | null; +} +export interface SessionInfo { + path: string; + id: string; + /** Working directory where the session was started. Empty string for old sessions. */ + cwd: string; + /** User-defined display name from session_info entries. */ + name?: string; + /** Path to the parent session (if this session was forked). */ + parentSessionPath?: string; + created: Date; + modified: Date; + messageCount: number; + firstMessage: string; + allMessagesText: string; +} +export type ReadonlySessionManager = Pick; +export declare function assertValidSessionId(id: string): void; +/** Exported for testing */ +export declare function migrateSessionEntries(entries: FileEntry[]): void; +/** Exported for compaction.test.ts */ +export declare function parseSessionEntries(content: string): FileEntry[]; +export declare function getLatestCompactionEntry(entries: SessionEntry[]): CompactionEntry | null; +/** + * Project one selected session entry into LLM/runtime messages. + * Plain custom entries are display/state entries and do not participate in context. + */ +export declare function sessionEntryToContextMessages(entry: SessionEntry): AgentMessage[]; +/** + * Build the active, compaction-aware session entry list. + * + * This follows the current leaf path. If the path contains compaction entries, + * the latest compaction is represented by the compaction entry itself, followed + * by the kept entries starting at firstKeptEntryId and all entries after the + * compaction entry. Older summarized entries are omitted. + */ +export declare function buildContextEntries(entries: SessionEntry[], leafId?: string | null, byId?: Map): SessionEntry[]; +/** + * Build the session context from entries using tree traversal. + * If leafId is provided, walks from that entry to root. + * Handles compaction and branch summaries along the path. + */ +export declare function buildSessionContext(entries: SessionEntry[], leafId?: string | null, byId?: Map): SessionContext; +export declare function getDefaultSessionDir(cwd: string, agentDir?: string): string; +/** Exported for testing */ +export declare function loadEntriesFromFile(filePath: string): FileEntry[]; +/** Exported for testing */ +export declare function findMostRecentSession(sessionDir: string, cwd?: string): string | null; +export type SessionListProgress = (loaded: number, total: number) => void; +/** + * Manages conversation sessions as append-only trees stored in JSONL files. + * + * Each session entry has an id and parentId forming a tree structure. The "leaf" + * pointer tracks the current position. Appending creates a child of the current leaf. + * Branching moves the leaf to an earlier entry, allowing new branches without + * modifying history. + * + * Use buildSessionContext() to get the resolved message list for the LLM, which + * handles compaction summaries and follows the path from root to current leaf. + */ +export declare class SessionManager { + private sessionId; + private sessionFile; + private sessionDir; + private cwd; + private persist; + private flushed; + private fileEntries; + private byId; + private labelsById; + private labelTimestampsById; + private leafId; + private constructor(); + /** Switch to a different session file (used for resume and branching) */ + setSessionFile(sessionFile: string): void; + private _setSessionFile; + newSession(options?: NewSessionOptions): string | undefined; + private _buildIndex; + private _rewriteFile; + isPersisted(): boolean; + getCwd(): string; + getSessionDir(): string; + usesDefaultSessionDir(): boolean; + getSessionId(): string; + getSessionFile(): string | undefined; + _persist(entry: SessionEntry): void; + private _appendEntry; + /** Append a message as child of current leaf, then advance leaf. Returns entry id. + * Does not allow writing CompactionSummaryMessage and BranchSummaryMessage directly. + * Reason: we want these to be top-level entries in the session, not message session entries, + * so it is easier to find them. + * These need to be appended via appendCompaction() and appendBranchSummary() methods. + */ + appendMessage(message: Message | CustomMessage | BashExecutionMessage): string; + /** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */ + appendThinkingLevelChange(thinkingLevel: string): string; + /** Append a model change as child of current leaf, then advance leaf. Returns entry id. */ + appendModelChange(provider: string, modelId: string): string; + /** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */ + appendCompaction(summary: string, firstKeptEntryId: string, tokensBefore: number, details?: T, fromHook?: boolean, usage?: Usage): string; + /** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */ + appendCustomEntry(customType: string, data?: unknown): string; + /** Append a session info entry (e.g., display name). Returns entry id. */ + appendSessionInfo(name: string): string; + /** Get the current session name from the latest session_info entry, if any. */ + getSessionName(): string | undefined; + /** + * Append a custom message entry (for extensions) that participates in LLM context. + * @param customType Extension identifier for filtering on reload + * @param content Message content (string or TextContent/ImageContent array) + * @param display Whether to show in TUI (true = styled display, false = hidden) + * @param details Optional extension-specific metadata (not sent to LLM) + * @returns Entry id + */ + appendCustomMessageEntry(customType: string, content: string | (TextContent | ImageContent)[], display: boolean, details?: T): string; + getLeafId(): string | null; + getLeafEntry(): SessionEntry | undefined; + getEntry(id: string): SessionEntry | undefined; + /** + * Get all direct children of an entry. + */ + getChildren(parentId: string): SessionEntry[]; + /** + * Get the label for an entry, if any. + */ + getLabel(id: string): string | undefined; + /** + * Set or clear a label on an entry. + * Labels are user-defined markers for bookmarking/navigation. + * Pass undefined or empty string to clear the label. + */ + appendLabelChange(targetId: string, label: string | undefined): string; + /** + * Walk from entry to root, returning all entries in path order. + * Includes all entry types (messages, compaction, model changes, etc.). + * Use buildSessionContext() to get the resolved messages for the LLM. + */ + getBranch(fromId?: string): SessionEntry[]; + /** + * Build the active, compaction-aware entry list for context/rendering. + * Uses tree traversal from current leaf. + */ + buildContextEntries(): SessionEntry[]; + /** + * Build the session context (what gets sent to the LLM). + * Uses tree traversal from current leaf. + */ + buildSessionContext(): SessionContext; + /** + * Get session header. + */ + getHeader(): SessionHeader | null; + /** + * Get all session entries (excludes header). Returns a shallow copy. + * The session is append-only: use appendXXX() to add entries, branch() to + * change the leaf pointer. Entries cannot be modified or deleted. + */ + getEntries(): SessionEntry[]; + /** + * Get the session as a tree structure. Returns a shallow defensive copy of all entries. + * A well-formed session has exactly one root (first entry with parentId === null). + * Orphaned entries (broken parent chain) are also returned as roots. + */ + getTree(): SessionTreeNode[]; + /** + * Start a new branch from an earlier entry. + * Moves the leaf pointer to the specified entry. The next appendXXX() call + * will create a child of that entry, forming a new branch. Existing entries + * are not modified or deleted. + */ + branch(branchFromId: string): void; + /** + * Reset the leaf pointer to null (before any entries). + * The next appendXXX() call will create a new root entry (parentId = null). + * Use this when navigating to re-edit the first user message. + */ + resetLeaf(): void; + /** + * Start a new branch with a summary of the abandoned path. + * Same as branch(), but also appends a branch_summary entry that captures + * context from the abandoned conversation path. + */ + branchWithSummary(branchFromId: string | null, summary: string, details?: unknown, fromHook?: boolean, usage?: Usage): string; + /** + * Create a new session file containing only the path from root to the specified leaf. + * Useful for extracting a single conversation path from a branched session. + * Returns the new session file path, or undefined if not persisting. + */ + createBranchedSession(leafId: string): string | undefined; + /** + * Create a new session. + * @param cwd Working directory (stored in session header) + * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions//). + */ + static create(cwd: string, sessionDir?: string, options?: NewSessionOptions): SessionManager; + /** + * Open a specific session file. + * @param path Path to session file + * @param sessionDir Optional session directory for /new or /branch. If omitted, derives from file's parent. + * @param cwdOverride Optional cwd override instead of the session header cwd. + */ + static open(path: string, sessionDir?: string, cwdOverride?: string): SessionManager; + /** + * Continue the most recent session, or create new if none. + * @param cwd Working directory + * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions//). + */ + static continueRecent(cwd: string, sessionDir?: string): SessionManager; + /** Create an in-memory session (no file persistence) */ + static inMemory(cwd?: string, options?: NewSessionOptions): SessionManager; + /** + * Fork a session from another project directory into the current project. + * Creates a new session in the target cwd with the full history from the source session. + * @param sourcePath Path to the source session file + * @param targetCwd Target working directory (where the new session will be stored) + * @param sessionDir Optional session directory. If omitted, uses default for targetCwd. + */ + static forkFrom(sourcePath: string, targetCwd: string, sessionDir?: string, options?: NewSessionOptions): SessionManager; + /** + * List all sessions for a directory. + * @param cwd Working directory (used to compute default session directory) + * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions//). + * @param onProgress Optional callback for progress updates (loaded, total) + */ + static list(cwd: string, sessionDir?: string, onProgress?: SessionListProgress): Promise; + /** + * List all sessions across all project directories. + * @param onProgress Optional callback for progress updates (loaded, total) + */ + static listAll(onProgress?: SessionListProgress): Promise; + static listAll(sessionDir?: string, onProgress?: SessionListProgress): Promise; +} +//# sourceMappingURL=session-manager.d.ts.map \ No newline at end of file diff --git a/dist/core/session-manager.d.ts.map b/dist/core/session-manager.d.ts.map new file mode 100644 index 0000000..4c090e4 --- /dev/null +++ b/dist/core/session-manager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-manager.d.ts","sourceRoot":"","sources":["../../src/core/session-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAE,KAAK,YAAY,EAAE,KAAK,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,KAAK,EAAU,MAAM,uBAAuB,CAAC;AAoB9G,OAAO,EACN,KAAK,oBAAoB,EACzB,KAAK,aAAa,EAIlB,MAAM,eAAe,CAAC;AAEvB,eAAO,MAAM,uBAAuB,IAAI,CAAC;AAEzC,MAAM,WAAW,aAAa;IAC7B,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,iBAAiB;IACjC,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,SAAS,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,mBAAoB,SAAQ,gBAAgB;IAC5D,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,EAAE,YAAY,CAAC;CACtB;AAED,MAAM,WAAW,wBAAy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W,CAAC,EAAE,MAAM,GAAG,cAAc,CAoBnF;IAED;;;;OAIG;IACH,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,cAAc,CAQtE;IAED,wDAAwD;IACxD,MAAM,CAAC,QAAQ,CAAC,GAAG,GAAE,MAAsB,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,cAAc,CAExF;IAED;;;;;;OAMG;IACH,MAAM,CAAC,QAAQ,CACd,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,UAAU,CAAC,EAAE,MAAM,EACnB,OAAO,CAAC,EAAE,iBAAiB,GACzB,cAAc,CA8ChB;IAED;;;;;OAKG;IACH,OAAa,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAS5G;IAED;;;OAGG;IACH,OAAa,OAAO,CAAC,UAAU,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;IAC/E,OAAa,OAAO,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;CA0DpG","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { type ImageContent, type Message, type TextContent, type Usage, uuidv7 } from \"@earendil-works/pi-ai\";\nimport { randomUUID } from \"crypto\";\nimport {\n\tappendFileSync,\n\tcloseSync,\n\tcreateReadStream,\n\texistsSync,\n\tmkdirSync,\n\topenSync,\n\treaddirSync,\n\treadSync,\n\tstatSync,\n\twriteFileSync,\n} from \"fs\";\nimport { readdir, stat } from \"fs/promises\";\nimport { join, resolve } from \"path\";\nimport { createInterface } from \"readline\";\nimport { StringDecoder } from \"string_decoder\";\nimport { getAgentDir as getDefaultAgentDir, getSessionsDir } from \"../config.ts\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport {\n\ttype BashExecutionMessage,\n\ttype CustomMessage,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n} from \"./messages.ts\";\n\nexport const CURRENT_SESSION_VERSION = 3;\n\nexport interface SessionHeader {\n\ttype: \"session\";\n\tversion?: number; // v1 sessions don't have this\n\tid: string;\n\ttimestamp: string;\n\tcwd: string;\n\tparentSession?: string;\n}\n\nexport interface NewSessionOptions {\n\tid?: string;\n\tparentSession?: string;\n}\n\nexport interface SessionEntryBase {\n\ttype: string;\n\tid: string;\n\tparentId: string | null;\n\ttimestamp: string;\n}\n\nexport interface SessionMessageEntry extends SessionEntryBase {\n\ttype: \"message\";\n\tmessage: AgentMessage;\n}\n\nexport interface ThinkingLevelChangeEntry extends SessionEntryBase {\n\ttype: \"thinking_level_change\";\n\tthinkingLevel: string;\n}\n\nexport interface ModelChangeEntry extends SessionEntryBase {\n\ttype: \"model_change\";\n\tprovider: string;\n\tmodelId: string;\n}\n\nexport interface CompactionEntry extends SessionEntryBase {\n\ttype: \"compaction\";\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n\t/** Usage from the LLM call(s) that generated this summary, if available */\n\tusage?: Usage;\n\t/** True if generated by an extension, undefined/false if pi-generated (backward compatible) */\n\tfromHook?: boolean;\n}\n\nexport interface BranchSummaryEntry extends SessionEntryBase {\n\ttype: \"branch_summary\";\n\tfromId: string;\n\tsummary: string;\n\t/** Extension-specific data (not sent to LLM) */\n\tdetails?: T;\n\t/** Usage from the LLM call that generated this summary, if available */\n\tusage?: Usage;\n\t/** True if generated by an extension, false if pi-generated */\n\tfromHook?: boolean;\n}\n\n/**\n * Custom entry for extensions to store extension-specific data in the session.\n * Use customType to identify your extension's entries.\n *\n * Purpose: Persist extension state across session reloads. On reload, extensions can\n * scan entries for their customType and reconstruct internal state.\n *\n * Does NOT participate in LLM context (ignored by buildSessionContext).\n * For injecting content into context, see CustomMessageEntry.\n */\nexport interface CustomEntry extends SessionEntryBase {\n\ttype: \"custom\";\n\tcustomType: string;\n\tdata?: T;\n}\n\n/** Label entry for user-defined bookmarks/markers on entries. */\nexport interface LabelEntry extends SessionEntryBase {\n\ttype: \"label\";\n\ttargetId: string;\n\tlabel: string | undefined;\n}\n\n/** Session metadata entry (e.g., user-defined display name). */\nexport interface SessionInfoEntry extends SessionEntryBase {\n\ttype: \"session_info\";\n\tname?: string;\n}\n\n/**\n * Custom message entry for extensions to inject messages into LLM context.\n * Use customType to identify your extension's entries.\n *\n * Unlike CustomEntry, this DOES participate in LLM context.\n * The content is converted to a user message in buildSessionContext().\n * Use details for extension-specific metadata (not sent to LLM).\n *\n * display controls TUI rendering:\n * - false: hidden entirely\n * - true: rendered with distinct styling (different from user messages)\n */\nexport interface CustomMessageEntry extends SessionEntryBase {\n\ttype: \"custom_message\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdetails?: T;\n\tdisplay: boolean;\n}\n\n/** Session entry - has id/parentId for tree structure (returned by \"read\" methods in SessionManager) */\nexport type SessionEntry =\n\t| SessionMessageEntry\n\t| ThinkingLevelChangeEntry\n\t| ModelChangeEntry\n\t| CompactionEntry\n\t| BranchSummaryEntry\n\t| CustomEntry\n\t| CustomMessageEntry\n\t| LabelEntry\n\t| SessionInfoEntry;\n\n/** Raw file entry (includes header) */\nexport type FileEntry = SessionHeader | SessionEntry;\n\n/** Tree node for getTree() - defensive copy of session structure */\nexport interface SessionTreeNode {\n\tentry: SessionEntry;\n\tchildren: SessionTreeNode[];\n\t/** Resolved label for this entry, if any */\n\tlabel?: string;\n\t/** Timestamp of the latest label change for this entry, if any */\n\tlabelTimestamp?: string;\n}\n\nexport interface SessionContext {\n\tmessages: AgentMessage[];\n\tthinkingLevel: string;\n\tmodel: { provider: string; modelId: string } | null;\n}\n\nexport interface SessionInfo {\n\tpath: string;\n\tid: string;\n\t/** Working directory where the session was started. Empty string for old sessions. */\n\tcwd: string;\n\t/** User-defined display name from session_info entries. */\n\tname?: string;\n\t/** Path to the parent session (if this session was forked). */\n\tparentSessionPath?: string;\n\tcreated: Date;\n\tmodified: Date;\n\tmessageCount: number;\n\tfirstMessage: string;\n\tallMessagesText: string;\n}\n\nexport type ReadonlySessionManager = Pick<\n\tSessionManager,\n\t| \"getCwd\"\n\t| \"getSessionDir\"\n\t| \"getSessionId\"\n\t| \"getSessionFile\"\n\t| \"getLeafId\"\n\t| \"getLeafEntry\"\n\t| \"getEntry\"\n\t| \"getLabel\"\n\t| \"getBranch\"\n\t| \"buildContextEntries\"\n\t| \"getHeader\"\n\t| \"getEntries\"\n\t| \"getTree\"\n\t| \"getSessionName\"\n>;\n\nfunction createSessionId(): string {\n\treturn uuidv7();\n}\n\nexport function assertValidSessionId(id: string): void {\n\tif (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id)) {\n\t\tthrow new Error(\n\t\t\t\"Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character\",\n\t\t);\n\t}\n}\n\n/** Generate a unique short ID (8 hex chars, collision-checked) */\nfunction generateId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\tconst id = randomUUID().slice(0, 8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\t// Fallback to full UUID if somehow we have collisions\n\treturn randomUUID();\n}\n\n/** Migrate v1 → v2: add id/parentId tree structure. Mutates in place. */\nfunction migrateV1ToV2(entries: FileEntry[]): void {\n\tconst ids = new Set();\n\tlet prevId: string | null = null;\n\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"session\") {\n\t\t\tentry.version = 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\tentry.id = generateId(ids);\n\t\tentry.parentId = prevId;\n\t\tprevId = entry.id;\n\n\t\t// Convert firstKeptEntryIndex to firstKeptEntryId for compaction\n\t\tif (entry.type === \"compaction\") {\n\t\t\tconst comp = entry as CompactionEntry & { firstKeptEntryIndex?: number };\n\t\t\tif (typeof comp.firstKeptEntryIndex === \"number\") {\n\t\t\t\tconst targetEntry = entries[comp.firstKeptEntryIndex];\n\t\t\t\tif (targetEntry && targetEntry.type !== \"session\") {\n\t\t\t\t\tcomp.firstKeptEntryId = targetEntry.id;\n\t\t\t\t}\n\t\t\t\tdelete comp.firstKeptEntryIndex;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Migrate v2 → v3: rename hookMessage role to custom. Mutates in place. */\nfunction migrateV2ToV3(entries: FileEntry[]): void {\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"session\") {\n\t\t\tentry.version = 3;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Update message entries with hookMessage role\n\t\tif (entry.type === \"message\") {\n\t\t\tconst msgEntry = entry as SessionMessageEntry;\n\t\t\tif (msgEntry.message && (msgEntry.message as { role: string }).role === \"hookMessage\") {\n\t\t\t\t(msgEntry.message as { role: string }).role = \"custom\";\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Run all necessary migrations to bring entries to current version.\n * Mutates entries in place. Returns true if any migration was applied.\n */\nfunction migrateToCurrentVersion(entries: FileEntry[]): boolean {\n\tconst header = entries.find((e) => e.type === \"session\") as SessionHeader | undefined;\n\tconst version = header?.version ?? 1;\n\n\tif (version >= CURRENT_SESSION_VERSION) return false;\n\n\tif (version < 2) migrateV1ToV2(entries);\n\tif (version < 3) migrateV2ToV3(entries);\n\n\treturn true;\n}\n\n/** Exported for testing */\nexport function migrateSessionEntries(entries: FileEntry[]): void {\n\tmigrateToCurrentVersion(entries);\n}\n\n/** Exported for compaction.test.ts */\nexport function parseSessionEntries(content: string): FileEntry[] {\n\tconst entries: FileEntry[] = [];\n\tconst lines = content.trim().split(\"\\n\");\n\n\tfor (const line of lines) {\n\t\tif (!line.trim()) continue;\n\t\ttry {\n\t\t\tconst entry = JSON.parse(line) as FileEntry;\n\t\t\tentries.push(entry);\n\t\t} catch {\n\t\t\t// Skip malformed lines\n\t\t}\n\t}\n\n\treturn entries;\n}\n\nexport function getLatestCompactionEntry(entries: SessionEntry[]): CompactionEntry | null {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tif (entries[i].type === \"compaction\") {\n\t\t\treturn entries[i] as CompactionEntry;\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction buildEntryIndex(entries: SessionEntry[], byId?: Map): Map {\n\tif (byId) return byId;\n\tconst index = new Map();\n\tfor (const entry of entries) {\n\t\tindex.set(entry.id, entry);\n\t}\n\treturn index;\n}\n\nfunction buildSessionPath(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map,\n): SessionEntry[] {\n\tconst index = buildEntryIndex(entries, byId);\n\tlet leaf: SessionEntry | undefined;\n\tif (leafId === null) {\n\t\treturn [];\n\t}\n\tif (leafId) {\n\t\tleaf = index.get(leafId);\n\t}\n\tleaf ??= entries[entries.length - 1];\n\tif (!leaf) {\n\t\treturn [];\n\t}\n\n\tconst path: SessionEntry[] = [];\n\tlet current: SessionEntry | undefined = leaf;\n\twhile (current) {\n\t\tpath.push(current);\n\t\tcurrent = current.parentId ? index.get(current.parentId) : undefined;\n\t}\n\tpath.reverse();\n\treturn path;\n}\n\nfunction getSessionContextSettings(path: SessionEntry[]): Pick {\n\tlet thinkingLevel = \"off\";\n\tlet model: { provider: string; modelId: string } | null = null;\n\n\tfor (const entry of path) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tmodel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t}\n\t}\n\n\treturn { thinkingLevel, model };\n}\n\n/**\n * Project one selected session entry into LLM/runtime messages.\n * Plain custom entries are display/state entries and do not participate in context.\n */\nexport function sessionEntryToContextMessages(entry: SessionEntry): AgentMessage[] {\n\tif (entry.type === \"message\") {\n\t\tconst message = entry.message;\n\t\t// Session files are parsed without validation; old versions, forks, or\n\t\t// hand-edited files can contain messages with null/missing content.\n\t\tif (\n\t\t\t(message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\") &&\n\t\t\tmessage.content == null\n\t\t) {\n\t\t\treturn [{ ...message, content: [] }];\n\t\t}\n\t\treturn [message];\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn [\n\t\t\tcreateCustomMessage(entry.customType, entry.content ?? [], entry.display, entry.details, entry.timestamp),\n\t\t];\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary) {\n\t\treturn [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)];\n\t}\n\tif (entry.type === \"compaction\") {\n\t\treturn [createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp)];\n\t}\n\treturn [];\n}\n\n/**\n * Build the active, compaction-aware session entry list.\n *\n * This follows the current leaf path. If the path contains compaction entries,\n * the latest compaction is represented by the compaction entry itself, followed\n * by the kept entries starting at firstKeptEntryId and all entries after the\n * compaction entry. Older summarized entries are omitted.\n */\nexport function buildContextEntries(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map,\n): SessionEntry[] {\n\tconst path = buildSessionPath(entries, leafId, byId);\n\tlet compaction: CompactionEntry | null = null;\n\n\tfor (const entry of path) {\n\t\tif (entry.type === \"compaction\") {\n\t\t\tcompaction = entry;\n\t\t}\n\t}\n\n\tif (!compaction) {\n\t\treturn path;\n\t}\n\n\tconst compactionIdx = path.findIndex((entry) => entry.id === compaction.id);\n\tif (compactionIdx < 0) {\n\t\treturn path;\n\t}\n\n\tconst contextEntries: SessionEntry[] = [compaction];\n\tlet foundFirstKept = false;\n\tfor (let i = 0; i < compactionIdx; i++) {\n\t\tconst entry = path[i];\n\t\tif (entry.id === compaction.firstKeptEntryId) {\n\t\t\tfoundFirstKept = true;\n\t\t}\n\t\tif (foundFirstKept) {\n\t\t\tcontextEntries.push(entry);\n\t\t}\n\t}\n\tcontextEntries.push(...path.slice(compactionIdx + 1));\n\treturn contextEntries;\n}\n\n/**\n * Build the session context from entries using tree traversal.\n * If leafId is provided, walks from that entry to root.\n * Handles compaction and branch summaries along the path.\n */\nexport function buildSessionContext(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map,\n): SessionContext {\n\tconst path = buildSessionPath(entries, leafId, byId);\n\tconst { thinkingLevel, model } = getSessionContextSettings(path);\n\tconst messages = buildContextEntries(entries, leafId, byId).flatMap(sessionEntryToContextMessages);\n\treturn { messages, thinkingLevel, model };\n}\n\n/**\n * Compute the default session directory for a cwd.\n * Encodes cwd into a safe directory name under ~/.pi/agent/sessions/.\n */\nfunction getDefaultSessionDirPath(cwd: string, agentDir: string = getDefaultAgentDir()): string {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir);\n\tconst safePath = `--${resolvedCwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n\treturn join(resolvedAgentDir, \"sessions\", safePath);\n}\n\nexport function getDefaultSessionDir(cwd: string, agentDir: string = getDefaultAgentDir()): string {\n\tconst sessionDir = getDefaultSessionDirPath(cwd, agentDir);\n\tif (!existsSync(sessionDir)) {\n\t\tmkdirSync(sessionDir, { recursive: true });\n\t}\n\treturn sessionDir;\n}\n\nconst SESSION_READ_BUFFER_SIZE = 1024 * 1024;\nconst SESSION_HEADER_READ_BUFFER_SIZE = 4096;\n/** Bound synchronous header discovery while allowing large cwd and custom metadata fields. */\nconst MAX_SESSION_HEADER_SCAN_BYTES = 1024 * 1024;\n\nclass SessionHeaderScanLimitError extends Error {\n\tconstructor(filePath: string) {\n\t\tsuper(`Session header exceeds ${MAX_SESSION_HEADER_SCAN_BYTES}-byte scan limit: ${filePath}`);\n\t\tthis.name = \"SessionHeaderScanLimitError\";\n\t}\n}\n\nfunction parseSessionEntryLine(line: string): FileEntry | null {\n\tif (!line.trim()) return null;\n\ttry {\n\t\treturn JSON.parse(line) as FileEntry;\n\t} catch {\n\t\t// Skip malformed lines\n\t\treturn null;\n\t}\n}\n\n/** Exported for testing */\nexport function loadEntriesFromFile(filePath: string): FileEntry[] {\n\tconst resolvedFilePath = normalizePath(filePath);\n\tif (!existsSync(resolvedFilePath)) return [];\n\n\tconst entries: FileEntry[] = [];\n\tconst fd = openSync(resolvedFilePath, \"r\");\n\ttry {\n\t\tconst decoder = new StringDecoder(\"utf8\");\n\t\tconst buffer = Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE);\n\t\tlet pending = \"\";\n\n\t\twhile (true) {\n\t\t\tconst bytesRead = readSync(fd, buffer, 0, buffer.length, null);\n\t\t\tif (bytesRead === 0) break;\n\n\t\t\tpending += decoder.write(buffer.subarray(0, bytesRead));\n\t\t\tlet lineStart = 0;\n\t\t\tlet newlineIndex = pending.indexOf(\"\\n\", lineStart);\n\t\t\twhile (newlineIndex !== -1) {\n\t\t\t\tconst entry = parseSessionEntryLine(pending.slice(lineStart, newlineIndex));\n\t\t\t\tif (entry) entries.push(entry);\n\t\t\t\tlineStart = newlineIndex + 1;\n\t\t\t\tnewlineIndex = pending.indexOf(\"\\n\", lineStart);\n\t\t\t}\n\t\t\tpending = pending.slice(lineStart);\n\t\t}\n\n\t\tpending += decoder.end();\n\t\tconst finalEntry = parseSessionEntryLine(pending);\n\t\tif (finalEntry) entries.push(finalEntry);\n\t} finally {\n\t\tcloseSync(fd);\n\t}\n\n\t// Validate session header\n\tif (entries.length === 0) return entries;\n\tconst header = entries[0];\n\tif (header.type !== \"session\" || typeof (header as { id?: unknown }).id !== \"string\") {\n\t\treturn [];\n\t}\n\n\treturn entries;\n}\n\n/**\n * Inspect a physical line while searching for the first parsed session entry.\n * Blank and malformed lines are skipped to match loadEntriesFromFile().\n * Returns undefined to keep scanning, null for a parsed non-header entry, or the header.\n */\nfunction parseSessionHeaderCandidate(line: string): SessionHeader | null | undefined {\n\tif (!line.trim()) return undefined;\n\tconst entry = parseSessionEntryLine(line);\n\tif (!entry) return undefined;\n\tif (entry.type !== \"session\" || typeof (entry as { id?: unknown }).id !== \"string\") return null;\n\treturn entry;\n}\n\nfunction readSessionHeader(filePath: string): SessionHeader | null {\n\tconst fd = openSync(filePath, \"r\");\n\ttry {\n\t\tconst decoder = new StringDecoder(\"utf8\");\n\t\tconst buffer = Buffer.allocUnsafe(SESSION_HEADER_READ_BUFFER_SIZE);\n\t\tconst lineChunks: string[] = [];\n\t\tlet scannedBytes = 0;\n\n\t\twhile (scannedBytes < MAX_SESSION_HEADER_SCAN_BYTES) {\n\t\t\tconst readLength = Math.min(buffer.length, MAX_SESSION_HEADER_SCAN_BYTES - scannedBytes);\n\t\t\tconst bytesRead = readSync(fd, buffer, 0, readLength, null);\n\t\t\tif (bytesRead === 0) {\n\t\t\t\tlineChunks.push(decoder.end());\n\t\t\t\treturn parseSessionHeaderCandidate(lineChunks.join(\"\")) ?? null;\n\t\t\t}\n\t\t\tscannedBytes += bytesRead;\n\n\t\t\tconst chunk = decoder.write(buffer.subarray(0, bytesRead));\n\t\t\tlet lineStart = 0;\n\t\t\tlet newlineIndex = chunk.indexOf(\"\\n\", lineStart);\n\t\t\twhile (newlineIndex !== -1) {\n\t\t\t\tlineChunks.push(chunk.slice(lineStart, newlineIndex));\n\t\t\t\tconst header = parseSessionHeaderCandidate(lineChunks.join(\"\"));\n\t\t\t\tif (header !== undefined) return header;\n\t\t\t\tlineChunks.length = 0;\n\t\t\t\tlineStart = newlineIndex + 1;\n\t\t\t\tnewlineIndex = chunk.indexOf(\"\\n\", lineStart);\n\t\t\t}\n\t\t\tlineChunks.push(chunk.slice(lineStart));\n\t\t}\n\n\t\t// Probe for EOF so a final header without a newline is allowed when it ends\n\t\t// exactly at the scan limit. Any additional byte exceeds the bounded scan.\n\t\tconst probe = Buffer.allocUnsafe(1);\n\t\tif (readSync(fd, probe, 0, probe.length, null) === 0) {\n\t\t\tlineChunks.push(decoder.end());\n\t\t\treturn parseSessionHeaderCandidate(lineChunks.join(\"\")) ?? null;\n\t\t}\n\t\tthrow new SessionHeaderScanLimitError(filePath);\n\t} finally {\n\t\tcloseSync(fd);\n\t}\n}\n\nfunction readSessionHeaderForDiscovery(filePath: string): SessionHeader | null {\n\ttry {\n\t\treturn readSessionHeader(filePath);\n\t} catch {\n\t\t// Discovery is best-effort: unreadable or oversized files are not sessions,\n\t\t// and one corrupt file must not prevent other sessions from being found.\n\t\treturn null;\n\t}\n}\n\nfunction getSessionHeaderCwd(header: SessionHeader): string | undefined {\n\tconst cwd = (header as { cwd?: unknown }).cwd;\n\treturn typeof cwd === \"string\" ? cwd : undefined;\n}\n\nfunction sessionCwdMatches(cwd: string | undefined, resolvedCwd: string): boolean {\n\treturn cwd !== undefined && cwd !== \"\" && resolvePath(cwd) === resolvedCwd;\n}\n\n/** Exported for testing */\nexport function findMostRecentSession(sessionDir: string, cwd?: string): string | null {\n\tconst resolvedSessionDir = normalizePath(sessionDir);\n\tconst resolvedCwd = cwd ? resolvePath(cwd) : undefined;\n\ttry {\n\t\tconst files = readdirSync(resolvedSessionDir)\n\t\t\t.filter((f) => f.endsWith(\".jsonl\"))\n\t\t\t.map((f) => join(resolvedSessionDir, f))\n\t\t\t.map((path) => ({ path, header: readSessionHeaderForDiscovery(path) }))\n\t\t\t.filter(\n\t\t\t\t(file): file is { path: string; header: SessionHeader } =>\n\t\t\t\t\tfile.header !== null &&\n\t\t\t\t\t(!resolvedCwd || sessionCwdMatches(getSessionHeaderCwd(file.header), resolvedCwd)),\n\t\t\t)\n\t\t\t.map(({ path }) => ({ path, mtime: statSync(path).mtime }))\n\t\t\t.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());\n\n\t\treturn files[0]?.path || null;\n\t} catch {\n\t\t// Directory access and stat races make recent-session discovery unavailable.\n\t\treturn null;\n\t}\n}\n\nfunction isMessageWithContent(message: AgentMessage): message is Message {\n\treturn typeof (message as Message).role === \"string\" && \"content\" in message;\n}\n\nfunction extractTextContent(message: Message): string {\n\tconst content = message.content;\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\treturn content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\" \");\n}\n\nfunction getMessageActivityTime(entry: SessionMessageEntry): number | undefined {\n\tconst message = entry.message;\n\tif (!isMessageWithContent(message)) return undefined;\n\tif (message.role !== \"user\" && message.role !== \"assistant\") return undefined;\n\n\tconst msgTimestamp = (message as { timestamp?: number }).timestamp;\n\tif (typeof msgTimestamp === \"number\") {\n\t\treturn msgTimestamp;\n\t}\n\n\tconst t = new Date(entry.timestamp).getTime();\n\treturn Number.isNaN(t) ? undefined : t;\n}\n\nasync function buildSessionInfo(filePath: string): Promise {\n\ttry {\n\t\tconst stats = await stat(filePath);\n\t\tlet header: SessionHeader | null = null;\n\t\tlet messageCount = 0;\n\t\tlet firstMessage = \"\";\n\t\tconst allMessages: string[] = [];\n\t\tlet name: string | undefined;\n\t\tlet lastActivityTime: number | undefined;\n\n\t\tconst rl = createInterface({\n\t\t\tinput: createReadStream(filePath, { encoding: \"utf8\" }),\n\t\t\tcrlfDelay: Infinity,\n\t\t});\n\n\t\tfor await (const line of rl) {\n\t\t\tconst entry = parseSessionEntryLine(line);\n\t\t\tif (!entry) continue;\n\n\t\t\tif (!header) {\n\t\t\t\tif (entry.type !== \"session\") return null;\n\t\t\t\theader = entry;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Extract session name (use latest, including explicit clears)\n\t\t\tif (entry.type === \"session_info\") {\n\t\t\t\tname = entry.name?.trim() || undefined;\n\t\t\t}\n\n\t\t\tif (entry.type !== \"message\") continue;\n\t\t\tmessageCount++;\n\n\t\t\tconst activityTime = getMessageActivityTime(entry);\n\t\t\tif (typeof activityTime === \"number\") {\n\t\t\t\tlastActivityTime = Math.max(lastActivityTime ?? 0, activityTime);\n\t\t\t}\n\n\t\t\tconst message = entry.message;\n\t\t\tif (!isMessageWithContent(message)) continue;\n\t\t\tif (message.role !== \"user\" && message.role !== \"assistant\") continue;\n\n\t\t\tconst textContent = extractTextContent(message);\n\t\t\tif (!textContent) continue;\n\n\t\t\tallMessages.push(textContent);\n\t\t\tif (!firstMessage && message.role === \"user\") {\n\t\t\t\tfirstMessage = textContent;\n\t\t\t}\n\t\t}\n\n\t\tif (!header) return null;\n\n\t\tconst cwd = typeof header.cwd === \"string\" ? header.cwd : \"\";\n\t\tconst parentSessionPath = header.parentSession;\n\t\tconst headerTime = typeof header.timestamp === \"string\" ? new Date(header.timestamp).getTime() : NaN;\n\t\tconst modified =\n\t\t\ttypeof lastActivityTime === \"number\" && lastActivityTime > 0\n\t\t\t\t? new Date(lastActivityTime)\n\t\t\t\t: !Number.isNaN(headerTime)\n\t\t\t\t\t? new Date(headerTime)\n\t\t\t\t\t: stats.mtime;\n\n\t\treturn {\n\t\t\tpath: filePath,\n\t\t\tid: header.id,\n\t\t\tcwd,\n\t\t\tname,\n\t\t\tparentSessionPath,\n\t\t\tcreated: new Date(header.timestamp),\n\t\t\tmodified,\n\t\t\tmessageCount,\n\t\t\tfirstMessage: firstMessage || \"(no messages)\",\n\t\t\tallMessagesText: allMessages.join(\" \"),\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport type SessionListProgress = (loaded: number, total: number) => void;\n\nconst MAX_CONCURRENT_SESSION_INFO_LOADS = 10;\n\nasync function buildSessionInfosWithConcurrency(\n\tfiles: string[],\n\tonLoaded: () => void,\n): Promise<(SessionInfo | null)[]> {\n\tconst results: (SessionInfo | null)[] = new Array(files.length).fill(null);\n\tconst inFlight = new Set>();\n\tlet nextIndex = 0;\n\n\tconst startNext = (): void => {\n\t\tconst index = nextIndex++;\n\t\tconst file = files[index];\n\t\tif (!file) return;\n\n\t\tlet task: Promise;\n\t\ttask = buildSessionInfo(file)\n\t\t\t.then((info) => {\n\t\t\t\tresults[index] = info;\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\tresults[index] = null;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tinFlight.delete(task);\n\t\t\t\tonLoaded();\n\t\t\t});\n\t\tinFlight.add(task);\n\t};\n\n\twhile (nextIndex < files.length || inFlight.size > 0) {\n\t\twhile (nextIndex < files.length && inFlight.size < MAX_CONCURRENT_SESSION_INFO_LOADS) {\n\t\t\tstartNext();\n\t\t}\n\t\tif (inFlight.size > 0) {\n\t\t\tawait Promise.race(inFlight);\n\t\t}\n\t}\n\n\treturn results;\n}\n\nasync function listSessionsFromDir(\n\tdir: string,\n\tonProgress?: SessionListProgress,\n\tprogressOffset = 0,\n\tprogressTotal?: number,\n): Promise {\n\tconst sessions: SessionInfo[] = [];\n\tif (!existsSync(dir)) {\n\t\treturn sessions;\n\t}\n\n\ttry {\n\t\tconst dirEntries = await readdir(dir);\n\t\tconst files = dirEntries.filter((f) => f.endsWith(\".jsonl\")).map((f) => join(dir, f));\n\t\tconst total = progressTotal ?? files.length;\n\n\t\tlet loaded = 0;\n\t\tconst results = await buildSessionInfosWithConcurrency(files, () => {\n\t\t\tloaded++;\n\t\t\tonProgress?.(progressOffset + loaded, total);\n\t\t});\n\t\tfor (const info of results) {\n\t\t\tif (info) {\n\t\t\t\tsessions.push(info);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Return empty list on error\n\t}\n\n\treturn sessions;\n}\n\n/**\n * Manages conversation sessions as append-only trees stored in JSONL files.\n *\n * Each session entry has an id and parentId forming a tree structure. The \"leaf\"\n * pointer tracks the current position. Appending creates a child of the current leaf.\n * Branching moves the leaf to an earlier entry, allowing new branches without\n * modifying history.\n *\n * Use buildSessionContext() to get the resolved message list for the LLM, which\n * handles compaction summaries and follows the path from root to current leaf.\n */\nexport class SessionManager {\n\tprivate sessionId: string = \"\";\n\tprivate sessionFile: string | undefined;\n\tprivate sessionDir: string;\n\tprivate cwd: string;\n\tprivate persist: boolean;\n\tprivate flushed: boolean = false;\n\tprivate fileEntries: FileEntry[] = [];\n\tprivate byId: Map = new Map();\n\tprivate labelsById: Map = new Map();\n\tprivate labelTimestampsById: Map = new Map();\n\tprivate leafId: string | null = null;\n\n\tprivate constructor(\n\t\tcwd: string,\n\t\tsessionDir: string,\n\t\tsessionFile: string | undefined,\n\t\tpersist: boolean,\n\t\tnewSessionOptions?: NewSessionOptions,\n\t\tpreloadedFileEntries?: FileEntry[],\n\t) {\n\t\tthis.cwd = resolvePath(cwd);\n\t\tthis.sessionDir = normalizePath(sessionDir);\n\t\tthis.persist = persist;\n\t\tif (persist && this.sessionDir && !existsSync(this.sessionDir)) {\n\t\t\tmkdirSync(this.sessionDir, { recursive: true });\n\t\t}\n\n\t\tif (sessionFile) {\n\t\t\tthis._setSessionFile(sessionFile, preloadedFileEntries);\n\t\t} else {\n\t\t\tthis.newSession(newSessionOptions);\n\t\t}\n\t}\n\n\t/** Switch to a different session file (used for resume and branching) */\n\tsetSessionFile(sessionFile: string): void {\n\t\tthis._setSessionFile(sessionFile);\n\t}\n\n\tprivate _setSessionFile(sessionFile: string, preloadedFileEntries?: FileEntry[]): void {\n\t\tthis.sessionFile = resolvePath(sessionFile);\n\t\tif (existsSync(this.sessionFile)) {\n\t\t\tthis.fileEntries = preloadedFileEntries ?? loadEntriesFromFile(this.sessionFile);\n\n\t\t\t// If file was empty, initialize it with a valid session header. If it was\n\t\t\t// non-empty but did not parse as a pi session, fail without modifying it.\n\t\t\tif (this.fileEntries.length === 0) {\n\t\t\t\tconst explicitPath = this.sessionFile;\n\t\t\t\tif (statSync(explicitPath).size > 0) {\n\t\t\t\t\tthrow new Error(`Session file is not a valid pi session: ${explicitPath}`);\n\t\t\t\t}\n\t\t\t\tthis.newSession();\n\t\t\t\tthis.sessionFile = explicitPath;\n\t\t\t\tthis._rewriteFile();\n\t\t\t\tthis.flushed = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst header = this.fileEntries.find((e) => e.type === \"session\") as SessionHeader | undefined;\n\t\t\tthis.sessionId = header?.id ?? createSessionId();\n\n\t\t\tif (migrateToCurrentVersion(this.fileEntries)) {\n\t\t\t\tthis._rewriteFile();\n\t\t\t}\n\n\t\t\tthis._buildIndex();\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tconst explicitPath = this.sessionFile;\n\t\t\tthis.newSession();\n\t\t\tthis.sessionFile = explicitPath; // preserve explicit path from --session flag\n\t\t}\n\t}\n\n\tnewSession(options?: NewSessionOptions): string | undefined {\n\t\tif (options?.id !== undefined) {\n\t\t\tassertValidSessionId(options.id);\n\t\t}\n\t\tthis.sessionId = options?.id ?? createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: this.sessionId,\n\t\t\ttimestamp,\n\t\t\tcwd: this.cwd,\n\t\t\tparentSession: options?.parentSession,\n\t\t};\n\t\tthis.fileEntries = [header];\n\t\tthis.byId.clear();\n\t\tthis.labelsById.clear();\n\t\tthis.labelTimestampsById.clear();\n\t\tthis.leafId = null;\n\t\tthis.flushed = false;\n\n\t\tif (this.persist) {\n\t\t\tconst fileTimestamp = timestamp.replace(/[:.]/g, \"-\");\n\t\t\tthis.sessionFile = join(this.getSessionDir(), `${fileTimestamp}_${this.sessionId}.jsonl`);\n\t\t}\n\t\treturn this.sessionFile;\n\t}\n\n\tprivate _buildIndex(): void {\n\t\tthis.byId.clear();\n\t\tthis.labelsById.clear();\n\t\tthis.labelTimestampsById.clear();\n\t\tthis.leafId = null;\n\t\tfor (const entry of this.fileEntries) {\n\t\t\tif (entry.type === \"session\") continue;\n\t\t\tthis.byId.set(entry.id, entry);\n\t\t\tthis.leafId = entry.id;\n\t\t\tif (entry.type === \"label\") {\n\t\t\t\tif (entry.label) {\n\t\t\t\t\tthis.labelsById.set(entry.targetId, entry.label);\n\t\t\t\t\tthis.labelTimestampsById.set(entry.targetId, entry.timestamp);\n\t\t\t\t} else {\n\t\t\t\t\tthis.labelsById.delete(entry.targetId);\n\t\t\t\t\tthis.labelTimestampsById.delete(entry.targetId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _rewriteFile(): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\t\tconst fd = openSync(this.sessionFile, \"w\");\n\t\ttry {\n\t\t\tfor (const entry of this.fileEntries) {\n\t\t\t\twriteFileSync(fd, `${JSON.stringify(entry)}\\n`);\n\t\t\t}\n\t\t} finally {\n\t\t\tcloseSync(fd);\n\t\t}\n\t}\n\n\tisPersisted(): boolean {\n\t\treturn this.persist;\n\t}\n\n\tgetCwd(): string {\n\t\treturn this.cwd;\n\t}\n\n\tgetSessionDir(): string {\n\t\treturn this.sessionDir;\n\t}\n\n\tusesDefaultSessionDir(): boolean {\n\t\treturn this.sessionDir === getDefaultSessionDirPath(this.cwd);\n\t}\n\n\tgetSessionId(): string {\n\t\treturn this.sessionId;\n\t}\n\n\tgetSessionFile(): string | undefined {\n\t\treturn this.sessionFile;\n\t}\n\n\t_persist(entry: SessionEntry): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\n\t\tconst hasAssistant = this.fileEntries.some((e) => e.type === \"message\" && e.message.role === \"assistant\");\n\t\tif (!hasAssistant) {\n\t\t\tif (this.flushed) {\n\t\t\t\tappendFileSync(this.sessionFile, `${JSON.stringify(entry)}\\n`);\n\t\t\t} else {\n\t\t\t\t// Mark as not flushed so when assistant arrives, all entries get written\n\t\t\t\tthis.flushed = false;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.flushed) {\n\t\t\tconst fd = openSync(this.sessionFile, \"wx\");\n\t\t\ttry {\n\t\t\t\tfor (const e of this.fileEntries) {\n\t\t\t\t\twriteFileSync(fd, `${JSON.stringify(e)}\\n`);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tcloseSync(fd);\n\t\t\t}\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tappendFileSync(this.sessionFile, `${JSON.stringify(entry)}\\n`);\n\t\t}\n\t}\n\n\tprivate _appendEntry(entry: SessionEntry): void {\n\t\tthis.fileEntries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.leafId = entry.id;\n\t\tthis._persist(entry);\n\t}\n\n\t/** Append a message as child of current leaf, then advance leaf. Returns entry id.\n\t * Does not allow writing CompactionSummaryMessage and BranchSummaryMessage directly.\n\t * Reason: we want these to be top-level entries in the session, not message session entries,\n\t * so it is easier to find them.\n\t * These need to be appended via appendCompaction() and appendBranchSummary() methods.\n\t */\n\tappendMessage(message: Message | CustomMessage | BashExecutionMessage): string {\n\t\tconst entry: SessionMessageEntry = {\n\t\t\ttype: \"message\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tmessage,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendThinkingLevelChange(thinkingLevel: string): string {\n\t\tconst entry: ThinkingLevelChangeEntry = {\n\t\t\ttype: \"thinking_level_change\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tthinkingLevel,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a model change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendModelChange(provider: string, modelId: string): string {\n\t\tconst entry: ModelChangeEntry = {\n\t\t\ttype: \"model_change\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tprovider,\n\t\t\tmodelId,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCompaction(\n\t\tsummary: string,\n\t\tfirstKeptEntryId: string,\n\t\ttokensBefore: number,\n\t\tdetails?: T,\n\t\tfromHook?: boolean,\n\t\tusage?: Usage,\n\t): string {\n\t\tconst entry: CompactionEntry = {\n\t\t\ttype: \"compaction\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tsummary,\n\t\t\tfirstKeptEntryId,\n\t\t\ttokensBefore,\n\t\t\tdetails,\n\t\t\tusage,\n\t\t\tfromHook,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCustomEntry(customType: string, data?: unknown): string {\n\t\tconst entry: CustomEntry = {\n\t\t\ttype: \"custom\",\n\t\t\tcustomType,\n\t\t\tdata,\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a session info entry (e.g., display name). Returns entry id. */\n\tappendSessionInfo(name: string): string {\n\t\tconst sanitizedName = name.replace(/[\\r\\n]+/g, \" \").trim();\n\t\tconst entry: SessionInfoEntry = {\n\t\t\ttype: \"session_info\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tname: sanitizedName,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Get the current session name from the latest session_info entry, if any. */\n\tgetSessionName(): string | undefined {\n\t\t// Walk entries in reverse to find the latest session_info entry.\n\t\t// Empty names explicitly clear the session title.\n\t\tconst entries = this.getEntries();\n\t\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\t\tconst entry = entries[i];\n\t\t\tif (entry.type === \"session_info\") {\n\t\t\t\treturn entry.name?.trim() || undefined;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Append a custom message entry (for extensions) that participates in LLM context.\n\t * @param customType Extension identifier for filtering on reload\n\t * @param content Message content (string or TextContent/ImageContent array)\n\t * @param display Whether to show in TUI (true = styled display, false = hidden)\n\t * @param details Optional extension-specific metadata (not sent to LLM)\n\t * @returns Entry id\n\t */\n\tappendCustomMessageEntry(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t): string {\n\t\tconst entry: CustomMessageEntry = {\n\t\t\ttype: \"custom_message\",\n\t\t\tcustomType,\n\t\t\tcontent,\n\t\t\tdisplay,\n\t\t\tdetails,\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t// =========================================================================\n\t// Tree Traversal\n\t// =========================================================================\n\n\tgetLeafId(): string | null {\n\t\treturn this.leafId;\n\t}\n\n\tgetLeafEntry(): SessionEntry | undefined {\n\t\treturn this.leafId ? this.byId.get(this.leafId) : undefined;\n\t}\n\n\tgetEntry(id: string): SessionEntry | undefined {\n\t\treturn this.byId.get(id);\n\t}\n\n\t/**\n\t * Get all direct children of an entry.\n\t */\n\tgetChildren(parentId: string): SessionEntry[] {\n\t\tconst children: SessionEntry[] = [];\n\t\tfor (const entry of this.byId.values()) {\n\t\t\tif (entry.parentId === parentId) {\n\t\t\t\tchildren.push(entry);\n\t\t\t}\n\t\t}\n\t\treturn children;\n\t}\n\n\t/**\n\t * Get the label for an entry, if any.\n\t */\n\tgetLabel(id: string): string | undefined {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\t/**\n\t * Set or clear a label on an entry.\n\t * Labels are user-defined markers for bookmarking/navigation.\n\t * Pass undefined or empty string to clear the label.\n\t */\n\tappendLabelChange(targetId: string, label: string | undefined): string {\n\t\tif (!this.byId.has(targetId)) {\n\t\t\tthrow new Error(`Entry ${targetId} not found`);\n\t\t}\n\t\tconst entry: LabelEntry = {\n\t\t\ttype: \"label\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId,\n\t\t\tlabel,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\tif (label) {\n\t\t\tthis.labelsById.set(targetId, label);\n\t\t\tthis.labelTimestampsById.set(targetId, entry.timestamp);\n\t\t} else {\n\t\t\tthis.labelsById.delete(targetId);\n\t\t\tthis.labelTimestampsById.delete(targetId);\n\t\t}\n\t\treturn entry.id;\n\t}\n\n\t/**\n\t * Walk from entry to root, returning all entries in path order.\n\t * Includes all entry types (messages, compaction, model changes, etc.).\n\t * Use buildSessionContext() to get the resolved messages for the LLM.\n\t */\n\tgetBranch(fromId?: string): SessionEntry[] {\n\t\tconst path: SessionEntry[] = [];\n\t\tconst startId = fromId ?? this.leafId;\n\t\tlet current = startId ? this.byId.get(startId) : undefined;\n\t\twhile (current) {\n\t\t\tpath.push(current);\n\t\t\tcurrent = current.parentId ? this.byId.get(current.parentId) : undefined;\n\t\t}\n\t\tpath.reverse();\n\t\treturn path;\n\t}\n\n\t/**\n\t * Build the active, compaction-aware entry list for context/rendering.\n\t * Uses tree traversal from current leaf.\n\t */\n\tbuildContextEntries(): SessionEntry[] {\n\t\treturn buildContextEntries(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/**\n\t * Build the session context (what gets sent to the LLM).\n\t * Uses tree traversal from current leaf.\n\t */\n\tbuildSessionContext(): SessionContext {\n\t\treturn buildSessionContext(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/**\n\t * Get session header.\n\t */\n\tgetHeader(): SessionHeader | null {\n\t\tconst h = this.fileEntries.find((e) => e.type === \"session\");\n\t\treturn h ? (h as SessionHeader) : null;\n\t}\n\n\t/**\n\t * Get all session entries (excludes header). Returns a shallow copy.\n\t * The session is append-only: use appendXXX() to add entries, branch() to\n\t * change the leaf pointer. Entries cannot be modified or deleted.\n\t */\n\tgetEntries(): SessionEntry[] {\n\t\treturn this.fileEntries.filter((e): e is SessionEntry => e.type !== \"session\");\n\t}\n\n\t/**\n\t * Get the session as a tree structure. Returns a shallow defensive copy of all entries.\n\t * A well-formed session has exactly one root (first entry with parentId === null).\n\t * Orphaned entries (broken parent chain) are also returned as roots.\n\t */\n\tgetTree(): SessionTreeNode[] {\n\t\tconst entries = this.getEntries();\n\t\tconst nodeMap = new Map();\n\t\tconst roots: SessionTreeNode[] = [];\n\n\t\t// Create nodes with resolved labels\n\t\tfor (const entry of entries) {\n\t\t\tconst label = this.labelsById.get(entry.id);\n\t\t\tconst labelTimestamp = this.labelTimestampsById.get(entry.id);\n\t\t\tnodeMap.set(entry.id, { entry, children: [], label, labelTimestamp });\n\t\t}\n\n\t\t// Build tree\n\t\tfor (const entry of entries) {\n\t\t\tconst node = nodeMap.get(entry.id)!;\n\t\t\tif (entry.parentId === null || entry.parentId === entry.id) {\n\t\t\t\troots.push(node);\n\t\t\t} else {\n\t\t\t\tconst parent = nodeMap.get(entry.parentId);\n\t\t\t\tif (parent) {\n\t\t\t\t\tparent.children.push(node);\n\t\t\t\t} else {\n\t\t\t\t\t// Orphan - treat as root\n\t\t\t\t\troots.push(node);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Sort children by timestamp (oldest first, newest at bottom)\n\t\t// Use iterative approach to avoid stack overflow on deep trees\n\t\tconst stack: SessionTreeNode[] = [...roots];\n\t\twhile (stack.length > 0) {\n\t\t\tconst node = stack.pop()!;\n\t\t\tnode.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime());\n\t\t\tstack.push(...node.children);\n\t\t}\n\n\t\treturn roots;\n\t}\n\n\t// =========================================================================\n\t// Branching\n\t// =========================================================================\n\n\t/**\n\t * Start a new branch from an earlier entry.\n\t * Moves the leaf pointer to the specified entry. The next appendXXX() call\n\t * will create a child of that entry, forming a new branch. Existing entries\n\t * are not modified or deleted.\n\t */\n\tbranch(branchFromId: string): void {\n\t\tif (!this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t}\n\n\t/**\n\t * Reset the leaf pointer to null (before any entries).\n\t * The next appendXXX() call will create a new root entry (parentId = null).\n\t * Use this when navigating to re-edit the first user message.\n\t */\n\tresetLeaf(): void {\n\t\tthis.leafId = null;\n\t}\n\n\t/**\n\t * Start a new branch with a summary of the abandoned path.\n\t * Same as branch(), but also appends a branch_summary entry that captures\n\t * context from the abandoned conversation path.\n\t */\n\tbranchWithSummary(\n\t\tbranchFromId: string | null,\n\t\tsummary: string,\n\t\tdetails?: unknown,\n\t\tfromHook?: boolean,\n\t\tusage?: Usage,\n\t): string {\n\t\tif (branchFromId !== null && !this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t\tconst entry: BranchSummaryEntry = {\n\t\t\ttype: \"branch_summary\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: branchFromId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tfromId: branchFromId ?? \"root\",\n\t\t\tsummary,\n\t\t\tdetails,\n\t\t\tusage,\n\t\t\tfromHook,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/**\n\t * Create a new session file containing only the path from root to the specified leaf.\n\t * Useful for extracting a single conversation path from a branched session.\n\t * Returns the new session file path, or undefined if not persisting.\n\t */\n\tcreateBranchedSession(leafId: string): string | undefined {\n\t\tconst previousSessionFile = this.sessionFile;\n\t\tconst path = this.getBranch(leafId);\n\t\tif (path.length === 0) {\n\t\t\tthrow new Error(`Entry ${leafId} not found`);\n\t\t}\n\n\t\t// Filter out LabelEntry from path - we'll recreate them from the resolved map.\n\t\t// Because labels are real tree entries, later entries can be children of labels;\n\t\t// removing labels requires re-chaining the retained path to avoid orphaned subtrees.\n\t\tconst pathWithoutLabels: SessionEntry[] = [];\n\t\tlet pathParentId: string | null = null;\n\t\tfor (const entry of path) {\n\t\t\tif (entry.type === \"label\") continue;\n\t\t\tpathWithoutLabels.push({ ...entry, parentId: pathParentId });\n\t\t\tpathParentId = entry.id;\n\t\t}\n\n\t\tconst newSessionId = createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst fileTimestamp = timestamp.replace(/[:.]/g, \"-\");\n\t\tconst newSessionFile = join(this.getSessionDir(), `${fileTimestamp}_${newSessionId}.jsonl`);\n\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: newSessionId,\n\t\t\ttimestamp,\n\t\t\tcwd: this.cwd,\n\t\t\tparentSession: this.persist ? previousSessionFile : undefined,\n\t\t};\n\n\t\t// Collect labels for entries in the path\n\t\tconst pathEntryIds = new Set(pathWithoutLabels.map((e) => e.id));\n\t\tconst labelsToWrite: Array<{ targetId: string; label: string; timestamp: string }> = [];\n\t\tfor (const [targetId, label] of this.labelsById) {\n\t\t\tif (pathEntryIds.has(targetId)) {\n\t\t\t\tlabelsToWrite.push({ targetId, label, timestamp: this.labelTimestampsById.get(targetId)! });\n\t\t\t}\n\t\t}\n\n\t\tif (this.persist) {\n\t\t\t// Build label entries\n\t\t\tconst lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;\n\t\t\tlet parentId = lastEntryId;\n\t\t\tconst labelEntries: LabelEntry[] = [];\n\t\t\tfor (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {\n\t\t\t\tconst labelEntry: LabelEntry = {\n\t\t\t\t\ttype: \"label\",\n\t\t\t\t\tid: generateId(new Set(pathEntryIds)),\n\t\t\t\t\tparentId,\n\t\t\t\t\ttimestamp: labelTimestamp,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tlabel,\n\t\t\t\t};\n\t\t\t\tpathEntryIds.add(labelEntry.id);\n\t\t\t\tlabelEntries.push(labelEntry);\n\t\t\t\tparentId = labelEntry.id;\n\t\t\t}\n\n\t\t\tthis.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];\n\t\t\tthis.sessionId = newSessionId;\n\t\t\tthis.sessionFile = newSessionFile;\n\t\t\tthis._buildIndex();\n\n\t\t\t// Only write the file now if it contains an assistant message.\n\t\t\t// Otherwise defer to _persist(), which creates the file on the\n\t\t\t// first assistant response, matching the newSession() contract\n\t\t\t// and avoiding the duplicate-header bug when _persist()'s\n\t\t\t// no-assistant guard later resets flushed to false.\n\t\t\tconst hasAssistant = this.fileEntries.some((e) => e.type === \"message\" && e.message.role === \"assistant\");\n\t\t\tif (hasAssistant) {\n\t\t\t\tthis._rewriteFile();\n\t\t\t\tthis.flushed = true;\n\t\t\t} else {\n\t\t\t\tthis.flushed = false;\n\t\t\t}\n\n\t\t\treturn newSessionFile;\n\t\t}\n\n\t\t// In-memory mode: replace current session with the path + labels\n\t\tconst labelEntries: LabelEntry[] = [];\n\t\tlet parentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;\n\t\tfor (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {\n\t\t\tconst labelEntry: LabelEntry = {\n\t\t\t\ttype: \"label\",\n\t\t\t\tid: generateId(new Set([...pathEntryIds, ...labelEntries.map((e) => e.id)])),\n\t\t\t\tparentId,\n\t\t\t\ttimestamp: labelTimestamp,\n\t\t\t\ttargetId,\n\t\t\t\tlabel,\n\t\t\t};\n\t\t\tlabelEntries.push(labelEntry);\n\t\t\tparentId = labelEntry.id;\n\t\t}\n\t\tthis.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];\n\t\tthis.sessionId = newSessionId;\n\t\tthis._buildIndex();\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Create a new session.\n\t * @param cwd Working directory (stored in session header)\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions//).\n\t */\n\tstatic create(cwd: string, sessionDir?: string, options?: NewSessionOptions): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\treturn new SessionManager(cwd, dir, undefined, true, options);\n\t}\n\n\t/**\n\t * Open a specific session file.\n\t * @param path Path to session file\n\t * @param sessionDir Optional session directory for /new or /branch. If omitted, derives from file's parent.\n\t * @param cwdOverride Optional cwd override instead of the session header cwd.\n\t */\n\tstatic open(path: string, sessionDir?: string, cwdOverride?: string): SessionManager {\n\t\tconst resolvedPath = resolvePath(path);\n\t\tlet header: SessionHeader | null = null;\n\t\tlet preloadedFileEntries: FileEntry[] | undefined;\n\t\tif (cwdOverride === undefined && existsSync(resolvedPath)) {\n\t\t\ttry {\n\t\t\t\theader = readSessionHeader(resolvedPath);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof SessionHeaderScanLimitError)) throw error;\n\t\t\t\t// The bounded scan is only a discovery optimization. A full load remains\n\t\t\t\t// authoritative for legacy files with very large headers or prefixes.\n\t\t\t\tpreloadedFileEntries = loadEntriesFromFile(resolvedPath);\n\t\t\t\tconst firstEntry = preloadedFileEntries[0];\n\t\t\t\theader = firstEntry?.type === \"session\" ? firstEntry : null;\n\t\t\t}\n\t\t}\n\t\tconst cwd = cwdOverride ?? (header ? getSessionHeaderCwd(header) : undefined) ?? process.cwd();\n\t\t// If no sessionDir provided, derive from file's parent directory\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, \"..\");\n\t\treturn new SessionManager(cwd, dir, resolvedPath, true, undefined, preloadedFileEntries);\n\t}\n\n\t/**\n\t * Continue the most recent session, or create new if none.\n\t * @param cwd Working directory\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions//).\n\t */\n\tstatic continueRecent(cwd: string, sessionDir?: string): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst mostRecent = findMostRecentSession(dir, filterCwd ? cwd : undefined);\n\t\tif (mostRecent) {\n\t\t\treturn new SessionManager(cwd, dir, mostRecent, true);\n\t\t}\n\t\treturn new SessionManager(cwd, dir, undefined, true);\n\t}\n\n\t/** Create an in-memory session (no file persistence) */\n\tstatic inMemory(cwd: string = process.cwd(), options?: NewSessionOptions): SessionManager {\n\t\treturn new SessionManager(cwd, \"\", undefined, false, options);\n\t}\n\n\t/**\n\t * Fork a session from another project directory into the current project.\n\t * Creates a new session in the target cwd with the full history from the source session.\n\t * @param sourcePath Path to the source session file\n\t * @param targetCwd Target working directory (where the new session will be stored)\n\t * @param sessionDir Optional session directory. If omitted, uses default for targetCwd.\n\t */\n\tstatic forkFrom(\n\t\tsourcePath: string,\n\t\ttargetCwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: NewSessionOptions,\n\t): SessionManager {\n\t\tconst resolvedSourcePath = resolvePath(sourcePath);\n\t\tconst resolvedTargetCwd = resolvePath(targetCwd);\n\t\tconst sourceEntries = loadEntriesFromFile(resolvedSourcePath);\n\t\tif (sourceEntries.length === 0) {\n\t\t\tthrow new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);\n\t\t}\n\n\t\tconst sourceHeader = sourceEntries.find((e) => e.type === \"session\") as SessionHeader | undefined;\n\t\tif (!sourceHeader) {\n\t\t\tthrow new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`);\n\t\t}\n\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(resolvedTargetCwd);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t}\n\n\t\t// Create new session file with new ID but forked content\n\t\tif (options?.id !== undefined) {\n\t\t\tassertValidSessionId(options.id);\n\t\t}\n\t\tconst newSessionId = options?.id ?? createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst fileTimestamp = timestamp.replace(/[:.]/g, \"-\");\n\t\tconst newSessionFile = join(dir, `${fileTimestamp}_${newSessionId}.jsonl`);\n\n\t\t// Write new header pointing to source as parent, with updated cwd\n\t\tconst newHeader: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: newSessionId,\n\t\t\ttimestamp,\n\t\t\tcwd: resolvedTargetCwd,\n\t\t\tparentSession: resolvedSourcePath,\n\t\t};\n\t\twriteFileSync(newSessionFile, `${JSON.stringify(newHeader)}\\n`, { flag: \"wx\" });\n\n\t\t// Copy all non-header entries from source\n\t\tfor (const entry of sourceEntries) {\n\t\t\tif (entry.type !== \"session\") {\n\t\t\t\tappendFileSync(newSessionFile, `${JSON.stringify(entry)}\\n`);\n\t\t\t}\n\t\t}\n\n\t\treturn new SessionManager(resolvedTargetCwd, dir, newSessionFile, true);\n\t}\n\n\t/**\n\t * List all sessions for a directory.\n\t * @param cwd Working directory (used to compute default session directory)\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions//).\n\t * @param onProgress Optional callback for progress updates (loaded, total)\n\t */\n\tstatic async list(cwd: string, sessionDir?: string, onProgress?: SessionListProgress): Promise {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst resolvedCwd = resolvePath(cwd);\n\t\tconst sessions = (await listSessionsFromDir(dir, onProgress)).filter(\n\t\t\t(session) => !filterCwd || sessionCwdMatches(session.cwd, resolvedCwd),\n\t\t);\n\t\tsessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());\n\t\treturn sessions;\n\t}\n\n\t/**\n\t * List all sessions across all project directories.\n\t * @param onProgress Optional callback for progress updates (loaded, total)\n\t */\n\tstatic async listAll(onProgress?: SessionListProgress): Promise;\n\tstatic async listAll(sessionDir?: string, onProgress?: SessionListProgress): Promise;\n\tstatic async listAll(\n\t\tsessionDirOrOnProgress?: string | SessionListProgress,\n\t\tonProgress?: SessionListProgress,\n\t): Promise {\n\t\tconst customSessionDir =\n\t\t\ttypeof sessionDirOrOnProgress === \"string\" ? normalizePath(sessionDirOrOnProgress) : undefined;\n\t\tconst progress = typeof sessionDirOrOnProgress === \"function\" ? sessionDirOrOnProgress : onProgress;\n\t\tif (customSessionDir) {\n\t\t\tconst sessions = await listSessionsFromDir(customSessionDir, progress);\n\t\t\tsessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());\n\t\t\treturn sessions;\n\t\t}\n\n\t\tconst sessionsDir = getSessionsDir();\n\n\t\ttry {\n\t\t\tif (!existsSync(sessionsDir)) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tconst entries = await readdir(sessionsDir, { withFileTypes: true });\n\t\t\tconst dirs = entries.filter((e) => e.isDirectory()).map((e) => join(sessionsDir, e.name));\n\n\t\t\t// Count total files first for accurate progress\n\t\t\tlet totalFiles = 0;\n\t\t\tconst dirFiles: string[][] = [];\n\t\t\tfor (const dir of dirs) {\n\t\t\t\ttry {\n\t\t\t\t\tconst files = (await readdir(dir)).filter((f) => f.endsWith(\".jsonl\"));\n\t\t\t\t\tdirFiles.push(files.map((f) => join(dir, f)));\n\t\t\t\t\ttotalFiles += files.length;\n\t\t\t\t} catch {\n\t\t\t\t\tdirFiles.push([]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Process all files with progress tracking\n\t\t\tlet loaded = 0;\n\t\t\tconst sessions: SessionInfo[] = [];\n\t\t\tconst allFiles = dirFiles.flat();\n\n\t\t\tconst results = await buildSessionInfosWithConcurrency(allFiles, () => {\n\t\t\t\tloaded++;\n\t\t\t\tprogress?.(loaded, totalFiles);\n\t\t\t});\n\n\t\t\tfor (const info of results) {\n\t\t\t\tif (info) {\n\t\t\t\t\tsessions.push(info);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());\n\t\t\treturn sessions;\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/session-manager.js b/dist/core/session-manager.js new file mode 100644 index 0000000..e535f0f --- /dev/null +++ b/dist/core/session-manager.js @@ -0,0 +1,1338 @@ +import { uuidv7 } from "@earendil-works/pi-ai"; +import { randomUUID } from "crypto"; +import { appendFileSync, closeSync, createReadStream, existsSync, mkdirSync, openSync, readdirSync, readSync, statSync, writeFileSync, } from "fs"; +import { readdir, stat } from "fs/promises"; +import { join, resolve } from "path"; +import { createInterface } from "readline"; +import { StringDecoder } from "string_decoder"; +import { getAgentDir as getDefaultAgentDir, getSessionsDir } from "../config.js"; +import { normalizePath, resolvePath } from "../utils/paths.js"; +import { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage, } from "./messages.js"; +export const CURRENT_SESSION_VERSION = 3; +function createSessionId() { + return uuidv7(); +} +export function assertValidSessionId(id) { + if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id)) { + throw new Error("Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character"); + } +} +/** Generate a unique short ID (8 hex chars, collision-checked) */ +function generateId(byId) { + for (let i = 0; i < 100; i++) { + const id = randomUUID().slice(0, 8); + if (!byId.has(id)) + return id; + } + // Fallback to full UUID if somehow we have collisions + return randomUUID(); +} +/** Migrate v1 → v2: add id/parentId tree structure. Mutates in place. */ +function migrateV1ToV2(entries) { + const ids = new Set(); + let prevId = null; + for (const entry of entries) { + if (entry.type === "session") { + entry.version = 2; + continue; + } + entry.id = generateId(ids); + entry.parentId = prevId; + prevId = entry.id; + // Convert firstKeptEntryIndex to firstKeptEntryId for compaction + if (entry.type === "compaction") { + const comp = entry; + if (typeof comp.firstKeptEntryIndex === "number") { + const targetEntry = entries[comp.firstKeptEntryIndex]; + if (targetEntry && targetEntry.type !== "session") { + comp.firstKeptEntryId = targetEntry.id; + } + delete comp.firstKeptEntryIndex; + } + } + } +} +/** Migrate v2 → v3: rename hookMessage role to custom. Mutates in place. */ +function migrateV2ToV3(entries) { + for (const entry of entries) { + if (entry.type === "session") { + entry.version = 3; + continue; + } + // Update message entries with hookMessage role + if (entry.type === "message") { + const msgEntry = entry; + if (msgEntry.message && msgEntry.message.role === "hookMessage") { + msgEntry.message.role = "custom"; + } + } + } +} +/** + * Run all necessary migrations to bring entries to current version. + * Mutates entries in place. Returns true if any migration was applied. + */ +function migrateToCurrentVersion(entries) { + const header = entries.find((e) => e.type === "session"); + const version = header?.version ?? 1; + if (version >= CURRENT_SESSION_VERSION) + return false; + if (version < 2) + migrateV1ToV2(entries); + if (version < 3) + migrateV2ToV3(entries); + return true; +} +/** Exported for testing */ +export function migrateSessionEntries(entries) { + migrateToCurrentVersion(entries); +} +/** Exported for compaction.test.ts */ +export function parseSessionEntries(content) { + const entries = []; + const lines = content.trim().split("\n"); + for (const line of lines) { + if (!line.trim()) + continue; + try { + const entry = JSON.parse(line); + entries.push(entry); + } + catch { + // Skip malformed lines + } + } + return entries; +} +export function getLatestCompactionEntry(entries) { + for (let i = entries.length - 1; i >= 0; i--) { + if (entries[i].type === "compaction") { + return entries[i]; + } + } + return null; +} +function buildEntryIndex(entries, byId) { + if (byId) + return byId; + const index = new Map(); + for (const entry of entries) { + index.set(entry.id, entry); + } + return index; +} +function buildSessionPath(entries, leafId, byId) { + const index = buildEntryIndex(entries, byId); + let leaf; + if (leafId === null) { + return []; + } + if (leafId) { + leaf = index.get(leafId); + } + leaf ??= entries[entries.length - 1]; + if (!leaf) { + return []; + } + const path = []; + let current = leaf; + while (current) { + path.push(current); + current = current.parentId ? index.get(current.parentId) : undefined; + } + path.reverse(); + return path; +} +function getSessionContextSettings(path) { + let thinkingLevel = "off"; + let model = null; + for (const entry of path) { + if (entry.type === "thinking_level_change") { + thinkingLevel = entry.thinkingLevel; + } + else if (entry.type === "model_change") { + model = { provider: entry.provider, modelId: entry.modelId }; + } + else if (entry.type === "message" && entry.message.role === "assistant") { + model = { provider: entry.message.provider, modelId: entry.message.model }; + } + } + return { thinkingLevel, model }; +} +/** + * Project one selected session entry into LLM/runtime messages. + * Plain custom entries are display/state entries and do not participate in context. + */ +export function sessionEntryToContextMessages(entry) { + if (entry.type === "message") { + const message = entry.message; + // Session files are parsed without validation; old versions, forks, or + // hand-edited files can contain messages with null/missing content. + if ((message.role === "user" || message.role === "assistant" || message.role === "toolResult") && + message.content == null) { + return [{ ...message, content: [] }]; + } + return [message]; + } + if (entry.type === "custom_message") { + return [ + createCustomMessage(entry.customType, entry.content ?? [], entry.display, entry.details, entry.timestamp), + ]; + } + if (entry.type === "branch_summary" && entry.summary) { + return [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)]; + } + if (entry.type === "compaction") { + return [createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp)]; + } + return []; +} +/** + * Build the active, compaction-aware session entry list. + * + * This follows the current leaf path. If the path contains compaction entries, + * the latest compaction is represented by the compaction entry itself, followed + * by the kept entries starting at firstKeptEntryId and all entries after the + * compaction entry. Older summarized entries are omitted. + */ +export function buildContextEntries(entries, leafId, byId) { + const path = buildSessionPath(entries, leafId, byId); + let compaction = null; + for (const entry of path) { + if (entry.type === "compaction") { + compaction = entry; + } + } + if (!compaction) { + return path; + } + const compactionIdx = path.findIndex((entry) => entry.id === compaction.id); + if (compactionIdx < 0) { + return path; + } + const contextEntries = [compaction]; + let foundFirstKept = false; + for (let i = 0; i < compactionIdx; i++) { + const entry = path[i]; + if (entry.id === compaction.firstKeptEntryId) { + foundFirstKept = true; + } + if (foundFirstKept) { + contextEntries.push(entry); + } + } + contextEntries.push(...path.slice(compactionIdx + 1)); + return contextEntries; +} +/** + * Build the session context from entries using tree traversal. + * If leafId is provided, walks from that entry to root. + * Handles compaction and branch summaries along the path. + */ +export function buildSessionContext(entries, leafId, byId) { + const path = buildSessionPath(entries, leafId, byId); + const { thinkingLevel, model } = getSessionContextSettings(path); + const messages = buildContextEntries(entries, leafId, byId).flatMap(sessionEntryToContextMessages); + return { messages, thinkingLevel, model }; +} +/** + * Compute the default session directory for a cwd. + * Encodes cwd into a safe directory name under ~/.pi/agent/sessions/. + */ +function getDefaultSessionDirPath(cwd, agentDir = getDefaultAgentDir()) { + const resolvedCwd = resolvePath(cwd); + const resolvedAgentDir = resolvePath(agentDir); + const safePath = `--${resolvedCwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`; + return join(resolvedAgentDir, "sessions", safePath); +} +export function getDefaultSessionDir(cwd, agentDir = getDefaultAgentDir()) { + const sessionDir = getDefaultSessionDirPath(cwd, agentDir); + if (!existsSync(sessionDir)) { + mkdirSync(sessionDir, { recursive: true }); + } + return sessionDir; +} +const SESSION_READ_BUFFER_SIZE = 1024 * 1024; +const SESSION_HEADER_READ_BUFFER_SIZE = 4096; +/** Bound synchronous header discovery while allowing large cwd and custom metadata fields. */ +const MAX_SESSION_HEADER_SCAN_BYTES = 1024 * 1024; +class SessionHeaderScanLimitError extends Error { + constructor(filePath) { + super(`Session header exceeds ${MAX_SESSION_HEADER_SCAN_BYTES}-byte scan limit: ${filePath}`); + this.name = "SessionHeaderScanLimitError"; + } +} +function parseSessionEntryLine(line) { + if (!line.trim()) + return null; + try { + return JSON.parse(line); + } + catch { + // Skip malformed lines + return null; + } +} +/** Exported for testing */ +export function loadEntriesFromFile(filePath) { + const resolvedFilePath = normalizePath(filePath); + if (!existsSync(resolvedFilePath)) + return []; + const entries = []; + const fd = openSync(resolvedFilePath, "r"); + try { + const decoder = new StringDecoder("utf8"); + const buffer = Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE); + let pending = ""; + while (true) { + const bytesRead = readSync(fd, buffer, 0, buffer.length, null); + if (bytesRead === 0) + break; + pending += decoder.write(buffer.subarray(0, bytesRead)); + let lineStart = 0; + let newlineIndex = pending.indexOf("\n", lineStart); + while (newlineIndex !== -1) { + const entry = parseSessionEntryLine(pending.slice(lineStart, newlineIndex)); + if (entry) + entries.push(entry); + lineStart = newlineIndex + 1; + newlineIndex = pending.indexOf("\n", lineStart); + } + pending = pending.slice(lineStart); + } + pending += decoder.end(); + const finalEntry = parseSessionEntryLine(pending); + if (finalEntry) + entries.push(finalEntry); + } + finally { + closeSync(fd); + } + // Validate session header + if (entries.length === 0) + return entries; + const header = entries[0]; + if (header.type !== "session" || typeof header.id !== "string") { + return []; + } + return entries; +} +/** + * Inspect a physical line while searching for the first parsed session entry. + * Blank and malformed lines are skipped to match loadEntriesFromFile(). + * Returns undefined to keep scanning, null for a parsed non-header entry, or the header. + */ +function parseSessionHeaderCandidate(line) { + if (!line.trim()) + return undefined; + const entry = parseSessionEntryLine(line); + if (!entry) + return undefined; + if (entry.type !== "session" || typeof entry.id !== "string") + return null; + return entry; +} +function readSessionHeader(filePath) { + const fd = openSync(filePath, "r"); + try { + const decoder = new StringDecoder("utf8"); + const buffer = Buffer.allocUnsafe(SESSION_HEADER_READ_BUFFER_SIZE); + const lineChunks = []; + let scannedBytes = 0; + while (scannedBytes < MAX_SESSION_HEADER_SCAN_BYTES) { + const readLength = Math.min(buffer.length, MAX_SESSION_HEADER_SCAN_BYTES - scannedBytes); + const bytesRead = readSync(fd, buffer, 0, readLength, null); + if (bytesRead === 0) { + lineChunks.push(decoder.end()); + return parseSessionHeaderCandidate(lineChunks.join("")) ?? null; + } + scannedBytes += bytesRead; + const chunk = decoder.write(buffer.subarray(0, bytesRead)); + let lineStart = 0; + let newlineIndex = chunk.indexOf("\n", lineStart); + while (newlineIndex !== -1) { + lineChunks.push(chunk.slice(lineStart, newlineIndex)); + const header = parseSessionHeaderCandidate(lineChunks.join("")); + if (header !== undefined) + return header; + lineChunks.length = 0; + lineStart = newlineIndex + 1; + newlineIndex = chunk.indexOf("\n", lineStart); + } + lineChunks.push(chunk.slice(lineStart)); + } + // Probe for EOF so a final header without a newline is allowed when it ends + // exactly at the scan limit. Any additional byte exceeds the bounded scan. + const probe = Buffer.allocUnsafe(1); + if (readSync(fd, probe, 0, probe.length, null) === 0) { + lineChunks.push(decoder.end()); + return parseSessionHeaderCandidate(lineChunks.join("")) ?? null; + } + throw new SessionHeaderScanLimitError(filePath); + } + finally { + closeSync(fd); + } +} +function readSessionHeaderForDiscovery(filePath) { + try { + return readSessionHeader(filePath); + } + catch { + // Discovery is best-effort: unreadable or oversized files are not sessions, + // and one corrupt file must not prevent other sessions from being found. + return null; + } +} +function getSessionHeaderCwd(header) { + const cwd = header.cwd; + return typeof cwd === "string" ? cwd : undefined; +} +function sessionCwdMatches(cwd, resolvedCwd) { + return cwd !== undefined && cwd !== "" && resolvePath(cwd) === resolvedCwd; +} +/** Exported for testing */ +export function findMostRecentSession(sessionDir, cwd) { + const resolvedSessionDir = normalizePath(sessionDir); + const resolvedCwd = cwd ? resolvePath(cwd) : undefined; + try { + const files = readdirSync(resolvedSessionDir) + .filter((f) => f.endsWith(".jsonl")) + .map((f) => join(resolvedSessionDir, f)) + .map((path) => ({ path, header: readSessionHeaderForDiscovery(path) })) + .filter((file) => file.header !== null && + (!resolvedCwd || sessionCwdMatches(getSessionHeaderCwd(file.header), resolvedCwd))) + .map(({ path }) => ({ path, mtime: statSync(path).mtime })) + .sort((a, b) => b.mtime.getTime() - a.mtime.getTime()); + return files[0]?.path || null; + } + catch { + // Directory access and stat races make recent-session discovery unavailable. + return null; + } +} +function isMessageWithContent(message) { + return typeof message.role === "string" && "content" in message; +} +function extractTextContent(message) { + const content = message.content; + if (typeof content === "string") { + return content; + } + return content + .filter((block) => block.type === "text") + .map((block) => block.text) + .join(" "); +} +function getMessageActivityTime(entry) { + const message = entry.message; + if (!isMessageWithContent(message)) + return undefined; + if (message.role !== "user" && message.role !== "assistant") + return undefined; + const msgTimestamp = message.timestamp; + if (typeof msgTimestamp === "number") { + return msgTimestamp; + } + const t = new Date(entry.timestamp).getTime(); + return Number.isNaN(t) ? undefined : t; +} +async function buildSessionInfo(filePath) { + try { + const stats = await stat(filePath); + let header = null; + let messageCount = 0; + let firstMessage = ""; + const allMessages = []; + let name; + let lastActivityTime; + const rl = createInterface({ + input: createReadStream(filePath, { encoding: "utf8" }), + crlfDelay: Infinity, + }); + for await (const line of rl) { + const entry = parseSessionEntryLine(line); + if (!entry) + continue; + if (!header) { + if (entry.type !== "session") + return null; + header = entry; + continue; + } + // Extract session name (use latest, including explicit clears) + if (entry.type === "session_info") { + name = entry.name?.trim() || undefined; + } + if (entry.type !== "message") + continue; + messageCount++; + const activityTime = getMessageActivityTime(entry); + if (typeof activityTime === "number") { + lastActivityTime = Math.max(lastActivityTime ?? 0, activityTime); + } + const message = entry.message; + if (!isMessageWithContent(message)) + continue; + if (message.role !== "user" && message.role !== "assistant") + continue; + const textContent = extractTextContent(message); + if (!textContent) + continue; + allMessages.push(textContent); + if (!firstMessage && message.role === "user") { + firstMessage = textContent; + } + } + if (!header) + return null; + const cwd = typeof header.cwd === "string" ? header.cwd : ""; + const parentSessionPath = header.parentSession; + const headerTime = typeof header.timestamp === "string" ? new Date(header.timestamp).getTime() : NaN; + const modified = typeof lastActivityTime === "number" && lastActivityTime > 0 + ? new Date(lastActivityTime) + : !Number.isNaN(headerTime) + ? new Date(headerTime) + : stats.mtime; + return { + path: filePath, + id: header.id, + cwd, + name, + parentSessionPath, + created: new Date(header.timestamp), + modified, + messageCount, + firstMessage: firstMessage || "(no messages)", + allMessagesText: allMessages.join(" "), + }; + } + catch { + return null; + } +} +const MAX_CONCURRENT_SESSION_INFO_LOADS = 10; +async function buildSessionInfosWithConcurrency(files, onLoaded) { + const results = new Array(files.length).fill(null); + const inFlight = new Set(); + let nextIndex = 0; + const startNext = () => { + const index = nextIndex++; + const file = files[index]; + if (!file) + return; + let task; + task = buildSessionInfo(file) + .then((info) => { + results[index] = info; + }) + .catch(() => { + results[index] = null; + }) + .finally(() => { + inFlight.delete(task); + onLoaded(); + }); + inFlight.add(task); + }; + while (nextIndex < files.length || inFlight.size > 0) { + while (nextIndex < files.length && inFlight.size < MAX_CONCURRENT_SESSION_INFO_LOADS) { + startNext(); + } + if (inFlight.size > 0) { + await Promise.race(inFlight); + } + } + return results; +} +async function listSessionsFromDir(dir, onProgress, progressOffset = 0, progressTotal) { + const sessions = []; + if (!existsSync(dir)) { + return sessions; + } + try { + const dirEntries = await readdir(dir); + const files = dirEntries.filter((f) => f.endsWith(".jsonl")).map((f) => join(dir, f)); + const total = progressTotal ?? files.length; + let loaded = 0; + const results = await buildSessionInfosWithConcurrency(files, () => { + loaded++; + onProgress?.(progressOffset + loaded, total); + }); + for (const info of results) { + if (info) { + sessions.push(info); + } + } + } + catch { + // Return empty list on error + } + return sessions; +} +/** + * Manages conversation sessions as append-only trees stored in JSONL files. + * + * Each session entry has an id and parentId forming a tree structure. The "leaf" + * pointer tracks the current position. Appending creates a child of the current leaf. + * Branching moves the leaf to an earlier entry, allowing new branches without + * modifying history. + * + * Use buildSessionContext() to get the resolved message list for the LLM, which + * handles compaction summaries and follows the path from root to current leaf. + */ +export class SessionManager { + sessionId = ""; + sessionFile; + sessionDir; + cwd; + persist; + flushed = false; + fileEntries = []; + byId = new Map(); + labelsById = new Map(); + labelTimestampsById = new Map(); + leafId = null; + constructor(cwd, sessionDir, sessionFile, persist, newSessionOptions, preloadedFileEntries) { + this.cwd = resolvePath(cwd); + this.sessionDir = normalizePath(sessionDir); + this.persist = persist; + if (persist && this.sessionDir && !existsSync(this.sessionDir)) { + mkdirSync(this.sessionDir, { recursive: true }); + } + if (sessionFile) { + this._setSessionFile(sessionFile, preloadedFileEntries); + } + else { + this.newSession(newSessionOptions); + } + } + /** Switch to a different session file (used for resume and branching) */ + setSessionFile(sessionFile) { + this._setSessionFile(sessionFile); + } + _setSessionFile(sessionFile, preloadedFileEntries) { + this.sessionFile = resolvePath(sessionFile); + if (existsSync(this.sessionFile)) { + this.fileEntries = preloadedFileEntries ?? loadEntriesFromFile(this.sessionFile); + // If file was empty, initialize it with a valid session header. If it was + // non-empty but did not parse as a pi session, fail without modifying it. + if (this.fileEntries.length === 0) { + const explicitPath = this.sessionFile; + if (statSync(explicitPath).size > 0) { + throw new Error(`Session file is not a valid pi session: ${explicitPath}`); + } + this.newSession(); + this.sessionFile = explicitPath; + this._rewriteFile(); + this.flushed = true; + return; + } + const header = this.fileEntries.find((e) => e.type === "session"); + this.sessionId = header?.id ?? createSessionId(); + if (migrateToCurrentVersion(this.fileEntries)) { + this._rewriteFile(); + } + this._buildIndex(); + this.flushed = true; + } + else { + const explicitPath = this.sessionFile; + this.newSession(); + this.sessionFile = explicitPath; // preserve explicit path from --session flag + } + } + newSession(options) { + if (options?.id !== undefined) { + assertValidSessionId(options.id); + } + this.sessionId = options?.id ?? createSessionId(); + const timestamp = new Date().toISOString(); + const header = { + type: "session", + version: CURRENT_SESSION_VERSION, + id: this.sessionId, + timestamp, + cwd: this.cwd, + parentSession: options?.parentSession, + }; + this.fileEntries = [header]; + this.byId.clear(); + this.labelsById.clear(); + this.labelTimestampsById.clear(); + this.leafId = null; + this.flushed = false; + if (this.persist) { + const fileTimestamp = timestamp.replace(/[:.]/g, "-"); + this.sessionFile = join(this.getSessionDir(), `${fileTimestamp}_${this.sessionId}.jsonl`); + } + return this.sessionFile; + } + _buildIndex() { + this.byId.clear(); + this.labelsById.clear(); + this.labelTimestampsById.clear(); + this.leafId = null; + for (const entry of this.fileEntries) { + if (entry.type === "session") + continue; + this.byId.set(entry.id, entry); + this.leafId = entry.id; + if (entry.type === "label") { + if (entry.label) { + this.labelsById.set(entry.targetId, entry.label); + this.labelTimestampsById.set(entry.targetId, entry.timestamp); + } + else { + this.labelsById.delete(entry.targetId); + this.labelTimestampsById.delete(entry.targetId); + } + } + } + } + _rewriteFile() { + if (!this.persist || !this.sessionFile) + return; + const fd = openSync(this.sessionFile, "w"); + try { + for (const entry of this.fileEntries) { + writeFileSync(fd, `${JSON.stringify(entry)}\n`); + } + } + finally { + closeSync(fd); + } + } + isPersisted() { + return this.persist; + } + getCwd() { + return this.cwd; + } + getSessionDir() { + return this.sessionDir; + } + usesDefaultSessionDir() { + return this.sessionDir === getDefaultSessionDirPath(this.cwd); + } + getSessionId() { + return this.sessionId; + } + getSessionFile() { + return this.sessionFile; + } + _persist(entry) { + if (!this.persist || !this.sessionFile) + return; + const hasAssistant = this.fileEntries.some((e) => e.type === "message" && e.message.role === "assistant"); + if (!hasAssistant) { + if (this.flushed) { + appendFileSync(this.sessionFile, `${JSON.stringify(entry)}\n`); + } + else { + // Mark as not flushed so when assistant arrives, all entries get written + this.flushed = false; + } + return; + } + if (!this.flushed) { + const fd = openSync(this.sessionFile, "wx"); + try { + for (const e of this.fileEntries) { + writeFileSync(fd, `${JSON.stringify(e)}\n`); + } + } + finally { + closeSync(fd); + } + this.flushed = true; + } + else { + appendFileSync(this.sessionFile, `${JSON.stringify(entry)}\n`); + } + } + _appendEntry(entry) { + this.fileEntries.push(entry); + this.byId.set(entry.id, entry); + this.leafId = entry.id; + this._persist(entry); + } + /** Append a message as child of current leaf, then advance leaf. Returns entry id. + * Does not allow writing CompactionSummaryMessage and BranchSummaryMessage directly. + * Reason: we want these to be top-level entries in the session, not message session entries, + * so it is easier to find them. + * These need to be appended via appendCompaction() and appendBranchSummary() methods. + */ + appendMessage(message) { + const entry = { + type: "message", + id: generateId(this.byId), + parentId: this.leafId, + timestamp: new Date().toISOString(), + message, + }; + this._appendEntry(entry); + return entry.id; + } + /** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */ + appendThinkingLevelChange(thinkingLevel) { + const entry = { + type: "thinking_level_change", + id: generateId(this.byId), + parentId: this.leafId, + timestamp: new Date().toISOString(), + thinkingLevel, + }; + this._appendEntry(entry); + return entry.id; + } + /** Append a model change as child of current leaf, then advance leaf. Returns entry id. */ + appendModelChange(provider, modelId) { + const entry = { + type: "model_change", + id: generateId(this.byId), + parentId: this.leafId, + timestamp: new Date().toISOString(), + provider, + modelId, + }; + this._appendEntry(entry); + return entry.id; + } + /** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */ + appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook, usage) { + const entry = { + type: "compaction", + id: generateId(this.byId), + parentId: this.leafId, + timestamp: new Date().toISOString(), + summary, + firstKeptEntryId, + tokensBefore, + details, + usage, + fromHook, + }; + this._appendEntry(entry); + return entry.id; + } + /** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */ + appendCustomEntry(customType, data) { + const entry = { + type: "custom", + customType, + data, + id: generateId(this.byId), + parentId: this.leafId, + timestamp: new Date().toISOString(), + }; + this._appendEntry(entry); + return entry.id; + } + /** Append a session info entry (e.g., display name). Returns entry id. */ + appendSessionInfo(name) { + const sanitizedName = name.replace(/[\r\n]+/g, " ").trim(); + const entry = { + type: "session_info", + id: generateId(this.byId), + parentId: this.leafId, + timestamp: new Date().toISOString(), + name: sanitizedName, + }; + this._appendEntry(entry); + return entry.id; + } + /** Get the current session name from the latest session_info entry, if any. */ + getSessionName() { + // Walk entries in reverse to find the latest session_info entry. + // Empty names explicitly clear the session title. + const entries = this.getEntries(); + for (let i = entries.length - 1; i >= 0; i--) { + const entry = entries[i]; + if (entry.type === "session_info") { + return entry.name?.trim() || undefined; + } + } + return undefined; + } + /** + * Append a custom message entry (for extensions) that participates in LLM context. + * @param customType Extension identifier for filtering on reload + * @param content Message content (string or TextContent/ImageContent array) + * @param display Whether to show in TUI (true = styled display, false = hidden) + * @param details Optional extension-specific metadata (not sent to LLM) + * @returns Entry id + */ + appendCustomMessageEntry(customType, content, display, details) { + const entry = { + type: "custom_message", + customType, + content, + display, + details, + id: generateId(this.byId), + parentId: this.leafId, + timestamp: new Date().toISOString(), + }; + this._appendEntry(entry); + return entry.id; + } + // ========================================================================= + // Tree Traversal + // ========================================================================= + getLeafId() { + return this.leafId; + } + getLeafEntry() { + return this.leafId ? this.byId.get(this.leafId) : undefined; + } + getEntry(id) { + return this.byId.get(id); + } + /** + * Get all direct children of an entry. + */ + getChildren(parentId) { + const children = []; + for (const entry of this.byId.values()) { + if (entry.parentId === parentId) { + children.push(entry); + } + } + return children; + } + /** + * Get the label for an entry, if any. + */ + getLabel(id) { + return this.labelsById.get(id); + } + /** + * Set or clear a label on an entry. + * Labels are user-defined markers for bookmarking/navigation. + * Pass undefined or empty string to clear the label. + */ + appendLabelChange(targetId, label) { + if (!this.byId.has(targetId)) { + throw new Error(`Entry ${targetId} not found`); + } + const entry = { + type: "label", + id: generateId(this.byId), + parentId: this.leafId, + timestamp: new Date().toISOString(), + targetId, + label, + }; + this._appendEntry(entry); + if (label) { + this.labelsById.set(targetId, label); + this.labelTimestampsById.set(targetId, entry.timestamp); + } + else { + this.labelsById.delete(targetId); + this.labelTimestampsById.delete(targetId); + } + return entry.id; + } + /** + * Walk from entry to root, returning all entries in path order. + * Includes all entry types (messages, compaction, model changes, etc.). + * Use buildSessionContext() to get the resolved messages for the LLM. + */ + getBranch(fromId) { + const path = []; + const startId = fromId ?? this.leafId; + let current = startId ? this.byId.get(startId) : undefined; + while (current) { + path.push(current); + current = current.parentId ? this.byId.get(current.parentId) : undefined; + } + path.reverse(); + return path; + } + /** + * Build the active, compaction-aware entry list for context/rendering. + * Uses tree traversal from current leaf. + */ + buildContextEntries() { + return buildContextEntries(this.getEntries(), this.leafId, this.byId); + } + /** + * Build the session context (what gets sent to the LLM). + * Uses tree traversal from current leaf. + */ + buildSessionContext() { + return buildSessionContext(this.getEntries(), this.leafId, this.byId); + } + /** + * Get session header. + */ + getHeader() { + const h = this.fileEntries.find((e) => e.type === "session"); + return h ? h : null; + } + /** + * Get all session entries (excludes header). Returns a shallow copy. + * The session is append-only: use appendXXX() to add entries, branch() to + * change the leaf pointer. Entries cannot be modified or deleted. + */ + getEntries() { + return this.fileEntries.filter((e) => e.type !== "session"); + } + /** + * Get the session as a tree structure. Returns a shallow defensive copy of all entries. + * A well-formed session has exactly one root (first entry with parentId === null). + * Orphaned entries (broken parent chain) are also returned as roots. + */ + getTree() { + const entries = this.getEntries(); + const nodeMap = new Map(); + const roots = []; + // Create nodes with resolved labels + for (const entry of entries) { + const label = this.labelsById.get(entry.id); + const labelTimestamp = this.labelTimestampsById.get(entry.id); + nodeMap.set(entry.id, { entry, children: [], label, labelTimestamp }); + } + // Build tree + for (const entry of entries) { + const node = nodeMap.get(entry.id); + if (entry.parentId === null || entry.parentId === entry.id) { + roots.push(node); + } + else { + const parent = nodeMap.get(entry.parentId); + if (parent) { + parent.children.push(node); + } + else { + // Orphan - treat as root + roots.push(node); + } + } + } + // Sort children by timestamp (oldest first, newest at bottom) + // Use iterative approach to avoid stack overflow on deep trees + const stack = [...roots]; + while (stack.length > 0) { + const node = stack.pop(); + node.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime()); + stack.push(...node.children); + } + return roots; + } + // ========================================================================= + // Branching + // ========================================================================= + /** + * Start a new branch from an earlier entry. + * Moves the leaf pointer to the specified entry. The next appendXXX() call + * will create a child of that entry, forming a new branch. Existing entries + * are not modified or deleted. + */ + branch(branchFromId) { + if (!this.byId.has(branchFromId)) { + throw new Error(`Entry ${branchFromId} not found`); + } + this.leafId = branchFromId; + } + /** + * Reset the leaf pointer to null (before any entries). + * The next appendXXX() call will create a new root entry (parentId = null). + * Use this when navigating to re-edit the first user message. + */ + resetLeaf() { + this.leafId = null; + } + /** + * Start a new branch with a summary of the abandoned path. + * Same as branch(), but also appends a branch_summary entry that captures + * context from the abandoned conversation path. + */ + branchWithSummary(branchFromId, summary, details, fromHook, usage) { + if (branchFromId !== null && !this.byId.has(branchFromId)) { + throw new Error(`Entry ${branchFromId} not found`); + } + this.leafId = branchFromId; + const entry = { + type: "branch_summary", + id: generateId(this.byId), + parentId: branchFromId, + timestamp: new Date().toISOString(), + fromId: branchFromId ?? "root", + summary, + details, + usage, + fromHook, + }; + this._appendEntry(entry); + return entry.id; + } + /** + * Create a new session file containing only the path from root to the specified leaf. + * Useful for extracting a single conversation path from a branched session. + * Returns the new session file path, or undefined if not persisting. + */ + createBranchedSession(leafId) { + const previousSessionFile = this.sessionFile; + const path = this.getBranch(leafId); + if (path.length === 0) { + throw new Error(`Entry ${leafId} not found`); + } + // Filter out LabelEntry from path - we'll recreate them from the resolved map. + // Because labels are real tree entries, later entries can be children of labels; + // removing labels requires re-chaining the retained path to avoid orphaned subtrees. + const pathWithoutLabels = []; + let pathParentId = null; + for (const entry of path) { + if (entry.type === "label") + continue; + pathWithoutLabels.push({ ...entry, parentId: pathParentId }); + pathParentId = entry.id; + } + const newSessionId = createSessionId(); + const timestamp = new Date().toISOString(); + const fileTimestamp = timestamp.replace(/[:.]/g, "-"); + const newSessionFile = join(this.getSessionDir(), `${fileTimestamp}_${newSessionId}.jsonl`); + const header = { + type: "session", + version: CURRENT_SESSION_VERSION, + id: newSessionId, + timestamp, + cwd: this.cwd, + parentSession: this.persist ? previousSessionFile : undefined, + }; + // Collect labels for entries in the path + const pathEntryIds = new Set(pathWithoutLabels.map((e) => e.id)); + const labelsToWrite = []; + for (const [targetId, label] of this.labelsById) { + if (pathEntryIds.has(targetId)) { + labelsToWrite.push({ targetId, label, timestamp: this.labelTimestampsById.get(targetId) }); + } + } + if (this.persist) { + // Build label entries + const lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null; + let parentId = lastEntryId; + const labelEntries = []; + for (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) { + const labelEntry = { + type: "label", + id: generateId(new Set(pathEntryIds)), + parentId, + timestamp: labelTimestamp, + targetId, + label, + }; + pathEntryIds.add(labelEntry.id); + labelEntries.push(labelEntry); + parentId = labelEntry.id; + } + this.fileEntries = [header, ...pathWithoutLabels, ...labelEntries]; + this.sessionId = newSessionId; + this.sessionFile = newSessionFile; + this._buildIndex(); + // Only write the file now if it contains an assistant message. + // Otherwise defer to _persist(), which creates the file on the + // first assistant response, matching the newSession() contract + // and avoiding the duplicate-header bug when _persist()'s + // no-assistant guard later resets flushed to false. + const hasAssistant = this.fileEntries.some((e) => e.type === "message" && e.message.role === "assistant"); + if (hasAssistant) { + this._rewriteFile(); + this.flushed = true; + } + else { + this.flushed = false; + } + return newSessionFile; + } + // In-memory mode: replace current session with the path + labels + const labelEntries = []; + let parentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null; + for (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) { + const labelEntry = { + type: "label", + id: generateId(new Set([...pathEntryIds, ...labelEntries.map((e) => e.id)])), + parentId, + timestamp: labelTimestamp, + targetId, + label, + }; + labelEntries.push(labelEntry); + parentId = labelEntry.id; + } + this.fileEntries = [header, ...pathWithoutLabels, ...labelEntries]; + this.sessionId = newSessionId; + this._buildIndex(); + return undefined; + } + /** + * Create a new session. + * @param cwd Working directory (stored in session header) + * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions//). + */ + static create(cwd, sessionDir, options) { + const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd); + return new SessionManager(cwd, dir, undefined, true, options); + } + /** + * Open a specific session file. + * @param path Path to session file + * @param sessionDir Optional session directory for /new or /branch. If omitted, derives from file's parent. + * @param cwdOverride Optional cwd override instead of the session header cwd. + */ + static open(path, sessionDir, cwdOverride) { + const resolvedPath = resolvePath(path); + let header = null; + let preloadedFileEntries; + if (cwdOverride === undefined && existsSync(resolvedPath)) { + try { + header = readSessionHeader(resolvedPath); + } + catch (error) { + if (!(error instanceof SessionHeaderScanLimitError)) + throw error; + // The bounded scan is only a discovery optimization. A full load remains + // authoritative for legacy files with very large headers or prefixes. + preloadedFileEntries = loadEntriesFromFile(resolvedPath); + const firstEntry = preloadedFileEntries[0]; + header = firstEntry?.type === "session" ? firstEntry : null; + } + } + const cwd = cwdOverride ?? (header ? getSessionHeaderCwd(header) : undefined) ?? process.cwd(); + // If no sessionDir provided, derive from file's parent directory + const dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, ".."); + return new SessionManager(cwd, dir, resolvedPath, true, undefined, preloadedFileEntries); + } + /** + * Continue the most recent session, or create new if none. + * @param cwd Working directory + * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions//). + */ + static continueRecent(cwd, sessionDir) { + const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd); + const filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd); + const mostRecent = findMostRecentSession(dir, filterCwd ? cwd : undefined); + if (mostRecent) { + return new SessionManager(cwd, dir, mostRecent, true); + } + return new SessionManager(cwd, dir, undefined, true); + } + /** Create an in-memory session (no file persistence) */ + static inMemory(cwd = process.cwd(), options) { + return new SessionManager(cwd, "", undefined, false, options); + } + /** + * Fork a session from another project directory into the current project. + * Creates a new session in the target cwd with the full history from the source session. + * @param sourcePath Path to the source session file + * @param targetCwd Target working directory (where the new session will be stored) + * @param sessionDir Optional session directory. If omitted, uses default for targetCwd. + */ + static forkFrom(sourcePath, targetCwd, sessionDir, options) { + const resolvedSourcePath = resolvePath(sourcePath); + const resolvedTargetCwd = resolvePath(targetCwd); + const sourceEntries = loadEntriesFromFile(resolvedSourcePath); + if (sourceEntries.length === 0) { + throw new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`); + } + const sourceHeader = sourceEntries.find((e) => e.type === "session"); + if (!sourceHeader) { + throw new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`); + } + const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(resolvedTargetCwd); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } + // Create new session file with new ID but forked content + if (options?.id !== undefined) { + assertValidSessionId(options.id); + } + const newSessionId = options?.id ?? createSessionId(); + const timestamp = new Date().toISOString(); + const fileTimestamp = timestamp.replace(/[:.]/g, "-"); + const newSessionFile = join(dir, `${fileTimestamp}_${newSessionId}.jsonl`); + // Write new header pointing to source as parent, with updated cwd + const newHeader = { + type: "session", + version: CURRENT_SESSION_VERSION, + id: newSessionId, + timestamp, + cwd: resolvedTargetCwd, + parentSession: resolvedSourcePath, + }; + writeFileSync(newSessionFile, `${JSON.stringify(newHeader)}\n`, { flag: "wx" }); + // Copy all non-header entries from source + for (const entry of sourceEntries) { + if (entry.type !== "session") { + appendFileSync(newSessionFile, `${JSON.stringify(entry)}\n`); + } + } + return new SessionManager(resolvedTargetCwd, dir, newSessionFile, true); + } + /** + * List all sessions for a directory. + * @param cwd Working directory (used to compute default session directory) + * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions//). + * @param onProgress Optional callback for progress updates (loaded, total) + */ + static async list(cwd, sessionDir, onProgress) { + const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd); + const filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd); + const resolvedCwd = resolvePath(cwd); + const sessions = (await listSessionsFromDir(dir, onProgress)).filter((session) => !filterCwd || sessionCwdMatches(session.cwd, resolvedCwd)); + sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime()); + return sessions; + } + static async listAll(sessionDirOrOnProgress, onProgress) { + const customSessionDir = typeof sessionDirOrOnProgress === "string" ? normalizePath(sessionDirOrOnProgress) : undefined; + const progress = typeof sessionDirOrOnProgress === "function" ? sessionDirOrOnProgress : onProgress; + if (customSessionDir) { + const sessions = await listSessionsFromDir(customSessionDir, progress); + sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime()); + return sessions; + } + const sessionsDir = getSessionsDir(); + try { + if (!existsSync(sessionsDir)) { + return []; + } + const entries = await readdir(sessionsDir, { withFileTypes: true }); + const dirs = entries.filter((e) => e.isDirectory()).map((e) => join(sessionsDir, e.name)); + // Count total files first for accurate progress + let totalFiles = 0; + const dirFiles = []; + for (const dir of dirs) { + try { + const files = (await readdir(dir)).filter((f) => f.endsWith(".jsonl")); + dirFiles.push(files.map((f) => join(dir, f))); + totalFiles += files.length; + } + catch { + dirFiles.push([]); + } + } + // Process all files with progress tracking + let loaded = 0; + const sessions = []; + const allFiles = dirFiles.flat(); + const results = await buildSessionInfosWithConcurrency(allFiles, () => { + loaded++; + progress?.(loaded, totalFiles); + }); + for (const info of results) { + if (info) { + sessions.push(info); + } + } + sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime()); + return sessions; + } + catch { + return []; + } + } +} +//# sourceMappingURL=session-manager.js.map \ No newline at end of file diff --git a/dist/core/session-manager.js.map b/dist/core/session-manager.js.map new file mode 100644 index 0000000..ecd8022 --- /dev/null +++ b/dist/core/session-manager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"session-manager.js","sourceRoot":"","sources":["../../src/core/session-manager.ts"],"names":[],"mappings":"AACA,OAAO,EAAiE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC9G,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EACN,cAAc,EACd,SAAS,EACT,gBAAgB,EAChB,UAAU,EACV,SAAS,EACT,QAAQ,EACR,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,aAAa,GACb,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,WAAW,IAAI,kBAAkB,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACjF,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAGN,0BAA0B,EAC1B,8BAA8B,EAC9B,mBAAmB,GACnB,MAAM,eAAe,CAAC;AAEvB,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AAkLzC,SAAS,eAAe,GAAW;IAClC,OAAO,MAAM,EAAE,CAAC;AAAA,CAChB;AAED,MAAM,UAAU,oBAAoB,CAAC,EAAU,EAAQ;IACtD,IAAI,CAAC,8CAA8C,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC;QAC9D,MAAM,IAAI,KAAK,CACd,yIAAyI,CACzI,CAAC;IACH,CAAC;AAAA,CACD;AAED,kEAAkE;AAClE,SAAS,UAAU,CAAC,IAAkC,EAAU;IAC/D,K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R,OAAO,EAAE,CAAC;QACX,CAAC;IAAA,CACD;CACD","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { type ImageContent, type Message, type TextContent, type Usage, uuidv7 } from \"@earendil-works/pi-ai\";\nimport { randomUUID } from \"crypto\";\nimport {\n\tappendFileSync,\n\tcloseSync,\n\tcreateReadStream,\n\texistsSync,\n\tmkdirSync,\n\topenSync,\n\treaddirSync,\n\treadSync,\n\tstatSync,\n\twriteFileSync,\n} from \"fs\";\nimport { readdir, stat } from \"fs/promises\";\nimport { join, resolve } from \"path\";\nimport { createInterface } from \"readline\";\nimport { StringDecoder } from \"string_decoder\";\nimport { getAgentDir as getDefaultAgentDir, getSessionsDir } from \"../config.ts\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport {\n\ttype BashExecutionMessage,\n\ttype CustomMessage,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n} from \"./messages.ts\";\n\nexport const CURRENT_SESSION_VERSION = 3;\n\nexport interface SessionHeader {\n\ttype: \"session\";\n\tversion?: number; // v1 sessions don't have this\n\tid: string;\n\ttimestamp: string;\n\tcwd: string;\n\tparentSession?: string;\n}\n\nexport interface NewSessionOptions {\n\tid?: string;\n\tparentSession?: string;\n}\n\nexport interface SessionEntryBase {\n\ttype: string;\n\tid: string;\n\tparentId: string | null;\n\ttimestamp: string;\n}\n\nexport interface SessionMessageEntry extends SessionEntryBase {\n\ttype: \"message\";\n\tmessage: AgentMessage;\n}\n\nexport interface ThinkingLevelChangeEntry extends SessionEntryBase {\n\ttype: \"thinking_level_change\";\n\tthinkingLevel: string;\n}\n\nexport interface ModelChangeEntry extends SessionEntryBase {\n\ttype: \"model_change\";\n\tprovider: string;\n\tmodelId: string;\n}\n\nexport interface CompactionEntry extends SessionEntryBase {\n\ttype: \"compaction\";\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\t/** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */\n\tdetails?: T;\n\t/** Usage from the LLM call(s) that generated this summary, if available */\n\tusage?: Usage;\n\t/** True if generated by an extension, undefined/false if pi-generated (backward compatible) */\n\tfromHook?: boolean;\n}\n\nexport interface BranchSummaryEntry extends SessionEntryBase {\n\ttype: \"branch_summary\";\n\tfromId: string;\n\tsummary: string;\n\t/** Extension-specific data (not sent to LLM) */\n\tdetails?: T;\n\t/** Usage from the LLM call that generated this summary, if available */\n\tusage?: Usage;\n\t/** True if generated by an extension, false if pi-generated */\n\tfromHook?: boolean;\n}\n\n/**\n * Custom entry for extensions to store extension-specific data in the session.\n * Use customType to identify your extension's entries.\n *\n * Purpose: Persist extension state across session reloads. On reload, extensions can\n * scan entries for their customType and reconstruct internal state.\n *\n * Does NOT participate in LLM context (ignored by buildSessionContext).\n * For injecting content into context, see CustomMessageEntry.\n */\nexport interface CustomEntry extends SessionEntryBase {\n\ttype: \"custom\";\n\tcustomType: string;\n\tdata?: T;\n}\n\n/** Label entry for user-defined bookmarks/markers on entries. */\nexport interface LabelEntry extends SessionEntryBase {\n\ttype: \"label\";\n\ttargetId: string;\n\tlabel: string | undefined;\n}\n\n/** Session metadata entry (e.g., user-defined display name). */\nexport interface SessionInfoEntry extends SessionEntryBase {\n\ttype: \"session_info\";\n\tname?: string;\n}\n\n/**\n * Custom message entry for extensions to inject messages into LLM context.\n * Use customType to identify your extension's entries.\n *\n * Unlike CustomEntry, this DOES participate in LLM context.\n * The content is converted to a user message in buildSessionContext().\n * Use details for extension-specific metadata (not sent to LLM).\n *\n * display controls TUI rendering:\n * - false: hidden entirely\n * - true: rendered with distinct styling (different from user messages)\n */\nexport interface CustomMessageEntry extends SessionEntryBase {\n\ttype: \"custom_message\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdetails?: T;\n\tdisplay: boolean;\n}\n\n/** Session entry - has id/parentId for tree structure (returned by \"read\" methods in SessionManager) */\nexport type SessionEntry =\n\t| SessionMessageEntry\n\t| ThinkingLevelChangeEntry\n\t| ModelChangeEntry\n\t| CompactionEntry\n\t| BranchSummaryEntry\n\t| CustomEntry\n\t| CustomMessageEntry\n\t| LabelEntry\n\t| SessionInfoEntry;\n\n/** Raw file entry (includes header) */\nexport type FileEntry = SessionHeader | SessionEntry;\n\n/** Tree node for getTree() - defensive copy of session structure */\nexport interface SessionTreeNode {\n\tentry: SessionEntry;\n\tchildren: SessionTreeNode[];\n\t/** Resolved label for this entry, if any */\n\tlabel?: string;\n\t/** Timestamp of the latest label change for this entry, if any */\n\tlabelTimestamp?: string;\n}\n\nexport interface SessionContext {\n\tmessages: AgentMessage[];\n\tthinkingLevel: string;\n\tmodel: { provider: string; modelId: string } | null;\n}\n\nexport interface SessionInfo {\n\tpath: string;\n\tid: string;\n\t/** Working directory where the session was started. Empty string for old sessions. */\n\tcwd: string;\n\t/** User-defined display name from session_info entries. */\n\tname?: string;\n\t/** Path to the parent session (if this session was forked). */\n\tparentSessionPath?: string;\n\tcreated: Date;\n\tmodified: Date;\n\tmessageCount: number;\n\tfirstMessage: string;\n\tallMessagesText: string;\n}\n\nexport type ReadonlySessionManager = Pick<\n\tSessionManager,\n\t| \"getCwd\"\n\t| \"getSessionDir\"\n\t| \"getSessionId\"\n\t| \"getSessionFile\"\n\t| \"getLeafId\"\n\t| \"getLeafEntry\"\n\t| \"getEntry\"\n\t| \"getLabel\"\n\t| \"getBranch\"\n\t| \"buildContextEntries\"\n\t| \"getHeader\"\n\t| \"getEntries\"\n\t| \"getTree\"\n\t| \"getSessionName\"\n>;\n\nfunction createSessionId(): string {\n\treturn uuidv7();\n}\n\nexport function assertValidSessionId(id: string): void {\n\tif (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id)) {\n\t\tthrow new Error(\n\t\t\t\"Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character\",\n\t\t);\n\t}\n}\n\n/** Generate a unique short ID (8 hex chars, collision-checked) */\nfunction generateId(byId: { has(id: string): boolean }): string {\n\tfor (let i = 0; i < 100; i++) {\n\t\tconst id = randomUUID().slice(0, 8);\n\t\tif (!byId.has(id)) return id;\n\t}\n\t// Fallback to full UUID if somehow we have collisions\n\treturn randomUUID();\n}\n\n/** Migrate v1 → v2: add id/parentId tree structure. Mutates in place. */\nfunction migrateV1ToV2(entries: FileEntry[]): void {\n\tconst ids = new Set();\n\tlet prevId: string | null = null;\n\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"session\") {\n\t\t\tentry.version = 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\tentry.id = generateId(ids);\n\t\tentry.parentId = prevId;\n\t\tprevId = entry.id;\n\n\t\t// Convert firstKeptEntryIndex to firstKeptEntryId for compaction\n\t\tif (entry.type === \"compaction\") {\n\t\t\tconst comp = entry as CompactionEntry & { firstKeptEntryIndex?: number };\n\t\t\tif (typeof comp.firstKeptEntryIndex === \"number\") {\n\t\t\t\tconst targetEntry = entries[comp.firstKeptEntryIndex];\n\t\t\t\tif (targetEntry && targetEntry.type !== \"session\") {\n\t\t\t\t\tcomp.firstKeptEntryId = targetEntry.id;\n\t\t\t\t}\n\t\t\t\tdelete comp.firstKeptEntryIndex;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Migrate v2 → v3: rename hookMessage role to custom. Mutates in place. */\nfunction migrateV2ToV3(entries: FileEntry[]): void {\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"session\") {\n\t\t\tentry.version = 3;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Update message entries with hookMessage role\n\t\tif (entry.type === \"message\") {\n\t\t\tconst msgEntry = entry as SessionMessageEntry;\n\t\t\tif (msgEntry.message && (msgEntry.message as { role: string }).role === \"hookMessage\") {\n\t\t\t\t(msgEntry.message as { role: string }).role = \"custom\";\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Run all necessary migrations to bring entries to current version.\n * Mutates entries in place. Returns true if any migration was applied.\n */\nfunction migrateToCurrentVersion(entries: FileEntry[]): boolean {\n\tconst header = entries.find((e) => e.type === \"session\") as SessionHeader | undefined;\n\tconst version = header?.version ?? 1;\n\n\tif (version >= CURRENT_SESSION_VERSION) return false;\n\n\tif (version < 2) migrateV1ToV2(entries);\n\tif (version < 3) migrateV2ToV3(entries);\n\n\treturn true;\n}\n\n/** Exported for testing */\nexport function migrateSessionEntries(entries: FileEntry[]): void {\n\tmigrateToCurrentVersion(entries);\n}\n\n/** Exported for compaction.test.ts */\nexport function parseSessionEntries(content: string): FileEntry[] {\n\tconst entries: FileEntry[] = [];\n\tconst lines = content.trim().split(\"\\n\");\n\n\tfor (const line of lines) {\n\t\tif (!line.trim()) continue;\n\t\ttry {\n\t\t\tconst entry = JSON.parse(line) as FileEntry;\n\t\t\tentries.push(entry);\n\t\t} catch {\n\t\t\t// Skip malformed lines\n\t\t}\n\t}\n\n\treturn entries;\n}\n\nexport function getLatestCompactionEntry(entries: SessionEntry[]): CompactionEntry | null {\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tif (entries[i].type === \"compaction\") {\n\t\t\treturn entries[i] as CompactionEntry;\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction buildEntryIndex(entries: SessionEntry[], byId?: Map): Map {\n\tif (byId) return byId;\n\tconst index = new Map();\n\tfor (const entry of entries) {\n\t\tindex.set(entry.id, entry);\n\t}\n\treturn index;\n}\n\nfunction buildSessionPath(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map,\n): SessionEntry[] {\n\tconst index = buildEntryIndex(entries, byId);\n\tlet leaf: SessionEntry | undefined;\n\tif (leafId === null) {\n\t\treturn [];\n\t}\n\tif (leafId) {\n\t\tleaf = index.get(leafId);\n\t}\n\tleaf ??= entries[entries.length - 1];\n\tif (!leaf) {\n\t\treturn [];\n\t}\n\n\tconst path: SessionEntry[] = [];\n\tlet current: SessionEntry | undefined = leaf;\n\twhile (current) {\n\t\tpath.push(current);\n\t\tcurrent = current.parentId ? index.get(current.parentId) : undefined;\n\t}\n\tpath.reverse();\n\treturn path;\n}\n\nfunction getSessionContextSettings(path: SessionEntry[]): Pick {\n\tlet thinkingLevel = \"off\";\n\tlet model: { provider: string; modelId: string } | null = null;\n\n\tfor (const entry of path) {\n\t\tif (entry.type === \"thinking_level_change\") {\n\t\t\tthinkingLevel = entry.thinkingLevel;\n\t\t} else if (entry.type === \"model_change\") {\n\t\t\tmodel = { provider: entry.provider, modelId: entry.modelId };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tmodel = { provider: entry.message.provider, modelId: entry.message.model };\n\t\t}\n\t}\n\n\treturn { thinkingLevel, model };\n}\n\n/**\n * Project one selected session entry into LLM/runtime messages.\n * Plain custom entries are display/state entries and do not participate in context.\n */\nexport function sessionEntryToContextMessages(entry: SessionEntry): AgentMessage[] {\n\tif (entry.type === \"message\") {\n\t\tconst message = entry.message;\n\t\t// Session files are parsed without validation; old versions, forks, or\n\t\t// hand-edited files can contain messages with null/missing content.\n\t\tif (\n\t\t\t(message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\") &&\n\t\t\tmessage.content == null\n\t\t) {\n\t\t\treturn [{ ...message, content: [] }];\n\t\t}\n\t\treturn [message];\n\t}\n\tif (entry.type === \"custom_message\") {\n\t\treturn [\n\t\t\tcreateCustomMessage(entry.customType, entry.content ?? [], entry.display, entry.details, entry.timestamp),\n\t\t];\n\t}\n\tif (entry.type === \"branch_summary\" && entry.summary) {\n\t\treturn [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)];\n\t}\n\tif (entry.type === \"compaction\") {\n\t\treturn [createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp)];\n\t}\n\treturn [];\n}\n\n/**\n * Build the active, compaction-aware session entry list.\n *\n * This follows the current leaf path. If the path contains compaction entries,\n * the latest compaction is represented by the compaction entry itself, followed\n * by the kept entries starting at firstKeptEntryId and all entries after the\n * compaction entry. Older summarized entries are omitted.\n */\nexport function buildContextEntries(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map,\n): SessionEntry[] {\n\tconst path = buildSessionPath(entries, leafId, byId);\n\tlet compaction: CompactionEntry | null = null;\n\n\tfor (const entry of path) {\n\t\tif (entry.type === \"compaction\") {\n\t\t\tcompaction = entry;\n\t\t}\n\t}\n\n\tif (!compaction) {\n\t\treturn path;\n\t}\n\n\tconst compactionIdx = path.findIndex((entry) => entry.id === compaction.id);\n\tif (compactionIdx < 0) {\n\t\treturn path;\n\t}\n\n\tconst contextEntries: SessionEntry[] = [compaction];\n\tlet foundFirstKept = false;\n\tfor (let i = 0; i < compactionIdx; i++) {\n\t\tconst entry = path[i];\n\t\tif (entry.id === compaction.firstKeptEntryId) {\n\t\t\tfoundFirstKept = true;\n\t\t}\n\t\tif (foundFirstKept) {\n\t\t\tcontextEntries.push(entry);\n\t\t}\n\t}\n\tcontextEntries.push(...path.slice(compactionIdx + 1));\n\treturn contextEntries;\n}\n\n/**\n * Build the session context from entries using tree traversal.\n * If leafId is provided, walks from that entry to root.\n * Handles compaction and branch summaries along the path.\n */\nexport function buildSessionContext(\n\tentries: SessionEntry[],\n\tleafId?: string | null,\n\tbyId?: Map,\n): SessionContext {\n\tconst path = buildSessionPath(entries, leafId, byId);\n\tconst { thinkingLevel, model } = getSessionContextSettings(path);\n\tconst messages = buildContextEntries(entries, leafId, byId).flatMap(sessionEntryToContextMessages);\n\treturn { messages, thinkingLevel, model };\n}\n\n/**\n * Compute the default session directory for a cwd.\n * Encodes cwd into a safe directory name under ~/.pi/agent/sessions/.\n */\nfunction getDefaultSessionDirPath(cwd: string, agentDir: string = getDefaultAgentDir()): string {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir);\n\tconst safePath = `--${resolvedCwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n\treturn join(resolvedAgentDir, \"sessions\", safePath);\n}\n\nexport function getDefaultSessionDir(cwd: string, agentDir: string = getDefaultAgentDir()): string {\n\tconst sessionDir = getDefaultSessionDirPath(cwd, agentDir);\n\tif (!existsSync(sessionDir)) {\n\t\tmkdirSync(sessionDir, { recursive: true });\n\t}\n\treturn sessionDir;\n}\n\nconst SESSION_READ_BUFFER_SIZE = 1024 * 1024;\nconst SESSION_HEADER_READ_BUFFER_SIZE = 4096;\n/** Bound synchronous header discovery while allowing large cwd and custom metadata fields. */\nconst MAX_SESSION_HEADER_SCAN_BYTES = 1024 * 1024;\n\nclass SessionHeaderScanLimitError extends Error {\n\tconstructor(filePath: string) {\n\t\tsuper(`Session header exceeds ${MAX_SESSION_HEADER_SCAN_BYTES}-byte scan limit: ${filePath}`);\n\t\tthis.name = \"SessionHeaderScanLimitError\";\n\t}\n}\n\nfunction parseSessionEntryLine(line: string): FileEntry | null {\n\tif (!line.trim()) return null;\n\ttry {\n\t\treturn JSON.parse(line) as FileEntry;\n\t} catch {\n\t\t// Skip malformed lines\n\t\treturn null;\n\t}\n}\n\n/** Exported for testing */\nexport function loadEntriesFromFile(filePath: string): FileEntry[] {\n\tconst resolvedFilePath = normalizePath(filePath);\n\tif (!existsSync(resolvedFilePath)) return [];\n\n\tconst entries: FileEntry[] = [];\n\tconst fd = openSync(resolvedFilePath, \"r\");\n\ttry {\n\t\tconst decoder = new StringDecoder(\"utf8\");\n\t\tconst buffer = Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE);\n\t\tlet pending = \"\";\n\n\t\twhile (true) {\n\t\t\tconst bytesRead = readSync(fd, buffer, 0, buffer.length, null);\n\t\t\tif (bytesRead === 0) break;\n\n\t\t\tpending += decoder.write(buffer.subarray(0, bytesRead));\n\t\t\tlet lineStart = 0;\n\t\t\tlet newlineIndex = pending.indexOf(\"\\n\", lineStart);\n\t\t\twhile (newlineIndex !== -1) {\n\t\t\t\tconst entry = parseSessionEntryLine(pending.slice(lineStart, newlineIndex));\n\t\t\t\tif (entry) entries.push(entry);\n\t\t\t\tlineStart = newlineIndex + 1;\n\t\t\t\tnewlineIndex = pending.indexOf(\"\\n\", lineStart);\n\t\t\t}\n\t\t\tpending = pending.slice(lineStart);\n\t\t}\n\n\t\tpending += decoder.end();\n\t\tconst finalEntry = parseSessionEntryLine(pending);\n\t\tif (finalEntry) entries.push(finalEntry);\n\t} finally {\n\t\tcloseSync(fd);\n\t}\n\n\t// Validate session header\n\tif (entries.length === 0) return entries;\n\tconst header = entries[0];\n\tif (header.type !== \"session\" || typeof (header as { id?: unknown }).id !== \"string\") {\n\t\treturn [];\n\t}\n\n\treturn entries;\n}\n\n/**\n * Inspect a physical line while searching for the first parsed session entry.\n * Blank and malformed lines are skipped to match loadEntriesFromFile().\n * Returns undefined to keep scanning, null for a parsed non-header entry, or the header.\n */\nfunction parseSessionHeaderCandidate(line: string): SessionHeader | null | undefined {\n\tif (!line.trim()) return undefined;\n\tconst entry = parseSessionEntryLine(line);\n\tif (!entry) return undefined;\n\tif (entry.type !== \"session\" || typeof (entry as { id?: unknown }).id !== \"string\") return null;\n\treturn entry;\n}\n\nfunction readSessionHeader(filePath: string): SessionHeader | null {\n\tconst fd = openSync(filePath, \"r\");\n\ttry {\n\t\tconst decoder = new StringDecoder(\"utf8\");\n\t\tconst buffer = Buffer.allocUnsafe(SESSION_HEADER_READ_BUFFER_SIZE);\n\t\tconst lineChunks: string[] = [];\n\t\tlet scannedBytes = 0;\n\n\t\twhile (scannedBytes < MAX_SESSION_HEADER_SCAN_BYTES) {\n\t\t\tconst readLength = Math.min(buffer.length, MAX_SESSION_HEADER_SCAN_BYTES - scannedBytes);\n\t\t\tconst bytesRead = readSync(fd, buffer, 0, readLength, null);\n\t\t\tif (bytesRead === 0) {\n\t\t\t\tlineChunks.push(decoder.end());\n\t\t\t\treturn parseSessionHeaderCandidate(lineChunks.join(\"\")) ?? null;\n\t\t\t}\n\t\t\tscannedBytes += bytesRead;\n\n\t\t\tconst chunk = decoder.write(buffer.subarray(0, bytesRead));\n\t\t\tlet lineStart = 0;\n\t\t\tlet newlineIndex = chunk.indexOf(\"\\n\", lineStart);\n\t\t\twhile (newlineIndex !== -1) {\n\t\t\t\tlineChunks.push(chunk.slice(lineStart, newlineIndex));\n\t\t\t\tconst header = parseSessionHeaderCandidate(lineChunks.join(\"\"));\n\t\t\t\tif (header !== undefined) return header;\n\t\t\t\tlineChunks.length = 0;\n\t\t\t\tlineStart = newlineIndex + 1;\n\t\t\t\tnewlineIndex = chunk.indexOf(\"\\n\", lineStart);\n\t\t\t}\n\t\t\tlineChunks.push(chunk.slice(lineStart));\n\t\t}\n\n\t\t// Probe for EOF so a final header without a newline is allowed when it ends\n\t\t// exactly at the scan limit. Any additional byte exceeds the bounded scan.\n\t\tconst probe = Buffer.allocUnsafe(1);\n\t\tif (readSync(fd, probe, 0, probe.length, null) === 0) {\n\t\t\tlineChunks.push(decoder.end());\n\t\t\treturn parseSessionHeaderCandidate(lineChunks.join(\"\")) ?? null;\n\t\t}\n\t\tthrow new SessionHeaderScanLimitError(filePath);\n\t} finally {\n\t\tcloseSync(fd);\n\t}\n}\n\nfunction readSessionHeaderForDiscovery(filePath: string): SessionHeader | null {\n\ttry {\n\t\treturn readSessionHeader(filePath);\n\t} catch {\n\t\t// Discovery is best-effort: unreadable or oversized files are not sessions,\n\t\t// and one corrupt file must not prevent other sessions from being found.\n\t\treturn null;\n\t}\n}\n\nfunction getSessionHeaderCwd(header: SessionHeader): string | undefined {\n\tconst cwd = (header as { cwd?: unknown }).cwd;\n\treturn typeof cwd === \"string\" ? cwd : undefined;\n}\n\nfunction sessionCwdMatches(cwd: string | undefined, resolvedCwd: string): boolean {\n\treturn cwd !== undefined && cwd !== \"\" && resolvePath(cwd) === resolvedCwd;\n}\n\n/** Exported for testing */\nexport function findMostRecentSession(sessionDir: string, cwd?: string): string | null {\n\tconst resolvedSessionDir = normalizePath(sessionDir);\n\tconst resolvedCwd = cwd ? resolvePath(cwd) : undefined;\n\ttry {\n\t\tconst files = readdirSync(resolvedSessionDir)\n\t\t\t.filter((f) => f.endsWith(\".jsonl\"))\n\t\t\t.map((f) => join(resolvedSessionDir, f))\n\t\t\t.map((path) => ({ path, header: readSessionHeaderForDiscovery(path) }))\n\t\t\t.filter(\n\t\t\t\t(file): file is { path: string; header: SessionHeader } =>\n\t\t\t\t\tfile.header !== null &&\n\t\t\t\t\t(!resolvedCwd || sessionCwdMatches(getSessionHeaderCwd(file.header), resolvedCwd)),\n\t\t\t)\n\t\t\t.map(({ path }) => ({ path, mtime: statSync(path).mtime }))\n\t\t\t.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());\n\n\t\treturn files[0]?.path || null;\n\t} catch {\n\t\t// Directory access and stat races make recent-session discovery unavailable.\n\t\treturn null;\n\t}\n}\n\nfunction isMessageWithContent(message: AgentMessage): message is Message {\n\treturn typeof (message as Message).role === \"string\" && \"content\" in message;\n}\n\nfunction extractTextContent(message: Message): string {\n\tconst content = message.content;\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\treturn content\n\t\t.filter((block): block is TextContent => block.type === \"text\")\n\t\t.map((block) => block.text)\n\t\t.join(\" \");\n}\n\nfunction getMessageActivityTime(entry: SessionMessageEntry): number | undefined {\n\tconst message = entry.message;\n\tif (!isMessageWithContent(message)) return undefined;\n\tif (message.role !== \"user\" && message.role !== \"assistant\") return undefined;\n\n\tconst msgTimestamp = (message as { timestamp?: number }).timestamp;\n\tif (typeof msgTimestamp === \"number\") {\n\t\treturn msgTimestamp;\n\t}\n\n\tconst t = new Date(entry.timestamp).getTime();\n\treturn Number.isNaN(t) ? undefined : t;\n}\n\nasync function buildSessionInfo(filePath: string): Promise {\n\ttry {\n\t\tconst stats = await stat(filePath);\n\t\tlet header: SessionHeader | null = null;\n\t\tlet messageCount = 0;\n\t\tlet firstMessage = \"\";\n\t\tconst allMessages: string[] = [];\n\t\tlet name: string | undefined;\n\t\tlet lastActivityTime: number | undefined;\n\n\t\tconst rl = createInterface({\n\t\t\tinput: createReadStream(filePath, { encoding: \"utf8\" }),\n\t\t\tcrlfDelay: Infinity,\n\t\t});\n\n\t\tfor await (const line of rl) {\n\t\t\tconst entry = parseSessionEntryLine(line);\n\t\t\tif (!entry) continue;\n\n\t\t\tif (!header) {\n\t\t\t\tif (entry.type !== \"session\") return null;\n\t\t\t\theader = entry;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Extract session name (use latest, including explicit clears)\n\t\t\tif (entry.type === \"session_info\") {\n\t\t\t\tname = entry.name?.trim() || undefined;\n\t\t\t}\n\n\t\t\tif (entry.type !== \"message\") continue;\n\t\t\tmessageCount++;\n\n\t\t\tconst activityTime = getMessageActivityTime(entry);\n\t\t\tif (typeof activityTime === \"number\") {\n\t\t\t\tlastActivityTime = Math.max(lastActivityTime ?? 0, activityTime);\n\t\t\t}\n\n\t\t\tconst message = entry.message;\n\t\t\tif (!isMessageWithContent(message)) continue;\n\t\t\tif (message.role !== \"user\" && message.role !== \"assistant\") continue;\n\n\t\t\tconst textContent = extractTextContent(message);\n\t\t\tif (!textContent) continue;\n\n\t\t\tallMessages.push(textContent);\n\t\t\tif (!firstMessage && message.role === \"user\") {\n\t\t\t\tfirstMessage = textContent;\n\t\t\t}\n\t\t}\n\n\t\tif (!header) return null;\n\n\t\tconst cwd = typeof header.cwd === \"string\" ? header.cwd : \"\";\n\t\tconst parentSessionPath = header.parentSession;\n\t\tconst headerTime = typeof header.timestamp === \"string\" ? new Date(header.timestamp).getTime() : NaN;\n\t\tconst modified =\n\t\t\ttypeof lastActivityTime === \"number\" && lastActivityTime > 0\n\t\t\t\t? new Date(lastActivityTime)\n\t\t\t\t: !Number.isNaN(headerTime)\n\t\t\t\t\t? new Date(headerTime)\n\t\t\t\t\t: stats.mtime;\n\n\t\treturn {\n\t\t\tpath: filePath,\n\t\t\tid: header.id,\n\t\t\tcwd,\n\t\t\tname,\n\t\t\tparentSessionPath,\n\t\t\tcreated: new Date(header.timestamp),\n\t\t\tmodified,\n\t\t\tmessageCount,\n\t\t\tfirstMessage: firstMessage || \"(no messages)\",\n\t\t\tallMessagesText: allMessages.join(\" \"),\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport type SessionListProgress = (loaded: number, total: number) => void;\n\nconst MAX_CONCURRENT_SESSION_INFO_LOADS = 10;\n\nasync function buildSessionInfosWithConcurrency(\n\tfiles: string[],\n\tonLoaded: () => void,\n): Promise<(SessionInfo | null)[]> {\n\tconst results: (SessionInfo | null)[] = new Array(files.length).fill(null);\n\tconst inFlight = new Set>();\n\tlet nextIndex = 0;\n\n\tconst startNext = (): void => {\n\t\tconst index = nextIndex++;\n\t\tconst file = files[index];\n\t\tif (!file) return;\n\n\t\tlet task: Promise;\n\t\ttask = buildSessionInfo(file)\n\t\t\t.then((info) => {\n\t\t\t\tresults[index] = info;\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\tresults[index] = null;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tinFlight.delete(task);\n\t\t\t\tonLoaded();\n\t\t\t});\n\t\tinFlight.add(task);\n\t};\n\n\twhile (nextIndex < files.length || inFlight.size > 0) {\n\t\twhile (nextIndex < files.length && inFlight.size < MAX_CONCURRENT_SESSION_INFO_LOADS) {\n\t\t\tstartNext();\n\t\t}\n\t\tif (inFlight.size > 0) {\n\t\t\tawait Promise.race(inFlight);\n\t\t}\n\t}\n\n\treturn results;\n}\n\nasync function listSessionsFromDir(\n\tdir: string,\n\tonProgress?: SessionListProgress,\n\tprogressOffset = 0,\n\tprogressTotal?: number,\n): Promise {\n\tconst sessions: SessionInfo[] = [];\n\tif (!existsSync(dir)) {\n\t\treturn sessions;\n\t}\n\n\ttry {\n\t\tconst dirEntries = await readdir(dir);\n\t\tconst files = dirEntries.filter((f) => f.endsWith(\".jsonl\")).map((f) => join(dir, f));\n\t\tconst total = progressTotal ?? files.length;\n\n\t\tlet loaded = 0;\n\t\tconst results = await buildSessionInfosWithConcurrency(files, () => {\n\t\t\tloaded++;\n\t\t\tonProgress?.(progressOffset + loaded, total);\n\t\t});\n\t\tfor (const info of results) {\n\t\t\tif (info) {\n\t\t\t\tsessions.push(info);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Return empty list on error\n\t}\n\n\treturn sessions;\n}\n\n/**\n * Manages conversation sessions as append-only trees stored in JSONL files.\n *\n * Each session entry has an id and parentId forming a tree structure. The \"leaf\"\n * pointer tracks the current position. Appending creates a child of the current leaf.\n * Branching moves the leaf to an earlier entry, allowing new branches without\n * modifying history.\n *\n * Use buildSessionContext() to get the resolved message list for the LLM, which\n * handles compaction summaries and follows the path from root to current leaf.\n */\nexport class SessionManager {\n\tprivate sessionId: string = \"\";\n\tprivate sessionFile: string | undefined;\n\tprivate sessionDir: string;\n\tprivate cwd: string;\n\tprivate persist: boolean;\n\tprivate flushed: boolean = false;\n\tprivate fileEntries: FileEntry[] = [];\n\tprivate byId: Map = new Map();\n\tprivate labelsById: Map = new Map();\n\tprivate labelTimestampsById: Map = new Map();\n\tprivate leafId: string | null = null;\n\n\tprivate constructor(\n\t\tcwd: string,\n\t\tsessionDir: string,\n\t\tsessionFile: string | undefined,\n\t\tpersist: boolean,\n\t\tnewSessionOptions?: NewSessionOptions,\n\t\tpreloadedFileEntries?: FileEntry[],\n\t) {\n\t\tthis.cwd = resolvePath(cwd);\n\t\tthis.sessionDir = normalizePath(sessionDir);\n\t\tthis.persist = persist;\n\t\tif (persist && this.sessionDir && !existsSync(this.sessionDir)) {\n\t\t\tmkdirSync(this.sessionDir, { recursive: true });\n\t\t}\n\n\t\tif (sessionFile) {\n\t\t\tthis._setSessionFile(sessionFile, preloadedFileEntries);\n\t\t} else {\n\t\t\tthis.newSession(newSessionOptions);\n\t\t}\n\t}\n\n\t/** Switch to a different session file (used for resume and branching) */\n\tsetSessionFile(sessionFile: string): void {\n\t\tthis._setSessionFile(sessionFile);\n\t}\n\n\tprivate _setSessionFile(sessionFile: string, preloadedFileEntries?: FileEntry[]): void {\n\t\tthis.sessionFile = resolvePath(sessionFile);\n\t\tif (existsSync(this.sessionFile)) {\n\t\t\tthis.fileEntries = preloadedFileEntries ?? loadEntriesFromFile(this.sessionFile);\n\n\t\t\t// If file was empty, initialize it with a valid session header. If it was\n\t\t\t// non-empty but did not parse as a pi session, fail without modifying it.\n\t\t\tif (this.fileEntries.length === 0) {\n\t\t\t\tconst explicitPath = this.sessionFile;\n\t\t\t\tif (statSync(explicitPath).size > 0) {\n\t\t\t\t\tthrow new Error(`Session file is not a valid pi session: ${explicitPath}`);\n\t\t\t\t}\n\t\t\t\tthis.newSession();\n\t\t\t\tthis.sessionFile = explicitPath;\n\t\t\t\tthis._rewriteFile();\n\t\t\t\tthis.flushed = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst header = this.fileEntries.find((e) => e.type === \"session\") as SessionHeader | undefined;\n\t\t\tthis.sessionId = header?.id ?? createSessionId();\n\n\t\t\tif (migrateToCurrentVersion(this.fileEntries)) {\n\t\t\t\tthis._rewriteFile();\n\t\t\t}\n\n\t\t\tthis._buildIndex();\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tconst explicitPath = this.sessionFile;\n\t\t\tthis.newSession();\n\t\t\tthis.sessionFile = explicitPath; // preserve explicit path from --session flag\n\t\t}\n\t}\n\n\tnewSession(options?: NewSessionOptions): string | undefined {\n\t\tif (options?.id !== undefined) {\n\t\t\tassertValidSessionId(options.id);\n\t\t}\n\t\tthis.sessionId = options?.id ?? createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: this.sessionId,\n\t\t\ttimestamp,\n\t\t\tcwd: this.cwd,\n\t\t\tparentSession: options?.parentSession,\n\t\t};\n\t\tthis.fileEntries = [header];\n\t\tthis.byId.clear();\n\t\tthis.labelsById.clear();\n\t\tthis.labelTimestampsById.clear();\n\t\tthis.leafId = null;\n\t\tthis.flushed = false;\n\n\t\tif (this.persist) {\n\t\t\tconst fileTimestamp = timestamp.replace(/[:.]/g, \"-\");\n\t\t\tthis.sessionFile = join(this.getSessionDir(), `${fileTimestamp}_${this.sessionId}.jsonl`);\n\t\t}\n\t\treturn this.sessionFile;\n\t}\n\n\tprivate _buildIndex(): void {\n\t\tthis.byId.clear();\n\t\tthis.labelsById.clear();\n\t\tthis.labelTimestampsById.clear();\n\t\tthis.leafId = null;\n\t\tfor (const entry of this.fileEntries) {\n\t\t\tif (entry.type === \"session\") continue;\n\t\t\tthis.byId.set(entry.id, entry);\n\t\t\tthis.leafId = entry.id;\n\t\t\tif (entry.type === \"label\") {\n\t\t\t\tif (entry.label) {\n\t\t\t\t\tthis.labelsById.set(entry.targetId, entry.label);\n\t\t\t\t\tthis.labelTimestampsById.set(entry.targetId, entry.timestamp);\n\t\t\t\t} else {\n\t\t\t\t\tthis.labelsById.delete(entry.targetId);\n\t\t\t\t\tthis.labelTimestampsById.delete(entry.targetId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate _rewriteFile(): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\t\tconst fd = openSync(this.sessionFile, \"w\");\n\t\ttry {\n\t\t\tfor (const entry of this.fileEntries) {\n\t\t\t\twriteFileSync(fd, `${JSON.stringify(entry)}\\n`);\n\t\t\t}\n\t\t} finally {\n\t\t\tcloseSync(fd);\n\t\t}\n\t}\n\n\tisPersisted(): boolean {\n\t\treturn this.persist;\n\t}\n\n\tgetCwd(): string {\n\t\treturn this.cwd;\n\t}\n\n\tgetSessionDir(): string {\n\t\treturn this.sessionDir;\n\t}\n\n\tusesDefaultSessionDir(): boolean {\n\t\treturn this.sessionDir === getDefaultSessionDirPath(this.cwd);\n\t}\n\n\tgetSessionId(): string {\n\t\treturn this.sessionId;\n\t}\n\n\tgetSessionFile(): string | undefined {\n\t\treturn this.sessionFile;\n\t}\n\n\t_persist(entry: SessionEntry): void {\n\t\tif (!this.persist || !this.sessionFile) return;\n\n\t\tconst hasAssistant = this.fileEntries.some((e) => e.type === \"message\" && e.message.role === \"assistant\");\n\t\tif (!hasAssistant) {\n\t\t\tif (this.flushed) {\n\t\t\t\tappendFileSync(this.sessionFile, `${JSON.stringify(entry)}\\n`);\n\t\t\t} else {\n\t\t\t\t// Mark as not flushed so when assistant arrives, all entries get written\n\t\t\t\tthis.flushed = false;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.flushed) {\n\t\t\tconst fd = openSync(this.sessionFile, \"wx\");\n\t\t\ttry {\n\t\t\t\tfor (const e of this.fileEntries) {\n\t\t\t\t\twriteFileSync(fd, `${JSON.stringify(e)}\\n`);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tcloseSync(fd);\n\t\t\t}\n\t\t\tthis.flushed = true;\n\t\t} else {\n\t\t\tappendFileSync(this.sessionFile, `${JSON.stringify(entry)}\\n`);\n\t\t}\n\t}\n\n\tprivate _appendEntry(entry: SessionEntry): void {\n\t\tthis.fileEntries.push(entry);\n\t\tthis.byId.set(entry.id, entry);\n\t\tthis.leafId = entry.id;\n\t\tthis._persist(entry);\n\t}\n\n\t/** Append a message as child of current leaf, then advance leaf. Returns entry id.\n\t * Does not allow writing CompactionSummaryMessage and BranchSummaryMessage directly.\n\t * Reason: we want these to be top-level entries in the session, not message session entries,\n\t * so it is easier to find them.\n\t * These need to be appended via appendCompaction() and appendBranchSummary() methods.\n\t */\n\tappendMessage(message: Message | CustomMessage | BashExecutionMessage): string {\n\t\tconst entry: SessionMessageEntry = {\n\t\t\ttype: \"message\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tmessage,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendThinkingLevelChange(thinkingLevel: string): string {\n\t\tconst entry: ThinkingLevelChangeEntry = {\n\t\t\ttype: \"thinking_level_change\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tthinkingLevel,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a model change as child of current leaf, then advance leaf. Returns entry id. */\n\tappendModelChange(provider: string, modelId: string): string {\n\t\tconst entry: ModelChangeEntry = {\n\t\t\ttype: \"model_change\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tprovider,\n\t\t\tmodelId,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCompaction(\n\t\tsummary: string,\n\t\tfirstKeptEntryId: string,\n\t\ttokensBefore: number,\n\t\tdetails?: T,\n\t\tfromHook?: boolean,\n\t\tusage?: Usage,\n\t): string {\n\t\tconst entry: CompactionEntry = {\n\t\t\ttype: \"compaction\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tsummary,\n\t\t\tfirstKeptEntryId,\n\t\t\ttokensBefore,\n\t\t\tdetails,\n\t\t\tusage,\n\t\t\tfromHook,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */\n\tappendCustomEntry(customType: string, data?: unknown): string {\n\t\tconst entry: CustomEntry = {\n\t\t\ttype: \"custom\",\n\t\t\tcustomType,\n\t\t\tdata,\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Append a session info entry (e.g., display name). Returns entry id. */\n\tappendSessionInfo(name: string): string {\n\t\tconst sanitizedName = name.replace(/[\\r\\n]+/g, \" \").trim();\n\t\tconst entry: SessionInfoEntry = {\n\t\t\ttype: \"session_info\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tname: sanitizedName,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/** Get the current session name from the latest session_info entry, if any. */\n\tgetSessionName(): string | undefined {\n\t\t// Walk entries in reverse to find the latest session_info entry.\n\t\t// Empty names explicitly clear the session title.\n\t\tconst entries = this.getEntries();\n\t\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\t\tconst entry = entries[i];\n\t\t\tif (entry.type === \"session_info\") {\n\t\t\t\treturn entry.name?.trim() || undefined;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Append a custom message entry (for extensions) that participates in LLM context.\n\t * @param customType Extension identifier for filtering on reload\n\t * @param content Message content (string or TextContent/ImageContent array)\n\t * @param display Whether to show in TUI (true = styled display, false = hidden)\n\t * @param details Optional extension-specific metadata (not sent to LLM)\n\t * @returns Entry id\n\t */\n\tappendCustomMessageEntry(\n\t\tcustomType: string,\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\tdisplay: boolean,\n\t\tdetails?: T,\n\t): string {\n\t\tconst entry: CustomMessageEntry = {\n\t\t\ttype: \"custom_message\",\n\t\t\tcustomType,\n\t\t\tcontent,\n\t\t\tdisplay,\n\t\t\tdetails,\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t// =========================================================================\n\t// Tree Traversal\n\t// =========================================================================\n\n\tgetLeafId(): string | null {\n\t\treturn this.leafId;\n\t}\n\n\tgetLeafEntry(): SessionEntry | undefined {\n\t\treturn this.leafId ? this.byId.get(this.leafId) : undefined;\n\t}\n\n\tgetEntry(id: string): SessionEntry | undefined {\n\t\treturn this.byId.get(id);\n\t}\n\n\t/**\n\t * Get all direct children of an entry.\n\t */\n\tgetChildren(parentId: string): SessionEntry[] {\n\t\tconst children: SessionEntry[] = [];\n\t\tfor (const entry of this.byId.values()) {\n\t\t\tif (entry.parentId === parentId) {\n\t\t\t\tchildren.push(entry);\n\t\t\t}\n\t\t}\n\t\treturn children;\n\t}\n\n\t/**\n\t * Get the label for an entry, if any.\n\t */\n\tgetLabel(id: string): string | undefined {\n\t\treturn this.labelsById.get(id);\n\t}\n\n\t/**\n\t * Set or clear a label on an entry.\n\t * Labels are user-defined markers for bookmarking/navigation.\n\t * Pass undefined or empty string to clear the label.\n\t */\n\tappendLabelChange(targetId: string, label: string | undefined): string {\n\t\tif (!this.byId.has(targetId)) {\n\t\t\tthrow new Error(`Entry ${targetId} not found`);\n\t\t}\n\t\tconst entry: LabelEntry = {\n\t\t\ttype: \"label\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: this.leafId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttargetId,\n\t\t\tlabel,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\tif (label) {\n\t\t\tthis.labelsById.set(targetId, label);\n\t\t\tthis.labelTimestampsById.set(targetId, entry.timestamp);\n\t\t} else {\n\t\t\tthis.labelsById.delete(targetId);\n\t\t\tthis.labelTimestampsById.delete(targetId);\n\t\t}\n\t\treturn entry.id;\n\t}\n\n\t/**\n\t * Walk from entry to root, returning all entries in path order.\n\t * Includes all entry types (messages, compaction, model changes, etc.).\n\t * Use buildSessionContext() to get the resolved messages for the LLM.\n\t */\n\tgetBranch(fromId?: string): SessionEntry[] {\n\t\tconst path: SessionEntry[] = [];\n\t\tconst startId = fromId ?? this.leafId;\n\t\tlet current = startId ? this.byId.get(startId) : undefined;\n\t\twhile (current) {\n\t\t\tpath.push(current);\n\t\t\tcurrent = current.parentId ? this.byId.get(current.parentId) : undefined;\n\t\t}\n\t\tpath.reverse();\n\t\treturn path;\n\t}\n\n\t/**\n\t * Build the active, compaction-aware entry list for context/rendering.\n\t * Uses tree traversal from current leaf.\n\t */\n\tbuildContextEntries(): SessionEntry[] {\n\t\treturn buildContextEntries(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/**\n\t * Build the session context (what gets sent to the LLM).\n\t * Uses tree traversal from current leaf.\n\t */\n\tbuildSessionContext(): SessionContext {\n\t\treturn buildSessionContext(this.getEntries(), this.leafId, this.byId);\n\t}\n\n\t/**\n\t * Get session header.\n\t */\n\tgetHeader(): SessionHeader | null {\n\t\tconst h = this.fileEntries.find((e) => e.type === \"session\");\n\t\treturn h ? (h as SessionHeader) : null;\n\t}\n\n\t/**\n\t * Get all session entries (excludes header). Returns a shallow copy.\n\t * The session is append-only: use appendXXX() to add entries, branch() to\n\t * change the leaf pointer. Entries cannot be modified or deleted.\n\t */\n\tgetEntries(): SessionEntry[] {\n\t\treturn this.fileEntries.filter((e): e is SessionEntry => e.type !== \"session\");\n\t}\n\n\t/**\n\t * Get the session as a tree structure. Returns a shallow defensive copy of all entries.\n\t * A well-formed session has exactly one root (first entry with parentId === null).\n\t * Orphaned entries (broken parent chain) are also returned as roots.\n\t */\n\tgetTree(): SessionTreeNode[] {\n\t\tconst entries = this.getEntries();\n\t\tconst nodeMap = new Map();\n\t\tconst roots: SessionTreeNode[] = [];\n\n\t\t// Create nodes with resolved labels\n\t\tfor (const entry of entries) {\n\t\t\tconst label = this.labelsById.get(entry.id);\n\t\t\tconst labelTimestamp = this.labelTimestampsById.get(entry.id);\n\t\t\tnodeMap.set(entry.id, { entry, children: [], label, labelTimestamp });\n\t\t}\n\n\t\t// Build tree\n\t\tfor (const entry of entries) {\n\t\t\tconst node = nodeMap.get(entry.id)!;\n\t\t\tif (entry.parentId === null || entry.parentId === entry.id) {\n\t\t\t\troots.push(node);\n\t\t\t} else {\n\t\t\t\tconst parent = nodeMap.get(entry.parentId);\n\t\t\t\tif (parent) {\n\t\t\t\t\tparent.children.push(node);\n\t\t\t\t} else {\n\t\t\t\t\t// Orphan - treat as root\n\t\t\t\t\troots.push(node);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Sort children by timestamp (oldest first, newest at bottom)\n\t\t// Use iterative approach to avoid stack overflow on deep trees\n\t\tconst stack: SessionTreeNode[] = [...roots];\n\t\twhile (stack.length > 0) {\n\t\t\tconst node = stack.pop()!;\n\t\t\tnode.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime());\n\t\t\tstack.push(...node.children);\n\t\t}\n\n\t\treturn roots;\n\t}\n\n\t// =========================================================================\n\t// Branching\n\t// =========================================================================\n\n\t/**\n\t * Start a new branch from an earlier entry.\n\t * Moves the leaf pointer to the specified entry. The next appendXXX() call\n\t * will create a child of that entry, forming a new branch. Existing entries\n\t * are not modified or deleted.\n\t */\n\tbranch(branchFromId: string): void {\n\t\tif (!this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t}\n\n\t/**\n\t * Reset the leaf pointer to null (before any entries).\n\t * The next appendXXX() call will create a new root entry (parentId = null).\n\t * Use this when navigating to re-edit the first user message.\n\t */\n\tresetLeaf(): void {\n\t\tthis.leafId = null;\n\t}\n\n\t/**\n\t * Start a new branch with a summary of the abandoned path.\n\t * Same as branch(), but also appends a branch_summary entry that captures\n\t * context from the abandoned conversation path.\n\t */\n\tbranchWithSummary(\n\t\tbranchFromId: string | null,\n\t\tsummary: string,\n\t\tdetails?: unknown,\n\t\tfromHook?: boolean,\n\t\tusage?: Usage,\n\t): string {\n\t\tif (branchFromId !== null && !this.byId.has(branchFromId)) {\n\t\t\tthrow new Error(`Entry ${branchFromId} not found`);\n\t\t}\n\t\tthis.leafId = branchFromId;\n\t\tconst entry: BranchSummaryEntry = {\n\t\t\ttype: \"branch_summary\",\n\t\t\tid: generateId(this.byId),\n\t\t\tparentId: branchFromId,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tfromId: branchFromId ?? \"root\",\n\t\t\tsummary,\n\t\t\tdetails,\n\t\t\tusage,\n\t\t\tfromHook,\n\t\t};\n\t\tthis._appendEntry(entry);\n\t\treturn entry.id;\n\t}\n\n\t/**\n\t * Create a new session file containing only the path from root to the specified leaf.\n\t * Useful for extracting a single conversation path from a branched session.\n\t * Returns the new session file path, or undefined if not persisting.\n\t */\n\tcreateBranchedSession(leafId: string): string | undefined {\n\t\tconst previousSessionFile = this.sessionFile;\n\t\tconst path = this.getBranch(leafId);\n\t\tif (path.length === 0) {\n\t\t\tthrow new Error(`Entry ${leafId} not found`);\n\t\t}\n\n\t\t// Filter out LabelEntry from path - we'll recreate them from the resolved map.\n\t\t// Because labels are real tree entries, later entries can be children of labels;\n\t\t// removing labels requires re-chaining the retained path to avoid orphaned subtrees.\n\t\tconst pathWithoutLabels: SessionEntry[] = [];\n\t\tlet pathParentId: string | null = null;\n\t\tfor (const entry of path) {\n\t\t\tif (entry.type === \"label\") continue;\n\t\t\tpathWithoutLabels.push({ ...entry, parentId: pathParentId });\n\t\t\tpathParentId = entry.id;\n\t\t}\n\n\t\tconst newSessionId = createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst fileTimestamp = timestamp.replace(/[:.]/g, \"-\");\n\t\tconst newSessionFile = join(this.getSessionDir(), `${fileTimestamp}_${newSessionId}.jsonl`);\n\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: newSessionId,\n\t\t\ttimestamp,\n\t\t\tcwd: this.cwd,\n\t\t\tparentSession: this.persist ? previousSessionFile : undefined,\n\t\t};\n\n\t\t// Collect labels for entries in the path\n\t\tconst pathEntryIds = new Set(pathWithoutLabels.map((e) => e.id));\n\t\tconst labelsToWrite: Array<{ targetId: string; label: string; timestamp: string }> = [];\n\t\tfor (const [targetId, label] of this.labelsById) {\n\t\t\tif (pathEntryIds.has(targetId)) {\n\t\t\t\tlabelsToWrite.push({ targetId, label, timestamp: this.labelTimestampsById.get(targetId)! });\n\t\t\t}\n\t\t}\n\n\t\tif (this.persist) {\n\t\t\t// Build label entries\n\t\t\tconst lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;\n\t\t\tlet parentId = lastEntryId;\n\t\t\tconst labelEntries: LabelEntry[] = [];\n\t\t\tfor (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {\n\t\t\t\tconst labelEntry: LabelEntry = {\n\t\t\t\t\ttype: \"label\",\n\t\t\t\t\tid: generateId(new Set(pathEntryIds)),\n\t\t\t\t\tparentId,\n\t\t\t\t\ttimestamp: labelTimestamp,\n\t\t\t\t\ttargetId,\n\t\t\t\t\tlabel,\n\t\t\t\t};\n\t\t\t\tpathEntryIds.add(labelEntry.id);\n\t\t\t\tlabelEntries.push(labelEntry);\n\t\t\t\tparentId = labelEntry.id;\n\t\t\t}\n\n\t\t\tthis.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];\n\t\t\tthis.sessionId = newSessionId;\n\t\t\tthis.sessionFile = newSessionFile;\n\t\t\tthis._buildIndex();\n\n\t\t\t// Only write the file now if it contains an assistant message.\n\t\t\t// Otherwise defer to _persist(), which creates the file on the\n\t\t\t// first assistant response, matching the newSession() contract\n\t\t\t// and avoiding the duplicate-header bug when _persist()'s\n\t\t\t// no-assistant guard later resets flushed to false.\n\t\t\tconst hasAssistant = this.fileEntries.some((e) => e.type === \"message\" && e.message.role === \"assistant\");\n\t\t\tif (hasAssistant) {\n\t\t\t\tthis._rewriteFile();\n\t\t\t\tthis.flushed = true;\n\t\t\t} else {\n\t\t\t\tthis.flushed = false;\n\t\t\t}\n\n\t\t\treturn newSessionFile;\n\t\t}\n\n\t\t// In-memory mode: replace current session with the path + labels\n\t\tconst labelEntries: LabelEntry[] = [];\n\t\tlet parentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;\n\t\tfor (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {\n\t\t\tconst labelEntry: LabelEntry = {\n\t\t\t\ttype: \"label\",\n\t\t\t\tid: generateId(new Set([...pathEntryIds, ...labelEntries.map((e) => e.id)])),\n\t\t\t\tparentId,\n\t\t\t\ttimestamp: labelTimestamp,\n\t\t\t\ttargetId,\n\t\t\t\tlabel,\n\t\t\t};\n\t\t\tlabelEntries.push(labelEntry);\n\t\t\tparentId = labelEntry.id;\n\t\t}\n\t\tthis.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];\n\t\tthis.sessionId = newSessionId;\n\t\tthis._buildIndex();\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Create a new session.\n\t * @param cwd Working directory (stored in session header)\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions//).\n\t */\n\tstatic create(cwd: string, sessionDir?: string, options?: NewSessionOptions): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\treturn new SessionManager(cwd, dir, undefined, true, options);\n\t}\n\n\t/**\n\t * Open a specific session file.\n\t * @param path Path to session file\n\t * @param sessionDir Optional session directory for /new or /branch. If omitted, derives from file's parent.\n\t * @param cwdOverride Optional cwd override instead of the session header cwd.\n\t */\n\tstatic open(path: string, sessionDir?: string, cwdOverride?: string): SessionManager {\n\t\tconst resolvedPath = resolvePath(path);\n\t\tlet header: SessionHeader | null = null;\n\t\tlet preloadedFileEntries: FileEntry[] | undefined;\n\t\tif (cwdOverride === undefined && existsSync(resolvedPath)) {\n\t\t\ttry {\n\t\t\t\theader = readSessionHeader(resolvedPath);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof SessionHeaderScanLimitError)) throw error;\n\t\t\t\t// The bounded scan is only a discovery optimization. A full load remains\n\t\t\t\t// authoritative for legacy files with very large headers or prefixes.\n\t\t\t\tpreloadedFileEntries = loadEntriesFromFile(resolvedPath);\n\t\t\t\tconst firstEntry = preloadedFileEntries[0];\n\t\t\t\theader = firstEntry?.type === \"session\" ? firstEntry : null;\n\t\t\t}\n\t\t}\n\t\tconst cwd = cwdOverride ?? (header ? getSessionHeaderCwd(header) : undefined) ?? process.cwd();\n\t\t// If no sessionDir provided, derive from file's parent directory\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, \"..\");\n\t\treturn new SessionManager(cwd, dir, resolvedPath, true, undefined, preloadedFileEntries);\n\t}\n\n\t/**\n\t * Continue the most recent session, or create new if none.\n\t * @param cwd Working directory\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions//).\n\t */\n\tstatic continueRecent(cwd: string, sessionDir?: string): SessionManager {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst mostRecent = findMostRecentSession(dir, filterCwd ? cwd : undefined);\n\t\tif (mostRecent) {\n\t\t\treturn new SessionManager(cwd, dir, mostRecent, true);\n\t\t}\n\t\treturn new SessionManager(cwd, dir, undefined, true);\n\t}\n\n\t/** Create an in-memory session (no file persistence) */\n\tstatic inMemory(cwd: string = process.cwd(), options?: NewSessionOptions): SessionManager {\n\t\treturn new SessionManager(cwd, \"\", undefined, false, options);\n\t}\n\n\t/**\n\t * Fork a session from another project directory into the current project.\n\t * Creates a new session in the target cwd with the full history from the source session.\n\t * @param sourcePath Path to the source session file\n\t * @param targetCwd Target working directory (where the new session will be stored)\n\t * @param sessionDir Optional session directory. If omitted, uses default for targetCwd.\n\t */\n\tstatic forkFrom(\n\t\tsourcePath: string,\n\t\ttargetCwd: string,\n\t\tsessionDir?: string,\n\t\toptions?: NewSessionOptions,\n\t): SessionManager {\n\t\tconst resolvedSourcePath = resolvePath(sourcePath);\n\t\tconst resolvedTargetCwd = resolvePath(targetCwd);\n\t\tconst sourceEntries = loadEntriesFromFile(resolvedSourcePath);\n\t\tif (sourceEntries.length === 0) {\n\t\t\tthrow new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);\n\t\t}\n\n\t\tconst sourceHeader = sourceEntries.find((e) => e.type === \"session\") as SessionHeader | undefined;\n\t\tif (!sourceHeader) {\n\t\t\tthrow new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`);\n\t\t}\n\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(resolvedTargetCwd);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t}\n\n\t\t// Create new session file with new ID but forked content\n\t\tif (options?.id !== undefined) {\n\t\t\tassertValidSessionId(options.id);\n\t\t}\n\t\tconst newSessionId = options?.id ?? createSessionId();\n\t\tconst timestamp = new Date().toISOString();\n\t\tconst fileTimestamp = timestamp.replace(/[:.]/g, \"-\");\n\t\tconst newSessionFile = join(dir, `${fileTimestamp}_${newSessionId}.jsonl`);\n\n\t\t// Write new header pointing to source as parent, with updated cwd\n\t\tconst newHeader: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: newSessionId,\n\t\t\ttimestamp,\n\t\t\tcwd: resolvedTargetCwd,\n\t\t\tparentSession: resolvedSourcePath,\n\t\t};\n\t\twriteFileSync(newSessionFile, `${JSON.stringify(newHeader)}\\n`, { flag: \"wx\" });\n\n\t\t// Copy all non-header entries from source\n\t\tfor (const entry of sourceEntries) {\n\t\t\tif (entry.type !== \"session\") {\n\t\t\t\tappendFileSync(newSessionFile, `${JSON.stringify(entry)}\\n`);\n\t\t\t}\n\t\t}\n\n\t\treturn new SessionManager(resolvedTargetCwd, dir, newSessionFile, true);\n\t}\n\n\t/**\n\t * List all sessions for a directory.\n\t * @param cwd Working directory (used to compute default session directory)\n\t * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions//).\n\t * @param onProgress Optional callback for progress updates (loaded, total)\n\t */\n\tstatic async list(cwd: string, sessionDir?: string, onProgress?: SessionListProgress): Promise {\n\t\tconst dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);\n\t\tconst filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);\n\t\tconst resolvedCwd = resolvePath(cwd);\n\t\tconst sessions = (await listSessionsFromDir(dir, onProgress)).filter(\n\t\t\t(session) => !filterCwd || sessionCwdMatches(session.cwd, resolvedCwd),\n\t\t);\n\t\tsessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());\n\t\treturn sessions;\n\t}\n\n\t/**\n\t * List all sessions across all project directories.\n\t * @param onProgress Optional callback for progress updates (loaded, total)\n\t */\n\tstatic async listAll(onProgress?: SessionListProgress): Promise;\n\tstatic async listAll(sessionDir?: string, onProgress?: SessionListProgress): Promise;\n\tstatic async listAll(\n\t\tsessionDirOrOnProgress?: string | SessionListProgress,\n\t\tonProgress?: SessionListProgress,\n\t): Promise {\n\t\tconst customSessionDir =\n\t\t\ttypeof sessionDirOrOnProgress === \"string\" ? normalizePath(sessionDirOrOnProgress) : undefined;\n\t\tconst progress = typeof sessionDirOrOnProgress === \"function\" ? sessionDirOrOnProgress : onProgress;\n\t\tif (customSessionDir) {\n\t\t\tconst sessions = await listSessionsFromDir(customSessionDir, progress);\n\t\t\tsessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());\n\t\t\treturn sessions;\n\t\t}\n\n\t\tconst sessionsDir = getSessionsDir();\n\n\t\ttry {\n\t\t\tif (!existsSync(sessionsDir)) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tconst entries = await readdir(sessionsDir, { withFileTypes: true });\n\t\t\tconst dirs = entries.filter((e) => e.isDirectory()).map((e) => join(sessionsDir, e.name));\n\n\t\t\t// Count total files first for accurate progress\n\t\t\tlet totalFiles = 0;\n\t\t\tconst dirFiles: string[][] = [];\n\t\t\tfor (const dir of dirs) {\n\t\t\t\ttry {\n\t\t\t\t\tconst files = (await readdir(dir)).filter((f) => f.endsWith(\".jsonl\"));\n\t\t\t\t\tdirFiles.push(files.map((f) => join(dir, f)));\n\t\t\t\t\ttotalFiles += files.length;\n\t\t\t\t} catch {\n\t\t\t\t\tdirFiles.push([]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Process all files with progress tracking\n\t\t\tlet loaded = 0;\n\t\t\tconst sessions: SessionInfo[] = [];\n\t\t\tconst allFiles = dirFiles.flat();\n\n\t\t\tconst results = await buildSessionInfosWithConcurrency(allFiles, () => {\n\t\t\t\tloaded++;\n\t\t\t\tprogress?.(loaded, totalFiles);\n\t\t\t});\n\n\t\t\tfor (const info of results) {\n\t\t\t\tif (info) {\n\t\t\t\t\tsessions.push(info);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());\n\t\t\treturn sessions;\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/settings-manager.d.ts b/dist/core/settings-manager.d.ts new file mode 100644 index 0000000..3922a19 --- /dev/null +++ b/dist/core/settings-manager.d.ts @@ -0,0 +1,297 @@ +import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; +import type { Transport } from "@earendil-works/pi-ai"; +export interface CompactionSettings { + enabled?: boolean; + reserveTokens?: number; + keepRecentTokens?: number; +} +export interface BranchSummarySettings { + reserveTokens?: number; + skipPrompt?: boolean; +} +export interface ProviderRetrySettings { + timeoutMs?: number; + maxRetries?: number; + maxRetryDelayMs?: number; +} +export interface RetrySettings { + enabled?: boolean; + maxRetries?: number; + baseDelayMs?: number; + provider?: ProviderRetrySettings; +} +export interface TerminalSettings { + showImages?: boolean; + imageWidthCells?: number; + clearOnShrink?: boolean; + showTerminalProgress?: boolean; +} +export interface ImageSettings { + autoResize?: boolean; + blockImages?: boolean; +} +export interface ThinkingBudgetsSettings { + minimal?: number; + low?: number; + medium?: number; + high?: number; +} +export interface MarkdownSettings { + codeBlockIndent?: string; +} +export interface WarningSettings { + anthropicExtraUsage?: boolean; +} +export type DefaultProjectTrust = "ask" | "always" | "never"; +export type TransportSetting = Transport; +/** + * Package source for npm/git packages. + * - String form: load all resources from the package + * - Object form: filter which resources to load + * - autoload=false: start empty and only apply explicit resource patterns + */ +export type PackageSource = string | { + source: string; + autoload?: boolean; + extensions?: string[]; + skills?: string[]; + prompts?: string[]; + themes?: string[]; +}; +export interface Settings { + lastChangelogVersion?: string; + defaultProvider?: string; + defaultModel?: string; + defaultThinkingLevel?: ThinkingLevel; + transport?: TransportSetting; + steeringMode?: "all" | "one-at-a-time"; + followUpMode?: "all" | "one-at-a-time"; + theme?: string; + compaction?: CompactionSettings; + branchSummary?: BranchSummarySettings; + retry?: RetrySettings; + hideThinkingBlock?: boolean; + showCacheMissNotices?: boolean; + externalEditor?: string; + shellPath?: string; + quietStartup?: boolean; + defaultProjectTrust?: DefaultProjectTrust; + shellCommandPrefix?: string; + npmCommand?: string[]; + collapseChangelog?: boolean; + enableInstallTelemetry?: boolean; + enableAnalytics?: boolean; + trackingId?: string; + packages?: PackageSource[]; + extensions?: string[]; + skills?: string[]; + prompts?: string[]; + themes?: string[]; + enableSkillCommands?: boolean; + terminal?: TerminalSettings; + images?: ImageSettings; + enabledModels?: string[]; + doubleEscapeAction?: "fork" | "tree" | "none"; + treeFilterMode?: "default" | "no-tools" | "user-only" | "labeled-only" | "all"; + thinkingBudgets?: ThinkingBudgetsSettings; + editorPaddingX?: number; + outputPad?: 0 | 1; + autocompleteMaxVisible?: number; + showHardwareCursor?: boolean; + markdown?: MarkdownSettings; + warnings?: WarningSettings; + sessionDir?: string; + httpProxy?: string; + httpIdleTimeoutMs?: number; + websocketConnectTimeoutMs?: number; +} +export type SettingsScope = "global" | "project"; +export interface SettingsManagerCreateOptions { + projectTrusted?: boolean; +} +export interface SettingsStorage { + withLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void; +} +export interface SettingsError { + scope: SettingsScope; + error: Error; +} +export declare class FileSettingsStorage implements SettingsStorage { + private globalSettingsPath; + private projectSettingsPath; + constructor(cwd: string, agentDir: string); + private acquireLockSyncWithRetry; + withLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void; +} +export declare class InMemorySettingsStorage implements SettingsStorage { + private global; + private project; + withLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void; +} +export declare class SettingsManager { + private storage; + private globalSettings; + private projectSettings; + private settings; + private projectTrusted; + private modifiedFields; + private modifiedNestedFields; + private modifiedProjectFields; + private modifiedProjectNestedFields; + private globalSettingsLoadError; + private projectSettingsLoadError; + private writeQueue; + private errors; + private constructor(); + /** Create a SettingsManager that loads from files */ + static create(cwd: string, agentDir?: string, options?: SettingsManagerCreateOptions): SettingsManager; + /** Create a SettingsManager from an arbitrary storage backend */ + static fromStorage(storage: SettingsStorage, options?: SettingsManagerCreateOptions): SettingsManager; + /** Create an in-memory SettingsManager (no file I/O) */ + static inMemory(settings?: Partial, options?: SettingsManagerCreateOptions): SettingsManager; + private static loadFromStorage; + private static tryLoadFromStorage; + /** Migrate old settings format to new format */ + private static migrateSettings; + getGlobalSettings(): Settings; + getProjectSettings(): Settings; + isProjectTrusted(): boolean; + setProjectTrusted(trusted: boolean): void; + reload(): Promise; + /** Apply additional overrides on top of current settings */ + applyOverrides(overrides: Partial): void; + /** Mark a global field as modified during this session */ + private markModified; + /** Mark a project field as modified during this session */ + private markProjectModified; + private assertProjectTrustedForWrite; + private recordError; + private clearModifiedScope; + private enqueueWrite; + private cloneModifiedNestedFields; + private persistScopedSettings; + private save; + private saveProjectSettings; + private updateProjectSettings; + flush(): Promise; + drainErrors(): SettingsError[]; + getLastChangelogVersion(): string | undefined; + setLastChangelogVersion(version: string): void; + getSessionDir(): string | undefined; + getDefaultProvider(): string | undefined; + getDefaultModel(): string | undefined; + setDefaultProvider(provider: string): void; + setDefaultModel(modelId: string): void; + setDefaultModelAndProvider(provider: string, modelId: string): void; + getSteeringMode(): "all" | "one-at-a-time"; + setSteeringMode(mode: "all" | "one-at-a-time"): void; + getFollowUpMode(): "all" | "one-at-a-time"; + setFollowUpMode(mode: "all" | "one-at-a-time"): void; + getThemeSetting(): string | undefined; + getTheme(): string | undefined; + setTheme(theme: string): void; + getDefaultThinkingLevel(): ThinkingLevel | undefined; + setDefaultThinkingLevel(level: ThinkingLevel): void; + getTransport(): TransportSetting; + setTransport(transport: TransportSetting): void; + getCompactionEnabled(): boolean; + setCompactionEnabled(enabled: boolean): void; + getCompactionReserveTokens(): number; + getCompactionKeepRecentTokens(): number; + getCompactionSettings(): { + enabled: boolean; + reserveTokens: number; + keepRecentTokens: number; + }; + getBranchSummarySettings(): { + reserveTokens: number; + skipPrompt: boolean; + }; + getBranchSummarySkipPrompt(): boolean; + getRetryEnabled(): boolean; + setRetryEnabled(enabled: boolean): void; + getRetrySettings(): { + enabled: boolean; + maxRetries: number; + baseDelayMs: number; + }; + getHttpIdleTimeoutMs(): number; + setHttpIdleTimeoutMs(timeoutMs: number): void; + getProviderRetrySettings(): { + timeoutMs?: number; + maxRetries?: number; + maxRetryDelayMs: number; + }; + getWebSocketConnectTimeoutMs(): number | undefined; + getHideThinkingBlock(): boolean; + getShowCacheMissNotices(): boolean; + getExternalEditorCommand(): string; + setHideThinkingBlock(hide: boolean): void; + setShowCacheMissNotices(show: boolean): void; + getShellPath(): string | undefined; + setShellPath(path: string | undefined): void; + getQuietStartup(): boolean; + setQuietStartup(quiet: boolean): void; + getDefaultProjectTrust(): DefaultProjectTrust; + setDefaultProjectTrust(defaultProjectTrust: DefaultProjectTrust): void; + getShellCommandPrefix(): string | undefined; + setShellCommandPrefix(prefix: string | undefined): void; + getNpmCommand(): string[] | undefined; + setNpmCommand(command: string[] | undefined): void; + getCollapseChangelog(): boolean; + setCollapseChangelog(collapse: boolean): void; + getEnableInstallTelemetry(): boolean; + setEnableInstallTelemetry(enabled: boolean): void; + getEnableAnalytics(): boolean; + getTrackingId(): string | undefined; + /** Set the analytics opt-in preference; generates a tracking identifier on first opt-in */ + setEnableAnalytics(enabled: boolean): void; + getPackages(): PackageSource[]; + setPackages(packages: PackageSource[]): void; + setProjectPackages(packages: PackageSource[]): void; + getExtensionPaths(): string[]; + setExtensionPaths(paths: string[]): void; + setProjectExtensionPaths(paths: string[]): void; + getSkillPaths(): string[]; + setSkillPaths(paths: string[]): void; + setProjectSkillPaths(paths: string[]): void; + getPromptTemplatePaths(): string[]; + setPromptTemplatePaths(paths: string[]): void; + setProjectPromptTemplatePaths(paths: string[]): void; + getThemePaths(): string[]; + setThemePaths(paths: string[]): void; + setProjectThemePaths(paths: string[]): void; + getEnableSkillCommands(): boolean; + setEnableSkillCommands(enabled: boolean): void; + getThinkingBudgets(): ThinkingBudgetsSettings | undefined; + getShowImages(): boolean; + setShowImages(show: boolean): void; + getImageWidthCells(): number; + setImageWidthCells(width: number): void; + getClearOnShrink(): boolean; + setClearOnShrink(enabled: boolean): void; + getShowTerminalProgress(): boolean; + setShowTerminalProgress(enabled: boolean): void; + getImageAutoResize(): boolean; + setImageAutoResize(enabled: boolean): void; + getBlockImages(): boolean; + setBlockImages(blocked: boolean): void; + getEnabledModels(): string[] | undefined; + setEnabledModels(patterns: string[] | undefined): void; + getDoubleEscapeAction(): "fork" | "tree" | "none"; + setDoubleEscapeAction(action: "fork" | "tree" | "none"): void; + getTreeFilterMode(): "default" | "no-tools" | "user-only" | "labeled-only" | "all"; + setTreeFilterMode(mode: "default" | "no-tools" | "user-only" | "labeled-only" | "all"): void; + getShowHardwareCursor(): boolean; + setShowHardwareCursor(enabled: boolean): void; + getEditorPaddingX(): number; + setEditorPaddingX(padding: number): void; + getOutputPad(): 0 | 1; + setOutputPad(padding: 0 | 1): void; + getAutocompleteMaxVisible(): number; + setAutocompleteMaxVisible(maxVisible: number): void; + getCodeBlockIndent(): string; + getWarnings(): WarningSettings; + setWarnings(warnings: WarningSettings): void; +} +//# sourceMappingURL=settings-manager.d.ts.map \ No newline at end of file diff --git a/dist/core/settings-manager.d.ts.map b/dist/core/settings-manager.d.ts.map new file mode 100644 index 0000000..287efe9 --- /dev/null +++ b/dist/core/settings-manager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"settings-manager.d.ts","sourceRoot":"","sources":["../../src/core/settings-manager.ts"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G,IAAI,CAI5C;IAED,iBAAiB,IAAI,MAAM,CAE1B;IAED,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAIvC;IAED,YAAY,IAAI,CAAC,GAAG,CAAC,CAEpB;IAED,YAAY,CAAC,OAAO,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,CAIjC;IAED,yBAAyB,IAAI,MAAM,CAElC;IAED,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAIlD;IAED,kBAAkB,IAAI,MAAM,CAE3B;IAED,WAAW,IAAI,eAAe,CAE7B;IAED,WAAW,CAAC,QAAQ,EAAE,eAAe,GAAG,IAAI,CAI3C;CACD","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Transport } from \"@earendil-works/pi-ai\";\nimport { randomUUID } from \"crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport { DEFAULT_HTTP_IDLE_TIMEOUT_MS, parseHttpIdleTimeoutMs } from \"./http-dispatcher.ts\";\n\nexport interface CompactionSettings {\n\tenabled?: boolean; // default: true\n\treserveTokens?: number; // default: 16384\n\tkeepRecentTokens?: number; // default: 20000\n}\n\nexport interface BranchSummarySettings {\n\treserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response)\n\tskipPrompt?: boolean; // default: false - when true, skips \"Summarize branch?\" prompt and defaults to no summary\n}\n\nexport interface ProviderRetrySettings {\n\ttimeoutMs?: number; // SDK/provider request timeout in milliseconds\n\tmaxRetries?: number; // SDK/provider retry attempts\n\tmaxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing)\n}\n\nexport interface RetrySettings {\n\tenabled?: boolean; // default: true\n\tmaxRetries?: number; // default: 3\n\tbaseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s)\n\tprovider?: ProviderRetrySettings;\n}\n\nexport interface TerminalSettings {\n\tshowImages?: boolean; // default: true (only relevant if terminal supports images)\n\timageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells)\n\tclearOnShrink?: boolean; // default: false (clear empty rows when content shrinks)\n\tshowTerminalProgress?: boolean; // default: false (OSC 9;4 terminal progress indicators)\n}\n\nexport interface ImageSettings {\n\tautoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility)\n\tblockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers\n}\n\nexport interface ThinkingBudgetsSettings {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\nexport interface MarkdownSettings {\n\tcodeBlockIndent?: string; // default: \" \"\n}\n\nexport interface WarningSettings {\n\tanthropicExtraUsage?: boolean; // default: true\n}\n\nexport type DefaultProjectTrust = \"ask\" | \"always\" | \"never\";\n\nexport type TransportSetting = Transport;\n\n/**\n * Package source for npm/git packages.\n * - String form: load all resources from the package\n * - Object form: filter which resources to load\n * - autoload=false: start empty and only apply explicit resource patterns\n */\nexport type PackageSource =\n\t| string\n\t| {\n\t\t\tsource: string;\n\t\t\tautoload?: boolean;\n\t\t\textensions?: string[];\n\t\t\tskills?: string[];\n\t\t\tprompts?: string[];\n\t\t\tthemes?: string[];\n\t };\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n\tdefaultThinkingLevel?: ThinkingLevel;\n\ttransport?: TransportSetting; // default: \"auto\"\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\ttheme?: string;\n\tcompaction?: CompactionSettings;\n\tbranchSummary?: BranchSummarySettings;\n\tretry?: RetrySettings;\n\thideThinkingBlock?: boolean;\n\tshowCacheMissNotices?: boolean; // default: false - show transcript notices for significant prompt-cache misses\n\texternalEditor?: string; // Command for Ctrl+G external editor; takes precedence over VISUAL/EDITOR\n\tshellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows); supports leading ~ expansion\n\tquietStartup?: boolean;\n\tdefaultProjectTrust?: DefaultProjectTrust; // default: \"ask\"; global setting only\n\tshellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., \"shopt -s expand_aliases\" for alias support)\n\tnpmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., [\"mise\", \"exec\", \"node@20\", \"--\", \"npm\"])\n\tcollapseChangelog?: boolean; // Show condensed changelog after update (use /changelog for full)\n\tenableInstallTelemetry?: boolean; // default: true - anonymous version/update ping after changelog-detected updates\n\tenableAnalytics?: boolean; // default: false - opt-in analytics data sharing\n\ttrackingId?: string; // analytics tracking identifier, generated when analytics is enabled\n\tpackages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)\n\textensions?: string[]; // Array of local extension file paths or directories\n\tskills?: string[]; // Array of local skill file paths or directories\n\tprompts?: string[]; // Array of local prompt template paths or directories\n\tthemes?: string[]; // Array of local theme file paths or directories\n\tenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands\n\tterminal?: TerminalSettings;\n\timages?: ImageSettings;\n\tenabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag)\n\tdoubleEscapeAction?: \"fork\" | \"tree\" | \"none\"; // Action for double-escape with empty editor (default: \"tree\")\n\ttreeFilterMode?: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"; // Default filter when opening /tree\n\tthinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels\n\teditorPaddingX?: number; // Horizontal padding for input editor (default: 0)\n\toutputPad?: 0 | 1; // Horizontal padding for chat message output (default: 1)\n\tautocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5)\n\tshowHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME\n\tmarkdown?: MarkdownSettings;\n\twarnings?: WarningSettings;\n\tsessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag)\n\thttpProxy?: string; // Proxy URL applied as HTTP_PROXY and HTTPS_PROXY for Pi-managed HTTP clients\n\thttpIdleTimeoutMs?: number; // HTTP header/body idle timeout in milliseconds; 0 disables it\n\twebsocketConnectTimeoutMs?: number; // WebSocket connect/open handshake timeout in milliseconds; 0 disables it\n}\n\n/** Deep merge settings: project/overrides take precedence, nested objects merge recursively */\nfunction deepMergeSettings(base: Settings, overrides: Settings): Settings {\n\tconst result: Settings = { ...base };\n\n\tfor (const key of Object.keys(overrides) as (keyof Settings)[]) {\n\t\tconst overrideValue = overrides[key];\n\t\tconst baseValue = base[key];\n\n\t\tif (overrideValue === undefined) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// For nested objects, merge recursively\n\t\tif (\n\t\t\ttypeof overrideValue === \"object\" &&\n\t\t\toverrideValue !== null &&\n\t\t\t!Array.isArray(overrideValue) &&\n\t\t\ttypeof baseValue === \"object\" &&\n\t\t\tbaseValue !== null &&\n\t\t\t!Array.isArray(baseValue)\n\t\t) {\n\t\t\t(result as Record)[key] = { ...baseValue, ...overrideValue };\n\t\t} else {\n\t\t\t// For primitives and arrays, override value wins\n\t\t\t(result as Record)[key] = overrideValue;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction parseTimeoutSetting(value: unknown, settingName: string): number | undefined {\n\tconst timeoutMs = parseHttpIdleTimeoutMs(value);\n\tif (timeoutMs !== undefined) {\n\t\treturn timeoutMs;\n\t}\n\tif (value !== undefined) {\n\t\tthrow new Error(`Invalid ${settingName} setting: ${String(value)}`);\n\t}\n\treturn undefined;\n}\n\nexport type SettingsScope = \"global\" | \"project\";\n\nexport interface SettingsManagerCreateOptions {\n\tprojectTrusted?: boolean;\n}\n\nexport interface SettingsStorage {\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void;\n}\n\nexport interface SettingsError {\n\tscope: SettingsScope;\n\terror: Error;\n}\n\nexport class FileSettingsStorage implements SettingsStorage {\n\tprivate globalSettingsPath: string;\n\tprivate projectSettingsPath: string;\n\n\tconstructor(cwd: string, agentDir: string) {\n\t\tconst resolvedCwd = resolvePath(cwd);\n\t\tconst resolvedAgentDir = resolvePath(agentDir);\n\t\tthis.globalSettingsPath = join(resolvedAgentDir, \"settings.json\");\n\t\tthis.projectSettingsPath = join(resolvedCwd, CONFIG_DIR_NAME, \"settings.json\");\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire settings lock\");\n\t}\n\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void {\n\t\tconst path = scope === \"global\" ? this.globalSettingsPath : this.projectSettingsPath;\n\t\tconst dir = dirname(path);\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\t// Only create directory and lock if file exists or we need to write\n\t\t\tconst fileExists = existsSync(path);\n\t\t\tif (fileExists) {\n\t\t\t\trelease = this.acquireLockSyncWithRetry(path);\n\t\t\t}\n\t\t\tconst current = fileExists ? readFileSync(path, \"utf-8\") : undefined;\n\t\t\tconst next = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\t// Only create directory when we actually need to write\n\t\t\t\tif (!existsSync(dir)) {\n\t\t\t\t\tmkdirSync(dir, { recursive: true });\n\t\t\t\t}\n\t\t\t\tif (!release) {\n\t\t\t\t\trelease = this.acquireLockSyncWithRetry(path);\n\t\t\t\t}\n\t\t\t\twriteFileSync(path, next, \"utf-8\");\n\t\t\t}\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemorySettingsStorage implements SettingsStorage {\n\tprivate global: string | undefined;\n\tprivate project: string | undefined;\n\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void {\n\t\tconst current = scope === \"global\" ? this.global : this.project;\n\t\tconst next = fn(current);\n\t\tif (next !== undefined) {\n\t\t\tif (scope === \"global\") {\n\t\t\t\tthis.global = next;\n\t\t\t} else {\n\t\t\t\tthis.project = next;\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class SettingsManager {\n\tprivate storage: SettingsStorage;\n\tprivate globalSettings: Settings;\n\tprivate projectSettings: Settings;\n\tprivate settings: Settings;\n\tprivate projectTrusted: boolean;\n\tprivate modifiedFields = new Set(); // Track global fields modified during session\n\tprivate modifiedNestedFields = new Map>(); // Track global nested field modifications\n\tprivate modifiedProjectFields = new Set(); // Track project fields modified during session\n\tprivate modifiedProjectNestedFields = new Map>(); // Track project nested field modifications\n\tprivate globalSettingsLoadError: Error | null = null; // Track if global settings file had parse errors\n\tprivate projectSettingsLoadError: Error | null = null; // Track if project settings file had parse errors\n\tprivate writeQueue: Promise = Promise.resolve();\n\tprivate errors: SettingsError[];\n\n\tprivate constructor(\n\t\tstorage: SettingsStorage,\n\t\tinitialGlobal: Settings,\n\t\tinitialProject: Settings,\n\t\tglobalLoadError: Error | null = null,\n\t\tprojectLoadError: Error | null = null,\n\t\tinitialErrors: SettingsError[] = [],\n\t\tprojectTrusted = true,\n\t) {\n\t\tthis.storage = storage;\n\t\tthis.globalSettings = initialGlobal;\n\t\tthis.projectSettings = initialProject;\n\t\tthis.projectTrusted = projectTrusted;\n\t\tthis.globalSettingsLoadError = globalLoadError;\n\t\tthis.projectSettingsLoadError = projectLoadError;\n\t\tthis.errors = [...initialErrors];\n\t\tthis.settings = deepMergeSettings(this.globalSettings, this.projectSettings);\n\t}\n\n\t/** Create a SettingsManager that loads from files */\n\tstatic create(\n\t\tcwd: string,\n\t\tagentDir: string = getAgentDir(),\n\t\toptions: SettingsManagerCreateOptions = {},\n\t): SettingsManager {\n\t\tconst storage = new FileSettingsStorage(cwd, agentDir);\n\t\treturn SettingsManager.fromStorage(storage, options);\n\t}\n\n\t/** Create a SettingsManager from an arbitrary storage backend */\n\tstatic fromStorage(storage: SettingsStorage, options: SettingsManagerCreateOptions = {}): SettingsManager {\n\t\tconst projectTrusted = options.projectTrusted ?? true;\n\t\tconst globalLoad = SettingsManager.tryLoadFromStorage(storage, \"global\");\n\t\tconst projectLoad = SettingsManager.tryLoadFromStorage(storage, \"project\", projectTrusted);\n\t\tconst initialErrors: SettingsError[] = [];\n\t\tif (globalLoad.error) {\n\t\t\tinitialErrors.push({ scope: \"global\", error: globalLoad.error });\n\t\t}\n\t\tif (projectLoad.error) {\n\t\t\tinitialErrors.push({ scope: \"project\", error: projectLoad.error });\n\t\t}\n\n\t\treturn new SettingsManager(\n\t\t\tstorage,\n\t\t\tglobalLoad.settings,\n\t\t\tprojectLoad.settings,\n\t\t\tglobalLoad.error,\n\t\t\tprojectLoad.error,\n\t\t\tinitialErrors,\n\t\t\tprojectTrusted,\n\t\t);\n\t}\n\n\t/** Create an in-memory SettingsManager (no file I/O) */\n\tstatic inMemory(settings: Partial = {}, options: SettingsManagerCreateOptions = {}): SettingsManager {\n\t\tconst storage = new InMemorySettingsStorage();\n\t\tconst initialSettings = SettingsManager.migrateSettings(structuredClone(settings) as Record);\n\t\tstorage.withLock(\"global\", () => JSON.stringify(initialSettings, null, 2));\n\t\treturn SettingsManager.fromStorage(storage, options);\n\t}\n\n\tprivate static loadFromStorage(storage: SettingsStorage, scope: SettingsScope, projectTrusted = true): Settings {\n\t\tif (scope === \"project\" && !projectTrusted) {\n\t\t\treturn {};\n\t\t}\n\n\t\tlet content: string | undefined;\n\t\tstorage.withLock(scope, (current) => {\n\t\t\tcontent = current;\n\t\t\treturn undefined;\n\t\t});\n\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\tconst settings = JSON.parse(content);\n\t\treturn SettingsManager.migrateSettings(settings);\n\t}\n\n\tprivate static tryLoadFromStorage(\n\t\tstorage: SettingsStorage,\n\t\tscope: SettingsScope,\n\t\tprojectTrusted = true,\n\t): { settings: Settings; error: Error | null } {\n\t\ttry {\n\t\t\treturn { settings: SettingsManager.loadFromStorage(storage, scope, projectTrusted), error: null };\n\t\t} catch (error) {\n\t\t\treturn { settings: {}, error: error as Error };\n\t\t}\n\t}\n\n\t/** Migrate old settings format to new format */\n\tprivate static migrateSettings(settings: Record): Settings {\n\t\t// Migrate queueMode -> steeringMode\n\t\tif (\"queueMode\" in settings && !(\"steeringMode\" in settings)) {\n\t\t\tsettings.steeringMode = settings.queueMode;\n\t\t\tdelete settings.queueMode;\n\t\t}\n\n\t\t// Migrate legacy websockets boolean -> transport enum\n\t\tif (!(\"transport\" in settings) && typeof settings.websockets === \"boolean\") {\n\t\t\tsettings.transport = settings.websockets ? \"websocket\" : \"sse\";\n\t\t\tdelete settings.websockets;\n\t\t}\n\n\t\t// Migrate old skills object format to new array format\n\t\tif (\n\t\t\t\"skills\" in settings &&\n\t\t\ttypeof settings.skills === \"object\" &&\n\t\t\tsettings.skills !== null &&\n\t\t\t!Array.isArray(settings.skills)\n\t\t) {\n\t\t\tconst skillsSettings = settings.skills as {\n\t\t\t\tenableSkillCommands?: boolean;\n\t\t\t\tcustomDirectories?: unknown;\n\t\t\t};\n\t\t\tif (skillsSettings.enableSkillCommands !== undefined && settings.enableSkillCommands === undefined) {\n\t\t\t\tsettings.enableSkillCommands = skillsSettings.enableSkillCommands;\n\t\t\t}\n\t\t\tif (Array.isArray(skillsSettings.customDirectories) && skillsSettings.customDirectories.length > 0) {\n\t\t\t\tsettings.skills = skillsSettings.customDirectories;\n\t\t\t} else {\n\t\t\t\tdelete settings.skills;\n\t\t\t}\n\t\t}\n\n\t\t// Migrate retry.maxDelayMs -> retry.provider.maxRetryDelayMs\n\t\tif (\n\t\t\t\"retry\" in settings &&\n\t\t\ttypeof settings.retry === \"object\" &&\n\t\t\tsettings.retry !== null &&\n\t\t\t!Array.isArray(settings.retry)\n\t\t) {\n\t\t\tconst retrySettings = settings.retry as Record;\n\t\t\tconst providerSettings =\n\t\t\t\ttypeof retrySettings.provider === \"object\" && retrySettings.provider !== null\n\t\t\t\t\t? (retrySettings.provider as Record)\n\t\t\t\t\t: undefined;\n\t\t\tif (\n\t\t\t\ttypeof retrySettings.maxDelayMs === \"number\" &&\n\t\t\t\t(providerSettings?.maxRetryDelayMs === undefined || providerSettings?.maxRetryDelayMs === null)\n\t\t\t) {\n\t\t\t\tretrySettings.provider = {\n\t\t\t\t\t...(providerSettings ?? {}),\n\t\t\t\t\tmaxRetryDelayMs: retrySettings.maxDelayMs,\n\t\t\t\t};\n\t\t\t}\n\t\t\tdelete retrySettings.maxDelayMs;\n\t\t}\n\n\t\treturn settings as Settings;\n\t}\n\n\tgetGlobalSettings(): Settings {\n\t\treturn structuredClone(this.globalSettings);\n\t}\n\n\tgetProjectSettings(): Settings {\n\t\treturn structuredClone(this.projectSettings);\n\t}\n\n\tisProjectTrusted(): boolean {\n\t\treturn this.projectTrusted;\n\t}\n\n\tsetProjectTrusted(trusted: boolean): void {\n\t\tif (this.projectTrusted === trusted) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.projectTrusted = trusted;\n\t\tthis.modifiedProjectFields.clear();\n\t\tthis.modifiedProjectNestedFields.clear();\n\n\t\tif (!trusted) {\n\t\t\tthis.projectSettings = {};\n\t\t\tthis.projectSettingsLoadError = null;\n\t\t\tthis.settings = deepMergeSettings(this.globalSettings, this.projectSettings);\n\t\t\treturn;\n\t\t}\n\n\t\tconst projectLoad = SettingsManager.tryLoadFromStorage(this.storage, \"project\", trusted);\n\t\tthis.projectSettings = projectLoad.settings;\n\t\tthis.projectSettingsLoadError = projectLoad.error;\n\t\tif (projectLoad.error) {\n\t\t\tthis.recordError(\"project\", projectLoad.error);\n\t\t}\n\t\tthis.settings = deepMergeSettings(this.globalSettings, this.projectSettings);\n\t}\n\n\tasync reload(): Promise {\n\t\tawait this.writeQueue;\n\t\tconst globalLoad = SettingsManager.tryLoadFromStorage(this.storage, \"global\");\n\t\tif (!globalLoad.error) {\n\t\t\tthis.globalSettings = globalLoad.settings;\n\t\t\tthis.globalSettingsLoadError = null;\n\t\t} else {\n\t\t\tthis.globalSettingsLoadError = globalLoad.error;\n\t\t\tthis.recordError(\"global\", globalLoad.error);\n\t\t}\n\n\t\tthis.modifiedFields.clear();\n\t\tthis.modifiedNestedFields.clear();\n\t\tthis.modifiedProjectFields.clear();\n\t\tthis.modifiedProjectNestedFields.clear();\n\n\t\tconst projectLoad = SettingsManager.tryLoadFromStorage(this.storage, \"project\", this.projectTrusted);\n\t\tif (!projectLoad.error) {\n\t\t\tthis.projectSettings = projectLoad.settings;\n\t\t\tthis.projectSettingsLoadError = null;\n\t\t} else {\n\t\t\tthis.projectSettingsLoadError = projectLoad.error;\n\t\t\tthis.recordError(\"project\", projectLoad.error);\n\t\t}\n\n\t\tthis.settings = deepMergeSettings(this.globalSettings, this.projectSettings);\n\t}\n\n\t/** Apply additional overrides on top of current settings */\n\tapplyOverrides(overrides: Partial): void {\n\t\tthis.settings = deepMergeSettings(this.settings, overrides);\n\t}\n\n\t/** Mark a global field as modified during this session */\n\tprivate markModified(field: keyof Settings, nestedKey?: string): void {\n\t\tthis.modifiedFields.add(field);\n\t\tif (nestedKey) {\n\t\t\tif (!this.modifiedNestedFields.has(field)) {\n\t\t\t\tthis.modifiedNestedFields.set(field, new Set());\n\t\t\t}\n\t\t\tthis.modifiedNestedFields.get(field)!.add(nestedKey);\n\t\t}\n\t}\n\n\t/** Mark a project field as modified during this session */\n\tprivate markProjectModified(field: keyof Settings, nestedKey?: string): void {\n\t\tthis.modifiedProjectFields.add(field);\n\t\tif (nestedKey) {\n\t\t\tif (!this.modifiedProjectNestedFields.has(field)) {\n\t\t\t\tthis.modifiedProjectNestedFields.set(field, new Set());\n\t\t\t}\n\t\t\tthis.modifiedProjectNestedFields.get(field)!.add(nestedKey);\n\t\t}\n\t}\n\n\tprivate assertProjectTrustedForWrite(): void {\n\t\tif (!this.projectTrusted) {\n\t\t\tthrow new Error(\"Project is not trusted; refusing to write project settings\");\n\t\t}\n\t}\n\n\tprivate recordError(scope: SettingsScope, error: unknown): void {\n\t\tconst normalizedError = error instanceof Error ? error : new Error(String(error));\n\t\tthis.errors.push({ scope, error: normalizedError });\n\t}\n\n\tprivate clearModifiedScope(scope: SettingsScope): void {\n\t\tif (scope === \"global\") {\n\t\t\tthis.modifiedFields.clear();\n\t\t\tthis.modifiedNestedFields.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.modifiedProjectFields.clear();\n\t\tthis.modifiedProjectNestedFields.clear();\n\t}\n\n\tprivate enqueueWrite(scope: SettingsScope, task: () => void): void {\n\t\tthis.writeQueue = this.writeQueue\n\t\t\t.then(() => {\n\t\t\t\tif (scope === \"project\") {\n\t\t\t\t\tthis.assertProjectTrustedForWrite();\n\t\t\t\t}\n\t\t\t\ttask();\n\t\t\t\tthis.clearModifiedScope(scope);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tthis.recordError(scope, error);\n\t\t\t});\n\t}\n\n\tprivate cloneModifiedNestedFields(source: Map>): Map> {\n\t\tconst snapshot = new Map>();\n\t\tfor (const [key, value] of source.entries()) {\n\t\t\tsnapshot.set(key, new Set(value));\n\t\t}\n\t\treturn snapshot;\n\t}\n\n\tprivate persistScopedSettings(\n\t\tscope: SettingsScope,\n\t\tsnapshotSettings: Settings,\n\t\tmodifiedFields: Set,\n\t\tmodifiedNestedFields: Map>,\n\t): void {\n\t\tthis.storage.withLock(scope, (current) => {\n\t\t\tconst currentFileSettings = current\n\t\t\t\t? SettingsManager.migrateSettings(JSON.parse(current) as Record)\n\t\t\t\t: {};\n\t\t\tconst mergedSettings: Settings = { ...currentFileSettings };\n\t\t\tfor (const field of modifiedFields) {\n\t\t\t\tconst value = snapshotSettings[field];\n\t\t\t\tif (modifiedNestedFields.has(field) && typeof value === \"object\" && value !== null) {\n\t\t\t\t\tconst nestedModified = modifiedNestedFields.get(field)!;\n\t\t\t\t\tconst baseNested = (currentFileSettings[field] as Record) ?? {};\n\t\t\t\t\tconst inMemoryNested = value as Record;\n\t\t\t\t\tconst mergedNested = { ...baseNested };\n\t\t\t\t\tfor (const nestedKey of nestedModified) {\n\t\t\t\t\t\tmergedNested[nestedKey] = inMemoryNested[nestedKey];\n\t\t\t\t\t}\n\t\t\t\t\t(mergedSettings as Record)[field] = mergedNested;\n\t\t\t\t} else {\n\t\t\t\t\t(mergedSettings as Record)[field] = value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn JSON.stringify(mergedSettings, null, 2);\n\t\t});\n\t}\n\n\tprivate save(): void {\n\t\tthis.settings = deepMergeSettings(this.globalSettings, this.projectSettings);\n\n\t\tif (this.globalSettingsLoadError) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst snapshotGlobalSettings = structuredClone(this.globalSettings);\n\t\tconst modifiedFields = new Set(this.modifiedFields);\n\t\tconst modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedNestedFields);\n\n\t\tthis.enqueueWrite(\"global\", () => {\n\t\t\tthis.persistScopedSettings(\"global\", snapshotGlobalSettings, modifiedFields, modifiedNestedFields);\n\t\t});\n\t}\n\n\tprivate saveProjectSettings(settings: Settings): void {\n\t\tthis.assertProjectTrustedForWrite();\n\t\tthis.projectSettings = structuredClone(settings);\n\t\tthis.settings = deepMergeSettings(this.globalSettings, this.projectSettings);\n\n\t\tif (this.projectSettingsLoadError) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst snapshotProjectSettings = structuredClone(this.projectSettings);\n\t\tconst modifiedFields = new Set(this.modifiedProjectFields);\n\t\tconst modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);\n\t\tthis.enqueueWrite(\"project\", () => {\n\t\t\tthis.persistScopedSettings(\"project\", snapshotProjectSettings, modifiedFields, modifiedNestedFields);\n\t\t});\n\t}\n\n\tprivate updateProjectSettings(field: keyof Settings, update: (settings: Settings) => void): void {\n\t\tthis.assertProjectTrustedForWrite();\n\t\tconst projectSettings = structuredClone(this.projectSettings);\n\t\tupdate(projectSettings);\n\t\tthis.markProjectModified(field);\n\t\tthis.saveProjectSettings(projectSettings);\n\t}\n\n\tasync flush(): Promise {\n\t\tawait this.writeQueue;\n\t}\n\n\tdrainErrors(): SettingsError[] {\n\t\tconst drained = [...this.errors];\n\t\tthis.errors = [];\n\t\treturn drained;\n\t}\n\n\tgetLastChangelogVersion(): string | undefined {\n\t\treturn this.settings.lastChangelogVersion;\n\t}\n\n\tsetLastChangelogVersion(version: string): void {\n\t\tthis.globalSettings.lastChangelogVersion = version;\n\t\tthis.markModified(\"lastChangelogVersion\");\n\t\tthis.save();\n\t}\n\n\tgetSessionDir(): string | undefined {\n\t\tconst sessionDir = this.settings.sessionDir;\n\t\treturn sessionDir ? normalizePath(sessionDir) : sessionDir;\n\t}\n\n\tgetDefaultProvider(): string | undefined {\n\t\treturn this.settings.defaultProvider;\n\t}\n\n\tgetDefaultModel(): string | undefined {\n\t\treturn this.settings.defaultModel;\n\t}\n\n\tsetDefaultProvider(provider: string): void {\n\t\tthis.globalSettings.defaultProvider = provider;\n\t\tthis.markModified(\"defaultProvider\");\n\t\tthis.save();\n\t}\n\n\tsetDefaultModel(modelId: string): void {\n\t\tthis.globalSettings.defaultModel = modelId;\n\t\tthis.markModified(\"defaultModel\");\n\t\tthis.save();\n\t}\n\n\tsetDefaultModelAndProvider(provider: string, modelId: string): void {\n\t\tthis.globalSettings.defaultProvider = provider;\n\t\tthis.globalSettings.defaultModel = modelId;\n\t\tthis.markModified(\"defaultProvider\");\n\t\tthis.markModified(\"defaultModel\");\n\t\tthis.save();\n\t}\n\n\tgetSteeringMode(): \"all\" | \"one-at-a-time\" {\n\t\treturn this.settings.steeringMode || \"one-at-a-time\";\n\t}\n\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void {\n\t\tthis.globalSettings.steeringMode = mode;\n\t\tthis.markModified(\"steeringMode\");\n\t\tthis.save();\n\t}\n\n\tgetFollowUpMode(): \"all\" | \"one-at-a-time\" {\n\t\treturn this.settings.followUpMode || \"one-at-a-time\";\n\t}\n\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void {\n\t\tthis.globalSettings.followUpMode = mode;\n\t\tthis.markModified(\"followUpMode\");\n\t\tthis.save();\n\t}\n\n\tgetThemeSetting(): string | undefined {\n\t\tconst value = this.settings.theme;\n\t\tif (typeof value === \"string\") return value;\n\t\treturn undefined;\n\t}\n\n\tgetTheme(): string | undefined {\n\t\tconst theme = this.getThemeSetting();\n\t\treturn theme?.includes(\"/\") ? undefined : theme;\n\t}\n\n\tsetTheme(theme: string): void {\n\t\tthis.globalSettings.theme = theme;\n\t\tthis.markModified(\"theme\");\n\t\tthis.save();\n\t}\n\n\tgetDefaultThinkingLevel(): ThinkingLevel | undefined {\n\t\treturn this.settings.defaultThinkingLevel;\n\t}\n\n\tsetDefaultThinkingLevel(level: ThinkingLevel): void {\n\t\tthis.globalSettings.defaultThinkingLevel = level;\n\t\tthis.markModified(\"defaultThinkingLevel\");\n\t\tthis.save();\n\t}\n\n\tgetTransport(): TransportSetting {\n\t\treturn this.settings.transport ?? \"auto\";\n\t}\n\n\tsetTransport(transport: TransportSetting): void {\n\t\tthis.globalSettings.transport = transport;\n\t\tthis.markModified(\"transport\");\n\t\tthis.save();\n\t}\n\n\tgetCompactionEnabled(): boolean {\n\t\treturn this.settings.compaction?.enabled ?? true;\n\t}\n\n\tsetCompactionEnabled(enabled: boolean): void {\n\t\tif (!this.globalSettings.compaction) {\n\t\t\tthis.globalSettings.compaction = {};\n\t\t}\n\t\tthis.globalSettings.compaction.enabled = enabled;\n\t\tthis.markModified(\"compaction\", \"enabled\");\n\t\tthis.save();\n\t}\n\n\tgetCompactionReserveTokens(): number {\n\t\treturn this.settings.compaction?.reserveTokens ?? 16384;\n\t}\n\n\tgetCompactionKeepRecentTokens(): number {\n\t\treturn this.settings.compaction?.keepRecentTokens ?? 20000;\n\t}\n\n\tgetCompactionSettings(): { enabled: boolean; reserveTokens: number; keepRecentTokens: number } {\n\t\treturn {\n\t\t\tenabled: this.getCompactionEnabled(),\n\t\t\treserveTokens: this.getCompactionReserveTokens(),\n\t\t\tkeepRecentTokens: this.getCompactionKeepRecentTokens(),\n\t\t};\n\t}\n\n\tgetBranchSummarySettings(): { reserveTokens: number; skipPrompt: boolean } {\n\t\treturn {\n\t\t\treserveTokens: this.settings.branchSummary?.reserveTokens ?? 16384,\n\t\t\tskipPrompt: this.settings.branchSummary?.skipPrompt ?? false,\n\t\t};\n\t}\n\n\tgetBranchSummarySkipPrompt(): boolean {\n\t\treturn this.settings.branchSummary?.skipPrompt ?? false;\n\t}\n\n\tgetRetryEnabled(): boolean {\n\t\treturn this.settings.retry?.enabled ?? true;\n\t}\n\n\tsetRetryEnabled(enabled: boolean): void {\n\t\tif (!this.globalSettings.retry) {\n\t\t\tthis.globalSettings.retry = {};\n\t\t}\n\t\tthis.globalSettings.retry.enabled = enabled;\n\t\tthis.markModified(\"retry\", \"enabled\");\n\t\tthis.save();\n\t}\n\n\tgetRetrySettings(): { enabled: boolean; maxRetries: number; baseDelayMs: number } {\n\t\treturn {\n\t\t\tenabled: this.getRetryEnabled(),\n\t\t\tmaxRetries: this.settings.retry?.maxRetries ?? 3,\n\t\t\tbaseDelayMs: this.settings.retry?.baseDelayMs ?? 2000,\n\t\t};\n\t}\n\n\tgetHttpIdleTimeoutMs(): number {\n\t\treturn parseTimeoutSetting(this.settings.httpIdleTimeoutMs, \"httpIdleTimeoutMs\") ?? DEFAULT_HTTP_IDLE_TIMEOUT_MS;\n\t}\n\n\tsetHttpIdleTimeoutMs(timeoutMs: number): void {\n\t\tif (!Number.isFinite(timeoutMs) || timeoutMs < 0) {\n\t\t\tthrow new Error(`Invalid httpIdleTimeoutMs setting: ${String(timeoutMs)}`);\n\t\t}\n\t\tthis.globalSettings.httpIdleTimeoutMs = Math.floor(timeoutMs);\n\t\tthis.markModified(\"httpIdleTimeoutMs\");\n\t\tthis.save();\n\t}\n\n\tgetProviderRetrySettings(): { timeoutMs?: number; maxRetries?: number; maxRetryDelayMs: number } {\n\t\treturn {\n\t\t\ttimeoutMs: this.settings.retry?.provider?.timeoutMs,\n\t\t\tmaxRetries: this.settings.retry?.provider?.maxRetries,\n\t\t\tmaxRetryDelayMs: this.settings.retry?.provider?.maxRetryDelayMs ?? 60000,\n\t\t};\n\t}\n\n\tgetWebSocketConnectTimeoutMs(): number | undefined {\n\t\treturn parseTimeoutSetting(this.settings.websocketConnectTimeoutMs, \"websocketConnectTimeoutMs\");\n\t}\n\n\tgetHideThinkingBlock(): boolean {\n\t\treturn this.settings.hideThinkingBlock ?? false;\n\t}\n\n\tgetShowCacheMissNotices(): boolean {\n\t\treturn this.settings.showCacheMissNotices ?? false;\n\t}\n\n\tgetExternalEditorCommand(): string {\n\t\tconst configuredEditor = this.settings.externalEditor;\n\t\tif (typeof configuredEditor === \"string\" && configuredEditor.trim() !== \"\") {\n\t\t\treturn configuredEditor;\n\t\t}\n\t\tconst environmentEditor = process.env.VISUAL || process.env.EDITOR;\n\t\tif (environmentEditor) {\n\t\t\treturn environmentEditor;\n\t\t}\n\t\treturn process.platform === \"win32\" ? \"notepad\" : \"nano\";\n\t}\n\n\tsetHideThinkingBlock(hide: boolean): void {\n\t\tthis.globalSettings.hideThinkingBlock = hide;\n\t\tthis.markModified(\"hideThinkingBlock\");\n\t\tthis.save();\n\t}\n\n\tsetShowCacheMissNotices(show: boolean): void {\n\t\tthis.globalSettings.showCacheMissNotices = show;\n\t\tthis.markModified(\"showCacheMissNotices\");\n\t\tthis.save();\n\t}\n\n\tgetShellPath(): string | undefined {\n\t\tconst shellPath = this.settings.shellPath;\n\t\treturn shellPath ? normalizePath(shellPath) : shellPath;\n\t}\n\n\tsetShellPath(path: string | undefined): void {\n\t\tthis.globalSettings.shellPath = path;\n\t\tthis.markModified(\"shellPath\");\n\t\tthis.save();\n\t}\n\n\tgetQuietStartup(): boolean {\n\t\treturn this.settings.quietStartup ?? false;\n\t}\n\n\tsetQuietStartup(quiet: boolean): void {\n\t\tthis.globalSettings.quietStartup = quiet;\n\t\tthis.markModified(\"quietStartup\");\n\t\tthis.save();\n\t}\n\n\tgetDefaultProjectTrust(): DefaultProjectTrust {\n\t\tconst value = this.globalSettings.defaultProjectTrust;\n\t\treturn value === \"always\" || value === \"never\" ? value : \"ask\";\n\t}\n\n\tsetDefaultProjectTrust(defaultProjectTrust: DefaultProjectTrust): void {\n\t\tthis.globalSettings.defaultProjectTrust = defaultProjectTrust;\n\t\tthis.markModified(\"defaultProjectTrust\");\n\t\tthis.save();\n\t}\n\n\tgetShellCommandPrefix(): string | undefined {\n\t\treturn this.settings.shellCommandPrefix;\n\t}\n\n\tsetShellCommandPrefix(prefix: string | undefined): void {\n\t\tthis.globalSettings.shellCommandPrefix = prefix;\n\t\tthis.markModified(\"shellCommandPrefix\");\n\t\tthis.save();\n\t}\n\n\tgetNpmCommand(): string[] | undefined {\n\t\treturn this.settings.npmCommand ? [...this.settings.npmCommand] : undefined;\n\t}\n\n\tsetNpmCommand(command: string[] | undefined): void {\n\t\tthis.globalSettings.npmCommand = command ? [...command] : undefined;\n\t\tthis.markModified(\"npmCommand\");\n\t\tthis.save();\n\t}\n\n\tgetCollapseChangelog(): boolean {\n\t\treturn this.settings.collapseChangelog ?? false;\n\t}\n\n\tsetCollapseChangelog(collapse: boolean): void {\n\t\tthis.globalSettings.collapseChangelog = collapse;\n\t\tthis.markModified(\"collapseChangelog\");\n\t\tthis.save();\n\t}\n\n\tgetEnableInstallTelemetry(): boolean {\n\t\treturn this.settings.enableInstallTelemetry ?? true;\n\t}\n\n\tsetEnableInstallTelemetry(enabled: boolean): void {\n\t\tthis.globalSettings.enableInstallTelemetry = enabled;\n\t\tthis.markModified(\"enableInstallTelemetry\");\n\t\tthis.save();\n\t}\n\n\tgetEnableAnalytics(): boolean {\n\t\treturn this.settings.enableAnalytics ?? false;\n\t}\n\n\tgetTrackingId(): string | undefined {\n\t\treturn this.settings.trackingId;\n\t}\n\n\t/** Set the analytics opt-in preference; generates a tracking identifier on first opt-in */\n\tsetEnableAnalytics(enabled: boolean): void {\n\t\tthis.globalSettings.enableAnalytics = enabled;\n\t\tthis.markModified(\"enableAnalytics\");\n\t\tif (enabled && !this.globalSettings.trackingId) {\n\t\t\tthis.globalSettings.trackingId = randomUUID();\n\t\t\tthis.markModified(\"trackingId\");\n\t\t}\n\t\tthis.save();\n\t}\n\n\tgetPackages(): PackageSource[] {\n\t\treturn [...(this.settings.packages ?? [])];\n\t}\n\n\tsetPackages(packages: PackageSource[]): void {\n\t\tthis.globalSettings.packages = packages;\n\t\tthis.markModified(\"packages\");\n\t\tthis.save();\n\t}\n\n\tsetProjectPackages(packages: PackageSource[]): void {\n\t\tthis.updateProjectSettings(\"packages\", (settings) => {\n\t\t\tsettings.packages = packages;\n\t\t});\n\t}\n\n\tgetExtensionPaths(): string[] {\n\t\treturn [...(this.settings.extensions ?? [])];\n\t}\n\n\tsetExtensionPaths(paths: string[]): void {\n\t\tthis.globalSettings.extensions = paths;\n\t\tthis.markModified(\"extensions\");\n\t\tthis.save();\n\t}\n\n\tsetProjectExtensionPaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"extensions\", (settings) => {\n\t\t\tsettings.extensions = paths;\n\t\t});\n\t}\n\n\tgetSkillPaths(): string[] {\n\t\treturn [...(this.settings.skills ?? [])];\n\t}\n\n\tsetSkillPaths(paths: string[]): void {\n\t\tthis.globalSettings.skills = paths;\n\t\tthis.markModified(\"skills\");\n\t\tthis.save();\n\t}\n\n\tsetProjectSkillPaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"skills\", (settings) => {\n\t\t\tsettings.skills = paths;\n\t\t});\n\t}\n\n\tgetPromptTemplatePaths(): string[] {\n\t\treturn [...(this.settings.prompts ?? [])];\n\t}\n\n\tsetPromptTemplatePaths(paths: string[]): void {\n\t\tthis.globalSettings.prompts = paths;\n\t\tthis.markModified(\"prompts\");\n\t\tthis.save();\n\t}\n\n\tsetProjectPromptTemplatePaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"prompts\", (settings) => {\n\t\t\tsettings.prompts = paths;\n\t\t});\n\t}\n\n\tgetThemePaths(): string[] {\n\t\treturn [...(this.settings.themes ?? [])];\n\t}\n\n\tsetThemePaths(paths: string[]): void {\n\t\tthis.globalSettings.themes = paths;\n\t\tthis.markModified(\"themes\");\n\t\tthis.save();\n\t}\n\n\tsetProjectThemePaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"themes\", (settings) => {\n\t\t\tsettings.themes = paths;\n\t\t});\n\t}\n\n\tgetEnableSkillCommands(): boolean {\n\t\treturn this.settings.enableSkillCommands ?? true;\n\t}\n\n\tsetEnableSkillCommands(enabled: boolean): void {\n\t\tthis.globalSettings.enableSkillCommands = enabled;\n\t\tthis.markModified(\"enableSkillCommands\");\n\t\tthis.save();\n\t}\n\n\tgetThinkingBudgets(): ThinkingBudgetsSettings | undefined {\n\t\treturn this.settings.thinkingBudgets;\n\t}\n\n\tgetShowImages(): boolean {\n\t\treturn this.settings.terminal?.showImages ?? true;\n\t}\n\n\tsetShowImages(show: boolean): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.showImages = show;\n\t\tthis.markModified(\"terminal\", \"showImages\");\n\t\tthis.save();\n\t}\n\n\tgetImageWidthCells(): number {\n\t\tconst width = this.settings.terminal?.imageWidthCells;\n\t\tif (typeof width !== \"number\" || !Number.isFinite(width)) {\n\t\t\treturn 60;\n\t\t}\n\t\treturn Math.max(1, Math.floor(width));\n\t}\n\n\tsetImageWidthCells(width: number): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.imageWidthCells = Math.max(1, Math.floor(width));\n\t\tthis.markModified(\"terminal\", \"imageWidthCells\");\n\t\tthis.save();\n\t}\n\n\tgetClearOnShrink(): boolean {\n\t\t// Settings takes precedence, then env var, then default false\n\t\tif (this.settings.terminal?.clearOnShrink !== undefined) {\n\t\t\treturn this.settings.terminal.clearOnShrink;\n\t\t}\n\t\treturn process.env.PI_CLEAR_ON_SHRINK === \"1\";\n\t}\n\n\tsetClearOnShrink(enabled: boolean): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.clearOnShrink = enabled;\n\t\tthis.markModified(\"terminal\", \"clearOnShrink\");\n\t\tthis.save();\n\t}\n\n\tgetShowTerminalProgress(): boolean {\n\t\treturn this.settings.terminal?.showTerminalProgress ?? false;\n\t}\n\n\tsetShowTerminalProgress(enabled: boolean): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.showTerminalProgress = enabled;\n\t\tthis.markModified(\"terminal\", \"showTerminalProgress\");\n\t\tthis.save();\n\t}\n\n\tgetImageAutoResize(): boolean {\n\t\treturn this.settings.images?.autoResize ?? true;\n\t}\n\n\tsetImageAutoResize(enabled: boolean): void {\n\t\tif (!this.globalSettings.images) {\n\t\t\tthis.globalSettings.images = {};\n\t\t}\n\t\tthis.globalSettings.images.autoResize = enabled;\n\t\tthis.markModified(\"images\", \"autoResize\");\n\t\tthis.save();\n\t}\n\n\tgetBlockImages(): boolean {\n\t\treturn this.settings.images?.blockImages ?? false;\n\t}\n\n\tsetBlockImages(blocked: boolean): void {\n\t\tif (!this.globalSettings.images) {\n\t\t\tthis.globalSettings.images = {};\n\t\t}\n\t\tthis.globalSettings.images.blockImages = blocked;\n\t\tthis.markModified(\"images\", \"blockImages\");\n\t\tthis.save();\n\t}\n\n\tgetEnabledModels(): string[] | undefined {\n\t\treturn this.settings.enabledModels;\n\t}\n\n\tsetEnabledModels(patterns: string[] | undefined): void {\n\t\tthis.globalSettings.enabledModels = patterns;\n\t\tthis.markModified(\"enabledModels\");\n\t\tthis.save();\n\t}\n\n\tgetDoubleEscapeAction(): \"fork\" | \"tree\" | \"none\" {\n\t\treturn this.settings.doubleEscapeAction ?? \"tree\";\n\t}\n\n\tsetDoubleEscapeAction(action: \"fork\" | \"tree\" | \"none\"): void {\n\t\tthis.globalSettings.doubleEscapeAction = action;\n\t\tthis.markModified(\"doubleEscapeAction\");\n\t\tthis.save();\n\t}\n\n\tgetTreeFilterMode(): \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\" {\n\t\tconst mode = this.settings.treeFilterMode;\n\t\tconst valid = [\"default\", \"no-tools\", \"user-only\", \"labeled-only\", \"all\"];\n\t\treturn mode && valid.includes(mode) ? mode : \"default\";\n\t}\n\n\tsetTreeFilterMode(mode: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"): void {\n\t\tthis.globalSettings.treeFilterMode = mode;\n\t\tthis.markModified(\"treeFilterMode\");\n\t\tthis.save();\n\t}\n\n\tgetShowHardwareCursor(): boolean {\n\t\treturn this.settings.showHardwareCursor ?? process.env.PI_HARDWARE_CURSOR === \"1\";\n\t}\n\n\tsetShowHardwareCursor(enabled: boolean): void {\n\t\tthis.globalSettings.showHardwareCursor = enabled;\n\t\tthis.markModified(\"showHardwareCursor\");\n\t\tthis.save();\n\t}\n\n\tgetEditorPaddingX(): number {\n\t\treturn this.settings.editorPaddingX ?? 0;\n\t}\n\n\tsetEditorPaddingX(padding: number): void {\n\t\tthis.globalSettings.editorPaddingX = Math.max(0, Math.min(3, Math.floor(padding)));\n\t\tthis.markModified(\"editorPaddingX\");\n\t\tthis.save();\n\t}\n\n\tgetOutputPad(): 0 | 1 {\n\t\treturn this.settings.outputPad === 0 ? 0 : 1;\n\t}\n\n\tsetOutputPad(padding: 0 | 1): void {\n\t\tthis.globalSettings.outputPad = padding;\n\t\tthis.markModified(\"outputPad\");\n\t\tthis.save();\n\t}\n\n\tgetAutocompleteMaxVisible(): number {\n\t\treturn this.settings.autocompleteMaxVisible ?? 5;\n\t}\n\n\tsetAutocompleteMaxVisible(maxVisible: number): void {\n\t\tthis.globalSettings.autocompleteMaxVisible = Math.max(3, Math.min(20, Math.floor(maxVisible)));\n\t\tthis.markModified(\"autocompleteMaxVisible\");\n\t\tthis.save();\n\t}\n\n\tgetCodeBlockIndent(): string {\n\t\treturn this.settings.markdown?.codeBlockIndent ?? \" \";\n\t}\n\n\tgetWarnings(): WarningSettings {\n\t\treturn { ...(this.settings.warnings ?? {}) };\n\t}\n\n\tsetWarnings(warnings: WarningSettings): void {\n\t\tthis.globalSettings.warnings = { ...warnings };\n\t\tthis.markModified(\"warnings\");\n\t\tthis.save();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/settings-manager.js b/dist/core/settings-manager.js new file mode 100644 index 0000000..4021796 --- /dev/null +++ b/dist/core/settings-manager.js @@ -0,0 +1,902 @@ +import { randomUUID } from "crypto"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; +import { dirname, join } from "path"; +import lockfile from "proper-lockfile"; +import { CONFIG_DIR_NAME, getAgentDir } from "../config.js"; +import { normalizePath, resolvePath } from "../utils/paths.js"; +import { DEFAULT_HTTP_IDLE_TIMEOUT_MS, parseHttpIdleTimeoutMs } from "./http-dispatcher.js"; +/** Deep merge settings: project/overrides take precedence, nested objects merge recursively */ +function deepMergeSettings(base, overrides) { + const result = { ...base }; + for (const key of Object.keys(overrides)) { + const overrideValue = overrides[key]; + const baseValue = base[key]; + if (overrideValue === undefined) { + continue; + } + // For nested objects, merge recursively + if (typeof overrideValue === "object" && + overrideValue !== null && + !Array.isArray(overrideValue) && + typeof baseValue === "object" && + baseValue !== null && + !Array.isArray(baseValue)) { + result[key] = { ...baseValue, ...overrideValue }; + } + else { + // For primitives and arrays, override value wins + result[key] = overrideValue; + } + } + return result; +} +function parseTimeoutSetting(value, settingName) { + const timeoutMs = parseHttpIdleTimeoutMs(value); + if (timeoutMs !== undefined) { + return timeoutMs; + } + if (value !== undefined) { + throw new Error(`Invalid ${settingName} setting: ${String(value)}`); + } + return undefined; +} +export class FileSettingsStorage { + globalSettingsPath; + projectSettingsPath; + constructor(cwd, agentDir) { + const resolvedCwd = resolvePath(cwd); + const resolvedAgentDir = resolvePath(agentDir); + this.globalSettingsPath = join(resolvedAgentDir, "settings.json"); + this.projectSettingsPath = join(resolvedCwd, CONFIG_DIR_NAME, "settings.json"); + } + acquireLockSyncWithRetry(path) { + const maxAttempts = 10; + const delayMs = 20; + let lastError; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + return lockfile.lockSync(path, { realpath: false }); + } + catch (error) { + const code = typeof error === "object" && error !== null && "code" in error + ? String(error.code) + : undefined; + if (code !== "ELOCKED" || attempt === maxAttempts) { + throw error; + } + lastError = error; + const start = Date.now(); + while (Date.now() - start < delayMs) { + // Sleep synchronously to avoid changing callers to async. + } + } + } + throw lastError ?? new Error("Failed to acquire settings lock"); + } + withLock(scope, fn) { + const path = scope === "global" ? this.globalSettingsPath : this.projectSettingsPath; + const dir = dirname(path); + let release; + try { + // Only create directory and lock if file exists or we need to write + const fileExists = existsSync(path); + if (fileExists) { + release = this.acquireLockSyncWithRetry(path); + } + const current = fileExists ? readFileSync(path, "utf-8") : undefined; + const next = fn(current); + if (next !== undefined) { + // Only create directory when we actually need to write + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } + if (!release) { + release = this.acquireLockSyncWithRetry(path); + } + writeFileSync(path, next, "utf-8"); + } + } + finally { + if (release) { + release(); + } + } + } +} +export class InMemorySettingsStorage { + global; + project; + withLock(scope, fn) { + const current = scope === "global" ? this.global : this.project; + const next = fn(current); + if (next !== undefined) { + if (scope === "global") { + this.global = next; + } + else { + this.project = next; + } + } + } +} +export class SettingsManager { + storage; + globalSettings; + projectSettings; + settings; + projectTrusted; + modifiedFields = new Set(); // Track global fields modified during session + modifiedNestedFields = new Map(); // Track global nested field modifications + modifiedProjectFields = new Set(); // Track project fields modified during session + modifiedProjectNestedFields = new Map(); // Track project nested field modifications + globalSettingsLoadError = null; // Track if global settings file had parse errors + projectSettingsLoadError = null; // Track if project settings file had parse errors + writeQueue = Promise.resolve(); + errors; + constructor(storage, initialGlobal, initialProject, globalLoadError = null, projectLoadError = null, initialErrors = [], projectTrusted = true) { + this.storage = storage; + this.globalSettings = initialGlobal; + this.projectSettings = initialProject; + this.projectTrusted = projectTrusted; + this.globalSettingsLoadError = globalLoadError; + this.projectSettingsLoadError = projectLoadError; + this.errors = [...initialErrors]; + this.settings = deepMergeSettings(this.globalSettings, this.projectSettings); + } + /** Create a SettingsManager that loads from files */ + static create(cwd, agentDir = getAgentDir(), options = {}) { + const storage = new FileSettingsStorage(cwd, agentDir); + return SettingsManager.fromStorage(storage, options); + } + /** Create a SettingsManager from an arbitrary storage backend */ + static fromStorage(storage, options = {}) { + const projectTrusted = options.projectTrusted ?? true; + const globalLoad = SettingsManager.tryLoadFromStorage(storage, "global"); + const projectLoad = SettingsManager.tryLoadFromStorage(storage, "project", projectTrusted); + const initialErrors = []; + if (globalLoad.error) { + initialErrors.push({ scope: "global", error: globalLoad.error }); + } + if (projectLoad.error) { + initialErrors.push({ scope: "project", error: projectLoad.error }); + } + return new SettingsManager(storage, globalLoad.settings, projectLoad.settings, globalLoad.error, projectLoad.error, initialErrors, projectTrusted); + } + /** Create an in-memory SettingsManager (no file I/O) */ + static inMemory(settings = {}, options = {}) { + const storage = new InMemorySettingsStorage(); + const initialSettings = SettingsManager.migrateSettings(structuredClone(settings)); + storage.withLock("global", () => JSON.stringify(initialSettings, null, 2)); + return SettingsManager.fromStorage(storage, options); + } + static loadFromStorage(storage, scope, projectTrusted = true) { + if (scope === "project" && !projectTrusted) { + return {}; + } + let content; + storage.withLock(scope, (current) => { + content = current; + return undefined; + }); + if (!content) { + return {}; + } + const settings = JSON.parse(content); + return SettingsManager.migrateSettings(settings); + } + static tryLoadFromStorage(storage, scope, projectTrusted = true) { + try { + return { settings: SettingsManager.loadFromStorage(storage, scope, projectTrusted), error: null }; + } + catch (error) { + return { settings: {}, error: error }; + } + } + /** Migrate old settings format to new format */ + static migrateSettings(settings) { + // Migrate queueMode -> steeringMode + if ("queueMode" in settings && !("steeringMode" in settings)) { + settings.steeringMode = settings.queueMode; + delete settings.queueMode; + } + // Migrate legacy websockets boolean -> transport enum + if (!("transport" in settings) && typeof settings.websockets === "boolean") { + settings.transport = settings.websockets ? "websocket" : "sse"; + delete settings.websockets; + } + // Migrate old skills object format to new array format + if ("skills" in settings && + typeof settings.skills === "object" && + settings.skills !== null && + !Array.isArray(settings.skills)) { + const skillsSettings = settings.skills; + if (skillsSettings.enableSkillCommands !== undefined && settings.enableSkillCommands === undefined) { + settings.enableSkillCommands = skillsSettings.enableSkillCommands; + } + if (Array.isArray(skillsSettings.customDirectories) && skillsSettings.customDirectories.length > 0) { + settings.skills = skillsSettings.customDirectories; + } + else { + delete settings.skills; + } + } + // Migrate retry.maxDelayMs -> retry.provider.maxRetryDelayMs + if ("retry" in settings && + typeof settings.retry === "object" && + settings.retry !== null && + !Array.isArray(settings.retry)) { + const retrySettings = settings.retry; + const providerSettings = typeof retrySettings.provider === "object" && retrySettings.provider !== null + ? retrySettings.provider + : undefined; + if (typeof retrySettings.maxDelayMs === "number" && + (providerSettings?.maxRetryDelayMs === undefined || providerSettings?.maxRetryDelayMs === null)) { + retrySettings.provider = { + ...(providerSettings ?? {}), + maxRetryDelayMs: retrySettings.maxDelayMs, + }; + } + delete retrySettings.maxDelayMs; + } + return settings; + } + getGlobalSettings() { + return structuredClone(this.globalSettings); + } + getProjectSettings() { + return structuredClone(this.projectSettings); + } + isProjectTrusted() { + return this.projectTrusted; + } + setProjectTrusted(trusted) { + if (this.projectTrusted === trusted) { + return; + } + this.projectTrusted = trusted; + this.modifiedProjectFields.clear(); + this.modifiedProjectNestedFields.clear(); + if (!trusted) { + this.projectSettings = {}; + this.projectSettingsLoadError = null; + this.settings = deepMergeSettings(this.globalSettings, this.projectSettings); + return; + } + const projectLoad = SettingsManager.tryLoadFromStorage(this.storage, "project", trusted); + this.projectSettings = projectLoad.settings; + this.projectSettingsLoadError = projectLoad.error; + if (projectLoad.error) { + this.recordError("project", projectLoad.error); + } + this.settings = deepMergeSettings(this.globalSettings, this.projectSettings); + } + async reload() { + await this.writeQueue; + const globalLoad = SettingsManager.tryLoadFromStorage(this.storage, "global"); + if (!globalLoad.error) { + this.globalSettings = globalLoad.settings; + this.globalSettingsLoadError = null; + } + else { + this.globalSettingsLoadError = globalLoad.error; + this.recordError("global", globalLoad.error); + } + this.modifiedFields.clear(); + this.modifiedNestedFields.clear(); + this.modifiedProjectFields.clear(); + this.modifiedProjectNestedFields.clear(); + const projectLoad = SettingsManager.tryLoadFromStorage(this.storage, "project", this.projectTrusted); + if (!projectLoad.error) { + this.projectSettings = projectLoad.settings; + this.projectSettingsLoadError = null; + } + else { + this.projectSettingsLoadError = projectLoad.error; + this.recordError("project", projectLoad.error); + } + this.settings = deepMergeSettings(this.globalSettings, this.projectSettings); + } + /** Apply additional overrides on top of current settings */ + applyOverrides(overrides) { + this.settings = deepMergeSettings(this.settings, overrides); + } + /** Mark a global field as modified during this session */ + markModified(field, nestedKey) { + this.modifiedFields.add(field); + if (nestedKey) { + if (!this.modifiedNestedFields.has(field)) { + this.modifiedNestedFields.set(field, new Set()); + } + this.modifiedNestedFields.get(field).add(nestedKey); + } + } + /** Mark a project field as modified during this session */ + markProjectModified(field, nestedKey) { + this.modifiedProjectFields.add(field); + if (nestedKey) { + if (!this.modifiedProjectNestedFields.has(field)) { + this.modifiedProjectNestedFields.set(field, new Set()); + } + this.modifiedProjectNestedFields.get(field).add(nestedKey); + } + } + assertProjectTrustedForWrite() { + if (!this.projectTrusted) { + throw new Error("Project is not trusted; refusing to write project settings"); + } + } + recordError(scope, error) { + const normalizedError = error instanceof Error ? error : new Error(String(error)); + this.errors.push({ scope, error: normalizedError }); + } + clearModifiedScope(scope) { + if (scope === "global") { + this.modifiedFields.clear(); + this.modifiedNestedFields.clear(); + return; + } + this.modifiedProjectFields.clear(); + this.modifiedProjectNestedFields.clear(); + } + enqueueWrite(scope, task) { + this.writeQueue = this.writeQueue + .then(() => { + if (scope === "project") { + this.assertProjectTrustedForWrite(); + } + task(); + this.clearModifiedScope(scope); + }) + .catch((error) => { + this.recordError(scope, error); + }); + } + cloneModifiedNestedFields(source) { + const snapshot = new Map(); + for (const [key, value] of source.entries()) { + snapshot.set(key, new Set(value)); + } + return snapshot; + } + persistScopedSettings(scope, snapshotSettings, modifiedFields, modifiedNestedFields) { + this.storage.withLock(scope, (current) => { + const currentFileSettings = current + ? SettingsManager.migrateSettings(JSON.parse(current)) + : {}; + const mergedSettings = { ...currentFileSettings }; + for (const field of modifiedFields) { + const value = snapshotSettings[field]; + if (modifiedNestedFields.has(field) && typeof value === "object" && value !== null) { + const nestedModified = modifiedNestedFields.get(field); + const baseNested = currentFileSettings[field] ?? {}; + const inMemoryNested = value; + const mergedNested = { ...baseNested }; + for (const nestedKey of nestedModified) { + mergedNested[nestedKey] = inMemoryNested[nestedKey]; + } + mergedSettings[field] = mergedNested; + } + else { + mergedSettings[field] = value; + } + } + return JSON.stringify(mergedSettings, null, 2); + }); + } + save() { + this.settings = deepMergeSettings(this.globalSettings, this.projectSettings); + if (this.globalSettingsLoadError) { + return; + } + const snapshotGlobalSettings = structuredClone(this.globalSettings); + const modifiedFields = new Set(this.modifiedFields); + const modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedNestedFields); + this.enqueueWrite("global", () => { + this.persistScopedSettings("global", snapshotGlobalSettings, modifiedFields, modifiedNestedFields); + }); + } + saveProjectSettings(settings) { + this.assertProjectTrustedForWrite(); + this.projectSettings = structuredClone(settings); + this.settings = deepMergeSettings(this.globalSettings, this.projectSettings); + if (this.projectSettingsLoadError) { + return; + } + const snapshotProjectSettings = structuredClone(this.projectSettings); + const modifiedFields = new Set(this.modifiedProjectFields); + const modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedProjectNestedFields); + this.enqueueWrite("project", () => { + this.persistScopedSettings("project", snapshotProjectSettings, modifiedFields, modifiedNestedFields); + }); + } + updateProjectSettings(field, update) { + this.assertProjectTrustedForWrite(); + const projectSettings = structuredClone(this.projectSettings); + update(projectSettings); + this.markProjectModified(field); + this.saveProjectSettings(projectSettings); + } + async flush() { + await this.writeQueue; + } + drainErrors() { + const drained = [...this.errors]; + this.errors = []; + return drained; + } + getLastChangelogVersion() { + return this.settings.lastChangelogVersion; + } + setLastChangelogVersion(version) { + this.globalSettings.lastChangelogVersion = version; + this.markModified("lastChangelogVersion"); + this.save(); + } + getSessionDir() { + const sessionDir = this.settings.sessionDir; + return sessionDir ? normalizePath(sessionDir) : sessionDir; + } + getDefaultProvider() { + return this.settings.defaultProvider; + } + getDefaultModel() { + return this.settings.defaultModel; + } + setDefaultProvider(provider) { + this.globalSettings.defaultProvider = provider; + this.markModified("defaultProvider"); + this.save(); + } + setDefaultModel(modelId) { + this.globalSettings.defaultModel = modelId; + this.markModified("defaultModel"); + this.save(); + } + setDefaultModelAndProvider(provider, modelId) { + this.globalSettings.defaultProvider = provider; + this.globalSettings.defaultModel = modelId; + this.markModified("defaultProvider"); + this.markModified("defaultModel"); + this.save(); + } + getSteeringMode() { + return this.settings.steeringMode || "one-at-a-time"; + } + setSteeringMode(mode) { + this.globalSettings.steeringMode = mode; + this.markModified("steeringMode"); + this.save(); + } + getFollowUpMode() { + return this.settings.followUpMode || "one-at-a-time"; + } + setFollowUpMode(mode) { + this.globalSettings.followUpMode = mode; + this.markModified("followUpMode"); + this.save(); + } + getThemeSetting() { + const value = this.settings.theme; + if (typeof value === "string") + return value; + return undefined; + } + getTheme() { + const theme = this.getThemeSetting(); + return theme?.includes("/") ? undefined : theme; + } + setTheme(theme) { + this.globalSettings.theme = theme; + this.markModified("theme"); + this.save(); + } + getDefaultThinkingLevel() { + return this.settings.defaultThinkingLevel; + } + setDefaultThinkingLevel(level) { + this.globalSettings.defaultThinkingLevel = level; + this.markModified("defaultThinkingLevel"); + this.save(); + } + getTransport() { + return this.settings.transport ?? "auto"; + } + setTransport(transport) { + this.globalSettings.transport = transport; + this.markModified("transport"); + this.save(); + } + getCompactionEnabled() { + return this.settings.compaction?.enabled ?? true; + } + setCompactionEnabled(enabled) { + if (!this.globalSettings.compaction) { + this.globalSettings.compaction = {}; + } + this.globalSettings.compaction.enabled = enabled; + this.markModified("compaction", "enabled"); + this.save(); + } + getCompactionReserveTokens() { + return this.settings.compaction?.reserveTokens ?? 16384; + } + getCompactionKeepRecentTokens() { + return this.settings.compaction?.keepRecentTokens ?? 20000; + } + getCompactionSettings() { + return { + enabled: this.getCompactionEnabled(), + reserveTokens: this.getCompactionReserveTokens(), + keepRecentTokens: this.getCompactionKeepRecentTokens(), + }; + } + getBranchSummarySettings() { + return { + reserveTokens: this.settings.branchSummary?.reserveTokens ?? 16384, + skipPrompt: this.settings.branchSummary?.skipPrompt ?? false, + }; + } + getBranchSummarySkipPrompt() { + return this.settings.branchSummary?.skipPrompt ?? false; + } + getRetryEnabled() { + return this.settings.retry?.enabled ?? true; + } + setRetryEnabled(enabled) { + if (!this.globalSettings.retry) { + this.globalSettings.retry = {}; + } + this.globalSettings.retry.enabled = enabled; + this.markModified("retry", "enabled"); + this.save(); + } + getRetrySettings() { + return { + enabled: this.getRetryEnabled(), + maxRetries: this.settings.retry?.maxRetries ?? 3, + baseDelayMs: this.settings.retry?.baseDelayMs ?? 2000, + }; + } + getHttpIdleTimeoutMs() { + return parseTimeoutSetting(this.settings.httpIdleTimeoutMs, "httpIdleTimeoutMs") ?? DEFAULT_HTTP_IDLE_TIMEOUT_MS; + } + setHttpIdleTimeoutMs(timeoutMs) { + if (!Number.isFinite(timeoutMs) || timeoutMs < 0) { + throw new Error(`Invalid httpIdleTimeoutMs setting: ${String(timeoutMs)}`); + } + this.globalSettings.httpIdleTimeoutMs = Math.floor(timeoutMs); + this.markModified("httpIdleTimeoutMs"); + this.save(); + } + getProviderRetrySettings() { + return { + timeoutMs: this.settings.retry?.provider?.timeoutMs, + maxRetries: this.settings.retry?.provider?.maxRetries, + maxRetryDelayMs: this.settings.retry?.provider?.maxRetryDelayMs ?? 60000, + }; + } + getWebSocketConnectTimeoutMs() { + return parseTimeoutSetting(this.settings.websocketConnectTimeoutMs, "websocketConnectTimeoutMs"); + } + getHideThinkingBlock() { + return this.settings.hideThinkingBlock ?? false; + } + getShowCacheMissNotices() { + return this.settings.showCacheMissNotices ?? false; + } + getExternalEditorCommand() { + const configuredEditor = this.settings.externalEditor; + if (typeof configuredEditor === "string" && configuredEditor.trim() !== "") { + return configuredEditor; + } + const environmentEditor = process.env.VISUAL || process.env.EDITOR; + if (environmentEditor) { + return environmentEditor; + } + return process.platform === "win32" ? "notepad" : "nano"; + } + setHideThinkingBlock(hide) { + this.globalSettings.hideThinkingBlock = hide; + this.markModified("hideThinkingBlock"); + this.save(); + } + setShowCacheMissNotices(show) { + this.globalSettings.showCacheMissNotices = show; + this.markModified("showCacheMissNotices"); + this.save(); + } + getShellPath() { + const shellPath = this.settings.shellPath; + return shellPath ? normalizePath(shellPath) : shellPath; + } + setShellPath(path) { + this.globalSettings.shellPath = path; + this.markModified("shellPath"); + this.save(); + } + getQuietStartup() { + return this.settings.quietStartup ?? false; + } + setQuietStartup(quiet) { + this.globalSettings.quietStartup = quiet; + this.markModified("quietStartup"); + this.save(); + } + getDefaultProjectTrust() { + const value = this.globalSettings.defaultProjectTrust; + return value === "always" || value === "never" ? value : "ask"; + } + setDefaultProjectTrust(defaultProjectTrust) { + this.globalSettings.defaultProjectTrust = defaultProjectTrust; + this.markModified("defaultProjectTrust"); + this.save(); + } + getShellCommandPrefix() { + return this.settings.shellCommandPrefix; + } + setShellCommandPrefix(prefix) { + this.globalSettings.shellCommandPrefix = prefix; + this.markModified("shellCommandPrefix"); + this.save(); + } + getNpmCommand() { + return this.settings.npmCommand ? [...this.settings.npmCommand] : undefined; + } + setNpmCommand(command) { + this.globalSettings.npmCommand = command ? [...command] : undefined; + this.markModified("npmCommand"); + this.save(); + } + getCollapseChangelog() { + return this.settings.collapseChangelog ?? false; + } + setCollapseChangelog(collapse) { + this.globalSettings.collapseChangelog = collapse; + this.markModified("collapseChangelog"); + this.save(); + } + getEnableInstallTelemetry() { + return this.settings.enableInstallTelemetry ?? true; + } + setEnableInstallTelemetry(enabled) { + this.globalSettings.enableInstallTelemetry = enabled; + this.markModified("enableInstallTelemetry"); + this.save(); + } + getEnableAnalytics() { + return this.settings.enableAnalytics ?? false; + } + getTrackingId() { + return this.settings.trackingId; + } + /** Set the analytics opt-in preference; generates a tracking identifier on first opt-in */ + setEnableAnalytics(enabled) { + this.globalSettings.enableAnalytics = enabled; + this.markModified("enableAnalytics"); + if (enabled && !this.globalSettings.trackingId) { + this.globalSettings.trackingId = randomUUID(); + this.markModified("trackingId"); + } + this.save(); + } + getPackages() { + return [...(this.settings.packages ?? [])]; + } + setPackages(packages) { + this.globalSettings.packages = packages; + this.markModified("packages"); + this.save(); + } + setProjectPackages(packages) { + this.updateProjectSettings("packages", (settings) => { + settings.packages = packages; + }); + } + getExtensionPaths() { + return [...(this.settings.extensions ?? [])]; + } + setExtensionPaths(paths) { + this.globalSettings.extensions = paths; + this.markModified("extensions"); + this.save(); + } + setProjectExtensionPaths(paths) { + this.updateProjectSettings("extensions", (settings) => { + settings.extensions = paths; + }); + } + getSkillPaths() { + return [...(this.settings.skills ?? [])]; + } + setSkillPaths(paths) { + this.globalSettings.skills = paths; + this.markModified("skills"); + this.save(); + } + setProjectSkillPaths(paths) { + this.updateProjectSettings("skills", (settings) => { + settings.skills = paths; + }); + } + getPromptTemplatePaths() { + return [...(this.settings.prompts ?? [])]; + } + setPromptTemplatePaths(paths) { + this.globalSettings.prompts = paths; + this.markModified("prompts"); + this.save(); + } + setProjectPromptTemplatePaths(paths) { + this.updateProjectSettings("prompts", (settings) => { + settings.prompts = paths; + }); + } + getThemePaths() { + return [...(this.settings.themes ?? [])]; + } + setThemePaths(paths) { + this.globalSettings.themes = paths; + this.markModified("themes"); + this.save(); + } + setProjectThemePaths(paths) { + this.updateProjectSettings("themes", (settings) => { + settings.themes = paths; + }); + } + getEnableSkillCommands() { + return this.settings.enableSkillCommands ?? true; + } + setEnableSkillCommands(enabled) { + this.globalSettings.enableSkillCommands = enabled; + this.markModified("enableSkillCommands"); + this.save(); + } + getThinkingBudgets() { + return this.settings.thinkingBudgets; + } + getShowImages() { + return this.settings.terminal?.showImages ?? true; + } + setShowImages(show) { + if (!this.globalSettings.terminal) { + this.globalSettings.terminal = {}; + } + this.globalSettings.terminal.showImages = show; + this.markModified("terminal", "showImages"); + this.save(); + } + getImageWidthCells() { + const width = this.settings.terminal?.imageWidthCells; + if (typeof width !== "number" || !Number.isFinite(width)) { + return 60; + } + return Math.max(1, Math.floor(width)); + } + setImageWidthCells(width) { + if (!this.globalSettings.terminal) { + this.globalSettings.terminal = {}; + } + this.globalSettings.terminal.imageWidthCells = Math.max(1, Math.floor(width)); + this.markModified("terminal", "imageWidthCells"); + this.save(); + } + getClearOnShrink() { + // Settings takes precedence, then env var, then default false + if (this.settings.terminal?.clearOnShrink !== undefined) { + return this.settings.terminal.clearOnShrink; + } + return process.env.PI_CLEAR_ON_SHRINK === "1"; + } + setClearOnShrink(enabled) { + if (!this.globalSettings.terminal) { + this.globalSettings.terminal = {}; + } + this.globalSettings.terminal.clearOnShrink = enabled; + this.markModified("terminal", "clearOnShrink"); + this.save(); + } + getShowTerminalProgress() { + return this.settings.terminal?.showTerminalProgress ?? false; + } + setShowTerminalProgress(enabled) { + if (!this.globalSettings.terminal) { + this.globalSettings.terminal = {}; + } + this.globalSettings.terminal.showTerminalProgress = enabled; + this.markModified("terminal", "showTerminalProgress"); + this.save(); + } + getImageAutoResize() { + return this.settings.images?.autoResize ?? true; + } + setImageAutoResize(enabled) { + if (!this.globalSettings.images) { + this.globalSettings.images = {}; + } + this.globalSettings.images.autoResize = enabled; + this.markModified("images", "autoResize"); + this.save(); + } + getBlockImages() { + return this.settings.images?.blockImages ?? false; + } + setBlockImages(blocked) { + if (!this.globalSettings.images) { + this.globalSettings.images = {}; + } + this.globalSettings.images.blockImages = blocked; + this.markModified("images", "blockImages"); + this.save(); + } + getEnabledModels() { + return this.settings.enabledModels; + } + setEnabledModels(patterns) { + this.globalSettings.enabledModels = patterns; + this.markModified("enabledModels"); + this.save(); + } + getDoubleEscapeAction() { + return this.settings.doubleEscapeAction ?? "tree"; + } + setDoubleEscapeAction(action) { + this.globalSettings.doubleEscapeAction = action; + this.markModified("doubleEscapeAction"); + this.save(); + } + getTreeFilterMode() { + const mode = this.settings.treeFilterMode; + const valid = ["default", "no-tools", "user-only", "labeled-only", "all"]; + return mode && valid.includes(mode) ? mode : "default"; + } + setTreeFilterMode(mode) { + this.globalSettings.treeFilterMode = mode; + this.markModified("treeFilterMode"); + this.save(); + } + getShowHardwareCursor() { + return this.settings.showHardwareCursor ?? process.env.PI_HARDWARE_CURSOR === "1"; + } + setShowHardwareCursor(enabled) { + this.globalSettings.showHardwareCursor = enabled; + this.markModified("showHardwareCursor"); + this.save(); + } + getEditorPaddingX() { + return this.settings.editorPaddingX ?? 0; + } + setEditorPaddingX(padding) { + this.globalSettings.editorPaddingX = Math.max(0, Math.min(3, Math.floor(padding))); + this.markModified("editorPaddingX"); + this.save(); + } + getOutputPad() { + return this.settings.outputPad === 0 ? 0 : 1; + } + setOutputPad(padding) { + this.globalSettings.outputPad = padding; + this.markModified("outputPad"); + this.save(); + } + getAutocompleteMaxVisible() { + return this.settings.autocompleteMaxVisible ?? 5; + } + setAutocompleteMaxVisible(maxVisible) { + this.globalSettings.autocompleteMaxVisible = Math.max(3, Math.min(20, Math.floor(maxVisible))); + this.markModified("autocompleteMaxVisible"); + this.save(); + } + getCodeBlockIndent() { + return this.settings.markdown?.codeBlockIndent ?? " "; + } + getWarnings() { + return { ...(this.settings.warnings ?? {}) }; + } + setWarnings(warnings) { + this.globalSettings.warnings = { ...warnings }; + this.markModified("warnings"); + this.save(); + } +} +//# sourceMappingURL=settings-manager.js.map \ No newline at end of file diff --git a/dist/core/settings-manager.js.map b/dist/core/settings-manager.js.map new file mode 100644 index 0000000..8f94378 --- /dev/null +++ b/dist/core/settings-manager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"settings-manager.js","sourceRoot":"","sources":["../../src/core/settings-manager.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACxE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,4BAA4B,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AA0H5F,+FAA+F;AAC/F,SAAS,iBAAiB,CAAC,IAAc,EAAE,SAAmB,EAAY;IACzE,MAAM,MAAM,GAAa,EAAE,GAAG,IAAI,EAAE,CAAC;IAErC,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAuB,EAAE,CAAC;QAChE,MAAM,aAAa,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;QACrC,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;QAE5B,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YACjC,SAAS;QACV,CAAC;QAED,wCAAwC;QAC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CAAC,QAAQ,EAAE,eAAe,IAAI,IAAI,CAAC;IAAA,CACvD;IAED,WAAW,GAAoB;QAC9B,OAAO,EAAE,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,IAAI,EAAE,CAAC,EAAE,CAAC;IAAA,CAC7C;IAED,WAAW,CAAC,QAAyB,EAAQ;QAC5C,IAAI,CAAC,cAAc,CAAC,QAAQ,GAAG,EAAE,GAAG,QAAQ,EAAE,CAAC;QAC/C,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC;QAC9B,IAAI,CAAC,IAAI,EAAE,CAAC;IAAA,CACZ;CACD","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Transport } from \"@earendil-works/pi-ai\";\nimport { randomUUID } from \"crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { normalizePath, resolvePath } from \"../utils/paths.ts\";\nimport { DEFAULT_HTTP_IDLE_TIMEOUT_MS, parseHttpIdleTimeoutMs } from \"./http-dispatcher.ts\";\n\nexport interface CompactionSettings {\n\tenabled?: boolean; // default: true\n\treserveTokens?: number; // default: 16384\n\tkeepRecentTokens?: number; // default: 20000\n}\n\nexport interface BranchSummarySettings {\n\treserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response)\n\tskipPrompt?: boolean; // default: false - when true, skips \"Summarize branch?\" prompt and defaults to no summary\n}\n\nexport interface ProviderRetrySettings {\n\ttimeoutMs?: number; // SDK/provider request timeout in milliseconds\n\tmaxRetries?: number; // SDK/provider retry attempts\n\tmaxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing)\n}\n\nexport interface RetrySettings {\n\tenabled?: boolean; // default: true\n\tmaxRetries?: number; // default: 3\n\tbaseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s)\n\tprovider?: ProviderRetrySettings;\n}\n\nexport interface TerminalSettings {\n\tshowImages?: boolean; // default: true (only relevant if terminal supports images)\n\timageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells)\n\tclearOnShrink?: boolean; // default: false (clear empty rows when content shrinks)\n\tshowTerminalProgress?: boolean; // default: false (OSC 9;4 terminal progress indicators)\n}\n\nexport interface ImageSettings {\n\tautoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility)\n\tblockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers\n}\n\nexport interface ThinkingBudgetsSettings {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\nexport interface MarkdownSettings {\n\tcodeBlockIndent?: string; // default: \" \"\n}\n\nexport interface WarningSettings {\n\tanthropicExtraUsage?: boolean; // default: true\n}\n\nexport type DefaultProjectTrust = \"ask\" | \"always\" | \"never\";\n\nexport type TransportSetting = Transport;\n\n/**\n * Package source for npm/git packages.\n * - String form: load all resources from the package\n * - Object form: filter which resources to load\n * - autoload=false: start empty and only apply explicit resource patterns\n */\nexport type PackageSource =\n\t| string\n\t| {\n\t\t\tsource: string;\n\t\t\tautoload?: boolean;\n\t\t\textensions?: string[];\n\t\t\tskills?: string[];\n\t\t\tprompts?: string[];\n\t\t\tthemes?: string[];\n\t };\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n\tdefaultThinkingLevel?: ThinkingLevel;\n\ttransport?: TransportSetting; // default: \"auto\"\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\ttheme?: string;\n\tcompaction?: CompactionSettings;\n\tbranchSummary?: BranchSummarySettings;\n\tretry?: RetrySettings;\n\thideThinkingBlock?: boolean;\n\tshowCacheMissNotices?: boolean; // default: false - show transcript notices for significant prompt-cache misses\n\texternalEditor?: string; // Command for Ctrl+G external editor; takes precedence over VISUAL/EDITOR\n\tshellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows); supports leading ~ expansion\n\tquietStartup?: boolean;\n\tdefaultProjectTrust?: DefaultProjectTrust; // default: \"ask\"; global setting only\n\tshellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., \"shopt -s expand_aliases\" for alias support)\n\tnpmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., [\"mise\", \"exec\", \"node@20\", \"--\", \"npm\"])\n\tcollapseChangelog?: boolean; // Show condensed changelog after update (use /changelog for full)\n\tenableInstallTelemetry?: boolean; // default: true - anonymous version/update ping after changelog-detected updates\n\tenableAnalytics?: boolean; // default: false - opt-in analytics data sharing\n\ttrackingId?: string; // analytics tracking identifier, generated when analytics is enabled\n\tpackages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)\n\textensions?: string[]; // Array of local extension file paths or directories\n\tskills?: string[]; // Array of local skill file paths or directories\n\tprompts?: string[]; // Array of local prompt template paths or directories\n\tthemes?: string[]; // Array of local theme file paths or directories\n\tenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands\n\tterminal?: TerminalSettings;\n\timages?: ImageSettings;\n\tenabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag)\n\tdoubleEscapeAction?: \"fork\" | \"tree\" | \"none\"; // Action for double-escape with empty editor (default: \"tree\")\n\ttreeFilterMode?: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"; // Default filter when opening /tree\n\tthinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels\n\teditorPaddingX?: number; // Horizontal padding for input editor (default: 0)\n\toutputPad?: 0 | 1; // Horizontal padding for chat message output (default: 1)\n\tautocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5)\n\tshowHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME\n\tmarkdown?: MarkdownSettings;\n\twarnings?: WarningSettings;\n\tsessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag)\n\thttpProxy?: string; // Proxy URL applied as HTTP_PROXY and HTTPS_PROXY for Pi-managed HTTP clients\n\thttpIdleTimeoutMs?: number; // HTTP header/body idle timeout in milliseconds; 0 disables it\n\twebsocketConnectTimeoutMs?: number; // WebSocket connect/open handshake timeout in milliseconds; 0 disables it\n}\n\n/** Deep merge settings: project/overrides take precedence, nested objects merge recursively */\nfunction deepMergeSettings(base: Settings, overrides: Settings): Settings {\n\tconst result: Settings = { ...base };\n\n\tfor (const key of Object.keys(overrides) as (keyof Settings)[]) {\n\t\tconst overrideValue = overrides[key];\n\t\tconst baseValue = base[key];\n\n\t\tif (overrideValue === undefined) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// For nested objects, merge recursively\n\t\tif (\n\t\t\ttypeof overrideValue === \"object\" &&\n\t\t\toverrideValue !== null &&\n\t\t\t!Array.isArray(overrideValue) &&\n\t\t\ttypeof baseValue === \"object\" &&\n\t\t\tbaseValue !== null &&\n\t\t\t!Array.isArray(baseValue)\n\t\t) {\n\t\t\t(result as Record)[key] = { ...baseValue, ...overrideValue };\n\t\t} else {\n\t\t\t// For primitives and arrays, override value wins\n\t\t\t(result as Record)[key] = overrideValue;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction parseTimeoutSetting(value: unknown, settingName: string): number | undefined {\n\tconst timeoutMs = parseHttpIdleTimeoutMs(value);\n\tif (timeoutMs !== undefined) {\n\t\treturn timeoutMs;\n\t}\n\tif (value !== undefined) {\n\t\tthrow new Error(`Invalid ${settingName} setting: ${String(value)}`);\n\t}\n\treturn undefined;\n}\n\nexport type SettingsScope = \"global\" | \"project\";\n\nexport interface SettingsManagerCreateOptions {\n\tprojectTrusted?: boolean;\n}\n\nexport interface SettingsStorage {\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void;\n}\n\nexport interface SettingsError {\n\tscope: SettingsScope;\n\terror: Error;\n}\n\nexport class FileSettingsStorage implements SettingsStorage {\n\tprivate globalSettingsPath: string;\n\tprivate projectSettingsPath: string;\n\n\tconstructor(cwd: string, agentDir: string) {\n\t\tconst resolvedCwd = resolvePath(cwd);\n\t\tconst resolvedAgentDir = resolvePath(agentDir);\n\t\tthis.globalSettingsPath = join(resolvedAgentDir, \"settings.json\");\n\t\tthis.projectSettingsPath = join(resolvedCwd, CONFIG_DIR_NAME, \"settings.json\");\n\t}\n\n\tprivate acquireLockSyncWithRetry(path: string): () => void {\n\t\tconst maxAttempts = 10;\n\t\tconst delayMs = 20;\n\t\tlet lastError: unknown;\n\n\t\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn lockfile.lockSync(path, { realpath: false });\n\t\t\t} catch (error) {\n\t\t\t\tconst code =\n\t\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tlastError = error;\n\t\t\t\tconst start = Date.now();\n\t\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t\t// Sleep synchronously to avoid changing callers to async.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow (lastError as Error) ?? new Error(\"Failed to acquire settings lock\");\n\t}\n\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void {\n\t\tconst path = scope === \"global\" ? this.globalSettingsPath : this.projectSettingsPath;\n\t\tconst dir = dirname(path);\n\n\t\tlet release: (() => void) | undefined;\n\t\ttry {\n\t\t\t// Only create directory and lock if file exists or we need to write\n\t\t\tconst fileExists = existsSync(path);\n\t\t\tif (fileExists) {\n\t\t\t\trelease = this.acquireLockSyncWithRetry(path);\n\t\t\t}\n\t\t\tconst current = fileExists ? readFileSync(path, \"utf-8\") : undefined;\n\t\t\tconst next = fn(current);\n\t\t\tif (next !== undefined) {\n\t\t\t\t// Only create directory when we actually need to write\n\t\t\t\tif (!existsSync(dir)) {\n\t\t\t\t\tmkdirSync(dir, { recursive: true });\n\t\t\t\t}\n\t\t\t\tif (!release) {\n\t\t\t\t\trelease = this.acquireLockSyncWithRetry(path);\n\t\t\t\t}\n\t\t\t\twriteFileSync(path, next, \"utf-8\");\n\t\t\t}\n\t\t} finally {\n\t\t\tif (release) {\n\t\t\t\trelease();\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class InMemorySettingsStorage implements SettingsStorage {\n\tprivate global: string | undefined;\n\tprivate project: string | undefined;\n\n\twithLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void {\n\t\tconst current = scope === \"global\" ? this.global : this.project;\n\t\tconst next = fn(current);\n\t\tif (next !== undefined) {\n\t\t\tif (scope === \"global\") {\n\t\t\t\tthis.global = next;\n\t\t\t} else {\n\t\t\t\tthis.project = next;\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport class SettingsManager {\n\tprivate storage: SettingsStorage;\n\tprivate globalSettings: Settings;\n\tprivate projectSettings: Settings;\n\tprivate settings: Settings;\n\tprivate projectTrusted: boolean;\n\tprivate modifiedFields = new Set(); // Track global fields modified during session\n\tprivate modifiedNestedFields = new Map>(); // Track global nested field modifications\n\tprivate modifiedProjectFields = new Set(); // Track project fields modified during session\n\tprivate modifiedProjectNestedFields = new Map>(); // Track project nested field modifications\n\tprivate globalSettingsLoadError: Error | null = null; // Track if global settings file had parse errors\n\tprivate projectSettingsLoadError: Error | null = null; // Track if project settings file had parse errors\n\tprivate writeQueue: Promise = Promise.resolve();\n\tprivate errors: SettingsError[];\n\n\tprivate constructor(\n\t\tstorage: SettingsStorage,\n\t\tinitialGlobal: Settings,\n\t\tinitialProject: Settings,\n\t\tglobalLoadError: Error | null = null,\n\t\tprojectLoadError: Error | null = null,\n\t\tinitialErrors: SettingsError[] = [],\n\t\tprojectTrusted = true,\n\t) {\n\t\tthis.storage = storage;\n\t\tthis.globalSettings = initialGlobal;\n\t\tthis.projectSettings = initialProject;\n\t\tthis.projectTrusted = projectTrusted;\n\t\tthis.globalSettingsLoadError = globalLoadError;\n\t\tthis.projectSettingsLoadError = projectLoadError;\n\t\tthis.errors = [...initialErrors];\n\t\tthis.settings = deepMergeSettings(this.globalSettings, this.projectSettings);\n\t}\n\n\t/** Create a SettingsManager that loads from files */\n\tstatic create(\n\t\tcwd: string,\n\t\tagentDir: string = getAgentDir(),\n\t\toptions: SettingsManagerCreateOptions = {},\n\t): SettingsManager {\n\t\tconst storage = new FileSettingsStorage(cwd, agentDir);\n\t\treturn SettingsManager.fromStorage(storage, options);\n\t}\n\n\t/** Create a SettingsManager from an arbitrary storage backend */\n\tstatic fromStorage(storage: SettingsStorage, options: SettingsManagerCreateOptions = {}): SettingsManager {\n\t\tconst projectTrusted = options.projectTrusted ?? true;\n\t\tconst globalLoad = SettingsManager.tryLoadFromStorage(storage, \"global\");\n\t\tconst projectLoad = SettingsManager.tryLoadFromStorage(storage, \"project\", projectTrusted);\n\t\tconst initialErrors: SettingsError[] = [];\n\t\tif (globalLoad.error) {\n\t\t\tinitialErrors.push({ scope: \"global\", error: globalLoad.error });\n\t\t}\n\t\tif (projectLoad.error) {\n\t\t\tinitialErrors.push({ scope: \"project\", error: projectLoad.error });\n\t\t}\n\n\t\treturn new SettingsManager(\n\t\t\tstorage,\n\t\t\tglobalLoad.settings,\n\t\t\tprojectLoad.settings,\n\t\t\tglobalLoad.error,\n\t\t\tprojectLoad.error,\n\t\t\tinitialErrors,\n\t\t\tprojectTrusted,\n\t\t);\n\t}\n\n\t/** Create an in-memory SettingsManager (no file I/O) */\n\tstatic inMemory(settings: Partial = {}, options: SettingsManagerCreateOptions = {}): SettingsManager {\n\t\tconst storage = new InMemorySettingsStorage();\n\t\tconst initialSettings = SettingsManager.migrateSettings(structuredClone(settings) as Record);\n\t\tstorage.withLock(\"global\", () => JSON.stringify(initialSettings, null, 2));\n\t\treturn SettingsManager.fromStorage(storage, options);\n\t}\n\n\tprivate static loadFromStorage(storage: SettingsStorage, scope: SettingsScope, projectTrusted = true): Settings {\n\t\tif (scope === \"project\" && !projectTrusted) {\n\t\t\treturn {};\n\t\t}\n\n\t\tlet content: string | undefined;\n\t\tstorage.withLock(scope, (current) => {\n\t\t\tcontent = current;\n\t\t\treturn undefined;\n\t\t});\n\n\t\tif (!content) {\n\t\t\treturn {};\n\t\t}\n\t\tconst settings = JSON.parse(content);\n\t\treturn SettingsManager.migrateSettings(settings);\n\t}\n\n\tprivate static tryLoadFromStorage(\n\t\tstorage: SettingsStorage,\n\t\tscope: SettingsScope,\n\t\tprojectTrusted = true,\n\t): { settings: Settings; error: Error | null } {\n\t\ttry {\n\t\t\treturn { settings: SettingsManager.loadFromStorage(storage, scope, projectTrusted), error: null };\n\t\t} catch (error) {\n\t\t\treturn { settings: {}, error: error as Error };\n\t\t}\n\t}\n\n\t/** Migrate old settings format to new format */\n\tprivate static migrateSettings(settings: Record): Settings {\n\t\t// Migrate queueMode -> steeringMode\n\t\tif (\"queueMode\" in settings && !(\"steeringMode\" in settings)) {\n\t\t\tsettings.steeringMode = settings.queueMode;\n\t\t\tdelete settings.queueMode;\n\t\t}\n\n\t\t// Migrate legacy websockets boolean -> transport enum\n\t\tif (!(\"transport\" in settings) && typeof settings.websockets === \"boolean\") {\n\t\t\tsettings.transport = settings.websockets ? \"websocket\" : \"sse\";\n\t\t\tdelete settings.websockets;\n\t\t}\n\n\t\t// Migrate old skills object format to new array format\n\t\tif (\n\t\t\t\"skills\" in settings &&\n\t\t\ttypeof settings.skills === \"object\" &&\n\t\t\tsettings.skills !== null &&\n\t\t\t!Array.isArray(settings.skills)\n\t\t) {\n\t\t\tconst skillsSettings = settings.skills as {\n\t\t\t\tenableSkillCommands?: boolean;\n\t\t\t\tcustomDirectories?: unknown;\n\t\t\t};\n\t\t\tif (skillsSettings.enableSkillCommands !== undefined && settings.enableSkillCommands === undefined) {\n\t\t\t\tsettings.enableSkillCommands = skillsSettings.enableSkillCommands;\n\t\t\t}\n\t\t\tif (Array.isArray(skillsSettings.customDirectories) && skillsSettings.customDirectories.length > 0) {\n\t\t\t\tsettings.skills = skillsSettings.customDirectories;\n\t\t\t} else {\n\t\t\t\tdelete settings.skills;\n\t\t\t}\n\t\t}\n\n\t\t// Migrate retry.maxDelayMs -> retry.provider.maxRetryDelayMs\n\t\tif (\n\t\t\t\"retry\" in settings &&\n\t\t\ttypeof settings.retry === \"object\" &&\n\t\t\tsettings.retry !== null &&\n\t\t\t!Array.isArray(settings.retry)\n\t\t) {\n\t\t\tconst retrySettings = settings.retry as Record;\n\t\t\tconst providerSettings =\n\t\t\t\ttypeof retrySettings.provider === \"object\" && retrySettings.provider !== null\n\t\t\t\t\t? (retrySettings.provider as Record)\n\t\t\t\t\t: undefined;\n\t\t\tif (\n\t\t\t\ttypeof retrySettings.maxDelayMs === \"number\" &&\n\t\t\t\t(providerSettings?.maxRetryDelayMs === undefined || providerSettings?.maxRetryDelayMs === null)\n\t\t\t) {\n\t\t\t\tretrySettings.provider = {\n\t\t\t\t\t...(providerSettings ?? {}),\n\t\t\t\t\tmaxRetryDelayMs: retrySettings.maxDelayMs,\n\t\t\t\t};\n\t\t\t}\n\t\t\tdelete retrySettings.maxDelayMs;\n\t\t}\n\n\t\treturn settings as Settings;\n\t}\n\n\tgetGlobalSettings(): Settings {\n\t\treturn structuredClone(this.globalSettings);\n\t}\n\n\tgetProjectSettings(): Settings {\n\t\treturn structuredClone(this.projectSettings);\n\t}\n\n\tisProjectTrusted(): boolean {\n\t\treturn this.projectTrusted;\n\t}\n\n\tsetProjectTrusted(trusted: boolean): void {\n\t\tif (this.projectTrusted === trusted) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.projectTrusted = trusted;\n\t\tthis.modifiedProjectFields.clear();\n\t\tthis.modifiedProjectNestedFields.clear();\n\n\t\tif (!trusted) {\n\t\t\tthis.projectSettings = {};\n\t\t\tthis.projectSettingsLoadError = null;\n\t\t\tthis.settings = deepMergeSettings(this.globalSettings, this.projectSettings);\n\t\t\treturn;\n\t\t}\n\n\t\tconst projectLoad = SettingsManager.tryLoadFromStorage(this.storage, \"project\", trusted);\n\t\tthis.projectSettings = projectLoad.settings;\n\t\tthis.projectSettingsLoadError = projectLoad.error;\n\t\tif (projectLoad.error) {\n\t\t\tthis.recordError(\"project\", projectLoad.error);\n\t\t}\n\t\tthis.settings = deepMergeSettings(this.globalSettings, this.projectSettings);\n\t}\n\n\tasync reload(): Promise {\n\t\tawait this.writeQueue;\n\t\tconst globalLoad = SettingsManager.tryLoadFromStorage(this.storage, \"global\");\n\t\tif (!globalLoad.error) {\n\t\t\tthis.globalSettings = globalLoad.settings;\n\t\t\tthis.globalSettingsLoadError = null;\n\t\t} else {\n\t\t\tthis.globalSettingsLoadError = globalLoad.error;\n\t\t\tthis.recordError(\"global\", globalLoad.error);\n\t\t}\n\n\t\tthis.modifiedFields.clear();\n\t\tthis.modifiedNestedFields.clear();\n\t\tthis.modifiedProjectFields.clear();\n\t\tthis.modifiedProjectNestedFields.clear();\n\n\t\tconst projectLoad = SettingsManager.tryLoadFromStorage(this.storage, \"project\", this.projectTrusted);\n\t\tif (!projectLoad.error) {\n\t\t\tthis.projectSettings = projectLoad.settings;\n\t\t\tthis.projectSettingsLoadError = null;\n\t\t} else {\n\t\t\tthis.projectSettingsLoadError = projectLoad.error;\n\t\t\tthis.recordError(\"project\", projectLoad.error);\n\t\t}\n\n\t\tthis.settings = deepMergeSettings(this.globalSettings, this.projectSettings);\n\t}\n\n\t/** Apply additional overrides on top of current settings */\n\tapplyOverrides(overrides: Partial): void {\n\t\tthis.settings = deepMergeSettings(this.settings, overrides);\n\t}\n\n\t/** Mark a global field as modified during this session */\n\tprivate markModified(field: keyof Settings, nestedKey?: string): void {\n\t\tthis.modifiedFields.add(field);\n\t\tif (nestedKey) {\n\t\t\tif (!this.modifiedNestedFields.has(field)) {\n\t\t\t\tthis.modifiedNestedFields.set(field, new Set());\n\t\t\t}\n\t\t\tthis.modifiedNestedFields.get(field)!.add(nestedKey);\n\t\t}\n\t}\n\n\t/** Mark a project field as modified during this session */\n\tprivate markProjectModified(field: keyof Settings, nestedKey?: string): void {\n\t\tthis.modifiedProjectFields.add(field);\n\t\tif (nestedKey) {\n\t\t\tif (!this.modifiedProjectNestedFields.has(field)) {\n\t\t\t\tthis.modifiedProjectNestedFields.set(field, new Set());\n\t\t\t}\n\t\t\tthis.modifiedProjectNestedFields.get(field)!.add(nestedKey);\n\t\t}\n\t}\n\n\tprivate assertProjectTrustedForWrite(): void {\n\t\tif (!this.projectTrusted) {\n\t\t\tthrow new Error(\"Project is not trusted; refusing to write project settings\");\n\t\t}\n\t}\n\n\tprivate recordError(scope: SettingsScope, error: unknown): void {\n\t\tconst normalizedError = error instanceof Error ? error : new Error(String(error));\n\t\tthis.errors.push({ scope, error: normalizedError });\n\t}\n\n\tprivate clearModifiedScope(scope: SettingsScope): void {\n\t\tif (scope === \"global\") {\n\t\t\tthis.modifiedFields.clear();\n\t\t\tthis.modifiedNestedFields.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.modifiedProjectFields.clear();\n\t\tthis.modifiedProjectNestedFields.clear();\n\t}\n\n\tprivate enqueueWrite(scope: SettingsScope, task: () => void): void {\n\t\tthis.writeQueue = this.writeQueue\n\t\t\t.then(() => {\n\t\t\t\tif (scope === \"project\") {\n\t\t\t\t\tthis.assertProjectTrustedForWrite();\n\t\t\t\t}\n\t\t\t\ttask();\n\t\t\t\tthis.clearModifiedScope(scope);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tthis.recordError(scope, error);\n\t\t\t});\n\t}\n\n\tprivate cloneModifiedNestedFields(source: Map>): Map> {\n\t\tconst snapshot = new Map>();\n\t\tfor (const [key, value] of source.entries()) {\n\t\t\tsnapshot.set(key, new Set(value));\n\t\t}\n\t\treturn snapshot;\n\t}\n\n\tprivate persistScopedSettings(\n\t\tscope: SettingsScope,\n\t\tsnapshotSettings: Settings,\n\t\tmodifiedFields: Set,\n\t\tmodifiedNestedFields: Map>,\n\t): void {\n\t\tthis.storage.withLock(scope, (current) => {\n\t\t\tconst currentFileSettings = current\n\t\t\t\t? SettingsManager.migrateSettings(JSON.parse(current) as Record)\n\t\t\t\t: {};\n\t\t\tconst mergedSettings: Settings = { ...currentFileSettings };\n\t\t\tfor (const field of modifiedFields) {\n\t\t\t\tconst value = snapshotSettings[field];\n\t\t\t\tif (modifiedNestedFields.has(field) && typeof value === \"object\" && value !== null) {\n\t\t\t\t\tconst nestedModified = modifiedNestedFields.get(field)!;\n\t\t\t\t\tconst baseNested = (currentFileSettings[field] as Record) ?? {};\n\t\t\t\t\tconst inMemoryNested = value as Record;\n\t\t\t\t\tconst mergedNested = { ...baseNested };\n\t\t\t\t\tfor (const nestedKey of nestedModified) {\n\t\t\t\t\t\tmergedNested[nestedKey] = inMemoryNested[nestedKey];\n\t\t\t\t\t}\n\t\t\t\t\t(mergedSettings as Record)[field] = mergedNested;\n\t\t\t\t} else {\n\t\t\t\t\t(mergedSettings as Record)[field] = value;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn JSON.stringify(mergedSettings, null, 2);\n\t\t});\n\t}\n\n\tprivate save(): void {\n\t\tthis.settings = deepMergeSettings(this.globalSettings, this.projectSettings);\n\n\t\tif (this.globalSettingsLoadError) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst snapshotGlobalSettings = structuredClone(this.globalSettings);\n\t\tconst modifiedFields = new Set(this.modifiedFields);\n\t\tconst modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedNestedFields);\n\n\t\tthis.enqueueWrite(\"global\", () => {\n\t\t\tthis.persistScopedSettings(\"global\", snapshotGlobalSettings, modifiedFields, modifiedNestedFields);\n\t\t});\n\t}\n\n\tprivate saveProjectSettings(settings: Settings): void {\n\t\tthis.assertProjectTrustedForWrite();\n\t\tthis.projectSettings = structuredClone(settings);\n\t\tthis.settings = deepMergeSettings(this.globalSettings, this.projectSettings);\n\n\t\tif (this.projectSettingsLoadError) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst snapshotProjectSettings = structuredClone(this.projectSettings);\n\t\tconst modifiedFields = new Set(this.modifiedProjectFields);\n\t\tconst modifiedNestedFields = this.cloneModifiedNestedFields(this.modifiedProjectNestedFields);\n\t\tthis.enqueueWrite(\"project\", () => {\n\t\t\tthis.persistScopedSettings(\"project\", snapshotProjectSettings, modifiedFields, modifiedNestedFields);\n\t\t});\n\t}\n\n\tprivate updateProjectSettings(field: keyof Settings, update: (settings: Settings) => void): void {\n\t\tthis.assertProjectTrustedForWrite();\n\t\tconst projectSettings = structuredClone(this.projectSettings);\n\t\tupdate(projectSettings);\n\t\tthis.markProjectModified(field);\n\t\tthis.saveProjectSettings(projectSettings);\n\t}\n\n\tasync flush(): Promise {\n\t\tawait this.writeQueue;\n\t}\n\n\tdrainErrors(): SettingsError[] {\n\t\tconst drained = [...this.errors];\n\t\tthis.errors = [];\n\t\treturn drained;\n\t}\n\n\tgetLastChangelogVersion(): string | undefined {\n\t\treturn this.settings.lastChangelogVersion;\n\t}\n\n\tsetLastChangelogVersion(version: string): void {\n\t\tthis.globalSettings.lastChangelogVersion = version;\n\t\tthis.markModified(\"lastChangelogVersion\");\n\t\tthis.save();\n\t}\n\n\tgetSessionDir(): string | undefined {\n\t\tconst sessionDir = this.settings.sessionDir;\n\t\treturn sessionDir ? normalizePath(sessionDir) : sessionDir;\n\t}\n\n\tgetDefaultProvider(): string | undefined {\n\t\treturn this.settings.defaultProvider;\n\t}\n\n\tgetDefaultModel(): string | undefined {\n\t\treturn this.settings.defaultModel;\n\t}\n\n\tsetDefaultProvider(provider: string): void {\n\t\tthis.globalSettings.defaultProvider = provider;\n\t\tthis.markModified(\"defaultProvider\");\n\t\tthis.save();\n\t}\n\n\tsetDefaultModel(modelId: string): void {\n\t\tthis.globalSettings.defaultModel = modelId;\n\t\tthis.markModified(\"defaultModel\");\n\t\tthis.save();\n\t}\n\n\tsetDefaultModelAndProvider(provider: string, modelId: string): void {\n\t\tthis.globalSettings.defaultProvider = provider;\n\t\tthis.globalSettings.defaultModel = modelId;\n\t\tthis.markModified(\"defaultProvider\");\n\t\tthis.markModified(\"defaultModel\");\n\t\tthis.save();\n\t}\n\n\tgetSteeringMode(): \"all\" | \"one-at-a-time\" {\n\t\treturn this.settings.steeringMode || \"one-at-a-time\";\n\t}\n\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void {\n\t\tthis.globalSettings.steeringMode = mode;\n\t\tthis.markModified(\"steeringMode\");\n\t\tthis.save();\n\t}\n\n\tgetFollowUpMode(): \"all\" | \"one-at-a-time\" {\n\t\treturn this.settings.followUpMode || \"one-at-a-time\";\n\t}\n\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void {\n\t\tthis.globalSettings.followUpMode = mode;\n\t\tthis.markModified(\"followUpMode\");\n\t\tthis.save();\n\t}\n\n\tgetThemeSetting(): string | undefined {\n\t\tconst value = this.settings.theme;\n\t\tif (typeof value === \"string\") return value;\n\t\treturn undefined;\n\t}\n\n\tgetTheme(): string | undefined {\n\t\tconst theme = this.getThemeSetting();\n\t\treturn theme?.includes(\"/\") ? undefined : theme;\n\t}\n\n\tsetTheme(theme: string): void {\n\t\tthis.globalSettings.theme = theme;\n\t\tthis.markModified(\"theme\");\n\t\tthis.save();\n\t}\n\n\tgetDefaultThinkingLevel(): ThinkingLevel | undefined {\n\t\treturn this.settings.defaultThinkingLevel;\n\t}\n\n\tsetDefaultThinkingLevel(level: ThinkingLevel): void {\n\t\tthis.globalSettings.defaultThinkingLevel = level;\n\t\tthis.markModified(\"defaultThinkingLevel\");\n\t\tthis.save();\n\t}\n\n\tgetTransport(): TransportSetting {\n\t\treturn this.settings.transport ?? \"auto\";\n\t}\n\n\tsetTransport(transport: TransportSetting): void {\n\t\tthis.globalSettings.transport = transport;\n\t\tthis.markModified(\"transport\");\n\t\tthis.save();\n\t}\n\n\tgetCompactionEnabled(): boolean {\n\t\treturn this.settings.compaction?.enabled ?? true;\n\t}\n\n\tsetCompactionEnabled(enabled: boolean): void {\n\t\tif (!this.globalSettings.compaction) {\n\t\t\tthis.globalSettings.compaction = {};\n\t\t}\n\t\tthis.globalSettings.compaction.enabled = enabled;\n\t\tthis.markModified(\"compaction\", \"enabled\");\n\t\tthis.save();\n\t}\n\n\tgetCompactionReserveTokens(): number {\n\t\treturn this.settings.compaction?.reserveTokens ?? 16384;\n\t}\n\n\tgetCompactionKeepRecentTokens(): number {\n\t\treturn this.settings.compaction?.keepRecentTokens ?? 20000;\n\t}\n\n\tgetCompactionSettings(): { enabled: boolean; reserveTokens: number; keepRecentTokens: number } {\n\t\treturn {\n\t\t\tenabled: this.getCompactionEnabled(),\n\t\t\treserveTokens: this.getCompactionReserveTokens(),\n\t\t\tkeepRecentTokens: this.getCompactionKeepRecentTokens(),\n\t\t};\n\t}\n\n\tgetBranchSummarySettings(): { reserveTokens: number; skipPrompt: boolean } {\n\t\treturn {\n\t\t\treserveTokens: this.settings.branchSummary?.reserveTokens ?? 16384,\n\t\t\tskipPrompt: this.settings.branchSummary?.skipPrompt ?? false,\n\t\t};\n\t}\n\n\tgetBranchSummarySkipPrompt(): boolean {\n\t\treturn this.settings.branchSummary?.skipPrompt ?? false;\n\t}\n\n\tgetRetryEnabled(): boolean {\n\t\treturn this.settings.retry?.enabled ?? true;\n\t}\n\n\tsetRetryEnabled(enabled: boolean): void {\n\t\tif (!this.globalSettings.retry) {\n\t\t\tthis.globalSettings.retry = {};\n\t\t}\n\t\tthis.globalSettings.retry.enabled = enabled;\n\t\tthis.markModified(\"retry\", \"enabled\");\n\t\tthis.save();\n\t}\n\n\tgetRetrySettings(): { enabled: boolean; maxRetries: number; baseDelayMs: number } {\n\t\treturn {\n\t\t\tenabled: this.getRetryEnabled(),\n\t\t\tmaxRetries: this.settings.retry?.maxRetries ?? 3,\n\t\t\tbaseDelayMs: this.settings.retry?.baseDelayMs ?? 2000,\n\t\t};\n\t}\n\n\tgetHttpIdleTimeoutMs(): number {\n\t\treturn parseTimeoutSetting(this.settings.httpIdleTimeoutMs, \"httpIdleTimeoutMs\") ?? DEFAULT_HTTP_IDLE_TIMEOUT_MS;\n\t}\n\n\tsetHttpIdleTimeoutMs(timeoutMs: number): void {\n\t\tif (!Number.isFinite(timeoutMs) || timeoutMs < 0) {\n\t\t\tthrow new Error(`Invalid httpIdleTimeoutMs setting: ${String(timeoutMs)}`);\n\t\t}\n\t\tthis.globalSettings.httpIdleTimeoutMs = Math.floor(timeoutMs);\n\t\tthis.markModified(\"httpIdleTimeoutMs\");\n\t\tthis.save();\n\t}\n\n\tgetProviderRetrySettings(): { timeoutMs?: number; maxRetries?: number; maxRetryDelayMs: number } {\n\t\treturn {\n\t\t\ttimeoutMs: this.settings.retry?.provider?.timeoutMs,\n\t\t\tmaxRetries: this.settings.retry?.provider?.maxRetries,\n\t\t\tmaxRetryDelayMs: this.settings.retry?.provider?.maxRetryDelayMs ?? 60000,\n\t\t};\n\t}\n\n\tgetWebSocketConnectTimeoutMs(): number | undefined {\n\t\treturn parseTimeoutSetting(this.settings.websocketConnectTimeoutMs, \"websocketConnectTimeoutMs\");\n\t}\n\n\tgetHideThinkingBlock(): boolean {\n\t\treturn this.settings.hideThinkingBlock ?? false;\n\t}\n\n\tgetShowCacheMissNotices(): boolean {\n\t\treturn this.settings.showCacheMissNotices ?? false;\n\t}\n\n\tgetExternalEditorCommand(): string {\n\t\tconst configuredEditor = this.settings.externalEditor;\n\t\tif (typeof configuredEditor === \"string\" && configuredEditor.trim() !== \"\") {\n\t\t\treturn configuredEditor;\n\t\t}\n\t\tconst environmentEditor = process.env.VISUAL || process.env.EDITOR;\n\t\tif (environmentEditor) {\n\t\t\treturn environmentEditor;\n\t\t}\n\t\treturn process.platform === \"win32\" ? \"notepad\" : \"nano\";\n\t}\n\n\tsetHideThinkingBlock(hide: boolean): void {\n\t\tthis.globalSettings.hideThinkingBlock = hide;\n\t\tthis.markModified(\"hideThinkingBlock\");\n\t\tthis.save();\n\t}\n\n\tsetShowCacheMissNotices(show: boolean): void {\n\t\tthis.globalSettings.showCacheMissNotices = show;\n\t\tthis.markModified(\"showCacheMissNotices\");\n\t\tthis.save();\n\t}\n\n\tgetShellPath(): string | undefined {\n\t\tconst shellPath = this.settings.shellPath;\n\t\treturn shellPath ? normalizePath(shellPath) : shellPath;\n\t}\n\n\tsetShellPath(path: string | undefined): void {\n\t\tthis.globalSettings.shellPath = path;\n\t\tthis.markModified(\"shellPath\");\n\t\tthis.save();\n\t}\n\n\tgetQuietStartup(): boolean {\n\t\treturn this.settings.quietStartup ?? false;\n\t}\n\n\tsetQuietStartup(quiet: boolean): void {\n\t\tthis.globalSettings.quietStartup = quiet;\n\t\tthis.markModified(\"quietStartup\");\n\t\tthis.save();\n\t}\n\n\tgetDefaultProjectTrust(): DefaultProjectTrust {\n\t\tconst value = this.globalSettings.defaultProjectTrust;\n\t\treturn value === \"always\" || value === \"never\" ? value : \"ask\";\n\t}\n\n\tsetDefaultProjectTrust(defaultProjectTrust: DefaultProjectTrust): void {\n\t\tthis.globalSettings.defaultProjectTrust = defaultProjectTrust;\n\t\tthis.markModified(\"defaultProjectTrust\");\n\t\tthis.save();\n\t}\n\n\tgetShellCommandPrefix(): string | undefined {\n\t\treturn this.settings.shellCommandPrefix;\n\t}\n\n\tsetShellCommandPrefix(prefix: string | undefined): void {\n\t\tthis.globalSettings.shellCommandPrefix = prefix;\n\t\tthis.markModified(\"shellCommandPrefix\");\n\t\tthis.save();\n\t}\n\n\tgetNpmCommand(): string[] | undefined {\n\t\treturn this.settings.npmCommand ? [...this.settings.npmCommand] : undefined;\n\t}\n\n\tsetNpmCommand(command: string[] | undefined): void {\n\t\tthis.globalSettings.npmCommand = command ? [...command] : undefined;\n\t\tthis.markModified(\"npmCommand\");\n\t\tthis.save();\n\t}\n\n\tgetCollapseChangelog(): boolean {\n\t\treturn this.settings.collapseChangelog ?? false;\n\t}\n\n\tsetCollapseChangelog(collapse: boolean): void {\n\t\tthis.globalSettings.collapseChangelog = collapse;\n\t\tthis.markModified(\"collapseChangelog\");\n\t\tthis.save();\n\t}\n\n\tgetEnableInstallTelemetry(): boolean {\n\t\treturn this.settings.enableInstallTelemetry ?? true;\n\t}\n\n\tsetEnableInstallTelemetry(enabled: boolean): void {\n\t\tthis.globalSettings.enableInstallTelemetry = enabled;\n\t\tthis.markModified(\"enableInstallTelemetry\");\n\t\tthis.save();\n\t}\n\n\tgetEnableAnalytics(): boolean {\n\t\treturn this.settings.enableAnalytics ?? false;\n\t}\n\n\tgetTrackingId(): string | undefined {\n\t\treturn this.settings.trackingId;\n\t}\n\n\t/** Set the analytics opt-in preference; generates a tracking identifier on first opt-in */\n\tsetEnableAnalytics(enabled: boolean): void {\n\t\tthis.globalSettings.enableAnalytics = enabled;\n\t\tthis.markModified(\"enableAnalytics\");\n\t\tif (enabled && !this.globalSettings.trackingId) {\n\t\t\tthis.globalSettings.trackingId = randomUUID();\n\t\t\tthis.markModified(\"trackingId\");\n\t\t}\n\t\tthis.save();\n\t}\n\n\tgetPackages(): PackageSource[] {\n\t\treturn [...(this.settings.packages ?? [])];\n\t}\n\n\tsetPackages(packages: PackageSource[]): void {\n\t\tthis.globalSettings.packages = packages;\n\t\tthis.markModified(\"packages\");\n\t\tthis.save();\n\t}\n\n\tsetProjectPackages(packages: PackageSource[]): void {\n\t\tthis.updateProjectSettings(\"packages\", (settings) => {\n\t\t\tsettings.packages = packages;\n\t\t});\n\t}\n\n\tgetExtensionPaths(): string[] {\n\t\treturn [...(this.settings.extensions ?? [])];\n\t}\n\n\tsetExtensionPaths(paths: string[]): void {\n\t\tthis.globalSettings.extensions = paths;\n\t\tthis.markModified(\"extensions\");\n\t\tthis.save();\n\t}\n\n\tsetProjectExtensionPaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"extensions\", (settings) => {\n\t\t\tsettings.extensions = paths;\n\t\t});\n\t}\n\n\tgetSkillPaths(): string[] {\n\t\treturn [...(this.settings.skills ?? [])];\n\t}\n\n\tsetSkillPaths(paths: string[]): void {\n\t\tthis.globalSettings.skills = paths;\n\t\tthis.markModified(\"skills\");\n\t\tthis.save();\n\t}\n\n\tsetProjectSkillPaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"skills\", (settings) => {\n\t\t\tsettings.skills = paths;\n\t\t});\n\t}\n\n\tgetPromptTemplatePaths(): string[] {\n\t\treturn [...(this.settings.prompts ?? [])];\n\t}\n\n\tsetPromptTemplatePaths(paths: string[]): void {\n\t\tthis.globalSettings.prompts = paths;\n\t\tthis.markModified(\"prompts\");\n\t\tthis.save();\n\t}\n\n\tsetProjectPromptTemplatePaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"prompts\", (settings) => {\n\t\t\tsettings.prompts = paths;\n\t\t});\n\t}\n\n\tgetThemePaths(): string[] {\n\t\treturn [...(this.settings.themes ?? [])];\n\t}\n\n\tsetThemePaths(paths: string[]): void {\n\t\tthis.globalSettings.themes = paths;\n\t\tthis.markModified(\"themes\");\n\t\tthis.save();\n\t}\n\n\tsetProjectThemePaths(paths: string[]): void {\n\t\tthis.updateProjectSettings(\"themes\", (settings) => {\n\t\t\tsettings.themes = paths;\n\t\t});\n\t}\n\n\tgetEnableSkillCommands(): boolean {\n\t\treturn this.settings.enableSkillCommands ?? true;\n\t}\n\n\tsetEnableSkillCommands(enabled: boolean): void {\n\t\tthis.globalSettings.enableSkillCommands = enabled;\n\t\tthis.markModified(\"enableSkillCommands\");\n\t\tthis.save();\n\t}\n\n\tgetThinkingBudgets(): ThinkingBudgetsSettings | undefined {\n\t\treturn this.settings.thinkingBudgets;\n\t}\n\n\tgetShowImages(): boolean {\n\t\treturn this.settings.terminal?.showImages ?? true;\n\t}\n\n\tsetShowImages(show: boolean): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.showImages = show;\n\t\tthis.markModified(\"terminal\", \"showImages\");\n\t\tthis.save();\n\t}\n\n\tgetImageWidthCells(): number {\n\t\tconst width = this.settings.terminal?.imageWidthCells;\n\t\tif (typeof width !== \"number\" || !Number.isFinite(width)) {\n\t\t\treturn 60;\n\t\t}\n\t\treturn Math.max(1, Math.floor(width));\n\t}\n\n\tsetImageWidthCells(width: number): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.imageWidthCells = Math.max(1, Math.floor(width));\n\t\tthis.markModified(\"terminal\", \"imageWidthCells\");\n\t\tthis.save();\n\t}\n\n\tgetClearOnShrink(): boolean {\n\t\t// Settings takes precedence, then env var, then default false\n\t\tif (this.settings.terminal?.clearOnShrink !== undefined) {\n\t\t\treturn this.settings.terminal.clearOnShrink;\n\t\t}\n\t\treturn process.env.PI_CLEAR_ON_SHRINK === \"1\";\n\t}\n\n\tsetClearOnShrink(enabled: boolean): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.clearOnShrink = enabled;\n\t\tthis.markModified(\"terminal\", \"clearOnShrink\");\n\t\tthis.save();\n\t}\n\n\tgetShowTerminalProgress(): boolean {\n\t\treturn this.settings.terminal?.showTerminalProgress ?? false;\n\t}\n\n\tsetShowTerminalProgress(enabled: boolean): void {\n\t\tif (!this.globalSettings.terminal) {\n\t\t\tthis.globalSettings.terminal = {};\n\t\t}\n\t\tthis.globalSettings.terminal.showTerminalProgress = enabled;\n\t\tthis.markModified(\"terminal\", \"showTerminalProgress\");\n\t\tthis.save();\n\t}\n\n\tgetImageAutoResize(): boolean {\n\t\treturn this.settings.images?.autoResize ?? true;\n\t}\n\n\tsetImageAutoResize(enabled: boolean): void {\n\t\tif (!this.globalSettings.images) {\n\t\t\tthis.globalSettings.images = {};\n\t\t}\n\t\tthis.globalSettings.images.autoResize = enabled;\n\t\tthis.markModified(\"images\", \"autoResize\");\n\t\tthis.save();\n\t}\n\n\tgetBlockImages(): boolean {\n\t\treturn this.settings.images?.blockImages ?? false;\n\t}\n\n\tsetBlockImages(blocked: boolean): void {\n\t\tif (!this.globalSettings.images) {\n\t\t\tthis.globalSettings.images = {};\n\t\t}\n\t\tthis.globalSettings.images.blockImages = blocked;\n\t\tthis.markModified(\"images\", \"blockImages\");\n\t\tthis.save();\n\t}\n\n\tgetEnabledModels(): string[] | undefined {\n\t\treturn this.settings.enabledModels;\n\t}\n\n\tsetEnabledModels(patterns: string[] | undefined): void {\n\t\tthis.globalSettings.enabledModels = patterns;\n\t\tthis.markModified(\"enabledModels\");\n\t\tthis.save();\n\t}\n\n\tgetDoubleEscapeAction(): \"fork\" | \"tree\" | \"none\" {\n\t\treturn this.settings.doubleEscapeAction ?? \"tree\";\n\t}\n\n\tsetDoubleEscapeAction(action: \"fork\" | \"tree\" | \"none\"): void {\n\t\tthis.globalSettings.doubleEscapeAction = action;\n\t\tthis.markModified(\"doubleEscapeAction\");\n\t\tthis.save();\n\t}\n\n\tgetTreeFilterMode(): \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\" {\n\t\tconst mode = this.settings.treeFilterMode;\n\t\tconst valid = [\"default\", \"no-tools\", \"user-only\", \"labeled-only\", \"all\"];\n\t\treturn mode && valid.includes(mode) ? mode : \"default\";\n\t}\n\n\tsetTreeFilterMode(mode: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"): void {\n\t\tthis.globalSettings.treeFilterMode = mode;\n\t\tthis.markModified(\"treeFilterMode\");\n\t\tthis.save();\n\t}\n\n\tgetShowHardwareCursor(): boolean {\n\t\treturn this.settings.showHardwareCursor ?? process.env.PI_HARDWARE_CURSOR === \"1\";\n\t}\n\n\tsetShowHardwareCursor(enabled: boolean): void {\n\t\tthis.globalSettings.showHardwareCursor = enabled;\n\t\tthis.markModified(\"showHardwareCursor\");\n\t\tthis.save();\n\t}\n\n\tgetEditorPaddingX(): number {\n\t\treturn this.settings.editorPaddingX ?? 0;\n\t}\n\n\tsetEditorPaddingX(padding: number): void {\n\t\tthis.globalSettings.editorPaddingX = Math.max(0, Math.min(3, Math.floor(padding)));\n\t\tthis.markModified(\"editorPaddingX\");\n\t\tthis.save();\n\t}\n\n\tgetOutputPad(): 0 | 1 {\n\t\treturn this.settings.outputPad === 0 ? 0 : 1;\n\t}\n\n\tsetOutputPad(padding: 0 | 1): void {\n\t\tthis.globalSettings.outputPad = padding;\n\t\tthis.markModified(\"outputPad\");\n\t\tthis.save();\n\t}\n\n\tgetAutocompleteMaxVisible(): number {\n\t\treturn this.settings.autocompleteMaxVisible ?? 5;\n\t}\n\n\tsetAutocompleteMaxVisible(maxVisible: number): void {\n\t\tthis.globalSettings.autocompleteMaxVisible = Math.max(3, Math.min(20, Math.floor(maxVisible)));\n\t\tthis.markModified(\"autocompleteMaxVisible\");\n\t\tthis.save();\n\t}\n\n\tgetCodeBlockIndent(): string {\n\t\treturn this.settings.markdown?.codeBlockIndent ?? \" \";\n\t}\n\n\tgetWarnings(): WarningSettings {\n\t\treturn { ...(this.settings.warnings ?? {}) };\n\t}\n\n\tsetWarnings(warnings: WarningSettings): void {\n\t\tthis.globalSettings.warnings = { ...warnings };\n\t\tthis.markModified(\"warnings\");\n\t\tthis.save();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/skills.d.ts b/dist/core/skills.d.ts new file mode 100644 index 0000000..20e3c18 --- /dev/null +++ b/dist/core/skills.d.ts @@ -0,0 +1,60 @@ +import type { ResourceDiagnostic } from "./diagnostics.ts"; +import { type SourceInfo } from "./source-info.ts"; +export interface SkillFrontmatter { + name?: string; + description?: string; + "disable-model-invocation"?: boolean; + [key: string]: unknown; +} +export interface Skill { + name: string; + description: string; + filePath: string; + baseDir: string; + sourceInfo: SourceInfo; + disableModelInvocation: boolean; +} +export interface LoadSkillsResult { + skills: Skill[]; + diagnostics: ResourceDiagnostic[]; +} +export interface LoadSkillsFromDirOptions { + /** Directory to scan for skills */ + dir: string; + /** Source identifier for these skills */ + source: string; +} +/** + * Load skills from a directory. + * + * Discovery rules: + * - if a directory contains SKILL.md, treat it as a skill root and do not recurse further + * - otherwise, load direct .md children in the root + * - recurse into subdirectories to find SKILL.md + */ +export declare function loadSkillsFromDir(options: LoadSkillsFromDirOptions): LoadSkillsResult; +/** + * Format skills for inclusion in a system prompt. + * Uses XML format per Agent Skills standard. + * See: https://agentskills.io/integrate-skills + * + * Skills with disableModelInvocation=true are excluded from the prompt + * (they can only be invoked explicitly via /skill:name commands). + */ +export declare function formatSkillsForPrompt(skills: Skill[]): string; +export interface LoadSkillsOptions { + /** Working directory for project-local skills. */ + cwd: string; + /** Agent config directory for global skills. */ + agentDir: string; + /** Explicit skill paths (files or directories) */ + skillPaths: string[]; + /** Include default skills directories. */ + includeDefaults: boolean; +} +/** + * Load skills from all configured locations. + * Returns skills and any validation diagnostics. + */ +export declare function loadSkills(options: LoadSkillsOptions): LoadSkillsResult; +//# sourceMappingURL=skills.d.ts.map \ No newline at end of file diff --git a/dist/core/skills.d.ts.map b/dist/core/skills.d.ts.map new file mode 100644 index 0000000..b781ca8 --- /dev/null +++ b/dist/core/skills.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"skills.d.ts","sourceRoot":"","sources":["../../src/core/skills.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAA6B,KAAK,UAAU,EAAE,MAAM,kBAAkB,CAAC;AA2D9E,MAAM,WAAW,gBAAgB;IAChC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,0BAA0B,CAAC,EAAE,OAAO,CAAC;IACrC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACvB;AAED,MAAM,WAAW,KAAK;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,UAAU,CAAC;IACvB,sBAAsB,EAAE,OAAO,CAAC;CAChC;AAED,MAAM,WAAW,gBAAgB;IAChC,MAAM,EAAE,KAAK,EAAE,CAAC;IAChB,WAAW,EAAE,kBAAkB,EAAE,CAAC;CAClC;AA2CD,MAAM,WAAW,wBAAwB;IACxC,mCAAmC;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,yCAAyC;IACzC,MAAM,EAAE,MAAM,CAAC;CACf;AA0BD;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,gBAAgB,CAGrF;AA4JD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,CA0B7D;AAWD,MAAM,WAAW,iBAAiB;IACjC,kDAAkD;IAClD,GAAG,EAAE,MAAM,CAAC;IACZ,gDAAgD;IAChD,QAAQ,EAAE,MAAM,CAAC;IACjB,kDAAkD;IAClD,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,0CAA0C;IAC1C,eAAe,EAAE,OAAO,CAAC;CACzB;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,gBAAgB,CAoGvE","sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport ignore from \"ignore\";\nimport { basename, dirname, join, relative, resolve, sep } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { parseFrontmatter } from \"../utils/frontmatter.ts\";\nimport { canonicalizePath, resolvePath } from \"../utils/paths.ts\";\nimport type { ResourceDiagnostic } from \"./diagnostics.ts\";\nimport { createSyntheticSourceInfo, type SourceInfo } from \"./source-info.ts\";\n\n/** Max name length per spec */\nconst MAX_NAME_LENGTH = 64;\n\n/** Max description length per spec */\nconst MAX_DESCRIPTION_LENGTH = 1024;\n\nconst IGNORE_FILE_NAMES = [\".gitignore\", \".ignore\", \".fdignore\"];\n\ntype IgnoreMatcher = ReturnType;\n\nfunction toPosixPath(p: string): string {\n\treturn p.split(sep).join(\"/\");\n}\n\nfunction prefixIgnorePattern(line: string, prefix: string): string | null {\n\tconst trimmed = line.trim();\n\tif (!trimmed) return null;\n\tif (trimmed.startsWith(\"#\") && !trimmed.startsWith(\"\\\\#\")) return null;\n\n\tlet pattern = line;\n\tlet negated = false;\n\n\tif (pattern.startsWith(\"!\")) {\n\t\tnegated = true;\n\t\tpattern = pattern.slice(1);\n\t} else if (pattern.startsWith(\"\\\\!\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tif (pattern.startsWith(\"/\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tconst prefixed = prefix ? `${prefix}${pattern}` : pattern;\n\treturn negated ? `!${prefixed}` : prefixed;\n}\n\nfunction addIgnoreRules(ig: IgnoreMatcher, dir: string, rootDir: string): void {\n\tconst relativeDir = relative(rootDir, dir);\n\tconst prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : \"\";\n\n\tfor (const filename of IGNORE_FILE_NAMES) {\n\t\tconst ignorePath = join(dir, filename);\n\t\tif (!existsSync(ignorePath)) continue;\n\t\ttry {\n\t\t\tconst content = readFileSync(ignorePath, \"utf-8\");\n\t\t\tconst patterns = content\n\t\t\t\t.split(/\\r?\\n/)\n\t\t\t\t.map((line) => prefixIgnorePattern(line, prefix))\n\t\t\t\t.filter((line): line is string => Boolean(line));\n\t\t\tif (patterns.length > 0) {\n\t\t\t\tig.add(patterns);\n\t\t\t}\n\t\t} catch {}\n\t}\n}\n\nexport interface SkillFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t\"disable-model-invocation\"?: boolean;\n\t[key: string]: unknown;\n}\n\nexport interface Skill {\n\tname: string;\n\tdescription: string;\n\tfilePath: string;\n\tbaseDir: string;\n\tsourceInfo: SourceInfo;\n\tdisableModelInvocation: boolean;\n}\n\nexport interface LoadSkillsResult {\n\tskills: Skill[];\n\tdiagnostics: ResourceDiagnostic[];\n}\n\n/**\n * Validate skill name per Agent Skills spec.\n * Returns array of validation error messages (empty if valid).\n */\nfunction validateName(name: string): string[] {\n\tconst errors: string[] = [];\n\n\tif (name.length > MAX_NAME_LENGTH) {\n\t\terrors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\t}\n\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(`name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)`);\n\t}\n\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) {\n\t\terrors.push(`name must not start or end with a hyphen`);\n\t}\n\n\tif (name.includes(\"--\")) {\n\t\terrors.push(`name must not contain consecutive hyphens`);\n\t}\n\n\treturn errors;\n}\n\n/**\n * Validate description per Agent Skills spec.\n */\nfunction validateDescription(description: string | undefined): string[] {\n\tconst errors: string[] = [];\n\n\tif (!description || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\n\treturn errors;\n}\n\nexport interface LoadSkillsFromDirOptions {\n\t/** Directory to scan for skills */\n\tdir: string;\n\t/** Source identifier for these skills */\n\tsource: string;\n}\n\nfunction createSkillSourceInfo(filePath: string, baseDir: string, source: string): SourceInfo {\n\tswitch (source) {\n\t\tcase \"user\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"user\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tcase \"project\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"project\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tcase \"path\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tdefault:\n\t\t\treturn createSyntheticSourceInfo(filePath, { source, baseDir });\n\t}\n}\n\n/**\n * Load skills from a directory.\n *\n * Discovery rules:\n * - if a directory contains SKILL.md, treat it as a skill root and do not recurse further\n * - otherwise, load direct .md children in the root\n * - recurse into subdirectories to find SKILL.md\n */\nexport function loadSkillsFromDir(options: LoadSkillsFromDirOptions): LoadSkillsResult {\n\tconst { dir, source } = options;\n\treturn loadSkillsFromDirInternal(dir, source, true);\n}\n\nfunction loadSkillsFromDirInternal(\n\tdir: string,\n\tsource: string,\n\tincludeRootFiles: boolean,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): LoadSkillsResult {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\tif (!existsSync(dir)) {\n\t\treturn { skills, diagnostics };\n\t}\n\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\taddIgnoreRules(ig, dir, root);\n\n\ttry {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name !== \"SKILL.md\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tif (!isFile || ig.ignores(relPath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst result = loadSkillFromFile(fullPath, source);\n\t\t\tif (result.skill) {\n\t\t\t\tskills.push(result.skill);\n\t\t\t}\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t\treturn { skills, diagnostics };\n\t\t}\n\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name.startsWith(\".\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Skip node_modules to avoid scanning dependencies\n\t\t\tif (entry.name === \"node_modules\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\n\t\t\t// For symlinks, check if they point to a directory and follow them\n\t\t\tlet isDirectory = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDirectory = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\t// Broken symlink, skip it\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tconst ignorePath = isDirectory ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (isDirectory) {\n\t\t\t\tconst subResult = loadSkillsFromDirInternal(fullPath, source, false, ig, root);\n\t\t\t\tskills.push(...subResult.skills);\n\t\t\t\tdiagnostics.push(...subResult.diagnostics);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!isFile || !includeRootFiles || !entry.name.endsWith(\".md\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst result = loadSkillFromFile(fullPath, source);\n\t\t\tif (result.skill) {\n\t\t\t\tskills.push(result.skill);\n\t\t\t}\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t}\n\t} catch {}\n\n\treturn { skills, diagnostics };\n}\n\nfunction loadSkillFromFile(\n\tfilePath: string,\n\tsource: string,\n): { skill: Skill | null; diagnostics: ResourceDiagnostic[] } {\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\ttry {\n\t\tconst rawContent = readFileSync(filePath, \"utf-8\");\n\t\tconst { frontmatter } = parseFrontmatter(rawContent);\n\t\tconst skillDir = dirname(filePath);\n\t\tconst parentDirName = basename(skillDir);\n\n\t\t// Validate description\n\t\tconst descErrors = validateDescription(frontmatter.description);\n\t\tfor (const error of descErrors) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\t}\n\n\t\t// Use name from frontmatter, or fall back to parent directory name\n\t\tconst name = frontmatter.name || parentDirName;\n\n\t\t// Validate name\n\t\tconst nameErrors = validateName(name);\n\t\tfor (const error of nameErrors) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\t}\n\n\t\t// Still load the skill even with warnings (unless description is completely missing)\n\t\tif (!frontmatter.description || frontmatter.description.trim() === \"\") {\n\t\t\treturn { skill: null, diagnostics };\n\t\t}\n\n\t\treturn {\n\t\t\tskill: {\n\t\t\t\tname,\n\t\t\t\tdescription: frontmatter.description,\n\t\t\t\tfilePath,\n\t\t\t\tbaseDir: skillDir,\n\t\t\t\tsourceInfo: createSkillSourceInfo(filePath, skillDir, source),\n\t\t\t\tdisableModelInvocation: frontmatter[\"disable-model-invocation\"] === true,\n\t\t\t},\n\t\t\tdiagnostics,\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to parse skill file\";\n\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n}\n\n/**\n * Format skills for inclusion in a system prompt.\n * Uses XML format per Agent Skills standard.\n * See: https://agentskills.io/integrate-skills\n *\n * Skills with disableModelInvocation=true are excluded from the prompt\n * (they can only be invoked explicitly via /skill:name commands).\n */\nexport function formatSkillsForPrompt(skills: Skill[]): string {\n\tconst visibleSkills = skills.filter((s) => !s.disableModelInvocation);\n\n\tif (visibleSkills.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\n\t\t\"\\n\\nThe following skills provide specialized instructions for specific tasks.\",\n\t\t\"Use the read tool to load a skill's file when the task matches its description.\",\n\t\t\"When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\",\n\t\t\"\",\n\t\t\"\",\n\t];\n\n\tfor (const skill of visibleSkills) {\n\t\tlines.push(\" \");\n\t\tlines.push(` ${escapeXml(skill.name)}`);\n\t\tlines.push(` ${escapeXml(skill.description)}`);\n\t\tlines.push(` ${escapeXml(skill.filePath)}`);\n\t\tlines.push(\" \");\n\t}\n\n\tlines.push(\"\");\n\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&\")\n\t\t.replace(//g, \">\")\n\t\t.replace(/\"/g, \""\")\n\t\t.replace(/'/g, \"'\");\n}\n\nexport interface LoadSkillsOptions {\n\t/** Working directory for project-local skills. */\n\tcwd: string;\n\t/** Agent config directory for global skills. */\n\tagentDir: string;\n\t/** Explicit skill paths (files or directories) */\n\tskillPaths: string[];\n\t/** Include default skills directories. */\n\tincludeDefaults: boolean;\n}\n\n/**\n * Load skills from all configured locations.\n * Returns skills and any validation diagnostics.\n */\nexport function loadSkills(options: LoadSkillsOptions): LoadSkillsResult {\n\tconst { agentDir, skillPaths, includeDefaults } = options;\n\n\t// Resolve agentDir - if not provided, use default from config\n\tconst resolvedCwd = resolvePath(options.cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir ?? getAgentDir());\n\n\tconst skillMap = new Map();\n\tconst realPathSet = new Set();\n\tconst allDiagnostics: ResourceDiagnostic[] = [];\n\tconst collisionDiagnostics: ResourceDiagnostic[] = [];\n\n\tfunction addSkills(result: LoadSkillsResult) {\n\t\tallDiagnostics.push(...result.diagnostics);\n\t\tfor (const skill of result.skills) {\n\t\t\t// Resolve symlinks to detect duplicate files\n\t\t\tconst realPath = canonicalizePath(skill.filePath);\n\n\t\t\t// Skip silently if we've already loaded this exact file (via symlink)\n\t\t\tif (realPathSet.has(realPath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst existing = skillMap.get(skill.name);\n\t\t\tif (existing) {\n\t\t\t\tcollisionDiagnostics.push({\n\t\t\t\t\ttype: \"collision\",\n\t\t\t\t\tmessage: `name \"${skill.name}\" collision`,\n\t\t\t\t\tpath: skill.filePath,\n\t\t\t\t\tcollision: {\n\t\t\t\t\t\tresourceType: \"skill\",\n\t\t\t\t\t\tname: skill.name,\n\t\t\t\t\t\twinnerPath: existing.filePath,\n\t\t\t\t\t\tloserPath: skill.filePath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tskillMap.set(skill.name, skill);\n\t\t\t\trealPathSet.add(realPath);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (includeDefaults) {\n\t\taddSkills(loadSkillsFromDirInternal(join(resolvedAgentDir, \"skills\"), \"user\", true));\n\t\taddSkills(loadSkillsFromDirInternal(resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\"), \"project\", true));\n\t}\n\n\tconst userSkillsDir = join(resolvedAgentDir, \"skills\");\n\tconst projectSkillsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\");\n\n\tconst isUnderPath = (target: string, root: string): boolean => {\n\t\tconst normalizedRoot = resolve(root);\n\t\tif (target === normalizedRoot) {\n\t\t\treturn true;\n\t\t}\n\t\tconst prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;\n\t\treturn target.startsWith(prefix);\n\t};\n\n\tconst getSource = (resolvedPath: string): \"user\" | \"project\" | \"path\" => {\n\t\tif (!includeDefaults) {\n\t\t\tif (isUnderPath(resolvedPath, userSkillsDir)) return \"user\";\n\t\t\tif (isUnderPath(resolvedPath, projectSkillsDir)) return \"project\";\n\t\t}\n\t\treturn \"path\";\n\t};\n\n\tfor (const rawPath of skillPaths) {\n\t\tconst resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true });\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path does not exist\", path: resolvedPath });\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stats = statSync(resolvedPath);\n\t\t\tconst source = getSource(resolvedPath);\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\taddSkills(loadSkillsFromDirInternal(resolvedPath, source, true));\n\t\t\t} else if (stats.isFile() && resolvedPath.endsWith(\".md\")) {\n\t\t\t\tconst result = loadSkillFromFile(resolvedPath, source);\n\t\t\t\tif (result.skill) {\n\t\t\t\t\taddSkills({ skills: [result.skill], diagnostics: result.diagnostics });\n\t\t\t\t} else {\n\t\t\t\t\tallDiagnostics.push(...result.diagnostics);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path is not a markdown file\", path: resolvedPath });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read skill path\";\n\t\t\tallDiagnostics.push({ type: \"warning\", message, path: resolvedPath });\n\t\t}\n\t}\n\n\treturn {\n\t\tskills: Array.from(skillMap.values()),\n\t\tdiagnostics: [...allDiagnostics, ...collisionDiagnostics],\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/skills.js b/dist/core/skills.js new file mode 100644 index 0000000..4e7e784 --- /dev/null +++ b/dist/core/skills.js @@ -0,0 +1,387 @@ +import { existsSync, readdirSync, readFileSync, statSync } from "fs"; +import ignore from "ignore"; +import { basename, dirname, join, relative, resolve, sep } from "path"; +import { CONFIG_DIR_NAME, getAgentDir } from "../config.js"; +import { parseFrontmatter } from "../utils/frontmatter.js"; +import { canonicalizePath, resolvePath } from "../utils/paths.js"; +import { createSyntheticSourceInfo } from "./source-info.js"; +/** Max name length per spec */ +const MAX_NAME_LENGTH = 64; +/** Max description length per spec */ +const MAX_DESCRIPTION_LENGTH = 1024; +const IGNORE_FILE_NAMES = [".gitignore", ".ignore", ".fdignore"]; +function toPosixPath(p) { + return p.split(sep).join("/"); +} +function prefixIgnorePattern(line, prefix) { + const trimmed = line.trim(); + if (!trimmed) + return null; + if (trimmed.startsWith("#") && !trimmed.startsWith("\\#")) + return null; + let pattern = line; + let negated = false; + if (pattern.startsWith("!")) { + negated = true; + pattern = pattern.slice(1); + } + else if (pattern.startsWith("\\!")) { + pattern = pattern.slice(1); + } + if (pattern.startsWith("/")) { + pattern = pattern.slice(1); + } + const prefixed = prefix ? `${prefix}${pattern}` : pattern; + return negated ? `!${prefixed}` : prefixed; +} +function addIgnoreRules(ig, dir, rootDir) { + const relativeDir = relative(rootDir, dir); + const prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : ""; + for (const filename of IGNORE_FILE_NAMES) { + const ignorePath = join(dir, filename); + if (!existsSync(ignorePath)) + continue; + try { + const content = readFileSync(ignorePath, "utf-8"); + const patterns = content + .split(/\r?\n/) + .map((line) => prefixIgnorePattern(line, prefix)) + .filter((line) => Boolean(line)); + if (patterns.length > 0) { + ig.add(patterns); + } + } + catch { } + } +} +/** + * Validate skill name per Agent Skills spec. + * Returns array of validation error messages (empty if valid). + */ +function validateName(name) { + const errors = []; + if (name.length > MAX_NAME_LENGTH) { + errors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`); + } + if (!/^[a-z0-9-]+$/.test(name)) { + errors.push(`name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)`); + } + if (name.startsWith("-") || name.endsWith("-")) { + errors.push(`name must not start or end with a hyphen`); + } + if (name.includes("--")) { + errors.push(`name must not contain consecutive hyphens`); + } + return errors; +} +/** + * Validate description per Agent Skills spec. + */ +function validateDescription(description) { + const errors = []; + if (!description || description.trim() === "") { + errors.push("description is required"); + } + else if (description.length > MAX_DESCRIPTION_LENGTH) { + errors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`); + } + return errors; +} +function createSkillSourceInfo(filePath, baseDir, source) { + switch (source) { + case "user": + return createSyntheticSourceInfo(filePath, { + source: "local", + scope: "user", + baseDir, + }); + case "project": + return createSyntheticSourceInfo(filePath, { + source: "local", + scope: "project", + baseDir, + }); + case "path": + return createSyntheticSourceInfo(filePath, { + source: "local", + baseDir, + }); + default: + return createSyntheticSourceInfo(filePath, { source, baseDir }); + } +} +/** + * Load skills from a directory. + * + * Discovery rules: + * - if a directory contains SKILL.md, treat it as a skill root and do not recurse further + * - otherwise, load direct .md children in the root + * - recurse into subdirectories to find SKILL.md + */ +export function loadSkillsFromDir(options) { + const { dir, source } = options; + return loadSkillsFromDirInternal(dir, source, true); +} +function loadSkillsFromDirInternal(dir, source, includeRootFiles, ignoreMatcher, rootDir) { + const skills = []; + const diagnostics = []; + if (!existsSync(dir)) { + return { skills, diagnostics }; + } + const root = rootDir ?? dir; + const ig = ignoreMatcher ?? ignore(); + addIgnoreRules(ig, dir, root); + try { + const entries = readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + if (entry.name !== "SKILL.md") { + continue; + } + const fullPath = join(dir, entry.name); + let isFile = entry.isFile(); + if (entry.isSymbolicLink()) { + try { + isFile = statSync(fullPath).isFile(); + } + catch { + continue; + } + } + const relPath = toPosixPath(relative(root, fullPath)); + if (!isFile || ig.ignores(relPath)) { + continue; + } + const result = loadSkillFromFile(fullPath, source); + if (result.skill) { + skills.push(result.skill); + } + diagnostics.push(...result.diagnostics); + return { skills, diagnostics }; + } + for (const entry of entries) { + if (entry.name.startsWith(".")) { + continue; + } + // Skip node_modules to avoid scanning dependencies + if (entry.name === "node_modules") { + continue; + } + const fullPath = join(dir, entry.name); + // For symlinks, check if they point to a directory and follow them + let isDirectory = entry.isDirectory(); + let isFile = entry.isFile(); + if (entry.isSymbolicLink()) { + try { + const stats = statSync(fullPath); + isDirectory = stats.isDirectory(); + isFile = stats.isFile(); + } + catch { + // Broken symlink, skip it + continue; + } + } + const relPath = toPosixPath(relative(root, fullPath)); + const ignorePath = isDirectory ? `${relPath}/` : relPath; + if (ig.ignores(ignorePath)) { + continue; + } + if (isDirectory) { + const subResult = loadSkillsFromDirInternal(fullPath, source, false, ig, root); + skills.push(...subResult.skills); + diagnostics.push(...subResult.diagnostics); + continue; + } + if (!isFile || !includeRootFiles || !entry.name.endsWith(".md")) { + continue; + } + const result = loadSkillFromFile(fullPath, source); + if (result.skill) { + skills.push(result.skill); + } + diagnostics.push(...result.diagnostics); + } + } + catch { } + return { skills, diagnostics }; +} +function loadSkillFromFile(filePath, source) { + const diagnostics = []; + try { + const rawContent = readFileSync(filePath, "utf-8"); + const { frontmatter } = parseFrontmatter(rawContent); + const skillDir = dirname(filePath); + const parentDirName = basename(skillDir); + // Validate description + const descErrors = validateDescription(frontmatter.description); + for (const error of descErrors) { + diagnostics.push({ type: "warning", message: error, path: filePath }); + } + // Use name from frontmatter, or fall back to parent directory name + const name = frontmatter.name || parentDirName; + // Validate name + const nameErrors = validateName(name); + for (const error of nameErrors) { + diagnostics.push({ type: "warning", message: error, path: filePath }); + } + // Still load the skill even with warnings (unless description is completely missing) + if (!frontmatter.description || frontmatter.description.trim() === "") { + return { skill: null, diagnostics }; + } + return { + skill: { + name, + description: frontmatter.description, + filePath, + baseDir: skillDir, + sourceInfo: createSkillSourceInfo(filePath, skillDir, source), + disableModelInvocation: frontmatter["disable-model-invocation"] === true, + }, + diagnostics, + }; + } + catch (error) { + const message = error instanceof Error ? error.message : "failed to parse skill file"; + diagnostics.push({ type: "warning", message, path: filePath }); + return { skill: null, diagnostics }; + } +} +/** + * Format skills for inclusion in a system prompt. + * Uses XML format per Agent Skills standard. + * See: https://agentskills.io/integrate-skills + * + * Skills with disableModelInvocation=true are excluded from the prompt + * (they can only be invoked explicitly via /skill:name commands). + */ +export function formatSkillsForPrompt(skills) { + const visibleSkills = skills.filter((s) => !s.disableModelInvocation); + if (visibleSkills.length === 0) { + return ""; + } + const lines = [ + "\n\nThe following skills provide specialized instructions for specific tasks.", + "Use the read tool to load a skill's file when the task matches its description.", + "When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.", + "", + "", + ]; + for (const skill of visibleSkills) { + lines.push(" "); + lines.push(` ${escapeXml(skill.name)}`); + lines.push(` ${escapeXml(skill.description)}`); + lines.push(` ${escapeXml(skill.filePath)}`); + lines.push(" "); + } + lines.push(""); + return lines.join("\n"); +} +function escapeXml(str) { + return str + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} +/** + * Load skills from all configured locations. + * Returns skills and any validation diagnostics. + */ +export function loadSkills(options) { + const { agentDir, skillPaths, includeDefaults } = options; + // Resolve agentDir - if not provided, use default from config + const resolvedCwd = resolvePath(options.cwd); + const resolvedAgentDir = resolvePath(agentDir ?? getAgentDir()); + const skillMap = new Map(); + const realPathSet = new Set(); + const allDiagnostics = []; + const collisionDiagnostics = []; + function addSkills(result) { + allDiagnostics.push(...result.diagnostics); + for (const skill of result.skills) { + // Resolve symlinks to detect duplicate files + const realPath = canonicalizePath(skill.filePath); + // Skip silently if we've already loaded this exact file (via symlink) + if (realPathSet.has(realPath)) { + continue; + } + const existing = skillMap.get(skill.name); + if (existing) { + collisionDiagnostics.push({ + type: "collision", + message: `name "${skill.name}" collision`, + path: skill.filePath, + collision: { + resourceType: "skill", + name: skill.name, + winnerPath: existing.filePath, + loserPath: skill.filePath, + }, + }); + } + else { + skillMap.set(skill.name, skill); + realPathSet.add(realPath); + } + } + } + if (includeDefaults) { + addSkills(loadSkillsFromDirInternal(join(resolvedAgentDir, "skills"), "user", true)); + addSkills(loadSkillsFromDirInternal(resolve(resolvedCwd, CONFIG_DIR_NAME, "skills"), "project", true)); + } + const userSkillsDir = join(resolvedAgentDir, "skills"); + const projectSkillsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, "skills"); + const isUnderPath = (target, root) => { + const normalizedRoot = resolve(root); + if (target === normalizedRoot) { + return true; + } + const prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`; + return target.startsWith(prefix); + }; + const getSource = (resolvedPath) => { + if (!includeDefaults) { + if (isUnderPath(resolvedPath, userSkillsDir)) + return "user"; + if (isUnderPath(resolvedPath, projectSkillsDir)) + return "project"; + } + return "path"; + }; + for (const rawPath of skillPaths) { + const resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true }); + if (!existsSync(resolvedPath)) { + allDiagnostics.push({ type: "warning", message: "skill path does not exist", path: resolvedPath }); + continue; + } + try { + const stats = statSync(resolvedPath); + const source = getSource(resolvedPath); + if (stats.isDirectory()) { + addSkills(loadSkillsFromDirInternal(resolvedPath, source, true)); + } + else if (stats.isFile() && resolvedPath.endsWith(".md")) { + const result = loadSkillFromFile(resolvedPath, source); + if (result.skill) { + addSkills({ skills: [result.skill], diagnostics: result.diagnostics }); + } + else { + allDiagnostics.push(...result.diagnostics); + } + } + else { + allDiagnostics.push({ type: "warning", message: "skill path is not a markdown file", path: resolvedPath }); + } + } + catch (error) { + const message = error instanceof Error ? error.message : "failed to read skill path"; + allDiagnostics.push({ type: "warning", message, path: resolvedPath }); + } + } + return { + skills: Array.from(skillMap.values()), + diagnostics: [...allDiagnostics, ...collisionDiagnostics], + }; +} +//# sourceMappingURL=skills.js.map \ No newline at end of file diff --git a/dist/core/skills.js.map b/dist/core/skills.js.map new file mode 100644 index 0000000..7afd3b9 --- /dev/null +++ b/dist/core/skills.js.map @@ -0,0 +1 @@ +{"version":3,"file":"skills.js","sourceRoot":"","sources":["../../src/core/skills.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACrE,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAElE,OAAO,EAAE,yBAAyB,EAAmB,MAAM,kBAAkB,CAAC;AAE9E,+BAA+B;AAC/B,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B,sCAAsC;AACtC,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAEpC,MAAM,iBAAiB,GAAG,CAAC,Y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M,EAAE,IAAI,YAAY,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;gBAC3D,MAAM,MAAM,GAAG,iBAAiB,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;gBACvD,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;oBAClB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC;gBACxE,CAAC;qBAAM,CAAC;oBACP,cAAc,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;gBAC5C,CAAC;YACF,CAAC;iBAAM,CAAC;gBACP,cAAc,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,mCAAmC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;YAC5G,CAAC;QACF,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,2BAA2B,CAAC;YACrF,cAAc,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;QACvE,CAAC;IACF,CAAC;IAED,OAAO;QACN,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QACrC,WAAW,EAAE,CAAC,GAAG,cAAc,EAAE,GAAG,oBAAoB,CAAC;KACzD,CAAC;AAAA,CACF","sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport ignore from \"ignore\";\nimport { basename, dirname, join, relative, resolve, sep } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { parseFrontmatter } from \"../utils/frontmatter.ts\";\nimport { canonicalizePath, resolvePath } from \"../utils/paths.ts\";\nimport type { ResourceDiagnostic } from \"./diagnostics.ts\";\nimport { createSyntheticSourceInfo, type SourceInfo } from \"./source-info.ts\";\n\n/** Max name length per spec */\nconst MAX_NAME_LENGTH = 64;\n\n/** Max description length per spec */\nconst MAX_DESCRIPTION_LENGTH = 1024;\n\nconst IGNORE_FILE_NAMES = [\".gitignore\", \".ignore\", \".fdignore\"];\n\ntype IgnoreMatcher = ReturnType;\n\nfunction toPosixPath(p: string): string {\n\treturn p.split(sep).join(\"/\");\n}\n\nfunction prefixIgnorePattern(line: string, prefix: string): string | null {\n\tconst trimmed = line.trim();\n\tif (!trimmed) return null;\n\tif (trimmed.startsWith(\"#\") && !trimmed.startsWith(\"\\\\#\")) return null;\n\n\tlet pattern = line;\n\tlet negated = false;\n\n\tif (pattern.startsWith(\"!\")) {\n\t\tnegated = true;\n\t\tpattern = pattern.slice(1);\n\t} else if (pattern.startsWith(\"\\\\!\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tif (pattern.startsWith(\"/\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tconst prefixed = prefix ? `${prefix}${pattern}` : pattern;\n\treturn negated ? `!${prefixed}` : prefixed;\n}\n\nfunction addIgnoreRules(ig: IgnoreMatcher, dir: string, rootDir: string): void {\n\tconst relativeDir = relative(rootDir, dir);\n\tconst prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : \"\";\n\n\tfor (const filename of IGNORE_FILE_NAMES) {\n\t\tconst ignorePath = join(dir, filename);\n\t\tif (!existsSync(ignorePath)) continue;\n\t\ttry {\n\t\t\tconst content = readFileSync(ignorePath, \"utf-8\");\n\t\t\tconst patterns = content\n\t\t\t\t.split(/\\r?\\n/)\n\t\t\t\t.map((line) => prefixIgnorePattern(line, prefix))\n\t\t\t\t.filter((line): line is string => Boolean(line));\n\t\t\tif (patterns.length > 0) {\n\t\t\t\tig.add(patterns);\n\t\t\t}\n\t\t} catch {}\n\t}\n}\n\nexport interface SkillFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t\"disable-model-invocation\"?: boolean;\n\t[key: string]: unknown;\n}\n\nexport interface Skill {\n\tname: string;\n\tdescription: string;\n\tfilePath: string;\n\tbaseDir: string;\n\tsourceInfo: SourceInfo;\n\tdisableModelInvocation: boolean;\n}\n\nexport interface LoadSkillsResult {\n\tskills: Skill[];\n\tdiagnostics: ResourceDiagnostic[];\n}\n\n/**\n * Validate skill name per Agent Skills spec.\n * Returns array of validation error messages (empty if valid).\n */\nfunction validateName(name: string): string[] {\n\tconst errors: string[] = [];\n\n\tif (name.length > MAX_NAME_LENGTH) {\n\t\terrors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\t}\n\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(`name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)`);\n\t}\n\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) {\n\t\terrors.push(`name must not start or end with a hyphen`);\n\t}\n\n\tif (name.includes(\"--\")) {\n\t\terrors.push(`name must not contain consecutive hyphens`);\n\t}\n\n\treturn errors;\n}\n\n/**\n * Validate description per Agent Skills spec.\n */\nfunction validateDescription(description: string | undefined): string[] {\n\tconst errors: string[] = [];\n\n\tif (!description || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\n\treturn errors;\n}\n\nexport interface LoadSkillsFromDirOptions {\n\t/** Directory to scan for skills */\n\tdir: string;\n\t/** Source identifier for these skills */\n\tsource: string;\n}\n\nfunction createSkillSourceInfo(filePath: string, baseDir: string, source: string): SourceInfo {\n\tswitch (source) {\n\t\tcase \"user\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"user\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tcase \"project\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"project\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tcase \"path\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tdefault:\n\t\t\treturn createSyntheticSourceInfo(filePath, { source, baseDir });\n\t}\n}\n\n/**\n * Load skills from a directory.\n *\n * Discovery rules:\n * - if a directory contains SKILL.md, treat it as a skill root and do not recurse further\n * - otherwise, load direct .md children in the root\n * - recurse into subdirectories to find SKILL.md\n */\nexport function loadSkillsFromDir(options: LoadSkillsFromDirOptions): LoadSkillsResult {\n\tconst { dir, source } = options;\n\treturn loadSkillsFromDirInternal(dir, source, true);\n}\n\nfunction loadSkillsFromDirInternal(\n\tdir: string,\n\tsource: string,\n\tincludeRootFiles: boolean,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): LoadSkillsResult {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\tif (!existsSync(dir)) {\n\t\treturn { skills, diagnostics };\n\t}\n\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\taddIgnoreRules(ig, dir, root);\n\n\ttry {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name !== \"SKILL.md\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tif (!isFile || ig.ignores(relPath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst result = loadSkillFromFile(fullPath, source);\n\t\t\tif (result.skill) {\n\t\t\t\tskills.push(result.skill);\n\t\t\t}\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t\treturn { skills, diagnostics };\n\t\t}\n\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name.startsWith(\".\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Skip node_modules to avoid scanning dependencies\n\t\t\tif (entry.name === \"node_modules\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\n\t\t\t// For symlinks, check if they point to a directory and follow them\n\t\t\tlet isDirectory = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDirectory = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\t// Broken symlink, skip it\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tconst ignorePath = isDirectory ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (isDirectory) {\n\t\t\t\tconst subResult = loadSkillsFromDirInternal(fullPath, source, false, ig, root);\n\t\t\t\tskills.push(...subResult.skills);\n\t\t\t\tdiagnostics.push(...subResult.diagnostics);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!isFile || !includeRootFiles || !entry.name.endsWith(\".md\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst result = loadSkillFromFile(fullPath, source);\n\t\t\tif (result.skill) {\n\t\t\t\tskills.push(result.skill);\n\t\t\t}\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t}\n\t} catch {}\n\n\treturn { skills, diagnostics };\n}\n\nfunction loadSkillFromFile(\n\tfilePath: string,\n\tsource: string,\n): { skill: Skill | null; diagnostics: ResourceDiagnostic[] } {\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\ttry {\n\t\tconst rawContent = readFileSync(filePath, \"utf-8\");\n\t\tconst { frontmatter } = parseFrontmatter(rawContent);\n\t\tconst skillDir = dirname(filePath);\n\t\tconst parentDirName = basename(skillDir);\n\n\t\t// Validate description\n\t\tconst descErrors = validateDescription(frontmatter.description);\n\t\tfor (const error of descErrors) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\t}\n\n\t\t// Use name from frontmatter, or fall back to parent directory name\n\t\tconst name = frontmatter.name || parentDirName;\n\n\t\t// Validate name\n\t\tconst nameErrors = validateName(name);\n\t\tfor (const error of nameErrors) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\t}\n\n\t\t// Still load the skill even with warnings (unless description is completely missing)\n\t\tif (!frontmatter.description || frontmatter.description.trim() === \"\") {\n\t\t\treturn { skill: null, diagnostics };\n\t\t}\n\n\t\treturn {\n\t\t\tskill: {\n\t\t\t\tname,\n\t\t\t\tdescription: frontmatter.description,\n\t\t\t\tfilePath,\n\t\t\t\tbaseDir: skillDir,\n\t\t\t\tsourceInfo: createSkillSourceInfo(filePath, skillDir, source),\n\t\t\t\tdisableModelInvocation: frontmatter[\"disable-model-invocation\"] === true,\n\t\t\t},\n\t\t\tdiagnostics,\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to parse skill file\";\n\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n}\n\n/**\n * Format skills for inclusion in a system prompt.\n * Uses XML format per Agent Skills standard.\n * See: https://agentskills.io/integrate-skills\n *\n * Skills with disableModelInvocation=true are excluded from the prompt\n * (they can only be invoked explicitly via /skill:name commands).\n */\nexport function formatSkillsForPrompt(skills: Skill[]): string {\n\tconst visibleSkills = skills.filter((s) => !s.disableModelInvocation);\n\n\tif (visibleSkills.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\n\t\t\"\\n\\nThe following skills provide specialized instructions for specific tasks.\",\n\t\t\"Use the read tool to load a skill's file when the task matches its description.\",\n\t\t\"When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\",\n\t\t\"\",\n\t\t\"\",\n\t];\n\n\tfor (const skill of visibleSkills) {\n\t\tlines.push(\" \");\n\t\tlines.push(` ${escapeXml(skill.name)}`);\n\t\tlines.push(` ${escapeXml(skill.description)}`);\n\t\tlines.push(` ${escapeXml(skill.filePath)}`);\n\t\tlines.push(\" \");\n\t}\n\n\tlines.push(\"\");\n\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&\")\n\t\t.replace(//g, \">\")\n\t\t.replace(/\"/g, \""\")\n\t\t.replace(/'/g, \"'\");\n}\n\nexport interface LoadSkillsOptions {\n\t/** Working directory for project-local skills. */\n\tcwd: string;\n\t/** Agent config directory for global skills. */\n\tagentDir: string;\n\t/** Explicit skill paths (files or directories) */\n\tskillPaths: string[];\n\t/** Include default skills directories. */\n\tincludeDefaults: boolean;\n}\n\n/**\n * Load skills from all configured locations.\n * Returns skills and any validation diagnostics.\n */\nexport function loadSkills(options: LoadSkillsOptions): LoadSkillsResult {\n\tconst { agentDir, skillPaths, includeDefaults } = options;\n\n\t// Resolve agentDir - if not provided, use default from config\n\tconst resolvedCwd = resolvePath(options.cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir ?? getAgentDir());\n\n\tconst skillMap = new Map();\n\tconst realPathSet = new Set();\n\tconst allDiagnostics: ResourceDiagnostic[] = [];\n\tconst collisionDiagnostics: ResourceDiagnostic[] = [];\n\n\tfunction addSkills(result: LoadSkillsResult) {\n\t\tallDiagnostics.push(...result.diagnostics);\n\t\tfor (const skill of result.skills) {\n\t\t\t// Resolve symlinks to detect duplicate files\n\t\t\tconst realPath = canonicalizePath(skill.filePath);\n\n\t\t\t// Skip silently if we've already loaded this exact file (via symlink)\n\t\t\tif (realPathSet.has(realPath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst existing = skillMap.get(skill.name);\n\t\t\tif (existing) {\n\t\t\t\tcollisionDiagnostics.push({\n\t\t\t\t\ttype: \"collision\",\n\t\t\t\t\tmessage: `name \"${skill.name}\" collision`,\n\t\t\t\t\tpath: skill.filePath,\n\t\t\t\t\tcollision: {\n\t\t\t\t\t\tresourceType: \"skill\",\n\t\t\t\t\t\tname: skill.name,\n\t\t\t\t\t\twinnerPath: existing.filePath,\n\t\t\t\t\t\tloserPath: skill.filePath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tskillMap.set(skill.name, skill);\n\t\t\t\trealPathSet.add(realPath);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (includeDefaults) {\n\t\taddSkills(loadSkillsFromDirInternal(join(resolvedAgentDir, \"skills\"), \"user\", true));\n\t\taddSkills(loadSkillsFromDirInternal(resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\"), \"project\", true));\n\t}\n\n\tconst userSkillsDir = join(resolvedAgentDir, \"skills\");\n\tconst projectSkillsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\");\n\n\tconst isUnderPath = (target: string, root: string): boolean => {\n\t\tconst normalizedRoot = resolve(root);\n\t\tif (target === normalizedRoot) {\n\t\t\treturn true;\n\t\t}\n\t\tconst prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;\n\t\treturn target.startsWith(prefix);\n\t};\n\n\tconst getSource = (resolvedPath: string): \"user\" | \"project\" | \"path\" => {\n\t\tif (!includeDefaults) {\n\t\t\tif (isUnderPath(resolvedPath, userSkillsDir)) return \"user\";\n\t\t\tif (isUnderPath(resolvedPath, projectSkillsDir)) return \"project\";\n\t\t}\n\t\treturn \"path\";\n\t};\n\n\tfor (const rawPath of skillPaths) {\n\t\tconst resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true });\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path does not exist\", path: resolvedPath });\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stats = statSync(resolvedPath);\n\t\t\tconst source = getSource(resolvedPath);\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\taddSkills(loadSkillsFromDirInternal(resolvedPath, source, true));\n\t\t\t} else if (stats.isFile() && resolvedPath.endsWith(\".md\")) {\n\t\t\t\tconst result = loadSkillFromFile(resolvedPath, source);\n\t\t\t\tif (result.skill) {\n\t\t\t\t\taddSkills({ skills: [result.skill], diagnostics: result.diagnostics });\n\t\t\t\t} else {\n\t\t\t\t\tallDiagnostics.push(...result.diagnostics);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path is not a markdown file\", path: resolvedPath });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read skill path\";\n\t\t\tallDiagnostics.push({ type: \"warning\", message, path: resolvedPath });\n\t\t}\n\t}\n\n\treturn {\n\t\tskills: Array.from(skillMap.values()),\n\t\tdiagnostics: [...allDiagnostics, ...collisionDiagnostics],\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/slash-commands.d.ts b/dist/core/slash-commands.d.ts new file mode 100644 index 0000000..f21c027 --- /dev/null +++ b/dist/core/slash-commands.d.ts @@ -0,0 +1,15 @@ +import type { SourceInfo } from "./source-info.ts"; +export type SlashCommandSource = "extension" | "prompt" | "skill"; +export interface SlashCommandInfo { + name: string; + description?: string; + source: SlashCommandSource; + sourceInfo: SourceInfo; +} +export interface BuiltinSlashCommand { + name: string; + description: string; + argumentHint?: string; +} +export declare const BUILTIN_SLASH_COMMANDS: ReadonlyArray; +//# sourceMappingURL=slash-commands.d.ts.map \ No newline at end of file diff --git a/dist/core/slash-commands.d.ts.map b/dist/core/slash-commands.d.ts.map new file mode 100644 index 0000000..b40ede2 --- /dev/null +++ b/dist/core/slash-commands.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"slash-commands.d.ts","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,QAAQ,GAAG,OAAO,CAAC;AAElE,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,eAAO,MAAM,sBAAsB,EAAE,aAAa,CAAC,mBAAmB,CAuBrE,CAAC","sourcesContent":["import { APP_NAME } from \"../config.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\targumentHint?: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\", argumentHint: \"\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"trust\", description: \"Save project trust decision for future sessions\" },\n\t{ name: \"login\", description: \"Configure provider authentication\", argumentHint: \"\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, themes, and context files\" },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n"]} \ No newline at end of file diff --git a/dist/core/slash-commands.js b/dist/core/slash-commands.js new file mode 100644 index 0000000..68ca0c3 --- /dev/null +++ b/dist/core/slash-commands.js @@ -0,0 +1,26 @@ +import { APP_NAME } from "../config.js"; +export const BUILTIN_SLASH_COMMANDS = [ + { name: "settings", description: "Open settings menu" }, + { name: "model", description: "Select model (opens selector UI)", argumentHint: "" }, + { name: "scoped-models", description: "Enable/disable models for Ctrl+P cycling" }, + { name: "export", description: "Export session (HTML default, or specify path: .html/.jsonl)" }, + { name: "import", description: "Import and resume a session from a JSONL file" }, + { name: "share", description: "Share session as a secret GitHub gist" }, + { name: "copy", description: "Copy last agent message to clipboard" }, + { name: "name", description: "Set session display name" }, + { name: "session", description: "Show session info and stats" }, + { name: "changelog", description: "Show changelog entries" }, + { name: "hotkeys", description: "Show all keyboard shortcuts" }, + { name: "fork", description: "Create a new fork from a previous user message" }, + { name: "clone", description: "Duplicate the current session at the current position" }, + { name: "tree", description: "Navigate session tree (switch branches)" }, + { name: "trust", description: "Save project trust decision for future sessions" }, + { name: "login", description: "Configure provider authentication", argumentHint: "" }, + { name: "logout", description: "Remove provider authentication" }, + { name: "new", description: "Start a new session" }, + { name: "compact", description: "Manually compact the session context" }, + { name: "resume", description: "Resume a different session" }, + { name: "reload", description: "Reload keybindings, extensions, skills, prompts, themes, and context files" }, + { name: "quit", description: `Quit ${APP_NAME}` }, +]; +//# sourceMappingURL=slash-commands.js.map \ No newline at end of file diff --git a/dist/core/slash-commands.js.map b/dist/core/slash-commands.js.map new file mode 100644 index 0000000..0503e71 --- /dev/null +++ b/dist/core/slash-commands.js.map @@ -0,0 +1 @@ +{"version":3,"file":"slash-commands.js","sourceRoot":"","sources":["../../src/core/slash-commands.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAkBxC,MAAM,CAAC,MAAM,sBAAsB,GAAuC;IACzE,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,oBAAoB,EAAE;IACvD,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,kCAAkC,EAAE,YAAY,EAAE,kBAAkB,EAAE;IACpG,EAAE,IAAI,EAAE,eAAe,EAAE,WAAW,EAAE,0CAA0C,EAAE;IAClF,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,8DAA8D,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,+CAA+C,EAAE;IAChF,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,uCAAuC,EAAE;IACvE,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACrE,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,0BAA0B,EAAE;IACzD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,wBAAwB,EAAE;IAC5D,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,6BAA6B,EAAE;IAC/D,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,gDAAgD,EAAE;IAC/E,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,uDAAuD,EAAE;IACvF,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,yCAAyC,EAAE;IACxE,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,iDAAiD,EAAE;IACjF,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,mCAAmC,EAAE,YAAY,EAAE,YAAY,EAAE;IAC/F,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,gCAAgC,EAAE;IACjE,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE;IACnD,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,sCAAsC,EAAE;IACxE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4BAA4B,EAAE;IAC7D,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,4EAA4E,EAAE;IAC7G,EAAE,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,QAAQ,EAAE,EAAE;CACjD,CAAC","sourcesContent":["import { APP_NAME } from \"../config.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type SlashCommandSource = \"extension\" | \"prompt\" | \"skill\";\n\nexport interface SlashCommandInfo {\n\tname: string;\n\tdescription?: string;\n\tsource: SlashCommandSource;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface BuiltinSlashCommand {\n\tname: string;\n\tdescription: string;\n\targumentHint?: string;\n}\n\nexport const BUILTIN_SLASH_COMMANDS: ReadonlyArray = [\n\t{ name: \"settings\", description: \"Open settings menu\" },\n\t{ name: \"model\", description: \"Select model (opens selector UI)\", argumentHint: \"\" },\n\t{ name: \"scoped-models\", description: \"Enable/disable models for Ctrl+P cycling\" },\n\t{ name: \"export\", description: \"Export session (HTML default, or specify path: .html/.jsonl)\" },\n\t{ name: \"import\", description: \"Import and resume a session from a JSONL file\" },\n\t{ name: \"share\", description: \"Share session as a secret GitHub gist\" },\n\t{ name: \"copy\", description: \"Copy last agent message to clipboard\" },\n\t{ name: \"name\", description: \"Set session display name\" },\n\t{ name: \"session\", description: \"Show session info and stats\" },\n\t{ name: \"changelog\", description: \"Show changelog entries\" },\n\t{ name: \"hotkeys\", description: \"Show all keyboard shortcuts\" },\n\t{ name: \"fork\", description: \"Create a new fork from a previous user message\" },\n\t{ name: \"clone\", description: \"Duplicate the current session at the current position\" },\n\t{ name: \"tree\", description: \"Navigate session tree (switch branches)\" },\n\t{ name: \"trust\", description: \"Save project trust decision for future sessions\" },\n\t{ name: \"login\", description: \"Configure provider authentication\", argumentHint: \"\" },\n\t{ name: \"logout\", description: \"Remove provider authentication\" },\n\t{ name: \"new\", description: \"Start a new session\" },\n\t{ name: \"compact\", description: \"Manually compact the session context\" },\n\t{ name: \"resume\", description: \"Resume a different session\" },\n\t{ name: \"reload\", description: \"Reload keybindings, extensions, skills, prompts, themes, and context files\" },\n\t{ name: \"quit\", description: `Quit ${APP_NAME}` },\n];\n"]} \ No newline at end of file diff --git a/dist/core/source-info.d.ts b/dist/core/source-info.d.ts new file mode 100644 index 0000000..a279fb7 --- /dev/null +++ b/dist/core/source-info.d.ts @@ -0,0 +1,18 @@ +import type { PathMetadata } from "./package-manager.ts"; +export type SourceScope = "user" | "project" | "temporary"; +export type SourceOrigin = "package" | "top-level"; +export interface SourceInfo { + path: string; + source: string; + scope: SourceScope; + origin: SourceOrigin; + baseDir?: string; +} +export declare function createSourceInfo(path: string, metadata: PathMetadata): SourceInfo; +export declare function createSyntheticSourceInfo(path: string, options: { + source: string; + scope?: SourceScope; + origin?: SourceOrigin; + baseDir?: string; +}): SourceInfo; +//# sourceMappingURL=source-info.d.ts.map \ No newline at end of file diff --git a/dist/core/source-info.d.ts.map b/dist/core/source-info.d.ts.map new file mode 100644 index 0000000..c77a695 --- /dev/null +++ b/dist/core/source-info.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"source-info.d.ts","sourceRoot":"","sources":["../../src/core/source-info.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAEzD,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,SAAS,GAAG,WAAW,CAAC;AAC3D,MAAM,MAAM,YAAY,GAAG,SAAS,GAAG,WAAW,CAAC;AAEnD,MAAM,WAAW,UAAU;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,WAAW,CAAC;IACnB,MAAM,EAAE,YAAY,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,GAAG,UAAU,CAQjF;AAED,wBAAgB,yBAAyB,CACxC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE;IACR,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB,GACC,UAAU,CAQZ","sourcesContent":["import type { PathMetadata } from \"./package-manager.ts\";\n\nexport type SourceScope = \"user\" | \"project\" | \"temporary\";\nexport type SourceOrigin = \"package\" | \"top-level\";\n\nexport interface SourceInfo {\n\tpath: string;\n\tsource: string;\n\tscope: SourceScope;\n\torigin: SourceOrigin;\n\tbaseDir?: string;\n}\n\nexport function createSourceInfo(path: string, metadata: PathMetadata): SourceInfo {\n\treturn {\n\t\tpath,\n\t\tsource: metadata.source,\n\t\tscope: metadata.scope,\n\t\torigin: metadata.origin,\n\t\tbaseDir: metadata.baseDir,\n\t};\n}\n\nexport function createSyntheticSourceInfo(\n\tpath: string,\n\toptions: {\n\t\tsource: string;\n\t\tscope?: SourceScope;\n\t\torigin?: SourceOrigin;\n\t\tbaseDir?: string;\n\t},\n): SourceInfo {\n\treturn {\n\t\tpath,\n\t\tsource: options.source,\n\t\tscope: options.scope ?? \"temporary\",\n\t\torigin: options.origin ?? \"top-level\",\n\t\tbaseDir: options.baseDir,\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/source-info.js b/dist/core/source-info.js new file mode 100644 index 0000000..9c32cb3 --- /dev/null +++ b/dist/core/source-info.js @@ -0,0 +1,19 @@ +export function createSourceInfo(path, metadata) { + return { + path, + source: metadata.source, + scope: metadata.scope, + origin: metadata.origin, + baseDir: metadata.baseDir, + }; +} +export function createSyntheticSourceInfo(path, options) { + return { + path, + source: options.source, + scope: options.scope ?? "temporary", + origin: options.origin ?? "top-level", + baseDir: options.baseDir, + }; +} +//# sourceMappingURL=source-info.js.map \ No newline at end of file diff --git a/dist/core/source-info.js.map b/dist/core/source-info.js.map new file mode 100644 index 0000000..9a14c63 --- /dev/null +++ b/dist/core/source-info.js.map @@ -0,0 +1 @@ +{"version":3,"file":"source-info.js","sourceRoot":"","sources":["../../src/core/source-info.ts"],"names":[],"mappings":"AAaA,MAAM,UAAU,gBAAgB,CAAC,IAAY,EAAE,QAAsB,EAAc;IAClF,OAAO;QACN,IAAI;QACJ,MAAM,EAAE,QAAQ,CAAC,MAAM;QACvB,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,MAAM,EAAE,QAAQ,CAAC,MAAM;QACvB,OAAO,EAAE,QAAQ,CAAC,OAAO;KACzB,CAAC;AAAA,CACF;AAED,MAAM,UAAU,yBAAyB,CACxC,IAAY,EACZ,OAKC,EACY;IACb,OAAO;QACN,IAAI;QACJ,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,WAAW;QACnC,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,WAAW;QACrC,OAAO,EAAE,OAAO,CAAC,OAAO;KACxB,CAAC;AAAA,CACF","sourcesContent":["import type { PathMetadata } from \"./package-manager.ts\";\n\nexport type SourceScope = \"user\" | \"project\" | \"temporary\";\nexport type SourceOrigin = \"package\" | \"top-level\";\n\nexport interface SourceInfo {\n\tpath: string;\n\tsource: string;\n\tscope: SourceScope;\n\torigin: SourceOrigin;\n\tbaseDir?: string;\n}\n\nexport function createSourceInfo(path: string, metadata: PathMetadata): SourceInfo {\n\treturn {\n\t\tpath,\n\t\tsource: metadata.source,\n\t\tscope: metadata.scope,\n\t\torigin: metadata.origin,\n\t\tbaseDir: metadata.baseDir,\n\t};\n}\n\nexport function createSyntheticSourceInfo(\n\tpath: string,\n\toptions: {\n\t\tsource: string;\n\t\tscope?: SourceScope;\n\t\torigin?: SourceOrigin;\n\t\tbaseDir?: string;\n\t},\n): SourceInfo {\n\treturn {\n\t\tpath,\n\t\tsource: options.source,\n\t\tscope: options.scope ?? \"temporary\",\n\t\torigin: options.origin ?? \"top-level\",\n\t\tbaseDir: options.baseDir,\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/system-prompt.d.ts b/dist/core/system-prompt.d.ts new file mode 100644 index 0000000..f2b1836 --- /dev/null +++ b/dist/core/system-prompt.d.ts @@ -0,0 +1,28 @@ +/** + * System prompt construction and project context loading + */ +import { type Skill } from "./skills.ts"; +export interface BuildSystemPromptOptions { + /** Custom system prompt (replaces default). */ + customPrompt?: string; + /** Tools to include in prompt. Default: [read, bash, edit, write] */ + selectedTools?: string[]; + /** Optional one-line tool snippets keyed by tool name. */ + toolSnippets?: Record; + /** Additional guideline bullets appended to the default system prompt guidelines. */ + promptGuidelines?: string[]; + /** Text to append to system prompt. */ + appendSystemPrompt?: string; + /** Working directory. */ + cwd: string; + /** Pre-loaded context files. */ + contextFiles?: Array<{ + path: string; + content: string; + }>; + /** Pre-loaded skills. */ + skills?: Skill[]; +} +/** Build the system prompt with tools, guidelines, and context */ +export declare function buildSystemPrompt(options: BuildSystemPromptOptions): string; +//# sourceMappingURL=system-prompt.d.ts.map \ No newline at end of file diff --git a/dist/core/system-prompt.d.ts.map b/dist/core/system-prompt.d.ts.map new file mode 100644 index 0000000..8ebc27f --- /dev/null +++ b/dist/core/system-prompt.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAEhE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,qEAAqE;IACrE,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,gCAAgC;IAChC,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;CACjB;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CAsI3E","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst promptCwd = cwd.replace(/\\\\/g, \"/\");\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `\\n${content}\\n\\n\\n`;\n\t\t\t}\n\t\t\tprompt += \"\\n\";\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nPi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md), environment variables (docs/environment-variables.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `\\n${content}\\n\\n\\n`;\n\t\t}\n\t\tprompt += \"\\n\";\n\t}\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n"]} \ No newline at end of file diff --git a/dist/core/system-prompt.js b/dist/core/system-prompt.js new file mode 100644 index 0000000..d6c8416 --- /dev/null +++ b/dist/core/system-prompt.js @@ -0,0 +1,110 @@ +/** + * System prompt construction and project context loading + */ +import { getDocsPath, getExamplesPath, getReadmePath } from "../config.js"; +import { formatSkillsForPrompt } from "./skills.js"; +/** Build the system prompt with tools, guidelines, and context */ +export function buildSystemPrompt(options) { + const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, skills: providedSkills, } = options; + const promptCwd = cwd.replace(/\\/g, "/"); + const appendSection = appendSystemPrompt ? `\n\n${appendSystemPrompt}` : ""; + const contextFiles = providedContextFiles ?? []; + const skills = providedSkills ?? []; + if (customPrompt) { + let prompt = customPrompt; + if (appendSection) { + prompt += appendSection; + } + // Append project context files + if (contextFiles.length > 0) { + prompt += "\n\n\n\n"; + prompt += "Project-specific instructions and guidelines:\n\n"; + for (const { path: filePath, content } of contextFiles) { + prompt += `\n${content}\n\n\n`; + } + prompt += "\n"; + } + // Append skills section (only if read tool is available) + const customPromptHasRead = !selectedTools || selectedTools.includes("read"); + if (customPromptHasRead && skills.length > 0) { + prompt += formatSkillsForPrompt(skills); + } + prompt += `\nCurrent working directory: ${promptCwd}`; + return prompt; + } + // Get absolute paths to documentation and examples + const readmePath = getReadmePath(); + const docsPath = getDocsPath(); + const examplesPath = getExamplesPath(); + // Build tools list based on selected tools. + // A tool appears in Available tools only when the caller provides a one-line snippet. + const tools = selectedTools || ["read", "bash", "edit", "write"]; + const visibleTools = tools.filter((name) => !!toolSnippets?.[name]); + const toolsList = visibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join("\n") : "(none)"; + // Build guidelines based on which tools are actually available + const guidelinesList = []; + const guidelinesSet = new Set(); + const addGuideline = (guideline) => { + if (guidelinesSet.has(guideline)) { + return; + } + guidelinesSet.add(guideline); + guidelinesList.push(guideline); + }; + const hasBash = tools.includes("bash"); + const hasGrep = tools.includes("grep"); + const hasFind = tools.includes("find"); + const hasLs = tools.includes("ls"); + const hasRead = tools.includes("read"); + // File exploration guidelines + if (hasBash && !hasGrep && !hasFind && !hasLs) { + addGuideline("Use bash for file operations like ls, rg, find"); + } + for (const guideline of promptGuidelines ?? []) { + const normalized = guideline.trim(); + if (normalized.length > 0) { + addGuideline(normalized); + } + } + // Always include these + addGuideline("Be concise in your responses"); + addGuideline("Show file paths clearly when working with files"); + const guidelines = guidelinesList.map((g) => `- ${g}`).join("\n"); + let prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files. + +Available tools: +${toolsList} + +In addition to the tools above, you may have access to other custom tools depending on the project. + +Guidelines: +${guidelines} + +Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI): +- Main documentation: ${readmePath} +- Additional docs: ${docsPath} +- Examples: ${examplesPath} (extensions, custom tools, SDK) +- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory +- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md), environment variables (docs/environment-variables.md) +- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing +- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`; + if (appendSection) { + prompt += appendSection; + } + // Append project context files + if (contextFiles.length > 0) { + prompt += "\n\n\n\n"; + prompt += "Project-specific instructions and guidelines:\n\n"; + for (const { path: filePath, content } of contextFiles) { + prompt += `\n${content}\n\n\n`; + } + prompt += "\n"; + } + // Append skills section (only if read tool is available) + if (hasRead && skills.length > 0) { + prompt += formatSkillsForPrompt(skills); + } + prompt += `\nCurrent working directory: ${promptCwd}`; + return prompt; +} +//# sourceMappingURL=system-prompt.js.map \ No newline at end of file diff --git a/dist/core/system-prompt.js.map b/dist/core/system-prompt.js.map new file mode 100644 index 0000000..f6dde55 --- /dev/null +++ b/dist/core/system-prompt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAqBhE,kEAAkE;AAClE,MAAM,UAAU,iBAAiB,CAAC,OAAiC,EAAU;IAC5E,MAAM,EACL,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,GAAG,EACH,YAAY,EAAE,oBAAoB,EAClC,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CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;IAED,MAAM,IAAI,gCAAgC,SAAS,EAAE,CAAC;IAEtD,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst promptCwd = cwd.replace(/\\\\/g, \"/\");\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `\\n${content}\\n\\n\\n`;\n\t\t\t}\n\t\t\tprompt += \"\\n\";\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}\n\nPi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md), environment variables (docs/environment-variables.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `\\n${content}\\n\\n\\n`;\n\t\t}\n\t\tprompt += \"\\n\";\n\t}\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n"]} \ No newline at end of file diff --git a/dist/core/telemetry.d.ts b/dist/core/telemetry.d.ts new file mode 100644 index 0000000..b03867a --- /dev/null +++ b/dist/core/telemetry.d.ts @@ -0,0 +1,3 @@ +import type { SettingsManager } from "./settings-manager.ts"; +export declare function isInstallTelemetryEnabled(settingsManager: SettingsManager, telemetryEnv?: string | undefined): boolean; +//# sourceMappingURL=telemetry.d.ts.map \ No newline at end of file diff --git a/dist/core/telemetry.d.ts.map b/dist/core/telemetry.d.ts.map new file mode 100644 index 0000000..042ab4a --- /dev/null +++ b/dist/core/telemetry.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../../src/core/telemetry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAO7D,wBAAgB,yBAAyB,CACxC,eAAe,EAAE,eAAe,EAChC,YAAY,GAAE,MAAM,GAAG,SAAoC,GACzD,OAAO,CAET","sourcesContent":["import type { SettingsManager } from \"./settings-manager.ts\";\n\nfunction isTruthyEnvFlag(value: string | undefined): boolean {\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\nexport function isInstallTelemetryEnabled(\n\tsettingsManager: SettingsManager,\n\ttelemetryEnv: string | undefined = process.env.PI_TELEMETRY,\n): boolean {\n\treturn telemetryEnv !== undefined ? isTruthyEnvFlag(telemetryEnv) : settingsManager.getEnableInstallTelemetry();\n}\n"]} \ No newline at end of file diff --git a/dist/core/telemetry.js b/dist/core/telemetry.js new file mode 100644 index 0000000..d9fa7ed --- /dev/null +++ b/dist/core/telemetry.js @@ -0,0 +1,9 @@ +function isTruthyEnvFlag(value) { + if (!value) + return false; + return value === "1" || value.toLowerCase() === "true" || value.toLowerCase() === "yes"; +} +export function isInstallTelemetryEnabled(settingsManager, telemetryEnv = process.env.PI_TELEMETRY) { + return telemetryEnv !== undefined ? isTruthyEnvFlag(telemetryEnv) : settingsManager.getEnableInstallTelemetry(); +} +//# sourceMappingURL=telemetry.js.map \ No newline at end of file diff --git a/dist/core/telemetry.js.map b/dist/core/telemetry.js.map new file mode 100644 index 0000000..a676b86 --- /dev/null +++ b/dist/core/telemetry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../../src/core/telemetry.ts"],"names":[],"mappings":"AAEA,SAAS,eAAe,CAAC,KAAyB,EAAW;IAC5D,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC;IACzB,OAAO,KAAK,KAAK,GAAG,IAAI,KAAK,CAAC,WAAW,EAAE,KAAK,MAAM,IAAI,KAAK,CAAC,WAAW,EAAE,KAAK,KAAK,CAAC;AAAA,CACxF;AAED,MAAM,UAAU,yBAAyB,CACxC,eAAgC,EAChC,YAAY,GAAuB,OAAO,CAAC,GAAG,CAAC,YAAY,EACjD;IACV,OAAO,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,yBAAyB,EAAE,CAAC;AAAA,CAChH","sourcesContent":["import type { SettingsManager } from \"./settings-manager.ts\";\n\nfunction isTruthyEnvFlag(value: string | undefined): boolean {\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\nexport function isInstallTelemetryEnabled(\n\tsettingsManager: SettingsManager,\n\ttelemetryEnv: string | undefined = process.env.PI_TELEMETRY,\n): boolean {\n\treturn telemetryEnv !== undefined ? isTruthyEnvFlag(telemetryEnv) : settingsManager.getEnableInstallTelemetry();\n}\n"]} \ No newline at end of file diff --git a/dist/core/timings.d.ts b/dist/core/timings.d.ts new file mode 100644 index 0000000..75dbf95 --- /dev/null +++ b/dist/core/timings.d.ts @@ -0,0 +1,10 @@ +/** + * Central timing instrumentation for startup profiling. + * Enable with PI_TIMING=1 environment variable. + */ +type TimingLabel = "main" | "extensions"; +export declare function resetTimings(namespace?: TimingLabel): void; +export declare function time(label: string, namespace?: TimingLabel): void; +export declare function printTimings(): void; +export {}; +//# sourceMappingURL=timings.d.ts.map \ No newline at end of file diff --git a/dist/core/timings.d.ts.map b/dist/core/timings.d.ts.map new file mode 100644 index 0000000..215e17e --- /dev/null +++ b/dist/core/timings.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"timings.d.ts","sourceRoot":"","sources":["../../src/core/timings.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAQH,KAAK,WAAW,GAAG,MAAM,GAAG,YAAY,CAAC;AAIzC,wBAAgB,YAAY,CAAC,SAAS,GAAE,WAAoB,GAAG,IAAI,CAGlE;AAED,wBAAgB,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,GAAE,WAAoB,GAAG,IAAI,CAWzE;AAaD,wBAAgB,YAAY,IAAI,IAAI,CAKnC","sourcesContent":["/**\n * Central timing instrumentation for startup profiling.\n * Enable with PI_TIMING=1 environment variable.\n */\n\nconst ENABLED = process.env.PI_TIMING === \"1\";\ninterface TimingNamespace {\n\ttimings: Array<{ label: string; ms: number }>;\n\tlastTime: number;\n}\n\ntype TimingLabel = \"main\" | \"extensions\";\n\nconst timingNamespaces = new Map();\n\nexport function resetTimings(namespace: TimingLabel = \"main\"): void {\n\tif (!ENABLED) return;\n\ttimingNamespaces.set(namespace, { timings: [], lastTime: Date.now() });\n}\n\nexport function time(label: string, namespace: TimingLabel = \"main\"): void {\n\tif (!ENABLED) return;\n\tconst now = Date.now();\n\n\tif (!timingNamespaces.has(namespace)) {\n\t\tresetTimings(namespace);\n\t}\n\n\tconst timingNamespace = timingNamespaces.get(namespace)!;\n\ttimingNamespace.timings.push({ label, ms: now - timingNamespace.lastTime });\n\ttimingNamespace.lastTime = now;\n}\n\nfunction printTimingGroup(title: string, timings: TimingNamespace[\"timings\"]): void {\n\tconst printableTimings = timings.filter((timing) => timing.ms >= 0);\n\tif (printableTimings.length === 0) return;\n\tconsole.error(`\\n--- ${title} ---`);\n\tfor (const t of printableTimings) {\n\t\tconsole.error(` ${t.label}: ${t.ms}ms`);\n\t}\n\tconsole.error(` TOTAL: ${printableTimings.reduce((a, b) => a + b.ms, 0)}ms`);\n\tconsole.error(`${\"-\".repeat(title.length + 8)}\\n`);\n}\n\nexport function printTimings(): void {\n\tif (!ENABLED) return;\n\tfor (const [namespace, timingNamespace] of timingNamespaces) {\n\t\tprintTimingGroup(`Startup Timings: ${namespace}`, timingNamespace.timings);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/timings.js b/dist/core/timings.js new file mode 100644 index 0000000..3008b48 --- /dev/null +++ b/dist/core/timings.js @@ -0,0 +1,41 @@ +/** + * Central timing instrumentation for startup profiling. + * Enable with PI_TIMING=1 environment variable. + */ +const ENABLED = process.env.PI_TIMING === "1"; +const timingNamespaces = new Map(); +export function resetTimings(namespace = "main") { + if (!ENABLED) + return; + timingNamespaces.set(namespace, { timings: [], lastTime: Date.now() }); +} +export function time(label, namespace = "main") { + if (!ENABLED) + return; + const now = Date.now(); + if (!timingNamespaces.has(namespace)) { + resetTimings(namespace); + } + const timingNamespace = timingNamespaces.get(namespace); + timingNamespace.timings.push({ label, ms: now - timingNamespace.lastTime }); + timingNamespace.lastTime = now; +} +function printTimingGroup(title, timings) { + const printableTimings = timings.filter((timing) => timing.ms >= 0); + if (printableTimings.length === 0) + return; + console.error(`\n--- ${title} ---`); + for (const t of printableTimings) { + console.error(` ${t.label}: ${t.ms}ms`); + } + console.error(` TOTAL: ${printableTimings.reduce((a, b) => a + b.ms, 0)}ms`); + console.error(`${"-".repeat(title.length + 8)}\n`); +} +export function printTimings() { + if (!ENABLED) + return; + for (const [namespace, timingNamespace] of timingNamespaces) { + printTimingGroup(`Startup Timings: ${namespace}`, timingNamespace.timings); + } +} +//# sourceMappingURL=timings.js.map \ No newline at end of file diff --git a/dist/core/timings.js.map b/dist/core/timings.js.map new file mode 100644 index 0000000..70d6e96 --- /dev/null +++ b/dist/core/timings.js.map @@ -0,0 +1 @@ +{"version":3,"file":"timings.js","sourceRoot":"","sources":["../../src/core/timings.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,SA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KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,CAAC,KAAK,CAAC,YAAY,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;IAC9E,OAAO,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;AAAA,CACnD;AAED,MAAM,UAAU,YAAY,GAAS;IACpC,IAAI,CAAC,OAAO;QAAE,OAAO;IACrB,KAAK,MAAM,CAAC,SAAS,EAAE,eAAe,CAAC,IAAI,gBAAgB,EAAE,CAAC;QAC7D,gBAAgB,CAAC,oBAAoB,SAAS,EAAE,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC;IAC5E,CAAC;AAAA,CACD","sourcesContent":["/**\n * Central timing instrumentation for startup profiling.\n * Enable with PI_TIMING=1 environment variable.\n */\n\nconst ENABLED = process.env.PI_TIMING === \"1\";\ninterface TimingNamespace {\n\ttimings: Array<{ label: string; ms: number }>;\n\tlastTime: number;\n}\n\ntype TimingLabel = \"main\" | \"extensions\";\n\nconst timingNamespaces = new Map();\n\nexport function resetTimings(namespace: TimingLabel = \"main\"): void {\n\tif (!ENABLED) return;\n\ttimingNamespaces.set(namespace, { timings: [], lastTime: Date.now() });\n}\n\nexport function time(label: string, namespace: TimingLabel = \"main\"): void {\n\tif (!ENABLED) return;\n\tconst now = Date.now();\n\n\tif (!timingNamespaces.has(namespace)) {\n\t\tresetTimings(namespace);\n\t}\n\n\tconst timingNamespace = timingNamespaces.get(namespace)!;\n\ttimingNamespace.timings.push({ label, ms: now - timingNamespace.lastTime });\n\ttimingNamespace.lastTime = now;\n}\n\nfunction printTimingGroup(title: string, timings: TimingNamespace[\"timings\"]): void {\n\tconst printableTimings = timings.filter((timing) => timing.ms >= 0);\n\tif (printableTimings.length === 0) return;\n\tconsole.error(`\\n--- ${title} ---`);\n\tfor (const t of printableTimings) {\n\t\tconsole.error(` ${t.label}: ${t.ms}ms`);\n\t}\n\tconsole.error(` TOTAL: ${printableTimings.reduce((a, b) => a + b.ms, 0)}ms`);\n\tconsole.error(`${\"-\".repeat(title.length + 8)}\\n`);\n}\n\nexport function printTimings(): void {\n\tif (!ENABLED) return;\n\tfor (const [namespace, timingNamespace] of timingNamespaces) {\n\t\tprintTimingGroup(`Startup Timings: ${namespace}`, timingNamespace.timings);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/bash.d.ts b/dist/core/tools/bash.d.ts new file mode 100644 index 0000000..ab40b66 --- /dev/null +++ b/dist/core/tools/bash.d.ts @@ -0,0 +1,70 @@ +import type { AgentTool } from "@earendil-works/pi-agent-core"; +import { type Static, Type } from "typebox"; +import type { ToolDefinition } from "../extensions/types.ts"; +import { type TruncationResult } from "./truncate.ts"; +declare const bashSchema: Type.TObject<{ + command: Type.TString; + timeout: Type.TOptional; +}>; +export type BashToolInput = Static; +export interface BashToolDetails { + truncation?: TruncationResult; + fullOutputPath?: string; +} +/** + * Pluggable operations for the bash tool. + * Override these to delegate command execution to remote systems (for example SSH). + */ +export interface BashOperations { + /** + * Execute a command and stream output. + * @param command The command to execute + * @param cwd Working directory + * @param options Execution options + * @returns Promise resolving to exit code (null if killed) + */ + exec: (command: string, cwd: string, options: { + onData: (data: Buffer) => void; + signal?: AbortSignal; + timeout?: number; + env?: NodeJS.ProcessEnv; + }) => Promise<{ + exitCode: number | null; + }>; +} +/** + * Create bash operations using pi's built-in local shell execution backend. + * + * This is useful for extensions that intercept user_bash and still want pi's + * standard local shell behavior while wrapping or rewriting commands. + */ +export declare function createLocalBashOperations(options?: { + shellPath?: string; +}): BashOperations; +export interface BashSpawnContext { + command: string; + cwd: string; + env: NodeJS.ProcessEnv; +} +export type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext; +export interface BashToolOptions { + /** Custom operations for command execution. Default: local shell */ + operations?: BashOperations; + /** Command prefix prepended to every command (for example shell setup commands) */ + commandPrefix?: string; + /** Optional explicit shell path from settings */ + shellPath?: string; + /** Expose current Pi session metadata as PI_* environment variables. Default: true */ + exposeSessionEnvironment?: boolean; + /** Hook to adjust command, cwd, or env before execution */ + spawnHook?: BashSpawnHook; +} +type BashRenderState = { + startedAt: number | undefined; + endedAt: number | undefined; + interval: NodeJS.Timeout | undefined; +}; +export declare function createBashToolDefinition(cwd: string, options?: BashToolOptions): ToolDefinition; +export declare function createBashTool(cwd: string, options?: BashToolOptions): AgentTool; +export {}; +//# sourceMappingURL=bash.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/bash.d.ts.map b/dist/core/tools/bash.d.ts.map new file mode 100644 index 0000000..85bbbb0 --- /dev/null +++ b/dist/core/tools/bash.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAG/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAY5C,OAAO,KAAK,EAAoB,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAIxG,OAAO,EAAoD,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAkBxG,QAAA,MAAM,UAAU;;;EAGd,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B;;;;;;OAMG;IACH,IAAI,EAAE,CACL,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,OAAO,EAAE;QACR,MAAM,EAAE,C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c,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAQnG","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Container, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport type { ExtensionContext, ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Bash command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\nexport type BashToolInput = Static;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = getShellConfig(options?.shellPath);\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute bash commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\treturn { exitCode };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.PI_SESSION_ID;\n\tdelete env.PI_SESSION_FILE;\n\tdelete env.PI_PROVIDER;\n\tdelete env.PI_MODEL;\n\tdelete env.PI_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.PI_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.PI_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.PI_PROVIDER = model.provider;\n\t\t\tenv.PI_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.PI_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\ntype BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatDuration(ms: number): string {\n\treturn `${(ms / 1000).toFixed(1)}s`;\n}\n\nfunction formatBashCall(args: { command?: string; timeout?: number } | undefined): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\treturn theme.fg(\"toolTitle\", theme.bold(`$ ${commandDisplay}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tlet output = getTextOutput(result as any, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines;\n\t\t\t\t\t\tstate.cachedSkipped = preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: \"bash\",\n\t\tlabel: \"bash\",\n\t\tdescription: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\t\tpromptGuidelines: exposeSessionEnvironment\n\t\t\t? [\"Inspect PI_* environment variables for current model and session details.\"]\n\t\t\t: undefined,\n\t\tparameters: bashSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\tctx?,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook, exposeSessionEnvironment, ctx);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: \"pi-bash\" });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`));\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, `Command exited with code ${exitCode}`));\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBashCall(args));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/bash.js b/dist/core/tools/bash.js new file mode 100644 index 0000000..8028dbf --- /dev/null +++ b/dist/core/tools/bash.js @@ -0,0 +1,390 @@ +import { constants } from "node:fs"; +import { access as fsAccess } from "node:fs/promises"; +import { Container, Text, truncateToWidth } from "@earendil-works/pi-tui"; +import { spawn } from "child_process"; +import { Type } from "typebox"; +import { keyHint } from "../../modes/interactive/components/keybinding-hints.js"; +import { truncateToVisualLines } from "../../modes/interactive/components/visual-truncate.js"; +import { theme } from "../../modes/interactive/theme/theme.js"; +import { waitForChildProcess } from "../../utils/child-process.js"; +import { getShellConfig, getShellEnv, killProcessTree, trackDetachedChildPid, untrackDetachedChildPid, } from "../../utils/shell.js"; +import { OutputAccumulator } from "./output-accumulator.js"; +import { getTextOutput, invalidArgText, str } from "./render-utils.js"; +import { wrapToolDefinition } from "./tool-definition-wrapper.js"; +import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize } from "./truncate.js"; +const MAX_TIMEOUT_MS = 2_147_483_647; +const MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000; +function resolveTimeoutMs(timeout) { + if (timeout === undefined) + return undefined; + if (!Number.isFinite(timeout) || timeout <= 0) { + throw new Error("Invalid timeout: must be a finite number of seconds"); + } + const timeoutMs = timeout * 1000; + if (timeoutMs > MAX_TIMEOUT_MS) { + throw new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`); + } + return timeoutMs; +} +const bashSchema = Type.Object({ + command: Type.String({ description: "Bash command to execute" }), + timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" })), +}); +/** + * Create bash operations using pi's built-in local shell execution backend. + * + * This is useful for extensions that intercept user_bash and still want pi's + * standard local shell behavior while wrapping or rewriting commands. + */ +export function createLocalBashOperations(options) { + return { + exec: async (command, cwd, { onData, signal, timeout, env }) => { + const timeoutMs = resolveTimeoutMs(timeout); + if (signal?.aborted) { + throw new Error("aborted"); + } + const shellConfig = getShellConfig(options?.shellPath); + try { + await fsAccess(cwd, constants.F_OK); + } + catch { + throw new Error(`Working directory does not exist: ${cwd}\nCannot execute bash commands.`); + } + const commandFromStdin = shellConfig.commandTransport === "stdin"; + const child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], { + cwd, + detached: process.platform !== "win32", + env: env ?? getShellEnv(), + stdio: [commandFromStdin ? "pipe" : "ignore", "pipe", "pipe"], + windowsHide: true, + }); + if (commandFromStdin) { + child.stdin?.on("error", () => { }); + child.stdin?.end(command); + } + if (child.pid) + trackDetachedChildPid(child.pid); + let timedOut = false; + let timeoutHandle; + const onAbort = () => { + if (child.pid) + killProcessTree(child.pid); + }; + try { + // Set timeout if provided. + if (timeoutMs !== undefined) { + timeoutHandle = setTimeout(() => { + timedOut = true; + if (child.pid) + killProcessTree(child.pid); + }, timeoutMs); + } + // Stream stdout and stderr. + child.stdout?.on("data", onData); + child.stderr?.on("data", onData); + // Handle abort signal by killing the entire process tree. + if (signal) { + if (signal.aborted) + onAbort(); + else + signal.addEventListener("abort", onAbort, { once: true }); + } + // Handle shell spawn errors and wait for the process to terminate without hanging + // on inherited stdio handles held by detached descendants. + const exitCode = await waitForChildProcess(child); + if (signal?.aborted) { + throw new Error("aborted"); + } + if (timedOut) { + throw new Error(`timeout:${timeout}`); + } + return { exitCode }; + } + finally { + if (child.pid) + untrackDetachedChildPid(child.pid); + if (timeoutHandle) + clearTimeout(timeoutHandle); + if (signal) + signal.removeEventListener("abort", onAbort); + } + }, + }; +} +function resolveSpawnContext(command, cwd, spawnHook, exposeSessionEnvironment, ctx) { + const env = { ...getShellEnv() }; + delete env.PI_SESSION_ID; + delete env.PI_SESSION_FILE; + delete env.PI_PROVIDER; + delete env.PI_MODEL; + delete env.PI_REASONING_LEVEL; + if (exposeSessionEnvironment && ctx) { + const model = ctx.model; + env.PI_SESSION_ID = ctx.sessionManager.getSessionId(); + const sessionFile = ctx.sessionManager.getSessionFile(); + if (sessionFile) + env.PI_SESSION_FILE = sessionFile; + if (model) { + env.PI_PROVIDER = model.provider; + env.PI_MODEL = model.id; + } + if (ctx.thinkingLevel) + env.PI_REASONING_LEVEL = ctx.thinkingLevel; + } + const baseContext = { command, cwd, env }; + return spawnHook ? spawnHook(baseContext) : baseContext; +} +const BASH_PREVIEW_LINES = 5; +const BASH_UPDATE_THROTTLE_MS = 100; +class BashResultRenderComponent extends Container { + state = { + cachedWidth: undefined, + cachedLines: undefined, + cachedSkipped: undefined, + }; +} +function formatDuration(ms) { + return `${(ms / 1000).toFixed(1)}s`; +} +function formatBashCall(args) { + const command = str(args?.command); + const timeout = args?.timeout; + const timeoutSuffix = timeout ? theme.fg("muted", ` (timeout ${timeout}s)`) : ""; + const commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg("toolOutput", "..."); + return theme.fg("toolTitle", theme.bold(`$ ${commandDisplay}`)) + timeoutSuffix; +} +function rebuildBashResultRenderComponent(component, result, options, showImages, startedAt, endedAt) { + const state = component.state; + component.clear(); + let output = getTextOutput(result, showImages).trim(); + const truncation = result.details?.truncation; + const fullOutputPath = result.details?.fullOutputPath; + if (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith("]")) { + const footerStart = output.lastIndexOf("\n\n["); + if (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) { + output = output.slice(0, footerStart).trimEnd(); + } + } + if (output) { + const styledOutput = output + .split("\n") + .map((line) => theme.fg("toolOutput", line)) + .join("\n"); + if (options.expanded) { + component.addChild(new Text(`\n${styledOutput}`, 0, 0)); + } + else { + component.addChild({ + render: (width) => { + if (state.cachedLines === undefined || state.cachedWidth !== width) { + const preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width); + state.cachedLines = preview.visualLines; + state.cachedSkipped = preview.skippedCount; + state.cachedWidth = width; + } + if (state.cachedSkipped && state.cachedSkipped > 0) { + const hint = theme.fg("muted", `... (${state.cachedSkipped} earlier lines,`) + + ` ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`; + return ["", truncateToWidth(hint, width, "..."), ...(state.cachedLines ?? [])]; + } + return ["", ...(state.cachedLines ?? [])]; + }, + invalidate: () => { + state.cachedWidth = undefined; + state.cachedLines = undefined; + state.cachedSkipped = undefined; + }, + }); + } + } + if (truncation?.truncated || fullOutputPath) { + const warnings = []; + if (fullOutputPath) { + warnings.push(`Full output: ${fullOutputPath}`); + } + if (truncation?.truncated) { + if (truncation.truncatedBy === "lines") { + warnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`); + } + else { + warnings.push(`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`); + } + } + component.addChild(new Text(`\n${theme.fg("warning", `[${warnings.join(". ")}]`)}`, 0, 0)); + } + if (startedAt !== undefined) { + const label = options.isPartial ? "Elapsed" : "Took"; + const endTime = endedAt ?? Date.now(); + component.addChild(new Text(`\n${theme.fg("muted", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0)); + } +} +export function createBashToolDefinition(cwd, options) { + const ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath }); + const commandPrefix = options?.commandPrefix; + const exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true; + const spawnHook = options?.spawnHook; + return { + name: "bash", + label: "bash", + description: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`, + promptSnippet: "Execute bash commands (ls, grep, find, etc.)", + promptGuidelines: exposeSessionEnvironment + ? ["Inspect PI_* environment variables for current model and session details."] + : undefined, + parameters: bashSchema, + async execute(_toolCallId, { command, timeout }, signal, onUpdate, ctx) { + const resolvedCommand = commandPrefix ? `${commandPrefix}\n${command}` : command; + const spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook, exposeSessionEnvironment, ctx); + const output = new OutputAccumulator({ tempFilePrefix: "pi-bash" }); + let acceptingOutput = true; + let updateTimer; + let updateDirty = false; + let lastUpdateAt = 0; + const emitOutputUpdate = () => { + if (!onUpdate || !updateDirty) + return; + updateDirty = false; + lastUpdateAt = Date.now(); + const snapshot = output.snapshot({ persistIfTruncated: true }); + onUpdate({ + content: [{ type: "text", text: snapshot.content || "" }], + details: { + truncation: snapshot.truncation.truncated ? snapshot.truncation : undefined, + fullOutputPath: snapshot.fullOutputPath, + }, + }); + }; + const clearUpdateTimer = () => { + if (updateTimer) { + clearTimeout(updateTimer); + updateTimer = undefined; + } + }; + const scheduleOutputUpdate = () => { + if (!onUpdate) + return; + updateDirty = true; + const delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt); + if (delay <= 0) { + clearUpdateTimer(); + emitOutputUpdate(); + return; + } + updateTimer ??= setTimeout(() => { + updateTimer = undefined; + emitOutputUpdate(); + }, delay); + }; + if (onUpdate) { + onUpdate({ content: [], details: undefined }); + } + const handleData = (data) => { + if (!acceptingOutput) + return; + output.append(data); + scheduleOutputUpdate(); + }; + const finishOutput = async () => { + acceptingOutput = false; + output.finish(); + clearUpdateTimer(); + emitOutputUpdate(); + const snapshot = output.snapshot({ persistIfTruncated: true }); + await output.closeTempFile(); + return snapshot; + }; + const formatOutput = (snapshot, emptyText = "(no output)") => { + const truncation = snapshot.truncation; + let text = snapshot.content || emptyText; + let details; + if (truncation.truncated) { + details = { truncation, fullOutputPath: snapshot.fullOutputPath }; + const startLine = truncation.totalLines - truncation.outputLines + 1; + const endLine = truncation.totalLines; + if (truncation.lastLinePartial) { + const lastLineSize = formatSize(output.getLastLineBytes()); + text += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`; + } + else if (truncation.truncatedBy === "lines") { + text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`; + } + else { + text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`; + } + } + return { text, details }; + }; + const appendStatus = (text, status) => `${text ? `${text}\n\n` : ""}${status}`; + try { + let exitCode; + try { + const result = await ops.exec(spawnContext.command, spawnContext.cwd, { + onData: handleData, + signal, + timeout, + env: spawnContext.env, + }); + exitCode = result.exitCode; + } + catch (err) { + const snapshot = await finishOutput(); + const { text } = formatOutput(snapshot, ""); + if (err instanceof Error && err.message === "aborted") { + throw new Error(appendStatus(text, "Command aborted")); + } + if (err instanceof Error && err.message.startsWith("timeout:")) { + const timeoutSecs = err.message.split(":")[1]; + throw new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`)); + } + throw err; + } + const snapshot = await finishOutput(); + const { text: outputText, details } = formatOutput(snapshot); + if (exitCode !== 0 && exitCode !== null) { + throw new Error(appendStatus(outputText, `Command exited with code ${exitCode}`)); + } + return { content: [{ type: "text", text: outputText }], details }; + } + finally { + clearUpdateTimer(); + } + }, + renderCall(args, _theme, context) { + const state = context.state; + if (context.executionStarted && state.startedAt === undefined) { + state.startedAt = Date.now(); + state.endedAt = undefined; + } + const text = context.lastComponent ?? new Text("", 0, 0); + text.setText(formatBashCall(args)); + return text; + }, + renderResult(result, options, _theme, context) { + const state = context.state; + if (state.startedAt !== undefined && options.isPartial && !state.interval) { + state.interval = setInterval(() => context.invalidate(), 1000); + } + if (!options.isPartial || context.isError) { + state.endedAt ??= Date.now(); + if (state.interval) { + clearInterval(state.interval); + state.interval = undefined; + } + } + const component = context.lastComponent ?? new BashResultRenderComponent(); + rebuildBashResultRenderComponent(component, result, options, context.showImages, state.startedAt, state.endedAt); + component.invalidate(); + return component; + }, + }; +} +export function createBashTool(cwd, options) { + const definition = createBashToolDefinition(cwd, options); + const tool = wrapToolDefinition(definition); + Object.assign(tool, { + promptSnippet: definition.promptSnippet, + promptGuidelines: definition.promptGuidelines, + }); + return tool; +} +//# sourceMappingURL=bash.js.map \ No newline at end of file diff --git a/dist/core/tools/bash.js.map b/dist/core/tools/bash.js.map new file mode 100644 index 0000000..9fb117b --- /dev/null +++ b/dist/core/tools/bash.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEtD,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,qBAAqB,EAAE,MAAM,uDAAuD,CAAC;AAC9F,OAAO,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EACN,cAAc,EACd,WAAW,EACX,eAAe,EACf,qBAAqB,EACrB,uBAAuB,GACvB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5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CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AAAA,CACZ","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Container, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport type { ExtensionContext, ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Bash command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\nexport type BashToolInput = Static;\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null }>;\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = getShellConfig(options?.shellPath);\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute bash commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\treturn { exitCode };\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tdelete env.PI_SESSION_ID;\n\tdelete env.PI_SESSION_FILE;\n\tdelete env.PI_PROVIDER;\n\tdelete env.PI_MODEL;\n\tdelete env.PI_REASONING_LEVEL;\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tenv.PI_SESSION_ID = ctx.sessionManager.getSessionId();\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) env.PI_SESSION_FILE = sessionFile;\n\t\tif (model) {\n\t\t\tenv.PI_PROVIDER = model.provider;\n\t\t\tenv.PI_MODEL = model.id;\n\t\t}\n\t\tif (ctx.thinkingLevel) env.PI_REASONING_LEVEL = ctx.thinkingLevel;\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\ntype BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatDuration(ms: number): string {\n\treturn `${(ms / 1000).toFixed(1)}s`;\n}\n\nfunction formatBashCall(args: { command?: string; timeout?: number } | undefined): string {\n\tconst command = str(args?.command);\n\tconst timeout = args?.timeout as number | undefined;\n\tconst timeoutSuffix = timeout ? theme.fg(\"muted\", ` (timeout ${timeout}s)`) : \"\";\n\tconst commandDisplay = command === null ? invalidArgText(theme) : command ? command : theme.fg(\"toolOutput\", \"...\");\n\treturn theme.fg(\"toolTitle\", theme.bold(`$ ${commandDisplay}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tlet output = getTextOutput(result as any, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines;\n\t\t\t\t\t\tstate.cachedSkipped = preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ToolDefinition {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: \"bash\",\n\t\tlabel: \"bash\",\n\t\tdescription: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\t\tpromptGuidelines: exposeSessionEnvironment\n\t\t\t? [\"Inspect PI_* environment variables for current model and session details.\"]\n\t\t\t: undefined,\n\t\tparameters: bashSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ command, timeout }: { command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\tonUpdate?,\n\t\t\tctx?,\n\t\t) {\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook, exposeSessionEnvironment, ctx);\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: \"pi-bash\" });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new Error(appendStatus(text, \"Command aborted\"));\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new Error(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`));\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new Error(appendStatus(outputText, `Command exited with code ${exitCode}`));\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatBashCall(args));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/edit-diff.d.ts b/dist/core/tools/edit-diff.d.ts new file mode 100644 index 0000000..daac17e --- /dev/null +++ b/dist/core/tools/edit-diff.d.ts @@ -0,0 +1,106 @@ +/** + * Shared diff computation utilities for the edit and similar tools. + */ +export declare function detectLineEnding(content: string): "\r\n" | "\n"; +export declare function normalizeToLF(text: string): string; +export declare function restoreLineEndings(text: string, ending: "\r\n" | "\n"): string; +/** + * Normalize text for fuzzy matching. Applies progressive transformations: + * - Strip trailing whitespace from each line + * - Normalize smart quotes to ASCII equivalents + * - Normalize Unicode dashes/hyphens to ASCII hyphen + * - Normalize special Unicode spaces to regular space + */ +export declare function normalizeForFuzzyMatch(text: string): string; +interface MatchedEdit { + editIndex: number; + matchIndex: number; + matchLength: number; + newText: string; +} +type TextReplacement = Pick; +/** + * Apply replacements matched against `baseContent` to `originalContent` while + * preserving unchanged line blocks from the original. + * + * This is useful when `baseContent` is a normalized view of the original. Each + * replacement is widened to the lines it actually touches, those touched lines + * are rewritten from the normalized base, and all other lines are copied back + * from `originalContent`. The actual replacement ranges drive preservation so + * duplicate normalized lines cannot be aligned to the wrong occurrence. + */ +export declare function applyReplacementsPreservingUnchangedLines(originalContent: string, baseContent: string, replacements: TextReplacement[]): string; +export interface FuzzyMatchResult { + /** Whether a match was found */ + found: boolean; + /** The index where the match starts (in the content that should be used for replacement) */ + index: number; + /** Length of the matched text */ + matchLength: number; + /** Whether fuzzy matching was used (false = exact match) */ + usedFuzzyMatch: boolean; + /** + * The content to use for replacement operations. + * When exact match: original content. When fuzzy match: normalized content. + */ + contentForReplacement: string; +} +export interface Edit { + oldText: string; + newText: string; +} +export interface AppliedEditsResult { + baseContent: string; + newContent: string; +} +/** + * Find oldText in content, trying exact match first, then fuzzy match. + * When fuzzy matching is used, the returned contentForReplacement is the + * fuzzy-normalized version of the content (trailing whitespace stripped, + * Unicode quotes/dashes normalized to ASCII). + */ +export declare function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult; +/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */ +export declare function stripBom(content: string): { + bom: string; + text: string; +}; +/** + * Apply one or more exact-text replacements to LF-normalized content. + * + * All edits are matched against the same original content. Replacements are + * then applied in reverse order so offsets remain stable. If any edit needs + * fuzzy matching, the operation runs in fuzzy-normalized content space and then + * overlays those line-level changes onto the original content so unchanged line + * blocks keep their original bytes. + */ +export declare function applyEditsToNormalizedContent(normalizedContent: string, edits: Edit[], path: string): AppliedEditsResult; +/** Generate a standard unified patch. */ +export declare function generateUnifiedPatch(path: string, oldContent: string, newContent: string, contextLines?: number): string; +/** + * Generate a display-oriented diff string with line numbers and context. + * Returns both the diff string and the first changed line number (in the new file). + */ +export declare function generateDiffString(oldContent: string, newContent: string, contextLines?: number): { + diff: string; + firstChangedLine: number | undefined; +}; +export interface EditDiffResult { + diff: string; + firstChangedLine: number | undefined; +} +export interface EditDiffError { + error: string; +} +/** + * Compute the diff for one or more edit operations without applying them. + * Used for preview rendering in the TUI before the tool executes. + */ +export declare function computeEditsDiff(path: string, edits: Edit[], cwd: string): Promise; +/** + * Compute the diff for a single edit operation without applying it. + * Kept as a convenience wrapper for single-edit callers. + */ +export declare function computeEditDiff(path: string, oldText: string, newText: string, cwd: string): Promise; +export {}; +//# sourceMappingURL=edit-diff.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/edit-diff.d.ts.map b/dist/core/tools/edit-diff.d.ts.map new file mode 100644 index 0000000..7f74f9f --- /dev/null +++ b/dist/core/tools/edit-diff.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"edit-diff.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;GAEG;AAOH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAM/D;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAE9E;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAqB3D;AAWD,UAAU,WAAW;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,KAAK,eAAe,GAAG,IAAI,CAAC,WAAW,EAAE,YAAY,GAAG,aAAa,GAAG,SAAS,CAAC,CAAC;AAiDnF;;;;;;;;;GASG;AACH,wBAAgB,yCAAyC,CACxD,eAAe,EAAE,MAAM,EACvB,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,eAAe,EAAE,GAC7B,MAAM,CAqCR;AAED,MAAM,WAAW,gBAAgB;IAChC,gCAAgC;IAChC,KAAK,EAAE,OAAO,CAAC;IACf,4FAA4F;IAC5F,KAAK,EAAE,MAAM,CAAC;IACd,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,4DAA4D;IAC5D,cAAc,EAAE,OAAO,CAAC;IACxB;;;OAGG;IACH,qBAAqB,EAAE,MAAM,CAAC;CAC9B;AAED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ED;;;GAGG;AACH,wBAAsB,eAAe,CACpC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,cAAc,GAAG,aAAa,CAAC,CAEzC","sourcesContent":["/**\n * Shared diff computation utilities for the edit and similar tools.\n */\n\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\nimport { resolveToCwd } from \"./path-utils.ts\";\n\nexport function detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n\tconst crlfIdx = content.indexOf(\"\\r\\n\");\n\tconst lfIdx = content.indexOf(\"\\n\");\n\tif (lfIdx === -1) return \"\\n\";\n\tif (crlfIdx === -1) return \"\\n\";\n\treturn crlfIdx < lfIdx ? \"\\r\\n\" : \"\\n\";\n}\n\nexport function normalizeToLF(text: string): string {\n\treturn text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n}\n\nexport function restoreLineEndings(text: string, ending: \"\\r\\n\" | \"\\n\"): string {\n\treturn ending === \"\\r\\n\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\n}\n\n/**\n * Normalize text for fuzzy matching. Applies progressive transformations:\n * - Strip trailing whitespace from each line\n * - Normalize smart quotes to ASCII equivalents\n * - Normalize Unicode dashes/hyphens to ASCII hyphen\n * - Normalize special Unicode spaces to regular space\n */\nexport function normalizeForFuzzyMatch(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.normalize(\"NFKC\")\n\t\t\t// Strip trailing whitespace per line\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.join(\"\\n\")\n\t\t\t// Smart single quotes → '\n\t\t\t.replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n\t\t\t// Smart double quotes → \"\n\t\t\t.replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n\t\t\t// Various dashes/hyphens → -\n\t\t\t// U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,\n\t\t\t// U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus\n\t\t\t.replace(/[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/g, \"-\")\n\t\t\t// Special spaces → regular space\n\t\t\t// U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,\n\t\t\t// U+205F medium math space, U+3000 ideographic space\n\t\t\t.replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, \" \")\n\t);\n}\n\nfunction splitLinesWithEndings(content: string): string[] {\n\treturn content.match(/[^\\n]*\\n|[^\\n]+/g) ?? [];\n}\n\ninterface LineSpan {\n\tstart: number;\n\tend: number;\n}\n\ninterface MatchedEdit {\n\teditIndex: number;\n\tmatchIndex: number;\n\tmatchLength: number;\n\tnewText: string;\n}\n\ntype TextReplacement = Pick;\n\nfunction getLineSpans(content: string): LineSpan[] {\n\tlet offset = 0;\n\treturn splitLinesWithEndings(content).map((line) => {\n\t\tconst span = { start: offset, end: offset + line.length };\n\t\toffset = span.end;\n\t\treturn span;\n\t});\n}\n\nfunction getReplacementLineRange(lines: LineSpan[], replacement: TextReplacement) {\n\tconst replacementStart = replacement.matchIndex;\n\tconst replacementEnd = replacement.matchIndex + replacement.matchLength;\n\n\tlet startLine = -1;\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst line = lines[i];\n\t\tif (replacementStart >= line.start && replacementStart < line.end) {\n\t\t\tstartLine = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (startLine === -1) {\n\t\tthrow new Error(\"Replacement range is outside the base content.\");\n\t}\n\n\tlet endLine = startLine;\n\twhile (endLine < lines.length && lines[endLine].end < replacementEnd) {\n\t\tendLine++;\n\t}\n\tif (endLine >= lines.length) {\n\t\tthrow new Error(\"Replacement range is outside the base content.\");\n\t}\n\n\treturn { startLine, endLine: endLine + 1 };\n}\n\nfunction applyReplacements(content: string, replacements: TextReplacement[], offset = 0): string {\n\tlet result = content;\n\tfor (let i = replacements.length - 1; i >= 0; i--) {\n\t\tconst replacement = replacements[i];\n\t\tconst matchIndex = replacement.matchIndex - offset;\n\t\tresult =\n\t\t\tresult.substring(0, matchIndex) + replacement.newText + result.substring(matchIndex + replacement.matchLength);\n\t}\n\treturn result;\n}\n\n/**\n * Apply replacements matched against `baseContent` to `originalContent` while\n * preserving unchanged line blocks from the original.\n *\n * This is useful when `baseContent` is a normalized view of the original. Each\n * replacement is widened to the lines it actually touches, those touched lines\n * are rewritten from the normalized base, and all other lines are copied back\n * from `originalContent`. The actual replacement ranges drive preservation so\n * duplicate normalized lines cannot be aligned to the wrong occurrence.\n */\nexport function applyReplacementsPreservingUnchangedLines(\n\toriginalContent: string,\n\tbaseContent: string,\n\treplacements: TextReplacement[],\n): string {\n\tconst originalLines = splitLinesWithEndings(originalContent);\n\tconst baseLines = getLineSpans(baseContent);\n\tif (originalLines.length !== baseLines.length) {\n\t\tthrow new Error(\"Cannot preserve unchanged lines because the base content has a different line count.\");\n\t}\n\n\tconst groups: Array<{ startLine: number; endLine: number; replacements: TextReplacement[] }> = [];\n\tconst sortedReplacements = [...replacements].sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (const replacement of sortedReplacements) {\n\t\tconst range = getReplacementLineRange(baseLines, replacement);\n\t\tconst current = groups[groups.length - 1];\n\t\tif (current && range.startLine < current.endLine) {\n\t\t\tcurrent.endLine = Math.max(current.endLine, range.endLine);\n\t\t\tcurrent.replacements.push(replacement);\n\t\t\tcontinue;\n\t\t}\n\t\tgroups.push({ ...range, replacements: [replacement] });\n\t}\n\n\tlet originalLineIndex = 0;\n\tlet result = \"\";\n\tfor (const group of groups) {\n\t\tresult += originalLines.slice(originalLineIndex, group.startLine).join(\"\");\n\n\t\tconst groupStartOffset = baseLines[group.startLine].start;\n\t\tconst groupEndOffset = baseLines[group.endLine - 1].end;\n\t\tresult += applyReplacements(\n\t\t\tbaseContent.slice(groupStartOffset, groupEndOffset),\n\t\t\tgroup.replacements,\n\t\t\tgroupStartOffset,\n\t\t);\n\t\toriginalLineIndex = group.endLine;\n\t}\n\tresult += originalLines.slice(originalLineIndex).join(\"\");\n\n\treturn result;\n}\n\nexport interface FuzzyMatchResult {\n\t/** Whether a match was found */\n\tfound: boolean;\n\t/** The index where the match starts (in the content that should be used for replacement) */\n\tindex: number;\n\t/** Length of the matched text */\n\tmatchLength: number;\n\t/** Whether fuzzy matching was used (false = exact match) */\n\tusedFuzzyMatch: boolean;\n\t/**\n\t * The content to use for replacement operations.\n\t * When exact match: original content. When fuzzy match: normalized content.\n\t */\n\tcontentForReplacement: string;\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n}\n\nexport interface AppliedEditsResult {\n\tbaseContent: string;\n\tnewContent: string;\n}\n\n/**\n * Find oldText in content, trying exact match first, then fuzzy match.\n * When fuzzy matching is used, the returned contentForReplacement is the\n * fuzzy-normalized version of the content (trailing whitespace stripped,\n * Unicode quotes/dashes normalized to ASCII).\n */\nexport function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult {\n\t// Try exact match first\n\tconst exactIndex = content.indexOf(oldText);\n\tif (exactIndex !== -1) {\n\t\treturn {\n\t\t\tfound: true,\n\t\t\tindex: exactIndex,\n\t\t\tmatchLength: oldText.length,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// Try fuzzy match - work entirely in normalized space\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\tconst fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);\n\n\tif (fuzzyIndex === -1) {\n\t\treturn {\n\t\t\tfound: false,\n\t\t\tindex: -1,\n\t\t\tmatchLength: 0,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// When fuzzy matching, return offsets in normalized space. Callers can use\n\t// the normalized content to compute replacements, then decide how much of\n\t// that normalized output should be written back.\n\treturn {\n\t\tfound: true,\n\t\tindex: fuzzyIndex,\n\t\tmatchLength: fuzzyOldText.length,\n\t\tusedFuzzyMatch: true,\n\t\tcontentForReplacement: fuzzyContent,\n\t};\n}\n\n/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */\nexport function stripBom(content: string): { bom: string; text: string } {\n\treturn content.startsWith(\"\\uFEFF\") ? { bom: \"\\uFEFF\", text: content.slice(1) } : { bom: \"\", text: content };\n}\n\nfunction countOccurrences(content: string, oldText: string): number {\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\treturn fuzzyContent.split(fuzzyOldText).length - 1;\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`,\n\t);\n}\n\nfunction getDuplicateError(path: string, editIndex: number, totalEdits: number, occurrences: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`,\n\t);\n}\n\nfunction getEmptyOldTextError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(`oldText must not be empty in ${path}.`);\n\t}\n\treturn new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`);\n}\n\nfunction getNoChangeError(path: string, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t);\n\t}\n\treturn new Error(`No changes made to ${path}. The replacements produced identical content.`);\n}\n\n/**\n * Apply one or more exact-text replacements to LF-normalized content.\n *\n * All edits are matched against the same original content. Replacements are\n * then applied in reverse order so offsets remain stable. If any edit needs\n * fuzzy matching, the operation runs in fuzzy-normalized content space and then\n * overlays those line-level changes onto the original content so unchanged line\n * blocks keep their original bytes.\n */\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\tconst normalizedEdits = edits.map((edit) => ({\n\t\toldText: normalizeToLF(edit.oldText),\n\t\tnewText: normalizeToLF(edit.newText),\n\t}));\n\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tif (normalizedEdits[i].oldText.length === 0) {\n\t\t\tthrow getEmptyOldTextError(path, i, normalizedEdits.length);\n\t\t}\n\t}\n\n\tconst initialMatches = normalizedEdits.map((edit) => fuzzyFindText(normalizedContent, edit.oldText));\n\tconst usedFuzzyMatch = initialMatches.some((match) => match.usedFuzzyMatch);\n\tconst replacementBaseContent = usedFuzzyMatch ? normalizeForFuzzyMatch(normalizedContent) : normalizedContent;\n\n\tconst matchedEdits: MatchedEdit[] = [];\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tconst edit = normalizedEdits[i];\n\t\tconst matchResult = fuzzyFindText(replacementBaseContent, edit.oldText);\n\t\tif (!matchResult.found) {\n\t\t\tthrow getNotFoundError(path, i, normalizedEdits.length);\n\t\t}\n\n\t\tconst occurrences = countOccurrences(replacementBaseContent, edit.oldText);\n\t\tif (occurrences > 1) {\n\t\t\tthrow getDuplicateError(path, i, normalizedEdits.length, occurrences);\n\t\t}\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex: matchResult.index,\n\t\t\tmatchLength: matchResult.matchLength,\n\t\t\tnewText: edit.newText,\n\t\t});\n\t}\n\n\tmatchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (let i = 1; i < matchedEdits.length; i++) {\n\t\tconst previous = matchedEdits[i - 1];\n\t\tconst current = matchedEdits[i];\n\t\tif (previous.matchIndex + previous.matchLength > current.matchIndex) {\n\t\t\tthrow new Error(\n\t\t\t\t`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst baseContent = normalizedContent;\n\tconst newContent = usedFuzzyMatch\n\t\t? applyReplacementsPreservingUnchangedLines(normalizedContent, replacementBaseContent, matchedEdits)\n\t\t: applyReplacements(replacementBaseContent, matchedEdits);\n\n\tif (baseContent === newContent) {\n\t\tthrow getNoChangeError(path, normalizedEdits.length);\n\t}\n\n\treturn { baseContent, newContent };\n}\n\n/** Generate a standard unified patch. */\nexport function generateUnifiedPatch(path: string, oldContent: string, newContent: string, contextLines = 4): string {\n\treturn Diff.createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, {\n\t\tcontext: contextLines,\n\t\theaderOptions: Diff.FILE_HEADERS_ONLY,\n\t});\n}\n\n/**\n * Generate a display-oriented diff string with line numbers and context.\n * Returns both the diff string and the first changed line number (in the new file).\n */\nexport function generateDiffString(\n\toldContent: string,\n\tnewContent: string,\n\tcontextLines = 4,\n): { diff: string; firstChangedLine: number | undefined } {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\tlet firstChangedLine: number | undefined;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\t// Capture the first changed line (in the new file)\n\t\t\tif (firstChangedLine === undefined) {\n\t\t\t\tfirstChangedLine = newLineNum;\n\t\t\t}\n\n\t\t\t// Show the change\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\t// removed\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\t// Context lines - only show a few before/after changes\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\t\t\tconst hasLeadingChange = lastWasChange;\n\t\t\tconst hasTrailingChange = nextPartIsChange;\n\n\t\t\tif (hasLeadingChange && hasTrailingChange) {\n\t\t\t\tif (raw.length <= contextLines * 2) {\n\t\t\t\t\tfor (const line of raw) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst leadingLines = raw.slice(0, contextLines);\n\t\t\t\t\tconst trailingLines = raw.slice(raw.length - contextLines);\n\t\t\t\t\tconst skippedLines = raw.length - leadingLines.length - trailingLines.length;\n\n\t\t\t\t\tfor (const line of leadingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\n\t\t\t\t\tfor (const line of trailingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (hasLeadingChange) {\n\t\t\t\tconst shownLines = raw.slice(0, contextLines);\n\t\t\t\tconst skippedLines = raw.length - shownLines.length;\n\n\t\t\t\tfor (const line of shownLines) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\t\t\t} else if (hasTrailingChange) {\n\t\t\t\tconst skippedLines = Math.max(0, raw.length - contextLines);\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\n\t\t\t\tfor (const line of raw.slice(skippedLines)) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Skip these context lines entirely\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn { diff: output.join(\"\\n\"), firstChangedLine };\n}\n\nexport interface EditDiffResult {\n\tdiff: string;\n\tfirstChangedLine: number | undefined;\n}\n\nexport interface EditDiffError {\n\terror: string;\n}\n\n/**\n * Compute the diff for one or more edit operations without applying them.\n * Used for preview rendering in the TUI before the tool executes.\n */\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise {\n\tconst absolutePath = resolveToCwd(path, cwd);\n\n\ttry {\n\t\t// Check if file exists and is readable\n\t\ttry {\n\t\t\tawait access(absolutePath, constants.R_OK);\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\treturn { error: `Could not edit file: ${path}. ${errorMessage}.` };\n\t\t}\n\n\t\t// Read the file\n\t\tconst rawContent = await readFile(absolutePath, \"utf-8\");\n\n\t\t// Strip BOM before matching (LLM won't include invisible BOM in oldText)\n\t\tconst { text: content } = stripBom(rawContent);\n\t\tconst normalizedContent = normalizeToLF(content);\n\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\n\t\t// Generate the diff\n\t\treturn generateDiffString(baseContent, newContent);\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n\n/**\n * Compute the diff for a single edit operation without applying it.\n * Kept as a convenience wrapper for single-edit callers.\n */\nexport async function computeEditDiff(\n\tpath: string,\n\toldText: string,\n\tnewText: string,\n\tcwd: string,\n): Promise {\n\treturn computeEditsDiff(path, [{ oldText, newText }], cwd);\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/edit-diff.js b/dist/core/tools/edit-diff.js new file mode 100644 index 0000000..954958c --- /dev/null +++ b/dist/core/tools/edit-diff.js @@ -0,0 +1,424 @@ +/** + * Shared diff computation utilities for the edit and similar tools. + */ +import * as Diff from "diff"; +import { constants } from "fs"; +import { access, readFile } from "fs/promises"; +import { resolveToCwd } from "./path-utils.js"; +export function detectLineEnding(content) { + const crlfIdx = content.indexOf("\r\n"); + const lfIdx = content.indexOf("\n"); + if (lfIdx === -1) + return "\n"; + if (crlfIdx === -1) + return "\n"; + return crlfIdx < lfIdx ? "\r\n" : "\n"; +} +export function normalizeToLF(text) { + return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); +} +export function restoreLineEndings(text, ending) { + return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text; +} +/** + * Normalize text for fuzzy matching. Applies progressive transformations: + * - Strip trailing whitespace from each line + * - Normalize smart quotes to ASCII equivalents + * - Normalize Unicode dashes/hyphens to ASCII hyphen + * - Normalize special Unicode spaces to regular space + */ +export function normalizeForFuzzyMatch(text) { + return (text + .normalize("NFKC") + // Strip trailing whitespace per line + .split("\n") + .map((line) => line.trimEnd()) + .join("\n") + // Smart single quotes → ' + .replace(/[\u2018\u2019\u201A\u201B]/g, "'") + // Smart double quotes → " + .replace(/[\u201C\u201D\u201E\u201F]/g, '"') + // Various dashes/hyphens → - + // U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash, + // U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus + .replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g, "-") + // Special spaces → regular space + // U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP, + // U+205F medium math space, U+3000 ideographic space + .replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ")); +} +function splitLinesWithEndings(content) { + return content.match(/[^\n]*\n|[^\n]+/g) ?? []; +} +function getLineSpans(content) { + let offset = 0; + return splitLinesWithEndings(content).map((line) => { + const span = { start: offset, end: offset + line.length }; + offset = span.end; + return span; + }); +} +function getReplacementLineRange(lines, replacement) { + const replacementStart = replacement.matchIndex; + const replacementEnd = replacement.matchIndex + replacement.matchLength; + let startLine = -1; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (replacementStart >= line.start && replacementStart < line.end) { + startLine = i; + break; + } + } + if (startLine === -1) { + throw new Error("Replacement range is outside the base content."); + } + let endLine = startLine; + while (endLine < lines.length && lines[endLine].end < replacementEnd) { + endLine++; + } + if (endLine >= lines.length) { + throw new Error("Replacement range is outside the base content."); + } + return { startLine, endLine: endLine + 1 }; +} +function applyReplacements(content, replacements, offset = 0) { + let result = content; + for (let i = replacements.length - 1; i >= 0; i--) { + const replacement = replacements[i]; + const matchIndex = replacement.matchIndex - offset; + result = + result.substring(0, matchIndex) + replacement.newText + result.substring(matchIndex + replacement.matchLength); + } + return result; +} +/** + * Apply replacements matched against `baseContent` to `originalContent` while + * preserving unchanged line blocks from the original. + * + * This is useful when `baseContent` is a normalized view of the original. Each + * replacement is widened to the lines it actually touches, those touched lines + * are rewritten from the normalized base, and all other lines are copied back + * from `originalContent`. The actual replacement ranges drive preservation so + * duplicate normalized lines cannot be aligned to the wrong occurrence. + */ +export function applyReplacementsPreservingUnchangedLines(originalContent, baseContent, replacements) { + const originalLines = splitLinesWithEndings(originalContent); + const baseLines = getLineSpans(baseContent); + if (originalLines.length !== baseLines.length) { + throw new Error("Cannot preserve unchanged lines because the base content has a different line count."); + } + const groups = []; + const sortedReplacements = [...replacements].sort((a, b) => a.matchIndex - b.matchIndex); + for (const replacement of sortedReplacements) { + const range = getReplacementLineRange(baseLines, replacement); + const current = groups[groups.length - 1]; + if (current && range.startLine < current.endLine) { + current.endLine = Math.max(current.endLine, range.endLine); + current.replacements.push(replacement); + continue; + } + groups.push({ ...range, replacements: [replacement] }); + } + let originalLineIndex = 0; + let result = ""; + for (const group of groups) { + result += originalLines.slice(originalLineIndex, group.startLine).join(""); + const groupStartOffset = baseLines[group.startLine].start; + const groupEndOffset = baseLines[group.endLine - 1].end; + result += applyReplacements(baseContent.slice(groupStartOffset, groupEndOffset), group.replacements, groupStartOffset); + originalLineIndex = group.endLine; + } + result += originalLines.slice(originalLineIndex).join(""); + return result; +} +/** + * Find oldText in content, trying exact match first, then fuzzy match. + * When fuzzy matching is used, the returned contentForReplacement is the + * fuzzy-normalized version of the content (trailing whitespace stripped, + * Unicode quotes/dashes normalized to ASCII). + */ +export function fuzzyFindText(content, oldText) { + // Try exact match first + const exactIndex = content.indexOf(oldText); + if (exactIndex !== -1) { + return { + found: true, + index: exactIndex, + matchLength: oldText.length, + usedFuzzyMatch: false, + contentForReplacement: content, + }; + } + // Try fuzzy match - work entirely in normalized space + const fuzzyContent = normalizeForFuzzyMatch(content); + const fuzzyOldText = normalizeForFuzzyMatch(oldText); + const fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText); + if (fuzzyIndex === -1) { + return { + found: false, + index: -1, + matchLength: 0, + usedFuzzyMatch: false, + contentForReplacement: content, + }; + } + // When fuzzy matching, return offsets in normalized space. Callers can use + // the normalized content to compute replacements, then decide how much of + // that normalized output should be written back. + return { + found: true, + index: fuzzyIndex, + matchLength: fuzzyOldText.length, + usedFuzzyMatch: true, + contentForReplacement: fuzzyContent, + }; +} +/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */ +export function stripBom(content) { + return content.startsWith("\uFEFF") ? { bom: "\uFEFF", text: content.slice(1) } : { bom: "", text: content }; +} +function countOccurrences(content, oldText) { + const fuzzyContent = normalizeForFuzzyMatch(content); + const fuzzyOldText = normalizeForFuzzyMatch(oldText); + return fuzzyContent.split(fuzzyOldText).length - 1; +} +function getNotFoundError(path, editIndex, totalEdits) { + if (totalEdits === 1) { + return new Error(`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`); + } + return new Error(`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`); +} +function getDuplicateError(path, editIndex, totalEdits, occurrences) { + if (totalEdits === 1) { + return new Error(`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`); + } + return new Error(`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`); +} +function getEmptyOldTextError(path, editIndex, totalEdits) { + if (totalEdits === 1) { + return new Error(`oldText must not be empty in ${path}.`); + } + return new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`); +} +function getNoChangeError(path, totalEdits) { + if (totalEdits === 1) { + return new Error(`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`); + } + return new Error(`No changes made to ${path}. The replacements produced identical content.`); +} +/** + * Apply one or more exact-text replacements to LF-normalized content. + * + * All edits are matched against the same original content. Replacements are + * then applied in reverse order so offsets remain stable. If any edit needs + * fuzzy matching, the operation runs in fuzzy-normalized content space and then + * overlays those line-level changes onto the original content so unchanged line + * blocks keep their original bytes. + */ +export function applyEditsToNormalizedContent(normalizedContent, edits, path) { + const normalizedEdits = edits.map((edit) => ({ + oldText: normalizeToLF(edit.oldText), + newText: normalizeToLF(edit.newText), + })); + for (let i = 0; i < normalizedEdits.length; i++) { + if (normalizedEdits[i].oldText.length === 0) { + throw getEmptyOldTextError(path, i, normalizedEdits.length); + } + } + const initialMatches = normalizedEdits.map((edit) => fuzzyFindText(normalizedContent, edit.oldText)); + const usedFuzzyMatch = initialMatches.some((match) => match.usedFuzzyMatch); + const replacementBaseContent = usedFuzzyMatch ? normalizeForFuzzyMatch(normalizedContent) : normalizedContent; + const matchedEdits = []; + for (let i = 0; i < normalizedEdits.length; i++) { + const edit = normalizedEdits[i]; + const matchResult = fuzzyFindText(replacementBaseContent, edit.oldText); + if (!matchResult.found) { + throw getNotFoundError(path, i, normalizedEdits.length); + } + const occurrences = countOccurrences(replacementBaseContent, edit.oldText); + if (occurrences > 1) { + throw getDuplicateError(path, i, normalizedEdits.length, occurrences); + } + matchedEdits.push({ + editIndex: i, + matchIndex: matchResult.index, + matchLength: matchResult.matchLength, + newText: edit.newText, + }); + } + matchedEdits.sort((a, b) => a.matchIndex - b.matchIndex); + for (let i = 1; i < matchedEdits.length; i++) { + const previous = matchedEdits[i - 1]; + const current = matchedEdits[i]; + if (previous.matchIndex + previous.matchLength > current.matchIndex) { + throw new Error(`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`); + } + } + const baseContent = normalizedContent; + const newContent = usedFuzzyMatch + ? applyReplacementsPreservingUnchangedLines(normalizedContent, replacementBaseContent, matchedEdits) + : applyReplacements(replacementBaseContent, matchedEdits); + if (baseContent === newContent) { + throw getNoChangeError(path, normalizedEdits.length); + } + return { baseContent, newContent }; +} +/** Generate a standard unified patch. */ +export function generateUnifiedPatch(path, oldContent, newContent, contextLines = 4) { + return Diff.createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, { + context: contextLines, + headerOptions: Diff.FILE_HEADERS_ONLY, + }); +} +/** + * Generate a display-oriented diff string with line numbers and context. + * Returns both the diff string and the first changed line number (in the new file). + */ +export function generateDiffString(oldContent, newContent, contextLines = 4) { + const parts = Diff.diffLines(oldContent, newContent); + const output = []; + const oldLines = oldContent.split("\n"); + const newLines = newContent.split("\n"); + const maxLineNum = Math.max(oldLines.length, newLines.length); + const lineNumWidth = String(maxLineNum).length; + let oldLineNum = 1; + let newLineNum = 1; + let lastWasChange = false; + let firstChangedLine; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + const raw = part.value.split("\n"); + if (raw[raw.length - 1] === "") { + raw.pop(); + } + if (part.added || part.removed) { + // Capture the first changed line (in the new file) + if (firstChangedLine === undefined) { + firstChangedLine = newLineNum; + } + // Show the change + for (const line of raw) { + if (part.added) { + const lineNum = String(newLineNum).padStart(lineNumWidth, " "); + output.push(`+${lineNum} ${line}`); + newLineNum++; + } + else { + // removed + const lineNum = String(oldLineNum).padStart(lineNumWidth, " "); + output.push(`-${lineNum} ${line}`); + oldLineNum++; + } + } + lastWasChange = true; + } + else { + // Context lines - only show a few before/after changes + const nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed); + const hasLeadingChange = lastWasChange; + const hasTrailingChange = nextPartIsChange; + if (hasLeadingChange && hasTrailingChange) { + if (raw.length <= contextLines * 2) { + for (const line of raw) { + const lineNum = String(oldLineNum).padStart(lineNumWidth, " "); + output.push(` ${lineNum} ${line}`); + oldLineNum++; + newLineNum++; + } + } + else { + const leadingLines = raw.slice(0, contextLines); + const trailingLines = raw.slice(raw.length - contextLines); + const skippedLines = raw.length - leadingLines.length - trailingLines.length; + for (const line of leadingLines) { + const lineNum = String(oldLineNum).padStart(lineNumWidth, " "); + output.push(` ${lineNum} ${line}`); + oldLineNum++; + newLineNum++; + } + output.push(` ${"".padStart(lineNumWidth, " ")} ...`); + oldLineNum += skippedLines; + newLineNum += skippedLines; + for (const line of trailingLines) { + const lineNum = String(oldLineNum).padStart(lineNumWidth, " "); + output.push(` ${lineNum} ${line}`); + oldLineNum++; + newLineNum++; + } + } + } + else if (hasLeadingChange) { + const shownLines = raw.slice(0, contextLines); + const skippedLines = raw.length - shownLines.length; + for (const line of shownLines) { + const lineNum = String(oldLineNum).padStart(lineNumWidth, " "); + output.push(` ${lineNum} ${line}`); + oldLineNum++; + newLineNum++; + } + if (skippedLines > 0) { + output.push(` ${"".padStart(lineNumWidth, " ")} ...`); + oldLineNum += skippedLines; + newLineNum += skippedLines; + } + } + else if (hasTrailingChange) { + const skippedLines = Math.max(0, raw.length - contextLines); + if (skippedLines > 0) { + output.push(` ${"".padStart(lineNumWidth, " ")} ...`); + oldLineNum += skippedLines; + newLineNum += skippedLines; + } + for (const line of raw.slice(skippedLines)) { + const lineNum = String(oldLineNum).padStart(lineNumWidth, " "); + output.push(` ${lineNum} ${line}`); + oldLineNum++; + newLineNum++; + } + } + else { + // Skip these context lines entirely + oldLineNum += raw.length; + newLineNum += raw.length; + } + lastWasChange = false; + } + } + return { diff: output.join("\n"), firstChangedLine }; +} +/** + * Compute the diff for one or more edit operations without applying them. + * Used for preview rendering in the TUI before the tool executes. + */ +export async function computeEditsDiff(path, edits, cwd) { + const absolutePath = resolveToCwd(path, cwd); + try { + // Check if file exists and is readable + try { + await access(absolutePath, constants.R_OK); + } + catch (error) { + const errorMessage = error instanceof Error && "code" in error ? `Error code: ${error.code}` : String(error); + return { error: `Could not edit file: ${path}. ${errorMessage}.` }; + } + // Read the file + const rawContent = await readFile(absolutePath, "utf-8"); + // Strip BOM before matching (LLM won't include invisible BOM in oldText) + const { text: content } = stripBom(rawContent); + const normalizedContent = normalizeToLF(content); + const { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path); + // Generate the diff + return generateDiffString(baseContent, newContent); + } + catch (err) { + return { error: err instanceof Error ? err.message : String(err) }; + } +} +/** + * Compute the diff for a single edit operation without applying it. + * Kept as a convenience wrapper for single-edit callers. + */ +export async function computeEditDiff(path, oldText, newText, cwd) { + return computeEditsDiff(path, [{ oldText, newText }], cwd); +} +//# sourceMappingURL=edit-diff.js.map \ No newline at end of file diff --git a/dist/core/tools/edit-diff.js.map b/dist/core/tools/edit-diff.js.map new file mode 100644 index 0000000..63a5b85 --- /dev/null +++ b/dist/core/tools/edit-diff.js.map @@ -0,0 +1 @@ +{"version":3,"file":"edit-diff.js","sourceRoot":"","sources":["../../../src/core/tools/edit-diff.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,UAAU,gBAAgB,CAAC,OAAe,EAAiB;IAChE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACxC,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACpC,IAAI,KAAK,KAAK,CAAC,CAAC;QAAE,OAAO,IAAI,CAAC;IAC9B,IAAI,OAAO,KAAK,CAAC,CAAC;QAAE,OAAO,IAAI,CAAC;IAChC,OAAO,OAAO,G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,CAAC,CAAC;AAAA,CAC3D","sourcesContent":["/**\n * Shared diff computation utilities for the edit and similar tools.\n */\n\nimport * as Diff from \"diff\";\nimport { constants } from \"fs\";\nimport { access, readFile } from \"fs/promises\";\nimport { resolveToCwd } from \"./path-utils.ts\";\n\nexport function detectLineEnding(content: string): \"\\r\\n\" | \"\\n\" {\n\tconst crlfIdx = content.indexOf(\"\\r\\n\");\n\tconst lfIdx = content.indexOf(\"\\n\");\n\tif (lfIdx === -1) return \"\\n\";\n\tif (crlfIdx === -1) return \"\\n\";\n\treturn crlfIdx < lfIdx ? \"\\r\\n\" : \"\\n\";\n}\n\nexport function normalizeToLF(text: string): string {\n\treturn text.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n}\n\nexport function restoreLineEndings(text: string, ending: \"\\r\\n\" | \"\\n\"): string {\n\treturn ending === \"\\r\\n\" ? text.replace(/\\n/g, \"\\r\\n\") : text;\n}\n\n/**\n * Normalize text for fuzzy matching. Applies progressive transformations:\n * - Strip trailing whitespace from each line\n * - Normalize smart quotes to ASCII equivalents\n * - Normalize Unicode dashes/hyphens to ASCII hyphen\n * - Normalize special Unicode spaces to regular space\n */\nexport function normalizeForFuzzyMatch(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.normalize(\"NFKC\")\n\t\t\t// Strip trailing whitespace per line\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trimEnd())\n\t\t\t.join(\"\\n\")\n\t\t\t// Smart single quotes → '\n\t\t\t.replace(/[\\u2018\\u2019\\u201A\\u201B]/g, \"'\")\n\t\t\t// Smart double quotes → \"\n\t\t\t.replace(/[\\u201C\\u201D\\u201E\\u201F]/g, '\"')\n\t\t\t// Various dashes/hyphens → -\n\t\t\t// U+2010 hyphen, U+2011 non-breaking hyphen, U+2012 figure dash,\n\t\t\t// U+2013 en-dash, U+2014 em-dash, U+2015 horizontal bar, U+2212 minus\n\t\t\t.replace(/[\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2212]/g, \"-\")\n\t\t\t// Special spaces → regular space\n\t\t\t// U+00A0 NBSP, U+2002-U+200A various spaces, U+202F narrow NBSP,\n\t\t\t// U+205F medium math space, U+3000 ideographic space\n\t\t\t.replace(/[\\u00A0\\u2002-\\u200A\\u202F\\u205F\\u3000]/g, \" \")\n\t);\n}\n\nfunction splitLinesWithEndings(content: string): string[] {\n\treturn content.match(/[^\\n]*\\n|[^\\n]+/g) ?? [];\n}\n\ninterface LineSpan {\n\tstart: number;\n\tend: number;\n}\n\ninterface MatchedEdit {\n\teditIndex: number;\n\tmatchIndex: number;\n\tmatchLength: number;\n\tnewText: string;\n}\n\ntype TextReplacement = Pick;\n\nfunction getLineSpans(content: string): LineSpan[] {\n\tlet offset = 0;\n\treturn splitLinesWithEndings(content).map((line) => {\n\t\tconst span = { start: offset, end: offset + line.length };\n\t\toffset = span.end;\n\t\treturn span;\n\t});\n}\n\nfunction getReplacementLineRange(lines: LineSpan[], replacement: TextReplacement) {\n\tconst replacementStart = replacement.matchIndex;\n\tconst replacementEnd = replacement.matchIndex + replacement.matchLength;\n\n\tlet startLine = -1;\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst line = lines[i];\n\t\tif (replacementStart >= line.start && replacementStart < line.end) {\n\t\t\tstartLine = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (startLine === -1) {\n\t\tthrow new Error(\"Replacement range is outside the base content.\");\n\t}\n\n\tlet endLine = startLine;\n\twhile (endLine < lines.length && lines[endLine].end < replacementEnd) {\n\t\tendLine++;\n\t}\n\tif (endLine >= lines.length) {\n\t\tthrow new Error(\"Replacement range is outside the base content.\");\n\t}\n\n\treturn { startLine, endLine: endLine + 1 };\n}\n\nfunction applyReplacements(content: string, replacements: TextReplacement[], offset = 0): string {\n\tlet result = content;\n\tfor (let i = replacements.length - 1; i >= 0; i--) {\n\t\tconst replacement = replacements[i];\n\t\tconst matchIndex = replacement.matchIndex - offset;\n\t\tresult =\n\t\t\tresult.substring(0, matchIndex) + replacement.newText + result.substring(matchIndex + replacement.matchLength);\n\t}\n\treturn result;\n}\n\n/**\n * Apply replacements matched against `baseContent` to `originalContent` while\n * preserving unchanged line blocks from the original.\n *\n * This is useful when `baseContent` is a normalized view of the original. Each\n * replacement is widened to the lines it actually touches, those touched lines\n * are rewritten from the normalized base, and all other lines are copied back\n * from `originalContent`. The actual replacement ranges drive preservation so\n * duplicate normalized lines cannot be aligned to the wrong occurrence.\n */\nexport function applyReplacementsPreservingUnchangedLines(\n\toriginalContent: string,\n\tbaseContent: string,\n\treplacements: TextReplacement[],\n): string {\n\tconst originalLines = splitLinesWithEndings(originalContent);\n\tconst baseLines = getLineSpans(baseContent);\n\tif (originalLines.length !== baseLines.length) {\n\t\tthrow new Error(\"Cannot preserve unchanged lines because the base content has a different line count.\");\n\t}\n\n\tconst groups: Array<{ startLine: number; endLine: number; replacements: TextReplacement[] }> = [];\n\tconst sortedReplacements = [...replacements].sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (const replacement of sortedReplacements) {\n\t\tconst range = getReplacementLineRange(baseLines, replacement);\n\t\tconst current = groups[groups.length - 1];\n\t\tif (current && range.startLine < current.endLine) {\n\t\t\tcurrent.endLine = Math.max(current.endLine, range.endLine);\n\t\t\tcurrent.replacements.push(replacement);\n\t\t\tcontinue;\n\t\t}\n\t\tgroups.push({ ...range, replacements: [replacement] });\n\t}\n\n\tlet originalLineIndex = 0;\n\tlet result = \"\";\n\tfor (const group of groups) {\n\t\tresult += originalLines.slice(originalLineIndex, group.startLine).join(\"\");\n\n\t\tconst groupStartOffset = baseLines[group.startLine].start;\n\t\tconst groupEndOffset = baseLines[group.endLine - 1].end;\n\t\tresult += applyReplacements(\n\t\t\tbaseContent.slice(groupStartOffset, groupEndOffset),\n\t\t\tgroup.replacements,\n\t\t\tgroupStartOffset,\n\t\t);\n\t\toriginalLineIndex = group.endLine;\n\t}\n\tresult += originalLines.slice(originalLineIndex).join(\"\");\n\n\treturn result;\n}\n\nexport interface FuzzyMatchResult {\n\t/** Whether a match was found */\n\tfound: boolean;\n\t/** The index where the match starts (in the content that should be used for replacement) */\n\tindex: number;\n\t/** Length of the matched text */\n\tmatchLength: number;\n\t/** Whether fuzzy matching was used (false = exact match) */\n\tusedFuzzyMatch: boolean;\n\t/**\n\t * The content to use for replacement operations.\n\t * When exact match: original content. When fuzzy match: normalized content.\n\t */\n\tcontentForReplacement: string;\n}\n\nexport interface Edit {\n\toldText: string;\n\tnewText: string;\n}\n\nexport interface AppliedEditsResult {\n\tbaseContent: string;\n\tnewContent: string;\n}\n\n/**\n * Find oldText in content, trying exact match first, then fuzzy match.\n * When fuzzy matching is used, the returned contentForReplacement is the\n * fuzzy-normalized version of the content (trailing whitespace stripped,\n * Unicode quotes/dashes normalized to ASCII).\n */\nexport function fuzzyFindText(content: string, oldText: string): FuzzyMatchResult {\n\t// Try exact match first\n\tconst exactIndex = content.indexOf(oldText);\n\tif (exactIndex !== -1) {\n\t\treturn {\n\t\t\tfound: true,\n\t\t\tindex: exactIndex,\n\t\t\tmatchLength: oldText.length,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// Try fuzzy match - work entirely in normalized space\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\tconst fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);\n\n\tif (fuzzyIndex === -1) {\n\t\treturn {\n\t\t\tfound: false,\n\t\t\tindex: -1,\n\t\t\tmatchLength: 0,\n\t\t\tusedFuzzyMatch: false,\n\t\t\tcontentForReplacement: content,\n\t\t};\n\t}\n\n\t// When fuzzy matching, return offsets in normalized space. Callers can use\n\t// the normalized content to compute replacements, then decide how much of\n\t// that normalized output should be written back.\n\treturn {\n\t\tfound: true,\n\t\tindex: fuzzyIndex,\n\t\tmatchLength: fuzzyOldText.length,\n\t\tusedFuzzyMatch: true,\n\t\tcontentForReplacement: fuzzyContent,\n\t};\n}\n\n/** Strip UTF-8 BOM if present, return both the BOM (if any) and the text without it */\nexport function stripBom(content: string): { bom: string; text: string } {\n\treturn content.startsWith(\"\\uFEFF\") ? { bom: \"\\uFEFF\", text: content.slice(1) } : { bom: \"\", text: content };\n}\n\nfunction countOccurrences(content: string, oldText: string): number {\n\tconst fuzzyContent = normalizeForFuzzyMatch(content);\n\tconst fuzzyOldText = normalizeForFuzzyMatch(oldText);\n\treturn fuzzyContent.split(fuzzyOldText).length - 1;\n}\n\nfunction getNotFoundError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`,\n\t);\n}\n\nfunction getDuplicateError(path: string, editIndex: number, totalEdits: number, occurrences: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t);\n\t}\n\treturn new Error(\n\t\t`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`,\n\t);\n}\n\nfunction getEmptyOldTextError(path: string, editIndex: number, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(`oldText must not be empty in ${path}.`);\n\t}\n\treturn new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`);\n}\n\nfunction getNoChangeError(path: string, totalEdits: number): Error {\n\tif (totalEdits === 1) {\n\t\treturn new Error(\n\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t);\n\t}\n\treturn new Error(`No changes made to ${path}. The replacements produced identical content.`);\n}\n\n/**\n * Apply one or more exact-text replacements to LF-normalized content.\n *\n * All edits are matched against the same original content. Replacements are\n * then applied in reverse order so offsets remain stable. If any edit needs\n * fuzzy matching, the operation runs in fuzzy-normalized content space and then\n * overlays those line-level changes onto the original content so unchanged line\n * blocks keep their original bytes.\n */\nexport function applyEditsToNormalizedContent(\n\tnormalizedContent: string,\n\tedits: Edit[],\n\tpath: string,\n): AppliedEditsResult {\n\tconst normalizedEdits = edits.map((edit) => ({\n\t\toldText: normalizeToLF(edit.oldText),\n\t\tnewText: normalizeToLF(edit.newText),\n\t}));\n\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tif (normalizedEdits[i].oldText.length === 0) {\n\t\t\tthrow getEmptyOldTextError(path, i, normalizedEdits.length);\n\t\t}\n\t}\n\n\tconst initialMatches = normalizedEdits.map((edit) => fuzzyFindText(normalizedContent, edit.oldText));\n\tconst usedFuzzyMatch = initialMatches.some((match) => match.usedFuzzyMatch);\n\tconst replacementBaseContent = usedFuzzyMatch ? normalizeForFuzzyMatch(normalizedContent) : normalizedContent;\n\n\tconst matchedEdits: MatchedEdit[] = [];\n\tfor (let i = 0; i < normalizedEdits.length; i++) {\n\t\tconst edit = normalizedEdits[i];\n\t\tconst matchResult = fuzzyFindText(replacementBaseContent, edit.oldText);\n\t\tif (!matchResult.found) {\n\t\t\tthrow getNotFoundError(path, i, normalizedEdits.length);\n\t\t}\n\n\t\tconst occurrences = countOccurrences(replacementBaseContent, edit.oldText);\n\t\tif (occurrences > 1) {\n\t\t\tthrow getDuplicateError(path, i, normalizedEdits.length, occurrences);\n\t\t}\n\n\t\tmatchedEdits.push({\n\t\t\teditIndex: i,\n\t\t\tmatchIndex: matchResult.index,\n\t\t\tmatchLength: matchResult.matchLength,\n\t\t\tnewText: edit.newText,\n\t\t});\n\t}\n\n\tmatchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);\n\tfor (let i = 1; i < matchedEdits.length; i++) {\n\t\tconst previous = matchedEdits[i - 1];\n\t\tconst current = matchedEdits[i];\n\t\tif (previous.matchIndex + previous.matchLength > current.matchIndex) {\n\t\t\tthrow new Error(\n\t\t\t\t`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst baseContent = normalizedContent;\n\tconst newContent = usedFuzzyMatch\n\t\t? applyReplacementsPreservingUnchangedLines(normalizedContent, replacementBaseContent, matchedEdits)\n\t\t: applyReplacements(replacementBaseContent, matchedEdits);\n\n\tif (baseContent === newContent) {\n\t\tthrow getNoChangeError(path, normalizedEdits.length);\n\t}\n\n\treturn { baseContent, newContent };\n}\n\n/** Generate a standard unified patch. */\nexport function generateUnifiedPatch(path: string, oldContent: string, newContent: string, contextLines = 4): string {\n\treturn Diff.createTwoFilesPatch(path, path, oldContent, newContent, undefined, undefined, {\n\t\tcontext: contextLines,\n\t\theaderOptions: Diff.FILE_HEADERS_ONLY,\n\t});\n}\n\n/**\n * Generate a display-oriented diff string with line numbers and context.\n * Returns both the diff string and the first changed line number (in the new file).\n */\nexport function generateDiffString(\n\toldContent: string,\n\tnewContent: string,\n\tcontextLines = 4,\n): { diff: string; firstChangedLine: number | undefined } {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\tlet firstChangedLine: number | undefined;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\t// Capture the first changed line (in the new file)\n\t\t\tif (firstChangedLine === undefined) {\n\t\t\t\tfirstChangedLine = newLineNum;\n\t\t\t}\n\n\t\t\t// Show the change\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\t// removed\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\t// Context lines - only show a few before/after changes\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\t\t\tconst hasLeadingChange = lastWasChange;\n\t\t\tconst hasTrailingChange = nextPartIsChange;\n\n\t\t\tif (hasLeadingChange && hasTrailingChange) {\n\t\t\t\tif (raw.length <= contextLines * 2) {\n\t\t\t\t\tfor (const line of raw) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tconst leadingLines = raw.slice(0, contextLines);\n\t\t\t\t\tconst trailingLines = raw.slice(raw.length - contextLines);\n\t\t\t\t\tconst skippedLines = raw.length - leadingLines.length - trailingLines.length;\n\n\t\t\t\t\tfor (const line of leadingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\n\t\t\t\t\tfor (const line of trailingLines) {\n\t\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\t\toldLineNum++;\n\t\t\t\t\t\tnewLineNum++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (hasLeadingChange) {\n\t\t\t\tconst shownLines = raw.slice(0, contextLines);\n\t\t\t\tconst skippedLines = raw.length - shownLines.length;\n\n\t\t\t\tfor (const line of shownLines) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\t\t\t} else if (hasTrailingChange) {\n\t\t\t\tconst skippedLines = Math.max(0, raw.length - contextLines);\n\t\t\t\tif (skippedLines > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t\toldLineNum += skippedLines;\n\t\t\t\t\tnewLineNum += skippedLines;\n\t\t\t\t}\n\n\t\t\t\tfor (const line of raw.slice(skippedLines)) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Skip these context lines entirely\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn { diff: output.join(\"\\n\"), firstChangedLine };\n}\n\nexport interface EditDiffResult {\n\tdiff: string;\n\tfirstChangedLine: number | undefined;\n}\n\nexport interface EditDiffError {\n\terror: string;\n}\n\n/**\n * Compute the diff for one or more edit operations without applying them.\n * Used for preview rendering in the TUI before the tool executes.\n */\nexport async function computeEditsDiff(\n\tpath: string,\n\tedits: Edit[],\n\tcwd: string,\n): Promise {\n\tconst absolutePath = resolveToCwd(path, cwd);\n\n\ttry {\n\t\t// Check if file exists and is readable\n\t\ttry {\n\t\t\tawait access(absolutePath, constants.R_OK);\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\treturn { error: `Could not edit file: ${path}. ${errorMessage}.` };\n\t\t}\n\n\t\t// Read the file\n\t\tconst rawContent = await readFile(absolutePath, \"utf-8\");\n\n\t\t// Strip BOM before matching (LLM won't include invisible BOM in oldText)\n\t\tconst { text: content } = stripBom(rawContent);\n\t\tconst normalizedContent = normalizeToLF(content);\n\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\n\t\t// Generate the diff\n\t\treturn generateDiffString(baseContent, newContent);\n\t} catch (err) {\n\t\treturn { error: err instanceof Error ? err.message : String(err) };\n\t}\n}\n\n/**\n * Compute the diff for a single edit operation without applying it.\n * Kept as a convenience wrapper for single-edit callers.\n */\nexport async function computeEditDiff(\n\tpath: string,\n\toldText: string,\n\tnewText: string,\n\tcwd: string,\n): Promise {\n\treturn computeEditsDiff(path, [{ oldText, newText }], cwd);\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/edit.d.ts b/dist/core/tools/edit.d.ts new file mode 100644 index 0000000..fa66ef9 --- /dev/null +++ b/dist/core/tools/edit.d.ts @@ -0,0 +1,51 @@ +import type { AgentTool } from "@earendil-works/pi-agent-core"; +import { Box } from "@earendil-works/pi-tui"; +import { type Static, Type } from "typebox"; +import type { ToolDefinition } from "../extensions/types.ts"; +import { type EditDiffError, type EditDiffResult } from "./edit-diff.ts"; +type EditPreview = EditDiffResult | EditDiffError; +type EditRenderState = { + callComponent?: EditCallRenderComponent; +}; +declare const editSchema: Type.TObject<{ + path: Type.TString; + edits: Type.TArray>; +}>; +export type EditToolInput = Static; +export interface EditToolDetails { + /** Display-oriented diff of the changes made */ + diff: string; + /** Standard unified patch of the changes made */ + patch: string; + /** Line number of the first change in the new file (for editor navigation) */ + firstChangedLine?: number; +} +/** + * Pluggable operations for the edit tool. + * Override these to delegate file editing to remote systems (for example SSH). + */ +export interface EditOperations { + /** Read file contents as a Buffer */ + readFile: (absolutePath: string) => Promise; + /** Write content to a file */ + writeFile: (absolutePath: string, content: string) => Promise; + /** Check if file is readable and writable (throw if not) */ + access: (absolutePath: string) => Promise; +} +export interface EditToolOptions { + /** Custom operations for file editing. Default: local filesystem */ + operations?: EditOperations; +} +type EditCallRenderComponent = Box & { + preview?: EditPreview; + previewArgsKey?: string; + previewPending?: boolean; + settledError?: boolean; +}; +export declare function createEditToolDefinition(cwd: string, options?: EditToolOptions): ToolDefinition; +export declare function createEditTool(cwd: string, options?: EditToolOptions): AgentTool; +export {}; +//# sourceMappingURL=edit.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/edit.d.ts.map b/dist/core/tools/edit.d.ts.map new file mode 100644 index 0000000..e75d910 --- /dev/null +++ b/dist/core/tools/edit.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../../src/core/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,GAAG,EAA2B,MAAM,wBAAwB,CAAC;AAGtE,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAKN,KAAK,aAAa,EAClB,KAAK,cAAc,EAMnB,MAAM,gBAAgB,CAAC;AAMxB,KAAK,WAAW,GAAG,cAAc,GAAG,aAAa,CA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AAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Box, Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, readFile as fsReadFile, writeFile as fsWriteFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { renderDiff } from \"../../modes/interactive/components/diff.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport {\n\tapplyEditsToNormalizedContent,\n\tcomputeEditsDiff,\n\tdetectLineEnding,\n\ttype Edit,\n\ttype EditDiffError,\n\ttype EditDiffResult,\n\tgenerateDiffString,\n\tgenerateUnifiedPatch,\n\tnormalizeToLF,\n\trestoreLineEndings,\n\tstripBom,\n} from \"./edit-diff.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { renderToolPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\ntype EditPreview = EditDiffResult | EditDiffError;\n\ntype EditRenderState = {\n\tcallComponent?: EditCallRenderComponent;\n};\n\nconst replaceEditSchema = Type.Object(\n\t{\n\t\toldText: Type.String({\n\t\t\tdescription:\n\t\t\t\t\"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.\",\n\t\t}),\n\t\tnewText: Type.String({ description: \"Replacement text for this targeted edit.\" }),\n\t},\n\t{},\n);\n\nconst editSchema = Type.Object(\n\t{\n\t\tpath: Type.String({ description: \"Path to the file to edit (relative or absolute)\" }),\n\t\tedits: Type.Array(replaceEditSchema, {\n\t\t\tdescription:\n\t\t\t\t\"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.\",\n\t\t}),\n\t},\n\t{},\n);\n\nexport type EditToolInput = Static;\ntype LegacyEditToolInput = EditToolInput & {\n\toldText?: unknown;\n\tnewText?: unknown;\n};\n\nexport interface EditToolDetails {\n\t/** Display-oriented diff of the changes made */\n\tdiff: string;\n\t/** Standard unified patch of the changes made */\n\tpatch: string;\n\t/** Line number of the first change in the new file (for editor navigation) */\n\tfirstChangedLine?: number;\n}\n\n/**\n * Pluggable operations for the edit tool.\n * Override these to delegate file editing to remote systems (for example SSH).\n */\nexport interface EditOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise;\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise;\n\t/** Check if file is readable and writable (throw if not) */\n\taccess: (absolutePath: string) => Promise;\n}\n\nconst defaultEditOperations: EditOperations = {\n\treadFile: (path) => fsReadFile(path),\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\taccess: (path) => fsAccess(path, constants.R_OK | constants.W_OK),\n};\n\nexport interface EditToolOptions {\n\t/** Custom operations for file editing. Default: local filesystem */\n\toperations?: EditOperations;\n}\n\nfunction prepareEditArguments(input: unknown): EditToolInput {\n\tif (!input || typeof input !== \"object\") {\n\t\treturn input as EditToolInput;\n\t}\n\n\tconst args = input as Record;\n\n\t// Some models (Opus 4.6, GLM-5.1) send edits as a JSON string instead of an array\n\tif (typeof args.edits === \"string\") {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(args.edits);\n\t\t\tif (Array.isArray(parsed)) args.edits = parsed;\n\t\t} catch {}\n\t}\n\n\tconst legacy = args as LegacyEditToolInput;\n\tif (typeof legacy.oldText !== \"string\" || typeof legacy.newText !== \"string\") {\n\t\treturn args as EditToolInput;\n\t}\n\n\tconst edits = Array.isArray(legacy.edits) ? [...legacy.edits] : [];\n\tedits.push({ oldText: legacy.oldText, newText: legacy.newText });\n\tconst { oldText: _oldText, newText: _newText, ...rest } = legacy;\n\treturn { ...rest, edits } as EditToolInput;\n}\n\nfunction validateEditInput(input: EditToolInput): { path: string; edits: Edit[] } {\n\tif (!Array.isArray(input.edits) || input.edits.length === 0) {\n\t\tthrow new Error(\"Edit tool input is invalid. edits must contain at least one replacement.\");\n\t}\n\treturn { path: input.path, edits: input.edits };\n}\n\ntype RenderableEditArgs = {\n\tpath?: string;\n\tfile_path?: string;\n\tedits?: Edit[];\n\toldText?: string;\n\tnewText?: string;\n};\n\ntype EditToolResultLike = {\n\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\tdetails?: EditToolDetails;\n};\n\ntype EditCallRenderComponent = Box & {\n\tpreview?: EditPreview;\n\tpreviewArgsKey?: string;\n\tpreviewPending?: boolean;\n\tsettledError?: boolean;\n};\n\nfunction createEditCallRenderComponent(): EditCallRenderComponent {\n\treturn Object.assign(new Box(1, 1, (text: string) => text), {\n\t\tpreview: undefined as EditPreview | undefined,\n\t\tpreviewArgsKey: undefined as string | undefined,\n\t\tpreviewPending: false,\n\t\tsettledError: false,\n\t});\n}\n\nfunction getEditCallRenderComponent(state: EditRenderState, lastComponent: unknown): EditCallRenderComponent {\n\tif (lastComponent instanceof Box) {\n\t\tconst component = lastComponent as EditCallRenderComponent;\n\t\tstate.callComponent = component;\n\t\treturn component;\n\t}\n\tif (state.callComponent) {\n\t\treturn state.callComponent;\n\t}\n\tconst component = createEditCallRenderComponent();\n\tstate.callComponent = component;\n\treturn component;\n}\n\nfunction getRenderablePreviewInput(args: RenderableEditArgs | undefined): { path: string; edits: Edit[] } | null {\n\tif (!args) {\n\t\treturn null;\n\t}\n\n\tconst path = typeof args.path === \"string\" ? args.path : typeof args.file_path === \"string\" ? args.file_path : null;\n\tif (!path) {\n\t\treturn null;\n\t}\n\n\tif (\n\t\tArray.isArray(args.edits) &&\n\t\targs.edits.length > 0 &&\n\t\targs.edits.every((edit) => typeof edit?.oldText === \"string\" && typeof edit?.newText === \"string\")\n\t) {\n\t\treturn { path, edits: args.edits };\n\t}\n\n\tif (typeof args.oldText === \"string\" && typeof args.newText === \"string\") {\n\t\treturn { path, edits: [{ oldText: args.oldText, newText: args.newText }] };\n\t}\n\n\treturn null;\n}\n\nfunction formatEditCall(args: RenderableEditArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"edit\"))} ${pathDisplay}`;\n}\n\nfunction formatEditResult(\n\targs: RenderableEditArgs | undefined,\n\tpreview: EditPreview | undefined,\n\tresult: EditToolResultLike,\n\ttheme: Theme,\n\tisError: boolean,\n): string | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst previewDiff = preview && !(\"error\" in preview) ? preview.diff : undefined;\n\tconst previewError = preview && \"error\" in preview ? preview.error : undefined;\n\tif (isError) {\n\t\tconst errorText = result.content\n\t\t\t.filter((c) => c.type === \"text\")\n\t\t\t.map((c) => c.text || \"\")\n\t\t\t.join(\"\\n\");\n\t\tif (!errorText || errorText === previewError) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn theme.fg(\"error\", errorText);\n\t}\n\n\tconst resultDiff = result.details?.diff;\n\tif (resultDiff && resultDiff !== previewDiff) {\n\t\treturn renderDiff(resultDiff, { filePath: rawPath ?? undefined });\n\t}\n\n\treturn undefined;\n}\n\nfunction getEditHeaderBg(\n\tpreview: EditPreview | undefined,\n\tsettledError: boolean | undefined,\n\ttheme: Theme,\n): (text: string) => string {\n\tif (preview) {\n\t\tif (\"error\" in preview) {\n\t\t\treturn (text: string) => theme.bg(\"toolErrorBg\", text);\n\t\t}\n\t\treturn (text: string) => theme.bg(\"toolSuccessBg\", text);\n\t}\n\tif (settledError) {\n\t\treturn (text: string) => theme.bg(\"toolErrorBg\", text);\n\t}\n\treturn (text: string) => theme.bg(\"toolPendingBg\", text);\n}\n\nfunction buildEditCallComponent(\n\tcomponent: EditCallRenderComponent,\n\targs: RenderableEditArgs | undefined,\n\ttheme: Theme,\n\tcwd: string,\n): EditCallRenderComponent {\n\tcomponent.setBgFn(getEditHeaderBg(component.preview, component.settledError, theme));\n\tcomponent.clear();\n\tcomponent.addChild(new Text(formatEditCall(args, theme, cwd), 0, 0));\n\n\tif (!component.preview) {\n\t\treturn component;\n\t}\n\n\tconst body =\n\t\t\"error\" in component.preview ? theme.fg(\"error\", component.preview.error) : renderDiff(component.preview.diff);\n\tcomponent.addChild(new Spacer(1));\n\tcomponent.addChild(new Text(body, 0, 0));\n\treturn component;\n}\n\nfunction setEditPreview(\n\tcomponent: EditCallRenderComponent,\n\tpreview: EditPreview,\n\targsKey: string | undefined,\n): boolean {\n\tconst current = component.preview;\n\tconst changed =\n\t\tcurrent === undefined ||\n\t\t(\"error\" in current && \"error\" in preview\n\t\t\t? current.error !== preview.error\n\t\t\t: \"error\" in current !== \"error\" in preview) ||\n\t\t(!(\"error\" in current) &&\n\t\t\t!(\"error\" in preview) &&\n\t\t\t(current.diff !== preview.diff || current.firstChangedLine !== preview.firstChangedLine));\n\tcomponent.preview = preview;\n\tcomponent.previewArgsKey = argsKey;\n\tcomponent.previewPending = false;\n\treturn changed;\n}\n\nexport function createEditToolDefinition(\n\tcwd: string,\n\toptions?: EditToolOptions,\n): ToolDefinition {\n\tconst ops = options?.operations ?? defaultEditOperations;\n\treturn {\n\t\tname: \"edit\",\n\t\tlabel: \"edit\",\n\t\tdescription:\n\t\t\t\"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.\",\n\t\tpromptSnippet:\n\t\t\t\"Make precise file edits with exact text replacement, including multiple disjoint edits in one call\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use edit for precise changes (edits[].oldText must match exactly)\",\n\t\t\t\"When changing multiple separate locations in one file, use one edit call with multiple entries in edits[] instead of multiple edit calls\",\n\t\t\t\"Each edits[].oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits. Merge nearby changes into one edit.\",\n\t\t\t\"Keep edits[].oldText as small as possible while still being unique in the file. Do not pad with large unchanged regions.\",\n\t\t],\n\t\tparameters: editSchema,\n\t\trenderShell: \"self\",\n\t\tprepareArguments: prepareEditArguments,\n\t\tasync execute(_toolCallId, input: EditToolInput, signal?: AbortSignal, _onUpdate?, _ctx?) {\n\t\t\tconst { path, edits } = validateEditInput(input);\n\t\t\tconst absolutePath = resolveToCwd(path, cwd);\n\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Check if file exists.\n\t\t\t\ttry {\n\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tthrowIfAborted();\n\t\t\t\t\tconst errorMessage =\n\t\t\t\t\t\terror instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\t\t\tthrow new Error(`Could not edit file: ${path}. ${errorMessage}.`);\n\t\t\t\t}\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Read the file.\n\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\tconst rawContent = buffer.toString(\"utf-8\");\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Strip BOM before matching. The model will not include an invisible BOM in oldText.\n\t\t\t\tconst { bom, text: content } = stripBom(rawContent);\n\t\t\t\tconst originalEnding = detectLineEnding(content);\n\t\t\t\tconst normalizedContent = normalizeToLF(content);\n\t\t\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\tconst finalContent = bom + restoreLineEndings(newContent, originalEnding);\n\t\t\t\tawait ops.writeFile(absolutePath, finalContent);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\tconst diffResult = generateDiffString(baseContent, newContent);\n\t\t\t\tconst patch = generateUnifiedPatch(path, baseContent, newContent);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Successfully replaced ${edits.length} block(s) in ${path}.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { diff: diffResult.diff, patch, firstChangedLine: diffResult.firstChangedLine },\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst component = getEditCallRenderComponent(context.state, context.lastComponent);\n\t\t\tconst previewInput = getRenderablePreviewInput(args as RenderableEditArgs | undefined);\n\t\t\tconst argsKey = previewInput\n\t\t\t\t? JSON.stringify({ path: previewInput.path, edits: previewInput.edits })\n\t\t\t\t: undefined;\n\n\t\t\tif (component.previewArgsKey !== argsKey) {\n\t\t\t\tcomponent.preview = undefined;\n\t\t\t\tcomponent.previewArgsKey = argsKey;\n\t\t\t\tcomponent.previewPending = false;\n\t\t\t\tcomponent.settledError = false;\n\t\t\t}\n\n\t\t\tif (context.argsComplete && previewInput && !component.preview && !component.previewPending) {\n\t\t\t\tcomponent.previewPending = true;\n\t\t\t\tconst requestKey = argsKey;\n\t\t\t\tvoid computeEditsDiff(previewInput.path, previewInput.edits, context.cwd).then((preview) => {\n\t\t\t\t\tif (component.previewArgsKey === requestKey) {\n\t\t\t\t\t\tsetEditPreview(component, preview, requestKey);\n\t\t\t\t\t\tcontext.invalidate();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn buildEditCallComponent(component, args, theme, context.cwd);\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst callComponent = context.state.callComponent;\n\t\t\tconst previewInput = getRenderablePreviewInput(context.args as RenderableEditArgs | undefined);\n\t\t\tconst argsKey = previewInput\n\t\t\t\t? JSON.stringify({ path: previewInput.path, edits: previewInput.edits })\n\t\t\t\t: undefined;\n\t\t\tconst typedResult = result as EditToolResultLike;\n\t\t\tconst resultDiff = !context.isError ? typedResult.details?.diff : undefined;\n\t\t\tlet changed = false;\n\t\t\tif (callComponent) {\n\t\t\t\tif (typeof resultDiff === \"string\") {\n\t\t\t\t\tchanged =\n\t\t\t\t\t\tsetEditPreview(\n\t\t\t\t\t\t\tcallComponent,\n\t\t\t\t\t\t\t{ diff: resultDiff, firstChangedLine: typedResult.details?.firstChangedLine },\n\t\t\t\t\t\t\targsKey,\n\t\t\t\t\t\t) || changed;\n\t\t\t\t}\n\t\t\t\tif (callComponent.settledError !== context.isError) {\n\t\t\t\t\tcallComponent.settledError = context.isError;\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t\tif (changed) {\n\t\t\t\t\tbuildEditCallComponent(\n\t\t\t\t\t\tcallComponent,\n\t\t\t\t\t\tcontext.args as RenderableEditArgs | undefined,\n\t\t\t\t\t\ttheme,\n\t\t\t\t\t\tcontext.cwd,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst output = formatEditResult(context.args, callComponent?.preview, typedResult, theme, context.isError);\n\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcomponent.clear();\n\t\t\tif (!output) {\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tcomponent.addChild(new Text(output, 1, 0));\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createEditTool(cwd: string, options?: EditToolOptions): AgentTool {\n\treturn wrapToolDefinition(createEditToolDefinition(cwd, options));\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/edit.js b/dist/core/tools/edit.js new file mode 100644 index 0000000..1940549 --- /dev/null +++ b/dist/core/tools/edit.js @@ -0,0 +1,284 @@ +import { Box, Container, Spacer, Text } from "@earendil-works/pi-tui"; +import { constants } from "fs"; +import { access as fsAccess, readFile as fsReadFile, writeFile as fsWriteFile } from "fs/promises"; +import { Type } from "typebox"; +import { renderDiff } from "../../modes/interactive/components/diff.js"; +import { applyEditsToNormalizedContent, computeEditsDiff, detectLineEnding, generateDiffString, generateUnifiedPatch, normalizeToLF, restoreLineEndings, stripBom, } from "./edit-diff.js"; +import { withFileMutationQueue } from "./file-mutation-queue.js"; +import { resolveToCwd } from "./path-utils.js"; +import { renderToolPath, str } from "./render-utils.js"; +import { wrapToolDefinition } from "./tool-definition-wrapper.js"; +const replaceEditSchema = Type.Object({ + oldText: Type.String({ + description: "Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.", + }), + newText: Type.String({ description: "Replacement text for this targeted edit." }), +}, {}); +const editSchema = Type.Object({ + path: Type.String({ description: "Path to the file to edit (relative or absolute)" }), + edits: Type.Array(replaceEditSchema, { + description: "One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.", + }), +}, {}); +const defaultEditOperations = { + readFile: (path) => fsReadFile(path), + writeFile: (path, content) => fsWriteFile(path, content, "utf-8"), + access: (path) => fsAccess(path, constants.R_OK | constants.W_OK), +}; +function prepareEditArguments(input) { + if (!input || typeof input !== "object") { + return input; + } + const args = input; + // Some models (Opus 4.6, GLM-5.1) send edits as a JSON string instead of an array + if (typeof args.edits === "string") { + try { + const parsed = JSON.parse(args.edits); + if (Array.isArray(parsed)) + args.edits = parsed; + } + catch { } + } + const legacy = args; + if (typeof legacy.oldText !== "string" || typeof legacy.newText !== "string") { + return args; + } + const edits = Array.isArray(legacy.edits) ? [...legacy.edits] : []; + edits.push({ oldText: legacy.oldText, newText: legacy.newText }); + const { oldText: _oldText, newText: _newText, ...rest } = legacy; + return { ...rest, edits }; +} +function validateEditInput(input) { + if (!Array.isArray(input.edits) || input.edits.length === 0) { + throw new Error("Edit tool input is invalid. edits must contain at least one replacement."); + } + return { path: input.path, edits: input.edits }; +} +function createEditCallRenderComponent() { + return Object.assign(new Box(1, 1, (text) => text), { + preview: undefined, + previewArgsKey: undefined, + previewPending: false, + settledError: false, + }); +} +function getEditCallRenderComponent(state, lastComponent) { + if (lastComponent instanceof Box) { + const component = lastComponent; + state.callComponent = component; + return component; + } + if (state.callComponent) { + return state.callComponent; + } + const component = createEditCallRenderComponent(); + state.callComponent = component; + return component; +} +function getRenderablePreviewInput(args) { + if (!args) { + return null; + } + const path = typeof args.path === "string" ? args.path : typeof args.file_path === "string" ? args.file_path : null; + if (!path) { + return null; + } + if (Array.isArray(args.edits) && + args.edits.length > 0 && + args.edits.every((edit) => typeof edit?.oldText === "string" && typeof edit?.newText === "string")) { + return { path, edits: args.edits }; + } + if (typeof args.oldText === "string" && typeof args.newText === "string") { + return { path, edits: [{ oldText: args.oldText, newText: args.newText }] }; + } + return null; +} +function formatEditCall(args, theme, cwd) { + const pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd); + return `${theme.fg("toolTitle", theme.bold("edit"))} ${pathDisplay}`; +} +function formatEditResult(args, preview, result, theme, isError) { + const rawPath = str(args?.file_path ?? args?.path); + const previewDiff = preview && !("error" in preview) ? preview.diff : undefined; + const previewError = preview && "error" in preview ? preview.error : undefined; + if (isError) { + const errorText = result.content + .filter((c) => c.type === "text") + .map((c) => c.text || "") + .join("\n"); + if (!errorText || errorText === previewError) { + return undefined; + } + return theme.fg("error", errorText); + } + const resultDiff = result.details?.diff; + if (resultDiff && resultDiff !== previewDiff) { + return renderDiff(resultDiff, { filePath: rawPath ?? undefined }); + } + return undefined; +} +function getEditHeaderBg(preview, settledError, theme) { + if (preview) { + if ("error" in preview) { + return (text) => theme.bg("toolErrorBg", text); + } + return (text) => theme.bg("toolSuccessBg", text); + } + if (settledError) { + return (text) => theme.bg("toolErrorBg", text); + } + return (text) => theme.bg("toolPendingBg", text); +} +function buildEditCallComponent(component, args, theme, cwd) { + component.setBgFn(getEditHeaderBg(component.preview, component.settledError, theme)); + component.clear(); + component.addChild(new Text(formatEditCall(args, theme, cwd), 0, 0)); + if (!component.preview) { + return component; + } + const body = "error" in component.preview ? theme.fg("error", component.preview.error) : renderDiff(component.preview.diff); + component.addChild(new Spacer(1)); + component.addChild(new Text(body, 0, 0)); + return component; +} +function setEditPreview(component, preview, argsKey) { + const current = component.preview; + const changed = current === undefined || + ("error" in current && "error" in preview + ? current.error !== preview.error + : "error" in current !== "error" in preview) || + (!("error" in current) && + !("error" in preview) && + (current.diff !== preview.diff || current.firstChangedLine !== preview.firstChangedLine)); + component.preview = preview; + component.previewArgsKey = argsKey; + component.previewPending = false; + return changed; +} +export function createEditToolDefinition(cwd, options) { + const ops = options?.operations ?? defaultEditOperations; + return { + name: "edit", + label: "edit", + description: "Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.", + promptSnippet: "Make precise file edits with exact text replacement, including multiple disjoint edits in one call", + promptGuidelines: [ + "Use edit for precise changes (edits[].oldText must match exactly)", + "When changing multiple separate locations in one file, use one edit call with multiple entries in edits[] instead of multiple edit calls", + "Each edits[].oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits. Merge nearby changes into one edit.", + "Keep edits[].oldText as small as possible while still being unique in the file. Do not pad with large unchanged regions.", + ], + parameters: editSchema, + renderShell: "self", + prepareArguments: prepareEditArguments, + async execute(_toolCallId, input, signal, _onUpdate, _ctx) { + const { path, edits } = validateEditInput(input); + const absolutePath = resolveToCwd(path, cwd); + return withFileMutationQueue(absolutePath, async () => { + // Do not reject from an abort event listener here: that would release the + // mutation queue while an in-flight filesystem operation may still finish. + // Checking signal.aborted after each await observes the same aborts while + // keeping the queue locked until the current operation has settled. + const throwIfAborted = () => { + if (signal?.aborted) + throw new Error("Operation aborted"); + }; + throwIfAborted(); + // Check if file exists. + try { + await ops.access(absolutePath); + } + catch (error) { + throwIfAborted(); + const errorMessage = error instanceof Error && "code" in error ? `Error code: ${error.code}` : String(error); + throw new Error(`Could not edit file: ${path}. ${errorMessage}.`); + } + throwIfAborted(); + // Read the file. + const buffer = await ops.readFile(absolutePath); + const rawContent = buffer.toString("utf-8"); + throwIfAborted(); + // Strip BOM before matching. The model will not include an invisible BOM in oldText. + const { bom, text: content } = stripBom(rawContent); + const originalEnding = detectLineEnding(content); + const normalizedContent = normalizeToLF(content); + const { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path); + throwIfAborted(); + const finalContent = bom + restoreLineEndings(newContent, originalEnding); + await ops.writeFile(absolutePath, finalContent); + throwIfAborted(); + const diffResult = generateDiffString(baseContent, newContent); + const patch = generateUnifiedPatch(path, baseContent, newContent); + return { + content: [ + { + type: "text", + text: `Successfully replaced ${edits.length} block(s) in ${path}.`, + }, + ], + details: { diff: diffResult.diff, patch, firstChangedLine: diffResult.firstChangedLine }, + }; + }); + }, + renderCall(args, theme, context) { + const component = getEditCallRenderComponent(context.state, context.lastComponent); + const previewInput = getRenderablePreviewInput(args); + const argsKey = previewInput + ? JSON.stringify({ path: previewInput.path, edits: previewInput.edits }) + : undefined; + if (component.previewArgsKey !== argsKey) { + component.preview = undefined; + component.previewArgsKey = argsKey; + component.previewPending = false; + component.settledError = false; + } + if (context.argsComplete && previewInput && !component.preview && !component.previewPending) { + component.previewPending = true; + const requestKey = argsKey; + void computeEditsDiff(previewInput.path, previewInput.edits, context.cwd).then((preview) => { + if (component.previewArgsKey === requestKey) { + setEditPreview(component, preview, requestKey); + context.invalidate(); + } + }); + } + return buildEditCallComponent(component, args, theme, context.cwd); + }, + renderResult(result, _options, theme, context) { + const callComponent = context.state.callComponent; + const previewInput = getRenderablePreviewInput(context.args); + const argsKey = previewInput + ? JSON.stringify({ path: previewInput.path, edits: previewInput.edits }) + : undefined; + const typedResult = result; + const resultDiff = !context.isError ? typedResult.details?.diff : undefined; + let changed = false; + if (callComponent) { + if (typeof resultDiff === "string") { + changed = + setEditPreview(callComponent, { diff: resultDiff, firstChangedLine: typedResult.details?.firstChangedLine }, argsKey) || changed; + } + if (callComponent.settledError !== context.isError) { + callComponent.settledError = context.isError; + changed = true; + } + if (changed) { + buildEditCallComponent(callComponent, context.args, theme, context.cwd); + } + } + const output = formatEditResult(context.args, callComponent?.preview, typedResult, theme, context.isError); + const component = context.lastComponent ?? new Container(); + component.clear(); + if (!output) { + return component; + } + component.addChild(new Spacer(1)); + component.addChild(new Text(output, 1, 0)); + return component; + }, + }; +} +export function createEditTool(cwd, options) { + return wrapToolDefinition(createEditToolDefinition(cwd, options)); +} +//# sourceMappingURL=edit.js.map \ No newline at end of file diff --git a/dist/core/tools/edit.js.map b/dist/core/tools/edit.js.map new file mode 100644 index 0000000..261ca01 --- /dev/null +++ b/dist/core/tools/edit.js.map @@ -0,0 +1 @@ +{"version":3,"file":"edit.js","sourceRoot":"","sources":["../../../src/core/tools/edit.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,QAAQ,IAAI,UAAU,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,aAAa,CAAC;AACnG,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,4CAA4C,CAAC;AAGxE,OAAO,EACN,6BAA6B,EAC7B,gBAAgB,EAChB,gBAAgB,EAIhB,kBAAkB,EAClB,oBAAoB,EACpB,aAAa,EACb,kBAAkB,EAClB,QAAQ,GACR,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,mBAAm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b,EAAE,IAAI,EAAE,UAAU,EAAE,gBAAgB,EAAE,WAAW,CAAC,OAAO,EAAE,gBAAgB,EAAE,EAC7E,OAAO,CACP,IAAI,OAAO,CAAC;gBACf,CAAC;gBACD,IAAI,aAAa,CAAC,YAAY,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC;oBACpD,aAAa,CAAC,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC;oBAC7C,OAAO,GAAG,IAAI,CAAC;gBAChB,CAAC;gBACD,IAAI,OAAO,EAAE,CAAC;oBACb,sBAAsB,CACrB,aAAa,EACb,OAAO,CAAC,IAAsC,EAC9C,KAAK,EACL,OAAO,CAAC,GAAG,CACX,CAAC;gBACH,CAAC;YACF,CAAC;YAED,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;YAC3G,MAAM,SAAS,GAAI,OAAO,CAAC,aAAuC,IAAI,IAAI,SAAS,EAAE,CAAC;YACtF,SAAS,CAAC,KAAK,EAAE,CAAC;YAClB,IAAI,CAAC,MAAM,EAAE,CAAC;gBACb,OAAO,SAAS,CAAC;YAClB,CAAC;YACD,SAAS,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAClC,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC3C,OAAO,SAAS,CAAC;QAAA,CACjB;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB,EAAgC;IACpG,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAClE","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Box, Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, readFile as fsReadFile, writeFile as fsWriteFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { renderDiff } from \"../../modes/interactive/components/diff.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport {\n\tapplyEditsToNormalizedContent,\n\tcomputeEditsDiff,\n\tdetectLineEnding,\n\ttype Edit,\n\ttype EditDiffError,\n\ttype EditDiffResult,\n\tgenerateDiffString,\n\tgenerateUnifiedPatch,\n\tnormalizeToLF,\n\trestoreLineEndings,\n\tstripBom,\n} from \"./edit-diff.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { renderToolPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\ntype EditPreview = EditDiffResult | EditDiffError;\n\ntype EditRenderState = {\n\tcallComponent?: EditCallRenderComponent;\n};\n\nconst replaceEditSchema = Type.Object(\n\t{\n\t\toldText: Type.String({\n\t\t\tdescription:\n\t\t\t\t\"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.\",\n\t\t}),\n\t\tnewText: Type.String({ description: \"Replacement text for this targeted edit.\" }),\n\t},\n\t{},\n);\n\nconst editSchema = Type.Object(\n\t{\n\t\tpath: Type.String({ description: \"Path to the file to edit (relative or absolute)\" }),\n\t\tedits: Type.Array(replaceEditSchema, {\n\t\t\tdescription:\n\t\t\t\t\"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.\",\n\t\t}),\n\t},\n\t{},\n);\n\nexport type EditToolInput = Static;\ntype LegacyEditToolInput = EditToolInput & {\n\toldText?: unknown;\n\tnewText?: unknown;\n};\n\nexport interface EditToolDetails {\n\t/** Display-oriented diff of the changes made */\n\tdiff: string;\n\t/** Standard unified patch of the changes made */\n\tpatch: string;\n\t/** Line number of the first change in the new file (for editor navigation) */\n\tfirstChangedLine?: number;\n}\n\n/**\n * Pluggable operations for the edit tool.\n * Override these to delegate file editing to remote systems (for example SSH).\n */\nexport interface EditOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise;\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise;\n\t/** Check if file is readable and writable (throw if not) */\n\taccess: (absolutePath: string) => Promise;\n}\n\nconst defaultEditOperations: EditOperations = {\n\treadFile: (path) => fsReadFile(path),\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\taccess: (path) => fsAccess(path, constants.R_OK | constants.W_OK),\n};\n\nexport interface EditToolOptions {\n\t/** Custom operations for file editing. Default: local filesystem */\n\toperations?: EditOperations;\n}\n\nfunction prepareEditArguments(input: unknown): EditToolInput {\n\tif (!input || typeof input !== \"object\") {\n\t\treturn input as EditToolInput;\n\t}\n\n\tconst args = input as Record;\n\n\t// Some models (Opus 4.6, GLM-5.1) send edits as a JSON string instead of an array\n\tif (typeof args.edits === \"string\") {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(args.edits);\n\t\t\tif (Array.isArray(parsed)) args.edits = parsed;\n\t\t} catch {}\n\t}\n\n\tconst legacy = args as LegacyEditToolInput;\n\tif (typeof legacy.oldText !== \"string\" || typeof legacy.newText !== \"string\") {\n\t\treturn args as EditToolInput;\n\t}\n\n\tconst edits = Array.isArray(legacy.edits) ? [...legacy.edits] : [];\n\tedits.push({ oldText: legacy.oldText, newText: legacy.newText });\n\tconst { oldText: _oldText, newText: _newText, ...rest } = legacy;\n\treturn { ...rest, edits } as EditToolInput;\n}\n\nfunction validateEditInput(input: EditToolInput): { path: string; edits: Edit[] } {\n\tif (!Array.isArray(input.edits) || input.edits.length === 0) {\n\t\tthrow new Error(\"Edit tool input is invalid. edits must contain at least one replacement.\");\n\t}\n\treturn { path: input.path, edits: input.edits };\n}\n\ntype RenderableEditArgs = {\n\tpath?: string;\n\tfile_path?: string;\n\tedits?: Edit[];\n\toldText?: string;\n\tnewText?: string;\n};\n\ntype EditToolResultLike = {\n\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\tdetails?: EditToolDetails;\n};\n\ntype EditCallRenderComponent = Box & {\n\tpreview?: EditPreview;\n\tpreviewArgsKey?: string;\n\tpreviewPending?: boolean;\n\tsettledError?: boolean;\n};\n\nfunction createEditCallRenderComponent(): EditCallRenderComponent {\n\treturn Object.assign(new Box(1, 1, (text: string) => text), {\n\t\tpreview: undefined as EditPreview | undefined,\n\t\tpreviewArgsKey: undefined as string | undefined,\n\t\tpreviewPending: false,\n\t\tsettledError: false,\n\t});\n}\n\nfunction getEditCallRenderComponent(state: EditRenderState, lastComponent: unknown): EditCallRenderComponent {\n\tif (lastComponent instanceof Box) {\n\t\tconst component = lastComponent as EditCallRenderComponent;\n\t\tstate.callComponent = component;\n\t\treturn component;\n\t}\n\tif (state.callComponent) {\n\t\treturn state.callComponent;\n\t}\n\tconst component = createEditCallRenderComponent();\n\tstate.callComponent = component;\n\treturn component;\n}\n\nfunction getRenderablePreviewInput(args: RenderableEditArgs | undefined): { path: string; edits: Edit[] } | null {\n\tif (!args) {\n\t\treturn null;\n\t}\n\n\tconst path = typeof args.path === \"string\" ? args.path : typeof args.file_path === \"string\" ? args.file_path : null;\n\tif (!path) {\n\t\treturn null;\n\t}\n\n\tif (\n\t\tArray.isArray(args.edits) &&\n\t\targs.edits.length > 0 &&\n\t\targs.edits.every((edit) => typeof edit?.oldText === \"string\" && typeof edit?.newText === \"string\")\n\t) {\n\t\treturn { path, edits: args.edits };\n\t}\n\n\tif (typeof args.oldText === \"string\" && typeof args.newText === \"string\") {\n\t\treturn { path, edits: [{ oldText: args.oldText, newText: args.newText }] };\n\t}\n\n\treturn null;\n}\n\nfunction formatEditCall(args: RenderableEditArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"edit\"))} ${pathDisplay}`;\n}\n\nfunction formatEditResult(\n\targs: RenderableEditArgs | undefined,\n\tpreview: EditPreview | undefined,\n\tresult: EditToolResultLike,\n\ttheme: Theme,\n\tisError: boolean,\n): string | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst previewDiff = preview && !(\"error\" in preview) ? preview.diff : undefined;\n\tconst previewError = preview && \"error\" in preview ? preview.error : undefined;\n\tif (isError) {\n\t\tconst errorText = result.content\n\t\t\t.filter((c) => c.type === \"text\")\n\t\t\t.map((c) => c.text || \"\")\n\t\t\t.join(\"\\n\");\n\t\tif (!errorText || errorText === previewError) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn theme.fg(\"error\", errorText);\n\t}\n\n\tconst resultDiff = result.details?.diff;\n\tif (resultDiff && resultDiff !== previewDiff) {\n\t\treturn renderDiff(resultDiff, { filePath: rawPath ?? undefined });\n\t}\n\n\treturn undefined;\n}\n\nfunction getEditHeaderBg(\n\tpreview: EditPreview | undefined,\n\tsettledError: boolean | undefined,\n\ttheme: Theme,\n): (text: string) => string {\n\tif (preview) {\n\t\tif (\"error\" in preview) {\n\t\t\treturn (text: string) => theme.bg(\"toolErrorBg\", text);\n\t\t}\n\t\treturn (text: string) => theme.bg(\"toolSuccessBg\", text);\n\t}\n\tif (settledError) {\n\t\treturn (text: string) => theme.bg(\"toolErrorBg\", text);\n\t}\n\treturn (text: string) => theme.bg(\"toolPendingBg\", text);\n}\n\nfunction buildEditCallComponent(\n\tcomponent: EditCallRenderComponent,\n\targs: RenderableEditArgs | undefined,\n\ttheme: Theme,\n\tcwd: string,\n): EditCallRenderComponent {\n\tcomponent.setBgFn(getEditHeaderBg(component.preview, component.settledError, theme));\n\tcomponent.clear();\n\tcomponent.addChild(new Text(formatEditCall(args, theme, cwd), 0, 0));\n\n\tif (!component.preview) {\n\t\treturn component;\n\t}\n\n\tconst body =\n\t\t\"error\" in component.preview ? theme.fg(\"error\", component.preview.error) : renderDiff(component.preview.diff);\n\tcomponent.addChild(new Spacer(1));\n\tcomponent.addChild(new Text(body, 0, 0));\n\treturn component;\n}\n\nfunction setEditPreview(\n\tcomponent: EditCallRenderComponent,\n\tpreview: EditPreview,\n\targsKey: string | undefined,\n): boolean {\n\tconst current = component.preview;\n\tconst changed =\n\t\tcurrent === undefined ||\n\t\t(\"error\" in current && \"error\" in preview\n\t\t\t? current.error !== preview.error\n\t\t\t: \"error\" in current !== \"error\" in preview) ||\n\t\t(!(\"error\" in current) &&\n\t\t\t!(\"error\" in preview) &&\n\t\t\t(current.diff !== preview.diff || current.firstChangedLine !== preview.firstChangedLine));\n\tcomponent.preview = preview;\n\tcomponent.previewArgsKey = argsKey;\n\tcomponent.previewPending = false;\n\treturn changed;\n}\n\nexport function createEditToolDefinition(\n\tcwd: string,\n\toptions?: EditToolOptions,\n): ToolDefinition {\n\tconst ops = options?.operations ?? defaultEditOperations;\n\treturn {\n\t\tname: \"edit\",\n\t\tlabel: \"edit\",\n\t\tdescription:\n\t\t\t\"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.\",\n\t\tpromptSnippet:\n\t\t\t\"Make precise file edits with exact text replacement, including multiple disjoint edits in one call\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use edit for precise changes (edits[].oldText must match exactly)\",\n\t\t\t\"When changing multiple separate locations in one file, use one edit call with multiple entries in edits[] instead of multiple edit calls\",\n\t\t\t\"Each edits[].oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits. Merge nearby changes into one edit.\",\n\t\t\t\"Keep edits[].oldText as small as possible while still being unique in the file. Do not pad with large unchanged regions.\",\n\t\t],\n\t\tparameters: editSchema,\n\t\trenderShell: \"self\",\n\t\tprepareArguments: prepareEditArguments,\n\t\tasync execute(_toolCallId, input: EditToolInput, signal?: AbortSignal, _onUpdate?, _ctx?) {\n\t\t\tconst { path, edits } = validateEditInput(input);\n\t\t\tconst absolutePath = resolveToCwd(path, cwd);\n\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Check if file exists.\n\t\t\t\ttry {\n\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tthrowIfAborted();\n\t\t\t\t\tconst errorMessage =\n\t\t\t\t\t\terror instanceof Error && \"code\" in error ? `Error code: ${error.code}` : String(error);\n\t\t\t\t\tthrow new Error(`Could not edit file: ${path}. ${errorMessage}.`);\n\t\t\t\t}\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Read the file.\n\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\tconst rawContent = buffer.toString(\"utf-8\");\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Strip BOM before matching. The model will not include an invisible BOM in oldText.\n\t\t\t\tconst { bom, text: content } = stripBom(rawContent);\n\t\t\t\tconst originalEnding = detectLineEnding(content);\n\t\t\t\tconst normalizedContent = normalizeToLF(content);\n\t\t\t\tconst { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\tconst finalContent = bom + restoreLineEndings(newContent, originalEnding);\n\t\t\t\tawait ops.writeFile(absolutePath, finalContent);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\tconst diffResult = generateDiffString(baseContent, newContent);\n\t\t\t\tconst patch = generateUnifiedPatch(path, baseContent, newContent);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Successfully replaced ${edits.length} block(s) in ${path}.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { diff: diffResult.diff, patch, firstChangedLine: diffResult.firstChangedLine },\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst component = getEditCallRenderComponent(context.state, context.lastComponent);\n\t\t\tconst previewInput = getRenderablePreviewInput(args as RenderableEditArgs | undefined);\n\t\t\tconst argsKey = previewInput\n\t\t\t\t? JSON.stringify({ path: previewInput.path, edits: previewInput.edits })\n\t\t\t\t: undefined;\n\n\t\t\tif (component.previewArgsKey !== argsKey) {\n\t\t\t\tcomponent.preview = undefined;\n\t\t\t\tcomponent.previewArgsKey = argsKey;\n\t\t\t\tcomponent.previewPending = false;\n\t\t\t\tcomponent.settledError = false;\n\t\t\t}\n\n\t\t\tif (context.argsComplete && previewInput && !component.preview && !component.previewPending) {\n\t\t\t\tcomponent.previewPending = true;\n\t\t\t\tconst requestKey = argsKey;\n\t\t\t\tvoid computeEditsDiff(previewInput.path, previewInput.edits, context.cwd).then((preview) => {\n\t\t\t\t\tif (component.previewArgsKey === requestKey) {\n\t\t\t\t\t\tsetEditPreview(component, preview, requestKey);\n\t\t\t\t\t\tcontext.invalidate();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn buildEditCallComponent(component, args, theme, context.cwd);\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst callComponent = context.state.callComponent;\n\t\t\tconst previewInput = getRenderablePreviewInput(context.args as RenderableEditArgs | undefined);\n\t\t\tconst argsKey = previewInput\n\t\t\t\t? JSON.stringify({ path: previewInput.path, edits: previewInput.edits })\n\t\t\t\t: undefined;\n\t\t\tconst typedResult = result as EditToolResultLike;\n\t\t\tconst resultDiff = !context.isError ? typedResult.details?.diff : undefined;\n\t\t\tlet changed = false;\n\t\t\tif (callComponent) {\n\t\t\t\tif (typeof resultDiff === \"string\") {\n\t\t\t\t\tchanged =\n\t\t\t\t\t\tsetEditPreview(\n\t\t\t\t\t\t\tcallComponent,\n\t\t\t\t\t\t\t{ diff: resultDiff, firstChangedLine: typedResult.details?.firstChangedLine },\n\t\t\t\t\t\t\targsKey,\n\t\t\t\t\t\t) || changed;\n\t\t\t\t}\n\t\t\t\tif (callComponent.settledError !== context.isError) {\n\t\t\t\t\tcallComponent.settledError = context.isError;\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t\tif (changed) {\n\t\t\t\t\tbuildEditCallComponent(\n\t\t\t\t\t\tcallComponent,\n\t\t\t\t\t\tcontext.args as RenderableEditArgs | undefined,\n\t\t\t\t\t\ttheme,\n\t\t\t\t\t\tcontext.cwd,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst output = formatEditResult(context.args, callComponent?.preview, typedResult, theme, context.isError);\n\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcomponent.clear();\n\t\t\tif (!output) {\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tcomponent.addChild(new Spacer(1));\n\t\t\tcomponent.addChild(new Text(output, 1, 0));\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nexport function createEditTool(cwd: string, options?: EditToolOptions): AgentTool {\n\treturn wrapToolDefinition(createEditToolDefinition(cwd, options));\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/file-mutation-queue.d.ts b/dist/core/tools/file-mutation-queue.d.ts new file mode 100644 index 0000000..40eabfe --- /dev/null +++ b/dist/core/tools/file-mutation-queue.d.ts @@ -0,0 +1,6 @@ +/** + * Serialize file mutation operations targeting the same file. + * Operations for different files still run in parallel. + */ +export declare function withFileMutationQueue(filePath: string, fn: () => Promise): Promise; +//# sourceMappingURL=file-mutation-queue.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/file-mutation-queue.d.ts.map b/dist/core/tools/file-mutation-queue.d.ts.map new file mode 100644 index 0000000..25011dc --- /dev/null +++ b/dist/core/tools/file-mutation-queue.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"file-mutation-queue.d.ts","sourceRoot":"","sources":["../../../src/core/tools/file-mutation-queue.ts"],"names":[],"mappings":"AA2BA;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CA6BjG","sourcesContent":["import { realpath } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\n\nconst fileMutationQueues = new Map>();\nlet registrationQueue = Promise.resolve();\n\nfunction isMissingPathError(error: unknown): boolean {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\t(error.code === \"ENOENT\" || error.code === \"ENOTDIR\")\n\t);\n}\n\nasync function getMutationQueueKey(filePath: string): Promise {\n\tconst resolvedPath = resolve(filePath);\n\ttry {\n\t\treturn await realpath(resolvedPath);\n\t} catch (error) {\n\t\tif (isMissingPathError(error)) {\n\t\t\treturn resolvedPath;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/**\n * Serialize file mutation operations targeting the same file.\n * Operations for different files still run in parallel.\n */\nexport async function withFileMutationQueue(filePath: string, fn: () => Promise): Promise {\n\tconst registration = registrationQueue.then(async () => {\n\t\tconst key = await getMutationQueueKey(filePath);\n\t\tconst currentQueue = fileMutationQueues.get(key) ?? Promise.resolve();\n\n\t\tlet releaseNext!: () => void;\n\t\tconst nextQueue = new Promise((resolveQueue) => {\n\t\t\treleaseNext = resolveQueue;\n\t\t});\n\t\tconst chainedQueue = currentQueue.then(() => nextQueue);\n\t\tfileMutationQueues.set(key, chainedQueue);\n\n\t\treturn { key, currentQueue, chainedQueue, releaseNext };\n\t});\n\tregistrationQueue = registration.then(\n\t\t() => undefined,\n\t\t() => undefined,\n\t);\n\n\tconst { key, currentQueue, chainedQueue, releaseNext } = await registration;\n\tawait currentQueue;\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\treleaseNext();\n\t\tif (fileMutationQueues.get(key) === chainedQueue) {\n\t\t\tfileMutationQueues.delete(key);\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/file-mutation-queue.js b/dist/core/tools/file-mutation-queue.js new file mode 100644 index 0000000..c223839 --- /dev/null +++ b/dist/core/tools/file-mutation-queue.js @@ -0,0 +1,52 @@ +import { realpath } from "node:fs/promises"; +import { resolve } from "node:path"; +const fileMutationQueues = new Map(); +let registrationQueue = Promise.resolve(); +function isMissingPathError(error) { + return (typeof error === "object" && + error !== null && + "code" in error && + (error.code === "ENOENT" || error.code === "ENOTDIR")); +} +async function getMutationQueueKey(filePath) { + const resolvedPath = resolve(filePath); + try { + return await realpath(resolvedPath); + } + catch (error) { + if (isMissingPathError(error)) { + return resolvedPath; + } + throw error; + } +} +/** + * Serialize file mutation operations targeting the same file. + * Operations for different files still run in parallel. + */ +export async function withFileMutationQueue(filePath, fn) { + const registration = registrationQueue.then(async () => { + const key = await getMutationQueueKey(filePath); + const currentQueue = fileMutationQueues.get(key) ?? Promise.resolve(); + let releaseNext; + const nextQueue = new Promise((resolveQueue) => { + releaseNext = resolveQueue; + }); + const chainedQueue = currentQueue.then(() => nextQueue); + fileMutationQueues.set(key, chainedQueue); + return { key, currentQueue, chainedQueue, releaseNext }; + }); + registrationQueue = registration.then(() => undefined, () => undefined); + const { key, currentQueue, chainedQueue, releaseNext } = await registration; + await currentQueue; + try { + return await fn(); + } + finally { + releaseNext(); + if (fileMutationQueues.get(key) === chainedQueue) { + fileMutationQueues.delete(key); + } + } +} +//# sourceMappingURL=file-mutation-queue.js.map \ No newline at end of file diff --git a/dist/core/tools/file-mutation-queue.js.map b/dist/core/tools/file-mutation-queue.js.map new file mode 100644 index 0000000..e13b336 --- /dev/null +++ b/dist/core/tools/file-mutation-queue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"file-mutation-queue.js","sourceRoot":"","sources":["../../../src/core/tools/file-mutation-queue.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAyB,CAAC;AAC5D,IAAI,iBAAiB,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;AAE1C,SAAS,kBAAkB,CAAC,KAAc,EAAW;IACpD,OAAO,CACN,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,MAAM,IAAI,KAAK;QACf,CAAC,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CACrD,CAAC;AAAA,CACF;AAED,KAAK,UAAU,mBAAmB,CAAC,QAAgB,EAAmB;IACrE,MAAM,YAAY,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IACvC,IAAI,CAAC;QACJ,OAAO,MAAM,QAAQ,CAAC,YAAY,CAAC,CAAC;IACrC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC;YAC/B,OAAO,YAAY,CAAC;QACrB,CAAC;QACD,MAAM,KAAK,CAAC;IACb,CAAC;AAAA,CACD;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAI,QAAgB,EAAE,EAAoB,EAAc;IAClG,MAAM,YAAY,GAAG,iBAAiB,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC;QACvD,MAAM,GAAG,GAAG,MAAM,mBAAmB,CAAC,QAAQ,CAAC,CAAC;QAChD,MAAM,YAAY,GAAG,kBAAkB,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;QAEtE,IAAI,WAAwB,CAAC;QAC7B,MAAM,SAAS,GAAG,IAAI,OAAO,CAAO,CAAC,YAAY,EAAE,EAAE,CAAC;YACrD,WAAW,GAAG,YAAY,CAAC;QAAA,CAC3B,CAAC,CAAC;QACH,MAAM,YAAY,GAAG,YAAY,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QACxD,kBAAkB,CAAC,GAAG,CAAC,GAAG,EAAE,YAAY,CAAC,CAAC;QAE1C,OAAO,EAAE,GAAG,EAAE,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,CAAC;IAAA,CACxD,CAAC,CAAC;IACH,iBAAiB,GAAG,YAAY,CAAC,IAAI,CACpC,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CAAC,SAAS,CACf,CAAC;IAEF,MAAM,EAAE,GAAG,EAAE,YAAY,EAAE,YAAY,EAAE,WAAW,EAAE,GAAG,MAAM,YAAY,CAAC;IAC5E,MAAM,YAAY,CAAC;IACnB,IAAI,CAAC;QACJ,OAAO,MAAM,EAAE,EAAE,CAAC;IACnB,CAAC;YAAS,CAAC;QACV,WAAW,EAAE,CAAC;QACd,IAAI,kBAAkB,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,YAAY,EAAE,CAAC;YAClD,kBAAkB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAChC,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import { realpath } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\n\nconst fileMutationQueues = new Map>();\nlet registrationQueue = Promise.resolve();\n\nfunction isMissingPathError(error: unknown): boolean {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\t(error.code === \"ENOENT\" || error.code === \"ENOTDIR\")\n\t);\n}\n\nasync function getMutationQueueKey(filePath: string): Promise {\n\tconst resolvedPath = resolve(filePath);\n\ttry {\n\t\treturn await realpath(resolvedPath);\n\t} catch (error) {\n\t\tif (isMissingPathError(error)) {\n\t\t\treturn resolvedPath;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/**\n * Serialize file mutation operations targeting the same file.\n * Operations for different files still run in parallel.\n */\nexport async function withFileMutationQueue(filePath: string, fn: () => Promise): Promise {\n\tconst registration = registrationQueue.then(async () => {\n\t\tconst key = await getMutationQueueKey(filePath);\n\t\tconst currentQueue = fileMutationQueues.get(key) ?? Promise.resolve();\n\n\t\tlet releaseNext!: () => void;\n\t\tconst nextQueue = new Promise((resolveQueue) => {\n\t\t\treleaseNext = resolveQueue;\n\t\t});\n\t\tconst chainedQueue = currentQueue.then(() => nextQueue);\n\t\tfileMutationQueues.set(key, chainedQueue);\n\n\t\treturn { key, currentQueue, chainedQueue, releaseNext };\n\t});\n\tregistrationQueue = registration.then(\n\t\t() => undefined,\n\t\t() => undefined,\n\t);\n\n\tconst { key, currentQueue, chainedQueue, releaseNext } = await registration;\n\tawait currentQueue;\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\treleaseNext();\n\t\tif (fileMutationQueues.get(key) === chainedQueue) {\n\t\t\tfileMutationQueues.delete(key);\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/find.d.ts b/dist/core/tools/find.d.ts new file mode 100644 index 0000000..7a3fc0a --- /dev/null +++ b/dist/core/tools/find.d.ts @@ -0,0 +1,35 @@ +import type { AgentTool } from "@earendil-works/pi-agent-core"; +import { type Static, Type } from "typebox"; +import type { ToolDefinition } from "../extensions/types.ts"; +import { type TruncationResult } from "./truncate.ts"; +declare const findSchema: Type.TObject<{ + pattern: Type.TString; + path: Type.TOptional; + limit: Type.TOptional; +}>; +export type FindToolInput = Static; +export interface FindToolDetails { + truncation?: TruncationResult; + resultLimitReached?: number; +} +/** + * Pluggable operations for the find tool. + * Override these to delegate file search to remote systems (for example SSH). + */ +export interface FindOperations { + /** Check if path exists */ + exists: (absolutePath: string) => Promise | boolean; + /** Find files matching glob pattern. Returns relative or absolute paths. */ + glob: (pattern: string, cwd: string, options: { + ignore: string[]; + limit: number; + }) => Promise | string[]; +} +export interface FindToolOptions { + /** Custom operations for find. Default: local filesystem plus fd */ + operations?: FindOperations; +} +export declare function createFindToolDefinition(cwd: string, options?: FindToolOptions): ToolDefinition; +export declare function createFindTool(cwd: string, options?: FindToolOptions): AgentTool; +export {}; +//# sourceMappingURL=find.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/find.d.ts.map b/dist/core/tools/find.d.ts.map new file mode 100644 index 0000000..40d83bc --- /dev/null +++ b/dist/core/tools/find.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"find.d.ts","sourceRoot":"","sources":["../../../src/core/tools/find.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAI/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAI5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAItF,OAAO,EAAiC,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAMnG,QAAA,MAAM,UAAU;;;;EAMd,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAItD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,2BAA2B;IAC3B,MAAM,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IAC7D,4EAA4E;IAC5E,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,MAAM,EAAE,MAAM,EAAE,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC;CACnH;AAQD,MAAM,WAAW,eAAe;IAC/B,oEAAoE;IACpE,UAAU,CAAC,EAAE,cAAc,CAAC;CAC5B;AAoDD,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAkQhE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import { createInterface } from \"node:readline\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { pathExists, resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nfunction toPosixPath(value: string): string {\n\treturn value.split(path.sep).join(\"/\");\n}\n\nconst findSchema = Type.Object({\n\tpattern: Type.String({\n\t\tdescription: \"Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'\",\n\t}),\n\tpath: Type.Optional(Type.String({ description: \"Directory to search in (default: current directory)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of results (default: 1000)\" })),\n});\n\nexport type FindToolInput = Static;\n\nconst DEFAULT_LIMIT = 1000;\n\nexport interface FindToolDetails {\n\ttruncation?: TruncationResult;\n\tresultLimitReached?: number;\n}\n\n/**\n * Pluggable operations for the find tool.\n * Override these to delegate file search to remote systems (for example SSH).\n */\nexport interface FindOperations {\n\t/** Check if path exists */\n\texists: (absolutePath: string) => Promise | boolean;\n\t/** Find files matching glob pattern. Returns relative or absolute paths. */\n\tglob: (pattern: string, cwd: string, options: { ignore: string[]; limit: number }) => Promise | string[];\n}\n\nconst defaultFindOperations: FindOperations = {\n\texists: pathExists,\n\t// This is a placeholder. Actual fd execution happens in execute() when no custom glob is provided.\n\tglob: () => [],\n};\n\nexport interface FindToolOptions {\n\t/** Custom operations for find. Default: local filesystem plus fd */\n\toperations?: FindOperations;\n}\n\nfunction formatFindCall(args: { pattern: string; path?: string; limit?: number } | undefined, theme: Theme): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"find\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", pattern || \"\")) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (limit !== undefined) {\n\t\ttext += theme.fg(\"toolOutput\", ` (limit ${limit})`);\n\t}\n\treturn text;\n}\n\nfunction formatFindResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: FindToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\tconst resultLimit = result.details?.resultLimitReached;\n\tconst truncation = result.details?.truncation;\n\tif (resultLimit || truncation?.truncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (resultLimit) warnings.push(`${resultLimit} results limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nexport function createFindToolDefinition(\n\tcwd: string,\n\toptions?: FindToolOptions,\n): ToolDefinition {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"find\",\n\t\tlabel: \"find\",\n\t\tdescription: `Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} results or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,\n\t\tpromptSnippet: \"Find files by glob pattern (respects .gitignore)\",\n\t\tparameters: findSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ pattern, path: searchDir, limit }: { pattern: string; path?: string; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet settled = false;\n\t\t\t\tlet stopChild: (() => void) | undefined;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tstopChild = undefined;\n\t\t\t\t\tfn();\n\t\t\t\t};\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\tstopChild?.();\n\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t};\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", cwd);\n\t\t\t\t\t\tconst effectiveLimit = limit ?? DEFAULT_LIMIT;\n\t\t\t\t\t\tconst ops = customOps ?? defaultFindOperations;\n\n\t\t\t\t\t\t// If custom operations provide glob(), use that instead of fd.\n\t\t\t\t\t\tif (customOps?.glob) {\n\t\t\t\t\t\t\tif (!(await ops.exists(searchPath))) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst results = await ops.glob(pattern, searchPath, {\n\t\t\t\t\t\t\t\tignore: [\"**/node_modules/**\", \"**/.git/**\"],\n\t\t\t\t\t\t\t\tlimit: effectiveLimit,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (results.length === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No files found matching pattern\" }],\n\t\t\t\t\t\t\t\t\t\tdetails: undefined,\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Relativize paths against the search root for stable output.\n\t\t\t\t\t\t\tconst relativized = results.map((p) => {\n\t\t\t\t\t\t\t\tif (p.startsWith(searchPath)) return toPosixPath(p.slice(searchPath.length + 1));\n\t\t\t\t\t\t\t\treturn toPosixPath(path.relative(searchPath, p));\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst resultLimitReached = relativized.length >= effectiveLimit;\n\t\t\t\t\t\t\tconst rawOutput = relativized.join(\"\\n\");\n\t\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet resultOutput = truncation.content;\n\t\t\t\t\t\t\tconst details: FindToolDetails = {};\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (resultLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(`${effectiveLimit} results limit reached`);\n\t\t\t\t\t\t\t\tdetails.resultLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) {\n\t\t\t\t\t\t\t\tresultOutput += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: resultOutput }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Default implementation uses fd.\n\t\t\t\t\t\tconst fdPath = await ensureTool(\"fd\", true);\n\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!fdPath) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"fd is not available and could not be downloaded\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst args: string[] = [\"--glob\", \"--color=never\", \"--hidden\"];\n\n\t\t\t\t\t\t// fd normally ignores .gitignore outside git repos, so keep --no-require-git\n\t\t\t\t\t\t// there. Inside repos, use fd's default git-aware behavior so parent\n\t\t\t\t\t\t// .gitignore rules stop at nested repo boundaries:\n\t\t\t\t\t\t// https://github.com/earendil-works/pi/issues/5960\n\t\t\t\t\t\tlet insideGitRepo = false;\n\t\t\t\t\t\tfor (let current = searchPath; ; ) {\n\t\t\t\t\t\t\tif (await pathExists(path.join(current, \".git\"))) {\n\t\t\t\t\t\t\t\tinsideGitRepo = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst parent = path.dirname(current);\n\t\t\t\t\t\t\tif (parent === current) break;\n\t\t\t\t\t\t\tcurrent = parent;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!insideGitRepo) args.push(\"--no-require-git\");\n\t\t\t\t\t\targs.push(\"--max-results\", String(effectiveLimit));\n\n\t\t\t\t\t\t// fd --glob matches against the basename unless --full-path is set; in --full-path\n\t\t\t\t\t\t// mode it matches against the absolute candidate path, so a path-containing\n\t\t\t\t\t\t// pattern like 'src/**/*.spec.ts' needs a leading '**/' to match anything.\n\t\t\t\t\t\tlet effectivePattern = pattern;\n\t\t\t\t\t\tif (pattern.includes(\"/\")) {\n\t\t\t\t\t\t\targs.push(\"--full-path\");\n\t\t\t\t\t\t\tif (!pattern.startsWith(\"/\") && !pattern.startsWith(\"**/\") && pattern !== \"**\") {\n\t\t\t\t\t\t\t\teffectivePattern = `**/${pattern}`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\targs.push(\"--\", effectivePattern, searchPath);\n\n\t\t\t\t\t\tconst child = spawn(fdPath, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\tconst lines: string[] = [];\n\n\t\t\t\t\t\tstopChild = () => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\trl.on(\"line\", (line) => {\n\t\t\t\t\t\t\tlines.push(line);\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run fd: ${error.message}`)));\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"close\", (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst output = lines.join(\"\\n\");\n\t\t\t\t\t\t\tif (code !== 0) {\n\t\t\t\t\t\t\t\tconst errorMsg = stderr.trim() || `fd exited with code ${code}`;\n\t\t\t\t\t\t\t\tif (!output) {\n\t\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!output) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No files found matching pattern\" }],\n\t\t\t\t\t\t\t\t\t\tdetails: undefined,\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst relativized: string[] = [];\n\t\t\t\t\t\t\tfor (const rawLine of lines) {\n\t\t\t\t\t\t\t\tconst line = rawLine.replace(/\\r$/, \"\").trim();\n\t\t\t\t\t\t\t\tif (!line) continue;\n\t\t\t\t\t\t\t\tconst hadTrailingSlash = line.endsWith(\"/\") || line.endsWith(\"\\\\\");\n\t\t\t\t\t\t\t\tlet relativePath = line;\n\t\t\t\t\t\t\t\tif (line.startsWith(searchPath)) {\n\t\t\t\t\t\t\t\t\trelativePath = line.slice(searchPath.length + 1);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\trelativePath = path.relative(searchPath, line);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (hadTrailingSlash && !relativePath.endsWith(\"/\")) relativePath += \"/\";\n\t\t\t\t\t\t\t\trelativized.push(toPosixPath(relativePath));\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst resultLimitReached = relativized.length >= effectiveLimit;\n\t\t\t\t\t\t\tconst rawOutput = relativized.join(\"\\n\");\n\t\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet resultOutput = truncation.content;\n\t\t\t\t\t\t\tconst details: FindToolDetails = {};\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (resultLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} results limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.resultLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) {\n\t\t\t\t\t\t\t\tresultOutput += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: resultOutput }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst error = e instanceof Error ? e : new Error(String(e));\n\t\t\t\t\t\tsettle(() => reject(error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatFindCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatFindResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createFindTool(cwd: string, options?: FindToolOptions): AgentTool {\n\treturn wrapToolDefinition(createFindToolDefinition(cwd, options));\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/find.js b/dist/core/tools/find.js new file mode 100644 index 0000000..b492459 --- /dev/null +++ b/dist/core/tools/find.js @@ -0,0 +1,305 @@ +import { createInterface } from "node:readline"; +import { Text } from "@earendil-works/pi-tui"; +import { spawn } from "child_process"; +import path from "path"; +import { Type } from "typebox"; +import { keyHint } from "../../modes/interactive/components/keybinding-hints.js"; +import { ensureTool } from "../../utils/tools-manager.js"; +import { pathExists, resolveToCwd } from "./path-utils.js"; +import { getTextOutput, invalidArgText, shortenPath, str } from "./render-utils.js"; +import { wrapToolDefinition } from "./tool-definition-wrapper.js"; +import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js"; +function toPosixPath(value) { + return value.split(path.sep).join("/"); +} +const findSchema = Type.Object({ + pattern: Type.String({ + description: "Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'", + }), + path: Type.Optional(Type.String({ description: "Directory to search in (default: current directory)" })), + limit: Type.Optional(Type.Number({ description: "Maximum number of results (default: 1000)" })), +}); +const DEFAULT_LIMIT = 1000; +const defaultFindOperations = { + exists: pathExists, + // This is a placeholder. Actual fd execution happens in execute() when no custom glob is provided. + glob: () => [], +}; +function formatFindCall(args, theme) { + const pattern = str(args?.pattern); + const rawPath = str(args?.path); + const path = rawPath !== null ? shortenPath(rawPath || ".") : null; + const limit = args?.limit; + const invalidArg = invalidArgText(theme); + let text = theme.fg("toolTitle", theme.bold("find")) + + " " + + (pattern === null ? invalidArg : theme.fg("accent", pattern || "")) + + theme.fg("toolOutput", ` in ${path === null ? invalidArg : path}`); + if (limit !== undefined) { + text += theme.fg("toolOutput", ` (limit ${limit})`); + } + return text; +} +function formatFindResult(result, options, theme, showImages) { + const output = getTextOutput(result, showImages).trim(); + let text = ""; + if (output) { + const lines = output.split("\n"); + const maxLines = options.expanded ? lines.length : 20; + const displayLines = lines.slice(0, maxLines); + const remaining = lines.length - maxLines; + text += `\n${displayLines.map((line) => theme.fg("toolOutput", line)).join("\n")}`; + if (remaining > 0) { + text += `${theme.fg("muted", `\n... (${remaining} more lines,`)} ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`; + } + } + const resultLimit = result.details?.resultLimitReached; + const truncation = result.details?.truncation; + if (resultLimit || truncation?.truncated) { + const warnings = []; + if (resultLimit) + warnings.push(`${resultLimit} results limit`); + if (truncation?.truncated) + warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`); + text += `\n${theme.fg("warning", `[Truncated: ${warnings.join(", ")}]`)}`; + } + return text; +} +export function createFindToolDefinition(cwd, options) { + const customOps = options?.operations; + return { + name: "find", + label: "find", + description: `Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} results or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`, + promptSnippet: "Find files by glob pattern (respects .gitignore)", + parameters: findSchema, + async execute(_toolCallId, { pattern, path: searchDir, limit }, signal, _onUpdate, _ctx) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(new Error("Operation aborted")); + return; + } + let settled = false; + let stopChild; + const settle = (fn) => { + if (settled) + return; + settled = true; + signal?.removeEventListener("abort", onAbort); + stopChild = undefined; + fn(); + }; + const onAbort = () => { + stopChild?.(); + settle(() => reject(new Error("Operation aborted"))); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + (async () => { + try { + const searchPath = resolveToCwd(searchDir || ".", cwd); + const effectiveLimit = limit ?? DEFAULT_LIMIT; + const ops = customOps ?? defaultFindOperations; + // If custom operations provide glob(), use that instead of fd. + if (customOps?.glob) { + if (!(await ops.exists(searchPath))) { + settle(() => reject(new Error(`Path not found: ${searchPath}`))); + return; + } + if (signal?.aborted) { + settle(() => reject(new Error("Operation aborted"))); + return; + } + const results = await ops.glob(pattern, searchPath, { + ignore: ["**/node_modules/**", "**/.git/**"], + limit: effectiveLimit, + }); + if (signal?.aborted) { + settle(() => reject(new Error("Operation aborted"))); + return; + } + if (results.length === 0) { + settle(() => resolve({ + content: [{ type: "text", text: "No files found matching pattern" }], + details: undefined, + })); + return; + } + // Relativize paths against the search root for stable output. + const relativized = results.map((p) => { + if (p.startsWith(searchPath)) + return toPosixPath(p.slice(searchPath.length + 1)); + return toPosixPath(path.relative(searchPath, p)); + }); + const resultLimitReached = relativized.length >= effectiveLimit; + const rawOutput = relativized.join("\n"); + const truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER }); + let resultOutput = truncation.content; + const details = {}; + const notices = []; + if (resultLimitReached) { + notices.push(`${effectiveLimit} results limit reached`); + details.resultLimitReached = effectiveLimit; + } + if (truncation.truncated) { + notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`); + details.truncation = truncation; + } + if (notices.length > 0) { + resultOutput += `\n\n[${notices.join(". ")}]`; + } + settle(() => resolve({ + content: [{ type: "text", text: resultOutput }], + details: Object.keys(details).length > 0 ? details : undefined, + })); + return; + } + // Default implementation uses fd. + const fdPath = await ensureTool("fd", true); + if (signal?.aborted) { + settle(() => reject(new Error("Operation aborted"))); + return; + } + if (!fdPath) { + settle(() => reject(new Error("fd is not available and could not be downloaded"))); + return; + } + const args = ["--glob", "--color=never", "--hidden"]; + // fd normally ignores .gitignore outside git repos, so keep --no-require-git + // there. Inside repos, use fd's default git-aware behavior so parent + // .gitignore rules stop at nested repo boundaries: + // https://github.com/earendil-works/pi/issues/5960 + let insideGitRepo = false; + for (let current = searchPath;;) { + if (await pathExists(path.join(current, ".git"))) { + insideGitRepo = true; + break; + } + const parent = path.dirname(current); + if (parent === current) + break; + current = parent; + } + if (!insideGitRepo) + args.push("--no-require-git"); + args.push("--max-results", String(effectiveLimit)); + // fd --glob matches against the basename unless --full-path is set; in --full-path + // mode it matches against the absolute candidate path, so a path-containing + // pattern like 'src/**/*.spec.ts' needs a leading '**/' to match anything. + let effectivePattern = pattern; + if (pattern.includes("/")) { + args.push("--full-path"); + if (!pattern.startsWith("/") && !pattern.startsWith("**/") && pattern !== "**") { + effectivePattern = `**/${pattern}`; + } + } + args.push("--", effectivePattern, searchPath); + const child = spawn(fdPath, args, { stdio: ["ignore", "pipe", "pipe"] }); + const rl = createInterface({ input: child.stdout }); + let stderr = ""; + const lines = []; + stopChild = () => { + if (!child.killed) { + child.kill(); + } + }; + const cleanup = () => { + rl.close(); + }; + child.stderr?.on("data", (chunk) => { + stderr += chunk.toString(); + }); + rl.on("line", (line) => { + lines.push(line); + }); + child.on("error", (error) => { + cleanup(); + settle(() => reject(new Error(`Failed to run fd: ${error.message}`))); + }); + child.on("close", (code) => { + cleanup(); + if (signal?.aborted) { + settle(() => reject(new Error("Operation aborted"))); + return; + } + const output = lines.join("\n"); + if (code !== 0) { + const errorMsg = stderr.trim() || `fd exited with code ${code}`; + if (!output) { + settle(() => reject(new Error(errorMsg))); + return; + } + } + if (!output) { + settle(() => resolve({ + content: [{ type: "text", text: "No files found matching pattern" }], + details: undefined, + })); + return; + } + const relativized = []; + for (const rawLine of lines) { + const line = rawLine.replace(/\r$/, "").trim(); + if (!line) + continue; + const hadTrailingSlash = line.endsWith("/") || line.endsWith("\\"); + let relativePath = line; + if (line.startsWith(searchPath)) { + relativePath = line.slice(searchPath.length + 1); + } + else { + relativePath = path.relative(searchPath, line); + } + if (hadTrailingSlash && !relativePath.endsWith("/")) + relativePath += "/"; + relativized.push(toPosixPath(relativePath)); + } + const resultLimitReached = relativized.length >= effectiveLimit; + const rawOutput = relativized.join("\n"); + const truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER }); + let resultOutput = truncation.content; + const details = {}; + const notices = []; + if (resultLimitReached) { + notices.push(`${effectiveLimit} results limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`); + details.resultLimitReached = effectiveLimit; + } + if (truncation.truncated) { + notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`); + details.truncation = truncation; + } + if (notices.length > 0) { + resultOutput += `\n\n[${notices.join(". ")}]`; + } + settle(() => resolve({ + content: [{ type: "text", text: resultOutput }], + details: Object.keys(details).length > 0 ? details : undefined, + })); + }); + } + catch (e) { + if (signal?.aborted) { + settle(() => reject(new Error("Operation aborted"))); + return; + } + const error = e instanceof Error ? e : new Error(String(e)); + settle(() => reject(error)); + } + })(); + }); + }, + renderCall(args, theme, context) { + const text = context.lastComponent ?? new Text("", 0, 0); + text.setText(formatFindCall(args, theme)); + return text; + }, + renderResult(result, options, theme, context) { + const text = context.lastComponent ?? new Text("", 0, 0); + text.setText(formatFindResult(result, options, theme, context.showImages)); + return text; + }, + }; +} +export function createFindTool(cwd, options) { + return wrapToolDefinition(createFindToolDefinition(cwd, options)); +} +//# sourceMappingURL=find.js.map \ No newline at end of file diff --git a/dist/core/tools/find.js.map b/dist/core/tools/find.js.map new file mode 100644 index 0000000..85f631e --- /dev/null +++ b/dist/core/tools/find.js.map @@ -0,0 +1 @@ +{"version":3,"file":"find.js","sourceRoot":"","sources":["../../../src/core/tools/find.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhD,OAAO,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AAEjF,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAE1D,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACpF,OAAO,EAAE,kBAAkB,EA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I,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;YAC1C,OAAO,IAAI,CAAC;QAAA,CACZ;QACD,YAAY,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE;YAC7C,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,MAAa,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;YAClF,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB,EAAgC;IACpG,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAClE","sourcesContent":["import { createInterface } from \"node:readline\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { pathExists, resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nfunction toPosixPath(value: string): string {\n\treturn value.split(path.sep).join(\"/\");\n}\n\nconst findSchema = Type.Object({\n\tpattern: Type.String({\n\t\tdescription: \"Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'\",\n\t}),\n\tpath: Type.Optional(Type.String({ description: \"Directory to search in (default: current directory)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of results (default: 1000)\" })),\n});\n\nexport type FindToolInput = Static;\n\nconst DEFAULT_LIMIT = 1000;\n\nexport interface FindToolDetails {\n\ttruncation?: TruncationResult;\n\tresultLimitReached?: number;\n}\n\n/**\n * Pluggable operations for the find tool.\n * Override these to delegate file search to remote systems (for example SSH).\n */\nexport interface FindOperations {\n\t/** Check if path exists */\n\texists: (absolutePath: string) => Promise | boolean;\n\t/** Find files matching glob pattern. Returns relative or absolute paths. */\n\tglob: (pattern: string, cwd: string, options: { ignore: string[]; limit: number }) => Promise | string[];\n}\n\nconst defaultFindOperations: FindOperations = {\n\texists: pathExists,\n\t// This is a placeholder. Actual fd execution happens in execute() when no custom glob is provided.\n\tglob: () => [],\n};\n\nexport interface FindToolOptions {\n\t/** Custom operations for find. Default: local filesystem plus fd */\n\toperations?: FindOperations;\n}\n\nfunction formatFindCall(args: { pattern: string; path?: string; limit?: number } | undefined, theme: Theme): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"find\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", pattern || \"\")) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (limit !== undefined) {\n\t\ttext += theme.fg(\"toolOutput\", ` (limit ${limit})`);\n\t}\n\treturn text;\n}\n\nfunction formatFindResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: FindToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\tconst resultLimit = result.details?.resultLimitReached;\n\tconst truncation = result.details?.truncation;\n\tif (resultLimit || truncation?.truncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (resultLimit) warnings.push(`${resultLimit} results limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nexport function createFindToolDefinition(\n\tcwd: string,\n\toptions?: FindToolOptions,\n): ToolDefinition {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"find\",\n\t\tlabel: \"find\",\n\t\tdescription: `Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} results or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,\n\t\tpromptSnippet: \"Find files by glob pattern (respects .gitignore)\",\n\t\tparameters: findSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ pattern, path: searchDir, limit }: { pattern: string; path?: string; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet settled = false;\n\t\t\t\tlet stopChild: (() => void) | undefined;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tstopChild = undefined;\n\t\t\t\t\tfn();\n\t\t\t\t};\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\tstopChild?.();\n\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t};\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", cwd);\n\t\t\t\t\t\tconst effectiveLimit = limit ?? DEFAULT_LIMIT;\n\t\t\t\t\t\tconst ops = customOps ?? defaultFindOperations;\n\n\t\t\t\t\t\t// If custom operations provide glob(), use that instead of fd.\n\t\t\t\t\t\tif (customOps?.glob) {\n\t\t\t\t\t\t\tif (!(await ops.exists(searchPath))) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst results = await ops.glob(pattern, searchPath, {\n\t\t\t\t\t\t\t\tignore: [\"**/node_modules/**\", \"**/.git/**\"],\n\t\t\t\t\t\t\t\tlimit: effectiveLimit,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (results.length === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No files found matching pattern\" }],\n\t\t\t\t\t\t\t\t\t\tdetails: undefined,\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Relativize paths against the search root for stable output.\n\t\t\t\t\t\t\tconst relativized = results.map((p) => {\n\t\t\t\t\t\t\t\tif (p.startsWith(searchPath)) return toPosixPath(p.slice(searchPath.length + 1));\n\t\t\t\t\t\t\t\treturn toPosixPath(path.relative(searchPath, p));\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst resultLimitReached = relativized.length >= effectiveLimit;\n\t\t\t\t\t\t\tconst rawOutput = relativized.join(\"\\n\");\n\t\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet resultOutput = truncation.content;\n\t\t\t\t\t\t\tconst details: FindToolDetails = {};\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (resultLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(`${effectiveLimit} results limit reached`);\n\t\t\t\t\t\t\t\tdetails.resultLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) {\n\t\t\t\t\t\t\t\tresultOutput += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: resultOutput }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Default implementation uses fd.\n\t\t\t\t\t\tconst fdPath = await ensureTool(\"fd\", true);\n\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!fdPath) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"fd is not available and could not be downloaded\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst args: string[] = [\"--glob\", \"--color=never\", \"--hidden\"];\n\n\t\t\t\t\t\t// fd normally ignores .gitignore outside git repos, so keep --no-require-git\n\t\t\t\t\t\t// there. Inside repos, use fd's default git-aware behavior so parent\n\t\t\t\t\t\t// .gitignore rules stop at nested repo boundaries:\n\t\t\t\t\t\t// https://github.com/earendil-works/pi/issues/5960\n\t\t\t\t\t\tlet insideGitRepo = false;\n\t\t\t\t\t\tfor (let current = searchPath; ; ) {\n\t\t\t\t\t\t\tif (await pathExists(path.join(current, \".git\"))) {\n\t\t\t\t\t\t\t\tinsideGitRepo = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst parent = path.dirname(current);\n\t\t\t\t\t\t\tif (parent === current) break;\n\t\t\t\t\t\t\tcurrent = parent;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!insideGitRepo) args.push(\"--no-require-git\");\n\t\t\t\t\t\targs.push(\"--max-results\", String(effectiveLimit));\n\n\t\t\t\t\t\t// fd --glob matches against the basename unless --full-path is set; in --full-path\n\t\t\t\t\t\t// mode it matches against the absolute candidate path, so a path-containing\n\t\t\t\t\t\t// pattern like 'src/**/*.spec.ts' needs a leading '**/' to match anything.\n\t\t\t\t\t\tlet effectivePattern = pattern;\n\t\t\t\t\t\tif (pattern.includes(\"/\")) {\n\t\t\t\t\t\t\targs.push(\"--full-path\");\n\t\t\t\t\t\t\tif (!pattern.startsWith(\"/\") && !pattern.startsWith(\"**/\") && pattern !== \"**\") {\n\t\t\t\t\t\t\t\teffectivePattern = `**/${pattern}`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\targs.push(\"--\", effectivePattern, searchPath);\n\n\t\t\t\t\t\tconst child = spawn(fdPath, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\tconst lines: string[] = [];\n\n\t\t\t\t\t\tstopChild = () => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\trl.on(\"line\", (line) => {\n\t\t\t\t\t\t\tlines.push(line);\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run fd: ${error.message}`)));\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"close\", (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst output = lines.join(\"\\n\");\n\t\t\t\t\t\t\tif (code !== 0) {\n\t\t\t\t\t\t\t\tconst errorMsg = stderr.trim() || `fd exited with code ${code}`;\n\t\t\t\t\t\t\t\tif (!output) {\n\t\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!output) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No files found matching pattern\" }],\n\t\t\t\t\t\t\t\t\t\tdetails: undefined,\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst relativized: string[] = [];\n\t\t\t\t\t\t\tfor (const rawLine of lines) {\n\t\t\t\t\t\t\t\tconst line = rawLine.replace(/\\r$/, \"\").trim();\n\t\t\t\t\t\t\t\tif (!line) continue;\n\t\t\t\t\t\t\t\tconst hadTrailingSlash = line.endsWith(\"/\") || line.endsWith(\"\\\\\");\n\t\t\t\t\t\t\t\tlet relativePath = line;\n\t\t\t\t\t\t\t\tif (line.startsWith(searchPath)) {\n\t\t\t\t\t\t\t\t\trelativePath = line.slice(searchPath.length + 1);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\trelativePath = path.relative(searchPath, line);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (hadTrailingSlash && !relativePath.endsWith(\"/\")) relativePath += \"/\";\n\t\t\t\t\t\t\t\trelativized.push(toPosixPath(relativePath));\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst resultLimitReached = relativized.length >= effectiveLimit;\n\t\t\t\t\t\t\tconst rawOutput = relativized.join(\"\\n\");\n\t\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet resultOutput = truncation.content;\n\t\t\t\t\t\t\tconst details: FindToolDetails = {};\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (resultLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} results limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.resultLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) {\n\t\t\t\t\t\t\t\tresultOutput += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: resultOutput }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst error = e instanceof Error ? e : new Error(String(e));\n\t\t\t\t\t\tsettle(() => reject(error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatFindCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatFindResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createFindTool(cwd: string, options?: FindToolOptions): AgentTool {\n\treturn wrapToolDefinition(createFindToolDefinition(cwd, options));\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/grep.d.ts b/dist/core/tools/grep.d.ts new file mode 100644 index 0000000..fd073cd --- /dev/null +++ b/dist/core/tools/grep.d.ts @@ -0,0 +1,37 @@ +import type { AgentTool } from "@earendil-works/pi-agent-core"; +import { type Static, Type } from "typebox"; +import type { ToolDefinition } from "../extensions/types.ts"; +import { type TruncationResult } from "./truncate.ts"; +declare const grepSchema: Type.TObject<{ + pattern: Type.TString; + path: Type.TOptional; + glob: Type.TOptional; + ignoreCase: Type.TOptional; + literal: Type.TOptional; + context: Type.TOptional; + limit: Type.TOptional; +}>; +export type GrepToolInput = Static; +export interface GrepToolDetails { + truncation?: TruncationResult; + matchLimitReached?: number; + linesTruncated?: boolean; +} +/** + * Pluggable operations for the grep tool. + * Override these to delegate search to remote systems (for example SSH). + */ +export interface GrepOperations { + /** Check if path is a directory. Throws if path does not exist. */ + isDirectory: (absolutePath: string) => Promise | boolean; + /** Read file contents for context lines */ + readFile: (absolutePath: string) => Promise | string; +} +export interface GrepToolOptions { + /** Custom operations for grep. Default: local filesystem plus ripgrep */ + operations?: GrepOperations; +} +export declare function createGrepToolDefinition(cwd: string, options?: GrepToolOptions): ToolDefinition; +export declare function createGrepTool(cwd: string, options?: GrepToolOptions): AgentTool; +export {}; +//# sourceMappingURL=grep.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/grep.d.ts.map b/dist/core/tools/grep.d.ts.map new file mode 100644 index 0000000..278d8c6 --- /dev/null +++ b/dist/core/tools/grep.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"grep.d.ts","sourceRoot":"","sources":["../../../src/core/tools/grep.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAI/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAI5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAItF,OAAO,EAIN,KAAK,gBAAgB,EAGrB,MAAM,eAAe,CAAC;AAEvB,QAAA,MAAM,UAAU;;;;;;;;EAYd,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAGtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,mEAAmE;IACnE,WAAW,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IAClE,2CAA2C;IAC3C,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;CAC7D;AAOD,MAAM,WAAW,eAAe;IAC/B,yEAAyE;IACzE,UAAU,CAAC,EAAE,cAAc,CAAC;CAC5B;AAyDD,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CA+PhE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import { readFile as fsReadFile, stat as fsStat } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.ts\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(Type.String({ description: \"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'\" })),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n});\n\nexport type GrepToolInput = Static;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\n/**\n * Pluggable operations for the grep tool.\n * Override these to delegate search to remote systems (for example SSH).\n */\nexport interface GrepOperations {\n\t/** Check if path is a directory. Throws if path does not exist. */\n\tisDirectory: (absolutePath: string) => Promise | boolean;\n\t/** Read file contents for context lines */\n\treadFile: (absolutePath: string) => Promise | string;\n}\n\nconst defaultGrepOperations: GrepOperations = {\n\tisDirectory: async (p) => (await fsStat(p)).isDirectory(),\n\treadFile: (p) => fsReadFile(p, \"utf-8\"),\n};\n\nexport interface GrepToolOptions {\n\t/** Custom operations for grep. Default: local filesystem plus ripgrep */\n\toperations?: GrepOperations;\n}\n\nfunction formatGrepCall(\n\targs: { pattern: string; path?: string; glob?: string; limit?: number } | undefined,\n\ttheme: Theme,\n): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst glob = str(args?.glob);\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"grep\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", `/${pattern || \"\"}/`)) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (glob) text += theme.fg(\"toolOutput\", ` (${glob})`);\n\tif (limit !== undefined) text += theme.fg(\"toolOutput\", ` limit ${limit}`);\n\treturn text;\n}\n\nfunction formatGrepResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: GrepToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 15;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\tconst matchLimit = result.details?.matchLimitReached;\n\tconst truncation = result.details?.truncation;\n\tconst linesTruncated = result.details?.linesTruncated;\n\tif (matchLimit || truncation?.truncated || linesTruncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (matchLimit) warnings.push(`${matchLimit} matches limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\tif (linesTruncated) warnings.push(\"some lines truncated\");\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nexport function createGrepToolDefinition(\n\tcwd: string,\n\toptions?: GrepToolOptions,\n): ToolDefinition {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: \"Search file contents for patterns (respects .gitignore)\",\n\t\tparameters: grepSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{\n\t\t\t\tpattern,\n\t\t\t\tpath: searchDir,\n\t\t\t\tglob,\n\t\t\t\tignoreCase,\n\t\t\t\tliteral,\n\t\t\t\tcontext,\n\t\t\t\tlimit,\n\t\t\t}: {\n\t\t\t\tpattern: string;\n\t\t\t\tpath?: string;\n\t\t\t\tglob?: string;\n\t\t\t\tignoreCase?: boolean;\n\t\t\t\tliteral?: boolean;\n\t\t\t\tcontext?: number;\n\t\t\t\tlimit?: number;\n\t\t\t},\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet settled = false;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tfn();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst rgPath = await ensureTool(\"rg\", true);\n\t\t\t\t\t\tif (!rgPath) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"ripgrep (rg) is not available and could not be downloaded\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", cwd);\n\t\t\t\t\t\tconst ops = customOps ?? defaultGrepOperations;\n\t\t\t\t\t\tlet isDirectory: boolean;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tisDirectory = await ops.isDirectory(searchPath);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst contextValue = context && context > 0 ? context : 0;\n\t\t\t\t\t\tconst effectiveLimit = Math.max(1, limit ?? DEFAULT_LIMIT);\n\t\t\t\t\t\tconst formatPath = (filePath: string): string => {\n\t\t\t\t\t\t\tif (isDirectory) {\n\t\t\t\t\t\t\t\tconst relative = path.relative(searchPath, filePath);\n\t\t\t\t\t\t\t\tif (relative && !relative.startsWith(\"..\")) {\n\t\t\t\t\t\t\t\t\treturn relative.replace(/\\\\/g, \"/\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn path.basename(filePath);\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst fileCache = new Map();\n\t\t\t\t\t\tconst getFileLines = async (filePath: string): Promise => {\n\t\t\t\t\t\t\tlet lines = fileCache.get(filePath);\n\t\t\t\t\t\t\tif (!lines) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tconst content = await ops.readFile(filePath);\n\t\t\t\t\t\t\t\t\tlines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\tlines = [];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfileCache.set(filePath, lines);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn lines;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst args: string[] = [\"--json\", \"--line-number\", \"--color=never\", \"--hidden\"];\n\t\t\t\t\t\tif (ignoreCase) args.push(\"--ignore-case\");\n\t\t\t\t\t\tif (literal) args.push(\"--fixed-strings\");\n\t\t\t\t\t\tif (glob) args.push(\"--glob\", glob);\n\t\t\t\t\t\targs.push(\"--\", pattern, searchPath);\n\n\t\t\t\t\t\tconst child = spawn(rgPath, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\tlet matchCount = 0;\n\t\t\t\t\t\tlet matchLimitReached = false;\n\t\t\t\t\t\tlet linesTruncated = false;\n\t\t\t\t\t\tlet aborted = false;\n\t\t\t\t\t\tlet killedDueToLimit = false;\n\t\t\t\t\t\tconst outputLines: string[] = [];\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst stopChild = (dueToLimit = false) => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tkilledDueToLimit = dueToLimit;\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\t\tstopChild();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tconst formatBlock = async (filePath: string, lineNumber: number): Promise => {\n\t\t\t\t\t\t\tconst relativePath = formatPath(filePath);\n\t\t\t\t\t\t\tconst lines = await getFileLines(filePath);\n\t\t\t\t\t\t\tif (!lines.length) return [`${relativePath}:${lineNumber}: (unable to read file)`];\n\t\t\t\t\t\t\tconst block: string[] = [];\n\t\t\t\t\t\t\tconst start = contextValue > 0 ? Math.max(1, lineNumber - contextValue) : lineNumber;\n\t\t\t\t\t\t\tconst end = contextValue > 0 ? Math.min(lines.length, lineNumber + contextValue) : lineNumber;\n\t\t\t\t\t\t\tfor (let current = start; current <= end; current++) {\n\t\t\t\t\t\t\t\tconst lineText = lines[current - 1] ?? \"\";\n\t\t\t\t\t\t\t\tconst sanitized = lineText.replace(/\\r/g, \"\");\n\t\t\t\t\t\t\t\tconst isMatchLine = current === lineNumber;\n\t\t\t\t\t\t\t\t// Truncate long lines so grep output stays compact.\n\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\tif (isMatchLine) block.push(`${relativePath}:${current}: ${truncatedText}`);\n\t\t\t\t\t\t\t\telse block.push(`${relativePath}-${current}- ${truncatedText}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn block;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// Collect matches during streaming, then format them after rg exits.\n\t\t\t\t\t\tconst matches: Array<{ filePath: string; lineNumber: number; lineText?: string }> = [];\n\t\t\t\t\t\trl.on(\"line\", (line) => {\n\t\t\t\t\t\t\tif (!line.trim() || matchCount >= effectiveLimit) return;\n\t\t\t\t\t\t\tlet event: any;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tevent = JSON.parse(line);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (event.type === \"match\") {\n\t\t\t\t\t\t\t\tmatchCount++;\n\t\t\t\t\t\t\t\tconst filePath = event.data?.path?.text;\n\t\t\t\t\t\t\t\tconst lineNumber = event.data?.line_number;\n\t\t\t\t\t\t\t\tconst lineText = event.data?.lines?.text;\n\t\t\t\t\t\t\t\tif (filePath && typeof lineNumber === \"number\")\n\t\t\t\t\t\t\t\t\tmatches.push({ filePath, lineNumber, lineText });\n\t\t\t\t\t\t\t\tif (matchCount >= effectiveLimit) {\n\t\t\t\t\t\t\t\t\tmatchLimitReached = true;\n\t\t\t\t\t\t\t\t\tstopChild(true);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run ripgrep: ${error.message}`)));\n\t\t\t\t\t\t});\n\t\t\t\t\t\tchild.on(\"close\", async (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!killedDueToLimit && code !== 0 && code !== 1) {\n\t\t\t\t\t\t\t\tconst errorMsg = stderr.trim() || `ripgrep exited with code ${code}`;\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (matchCount === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: \"No matches found\" }], details: undefined }),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Format matches after streaming finishes so custom readFile() backends can be async.\n\t\t\t\t\t\t\tfor (const match of matches) {\n\t\t\t\t\t\t\t\tif (contextValue === 0 && match.lineText !== undefined) {\n\t\t\t\t\t\t\t\t\tconst relativePath = formatPath(match.filePath);\n\t\t\t\t\t\t\t\t\tconst sanitized = match.lineText\n\t\t\t\t\t\t\t\t\t\t.replace(/\\r\\n/g, \"\\n\")\n\t\t\t\t\t\t\t\t\t\t.replace(/\\r/g, \"\")\n\t\t\t\t\t\t\t\t\t\t.replace(/\\n$/, \"\");\n\t\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\t\toutputLines.push(`${relativePath}:${match.lineNumber}: ${truncatedText}`);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tconst block = await formatBlock(match.filePath, match.lineNumber);\n\t\t\t\t\t\t\t\t\toutputLines.push(...block);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst rawOutput = outputLines.join(\"\\n\");\n\t\t\t\t\t\t\t// Apply byte truncation. There is no line limit here because the match limit already capped rows.\n\t\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet output = truncation.content;\n\t\t\t\t\t\t\tconst details: GrepToolDetails = {};\n\t\t\t\t\t\t\t// Build actionable notices for truncation and match limits.\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (matchLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.matchLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (linesTruncated) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.linesTruncated = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: output }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tsettle(() => reject(err as Error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createGrepTool(cwd: string, options?: GrepToolOptions): AgentTool {\n\treturn wrapToolDefinition(createGrepToolDefinition(cwd, options));\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/grep.js b/dist/core/tools/grep.js new file mode 100644 index 0000000..a8d520b --- /dev/null +++ b/dist/core/tools/grep.js @@ -0,0 +1,304 @@ +import { readFile as fsReadFile, stat as fsStat } from "node:fs/promises"; +import { createInterface } from "node:readline"; +import { Text } from "@earendil-works/pi-tui"; +import { spawn } from "child_process"; +import path from "path"; +import { Type } from "typebox"; +import { keyHint } from "../../modes/interactive/components/keybinding-hints.js"; +import { ensureTool } from "../../utils/tools-manager.js"; +import { resolveToCwd } from "./path-utils.js"; +import { getTextOutput, invalidArgText, shortenPath, str } from "./render-utils.js"; +import { wrapToolDefinition } from "./tool-definition-wrapper.js"; +import { DEFAULT_MAX_BYTES, formatSize, GREP_MAX_LINE_LENGTH, truncateHead, truncateLine, } from "./truncate.js"; +const grepSchema = Type.Object({ + pattern: Type.String({ description: "Search pattern (regex or literal string)" }), + path: Type.Optional(Type.String({ description: "Directory or file to search (default: current directory)" })), + glob: Type.Optional(Type.String({ description: "Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'" })), + ignoreCase: Type.Optional(Type.Boolean({ description: "Case-insensitive search (default: false)" })), + literal: Type.Optional(Type.Boolean({ description: "Treat pattern as literal string instead of regex (default: false)" })), + context: Type.Optional(Type.Number({ description: "Number of lines to show before and after each match (default: 0)" })), + limit: Type.Optional(Type.Number({ description: "Maximum number of matches to return (default: 100)" })), +}); +const DEFAULT_LIMIT = 100; +const defaultGrepOperations = { + isDirectory: async (p) => (await fsStat(p)).isDirectory(), + readFile: (p) => fsReadFile(p, "utf-8"), +}; +function formatGrepCall(args, theme) { + const pattern = str(args?.pattern); + const rawPath = str(args?.path); + const path = rawPath !== null ? shortenPath(rawPath || ".") : null; + const glob = str(args?.glob); + const limit = args?.limit; + const invalidArg = invalidArgText(theme); + let text = theme.fg("toolTitle", theme.bold("grep")) + + " " + + (pattern === null ? invalidArg : theme.fg("accent", `/${pattern || ""}/`)) + + theme.fg("toolOutput", ` in ${path === null ? invalidArg : path}`); + if (glob) + text += theme.fg("toolOutput", ` (${glob})`); + if (limit !== undefined) + text += theme.fg("toolOutput", ` limit ${limit}`); + return text; +} +function formatGrepResult(result, options, theme, showImages) { + const output = getTextOutput(result, showImages).trim(); + let text = ""; + if (output) { + const lines = output.split("\n"); + const maxLines = options.expanded ? lines.length : 15; + const displayLines = lines.slice(0, maxLines); + const remaining = lines.length - maxLines; + text += `\n${displayLines.map((line) => theme.fg("toolOutput", line)).join("\n")}`; + if (remaining > 0) { + text += `${theme.fg("muted", `\n... (${remaining} more lines,`)} ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`; + } + } + const matchLimit = result.details?.matchLimitReached; + const truncation = result.details?.truncation; + const linesTruncated = result.details?.linesTruncated; + if (matchLimit || truncation?.truncated || linesTruncated) { + const warnings = []; + if (matchLimit) + warnings.push(`${matchLimit} matches limit`); + if (truncation?.truncated) + warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`); + if (linesTruncated) + warnings.push("some lines truncated"); + text += `\n${theme.fg("warning", `[Truncated: ${warnings.join(", ")}]`)}`; + } + return text; +} +export function createGrepToolDefinition(cwd, options) { + const customOps = options?.operations; + return { + name: "grep", + label: "grep", + description: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`, + promptSnippet: "Search file contents for patterns (respects .gitignore)", + parameters: grepSchema, + async execute(_toolCallId, { pattern, path: searchDir, glob, ignoreCase, literal, context, limit, }, signal, _onUpdate, _ctx) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(new Error("Operation aborted")); + return; + } + let settled = false; + const settle = (fn) => { + if (!settled) { + settled = true; + fn(); + } + }; + (async () => { + try { + const rgPath = await ensureTool("rg", true); + if (!rgPath) { + settle(() => reject(new Error("ripgrep (rg) is not available and could not be downloaded"))); + return; + } + const searchPath = resolveToCwd(searchDir || ".", cwd); + const ops = customOps ?? defaultGrepOperations; + let isDirectory; + try { + isDirectory = await ops.isDirectory(searchPath); + } + catch { + settle(() => reject(new Error(`Path not found: ${searchPath}`))); + return; + } + const contextValue = context && context > 0 ? context : 0; + const effectiveLimit = Math.max(1, limit ?? DEFAULT_LIMIT); + const formatPath = (filePath) => { + if (isDirectory) { + const relative = path.relative(searchPath, filePath); + if (relative && !relative.startsWith("..")) { + return relative.replace(/\\/g, "/"); + } + } + return path.basename(filePath); + }; + const fileCache = new Map(); + const getFileLines = async (filePath) => { + let lines = fileCache.get(filePath); + if (!lines) { + try { + const content = await ops.readFile(filePath); + lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n"); + } + catch { + lines = []; + } + fileCache.set(filePath, lines); + } + return lines; + }; + const args = ["--json", "--line-number", "--color=never", "--hidden"]; + if (ignoreCase) + args.push("--ignore-case"); + if (literal) + args.push("--fixed-strings"); + if (glob) + args.push("--glob", glob); + args.push("--", pattern, searchPath); + const child = spawn(rgPath, args, { stdio: ["ignore", "pipe", "pipe"] }); + const rl = createInterface({ input: child.stdout }); + let stderr = ""; + let matchCount = 0; + let matchLimitReached = false; + let linesTruncated = false; + let aborted = false; + let killedDueToLimit = false; + const outputLines = []; + const cleanup = () => { + rl.close(); + signal?.removeEventListener("abort", onAbort); + }; + const stopChild = (dueToLimit = false) => { + if (!child.killed) { + killedDueToLimit = dueToLimit; + child.kill(); + } + }; + const onAbort = () => { + aborted = true; + stopChild(); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + child.stderr?.on("data", (chunk) => { + stderr += chunk.toString(); + }); + const formatBlock = async (filePath, lineNumber) => { + const relativePath = formatPath(filePath); + const lines = await getFileLines(filePath); + if (!lines.length) + return [`${relativePath}:${lineNumber}: (unable to read file)`]; + const block = []; + const start = contextValue > 0 ? Math.max(1, lineNumber - contextValue) : lineNumber; + const end = contextValue > 0 ? Math.min(lines.length, lineNumber + contextValue) : lineNumber; + for (let current = start; current <= end; current++) { + const lineText = lines[current - 1] ?? ""; + const sanitized = lineText.replace(/\r/g, ""); + const isMatchLine = current === lineNumber; + // Truncate long lines so grep output stays compact. + const { text: truncatedText, wasTruncated } = truncateLine(sanitized); + if (wasTruncated) + linesTruncated = true; + if (isMatchLine) + block.push(`${relativePath}:${current}: ${truncatedText}`); + else + block.push(`${relativePath}-${current}- ${truncatedText}`); + } + return block; + }; + // Collect matches during streaming, then format them after rg exits. + const matches = []; + rl.on("line", (line) => { + if (!line.trim() || matchCount >= effectiveLimit) + return; + let event; + try { + event = JSON.parse(line); + } + catch { + return; + } + if (event.type === "match") { + matchCount++; + const filePath = event.data?.path?.text; + const lineNumber = event.data?.line_number; + const lineText = event.data?.lines?.text; + if (filePath && typeof lineNumber === "number") + matches.push({ filePath, lineNumber, lineText }); + if (matchCount >= effectiveLimit) { + matchLimitReached = true; + stopChild(true); + } + } + }); + child.on("error", (error) => { + cleanup(); + settle(() => reject(new Error(`Failed to run ripgrep: ${error.message}`))); + }); + child.on("close", async (code) => { + cleanup(); + if (aborted) { + settle(() => reject(new Error("Operation aborted"))); + return; + } + if (!killedDueToLimit && code !== 0 && code !== 1) { + const errorMsg = stderr.trim() || `ripgrep exited with code ${code}`; + settle(() => reject(new Error(errorMsg))); + return; + } + if (matchCount === 0) { + settle(() => resolve({ content: [{ type: "text", text: "No matches found" }], details: undefined })); + return; + } + // Format matches after streaming finishes so custom readFile() backends can be async. + for (const match of matches) { + if (contextValue === 0 && match.lineText !== undefined) { + const relativePath = formatPath(match.filePath); + const sanitized = match.lineText + .replace(/\r\n/g, "\n") + .replace(/\r/g, "") + .replace(/\n$/, ""); + const { text: truncatedText, wasTruncated } = truncateLine(sanitized); + if (wasTruncated) + linesTruncated = true; + outputLines.push(`${relativePath}:${match.lineNumber}: ${truncatedText}`); + } + else { + const block = await formatBlock(match.filePath, match.lineNumber); + outputLines.push(...block); + } + } + const rawOutput = outputLines.join("\n"); + // Apply byte truncation. There is no line limit here because the match limit already capped rows. + const truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER }); + let output = truncation.content; + const details = {}; + // Build actionable notices for truncation and match limits. + const notices = []; + if (matchLimitReached) { + notices.push(`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`); + details.matchLimitReached = effectiveLimit; + } + if (truncation.truncated) { + notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`); + details.truncation = truncation; + } + if (linesTruncated) { + notices.push(`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`); + details.linesTruncated = true; + } + if (notices.length > 0) + output += `\n\n[${notices.join(". ")}]`; + settle(() => resolve({ + content: [{ type: "text", text: output }], + details: Object.keys(details).length > 0 ? details : undefined, + })); + }); + } + catch (err) { + settle(() => reject(err)); + } + })(); + }); + }, + renderCall(args, theme, context) { + const text = context.lastComponent ?? new Text("", 0, 0); + text.setText(formatGrepCall(args, theme)); + return text; + }, + renderResult(result, options, theme, context) { + const text = context.lastComponent ?? new Text("", 0, 0); + text.setText(formatGrepResult(result, options, theme, context.showImages)); + return text; + }, + }; +} +export function createGrepTool(cwd, options) { + return wrapToolDefinition(createGrepToolDefinition(cwd, options)); +} +//# sourceMappingURL=grep.js.map \ No newline at end of file diff --git a/dist/core/tools/grep.js.map b/dist/core/tools/grep.js.map new file mode 100644 index 0000000..fc6ee1e --- /dev/null +++ b/dist/core/tools/grep.js.map @@ -0,0 +1 @@ +{"version":3,"file":"grep.js","sourceRoot":"","sources":["../../../src/core/tools/gr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GAAG,EAAE,CAAC,MAAM,CAAC,GAAY,CAAC,CAAC,CAAC;oBACpC,CAAC;gBAAA,CACD,CAAC,EAAE,CAAC;YAAA,CACL,CAAC,CAAC;QAAA,CACH;QACD,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE;YAChC,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC;YAC1C,OAAO,IAAI,CAAC;QAAA,CACZ;QACD,YAAY,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE;YAC7C,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,MAAa,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;YAClF,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB,EAAgC;IACpG,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAClE","sourcesContent":["import { readFile as fsReadFile, stat as fsStat } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport { spawn } from \"child_process\";\nimport path from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, invalidArgText, shortenPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tformatSize,\n\tGREP_MAX_LINE_LENGTH,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n} from \"./truncate.ts\";\n\nconst grepSchema = Type.Object({\n\tpattern: Type.String({ description: \"Search pattern (regex or literal string)\" }),\n\tpath: Type.Optional(Type.String({ description: \"Directory or file to search (default: current directory)\" })),\n\tglob: Type.Optional(Type.String({ description: \"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'\" })),\n\tignoreCase: Type.Optional(Type.Boolean({ description: \"Case-insensitive search (default: false)\" })),\n\tliteral: Type.Optional(\n\t\tType.Boolean({ description: \"Treat pattern as literal string instead of regex (default: false)\" }),\n\t),\n\tcontext: Type.Optional(\n\t\tType.Number({ description: \"Number of lines to show before and after each match (default: 0)\" }),\n\t),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of matches to return (default: 100)\" })),\n});\n\nexport type GrepToolInput = Static;\nconst DEFAULT_LIMIT = 100;\n\nexport interface GrepToolDetails {\n\ttruncation?: TruncationResult;\n\tmatchLimitReached?: number;\n\tlinesTruncated?: boolean;\n}\n\n/**\n * Pluggable operations for the grep tool.\n * Override these to delegate search to remote systems (for example SSH).\n */\nexport interface GrepOperations {\n\t/** Check if path is a directory. Throws if path does not exist. */\n\tisDirectory: (absolutePath: string) => Promise | boolean;\n\t/** Read file contents for context lines */\n\treadFile: (absolutePath: string) => Promise | string;\n}\n\nconst defaultGrepOperations: GrepOperations = {\n\tisDirectory: async (p) => (await fsStat(p)).isDirectory(),\n\treadFile: (p) => fsReadFile(p, \"utf-8\"),\n};\n\nexport interface GrepToolOptions {\n\t/** Custom operations for grep. Default: local filesystem plus ripgrep */\n\toperations?: GrepOperations;\n}\n\nfunction formatGrepCall(\n\targs: { pattern: string; path?: string; glob?: string; limit?: number } | undefined,\n\ttheme: Theme,\n): string {\n\tconst pattern = str(args?.pattern);\n\tconst rawPath = str(args?.path);\n\tconst path = rawPath !== null ? shortenPath(rawPath || \".\") : null;\n\tconst glob = str(args?.glob);\n\tconst limit = args?.limit;\n\tconst invalidArg = invalidArgText(theme);\n\tlet text =\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"grep\")) +\n\t\t\" \" +\n\t\t(pattern === null ? invalidArg : theme.fg(\"accent\", `/${pattern || \"\"}/`)) +\n\t\ttheme.fg(\"toolOutput\", ` in ${path === null ? invalidArg : path}`);\n\tif (glob) text += theme.fg(\"toolOutput\", ` (${glob})`);\n\tif (limit !== undefined) text += theme.fg(\"toolOutput\", ` limit ${limit}`);\n\treturn text;\n}\n\nfunction formatGrepResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: GrepToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 15;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\tconst matchLimit = result.details?.matchLimitReached;\n\tconst truncation = result.details?.truncation;\n\tconst linesTruncated = result.details?.linesTruncated;\n\tif (matchLimit || truncation?.truncated || linesTruncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (matchLimit) warnings.push(`${matchLimit} matches limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\tif (linesTruncated) warnings.push(\"some lines truncated\");\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nexport function createGrepToolDefinition(\n\tcwd: string,\n\toptions?: GrepToolOptions,\n): ToolDefinition {\n\tconst customOps = options?.operations;\n\treturn {\n\t\tname: \"grep\",\n\t\tlabel: \"grep\",\n\t\tdescription: `Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${DEFAULT_LIMIT} matches or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Long lines are truncated to ${GREP_MAX_LINE_LENGTH} chars.`,\n\t\tpromptSnippet: \"Search file contents for patterns (respects .gitignore)\",\n\t\tparameters: grepSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{\n\t\t\t\tpattern,\n\t\t\t\tpath: searchDir,\n\t\t\t\tglob,\n\t\t\t\tignoreCase,\n\t\t\t\tliteral,\n\t\t\t\tcontext,\n\t\t\t\tlimit,\n\t\t\t}: {\n\t\t\t\tpattern: string;\n\t\t\t\tpath?: string;\n\t\t\t\tglob?: string;\n\t\t\t\tignoreCase?: boolean;\n\t\t\t\tliteral?: boolean;\n\t\t\t\tcontext?: number;\n\t\t\t\tlimit?: number;\n\t\t\t},\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet settled = false;\n\t\t\t\tconst settle = (fn: () => void) => {\n\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tfn();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst rgPath = await ensureTool(\"rg\", true);\n\t\t\t\t\t\tif (!rgPath) {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(\"ripgrep (rg) is not available and could not be downloaded\")));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst searchPath = resolveToCwd(searchDir || \".\", cwd);\n\t\t\t\t\t\tconst ops = customOps ?? defaultGrepOperations;\n\t\t\t\t\t\tlet isDirectory: boolean;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tisDirectory = await ops.isDirectory(searchPath);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Path not found: ${searchPath}`)));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst contextValue = context && context > 0 ? context : 0;\n\t\t\t\t\t\tconst effectiveLimit = Math.max(1, limit ?? DEFAULT_LIMIT);\n\t\t\t\t\t\tconst formatPath = (filePath: string): string => {\n\t\t\t\t\t\t\tif (isDirectory) {\n\t\t\t\t\t\t\t\tconst relative = path.relative(searchPath, filePath);\n\t\t\t\t\t\t\t\tif (relative && !relative.startsWith(\"..\")) {\n\t\t\t\t\t\t\t\t\treturn relative.replace(/\\\\/g, \"/\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn path.basename(filePath);\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst fileCache = new Map();\n\t\t\t\t\t\tconst getFileLines = async (filePath: string): Promise => {\n\t\t\t\t\t\t\tlet lines = fileCache.get(filePath);\n\t\t\t\t\t\t\tif (!lines) {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tconst content = await ops.readFile(filePath);\n\t\t\t\t\t\t\t\t\tlines = content.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\tlines = [];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfileCache.set(filePath, lines);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn lines;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst args: string[] = [\"--json\", \"--line-number\", \"--color=never\", \"--hidden\"];\n\t\t\t\t\t\tif (ignoreCase) args.push(\"--ignore-case\");\n\t\t\t\t\t\tif (literal) args.push(\"--fixed-strings\");\n\t\t\t\t\t\tif (glob) args.push(\"--glob\", glob);\n\t\t\t\t\t\targs.push(\"--\", pattern, searchPath);\n\n\t\t\t\t\t\tconst child = spawn(rgPath, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\t\t\t\tconst rl = createInterface({ input: child.stdout });\n\t\t\t\t\t\tlet stderr = \"\";\n\t\t\t\t\t\tlet matchCount = 0;\n\t\t\t\t\t\tlet matchLimitReached = false;\n\t\t\t\t\t\tlet linesTruncated = false;\n\t\t\t\t\t\tlet aborted = false;\n\t\t\t\t\t\tlet killedDueToLimit = false;\n\t\t\t\t\t\tconst outputLines: string[] = [];\n\n\t\t\t\t\t\tconst cleanup = () => {\n\t\t\t\t\t\t\trl.close();\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst stopChild = (dueToLimit = false) => {\n\t\t\t\t\t\t\tif (!child.killed) {\n\t\t\t\t\t\t\t\tkilledDueToLimit = dueToLimit;\n\t\t\t\t\t\t\t\tchild.kill();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\t\tstopChild();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t\t\tchild.stderr?.on(\"data\", (chunk) => {\n\t\t\t\t\t\t\tstderr += chunk.toString();\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tconst formatBlock = async (filePath: string, lineNumber: number): Promise => {\n\t\t\t\t\t\t\tconst relativePath = formatPath(filePath);\n\t\t\t\t\t\t\tconst lines = await getFileLines(filePath);\n\t\t\t\t\t\t\tif (!lines.length) return [`${relativePath}:${lineNumber}: (unable to read file)`];\n\t\t\t\t\t\t\tconst block: string[] = [];\n\t\t\t\t\t\t\tconst start = contextValue > 0 ? Math.max(1, lineNumber - contextValue) : lineNumber;\n\t\t\t\t\t\t\tconst end = contextValue > 0 ? Math.min(lines.length, lineNumber + contextValue) : lineNumber;\n\t\t\t\t\t\t\tfor (let current = start; current <= end; current++) {\n\t\t\t\t\t\t\t\tconst lineText = lines[current - 1] ?? \"\";\n\t\t\t\t\t\t\t\tconst sanitized = lineText.replace(/\\r/g, \"\");\n\t\t\t\t\t\t\t\tconst isMatchLine = current === lineNumber;\n\t\t\t\t\t\t\t\t// Truncate long lines so grep output stays compact.\n\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\tif (isMatchLine) block.push(`${relativePath}:${current}: ${truncatedText}`);\n\t\t\t\t\t\t\t\telse block.push(`${relativePath}-${current}- ${truncatedText}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn block;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// Collect matches during streaming, then format them after rg exits.\n\t\t\t\t\t\tconst matches: Array<{ filePath: string; lineNumber: number; lineText?: string }> = [];\n\t\t\t\t\t\trl.on(\"line\", (line) => {\n\t\t\t\t\t\t\tif (!line.trim() || matchCount >= effectiveLimit) return;\n\t\t\t\t\t\t\tlet event: any;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tevent = JSON.parse(line);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (event.type === \"match\") {\n\t\t\t\t\t\t\t\tmatchCount++;\n\t\t\t\t\t\t\t\tconst filePath = event.data?.path?.text;\n\t\t\t\t\t\t\t\tconst lineNumber = event.data?.line_number;\n\t\t\t\t\t\t\t\tconst lineText = event.data?.lines?.text;\n\t\t\t\t\t\t\t\tif (filePath && typeof lineNumber === \"number\")\n\t\t\t\t\t\t\t\t\tmatches.push({ filePath, lineNumber, lineText });\n\t\t\t\t\t\t\t\tif (matchCount >= effectiveLimit) {\n\t\t\t\t\t\t\t\t\tmatchLimitReached = true;\n\t\t\t\t\t\t\t\t\tstopChild(true);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tsettle(() => reject(new Error(`Failed to run ripgrep: ${error.message}`)));\n\t\t\t\t\t\t});\n\t\t\t\t\t\tchild.on(\"close\", async (code) => {\n\t\t\t\t\t\t\tcleanup();\n\t\t\t\t\t\t\tif (aborted) {\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(\"Operation aborted\")));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!killedDueToLimit && code !== 0 && code !== 1) {\n\t\t\t\t\t\t\t\tconst errorMsg = stderr.trim() || `ripgrep exited with code ${code}`;\n\t\t\t\t\t\t\t\tsettle(() => reject(new Error(errorMsg)));\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (matchCount === 0) {\n\t\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: \"No matches found\" }], details: undefined }),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Format matches after streaming finishes so custom readFile() backends can be async.\n\t\t\t\t\t\t\tfor (const match of matches) {\n\t\t\t\t\t\t\t\tif (contextValue === 0 && match.lineText !== undefined) {\n\t\t\t\t\t\t\t\t\tconst relativePath = formatPath(match.filePath);\n\t\t\t\t\t\t\t\t\tconst sanitized = match.lineText\n\t\t\t\t\t\t\t\t\t\t.replace(/\\r\\n/g, \"\\n\")\n\t\t\t\t\t\t\t\t\t\t.replace(/\\r/g, \"\")\n\t\t\t\t\t\t\t\t\t\t.replace(/\\n$/, \"\");\n\t\t\t\t\t\t\t\t\tconst { text: truncatedText, wasTruncated } = truncateLine(sanitized);\n\t\t\t\t\t\t\t\t\tif (wasTruncated) linesTruncated = true;\n\t\t\t\t\t\t\t\t\toutputLines.push(`${relativePath}:${match.lineNumber}: ${truncatedText}`);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tconst block = await formatBlock(match.filePath, match.lineNumber);\n\t\t\t\t\t\t\t\t\toutputLines.push(...block);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst rawOutput = outputLines.join(\"\\n\");\n\t\t\t\t\t\t\t// Apply byte truncation. There is no line limit here because the match limit already capped rows.\n\t\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\t\tlet output = truncation.content;\n\t\t\t\t\t\t\tconst details: GrepToolDetails = {};\n\t\t\t\t\t\t\t// Build actionable notices for truncation and match limits.\n\t\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\t\tif (matchLimitReached) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.matchLimitReached = effectiveLimit;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (linesTruncated) {\n\t\t\t\t\t\t\t\tnotices.push(\n\t\t\t\t\t\t\t\t\t`Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read tool to see full lines`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tdetails.linesTruncated = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (notices.length > 0) output += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t\tsettle(() =>\n\t\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: output }],\n\t\t\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tsettle(() => reject(err as Error));\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepCall(args, theme));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatGrepResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createGrepTool(cwd: string, options?: GrepToolOptions): AgentTool {\n\treturn wrapToolDefinition(createGrepToolDefinition(cwd, options));\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/index.d.ts b/dist/core/tools/index.d.ts new file mode 100644 index 0000000..fbf87f9 --- /dev/null +++ b/dist/core/tools/index.d.ts @@ -0,0 +1,40 @@ +export { type BashOperations, type BashSpawnContext, type BashSpawnHook, type BashToolDetails, type BashToolInput, type BashToolOptions, createBashTool, createBashToolDefinition, createLocalBashOperations, } from "./bash.ts"; +export { createEditTool, createEditToolDefinition, type EditOperations, type EditToolDetails, type EditToolInput, type EditToolOptions, } from "./edit.ts"; +export { withFileMutationQueue } from "./file-mutation-queue.ts"; +export { createFindTool, createFindToolDefinition, type FindOperations, type FindToolDetails, type FindToolInput, type FindToolOptions, } from "./find.ts"; +export { createGrepTool, createGrepToolDefinition, type GrepOperations, type GrepToolDetails, type GrepToolInput, type GrepToolOptions, } from "./grep.ts"; +export { createLsTool, createLsToolDefinition, type LsOperations, type LsToolDetails, type LsToolInput, type LsToolOptions, } from "./ls.ts"; +export { createReadTool, createReadToolDefinition, type ReadOperations, type ReadToolDetails, type ReadToolInput, type ReadToolOptions, } from "./read.ts"; +export { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationOptions, type TruncationResult, truncateHead, truncateLine, truncateTail, } from "./truncate.ts"; +export { createWriteTool, createWriteToolDefinition, type WriteOperations, type WriteToolInput, type WriteToolOptions, } from "./write.ts"; +import type { AgentTool } from "@earendil-works/pi-agent-core"; +import type { ToolDefinition } from "../extensions/types.ts"; +import { type BashToolOptions } from "./bash.ts"; +import { type EditToolOptions } from "./edit.ts"; +import { type FindToolOptions } from "./find.ts"; +import { type GrepToolOptions } from "./grep.ts"; +import { type LsToolOptions } from "./ls.ts"; +import { type ReadToolOptions } from "./read.ts"; +import { type WriteToolOptions } from "./write.ts"; +export type Tool = AgentTool; +export type ToolDef = ToolDefinition; +export type ToolName = "read" | "bash" | "edit" | "write" | "grep" | "find" | "ls"; +export declare const allToolNames: Set; +export interface ToolsOptions { + read?: ReadToolOptions; + bash?: BashToolOptions; + write?: WriteToolOptions; + edit?: EditToolOptions; + grep?: GrepToolOptions; + find?: FindToolOptions; + ls?: LsToolOptions; +} +export declare function createToolDefinition(toolName: ToolName, cwd: string, options?: ToolsOptions): ToolDef; +export declare function createTool(toolName: ToolName, cwd: string, options?: ToolsOptions): Tool; +export declare function createCodingToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[]; +export declare function createReadOnlyToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[]; +export declare function createAllToolDefinitions(cwd: string, options?: ToolsOptions): Record; +export declare function createCodingTools(cwd: string, options?: ToolsOptions): Tool[]; +export declare function createReadOnlyTools(cwd: string, options?: ToolsOptions): Tool[]; +export declare function createAllTools(cwd: string, options?: ToolsOptions): Record; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/index.d.ts.map b/dist/core/tools/index.d.ts.map new file mode 100644 index 0000000..0388bdb --- /dev/null +++ b/dist/core/tools/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,cAAc,EACd,wBAAwB,EACxB,yBAAyB,GACzB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,wBAAwB,EACxB,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,GACpB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACN,cAAc,EACd,wBAAwB,EACxB,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,GACpB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,wBAAwB,EACxB,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,GACpB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,YAAY,EACZ,sBAAsB,E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AM,CAAC,QAAQ,EAAE,IAAI,CAAC,CAU1F","sourcesContent":["export {\n\ttype BashOperations,\n\ttype BashSpawnContext,\n\ttype BashSpawnHook,\n\ttype BashToolDetails,\n\ttype BashToolInput,\n\ttype BashToolOptions,\n\tcreateBashTool,\n\tcreateBashToolDefinition,\n\tcreateLocalBashOperations,\n} from \"./bash.ts\";\nexport {\n\tcreateEditTool,\n\tcreateEditToolDefinition,\n\ttype EditOperations,\n\ttype EditToolDetails,\n\ttype EditToolInput,\n\ttype EditToolOptions,\n} from \"./edit.ts\";\nexport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nexport {\n\tcreateFindTool,\n\tcreateFindToolDefinition,\n\ttype FindOperations,\n\ttype FindToolDetails,\n\ttype FindToolInput,\n\ttype FindToolOptions,\n} from \"./find.ts\";\nexport {\n\tcreateGrepTool,\n\tcreateGrepToolDefinition,\n\ttype GrepOperations,\n\ttype GrepToolDetails,\n\ttype GrepToolInput,\n\ttype GrepToolOptions,\n} from \"./grep.ts\";\nexport {\n\tcreateLsTool,\n\tcreateLsToolDefinition,\n\ttype LsOperations,\n\ttype LsToolDetails,\n\ttype LsToolInput,\n\ttype LsToolOptions,\n} from \"./ls.ts\";\nexport {\n\tcreateReadTool,\n\tcreateReadToolDefinition,\n\ttype ReadOperations,\n\ttype ReadToolDetails,\n\ttype ReadToolInput,\n\ttype ReadToolOptions,\n} from \"./read.ts\";\nexport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationOptions,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n\ttruncateTail,\n} from \"./truncate.ts\";\nexport {\n\tcreateWriteTool,\n\tcreateWriteToolDefinition,\n\ttype WriteOperations,\n\ttype WriteToolInput,\n\ttype WriteToolOptions,\n} from \"./write.ts\";\n\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { type BashToolOptions, createBashTool, createBashToolDefinition } from \"./bash.ts\";\nimport { createEditTool, createEditToolDefinition, type EditToolOptions } from \"./edit.ts\";\nimport { createFindTool, createFindToolDefinition, type FindToolOptions } from \"./find.ts\";\nimport { createGrepTool, createGrepToolDefinition, type GrepToolOptions } from \"./grep.ts\";\nimport { createLsTool, createLsToolDefinition, type LsToolOptions } from \"./ls.ts\";\nimport { createReadTool, createReadToolDefinition, type ReadToolOptions } from \"./read.ts\";\nimport { createWriteTool, createWriteToolDefinition, type WriteToolOptions } from \"./write.ts\";\n\nexport type Tool = AgentTool;\nexport type ToolDef = ToolDefinition;\nexport type ToolName = \"read\" | \"bash\" | \"edit\" | \"write\" | \"grep\" | \"find\" | \"ls\";\nexport const allToolNames: Set = new Set([\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\"]);\n\nexport interface ToolsOptions {\n\tread?: ReadToolOptions;\n\tbash?: BashToolOptions;\n\twrite?: WriteToolOptions;\n\tedit?: EditToolOptions;\n\tgrep?: GrepToolOptions;\n\tfind?: FindToolOptions;\n\tls?: LsToolOptions;\n}\n\nexport function createToolDefinition(toolName: ToolName, cwd: string, options?: ToolsOptions): ToolDef {\n\tswitch (toolName) {\n\t\tcase \"read\":\n\t\t\treturn createReadToolDefinition(cwd, options?.read);\n\t\tcase \"bash\":\n\t\t\treturn createBashToolDefinition(cwd, options?.bash);\n\t\tcase \"edit\":\n\t\t\treturn createEditToolDefinition(cwd, options?.edit);\n\t\tcase \"write\":\n\t\t\treturn createWriteToolDefinition(cwd, options?.write);\n\t\tcase \"grep\":\n\t\t\treturn createGrepToolDefinition(cwd, options?.grep);\n\t\tcase \"find\":\n\t\t\treturn createFindToolDefinition(cwd, options?.find);\n\t\tcase \"ls\":\n\t\t\treturn createLsToolDefinition(cwd, options?.ls);\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown tool name: ${toolName}`);\n\t}\n}\n\nexport function createTool(toolName: ToolName, cwd: string, options?: ToolsOptions): Tool {\n\tswitch (toolName) {\n\t\tcase \"read\":\n\t\t\treturn createReadTool(cwd, options?.read);\n\t\tcase \"bash\":\n\t\t\treturn createBashTool(cwd, options?.bash);\n\t\tcase \"edit\":\n\t\t\treturn createEditTool(cwd, options?.edit);\n\t\tcase \"write\":\n\t\t\treturn createWriteTool(cwd, options?.write);\n\t\tcase \"grep\":\n\t\t\treturn createGrepTool(cwd, options?.grep);\n\t\tcase \"find\":\n\t\t\treturn createFindTool(cwd, options?.find);\n\t\tcase \"ls\":\n\t\t\treturn createLsTool(cwd, options?.ls);\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown tool name: ${toolName}`);\n\t}\n}\n\nexport function createCodingToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[] {\n\treturn [\n\t\tcreateReadToolDefinition(cwd, options?.read),\n\t\tcreateBashToolDefinition(cwd, options?.bash),\n\t\tcreateEditToolDefinition(cwd, options?.edit),\n\t\tcreateWriteToolDefinition(cwd, options?.write),\n\t];\n}\n\nexport function createReadOnlyToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[] {\n\treturn [\n\t\tcreateReadToolDefinition(cwd, options?.read),\n\t\tcreateGrepToolDefinition(cwd, options?.grep),\n\t\tcreateFindToolDefinition(cwd, options?.find),\n\t\tcreateLsToolDefinition(cwd, options?.ls),\n\t];\n}\n\nexport function createAllToolDefinitions(cwd: string, options?: ToolsOptions): Record {\n\treturn {\n\t\tread: createReadToolDefinition(cwd, options?.read),\n\t\tbash: createBashToolDefinition(cwd, options?.bash),\n\t\tedit: createEditToolDefinition(cwd, options?.edit),\n\t\twrite: createWriteToolDefinition(cwd, options?.write),\n\t\tgrep: createGrepToolDefinition(cwd, options?.grep),\n\t\tfind: createFindToolDefinition(cwd, options?.find),\n\t\tls: createLsToolDefinition(cwd, options?.ls),\n\t};\n}\n\nexport function createCodingTools(cwd: string, options?: ToolsOptions): Tool[] {\n\treturn [\n\t\tcreateReadTool(cwd, options?.read),\n\t\tcreateBashTool(cwd, options?.bash),\n\t\tcreateEditTool(cwd, options?.edit),\n\t\tcreateWriteTool(cwd, options?.write),\n\t];\n}\n\nexport function createReadOnlyTools(cwd: string, options?: ToolsOptions): Tool[] {\n\treturn [\n\t\tcreateReadTool(cwd, options?.read),\n\t\tcreateGrepTool(cwd, options?.grep),\n\t\tcreateFindTool(cwd, options?.find),\n\t\tcreateLsTool(cwd, options?.ls),\n\t];\n}\n\nexport function createAllTools(cwd: string, options?: ToolsOptions): Record {\n\treturn {\n\t\tread: createReadTool(cwd, options?.read),\n\t\tbash: createBashTool(cwd, options?.bash),\n\t\tedit: createEditTool(cwd, options?.edit),\n\t\twrite: createWriteTool(cwd, options?.write),\n\t\tgrep: createGrepTool(cwd, options?.grep),\n\t\tfind: createFindTool(cwd, options?.find),\n\t\tls: createLsTool(cwd, options?.ls),\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/index.js b/dist/core/tools/index.js new file mode 100644 index 0000000..9bcca72 --- /dev/null +++ b/dist/core/tools/index.js @@ -0,0 +1,112 @@ +export { createBashTool, createBashToolDefinition, createLocalBashOperations, } from "./bash.js"; +export { createEditTool, createEditToolDefinition, } from "./edit.js"; +export { withFileMutationQueue } from "./file-mutation-queue.js"; +export { createFindTool, createFindToolDefinition, } from "./find.js"; +export { createGrepTool, createGrepToolDefinition, } from "./grep.js"; +export { createLsTool, createLsToolDefinition, } from "./ls.js"; +export { createReadTool, createReadToolDefinition, } from "./read.js"; +export { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead, truncateLine, truncateTail, } from "./truncate.js"; +export { createWriteTool, createWriteToolDefinition, } from "./write.js"; +import { createBashTool, createBashToolDefinition } from "./bash.js"; +import { createEditTool, createEditToolDefinition } from "./edit.js"; +import { createFindTool, createFindToolDefinition } from "./find.js"; +import { createGrepTool, createGrepToolDefinition } from "./grep.js"; +import { createLsTool, createLsToolDefinition } from "./ls.js"; +import { createReadTool, createReadToolDefinition } from "./read.js"; +import { createWriteTool, createWriteToolDefinition } from "./write.js"; +export const allToolNames = new Set(["read", "bash", "edit", "write", "grep", "find", "ls"]); +export function createToolDefinition(toolName, cwd, options) { + switch (toolName) { + case "read": + return createReadToolDefinition(cwd, options?.read); + case "bash": + return createBashToolDefinition(cwd, options?.bash); + case "edit": + return createEditToolDefinition(cwd, options?.edit); + case "write": + return createWriteToolDefinition(cwd, options?.write); + case "grep": + return createGrepToolDefinition(cwd, options?.grep); + case "find": + return createFindToolDefinition(cwd, options?.find); + case "ls": + return createLsToolDefinition(cwd, options?.ls); + default: + throw new Error(`Unknown tool name: ${toolName}`); + } +} +export function createTool(toolName, cwd, options) { + switch (toolName) { + case "read": + return createReadTool(cwd, options?.read); + case "bash": + return createBashTool(cwd, options?.bash); + case "edit": + return createEditTool(cwd, options?.edit); + case "write": + return createWriteTool(cwd, options?.write); + case "grep": + return createGrepTool(cwd, options?.grep); + case "find": + return createFindTool(cwd, options?.find); + case "ls": + return createLsTool(cwd, options?.ls); + default: + throw new Error(`Unknown tool name: ${toolName}`); + } +} +export function createCodingToolDefinitions(cwd, options) { + return [ + createReadToolDefinition(cwd, options?.read), + createBashToolDefinition(cwd, options?.bash), + createEditToolDefinition(cwd, options?.edit), + createWriteToolDefinition(cwd, options?.write), + ]; +} +export function createReadOnlyToolDefinitions(cwd, options) { + return [ + createReadToolDefinition(cwd, options?.read), + createGrepToolDefinition(cwd, options?.grep), + createFindToolDefinition(cwd, options?.find), + createLsToolDefinition(cwd, options?.ls), + ]; +} +export function createAllToolDefinitions(cwd, options) { + return { + read: createReadToolDefinition(cwd, options?.read), + bash: createBashToolDefinition(cwd, options?.bash), + edit: createEditToolDefinition(cwd, options?.edit), + write: createWriteToolDefinition(cwd, options?.write), + grep: createGrepToolDefinition(cwd, options?.grep), + find: createFindToolDefinition(cwd, options?.find), + ls: createLsToolDefinition(cwd, options?.ls), + }; +} +export function createCodingTools(cwd, options) { + return [ + createReadTool(cwd, options?.read), + createBashTool(cwd, options?.bash), + createEditTool(cwd, options?.edit), + createWriteTool(cwd, options?.write), + ]; +} +export function createReadOnlyTools(cwd, options) { + return [ + createReadTool(cwd, options?.read), + createGrepTool(cwd, options?.grep), + createFindTool(cwd, options?.find), + createLsTool(cwd, options?.ls), + ]; +} +export function createAllTools(cwd, options) { + return { + read: createReadTool(cwd, options?.read), + bash: createBashTool(cwd, options?.bash), + edit: createEditTool(cwd, options?.edit), + write: createWriteTool(cwd, options?.write), + grep: createGrepTool(cwd, options?.grep), + find: createFindTool(cwd, options?.find), + ls: createLsTool(cwd, options?.ls), + }; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/core/tools/index.js.map b/dist/core/tools/index.js.map new file mode 100644 index 0000000..21d2a11 --- /dev/null +++ b/dist/core/tools/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAON,cAAc,EACd,wBAAwB,EACxB,yBAAyB,GACzB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,wBAAwB,GAKxB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACN,cAAc,EACd,wBAAwB,GAKxB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,cAAc,EACd,wBAAwB,GAKxB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,YAAY,EACZ,sBAAsB,GAKtB,MAAM,SAAS,CAAC;AACjB,OAAO,EACN,cAAc,EACd,wBAAwB,GAKxB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,iBAAiB,EACjB,iBAAiB,EACjB,UAAU,EAGV,YAAY,EACZ,YAAY,EACZ,YAAY,GACZ,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,eAAe,EACf,yBAAyB,GAIzB,MAAM,YAAY,CAAC;AAIpB,OAAO,EAAwB,cAAc,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AAC3F,OAAO,EAAE,cAA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,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC;QAClC,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC;QAClC,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC;QAClC,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC;KAC9B,CAAC;AAAA,CACF;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAsB,EAA0B;IAC3F,OAAO;QACN,IAAI,EAAE,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC;QACxC,IAAI,EAAE,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC;QACxC,IAAI,EAAE,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC;QACxC,KAAK,EAAE,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,CAAC;QAC3C,IAAI,EAAE,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC;QACxC,IAAI,EAAE,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC;QACxC,EAAE,EAAE,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC;KAClC,CAAC;AAAA,CACF","sourcesContent":["export {\n\ttype BashOperations,\n\ttype BashSpawnContext,\n\ttype BashSpawnHook,\n\ttype BashToolDetails,\n\ttype BashToolInput,\n\ttype BashToolOptions,\n\tcreateBashTool,\n\tcreateBashToolDefinition,\n\tcreateLocalBashOperations,\n} from \"./bash.ts\";\nexport {\n\tcreateEditTool,\n\tcreateEditToolDefinition,\n\ttype EditOperations,\n\ttype EditToolDetails,\n\ttype EditToolInput,\n\ttype EditToolOptions,\n} from \"./edit.ts\";\nexport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nexport {\n\tcreateFindTool,\n\tcreateFindToolDefinition,\n\ttype FindOperations,\n\ttype FindToolDetails,\n\ttype FindToolInput,\n\ttype FindToolOptions,\n} from \"./find.ts\";\nexport {\n\tcreateGrepTool,\n\tcreateGrepToolDefinition,\n\ttype GrepOperations,\n\ttype GrepToolDetails,\n\ttype GrepToolInput,\n\ttype GrepToolOptions,\n} from \"./grep.ts\";\nexport {\n\tcreateLsTool,\n\tcreateLsToolDefinition,\n\ttype LsOperations,\n\ttype LsToolDetails,\n\ttype LsToolInput,\n\ttype LsToolOptions,\n} from \"./ls.ts\";\nexport {\n\tcreateReadTool,\n\tcreateReadToolDefinition,\n\ttype ReadOperations,\n\ttype ReadToolDetails,\n\ttype ReadToolInput,\n\ttype ReadToolOptions,\n} from \"./read.ts\";\nexport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tformatSize,\n\ttype TruncationOptions,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n\ttruncateTail,\n} from \"./truncate.ts\";\nexport {\n\tcreateWriteTool,\n\tcreateWriteToolDefinition,\n\ttype WriteOperations,\n\ttype WriteToolInput,\n\ttype WriteToolOptions,\n} from \"./write.ts\";\n\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { ToolDefinition } from \"../extensions/types.ts\";\nimport { type BashToolOptions, createBashTool, createBashToolDefinition } from \"./bash.ts\";\nimport { createEditTool, createEditToolDefinition, type EditToolOptions } from \"./edit.ts\";\nimport { createFindTool, createFindToolDefinition, type FindToolOptions } from \"./find.ts\";\nimport { createGrepTool, createGrepToolDefinition, type GrepToolOptions } from \"./grep.ts\";\nimport { createLsTool, createLsToolDefinition, type LsToolOptions } from \"./ls.ts\";\nimport { createReadTool, createReadToolDefinition, type ReadToolOptions } from \"./read.ts\";\nimport { createWriteTool, createWriteToolDefinition, type WriteToolOptions } from \"./write.ts\";\n\nexport type Tool = AgentTool;\nexport type ToolDef = ToolDefinition;\nexport type ToolName = \"read\" | \"bash\" | \"edit\" | \"write\" | \"grep\" | \"find\" | \"ls\";\nexport const allToolNames: Set = new Set([\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\"]);\n\nexport interface ToolsOptions {\n\tread?: ReadToolOptions;\n\tbash?: BashToolOptions;\n\twrite?: WriteToolOptions;\n\tedit?: EditToolOptions;\n\tgrep?: GrepToolOptions;\n\tfind?: FindToolOptions;\n\tls?: LsToolOptions;\n}\n\nexport function createToolDefinition(toolName: ToolName, cwd: string, options?: ToolsOptions): ToolDef {\n\tswitch (toolName) {\n\t\tcase \"read\":\n\t\t\treturn createReadToolDefinition(cwd, options?.read);\n\t\tcase \"bash\":\n\t\t\treturn createBashToolDefinition(cwd, options?.bash);\n\t\tcase \"edit\":\n\t\t\treturn createEditToolDefinition(cwd, options?.edit);\n\t\tcase \"write\":\n\t\t\treturn createWriteToolDefinition(cwd, options?.write);\n\t\tcase \"grep\":\n\t\t\treturn createGrepToolDefinition(cwd, options?.grep);\n\t\tcase \"find\":\n\t\t\treturn createFindToolDefinition(cwd, options?.find);\n\t\tcase \"ls\":\n\t\t\treturn createLsToolDefinition(cwd, options?.ls);\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown tool name: ${toolName}`);\n\t}\n}\n\nexport function createTool(toolName: ToolName, cwd: string, options?: ToolsOptions): Tool {\n\tswitch (toolName) {\n\t\tcase \"read\":\n\t\t\treturn createReadTool(cwd, options?.read);\n\t\tcase \"bash\":\n\t\t\treturn createBashTool(cwd, options?.bash);\n\t\tcase \"edit\":\n\t\t\treturn createEditTool(cwd, options?.edit);\n\t\tcase \"write\":\n\t\t\treturn createWriteTool(cwd, options?.write);\n\t\tcase \"grep\":\n\t\t\treturn createGrepTool(cwd, options?.grep);\n\t\tcase \"find\":\n\t\t\treturn createFindTool(cwd, options?.find);\n\t\tcase \"ls\":\n\t\t\treturn createLsTool(cwd, options?.ls);\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown tool name: ${toolName}`);\n\t}\n}\n\nexport function createCodingToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[] {\n\treturn [\n\t\tcreateReadToolDefinition(cwd, options?.read),\n\t\tcreateBashToolDefinition(cwd, options?.bash),\n\t\tcreateEditToolDefinition(cwd, options?.edit),\n\t\tcreateWriteToolDefinition(cwd, options?.write),\n\t];\n}\n\nexport function createReadOnlyToolDefinitions(cwd: string, options?: ToolsOptions): ToolDef[] {\n\treturn [\n\t\tcreateReadToolDefinition(cwd, options?.read),\n\t\tcreateGrepToolDefinition(cwd, options?.grep),\n\t\tcreateFindToolDefinition(cwd, options?.find),\n\t\tcreateLsToolDefinition(cwd, options?.ls),\n\t];\n}\n\nexport function createAllToolDefinitions(cwd: string, options?: ToolsOptions): Record {\n\treturn {\n\t\tread: createReadToolDefinition(cwd, options?.read),\n\t\tbash: createBashToolDefinition(cwd, options?.bash),\n\t\tedit: createEditToolDefinition(cwd, options?.edit),\n\t\twrite: createWriteToolDefinition(cwd, options?.write),\n\t\tgrep: createGrepToolDefinition(cwd, options?.grep),\n\t\tfind: createFindToolDefinition(cwd, options?.find),\n\t\tls: createLsToolDefinition(cwd, options?.ls),\n\t};\n}\n\nexport function createCodingTools(cwd: string, options?: ToolsOptions): Tool[] {\n\treturn [\n\t\tcreateReadTool(cwd, options?.read),\n\t\tcreateBashTool(cwd, options?.bash),\n\t\tcreateEditTool(cwd, options?.edit),\n\t\tcreateWriteTool(cwd, options?.write),\n\t];\n}\n\nexport function createReadOnlyTools(cwd: string, options?: ToolsOptions): Tool[] {\n\treturn [\n\t\tcreateReadTool(cwd, options?.read),\n\t\tcreateGrepTool(cwd, options?.grep),\n\t\tcreateFindTool(cwd, options?.find),\n\t\tcreateLsTool(cwd, options?.ls),\n\t];\n}\n\nexport function createAllTools(cwd: string, options?: ToolsOptions): Record {\n\treturn {\n\t\tread: createReadTool(cwd, options?.read),\n\t\tbash: createBashTool(cwd, options?.bash),\n\t\tedit: createEditTool(cwd, options?.edit),\n\t\twrite: createWriteTool(cwd, options?.write),\n\t\tgrep: createGrepTool(cwd, options?.grep),\n\t\tfind: createFindTool(cwd, options?.find),\n\t\tls: createLsTool(cwd, options?.ls),\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/ls.d.ts b/dist/core/tools/ls.d.ts new file mode 100644 index 0000000..f9de5f3 --- /dev/null +++ b/dist/core/tools/ls.d.ts @@ -0,0 +1,37 @@ +import type { AgentTool } from "@earendil-works/pi-agent-core"; +import { type Static, Type } from "typebox"; +import type { ToolDefinition } from "../extensions/types.ts"; +import { type TruncationResult } from "./truncate.ts"; +declare const lsSchema: Type.TObject<{ + path: Type.TOptional; + limit: Type.TOptional; +}>; +export type LsToolInput = Static; +export interface LsToolDetails { + truncation?: TruncationResult; + entryLimitReached?: number; +} +/** + * Pluggable operations for the ls tool. + * Override these to delegate directory listing to remote systems (for example SSH). + */ +export interface LsOperations { + /** Check if path exists */ + exists: (absolutePath: string) => Promise | boolean; + /** Get file or directory stats. Throws if not found. */ + stat: (absolutePath: string) => Promise<{ + isDirectory: () => boolean; + }> | { + isDirectory: () => boolean; + }; + /** Read directory entries */ + readdir: (absolutePath: string) => Promise | string[]; +} +export interface LsToolOptions { + /** Custom operations for directory listing. Default: local filesystem */ + operations?: LsOperations; +} +export declare function createLsToolDefinition(cwd: string, options?: LsToolOptions): ToolDefinition; +export declare function createLsTool(cwd: string, options?: LsToolOptions): AgentTool; +export {}; +//# sourceMappingURL=ls.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/ls.d.ts.map b/dist/core/tools/ls.d.ts.map new file mode 100644 index 0000000..e19319e --- /dev/null +++ b/dist/core/tools/ls.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ls.d.ts","sourceRoot":"","sources":["../../../src/core/tools/ls.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAG/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAItF,OAAO,EAAiC,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEnG,QAAA,MAAM,QAAQ;;;EAGZ,CAAC;AAEH,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,OAAO,QAAQ,CAAC,CAAC;AAIlD,MAAM,WAAW,aAAa;IAC7B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC5B,2BAA2B;IAC3B,MAAM,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IAC7D,wDAAwD;IACxD,IAAI,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC;QAAE,WAAW,EAAE,MAAM,OAAO,CAAA;KAAE,CAAC,GAAG;QAAE,WAAW,EAAE,MAAM,OAAO,CAAA;KAAE,CAAC;IACzG,6BAA6B;IAC7B,OAAO,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC;CAChE;AAQD,MAAM,WAAW,aAAa;IAC7B,yEAAyE;IACzE,UAAU,CAAC,EAAE,YAAY,CAAC;CAC1B;AA6CD,wBAAgB,sBAAsB,CACrC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,aAAa,GACrB,cAAc,CAAC,OAAO,QAAQ,EAAE,aAAa,GAAG,SAAS,CAAC,CA2H5D;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,SAAS,CAAC,OAAO,QAAQ,CAAC,CAE7F","sourcesContent":["import { readdir as fsReaddir, stat as fsStat } from \"node:fs/promises\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport nodePath from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { pathExists, resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, renderToolPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst lsSchema = Type.Object({\n\tpath: Type.Optional(Type.String({ description: \"Directory to list (default: current directory)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of entries to return (default: 500)\" })),\n});\n\nexport type LsToolInput = Static;\n\nconst DEFAULT_LIMIT = 500;\n\nexport interface LsToolDetails {\n\ttruncation?: TruncationResult;\n\tentryLimitReached?: number;\n}\n\n/**\n * Pluggable operations for the ls tool.\n * Override these to delegate directory listing to remote systems (for example SSH).\n */\nexport interface LsOperations {\n\t/** Check if path exists */\n\texists: (absolutePath: string) => Promise | boolean;\n\t/** Get file or directory stats. Throws if not found. */\n\tstat: (absolutePath: string) => Promise<{ isDirectory: () => boolean }> | { isDirectory: () => boolean };\n\t/** Read directory entries */\n\treaddir: (absolutePath: string) => Promise | string[];\n}\n\nconst defaultLsOperations: LsOperations = {\n\texists: pathExists,\n\tstat: fsStat,\n\treaddir: fsReaddir,\n};\n\nexport interface LsToolOptions {\n\t/** Custom operations for directory listing. Default: local filesystem */\n\toperations?: LsOperations;\n}\n\nfunction formatLsCall(args: { path?: string; limit?: number } | undefined, theme: Theme, cwd: string): string {\n\tconst limit = args?.limit;\n\tconst pathDisplay = renderToolPath(str(args?.path), theme, cwd, { emptyFallback: \".\" });\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"ls\"))} ${pathDisplay}`;\n\tif (limit !== undefined) {\n\t\ttext += theme.fg(\"toolOutput\", ` (limit ${limit})`);\n\t}\n\treturn text;\n}\n\nfunction formatLsResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: LsToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\tconst entryLimit = result.details?.entryLimitReached;\n\tconst truncation = result.details?.truncation;\n\tif (entryLimit || truncation?.truncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (entryLimit) warnings.push(`${entryLimit} entries limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nexport function createLsToolDefinition(\n\tcwd: string,\n\toptions?: LsToolOptions,\n): ToolDefinition {\n\tconst ops = options?.operations ?? defaultLsOperations;\n\treturn {\n\t\tname: \"ls\",\n\t\tlabel: \"ls\",\n\t\tdescription: `List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${DEFAULT_LIMIT} entries or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,\n\t\tpromptSnippet: \"List directory contents\",\n\t\tparameters: lsSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, limit }: { path?: string; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst onAbort = () => reject(new Error(\"Operation aborted\"));\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst dirPath = resolveToCwd(path || \".\", cwd);\n\t\t\t\t\t\tconst effectiveLimit = limit ?? DEFAULT_LIMIT;\n\n\t\t\t\t\t\t// Check if path exists.\n\t\t\t\t\t\tif (!(await ops.exists(dirPath))) {\n\t\t\t\t\t\t\treject(new Error(`Path not found: ${dirPath}`));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Check if path is a directory.\n\t\t\t\t\t\tconst stat = await ops.stat(dirPath);\n\t\t\t\t\t\tif (!stat.isDirectory()) {\n\t\t\t\t\t\t\treject(new Error(`Not a directory: ${dirPath}`));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Read directory entries.\n\t\t\t\t\t\tlet entries: string[];\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tentries = await ops.readdir(dirPath);\n\t\t\t\t\t\t} catch (e: any) {\n\t\t\t\t\t\t\treject(new Error(`Cannot read directory: ${e.message}`));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Sort alphabetically, case-insensitive.\n\t\t\t\t\t\tentries.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));\n\n\t\t\t\t\t\t// Format entries with directory indicators.\n\t\t\t\t\t\tconst results: string[] = [];\n\t\t\t\t\t\tlet entryLimitReached = false;\n\t\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\t\tif (results.length >= effectiveLimit) {\n\t\t\t\t\t\t\t\tentryLimitReached = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst fullPath = nodePath.join(dirPath, entry);\n\t\t\t\t\t\t\tlet suffix = \"\";\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst entryStat = await ops.stat(fullPath);\n\t\t\t\t\t\t\t\tif (entryStat.isDirectory()) suffix = \"/\";\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// Skip entries we cannot stat.\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tresults.push(entry + suffix);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\n\t\t\t\t\t\tif (results.length === 0) {\n\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: \"(empty directory)\" }], details: undefined });\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst rawOutput = results.join(\"\\n\");\n\t\t\t\t\t\t// Apply byte truncation. There is no separate line limit because entry count is already capped.\n\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\tlet output = truncation.content;\n\t\t\t\t\t\tconst details: LsToolDetails = {};\n\t\t\t\t\t\t// Build actionable notices for truncation and entry limits.\n\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\tif (entryLimitReached) {\n\t\t\t\t\t\t\tnotices.push(`${effectiveLimit} entries limit reached. Use limit=${effectiveLimit * 2} for more`);\n\t\t\t\t\t\t\tdetails.entryLimitReached = effectiveLimit;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (notices.length > 0) {\n\t\t\t\t\t\t\toutput += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: output }],\n\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (e: any) {\n\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\treject(e);\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatLsCall(args, theme, context.cwd));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatLsResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createLsTool(cwd: string, options?: LsToolOptions): AgentTool {\n\treturn wrapToolDefinition(createLsToolDefinition(cwd, options));\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/ls.js b/dist/core/tools/ls.js new file mode 100644 index 0000000..8e0a39b --- /dev/null +++ b/dist/core/tools/ls.js @@ -0,0 +1,167 @@ +import { readdir as fsReaddir, stat as fsStat } from "node:fs/promises"; +import { Text } from "@earendil-works/pi-tui"; +import nodePath from "path"; +import { Type } from "typebox"; +import { keyHint } from "../../modes/interactive/components/keybinding-hints.js"; +import { pathExists, resolveToCwd } from "./path-utils.js"; +import { getTextOutput, renderToolPath, str } from "./render-utils.js"; +import { wrapToolDefinition } from "./tool-definition-wrapper.js"; +import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js"; +const lsSchema = Type.Object({ + path: Type.Optional(Type.String({ description: "Directory to list (default: current directory)" })), + limit: Type.Optional(Type.Number({ description: "Maximum number of entries to return (default: 500)" })), +}); +const DEFAULT_LIMIT = 500; +const defaultLsOperations = { + exists: pathExists, + stat: fsStat, + readdir: fsReaddir, +}; +function formatLsCall(args, theme, cwd) { + const limit = args?.limit; + const pathDisplay = renderToolPath(str(args?.path), theme, cwd, { emptyFallback: "." }); + let text = `${theme.fg("toolTitle", theme.bold("ls"))} ${pathDisplay}`; + if (limit !== undefined) { + text += theme.fg("toolOutput", ` (limit ${limit})`); + } + return text; +} +function formatLsResult(result, options, theme, showImages) { + const output = getTextOutput(result, showImages).trim(); + let text = ""; + if (output) { + const lines = output.split("\n"); + const maxLines = options.expanded ? lines.length : 20; + const displayLines = lines.slice(0, maxLines); + const remaining = lines.length - maxLines; + text += `\n${displayLines.map((line) => theme.fg("toolOutput", line)).join("\n")}`; + if (remaining > 0) { + text += `${theme.fg("muted", `\n... (${remaining} more lines,`)} ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`; + } + } + const entryLimit = result.details?.entryLimitReached; + const truncation = result.details?.truncation; + if (entryLimit || truncation?.truncated) { + const warnings = []; + if (entryLimit) + warnings.push(`${entryLimit} entries limit`); + if (truncation?.truncated) + warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`); + text += `\n${theme.fg("warning", `[Truncated: ${warnings.join(", ")}]`)}`; + } + return text; +} +export function createLsToolDefinition(cwd, options) { + const ops = options?.operations ?? defaultLsOperations; + return { + name: "ls", + label: "ls", + description: `List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${DEFAULT_LIMIT} entries or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`, + promptSnippet: "List directory contents", + parameters: lsSchema, + async execute(_toolCallId, { path, limit }, signal, _onUpdate, _ctx) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(new Error("Operation aborted")); + return; + } + const onAbort = () => reject(new Error("Operation aborted")); + signal?.addEventListener("abort", onAbort, { once: true }); + (async () => { + try { + const dirPath = resolveToCwd(path || ".", cwd); + const effectiveLimit = limit ?? DEFAULT_LIMIT; + // Check if path exists. + if (!(await ops.exists(dirPath))) { + reject(new Error(`Path not found: ${dirPath}`)); + return; + } + // Check if path is a directory. + const stat = await ops.stat(dirPath); + if (!stat.isDirectory()) { + reject(new Error(`Not a directory: ${dirPath}`)); + return; + } + // Read directory entries. + let entries; + try { + entries = await ops.readdir(dirPath); + } + catch (e) { + reject(new Error(`Cannot read directory: ${e.message}`)); + return; + } + // Sort alphabetically, case-insensitive. + entries.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())); + // Format entries with directory indicators. + const results = []; + let entryLimitReached = false; + for (const entry of entries) { + if (results.length >= effectiveLimit) { + entryLimitReached = true; + break; + } + const fullPath = nodePath.join(dirPath, entry); + let suffix = ""; + try { + const entryStat = await ops.stat(fullPath); + if (entryStat.isDirectory()) + suffix = "/"; + } + catch { + // Skip entries we cannot stat. + continue; + } + results.push(entry + suffix); + } + signal?.removeEventListener("abort", onAbort); + if (results.length === 0) { + resolve({ content: [{ type: "text", text: "(empty directory)" }], details: undefined }); + return; + } + const rawOutput = results.join("\n"); + // Apply byte truncation. There is no separate line limit because entry count is already capped. + const truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER }); + let output = truncation.content; + const details = {}; + // Build actionable notices for truncation and entry limits. + const notices = []; + if (entryLimitReached) { + notices.push(`${effectiveLimit} entries limit reached. Use limit=${effectiveLimit * 2} for more`); + details.entryLimitReached = effectiveLimit; + } + if (truncation.truncated) { + notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`); + details.truncation = truncation; + } + if (notices.length > 0) { + output += `\n\n[${notices.join(". ")}]`; + } + resolve({ + content: [{ type: "text", text: output }], + details: Object.keys(details).length > 0 ? details : undefined, + }); + } + catch (e) { + signal?.removeEventListener("abort", onAbort); + reject(e); + } + })(); + }); + }, + renderCall(args, theme, context) { + const text = context.lastComponent ?? new Text("", 0, 0); + text.setText(formatLsCall(args, theme, context.cwd)); + return text; + }, + renderResult(result, options, theme, context) { + const text = context.lastComponent ?? new Text("", 0, 0); + text.setText(formatLsResult(result, options, theme, context.showImages)); + return text; + }, + }; +} +export function createLsTool(cwd, options) { + return wrapToolDefinition(createLsToolDefinition(cwd, options)); +} +//# sourceMappingURL=ls.js.map \ No newline at end of file diff --git a/dist/core/tools/ls.js.map b/dist/core/tools/ls.js.map new file mode 100644 index 0000000..d565657 --- /dev/null +++ b/dist/core/tools/ls.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ls.js","sourceRoot":"","sources":["../../../src/core/tools/ls.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,IAAI,IAAI,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAExE,OAAO,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAC9C,OAAO,QAAQ,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AAGjF,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAyB,YAAY,EAAE,MAAM,eAAe,CAAC;AAEnG,MAAM,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC;IAC5B,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,gDAAgD,EAAE,CAAC,CAAC;IACnG,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,oDAAoD,EAAE,CAAC,CAAC;CACxG,CAAC,CAAC;AAIH,MAAM,aAAa,GAAG,G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,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS;yBAC9D,CAAC,CAAC;oBACJ,CAAC;oBAAC,OAAO,CAAM,EAAE,CAAC;wBACjB,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;wBAC9C,MAAM,CAAC,CAAC,CAAC,CAAC;oBACX,CAAC;gBAAA,CACD,CAAC,EAAE,CAAC;YAAA,CACL,CAAC,CAAC;QAAA,CACH;QACD,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE;YAChC,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;YACrD,OAAO,IAAI,CAAC;QAAA,CACZ;QACD,YAAY,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE;YAC7C,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,MAAa,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;YAChF,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,YAAY,CAAC,GAAW,EAAE,OAAuB,EAA8B;IAC9F,OAAO,kBAAkB,CAAC,sBAAsB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAChE","sourcesContent":["import { readdir as fsReaddir, stat as fsStat } from \"node:fs/promises\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport nodePath from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { pathExists, resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, renderToolPath, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst lsSchema = Type.Object({\n\tpath: Type.Optional(Type.String({ description: \"Directory to list (default: current directory)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of entries to return (default: 500)\" })),\n});\n\nexport type LsToolInput = Static;\n\nconst DEFAULT_LIMIT = 500;\n\nexport interface LsToolDetails {\n\ttruncation?: TruncationResult;\n\tentryLimitReached?: number;\n}\n\n/**\n * Pluggable operations for the ls tool.\n * Override these to delegate directory listing to remote systems (for example SSH).\n */\nexport interface LsOperations {\n\t/** Check if path exists */\n\texists: (absolutePath: string) => Promise | boolean;\n\t/** Get file or directory stats. Throws if not found. */\n\tstat: (absolutePath: string) => Promise<{ isDirectory: () => boolean }> | { isDirectory: () => boolean };\n\t/** Read directory entries */\n\treaddir: (absolutePath: string) => Promise | string[];\n}\n\nconst defaultLsOperations: LsOperations = {\n\texists: pathExists,\n\tstat: fsStat,\n\treaddir: fsReaddir,\n};\n\nexport interface LsToolOptions {\n\t/** Custom operations for directory listing. Default: local filesystem */\n\toperations?: LsOperations;\n}\n\nfunction formatLsCall(args: { path?: string; limit?: number } | undefined, theme: Theme, cwd: string): string {\n\tconst limit = args?.limit;\n\tconst pathDisplay = renderToolPath(str(args?.path), theme, cwd, { emptyFallback: \".\" });\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"ls\"))} ${pathDisplay}`;\n\tif (limit !== undefined) {\n\t\ttext += theme.fg(\"toolOutput\", ` (limit ${limit})`);\n\t}\n\treturn text;\n}\n\nfunction formatLsResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: LsToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 20;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\tconst entryLimit = result.details?.entryLimitReached;\n\tconst truncation = result.details?.truncation;\n\tif (entryLimit || truncation?.truncated) {\n\t\tconst warnings: string[] = [];\n\t\tif (entryLimit) warnings.push(`${entryLimit} entries limit`);\n\t\tif (truncation?.truncated) warnings.push(`${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit`);\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${warnings.join(\", \")}]`)}`;\n\t}\n\treturn text;\n}\n\nexport function createLsToolDefinition(\n\tcwd: string,\n\toptions?: LsToolOptions,\n): ToolDefinition {\n\tconst ops = options?.operations ?? defaultLsOperations;\n\treturn {\n\t\tname: \"ls\",\n\t\tlabel: \"ls\",\n\t\tdescription: `List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${DEFAULT_LIMIT} entries or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first).`,\n\t\tpromptSnippet: \"List directory contents\",\n\t\tparameters: lsSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, limit }: { path?: string; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst onAbort = () => reject(new Error(\"Operation aborted\"));\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst dirPath = resolveToCwd(path || \".\", cwd);\n\t\t\t\t\t\tconst effectiveLimit = limit ?? DEFAULT_LIMIT;\n\n\t\t\t\t\t\t// Check if path exists.\n\t\t\t\t\t\tif (!(await ops.exists(dirPath))) {\n\t\t\t\t\t\t\treject(new Error(`Path not found: ${dirPath}`));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Check if path is a directory.\n\t\t\t\t\t\tconst stat = await ops.stat(dirPath);\n\t\t\t\t\t\tif (!stat.isDirectory()) {\n\t\t\t\t\t\t\treject(new Error(`Not a directory: ${dirPath}`));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Read directory entries.\n\t\t\t\t\t\tlet entries: string[];\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tentries = await ops.readdir(dirPath);\n\t\t\t\t\t\t} catch (e: any) {\n\t\t\t\t\t\t\treject(new Error(`Cannot read directory: ${e.message}`));\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Sort alphabetically, case-insensitive.\n\t\t\t\t\t\tentries.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));\n\n\t\t\t\t\t\t// Format entries with directory indicators.\n\t\t\t\t\t\tconst results: string[] = [];\n\t\t\t\t\t\tlet entryLimitReached = false;\n\t\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\t\tif (results.length >= effectiveLimit) {\n\t\t\t\t\t\t\t\tentryLimitReached = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst fullPath = nodePath.join(dirPath, entry);\n\t\t\t\t\t\t\tlet suffix = \"\";\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst entryStat = await ops.stat(fullPath);\n\t\t\t\t\t\t\t\tif (entryStat.isDirectory()) suffix = \"/\";\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// Skip entries we cannot stat.\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tresults.push(entry + suffix);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\n\t\t\t\t\t\tif (results.length === 0) {\n\t\t\t\t\t\t\tresolve({ content: [{ type: \"text\", text: \"(empty directory)\" }], details: undefined });\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst rawOutput = results.join(\"\\n\");\n\t\t\t\t\t\t// Apply byte truncation. There is no separate line limit because entry count is already capped.\n\t\t\t\t\t\tconst truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER });\n\t\t\t\t\t\tlet output = truncation.content;\n\t\t\t\t\t\tconst details: LsToolDetails = {};\n\t\t\t\t\t\t// Build actionable notices for truncation and entry limits.\n\t\t\t\t\t\tconst notices: string[] = [];\n\t\t\t\t\t\tif (entryLimitReached) {\n\t\t\t\t\t\t\tnotices.push(`${effectiveLimit} entries limit reached. Use limit=${effectiveLimit * 2} for more`);\n\t\t\t\t\t\t\tdetails.entryLimitReached = effectiveLimit;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\t\t\tnotices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);\n\t\t\t\t\t\t\tdetails.truncation = truncation;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (notices.length > 0) {\n\t\t\t\t\t\t\toutput += `\\n\\n[${notices.join(\". \")}]`;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: output }],\n\t\t\t\t\t\t\tdetails: Object.keys(details).length > 0 ? details : undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (e: any) {\n\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\treject(e);\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatLsCall(args, theme, context.cwd));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatLsResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createLsTool(cwd: string, options?: LsToolOptions): AgentTool {\n\treturn wrapToolDefinition(createLsToolDefinition(cwd, options));\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/output-accumulator.d.ts b/dist/core/tools/output-accumulator.d.ts new file mode 100644 index 0000000..fbd581f --- /dev/null +++ b/dist/core/tools/output-accumulator.d.ts @@ -0,0 +1,52 @@ +import { type TruncationResult } from "./truncate.ts"; +export interface OutputAccumulatorOptions { + maxLines?: number; + maxBytes?: number; + tempFilePrefix?: string; +} +export interface OutputSnapshot { + content: string; + truncation: TruncationResult; + fullOutputPath?: string; +} +/** + * Incrementally tracks streaming output with bounded memory. + * + * Appends decode chunks with a streaming UTF-8 decoder, keeps only a decoded + * tail for display snapshots, and opens a temp file when the full output needs + * to be preserved. + */ +export declare class OutputAccumulator { + private readonly maxLines; + private readonly maxBytes; + private readonly maxRollingBytes; + private readonly tempFilePrefix; + private readonly decoder; + private rawChunks; + private tailText; + private tailBytes; + private tailStartsAtLineBoundary; + private totalRawBytes; + private totalDecodedBytes; + private completedLines; + private totalLines; + private currentLineBytes; + private hasOpenLine; + private finished; + private tempFilePath; + private tempFileStream; + constructor(options?: OutputAccumulatorOptions); + append(data: Buffer): void; + finish(): void; + snapshot(options?: { + persistIfTruncated?: boolean; + }): OutputSnapshot; + closeTempFile(): Promise; + getLastLineBytes(): number; + private appendDecodedText; + private trimTail; + private getSnapshotText; + private shouldUseTempFile; + private ensureTempFile; +} +//# sourceMappingURL=output-accumulator.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/output-accumulator.d.ts.map b/dist/core/tools/output-accumulator.d.ts.map new file mode 100644 index 0000000..ada29b2 --- /dev/null +++ b/dist/core/tools/output-accumulator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"output-accumulator.d.ts","sourceRoot":"","sources":["../../../src/core/tools/output-accumulator.ts"],"names":[],"mappings":"AAIA,OAAO,EAAwC,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAE1G,MAAM,WAAW,wBAAwB;IACxC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,cAAc;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,gBAAgB,CAAC;IAC7B,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAWD;;;;;;GAMG;AACH,qBAAa,iBAAiB;IAC7B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IACzC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAS;IACxC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAE7C,OAAO,CAAC,SAAS,CAAgB;IACjC,OAAO,CAAC,QAAQ,CAAM;IACtB,OAAO,CAAC,SAAS,CAAK;IACtB,OAAO,CAAC,wBAAwB,CAAQ;IACxC,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,iBAAiB,CAAK;IAC9B,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,gBAAgB,CAAK;IAC7B,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,QAAQ,CAAS;IAEzB,OAAO,CAAC,YAAY,CAAqB;IACzC,OAAO,CAAC,cAAc,CAA0B;IAEhD,YAAY,OAAO,GAAE,wBAA6B,EAKjD;IAED,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAczB;IAED,MAAM,IAAI,IAAI,CASb;IAED,QAAQ,CAAC,OAAO,GAAE;QAAE,kBAAkB,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,cAAc,CA4BvE;IAEK,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC,CAqBnC;IAED,gBAAgB,IAAI,MAAM,CAEzB;IAED,OAAO,CAAC,iBAAiB;IA+BzB,OAAO,CAAC,QAAQ;IAiBhB,OAAO,CAAC,eAAe;IASvB,OAAO,CAAC,iBAAiB;IAMzB,OAAO,CAAC,cAAc;CAWtB","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { createWriteStream, type WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type TruncationResult, truncateTail } from \"./truncate.ts\";\n\nexport interface OutputAccumulatorOptions {\n\tmaxLines?: number;\n\tmaxBytes?: number;\n\ttempFilePrefix?: string;\n}\n\nexport interface OutputSnapshot {\n\tcontent: string;\n\ttruncation: TruncationResult;\n\tfullOutputPath?: string;\n}\n\nfunction defaultTempFilePath(prefix: string): string {\n\tconst id = randomBytes(8).toString(\"hex\");\n\treturn join(tmpdir(), `${prefix}-${id}.log`);\n}\n\nfunction byteLength(text: string): number {\n\treturn Buffer.byteLength(text, \"utf-8\");\n}\n\n/**\n * Incrementally tracks streaming output with bounded memory.\n *\n * Appends decode chunks with a streaming UTF-8 decoder, keeps only a decoded\n * tail for display snapshots, and opens a temp file when the full output needs\n * to be preserved.\n */\nexport class OutputAccumulator {\n\tprivate readonly maxLines: number;\n\tprivate readonly maxBytes: number;\n\tprivate readonly maxRollingBytes: number;\n\tprivate readonly tempFilePrefix: string;\n\tprivate readonly decoder = new TextDecoder();\n\n\tprivate rawChunks: Buffer[] = [];\n\tprivate tailText = \"\";\n\tprivate tailBytes = 0;\n\tprivate tailStartsAtLineBoundary = true;\n\tprivate totalRawBytes = 0;\n\tprivate totalDecodedBytes = 0;\n\tprivate completedLines = 0;\n\tprivate totalLines = 0;\n\tprivate currentLineBytes = 0;\n\tprivate hasOpenLine = false;\n\tprivate finished = false;\n\n\tprivate tempFilePath: string | undefined;\n\tprivate tempFileStream: WriteStream | undefined;\n\n\tconstructor(options: OutputAccumulatorOptions = {}) {\n\t\tthis.maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\t\tthis.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\t\tthis.maxRollingBytes = Math.max(this.maxBytes * 2, 1);\n\t\tthis.tempFilePrefix = options.tempFilePrefix ?? \"pi-output\";\n\t}\n\n\tappend(data: Buffer): void {\n\t\tif (this.finished) {\n\t\t\tthrow new Error(\"Cannot append to a finished output accumulator\");\n\t\t}\n\n\t\tthis.totalRawBytes += data.length;\n\t\tthis.appendDecodedText(this.decoder.decode(data, { stream: true }));\n\n\t\tif (this.tempFileStream || this.shouldUseTempFile()) {\n\t\t\tthis.ensureTempFile();\n\t\t\tthis.tempFileStream?.write(data);\n\t\t} else if (data.length > 0) {\n\t\t\tthis.rawChunks.push(data);\n\t\t}\n\t}\n\n\tfinish(): void {\n\t\tif (this.finished) {\n\t\t\treturn;\n\t\t}\n\t\tthis.finished = true;\n\t\tthis.appendDecodedText(this.decoder.decode());\n\t\tif (this.shouldUseTempFile()) {\n\t\t\tthis.ensureTempFile();\n\t\t}\n\t}\n\n\tsnapshot(options: { persistIfTruncated?: boolean } = {}): OutputSnapshot {\n\t\tconst tailTruncation = truncateTail(this.getSnapshotText(), {\n\t\t\tmaxLines: this.maxLines,\n\t\t\tmaxBytes: this.maxBytes,\n\t\t});\n\t\tconst truncated = this.totalLines > this.maxLines || this.totalDecodedBytes > this.maxBytes;\n\t\tconst truncatedBy = truncated\n\t\t\t? (tailTruncation.truncatedBy ?? (this.totalDecodedBytes > this.maxBytes ? \"bytes\" : \"lines\"))\n\t\t\t: null;\n\t\tconst truncation: TruncationResult = {\n\t\t\t...tailTruncation,\n\t\t\ttruncated,\n\t\t\ttruncatedBy,\n\t\t\ttotalLines: this.totalLines,\n\t\t\ttotalBytes: this.totalDecodedBytes,\n\t\t\tmaxLines: this.maxLines,\n\t\t\tmaxBytes: this.maxBytes,\n\t\t};\n\n\t\tif (options.persistIfTruncated && truncation.truncated) {\n\t\t\tthis.ensureTempFile();\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: truncation.content,\n\t\t\ttruncation,\n\t\t\tfullOutputPath: this.tempFilePath,\n\t\t};\n\t}\n\n\tasync closeTempFile(): Promise {\n\t\tif (!this.tempFileStream) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst stream = this.tempFileStream;\n\t\tthis.tempFileStream = undefined;\n\n\t\tawait new Promise((resolve, reject) => {\n\t\t\tconst onError = (error: Error) => {\n\t\t\t\tstream.off(\"finish\", onFinish);\n\t\t\t\treject(error);\n\t\t\t};\n\t\t\tconst onFinish = () => {\n\t\t\t\tstream.off(\"error\", onError);\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\tstream.once(\"error\", onError);\n\t\t\tstream.once(\"finish\", onFinish);\n\t\t\tstream.end();\n\t\t});\n\t}\n\n\tgetLastLineBytes(): number {\n\t\treturn this.currentLineBytes;\n\t}\n\n\tprivate appendDecodedText(text: string): void {\n\t\tif (text.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst bytes = byteLength(text);\n\t\tthis.totalDecodedBytes += bytes;\n\t\tthis.tailText += text;\n\t\tthis.tailBytes += bytes;\n\t\tif (this.tailBytes > this.maxRollingBytes * 2) {\n\t\t\tthis.trimTail();\n\t\t}\n\n\t\tlet newlines = 0;\n\t\tlet lastNewline = -1;\n\t\tfor (let i = text.indexOf(\"\\n\"); i !== -1; i = text.indexOf(\"\\n\", i + 1)) {\n\t\t\tnewlines++;\n\t\t\tlastNewline = i;\n\t\t}\n\t\tif (newlines === 0) {\n\t\t\tthis.currentLineBytes += bytes;\n\t\t\tthis.hasOpenLine = true;\n\t\t} else {\n\t\t\tthis.completedLines += newlines;\n\t\t\tconst tail = text.slice(lastNewline + 1);\n\t\t\tthis.currentLineBytes = byteLength(tail);\n\t\t\tthis.hasOpenLine = tail.length > 0;\n\t\t}\n\t\tthis.totalLines = this.completedLines + (this.hasOpenLine ? 1 : 0);\n\t}\n\n\tprivate trimTail(): void {\n\t\tconst buffer = Buffer.from(this.tailText, \"utf-8\");\n\t\tif (buffer.length <= this.maxRollingBytes) {\n\t\t\tthis.tailBytes = buffer.length;\n\t\t\treturn;\n\t\t}\n\n\t\tlet start = buffer.length - this.maxRollingBytes;\n\t\twhile (start < buffer.length && (buffer[start] & 0xc0) === 0x80) {\n\t\t\tstart++;\n\t\t}\n\n\t\tthis.tailStartsAtLineBoundary = start === 0 ? this.tailStartsAtLineBoundary : buffer[start - 1] === 0x0a;\n\t\tthis.tailText = buffer.subarray(start).toString(\"utf-8\");\n\t\tthis.tailBytes = byteLength(this.tailText);\n\t}\n\n\tprivate getSnapshotText(): string {\n\t\tif (this.tailStartsAtLineBoundary) {\n\t\t\treturn this.tailText;\n\t\t}\n\n\t\tconst firstNewline = this.tailText.indexOf(\"\\n\");\n\t\treturn firstNewline === -1 ? this.tailText : this.tailText.slice(firstNewline + 1);\n\t}\n\n\tprivate shouldUseTempFile(): boolean {\n\t\treturn (\n\t\t\tthis.totalRawBytes > this.maxBytes || this.totalDecodedBytes > this.maxBytes || this.totalLines > this.maxLines\n\t\t);\n\t}\n\n\tprivate ensureTempFile(): void {\n\t\tif (this.tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tthis.tempFilePath = defaultTempFilePath(this.tempFilePrefix);\n\t\tthis.tempFileStream = createWriteStream(this.tempFilePath);\n\t\tfor (const chunk of this.rawChunks) {\n\t\t\tthis.tempFileStream.write(chunk);\n\t\t}\n\t\tthis.rawChunks = [];\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/output-accumulator.js b/dist/core/tools/output-accumulator.js new file mode 100644 index 0000000..7241668 --- /dev/null +++ b/dist/core/tools/output-accumulator.js @@ -0,0 +1,184 @@ +import { randomBytes } from "node:crypto"; +import { createWriteStream } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, truncateTail } from "./truncate.js"; +function defaultTempFilePath(prefix) { + const id = randomBytes(8).toString("hex"); + return join(tmpdir(), `${prefix}-${id}.log`); +} +function byteLength(text) { + return Buffer.byteLength(text, "utf-8"); +} +/** + * Incrementally tracks streaming output with bounded memory. + * + * Appends decode chunks with a streaming UTF-8 decoder, keeps only a decoded + * tail for display snapshots, and opens a temp file when the full output needs + * to be preserved. + */ +export class OutputAccumulator { + maxLines; + maxBytes; + maxRollingBytes; + tempFilePrefix; + decoder = new TextDecoder(); + rawChunks = []; + tailText = ""; + tailBytes = 0; + tailStartsAtLineBoundary = true; + totalRawBytes = 0; + totalDecodedBytes = 0; + completedLines = 0; + totalLines = 0; + currentLineBytes = 0; + hasOpenLine = false; + finished = false; + tempFilePath; + tempFileStream; + constructor(options = {}) { + this.maxLines = options.maxLines ?? DEFAULT_MAX_LINES; + this.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES; + this.maxRollingBytes = Math.max(this.maxBytes * 2, 1); + this.tempFilePrefix = options.tempFilePrefix ?? "pi-output"; + } + append(data) { + if (this.finished) { + throw new Error("Cannot append to a finished output accumulator"); + } + this.totalRawBytes += data.length; + this.appendDecodedText(this.decoder.decode(data, { stream: true })); + if (this.tempFileStream || this.shouldUseTempFile()) { + this.ensureTempFile(); + this.tempFileStream?.write(data); + } + else if (data.length > 0) { + this.rawChunks.push(data); + } + } + finish() { + if (this.finished) { + return; + } + this.finished = true; + this.appendDecodedText(this.decoder.decode()); + if (this.shouldUseTempFile()) { + this.ensureTempFile(); + } + } + snapshot(options = {}) { + const tailTruncation = truncateTail(this.getSnapshotText(), { + maxLines: this.maxLines, + maxBytes: this.maxBytes, + }); + const truncated = this.totalLines > this.maxLines || this.totalDecodedBytes > this.maxBytes; + const truncatedBy = truncated + ? (tailTruncation.truncatedBy ?? (this.totalDecodedBytes > this.maxBytes ? "bytes" : "lines")) + : null; + const truncation = { + ...tailTruncation, + truncated, + truncatedBy, + totalLines: this.totalLines, + totalBytes: this.totalDecodedBytes, + maxLines: this.maxLines, + maxBytes: this.maxBytes, + }; + if (options.persistIfTruncated && truncation.truncated) { + this.ensureTempFile(); + } + return { + content: truncation.content, + truncation, + fullOutputPath: this.tempFilePath, + }; + } + async closeTempFile() { + if (!this.tempFileStream) { + return; + } + const stream = this.tempFileStream; + this.tempFileStream = undefined; + await new Promise((resolve, reject) => { + const onError = (error) => { + stream.off("finish", onFinish); + reject(error); + }; + const onFinish = () => { + stream.off("error", onError); + resolve(); + }; + stream.once("error", onError); + stream.once("finish", onFinish); + stream.end(); + }); + } + getLastLineBytes() { + return this.currentLineBytes; + } + appendDecodedText(text) { + if (text.length === 0) { + return; + } + const bytes = byteLength(text); + this.totalDecodedBytes += bytes; + this.tailText += text; + this.tailBytes += bytes; + if (this.tailBytes > this.maxRollingBytes * 2) { + this.trimTail(); + } + let newlines = 0; + let lastNewline = -1; + for (let i = text.indexOf("\n"); i !== -1; i = text.indexOf("\n", i + 1)) { + newlines++; + lastNewline = i; + } + if (newlines === 0) { + this.currentLineBytes += bytes; + this.hasOpenLine = true; + } + else { + this.completedLines += newlines; + const tail = text.slice(lastNewline + 1); + this.currentLineBytes = byteLength(tail); + this.hasOpenLine = tail.length > 0; + } + this.totalLines = this.completedLines + (this.hasOpenLine ? 1 : 0); + } + trimTail() { + const buffer = Buffer.from(this.tailText, "utf-8"); + if (buffer.length <= this.maxRollingBytes) { + this.tailBytes = buffer.length; + return; + } + let start = buffer.length - this.maxRollingBytes; + while (start < buffer.length && (buffer[start] & 0xc0) === 0x80) { + start++; + } + this.tailStartsAtLineBoundary = start === 0 ? this.tailStartsAtLineBoundary : buffer[start - 1] === 0x0a; + this.tailText = buffer.subarray(start).toString("utf-8"); + this.tailBytes = byteLength(this.tailText); + } + getSnapshotText() { + if (this.tailStartsAtLineBoundary) { + return this.tailText; + } + const firstNewline = this.tailText.indexOf("\n"); + return firstNewline === -1 ? this.tailText : this.tailText.slice(firstNewline + 1); + } + shouldUseTempFile() { + return (this.totalRawBytes > this.maxBytes || this.totalDecodedBytes > this.maxBytes || this.totalLines > this.maxLines); + } + ensureTempFile() { + if (this.tempFilePath) { + return; + } + this.tempFilePath = defaultTempFilePath(this.tempFilePrefix); + this.tempFileStream = createWriteStream(this.tempFilePath); + for (const chunk of this.rawChunks) { + this.tempFileStream.write(chunk); + } + this.rawChunks = []; + } +} +//# sourceMappingURL=output-accumulator.js.map \ No newline at end of file diff --git a/dist/core/tools/output-accumulator.js.map b/dist/core/tools/output-accumulator.js.map new file mode 100644 index 0000000..82a1969 --- /dev/null +++ b/dist/core/tools/output-accumulator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"output-accumulator.js","sourceRoot":"","sources":["../../../src/core/tools/output-accumulator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAoB,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,MAAM,E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to\";\nimport { createWriteStream, type WriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type TruncationResult, truncateTail } from \"./truncate.ts\";\n\nexport interface OutputAccumulatorOptions {\n\tmaxLines?: number;\n\tmaxBytes?: number;\n\ttempFilePrefix?: string;\n}\n\nexport interface OutputSnapshot {\n\tcontent: string;\n\ttruncation: TruncationResult;\n\tfullOutputPath?: string;\n}\n\nfunction defaultTempFilePath(prefix: string): string {\n\tconst id = randomBytes(8).toString(\"hex\");\n\treturn join(tmpdir(), `${prefix}-${id}.log`);\n}\n\nfunction byteLength(text: string): number {\n\treturn Buffer.byteLength(text, \"utf-8\");\n}\n\n/**\n * Incrementally tracks streaming output with bounded memory.\n *\n * Appends decode chunks with a streaming UTF-8 decoder, keeps only a decoded\n * tail for display snapshots, and opens a temp file when the full output needs\n * to be preserved.\n */\nexport class OutputAccumulator {\n\tprivate readonly maxLines: number;\n\tprivate readonly maxBytes: number;\n\tprivate readonly maxRollingBytes: number;\n\tprivate readonly tempFilePrefix: string;\n\tprivate readonly decoder = new TextDecoder();\n\n\tprivate rawChunks: Buffer[] = [];\n\tprivate tailText = \"\";\n\tprivate tailBytes = 0;\n\tprivate tailStartsAtLineBoundary = true;\n\tprivate totalRawBytes = 0;\n\tprivate totalDecodedBytes = 0;\n\tprivate completedLines = 0;\n\tprivate totalLines = 0;\n\tprivate currentLineBytes = 0;\n\tprivate hasOpenLine = false;\n\tprivate finished = false;\n\n\tprivate tempFilePath: string | undefined;\n\tprivate tempFileStream: WriteStream | undefined;\n\n\tconstructor(options: OutputAccumulatorOptions = {}) {\n\t\tthis.maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\t\tthis.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\t\tthis.maxRollingBytes = Math.max(this.maxBytes * 2, 1);\n\t\tthis.tempFilePrefix = options.tempFilePrefix ?? \"pi-output\";\n\t}\n\n\tappend(data: Buffer): void {\n\t\tif (this.finished) {\n\t\t\tthrow new Error(\"Cannot append to a finished output accumulator\");\n\t\t}\n\n\t\tthis.totalRawBytes += data.length;\n\t\tthis.appendDecodedText(this.decoder.decode(data, { stream: true }));\n\n\t\tif (this.tempFileStream || this.shouldUseTempFile()) {\n\t\t\tthis.ensureTempFile();\n\t\t\tthis.tempFileStream?.write(data);\n\t\t} else if (data.length > 0) {\n\t\t\tthis.rawChunks.push(data);\n\t\t}\n\t}\n\n\tfinish(): void {\n\t\tif (this.finished) {\n\t\t\treturn;\n\t\t}\n\t\tthis.finished = true;\n\t\tthis.appendDecodedText(this.decoder.decode());\n\t\tif (this.shouldUseTempFile()) {\n\t\t\tthis.ensureTempFile();\n\t\t}\n\t}\n\n\tsnapshot(options: { persistIfTruncated?: boolean } = {}): OutputSnapshot {\n\t\tconst tailTruncation = truncateTail(this.getSnapshotText(), {\n\t\t\tmaxLines: this.maxLines,\n\t\t\tmaxBytes: this.maxBytes,\n\t\t});\n\t\tconst truncated = this.totalLines > this.maxLines || this.totalDecodedBytes > this.maxBytes;\n\t\tconst truncatedBy = truncated\n\t\t\t? (tailTruncation.truncatedBy ?? (this.totalDecodedBytes > this.maxBytes ? \"bytes\" : \"lines\"))\n\t\t\t: null;\n\t\tconst truncation: TruncationResult = {\n\t\t\t...tailTruncation,\n\t\t\ttruncated,\n\t\t\ttruncatedBy,\n\t\t\ttotalLines: this.totalLines,\n\t\t\ttotalBytes: this.totalDecodedBytes,\n\t\t\tmaxLines: this.maxLines,\n\t\t\tmaxBytes: this.maxBytes,\n\t\t};\n\n\t\tif (options.persistIfTruncated && truncation.truncated) {\n\t\t\tthis.ensureTempFile();\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: truncation.content,\n\t\t\ttruncation,\n\t\t\tfullOutputPath: this.tempFilePath,\n\t\t};\n\t}\n\n\tasync closeTempFile(): Promise {\n\t\tif (!this.tempFileStream) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst stream = this.tempFileStream;\n\t\tthis.tempFileStream = undefined;\n\n\t\tawait new Promise((resolve, reject) => {\n\t\t\tconst onError = (error: Error) => {\n\t\t\t\tstream.off(\"finish\", onFinish);\n\t\t\t\treject(error);\n\t\t\t};\n\t\t\tconst onFinish = () => {\n\t\t\t\tstream.off(\"error\", onError);\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\tstream.once(\"error\", onError);\n\t\t\tstream.once(\"finish\", onFinish);\n\t\t\tstream.end();\n\t\t});\n\t}\n\n\tgetLastLineBytes(): number {\n\t\treturn this.currentLineBytes;\n\t}\n\n\tprivate appendDecodedText(text: string): void {\n\t\tif (text.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst bytes = byteLength(text);\n\t\tthis.totalDecodedBytes += bytes;\n\t\tthis.tailText += text;\n\t\tthis.tailBytes += bytes;\n\t\tif (this.tailBytes > this.maxRollingBytes * 2) {\n\t\t\tthis.trimTail();\n\t\t}\n\n\t\tlet newlines = 0;\n\t\tlet lastNewline = -1;\n\t\tfor (let i = text.indexOf(\"\\n\"); i !== -1; i = text.indexOf(\"\\n\", i + 1)) {\n\t\t\tnewlines++;\n\t\t\tlastNewline = i;\n\t\t}\n\t\tif (newlines === 0) {\n\t\t\tthis.currentLineBytes += bytes;\n\t\t\tthis.hasOpenLine = true;\n\t\t} else {\n\t\t\tthis.completedLines += newlines;\n\t\t\tconst tail = text.slice(lastNewline + 1);\n\t\t\tthis.currentLineBytes = byteLength(tail);\n\t\t\tthis.hasOpenLine = tail.length > 0;\n\t\t}\n\t\tthis.totalLines = this.completedLines + (this.hasOpenLine ? 1 : 0);\n\t}\n\n\tprivate trimTail(): void {\n\t\tconst buffer = Buffer.from(this.tailText, \"utf-8\");\n\t\tif (buffer.length <= this.maxRollingBytes) {\n\t\t\tthis.tailBytes = buffer.length;\n\t\t\treturn;\n\t\t}\n\n\t\tlet start = buffer.length - this.maxRollingBytes;\n\t\twhile (start < buffer.length && (buffer[start] & 0xc0) === 0x80) {\n\t\t\tstart++;\n\t\t}\n\n\t\tthis.tailStartsAtLineBoundary = start === 0 ? this.tailStartsAtLineBoundary : buffer[start - 1] === 0x0a;\n\t\tthis.tailText = buffer.subarray(start).toString(\"utf-8\");\n\t\tthis.tailBytes = byteLength(this.tailText);\n\t}\n\n\tprivate getSnapshotText(): string {\n\t\tif (this.tailStartsAtLineBoundary) {\n\t\t\treturn this.tailText;\n\t\t}\n\n\t\tconst firstNewline = this.tailText.indexOf(\"\\n\");\n\t\treturn firstNewline === -1 ? this.tailText : this.tailText.slice(firstNewline + 1);\n\t}\n\n\tprivate shouldUseTempFile(): boolean {\n\t\treturn (\n\t\t\tthis.totalRawBytes > this.maxBytes || this.totalDecodedBytes > this.maxBytes || this.totalLines > this.maxLines\n\t\t);\n\t}\n\n\tprivate ensureTempFile(): void {\n\t\tif (this.tempFilePath) {\n\t\t\treturn;\n\t\t}\n\t\tthis.tempFilePath = defaultTempFilePath(this.tempFilePrefix);\n\t\tthis.tempFileStream = createWriteStream(this.tempFilePath);\n\t\tfor (const chunk of this.rawChunks) {\n\t\t\tthis.tempFileStream.write(chunk);\n\t\t}\n\t\tthis.rawChunks = [];\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/path-utils.d.ts b/dist/core/tools/path-utils.d.ts new file mode 100644 index 0000000..5df8b6b --- /dev/null +++ b/dist/core/tools/path-utils.d.ts @@ -0,0 +1,10 @@ +export declare function pathExists(filePath: string): Promise; +export declare function expandPath(filePath: string): string; +/** + * Resolve a path relative to the given cwd. + * Handles ~ expansion and absolute paths. + */ +export declare function resolveToCwd(filePath: string, cwd: string): string; +export declare function resolveReadPath(filePath: string, cwd: string): string; +export declare function resolveReadPathAsync(filePath: string, cwd: string): Promise; +//# sourceMappingURL=path-utils.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/path-utils.d.ts.map b/dist/core/tools/path-utils.d.ts.map new file mode 100644 index 0000000..7ce15b7 --- /dev/null +++ b/dist/core/tools/path-utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"path-utils.d.ts","sourceRoot":"","sources":["../../../src/core/tools/path-utils.ts"],"names":[],"mappings":"AA8BA,wBAAsB,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAOnE;AAED,wBAAgB,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEnD;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAElE;AAED,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAgCrE;AAED,wBAAsB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAgCzF","sourcesContent":["import { accessSync, constants } from \"node:fs\";\nimport { access } from \"node:fs/promises\";\nimport { normalizePath, resolvePath } from \"../../utils/paths.ts\";\n\nconst NARROW_NO_BREAK_SPACE = \"\\u202F\";\n\nfunction tryMacOSScreenshotPath(filePath: string): string {\n\treturn filePath.replace(/ (AM|PM)\\./gi, `${NARROW_NO_BREAK_SPACE}$1.`);\n}\n\nfunction tryNFDVariant(filePath: string): string {\n\t// macOS stores filenames in NFD (decomposed) form, try converting user input to NFD\n\treturn filePath.normalize(\"NFD\");\n}\n\nfunction tryCurlyQuoteVariant(filePath: string): string {\n\t// macOS uses U+2019 (right single quotation mark) in screenshot names like \"Capture d'écran\"\n\t// Users typically type U+0027 (straight apostrophe)\n\treturn filePath.replace(/'/g, \"\\u2019\");\n}\n\nfunction fileExists(filePath: string): boolean {\n\ttry {\n\t\taccessSync(filePath, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport async function pathExists(filePath: string): Promise {\n\ttry {\n\t\tawait access(filePath, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function expandPath(filePath: string): string {\n\treturn normalizePath(filePath, { normalizeUnicodeSpaces: true, stripAtPrefix: true });\n}\n\n/**\n * Resolve a path relative to the given cwd.\n * Handles ~ expansion and absolute paths.\n */\nexport function resolveToCwd(filePath: string, cwd: string): string {\n\treturn resolvePath(filePath, cwd, { normalizeUnicodeSpaces: true, stripAtPrefix: true });\n}\n\nexport function resolveReadPath(filePath: string, cwd: string): string {\n\tconst resolved = resolveToCwd(filePath, cwd);\n\n\tif (fileExists(resolved)) {\n\t\treturn resolved;\n\t}\n\n\t// Try macOS AM/PM variant (narrow no-break space before AM/PM)\n\tconst amPmVariant = tryMacOSScreenshotPath(resolved);\n\tif (amPmVariant !== resolved && fileExists(amPmVariant)) {\n\t\treturn amPmVariant;\n\t}\n\n\t// Try NFD variant (macOS stores filenames in NFD form)\n\tconst nfdVariant = tryNFDVariant(resolved);\n\tif (nfdVariant !== resolved && fileExists(nfdVariant)) {\n\t\treturn nfdVariant;\n\t}\n\n\t// Try curly quote variant (macOS uses U+2019 in screenshot names)\n\tconst curlyVariant = tryCurlyQuoteVariant(resolved);\n\tif (curlyVariant !== resolved && fileExists(curlyVariant)) {\n\t\treturn curlyVariant;\n\t}\n\n\t// Try combined NFD + curly quote (for French macOS screenshots like \"Capture d'écran\")\n\tconst nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);\n\tif (nfdCurlyVariant !== resolved && fileExists(nfdCurlyVariant)) {\n\t\treturn nfdCurlyVariant;\n\t}\n\n\treturn resolved;\n}\n\nexport async function resolveReadPathAsync(filePath: string, cwd: string): Promise {\n\tconst resolved = resolveToCwd(filePath, cwd);\n\n\tif (await pathExists(resolved)) {\n\t\treturn resolved;\n\t}\n\n\t// Try macOS AM/PM variant (narrow no-break space before AM/PM)\n\tconst amPmVariant = tryMacOSScreenshotPath(resolved);\n\tif (amPmVariant !== resolved && (await pathExists(amPmVariant))) {\n\t\treturn amPmVariant;\n\t}\n\n\t// Try NFD variant (macOS stores filenames in NFD form)\n\tconst nfdVariant = tryNFDVariant(resolved);\n\tif (nfdVariant !== resolved && (await pathExists(nfdVariant))) {\n\t\treturn nfdVariant;\n\t}\n\n\t// Try curly quote variant (macOS uses U+2019 in screenshot names)\n\tconst curlyVariant = tryCurlyQuoteVariant(resolved);\n\tif (curlyVariant !== resolved && (await pathExists(curlyVariant))) {\n\t\treturn curlyVariant;\n\t}\n\n\t// Try combined NFD + curly quote (for French macOS screenshots like \"Capture d'écran\")\n\tconst nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);\n\tif (nfdCurlyVariant !== resolved && (await pathExists(nfdCurlyVariant))) {\n\t\treturn nfdCurlyVariant;\n\t}\n\n\treturn resolved;\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/path-utils.js b/dist/core/tools/path-utils.js new file mode 100644 index 0000000..47382b5 --- /dev/null +++ b/dist/core/tools/path-utils.js @@ -0,0 +1,99 @@ +import { accessSync, constants } from "node:fs"; +import { access } from "node:fs/promises"; +import { normalizePath, resolvePath } from "../../utils/paths.js"; +const NARROW_NO_BREAK_SPACE = "\u202F"; +function tryMacOSScreenshotPath(filePath) { + return filePath.replace(/ (AM|PM)\./gi, `${NARROW_NO_BREAK_SPACE}$1.`); +} +function tryNFDVariant(filePath) { + // macOS stores filenames in NFD (decomposed) form, try converting user input to NFD + return filePath.normalize("NFD"); +} +function tryCurlyQuoteVariant(filePath) { + // macOS uses U+2019 (right single quotation mark) in screenshot names like "Capture d'écran" + // Users typically type U+0027 (straight apostrophe) + return filePath.replace(/'/g, "\u2019"); +} +function fileExists(filePath) { + try { + accessSync(filePath, constants.F_OK); + return true; + } + catch { + return false; + } +} +export async function pathExists(filePath) { + try { + await access(filePath, constants.F_OK); + return true; + } + catch { + return false; + } +} +export function expandPath(filePath) { + return normalizePath(filePath, { normalizeUnicodeSpaces: true, stripAtPrefix: true }); +} +/** + * Resolve a path relative to the given cwd. + * Handles ~ expansion and absolute paths. + */ +export function resolveToCwd(filePath, cwd) { + return resolvePath(filePath, cwd, { normalizeUnicodeSpaces: true, stripAtPrefix: true }); +} +export function resolveReadPath(filePath, cwd) { + const resolved = resolveToCwd(filePath, cwd); + if (fileExists(resolved)) { + return resolved; + } + // Try macOS AM/PM variant (narrow no-break space before AM/PM) + const amPmVariant = tryMacOSScreenshotPath(resolved); + if (amPmVariant !== resolved && fileExists(amPmVariant)) { + return amPmVariant; + } + // Try NFD variant (macOS stores filenames in NFD form) + const nfdVariant = tryNFDVariant(resolved); + if (nfdVariant !== resolved && fileExists(nfdVariant)) { + return nfdVariant; + } + // Try curly quote variant (macOS uses U+2019 in screenshot names) + const curlyVariant = tryCurlyQuoteVariant(resolved); + if (curlyVariant !== resolved && fileExists(curlyVariant)) { + return curlyVariant; + } + // Try combined NFD + curly quote (for French macOS screenshots like "Capture d'écran") + const nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant); + if (nfdCurlyVariant !== resolved && fileExists(nfdCurlyVariant)) { + return nfdCurlyVariant; + } + return resolved; +} +export async function resolveReadPathAsync(filePath, cwd) { + const resolved = resolveToCwd(filePath, cwd); + if (await pathExists(resolved)) { + return resolved; + } + // Try macOS AM/PM variant (narrow no-break space before AM/PM) + const amPmVariant = tryMacOSScreenshotPath(resolved); + if (amPmVariant !== resolved && (await pathExists(amPmVariant))) { + return amPmVariant; + } + // Try NFD variant (macOS stores filenames in NFD form) + const nfdVariant = tryNFDVariant(resolved); + if (nfdVariant !== resolved && (await pathExists(nfdVariant))) { + return nfdVariant; + } + // Try curly quote variant (macOS uses U+2019 in screenshot names) + const curlyVariant = tryCurlyQuoteVariant(resolved); + if (curlyVariant !== resolved && (await pathExists(curlyVariant))) { + return curlyVariant; + } + // Try combined NFD + curly quote (for French macOS screenshots like "Capture d'écran") + const nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant); + if (nfdCurlyVariant !== resolved && (await pathExists(nfdCurlyVariant))) { + return nfdCurlyVariant; + } + return resolved; +} +//# sourceMappingURL=path-utils.js.map \ No newline at end of file diff --git a/dist/core/tools/path-utils.js.map b/dist/core/tools/path-utils.js.map new file mode 100644 index 0000000..bf8dd6e --- /dev/null +++ b/dist/core/tools/path-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"path-utils.js","sourceRoot":"","sources":["../../../src/core/tools/path-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAElE,MAAM,qBAAqB,GAAG,QAAQ,CAAC;AAEvC,SAAS,sBAAsB,CAAC,QAAgB,EAAU;IACzD,OAAO,QAAQ,CAAC,OAAO,CAAC,cAAc,EAAE,GAAG,qBAAqB,KAAK,CAAC,CAAC;AAAA,CACvE;AAED,SAAS,aAAa,CAAC,QAAgB,EAAU;IAChD,oFAAoF;IACpF,OAAO,QAAQ,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAAA,CACjC;AAED,SAAS,oBAAoB,CAAC,QAAgB,EAAU;IACvD,8FAA6F;IAC7F,oDAAoD;IACpD,OAAO,QAAQ,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AAAA,CACxC;AAED,SAAS,UAAU,CAAC,QAAgB,EAAW;IAC9C,IAAI,CAAC;QACJ,UAAU,CAAC,QAAQ,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC;QACrC,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;AAAA,CACD;AAED,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,QAAgB,EAAoB;IACpE,IAAI,CAAC;QACJ,MAAM,MAAM,CAAC,QAAQ,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC;QACvC,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,MAAM,CAAC;QACR,O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import { access } from \"node:fs/promises\";\nimport { normalizePath, resolvePath } from \"../../utils/paths.ts\";\n\nconst NARROW_NO_BREAK_SPACE = \"\\u202F\";\n\nfunction tryMacOSScreenshotPath(filePath: string): string {\n\treturn filePath.replace(/ (AM|PM)\\./gi, `${NARROW_NO_BREAK_SPACE}$1.`);\n}\n\nfunction tryNFDVariant(filePath: string): string {\n\t// macOS stores filenames in NFD (decomposed) form, try converting user input to NFD\n\treturn filePath.normalize(\"NFD\");\n}\n\nfunction tryCurlyQuoteVariant(filePath: string): string {\n\t// macOS uses U+2019 (right single quotation mark) in screenshot names like \"Capture d'écran\"\n\t// Users typically type U+0027 (straight apostrophe)\n\treturn filePath.replace(/'/g, \"\\u2019\");\n}\n\nfunction fileExists(filePath: string): boolean {\n\ttry {\n\t\taccessSync(filePath, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport async function pathExists(filePath: string): Promise {\n\ttry {\n\t\tawait access(filePath, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function expandPath(filePath: string): string {\n\treturn normalizePath(filePath, { normalizeUnicodeSpaces: true, stripAtPrefix: true });\n}\n\n/**\n * Resolve a path relative to the given cwd.\n * Handles ~ expansion and absolute paths.\n */\nexport function resolveToCwd(filePath: string, cwd: string): string {\n\treturn resolvePath(filePath, cwd, { normalizeUnicodeSpaces: true, stripAtPrefix: true });\n}\n\nexport function resolveReadPath(filePath: string, cwd: string): string {\n\tconst resolved = resolveToCwd(filePath, cwd);\n\n\tif (fileExists(resolved)) {\n\t\treturn resolved;\n\t}\n\n\t// Try macOS AM/PM variant (narrow no-break space before AM/PM)\n\tconst amPmVariant = tryMacOSScreenshotPath(resolved);\n\tif (amPmVariant !== resolved && fileExists(amPmVariant)) {\n\t\treturn amPmVariant;\n\t}\n\n\t// Try NFD variant (macOS stores filenames in NFD form)\n\tconst nfdVariant = tryNFDVariant(resolved);\n\tif (nfdVariant !== resolved && fileExists(nfdVariant)) {\n\t\treturn nfdVariant;\n\t}\n\n\t// Try curly quote variant (macOS uses U+2019 in screenshot names)\n\tconst curlyVariant = tryCurlyQuoteVariant(resolved);\n\tif (curlyVariant !== resolved && fileExists(curlyVariant)) {\n\t\treturn curlyVariant;\n\t}\n\n\t// Try combined NFD + curly quote (for French macOS screenshots like \"Capture d'écran\")\n\tconst nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);\n\tif (nfdCurlyVariant !== resolved && fileExists(nfdCurlyVariant)) {\n\t\treturn nfdCurlyVariant;\n\t}\n\n\treturn resolved;\n}\n\nexport async function resolveReadPathAsync(filePath: string, cwd: string): Promise {\n\tconst resolved = resolveToCwd(filePath, cwd);\n\n\tif (await pathExists(resolved)) {\n\t\treturn resolved;\n\t}\n\n\t// Try macOS AM/PM variant (narrow no-break space before AM/PM)\n\tconst amPmVariant = tryMacOSScreenshotPath(resolved);\n\tif (amPmVariant !== resolved && (await pathExists(amPmVariant))) {\n\t\treturn amPmVariant;\n\t}\n\n\t// Try NFD variant (macOS stores filenames in NFD form)\n\tconst nfdVariant = tryNFDVariant(resolved);\n\tif (nfdVariant !== resolved && (await pathExists(nfdVariant))) {\n\t\treturn nfdVariant;\n\t}\n\n\t// Try curly quote variant (macOS uses U+2019 in screenshot names)\n\tconst curlyVariant = tryCurlyQuoteVariant(resolved);\n\tif (curlyVariant !== resolved && (await pathExists(curlyVariant))) {\n\t\treturn curlyVariant;\n\t}\n\n\t// Try combined NFD + curly quote (for French macOS screenshots like \"Capture d'écran\")\n\tconst nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);\n\tif (nfdCurlyVariant !== resolved && (await pathExists(nfdCurlyVariant))) {\n\t\treturn nfdCurlyVariant;\n\t}\n\n\treturn resolved;\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/read.d.ts b/dist/core/tools/read.d.ts new file mode 100644 index 0000000..21d889d --- /dev/null +++ b/dist/core/tools/read.d.ts @@ -0,0 +1,35 @@ +import type { AgentTool } from "@earendil-works/pi-agent-core"; +import { type Static, Type } from "typebox"; +import type { ToolDefinition } from "../extensions/types.ts"; +import { type TruncationResult } from "./truncate.ts"; +declare const readSchema: Type.TObject<{ + path: Type.TString; + offset: Type.TOptional; + limit: Type.TOptional; +}>; +export type ReadToolInput = Static; +export interface ReadToolDetails { + truncation?: TruncationResult; +} +/** + * Pluggable operations for the read tool. + * Override these to delegate file reading to remote systems (for example SSH). + */ +export interface ReadOperations { + /** Read file contents as a Buffer */ + readFile: (absolutePath: string) => Promise; + /** Check if file is readable (throw if not) */ + access: (absolutePath: string) => Promise; + /** Detect image MIME type, return null or undefined for non-images */ + detectImageMimeType?: (absolutePath: string) => Promise; +} +export interface ReadToolOptions { + /** Whether to auto-resize images to 2000x2000 max. Default: true */ + autoResizeImages?: boolean; + /** Custom operations for file reading. Default: local filesystem */ + operations?: ReadOperations; +} +export declare function createReadToolDefinition(cwd: string, options?: ReadToolOptions): ToolDefinition; +export declare function createReadTool(cwd: string, options?: ReadToolOptions): AgentTool; +export {}; +//# sourceMappingURL=read.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/read.d.ts.map b/dist/core/tools/read.d.ts.map new file mode 100644 index 0000000..fc50fea --- /dev/null +++ b/dist/core/tools/read.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAK/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAO5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAItF,OAAO,EAAoD,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEtH,QAAA,MAAM,UAAU;;;;EAId,CAAC;AAEH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC9B;AASD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,qCAAqC;IACrC,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,+CAA+C;IAC/C,MAAM,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,sEAAsE;IACtE,mBAAmB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;CACnF;AAQD,MAAM,WAAW,eAAe;IAC/B,oEAAoE;IACpE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,oEAAoE;IACpE,UAAU,CAAC,EAAE,cAAc,CAAC;CAC5B;AA4ID,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,cAAc,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CA6IhE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, readFile as fsReadFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { getReadmePath } from \"../../config.ts\";\nimport { keyHint, keyText } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { processImage } from \"../../utils/image-process.ts\";\nimport { detectSupportedImageMimeTypeFromFile } from \"../../utils/mime.ts\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"../../utils/paths.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { resolveReadPathAsync, resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport type ReadToolInput = Static;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n}\n\ninterface CompactReadClassification {\n\tkind: \"docs\" | \"resource\" | \"skill\";\n\tlabel: string;\n}\n\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\n\n/**\n * Pluggable operations for the read tool.\n * Override these to delegate file reading to remote systems (for example SSH).\n */\nexport interface ReadOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise;\n\t/** Check if file is readable (throw if not) */\n\taccess: (absolutePath: string) => Promise;\n\t/** Detect image MIME type, return null or undefined for non-images */\n\tdetectImageMimeType?: (absolutePath: string) => Promise;\n}\n\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images to 2000x2000 max. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Custom operations for file reading. Default: local filesystem */\n\toperations?: ReadOperations;\n}\n\ntype ReadRenderArgs = { path?: string; file_path?: string; offset?: number; limit?: number };\n\nfunction formatReadLineRange(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tif (args?.offset === undefined && args?.limit === undefined) return \"\";\n\tconst startLine = args.offset ?? 1;\n\tconst endLine = args.limit !== undefined ? startLine + args.limit - 1 : \"\";\n\treturn theme.fg(\"warning\", `:${startLine}${endLine ? `-${endLine}` : \"\"}`);\n}\n\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${formatReadLineRange(args, theme)}`;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction getNonVisionImageNote(model: Model | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\nfunction toPosixPath(filePath: string): string {\n\treturn filePath.split(sep).join(\"/\");\n}\n\nfunction getPiDocsClassification(absolutePath: string): CompactReadClassification | undefined {\n\tconst packageRoot = dirname(getReadmePath());\n\tconst relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath));\n\tif (\n\t\trelativePath === \"\" ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst label = toPosixPath(relativePath);\n\tif (label === \"README.md\" || label.startsWith(\"docs/\") || label.startsWith(\"examples/\")) {\n\t\treturn { kind: \"docs\", label };\n\t}\n\treturn undefined;\n}\n\nfunction getCompactReadClassification(\n\targs: ReadRenderArgs | undefined,\n\tcwd: string,\n): CompactReadClassification | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tif (!rawPath) return undefined;\n\n\tconst absolutePath = resolveToCwd(rawPath, cwd);\n\tconst fileName = basename(absolutePath);\n\tif (fileName === \"SKILL.md\") {\n\t\treturn { kind: \"skill\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\n\tconst docsClassification = getPiDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\n\treturn undefined;\n}\n\nfunction formatCompactReadCall(\n\tclassification: CompactReadClassification,\n\targs: ReadRenderArgs | undefined,\n\ttheme: Theme,\n): string {\n\tconst expandHint = theme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} to expand)`);\n\tif (classification.kind === \"skill\") {\n\t\treturn (\n\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m `) +\n\t\t\ttheme.fg(\"customMessageText\", classification.label) +\n\t\t\tformatReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tformatReadLineRange(args, theme) +\n\t\texpandHint\n\t);\n}\n\nfunction formatReadResult(\n\targs: ReadRenderArgs | undefined,\n\tresult: { content: (TextContent | ImageContent)[]; details?: ReadToolDetails },\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n\t_cwd: string,\n\tisError: boolean,\n): string {\n\tif (!options.expanded && !isError) {\n\t\treturn \"\";\n\t}\n\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst output = getTextOutput(result, showImages);\n\tconst lang = !isError && rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tconst renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split(\"\\n\");\n\tconst lines = trimTrailingEmptyLines(renderedLines);\n\tconst maxLines = options.expanded ? lines.length : 10;\n\tconst displayLines = lines.slice(0, maxLines);\n\tconst remaining = lines.length - maxLines;\n\tlet text = `\\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\tif (remaining > 0) {\n\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t}\n\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`;\n\t\t} else {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;\n\t\t}\n\t}\n\treturn text;\n}\n\nexport function createReadToolDefinition(\n\tcwd: string,\n\toptions?: ReadToolOptions,\n): ToolDefinition {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: \"Read file contents\",\n\t\tpromptGuidelines: [\"Use read to examine files instead of cat or sed.\"],\n\t\tparameters: readSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, offset, limit }: { path: string; offset?: number; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?,\n\t\t) {\n\t\t\treturn new Promise<{ content: (TextContent | ImageContent)[]; details: ReadToolDetails | undefined }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet aborted = false;\n\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t};\n\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst absolutePath = await resolveReadPathAsync(path, cwd);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\t// Check if file exists and is readable.\n\t\t\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tconst mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;\n\t\t\t\t\t\t\tlet content: (TextContent | ImageContent)[];\n\t\t\t\t\t\t\tlet details: ReadToolDetails | undefined;\n\t\t\t\t\t\t\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\t// Read image as binary.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst processed = await processImage(buffer, mimeType, { autoResizeImages });\n\t\t\t\t\t\t\t\tif (!processed.ok) {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${processed.mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (processed.hints.length > 0) textNote += `\\n${processed.hints.join(\"\\n\")}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: processed.data, mimeType: processed.mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read text content.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst textContent = buffer.toString(\"utf-8\");\n\t\t\t\t\t\t\t\tconst allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tconst totalFileLines = allLines.length;\n\t\t\t\t\t\t\t\t// Apply offset if specified. Convert from 1-indexed input to 0-indexed array access.\n\t\t\t\t\t\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\t// Check if offset is out of bounds.\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Offset ${offset} is beyond end of file (${allLines.length} lines total)`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet selectedContent: string;\n\t\t\t\t\t\t\t\tlet userLimitedLines: number | undefined;\n\t\t\t\t\t\t\t\t// If limit is specified by the user, honor it first. Otherwise truncateHead decides.\n\t\t\t\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\t\t\t\tconst endLine = Math.min(startLine + limit, allLines.length);\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine, endLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t\tuserLimitedLines = endLine - startLine;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Apply truncation, respecting both line and byte limits.\n\t\t\t\t\t\t\t\tconst truncation = truncateHead(selectedContent);\n\t\t\t\t\t\t\t\tlet outputText: string;\n\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t// First line alone exceeds the byte limit. Point the model at a bash fallback.\n\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], \"utf-8\"));\n\t\t\t\t\t\t\t\t\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t// Truncation occurred. Build an actionable continuation notice.\n\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {\n\t\t\t\t\t\t\t\t\t// User-specified limit stopped early, but the file still has more content.\n\t\t\t\t\t\t\t\t\tconst remaining = allLines.length - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// No truncation and no remaining user-limited content.\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tresolve({ content, details });\n\t\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tif (!aborted) reject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\t\ttext.setText(\n\t\t\t\tclassification\n\t\t\t\t\t? formatCompactReadCall(classification, args, theme)\n\t\t\t\t\t: formatReadCall(args, theme, context.cwd),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(\n\t\t\t\tformatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createReadTool(cwd: string, options?: ReadToolOptions): AgentTool {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/read.js b/dist/core/tools/read.js new file mode 100644 index 0000000..863dec5 --- /dev/null +++ b/dist/core/tools/read.js @@ -0,0 +1,276 @@ +import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from "node:path"; +import { Text } from "@earendil-works/pi-tui"; +import { constants } from "fs"; +import { access as fsAccess, readFile as fsReadFile } from "fs/promises"; +import { Type } from "typebox"; +import { getReadmePath } from "../../config.js"; +import { keyHint, keyText } from "../../modes/interactive/components/keybinding-hints.js"; +import { getLanguageFromPath, highlightCode } from "../../modes/interactive/theme/theme.js"; +import { processImage } from "../../utils/image-process.js"; +import { detectSupportedImageMimeTypeFromFile } from "../../utils/mime.js"; +import { formatPathRelativeToCwdOrAbsolute } from "../../utils/paths.js"; +import { resolveReadPathAsync, resolveToCwd } from "./path-utils.js"; +import { getTextOutput, renderToolPath, replaceTabs, str } from "./render-utils.js"; +import { wrapToolDefinition } from "./tool-definition-wrapper.js"; +import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead } from "./truncate.js"; +const readSchema = Type.Object({ + path: Type.String({ description: "Path to the file to read (relative or absolute)" }), + offset: Type.Optional(Type.Number({ description: "Line number to start reading from (1-indexed)" })), + limit: Type.Optional(Type.Number({ description: "Maximum number of lines to read" })), +}); +const COMPACT_RESOURCE_FILE_NAMES = new Set(["AGENTS.md", "AGENTS.MD", "CLAUDE.md", "CLAUDE.MD"]); +const defaultReadOperations = { + readFile: (path) => fsReadFile(path), + access: (path) => fsAccess(path, constants.R_OK), + detectImageMimeType: detectSupportedImageMimeTypeFromFile, +}; +function formatReadLineRange(args, theme) { + if (args?.offset === undefined && args?.limit === undefined) + return ""; + const startLine = args.offset ?? 1; + const endLine = args.limit !== undefined ? startLine + args.limit - 1 : ""; + return theme.fg("warning", `:${startLine}${endLine ? `-${endLine}` : ""}`); +} +function formatReadCall(args, theme, cwd) { + const pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd); + return `${theme.fg("toolTitle", theme.bold("read"))} ${pathDisplay}${formatReadLineRange(args, theme)}`; +} +function trimTrailingEmptyLines(lines) { + let end = lines.length; + while (end > 0 && lines[end - 1] === "") { + end--; + } + return lines.slice(0, end); +} +function getNonVisionImageNote(model) { + if (!model || model.input.includes("image")) { + return undefined; + } + return "[Current model does not support images. The image will be omitted from this request.]"; +} +function toPosixPath(filePath) { + return filePath.split(sep).join("/"); +} +function getPiDocsClassification(absolutePath) { + const packageRoot = dirname(getReadmePath()); + const relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath)); + if (relativePath === "" || + relativePath === ".." || + relativePath.startsWith(`..${sep}`) || + isAbsolute(relativePath)) { + return undefined; + } + const label = toPosixPath(relativePath); + if (label === "README.md" || label.startsWith("docs/") || label.startsWith("examples/")) { + return { kind: "docs", label }; + } + return undefined; +} +function getCompactReadClassification(args, cwd) { + const rawPath = str(args?.file_path ?? args?.path); + if (!rawPath) + return undefined; + const absolutePath = resolveToCwd(rawPath, cwd); + const fileName = basename(absolutePath); + if (fileName === "SKILL.md") { + return { kind: "skill", label: basename(dirname(absolutePath)) || fileName }; + } + const docsClassification = getPiDocsClassification(absolutePath); + if (docsClassification) + return docsClassification; + if (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) { + return { kind: "resource", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) }; + } + return undefined; +} +function formatCompactReadCall(classification, args, theme) { + const expandHint = theme.fg("dim", ` (${keyText("app.tools.expand")} to expand)`); + if (classification.kind === "skill") { + return (theme.fg("customMessageLabel", `\x1b[1m[skill]\x1b[22m `) + + theme.fg("customMessageText", classification.label) + + formatReadLineRange(args, theme) + + expandHint); + } + return (theme.fg("toolTitle", theme.bold(`read ${classification.kind}`)) + + " " + + theme.fg("accent", classification.label) + + formatReadLineRange(args, theme) + + expandHint); +} +function formatReadResult(args, result, options, theme, showImages, _cwd, isError) { + if (!options.expanded && !isError) { + return ""; + } + const rawPath = str(args?.file_path ?? args?.path); + const output = getTextOutput(result, showImages); + const lang = !isError && rawPath ? getLanguageFromPath(rawPath) : undefined; + const renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split("\n"); + const lines = trimTrailingEmptyLines(renderedLines); + const maxLines = options.expanded ? lines.length : 10; + const displayLines = lines.slice(0, maxLines); + const remaining = lines.length - maxLines; + let text = `\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg("toolOutput", replaceTabs(line)))).join("\n")}`; + if (remaining > 0) { + text += `${theme.fg("muted", `\n... (${remaining} more lines,`)} ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`; + } + const truncation = result.details?.truncation; + if (truncation?.truncated) { + if (truncation.firstLineExceedsLimit) { + text += `\n${theme.fg("warning", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`; + } + else if (truncation.truncatedBy === "lines") { + text += `\n${theme.fg("warning", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`; + } + else { + text += `\n${theme.fg("warning", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`; + } + } + return text; +} +export function createReadToolDefinition(cwd, options) { + const autoResizeImages = options?.autoResizeImages ?? true; + const ops = options?.operations ?? defaultReadOperations; + return { + name: "read", + label: "read", + description: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`, + promptSnippet: "Read file contents", + promptGuidelines: ["Use read to examine files instead of cat or sed."], + parameters: readSchema, + async execute(_toolCallId, { path, offset, limit }, signal, _onUpdate, ctx) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(new Error("Operation aborted")); + return; + } + let aborted = false; + const onAbort = () => { + aborted = true; + reject(new Error("Operation aborted")); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + (async () => { + try { + const absolutePath = await resolveReadPathAsync(path, cwd); + if (aborted) + return; + // Check if file exists and is readable. + await ops.access(absolutePath); + if (aborted) + return; + const mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined; + let content; + let details; + const nonVisionImageNote = getNonVisionImageNote(ctx?.model); + if (mimeType) { + // Read image as binary. + const buffer = await ops.readFile(absolutePath); + const processed = await processImage(buffer, mimeType, { autoResizeImages }); + if (!processed.ok) { + let textNote = `Read image file [${mimeType}]\n${processed.message}`; + if (nonVisionImageNote) + textNote += `\n${nonVisionImageNote}`; + content = [{ type: "text", text: textNote }]; + } + else { + let textNote = `Read image file [${processed.mimeType}]`; + if (processed.hints.length > 0) + textNote += `\n${processed.hints.join("\n")}`; + if (nonVisionImageNote) + textNote += `\n${nonVisionImageNote}`; + content = [ + { type: "text", text: textNote }, + { type: "image", data: processed.data, mimeType: processed.mimeType }, + ]; + } + } + else { + // Read text content. + const buffer = await ops.readFile(absolutePath); + const textContent = buffer.toString("utf-8"); + const allLines = textContent.split("\n"); + const totalFileLines = allLines.length; + // Apply offset if specified. Convert from 1-indexed input to 0-indexed array access. + const startLine = offset ? Math.max(0, offset - 1) : 0; + const startLineDisplay = startLine + 1; + // Check if offset is out of bounds. + if (startLine >= allLines.length) { + throw new Error(`Offset ${offset} is beyond end of file (${allLines.length} lines total)`); + } + let selectedContent; + let userLimitedLines; + // If limit is specified by the user, honor it first. Otherwise truncateHead decides. + if (limit !== undefined) { + const endLine = Math.min(startLine + limit, allLines.length); + selectedContent = allLines.slice(startLine, endLine).join("\n"); + userLimitedLines = endLine - startLine; + } + else { + selectedContent = allLines.slice(startLine).join("\n"); + } + // Apply truncation, respecting both line and byte limits. + const truncation = truncateHead(selectedContent); + let outputText; + if (truncation.firstLineExceedsLimit) { + // First line alone exceeds the byte limit. Point the model at a bash fallback. + const firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], "utf-8")); + outputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`; + details = { truncation }; + } + else if (truncation.truncated) { + // Truncation occurred. Build an actionable continuation notice. + const endLineDisplay = startLineDisplay + truncation.outputLines - 1; + const nextOffset = endLineDisplay + 1; + outputText = truncation.content; + if (truncation.truncatedBy === "lines") { + outputText += `\n\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`; + } + else { + outputText += `\n\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`; + } + details = { truncation }; + } + else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) { + // User-specified limit stopped early, but the file still has more content. + const remaining = allLines.length - (startLine + userLimitedLines); + const nextOffset = startLine + userLimitedLines + 1; + outputText = `${truncation.content}\n\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`; + } + else { + // No truncation and no remaining user-limited content. + outputText = truncation.content; + } + content = [{ type: "text", text: outputText }]; + } + if (aborted) + return; + signal?.removeEventListener("abort", onAbort); + resolve({ content, details }); + } + catch (error) { + signal?.removeEventListener("abort", onAbort); + if (!aborted) + reject(error); + } + })(); + }); + }, + renderCall(args, theme, context) { + const text = context.lastComponent ?? new Text("", 0, 0); + const classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined; + text.setText(classification + ? formatCompactReadCall(classification, args, theme) + : formatReadCall(args, theme, context.cwd)); + return text; + }, + renderResult(result, options, theme, context) { + const text = context.lastComponent ?? new Text("", 0, 0); + text.setText(formatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError)); + return text; + }, + }; +} +export function createReadTool(cwd, options) { + return wrapToolDefinition(createReadToolDefinition(cwd, options)); +} +//# sourceMappingURL=read.js.map \ No newline at end of file diff --git a/dist/core/tools/read.js.map b/dist/core/tools/read.js.map new file mode 100644 index 0000000..d3438f3 --- /dev/null +++ b/dist/core/tools/read.js.map @@ -0,0 +1 @@ +{"version":3,"file":"read.js","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAGjG,OAAO,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,EAAE,MAAM,IAAI,QAAQ,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AAC1F,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAc,MAAM,wCAAwC,CAAC;AACxG,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAE,iCAAiC,EAAE,MAAM,sBAAsB,CAAC;AAEzE,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,WAAW,EAAE,G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,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC,CACxG,CAAC;YACF,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,OAAyB,EAAgC;IACpG,OAAO,kBAAkB,CAAC,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CAClE","sourcesContent":["import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, readFile as fsReadFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { getReadmePath } from \"../../config.ts\";\nimport { keyHint, keyText } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { processImage } from \"../../utils/image-process.ts\";\nimport { detectSupportedImageMimeTypeFromFile } from \"../../utils/mime.ts\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"../../utils/paths.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { resolveReadPathAsync, resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport type ReadToolInput = Static;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n}\n\ninterface CompactReadClassification {\n\tkind: \"docs\" | \"resource\" | \"skill\";\n\tlabel: string;\n}\n\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\n\n/**\n * Pluggable operations for the read tool.\n * Override these to delegate file reading to remote systems (for example SSH).\n */\nexport interface ReadOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise;\n\t/** Check if file is readable (throw if not) */\n\taccess: (absolutePath: string) => Promise;\n\t/** Detect image MIME type, return null or undefined for non-images */\n\tdetectImageMimeType?: (absolutePath: string) => Promise;\n}\n\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images to 2000x2000 max. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Custom operations for file reading. Default: local filesystem */\n\toperations?: ReadOperations;\n}\n\ntype ReadRenderArgs = { path?: string; file_path?: string; offset?: number; limit?: number };\n\nfunction formatReadLineRange(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tif (args?.offset === undefined && args?.limit === undefined) return \"\";\n\tconst startLine = args.offset ?? 1;\n\tconst endLine = args.limit !== undefined ? startLine + args.limit - 1 : \"\";\n\treturn theme.fg(\"warning\", `:${startLine}${endLine ? `-${endLine}` : \"\"}`);\n}\n\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${formatReadLineRange(args, theme)}`;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction getNonVisionImageNote(model: Model | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\nfunction toPosixPath(filePath: string): string {\n\treturn filePath.split(sep).join(\"/\");\n}\n\nfunction getPiDocsClassification(absolutePath: string): CompactReadClassification | undefined {\n\tconst packageRoot = dirname(getReadmePath());\n\tconst relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath));\n\tif (\n\t\trelativePath === \"\" ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst label = toPosixPath(relativePath);\n\tif (label === \"README.md\" || label.startsWith(\"docs/\") || label.startsWith(\"examples/\")) {\n\t\treturn { kind: \"docs\", label };\n\t}\n\treturn undefined;\n}\n\nfunction getCompactReadClassification(\n\targs: ReadRenderArgs | undefined,\n\tcwd: string,\n): CompactReadClassification | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tif (!rawPath) return undefined;\n\n\tconst absolutePath = resolveToCwd(rawPath, cwd);\n\tconst fileName = basename(absolutePath);\n\tif (fileName === \"SKILL.md\") {\n\t\treturn { kind: \"skill\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\n\tconst docsClassification = getPiDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\n\treturn undefined;\n}\n\nfunction formatCompactReadCall(\n\tclassification: CompactReadClassification,\n\targs: ReadRenderArgs | undefined,\n\ttheme: Theme,\n): string {\n\tconst expandHint = theme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} to expand)`);\n\tif (classification.kind === \"skill\") {\n\t\treturn (\n\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m `) +\n\t\t\ttheme.fg(\"customMessageText\", classification.label) +\n\t\t\tformatReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tformatReadLineRange(args, theme) +\n\t\texpandHint\n\t);\n}\n\nfunction formatReadResult(\n\targs: ReadRenderArgs | undefined,\n\tresult: { content: (TextContent | ImageContent)[]; details?: ReadToolDetails },\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n\t_cwd: string,\n\tisError: boolean,\n): string {\n\tif (!options.expanded && !isError) {\n\t\treturn \"\";\n\t}\n\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst output = getTextOutput(result, showImages);\n\tconst lang = !isError && rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tconst renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split(\"\\n\");\n\tconst lines = trimTrailingEmptyLines(renderedLines);\n\tconst maxLines = options.expanded ? lines.length : 10;\n\tconst displayLines = lines.slice(0, maxLines);\n\tconst remaining = lines.length - maxLines;\n\tlet text = `\\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\tif (remaining > 0) {\n\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t}\n\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`;\n\t\t} else {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;\n\t\t}\n\t}\n\treturn text;\n}\n\nexport function createReadToolDefinition(\n\tcwd: string,\n\toptions?: ReadToolOptions,\n): ToolDefinition {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: \"Read file contents\",\n\t\tpromptGuidelines: [\"Use read to examine files instead of cat or sed.\"],\n\t\tparameters: readSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, offset, limit }: { path: string; offset?: number; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?,\n\t\t) {\n\t\t\treturn new Promise<{ content: (TextContent | ImageContent)[]; details: ReadToolDetails | undefined }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet aborted = false;\n\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t};\n\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst absolutePath = await resolveReadPathAsync(path, cwd);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\t// Check if file exists and is readable.\n\t\t\t\t\t\t\tawait ops.access(absolutePath);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tconst mimeType = ops.detectImageMimeType ? await ops.detectImageMimeType(absolutePath) : undefined;\n\t\t\t\t\t\t\tlet content: (TextContent | ImageContent)[];\n\t\t\t\t\t\t\tlet details: ReadToolDetails | undefined;\n\t\t\t\t\t\t\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\t// Read image as binary.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst processed = await processImage(buffer, mimeType, { autoResizeImages });\n\t\t\t\t\t\t\t\tif (!processed.ok) {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${processed.mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (processed.hints.length > 0) textNote += `\\n${processed.hints.join(\"\\n\")}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: processed.data, mimeType: processed.mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read text content.\n\t\t\t\t\t\t\t\tconst buffer = await ops.readFile(absolutePath);\n\t\t\t\t\t\t\t\tconst textContent = buffer.toString(\"utf-8\");\n\t\t\t\t\t\t\t\tconst allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tconst totalFileLines = allLines.length;\n\t\t\t\t\t\t\t\t// Apply offset if specified. Convert from 1-indexed input to 0-indexed array access.\n\t\t\t\t\t\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\t// Check if offset is out of bounds.\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Offset ${offset} is beyond end of file (${allLines.length} lines total)`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet selectedContent: string;\n\t\t\t\t\t\t\t\tlet userLimitedLines: number | undefined;\n\t\t\t\t\t\t\t\t// If limit is specified by the user, honor it first. Otherwise truncateHead decides.\n\t\t\t\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\t\t\t\tconst endLine = Math.min(startLine + limit, allLines.length);\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine, endLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t\tuserLimitedLines = endLine - startLine;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Apply truncation, respecting both line and byte limits.\n\t\t\t\t\t\t\t\tconst truncation = truncateHead(selectedContent);\n\t\t\t\t\t\t\t\tlet outputText: string;\n\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t// First line alone exceeds the byte limit. Point the model at a bash fallback.\n\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], \"utf-8\"));\n\t\t\t\t\t\t\t\t\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t// Truncation occurred. Build an actionable continuation notice.\n\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {\n\t\t\t\t\t\t\t\t\t// User-specified limit stopped early, but the file still has more content.\n\t\t\t\t\t\t\t\t\tconst remaining = allLines.length - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// No truncation and no remaining user-limited content.\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tresolve({ content, details });\n\t\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tif (!aborted) reject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\t\ttext.setText(\n\t\t\t\tclassification\n\t\t\t\t\t? formatCompactReadCall(classification, args, theme)\n\t\t\t\t\t: formatReadCall(args, theme, context.cwd),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(\n\t\t\t\tformatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createReadTool(cwd: string, options?: ReadToolOptions): AgentTool {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/render-utils.d.ts b/dist/core/tools/render-utils.d.ts new file mode 100644 index 0000000..db63968 --- /dev/null +++ b/dist/core/tools/render-utils.d.ts @@ -0,0 +1,24 @@ +import type { ImageContent, TextContent } from "@earendil-works/pi-ai"; +import type { Theme } from "../../modes/interactive/theme/theme.ts"; +export declare function shortenPath(path: unknown): string; +export declare function linkPath(styledText: string, rawPath: string, cwd: string): string; +export declare function str(value: unknown): string | null; +export declare function replaceTabs(text: string): string; +export declare function normalizeDisplayText(text: string): string; +export declare function getTextOutput(result: { + content: Array<{ + type: string; + text?: string; + data?: string; + mimeType?: string; + }>; +} | undefined, showImages: boolean): string; +export type ToolRenderResultLike = { + content: (TextContent | ImageContent)[]; + details: TDetails; +}; +export declare function invalidArgText(theme: Theme): string; +export declare function renderToolPath(rawPath: string | null, theme: Theme, cwd: string, options?: { + emptyFallback?: string; +}): string; +//# sourceMappingURL=render-utils.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/render-utils.d.ts.map b/dist/core/tools/render-utils.d.ts.map new file mode 100644 index 0000000..7624096 --- /dev/null +++ b/dist/core/tools/render-utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"render-utils.d.ts","sourceRoot":"","sources":["../../../src/core/tools/render-utils.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEvE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAKpE,wBAAgB,WAAW,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,CAOjD;AAED,wBAAgB,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAIjF;AAED,wBAAgB,GAAG,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAIjD;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEhD;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED,wBAAgB,aAAa,CAC5B,MAAM,EAAE;IAAE,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CAAE,GAAG,SAAS,EACzG,UAAU,EAAE,OAAO,GACjB,MAAM,CAsBR;AAED,MAAM,MAAM,oBAAoB,CAAC,QAAQ,IAAI;IAC5C,OAAO,EAAE,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,CAAC;IACxC,OAAO,EAAE,QAAQ,CAAC;CAClB,CAAC;AAEF,wBAAgB,cAAc,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,CAEnD;AAED,wBAAgB,cAAc,CAC7B,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,KAAK,EAAE,KAAK,EACZ,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAA;CAAE,GAClC,MAAM,CAKR","sourcesContent":["import * as os from \"node:os\";\nimport { pathToFileURL } from \"node:url\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport { getCapabilities, getImageDimensions, hyperlink, imageFallback } from \"@earendil-works/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { stripAnsi } from \"../../utils/ansi.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { sanitizeBinaryOutput } from \"../../utils/shell.ts\";\n\nexport function shortenPath(path: unknown): string {\n\tif (typeof path !== \"string\") return \"\";\n\tconst home = os.homedir();\n\tif (path.startsWith(home)) {\n\t\treturn `~${path.slice(home.length)}`;\n\t}\n\treturn path;\n}\n\nexport function linkPath(styledText: string, rawPath: string, cwd: string): string {\n\tif (!getCapabilities().hyperlinks) return styledText;\n\tconst absolutePath = resolvePath(rawPath, cwd);\n\treturn hyperlink(styledText, pathToFileURL(absolutePath).href);\n}\n\nexport function str(value: unknown): string | null {\n\tif (typeof value === \"string\") return value;\n\tif (value == null) return \"\";\n\treturn null;\n}\n\nexport function replaceTabs(text: string): string {\n\treturn text.replace(/\\t/g, \" \");\n}\n\nexport function normalizeDisplayText(text: string): string {\n\treturn text.replace(/\\r/g, \"\");\n}\n\nexport function getTextOutput(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }> } | undefined,\n\tshowImages: boolean,\n): string {\n\tif (!result) return \"\";\n\n\tconst textBlocks = result.content.filter((c) => c.type === \"text\");\n\tconst imageBlocks = result.content.filter((c) => c.type === \"image\");\n\n\tlet output = textBlocks.map((c) => sanitizeBinaryOutput(stripAnsi(c.text || \"\")).replace(/\\r/g, \"\")).join(\"\\n\");\n\n\tconst caps = getCapabilities();\n\tif (imageBlocks.length > 0 && (!caps.images || !showImages)) {\n\t\tconst imageIndicators = imageBlocks\n\t\t\t.map((img) => {\n\t\t\t\tconst mimeType = img.mimeType ?? \"image/unknown\";\n\t\t\t\tconst dims =\n\t\t\t\t\timg.data && img.mimeType ? (getImageDimensions(img.data, img.mimeType) ?? undefined) : undefined;\n\t\t\t\treturn imageFallback(mimeType, dims);\n\t\t\t})\n\t\t\t.join(\"\\n\");\n\t\toutput = output ? `${output}\\n${imageIndicators}` : imageIndicators;\n\t}\n\n\treturn output;\n}\n\nexport type ToolRenderResultLike = {\n\tcontent: (TextContent | ImageContent)[];\n\tdetails: TDetails;\n};\n\nexport function invalidArgText(theme: Theme): string {\n\treturn theme.fg(\"error\", \"[invalid arg]\");\n}\n\nexport function renderToolPath(\n\trawPath: string | null,\n\ttheme: Theme,\n\tcwd: string,\n\toptions?: { emptyFallback?: string },\n): string {\n\tif (rawPath === null) return invalidArgText(theme);\n\tconst value = rawPath || options?.emptyFallback;\n\tif (!value) return theme.fg(\"toolOutput\", \"...\");\n\treturn linkPath(theme.fg(\"accent\", shortenPath(value)), value, cwd);\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/render-utils.js b/dist/core/tools/render-utils.js new file mode 100644 index 0000000..479a0b4 --- /dev/null +++ b/dist/core/tools/render-utils.js @@ -0,0 +1,65 @@ +import * as os from "node:os"; +import { pathToFileURL } from "node:url"; +import { getCapabilities, getImageDimensions, hyperlink, imageFallback } from "@earendil-works/pi-tui"; +import { stripAnsi } from "../../utils/ansi.js"; +import { resolvePath } from "../../utils/paths.js"; +import { sanitizeBinaryOutput } from "../../utils/shell.js"; +export function shortenPath(path) { + if (typeof path !== "string") + return ""; + const home = os.homedir(); + if (path.startsWith(home)) { + return `~${path.slice(home.length)}`; + } + return path; +} +export function linkPath(styledText, rawPath, cwd) { + if (!getCapabilities().hyperlinks) + return styledText; + const absolutePath = resolvePath(rawPath, cwd); + return hyperlink(styledText, pathToFileURL(absolutePath).href); +} +export function str(value) { + if (typeof value === "string") + return value; + if (value == null) + return ""; + return null; +} +export function replaceTabs(text) { + return text.replace(/\t/g, " "); +} +export function normalizeDisplayText(text) { + return text.replace(/\r/g, ""); +} +export function getTextOutput(result, showImages) { + if (!result) + return ""; + const textBlocks = result.content.filter((c) => c.type === "text"); + const imageBlocks = result.content.filter((c) => c.type === "image"); + let output = textBlocks.map((c) => sanitizeBinaryOutput(stripAnsi(c.text || "")).replace(/\r/g, "")).join("\n"); + const caps = getCapabilities(); + if (imageBlocks.length > 0 && (!caps.images || !showImages)) { + const imageIndicators = imageBlocks + .map((img) => { + const mimeType = img.mimeType ?? "image/unknown"; + const dims = img.data && img.mimeType ? (getImageDimensions(img.data, img.mimeType) ?? undefined) : undefined; + return imageFallback(mimeType, dims); + }) + .join("\n"); + output = output ? `${output}\n${imageIndicators}` : imageIndicators; + } + return output; +} +export function invalidArgText(theme) { + return theme.fg("error", "[invalid arg]"); +} +export function renderToolPath(rawPath, theme, cwd, options) { + if (rawPath === null) + return invalidArgText(theme); + const value = rawPath || options?.emptyFallback; + if (!value) + return theme.fg("toolOutput", "..."); + return linkPath(theme.fg("accent", shortenPath(value)), value, cwd); +} +//# sourceMappingURL=render-utils.js.map \ No newline at end of file diff --git a/dist/core/tools/render-utils.js.map b/dist/core/tools/render-utils.js.map new file mode 100644 index 0000000..fdc19fe --- /dev/null +++ b/dist/core/tools/render-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"render-utils.js","sourceRoot":"","sources":["../../../src/core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,IAAI,EAAE,GAAG,CAAC,QAAQ,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;YAClG,OAAO,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QAAA,CACrC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAC;QACb,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,KAAK,eAAe,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC;IACrE,CAAC;IAED,OAAO,MAAM,CAAC;AAAA,CACd;AAOD,MAAM,UAAU,cAAc,CAAC,KAAY,EAAU;IACpD,OAAO,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;AAAA,CAC1C;AAED,MAAM,UAAU,cAAc,CAC7B,OAAsB,EACtB,KAAY,EACZ,GAAW,EACX,OAAoC,EAC3B;IACT,IAAI,OAAO,KAAK,IAAI;QAAE,OAAO,cAAc,CAAC,KAAK,CAAC,CAAC;IACnD,MAAM,KAAK,GAAG,OAAO,IAAI,OAAO,EAAE,aAAa,CAAC;IAChD,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC,EAAE,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;IACjD,OAAO,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;AAAA,CACpE","sourcesContent":["import * as os from \"node:os\";\nimport { pathToFileURL } from \"node:url\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport { getCapabilities, getImageDimensions, hyperlink, imageFallback } from \"@earendil-works/pi-tui\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { stripAnsi } from \"../../utils/ansi.ts\";\nimport { resolvePath } from \"../../utils/paths.ts\";\nimport { sanitizeBinaryOutput } from \"../../utils/shell.ts\";\n\nexport function shortenPath(path: unknown): string {\n\tif (typeof path !== \"string\") return \"\";\n\tconst home = os.homedir();\n\tif (path.startsWith(home)) {\n\t\treturn `~${path.slice(home.length)}`;\n\t}\n\treturn path;\n}\n\nexport function linkPath(styledText: string, rawPath: string, cwd: string): string {\n\tif (!getCapabilities().hyperlinks) return styledText;\n\tconst absolutePath = resolvePath(rawPath, cwd);\n\treturn hyperlink(styledText, pathToFileURL(absolutePath).href);\n}\n\nexport function str(value: unknown): string | null {\n\tif (typeof value === \"string\") return value;\n\tif (value == null) return \"\";\n\treturn null;\n}\n\nexport function replaceTabs(text: string): string {\n\treturn text.replace(/\\t/g, \" \");\n}\n\nexport function normalizeDisplayText(text: string): string {\n\treturn text.replace(/\\r/g, \"\");\n}\n\nexport function getTextOutput(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }> } | undefined,\n\tshowImages: boolean,\n): string {\n\tif (!result) return \"\";\n\n\tconst textBlocks = result.content.filter((c) => c.type === \"text\");\n\tconst imageBlocks = result.content.filter((c) => c.type === \"image\");\n\n\tlet output = textBlocks.map((c) => sanitizeBinaryOutput(stripAnsi(c.text || \"\")).replace(/\\r/g, \"\")).join(\"\\n\");\n\n\tconst caps = getCapabilities();\n\tif (imageBlocks.length > 0 && (!caps.images || !showImages)) {\n\t\tconst imageIndicators = imageBlocks\n\t\t\t.map((img) => {\n\t\t\t\tconst mimeType = img.mimeType ?? \"image/unknown\";\n\t\t\t\tconst dims =\n\t\t\t\t\timg.data && img.mimeType ? (getImageDimensions(img.data, img.mimeType) ?? undefined) : undefined;\n\t\t\t\treturn imageFallback(mimeType, dims);\n\t\t\t})\n\t\t\t.join(\"\\n\");\n\t\toutput = output ? `${output}\\n${imageIndicators}` : imageIndicators;\n\t}\n\n\treturn output;\n}\n\nexport type ToolRenderResultLike = {\n\tcontent: (TextContent | ImageContent)[];\n\tdetails: TDetails;\n};\n\nexport function invalidArgText(theme: Theme): string {\n\treturn theme.fg(\"error\", \"[invalid arg]\");\n}\n\nexport function renderToolPath(\n\trawPath: string | null,\n\ttheme: Theme,\n\tcwd: string,\n\toptions?: { emptyFallback?: string },\n): string {\n\tif (rawPath === null) return invalidArgText(theme);\n\tconst value = rawPath || options?.emptyFallback;\n\tif (!value) return theme.fg(\"toolOutput\", \"...\");\n\treturn linkPath(theme.fg(\"accent\", shortenPath(value)), value, cwd);\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/tool-definition-wrapper.d.ts b/dist/core/tools/tool-definition-wrapper.d.ts new file mode 100644 index 0000000..4cee070 --- /dev/null +++ b/dist/core/tools/tool-definition-wrapper.d.ts @@ -0,0 +1,14 @@ +import type { AgentTool } from "@earendil-works/pi-agent-core"; +import type { ExtensionContext, ToolDefinition } from "../extensions/types.ts"; +/** Wrap a ToolDefinition into an AgentTool for the core runtime. */ +export declare function wrapToolDefinition(definition: ToolDefinition, ctxFactory?: () => ExtensionContext): AgentTool; +/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */ +export declare function wrapToolDefinitions(definitions: ToolDefinition[], ctxFactory?: () => ExtensionContext): AgentTool[]; +/** + * Synthesize a minimal ToolDefinition from an AgentTool. + * + * This keeps AgentSession's internal registry definition-first even when a caller + * provides plain AgentTool overrides that do not include prompt metadata or renderers. + */ +export declare function createToolDefinitionFromAgentTool(tool: AgentTool): ToolDefinition; +//# sourceMappingURL=tool-definition-wrapper.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/tool-definition-wrapper.d.ts.map b/dist/core/tools/tool-definition-wrapper.d.ts.map new file mode 100644 index 0000000..30e9338 --- /dev/null +++ b/dist/core/tools/tool-definition-wrapper.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tool-definition-wrapper.d.ts","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAE/E,oEAAoE;AACpE,wBAAgB,kBAAkB,CAAC,QAAQ,GAAG,OAAO,EACpD,UAAU,EAAE,cAAc,CAAC,GAAG,EAAE,QAAQ,CAAC,EACzC,UAAU,CAAC,EAAE,MAAM,gBAAgB,GACjC,SAAS,CAAC,GAAG,EAAE,QAAQ,CAAC,CAY1B;AAED,0EAA0E;AAC1E,wBAAgB,mBAAmB,CAClC,WAAW,EAAE,cAAc,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,EACvC,UAAU,CAAC,EAAE,MAAM,gBAAgB,GACjC,SAAS,CAAC,GAAG,CAAC,EAAE,CAElB;AAED;;;;;GAKG;AACH,wBAAgB,iCAAiC,CAAC,IAAI,EAAE,SAAS,CAAC,GAAG,CAAC,GAAG,cAAc,CAAC,GAAG,EAAE,OAAO,CAAC,CAWpG","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\n\n/** Wrap a ToolDefinition into an AgentTool for the core runtime. */\nexport function wrapToolDefinition(\n\tdefinition: ToolDefinition,\n\tctxFactory?: () => ExtensionContext,\n): AgentTool {\n\treturn {\n\t\tname: definition.name,\n\t\tlabel: definition.label,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\tconstrainedSampling: definition.constrainedSampling,\n\t\tprepareArguments: definition.prepareArguments,\n\t\texecutionMode: definition.executionMode,\n\t\texecute: (toolCallId, params, signal, onUpdate, ctx?: ExtensionContext) =>\n\t\t\tdefinition.execute(toolCallId, params, signal, onUpdate, ctx ?? (ctxFactory?.() as ExtensionContext)),\n\t};\n}\n\n/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */\nexport function wrapToolDefinitions(\n\tdefinitions: ToolDefinition[],\n\tctxFactory?: () => ExtensionContext,\n): AgentTool[] {\n\treturn definitions.map((definition) => wrapToolDefinition(definition, ctxFactory));\n}\n\n/**\n * Synthesize a minimal ToolDefinition from an AgentTool.\n *\n * This keeps AgentSession's internal registry definition-first even when a caller\n * provides plain AgentTool overrides that do not include prompt metadata or renderers.\n */\nexport function createToolDefinitionFromAgentTool(tool: AgentTool): ToolDefinition {\n\treturn {\n\t\tname: tool.name,\n\t\tlabel: tool.label,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters as any,\n\t\tconstrainedSampling: tool.constrainedSampling,\n\t\tprepareArguments: tool.prepareArguments,\n\t\texecutionMode: tool.executionMode,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => tool.execute(toolCallId, params, signal, onUpdate),\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/tool-definition-wrapper.js b/dist/core/tools/tool-definition-wrapper.js new file mode 100644 index 0000000..e05fec9 --- /dev/null +++ b/dist/core/tools/tool-definition-wrapper.js @@ -0,0 +1,36 @@ +/** Wrap a ToolDefinition into an AgentTool for the core runtime. */ +export function wrapToolDefinition(definition, ctxFactory) { + return { + name: definition.name, + label: definition.label, + description: definition.description, + parameters: definition.parameters, + constrainedSampling: definition.constrainedSampling, + prepareArguments: definition.prepareArguments, + executionMode: definition.executionMode, + execute: (toolCallId, params, signal, onUpdate, ctx) => definition.execute(toolCallId, params, signal, onUpdate, ctx ?? ctxFactory?.()), + }; +} +/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */ +export function wrapToolDefinitions(definitions, ctxFactory) { + return definitions.map((definition) => wrapToolDefinition(definition, ctxFactory)); +} +/** + * Synthesize a minimal ToolDefinition from an AgentTool. + * + * This keeps AgentSession's internal registry definition-first even when a caller + * provides plain AgentTool overrides that do not include prompt metadata or renderers. + */ +export function createToolDefinitionFromAgentTool(tool) { + return { + name: tool.name, + label: tool.label, + description: tool.description, + parameters: tool.parameters, + constrainedSampling: tool.constrainedSampling, + prepareArguments: tool.prepareArguments, + executionMode: tool.executionMode, + execute: async (toolCallId, params, signal, onUpdate) => tool.execute(toolCallId, params, signal, onUpdate), + }; +} +//# sourceMappingURL=tool-definition-wrapper.js.map \ No newline at end of file diff --git a/dist/core/tools/tool-definition-wrapper.js.map b/dist/core/tools/tool-definition-wrapper.js.map new file mode 100644 index 0000000..dc0d0a9 --- /dev/null +++ b/dist/core/tools/tool-definition-wrapper.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tool-definition-wrapper.js","sourceRoot":"","sources":["../../../src/core/tools/tool-definition-wrapper.ts"],"names":[],"mappings":"AAGA,oEAAoE;AACpE,MAAM,UAAU,kBAAkB,CACjC,UAAyC,EACzC,UAAmC,EACR;IAC3B,OAAO;QACN,IAAI,EAAE,UAAU,CAAC,IAAI;QACrB,KAAK,EAAE,UAAU,CAAC,KAAK;QACvB,WAAW,EAAE,UAAU,CAAC,WAAW;QACnC,UAAU,EAAE,UAAU,CAAC,UAAU;QACjC,mBAAmB,EAAE,UAAU,CAAC,mBAAmB;QACnD,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;QAC7C,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,OAAO,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAsB,EAAE,EAAE,CACzE,UAAU,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAK,UAAU,EAAE,EAAuB,CAAC;KACtG,CAAC;AAAA,CACF;AAED,0EAA0E;AAC1E,MAAM,UAAU,mBAAmB,CAClC,WAAuC,EACvC,UAAmC,EAChB;IACnB,OAAO,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,kBAAkB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC;AAAA,CACnF;AAED;;;;;GAKG;AACH,MAAM,UAAU,iCAAiC,CAAC,IAAoB,EAAgC;IACrG,OAAO;QACN,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,UAAU,EAAE,IAAI,CAAC,UAAiB;QAClC,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;QAC7C,gBAAgB,EAAE,IAAI,CAAC,gBAAgB;QACvC,aAAa,EAAE,IAAI,CAAC,aAAa;QACjC,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC;KAC3G,CAAC;AAAA,CACF","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\n\n/** Wrap a ToolDefinition into an AgentTool for the core runtime. */\nexport function wrapToolDefinition(\n\tdefinition: ToolDefinition,\n\tctxFactory?: () => ExtensionContext,\n): AgentTool {\n\treturn {\n\t\tname: definition.name,\n\t\tlabel: definition.label,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\tconstrainedSampling: definition.constrainedSampling,\n\t\tprepareArguments: definition.prepareArguments,\n\t\texecutionMode: definition.executionMode,\n\t\texecute: (toolCallId, params, signal, onUpdate, ctx?: ExtensionContext) =>\n\t\t\tdefinition.execute(toolCallId, params, signal, onUpdate, ctx ?? (ctxFactory?.() as ExtensionContext)),\n\t};\n}\n\n/** Wrap multiple ToolDefinitions into AgentTools for the core runtime. */\nexport function wrapToolDefinitions(\n\tdefinitions: ToolDefinition[],\n\tctxFactory?: () => ExtensionContext,\n): AgentTool[] {\n\treturn definitions.map((definition) => wrapToolDefinition(definition, ctxFactory));\n}\n\n/**\n * Synthesize a minimal ToolDefinition from an AgentTool.\n *\n * This keeps AgentSession's internal registry definition-first even when a caller\n * provides plain AgentTool overrides that do not include prompt metadata or renderers.\n */\nexport function createToolDefinitionFromAgentTool(tool: AgentTool): ToolDefinition {\n\treturn {\n\t\tname: tool.name,\n\t\tlabel: tool.label,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters as any,\n\t\tconstrainedSampling: tool.constrainedSampling,\n\t\tprepareArguments: tool.prepareArguments,\n\t\texecutionMode: tool.executionMode,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => tool.execute(toolCallId, params, signal, onUpdate),\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/truncate.d.ts b/dist/core/tools/truncate.d.ts new file mode 100644 index 0000000..baf4c54 --- /dev/null +++ b/dist/core/tools/truncate.d.ts @@ -0,0 +1,70 @@ +/** + * Shared truncation utilities for tool outputs. + * + * Truncation is based on two independent limits - whichever is hit first wins: + * - Line limit (default: 2000 lines) + * - Byte limit (default: 50KB) + * + * Never returns partial lines (except bash tail truncation edge case). + */ +export declare const DEFAULT_MAX_LINES = 2000; +export declare const DEFAULT_MAX_BYTES: number; +export declare const GREP_MAX_LINE_LENGTH = 500; +export interface TruncationResult { + /** The truncated content */ + content: string; + /** Whether truncation occurred */ + truncated: boolean; + /** Which limit was hit: "lines", "bytes", or null if not truncated */ + truncatedBy: "lines" | "bytes" | null; + /** Total number of lines in the original content */ + totalLines: number; + /** Total number of bytes in the original content */ + totalBytes: number; + /** Number of complete lines in the truncated output */ + outputLines: number; + /** Number of bytes in the truncated output */ + outputBytes: number; + /** Whether the last line was partially truncated (only for tail truncation edge case) */ + lastLinePartial: boolean; + /** Whether the first line exceeded the byte limit (for head truncation) */ + firstLineExceedsLimit: boolean; + /** The max lines limit that was applied */ + maxLines: number; + /** The max bytes limit that was applied */ + maxBytes: number; +} +export interface TruncationOptions { + /** Maximum number of lines (default: 2000) */ + maxLines?: number; + /** Maximum number of bytes (default: 50KB) */ + maxBytes?: number; +} +/** + * Format bytes as human-readable size. + */ +export declare function formatSize(bytes: number): string; +/** + * Truncate content from the head (keep first N lines/bytes). + * Suitable for file reads where you want to see the beginning. + * + * Never returns partial lines. If first line exceeds byte limit, + * returns empty content with firstLineExceedsLimit=true. + */ +export declare function truncateHead(content: string, options?: TruncationOptions): TruncationResult; +/** + * Truncate content from the tail (keep last N lines/bytes). + * Suitable for bash output where you want to see the end (errors, final results). + * + * May return partial first line if the last line of original content exceeds byte limit. + */ +export declare function truncateTail(content: string, options?: TruncationOptions): TruncationResult; +/** + * Truncate a single line to max characters, adding [truncated] suffix. + * Used for grep match lines. + */ +export declare function truncateLine(line: string, maxChars?: number): { + text: string; + wasTruncated: boolean; +}; +//# sourceMappingURL=truncate.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/truncate.d.ts.map b/dist/core/tools/truncate.d.ts.map new file mode 100644 index 0000000..def78d7 --- /dev/null +++ b/dist/core/tools/truncate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"truncate.d.ts","sourceRoot":"","sources":["../../../src/core/tools/truncate.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,eAAO,MAAM,iBAAiB,OAAO,CAAC;AACtC,eAAO,MAAM,iBAAiB,QAAY,CAAC;AAC3C,eAAO,MAAM,oBAAoB,MAAM,CAAC;AAExC,MAAM,WAAW,gBAAgB;IAChC,4BAA4B;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,kCAAkC;IAClC,SAAS,EAAE,OAAO,CAAC;IACnB,sEAAsE;IACtE,WAAW,EAAE,OAAO,GAAG,OAAO,GAAG,IAAI,CAAC;IACtC,oDAAoD;IACpD,UAAU,EAAE,MAAM,CAAC;IACnB,oDAAoD;IACpD,UAAU,EAAE,MAAM,CAAC;IACnB,uDAAuD;IACvD,WAAW,EAAE,MAAM,CAAC;IACpB,8CAA8C;IAC9C,WAAW,EAAE,MAAM,CAAC;IACpB,yFAAyF;IACzF,eAAe,EAAE,OAAO,CAAC;IACzB,2EAA2E;IAC3E,qBAAqB,EAAE,OAAO,CAAC;IAC/B,2CAA2C;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,2CAA2C;IAC3C,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,iBAAiB;IACjC,8CAA8C;IAC9C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAaD;;GAEG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAQhD;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB,GAAG,gBAAgB,CAkF/F;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB,GAAG,gBAAgB,CAyE/F;AAuBD;;;GAGG;AACH,wBAAgB,YAAY,CAC3B,IAAI,EAAE,MAAM,EACZ,QAAQ,GAAE,MAA6B,GACrC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,OAAO,CAAA;CAAE,CAKzC","sourcesContent":["/**\n * Shared truncation utilities for tool outputs.\n *\n * Truncation is based on two independent limits - whichever is hit first wins:\n * - Line limit (default: 2000 lines)\n * - Byte limit (default: 50KB)\n *\n * Never returns partial lines (except bash tail truncation edge case).\n */\n\nexport const DEFAULT_MAX_LINES = 2000;\nexport const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB\nexport const GREP_MAX_LINE_LENGTH = 500; // Max chars per grep match line\n\nexport interface TruncationResult {\n\t/** The truncated content */\n\tcontent: string;\n\t/** Whether truncation occurred */\n\ttruncated: boolean;\n\t/** Which limit was hit: \"lines\", \"bytes\", or null if not truncated */\n\ttruncatedBy: \"lines\" | \"bytes\" | null;\n\t/** Total number of lines in the original content */\n\ttotalLines: number;\n\t/** Total number of bytes in the original content */\n\ttotalBytes: number;\n\t/** Number of complete lines in the truncated output */\n\toutputLines: number;\n\t/** Number of bytes in the truncated output */\n\toutputBytes: number;\n\t/** Whether the last line was partially truncated (only for tail truncation edge case) */\n\tlastLinePartial: boolean;\n\t/** Whether the first line exceeded the byte limit (for head truncation) */\n\tfirstLineExceedsLimit: boolean;\n\t/** The max lines limit that was applied */\n\tmaxLines: number;\n\t/** The max bytes limit that was applied */\n\tmaxBytes: number;\n}\n\nexport interface TruncationOptions {\n\t/** Maximum number of lines (default: 2000) */\n\tmaxLines?: number;\n\t/** Maximum number of bytes (default: 50KB) */\n\tmaxBytes?: number;\n}\n\nfunction splitLinesForCounting(content: string): string[] {\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\tconst lines = content.split(\"\\n\");\n\tif (content.endsWith(\"\\n\")) {\n\t\tlines.pop();\n\t}\n\treturn lines;\n}\n\n/**\n * Format bytes as human-readable size.\n */\nexport function formatSize(bytes: number): string {\n\tif (bytes < 1024) {\n\t\treturn `${bytes}B`;\n\t} else if (bytes < 1024 * 1024) {\n\t\treturn `${(bytes / 1024).toFixed(1)}KB`;\n\t} else {\n\t\treturn `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n\t}\n}\n\n/**\n * Truncate content from the head (keep first N lines/bytes).\n * Suitable for file reads where you want to see the beginning.\n *\n * Never returns partial lines. If first line exceeds byte limit,\n * returns empty content with firstLineExceedsLimit=true.\n */\nexport function truncateHead(content: string, options: TruncationOptions = {}): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = Buffer.byteLength(content, \"utf-8\");\n\tconst lines = splitLinesForCounting(content);\n\tconst totalLines = lines.length;\n\n\t// Check if no truncation needed\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Check if first line alone exceeds byte limit\n\tconst firstLineBytes = Buffer.byteLength(lines[0], \"utf-8\");\n\tif (firstLineBytes > maxBytes) {\n\t\treturn {\n\t\t\tcontent: \"\",\n\t\t\ttruncated: true,\n\t\t\ttruncatedBy: \"bytes\",\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: 0,\n\t\t\toutputBytes: 0,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: true,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Collect complete lines that fit\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\n\tfor (let i = 0; i < lines.length && i < maxLines; i++) {\n\t\tconst line = lines[i];\n\t\tconst lineBytes = Buffer.byteLength(line, \"utf-8\") + (i > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.push(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\t// If we exited due to line limit\n\tif (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {\n\t\ttruncatedBy = \"lines\";\n\t}\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = Buffer.byteLength(outputContent, \"utf-8\");\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial: false,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n\n/**\n * Truncate content from the tail (keep last N lines/bytes).\n * Suitable for bash output where you want to see the end (errors, final results).\n *\n * May return partial first line if the last line of original content exceeds byte limit.\n */\nexport function truncateTail(content: string, options: TruncationOptions = {}): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = Buffer.byteLength(content, \"utf-8\");\n\tconst lines = splitLinesForCounting(content);\n\tconst totalLines = lines.length;\n\n\t// Check if no truncation needed\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Work backwards from the end\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\tlet lastLinePartial = false;\n\n\tfor (let i = lines.length - 1; i >= 0 && outputLinesArr.length < maxLines; i--) {\n\t\tconst line = lines[i];\n\t\tconst lineBytes = Buffer.byteLength(line, \"utf-8\") + (outputLinesArr.length > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\t// Edge case: if we haven't added ANY lines yet and this line exceeds maxBytes,\n\t\t\t// take the end of the line (partial)\n\t\t\tif (outputLinesArr.length === 0) {\n\t\t\t\tconst truncatedLine = truncateStringToBytesFromEnd(line, maxBytes);\n\t\t\t\toutputLinesArr.unshift(truncatedLine);\n\t\t\t\toutputBytesCount = Buffer.byteLength(truncatedLine, \"utf-8\");\n\t\t\t\tlastLinePartial = true;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.unshift(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\t// If we exited due to line limit\n\tif (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {\n\t\ttruncatedBy = \"lines\";\n\t}\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = Buffer.byteLength(outputContent, \"utf-8\");\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n\n/**\n * Truncate a string to fit within a byte limit (from the end).\n * Handles multi-byte UTF-8 characters correctly.\n */\nfunction truncateStringToBytesFromEnd(str: string, maxBytes: number): string {\n\tconst buf = Buffer.from(str, \"utf-8\");\n\tif (buf.length <= maxBytes) {\n\t\treturn str;\n\t}\n\n\t// Start from the end, skip maxBytes back\n\tlet start = buf.length - maxBytes;\n\n\t// Find a valid UTF-8 boundary (start of a character)\n\twhile (start < buf.length && (buf[start] & 0xc0) === 0x80) {\n\t\tstart++;\n\t}\n\n\treturn buf.slice(start).toString(\"utf-8\");\n}\n\n/**\n * Truncate a single line to max characters, adding [truncated] suffix.\n * Used for grep match lines.\n */\nexport function truncateLine(\n\tline: string,\n\tmaxChars: number = GREP_MAX_LINE_LENGTH,\n): { text: string; wasTruncated: boolean } {\n\tif (line.length <= maxChars) {\n\t\treturn { text: line, wasTruncated: false };\n\t}\n\treturn { text: `${line.slice(0, maxChars)}... [truncated]`, wasTruncated: true };\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/truncate.js b/dist/core/tools/truncate.js new file mode 100644 index 0000000..757a877 --- /dev/null +++ b/dist/core/tools/truncate.js @@ -0,0 +1,215 @@ +/** + * Shared truncation utilities for tool outputs. + * + * Truncation is based on two independent limits - whichever is hit first wins: + * - Line limit (default: 2000 lines) + * - Byte limit (default: 50KB) + * + * Never returns partial lines (except bash tail truncation edge case). + */ +export const DEFAULT_MAX_LINES = 2000; +export const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB +export const GREP_MAX_LINE_LENGTH = 500; // Max chars per grep match line +function splitLinesForCounting(content) { + if (content.length === 0) { + return []; + } + const lines = content.split("\n"); + if (content.endsWith("\n")) { + lines.pop(); + } + return lines; +} +/** + * Format bytes as human-readable size. + */ +export function formatSize(bytes) { + if (bytes < 1024) { + return `${bytes}B`; + } + else if (bytes < 1024 * 1024) { + return `${(bytes / 1024).toFixed(1)}KB`; + } + else { + return `${(bytes / (1024 * 1024)).toFixed(1)}MB`; + } +} +/** + * Truncate content from the head (keep first N lines/bytes). + * Suitable for file reads where you want to see the beginning. + * + * Never returns partial lines. If first line exceeds byte limit, + * returns empty content with firstLineExceedsLimit=true. + */ +export function truncateHead(content, options = {}) { + const maxLines = options.maxLines ?? DEFAULT_MAX_LINES; + const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES; + const totalBytes = Buffer.byteLength(content, "utf-8"); + const lines = splitLinesForCounting(content); + const totalLines = lines.length; + // Check if no truncation needed + if (totalLines <= maxLines && totalBytes <= maxBytes) { + return { + content, + truncated: false, + truncatedBy: null, + totalLines, + totalBytes, + outputLines: totalLines, + outputBytes: totalBytes, + lastLinePartial: false, + firstLineExceedsLimit: false, + maxLines, + maxBytes, + }; + } + // Check if first line alone exceeds byte limit + const firstLineBytes = Buffer.byteLength(lines[0], "utf-8"); + if (firstLineBytes > maxBytes) { + return { + content: "", + truncated: true, + truncatedBy: "bytes", + totalLines, + totalBytes, + outputLines: 0, + outputBytes: 0, + lastLinePartial: false, + firstLineExceedsLimit: true, + maxLines, + maxBytes, + }; + } + // Collect complete lines that fit + const outputLinesArr = []; + let outputBytesCount = 0; + let truncatedBy = "lines"; + for (let i = 0; i < lines.length && i < maxLines; i++) { + const line = lines[i]; + const lineBytes = Buffer.byteLength(line, "utf-8") + (i > 0 ? 1 : 0); // +1 for newline + if (outputBytesCount + lineBytes > maxBytes) { + truncatedBy = "bytes"; + break; + } + outputLinesArr.push(line); + outputBytesCount += lineBytes; + } + // If we exited due to line limit + if (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) { + truncatedBy = "lines"; + } + const outputContent = outputLinesArr.join("\n"); + const finalOutputBytes = Buffer.byteLength(outputContent, "utf-8"); + return { + content: outputContent, + truncated: true, + truncatedBy, + totalLines, + totalBytes, + outputLines: outputLinesArr.length, + outputBytes: finalOutputBytes, + lastLinePartial: false, + firstLineExceedsLimit: false, + maxLines, + maxBytes, + }; +} +/** + * Truncate content from the tail (keep last N lines/bytes). + * Suitable for bash output where you want to see the end (errors, final results). + * + * May return partial first line if the last line of original content exceeds byte limit. + */ +export function truncateTail(content, options = {}) { + const maxLines = options.maxLines ?? DEFAULT_MAX_LINES; + const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES; + const totalBytes = Buffer.byteLength(content, "utf-8"); + const lines = splitLinesForCounting(content); + const totalLines = lines.length; + // Check if no truncation needed + if (totalLines <= maxLines && totalBytes <= maxBytes) { + return { + content, + truncated: false, + truncatedBy: null, + totalLines, + totalBytes, + outputLines: totalLines, + outputBytes: totalBytes, + lastLinePartial: false, + firstLineExceedsLimit: false, + maxLines, + maxBytes, + }; + } + // Work backwards from the end + const outputLinesArr = []; + let outputBytesCount = 0; + let truncatedBy = "lines"; + let lastLinePartial = false; + for (let i = lines.length - 1; i >= 0 && outputLinesArr.length < maxLines; i--) { + const line = lines[i]; + const lineBytes = Buffer.byteLength(line, "utf-8") + (outputLinesArr.length > 0 ? 1 : 0); // +1 for newline + if (outputBytesCount + lineBytes > maxBytes) { + truncatedBy = "bytes"; + // Edge case: if we haven't added ANY lines yet and this line exceeds maxBytes, + // take the end of the line (partial) + if (outputLinesArr.length === 0) { + const truncatedLine = truncateStringToBytesFromEnd(line, maxBytes); + outputLinesArr.unshift(truncatedLine); + outputBytesCount = Buffer.byteLength(truncatedLine, "utf-8"); + lastLinePartial = true; + } + break; + } + outputLinesArr.unshift(line); + outputBytesCount += lineBytes; + } + // If we exited due to line limit + if (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) { + truncatedBy = "lines"; + } + const outputContent = outputLinesArr.join("\n"); + const finalOutputBytes = Buffer.byteLength(outputContent, "utf-8"); + return { + content: outputContent, + truncated: true, + truncatedBy, + totalLines, + totalBytes, + outputLines: outputLinesArr.length, + outputBytes: finalOutputBytes, + lastLinePartial, + firstLineExceedsLimit: false, + maxLines, + maxBytes, + }; +} +/** + * Truncate a string to fit within a byte limit (from the end). + * Handles multi-byte UTF-8 characters correctly. + */ +function truncateStringToBytesFromEnd(str, maxBytes) { + const buf = Buffer.from(str, "utf-8"); + if (buf.length <= maxBytes) { + return str; + } + // Start from the end, skip maxBytes back + let start = buf.length - maxBytes; + // Find a valid UTF-8 boundary (start of a character) + while (start < buf.length && (buf[start] & 0xc0) === 0x80) { + start++; + } + return buf.slice(start).toString("utf-8"); +} +/** + * Truncate a single line to max characters, adding [truncated] suffix. + * Used for grep match lines. + */ +export function truncateLine(line, maxChars = GREP_MAX_LINE_LENGTH) { + if (line.length <= maxChars) { + return { text: line, wasTruncated: false }; + } + return { text: `${line.slice(0, maxChars)}... [truncated]`, wasTruncated: true }; +} +//# sourceMappingURL=truncate.js.map \ No newline at end of file diff --git a/dist/core/tools/truncate.js.map b/dist/core/tools/truncate.js.map new file mode 100644 index 0000000..2a951d6 --- /dev/null +++ b/dist/core/tools/truncate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"truncate.js","sourceRoot":"","sources":["../../../src/core/tools/truncate.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AACtC,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,OAAO;AACnD,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAG,CAAC,CAAC,gCAAgC;AAkCzE,SAAS,qBAAqB,CAAC,OAAe,EAAY;IACzD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1B,OAAO,EAAE,CAAC;IACX,CAAC;IACD,MAAM,KAAK,GAAG,OAAO,CAAC,K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KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,iBAAiB,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC;AAAA,CACjF","sourcesContent":["/**\n * Shared truncation utilities for tool outputs.\n *\n * Truncation is based on two independent limits - whichever is hit first wins:\n * - Line limit (default: 2000 lines)\n * - Byte limit (default: 50KB)\n *\n * Never returns partial lines (except bash tail truncation edge case).\n */\n\nexport const DEFAULT_MAX_LINES = 2000;\nexport const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB\nexport const GREP_MAX_LINE_LENGTH = 500; // Max chars per grep match line\n\nexport interface TruncationResult {\n\t/** The truncated content */\n\tcontent: string;\n\t/** Whether truncation occurred */\n\ttruncated: boolean;\n\t/** Which limit was hit: \"lines\", \"bytes\", or null if not truncated */\n\ttruncatedBy: \"lines\" | \"bytes\" | null;\n\t/** Total number of lines in the original content */\n\ttotalLines: number;\n\t/** Total number of bytes in the original content */\n\ttotalBytes: number;\n\t/** Number of complete lines in the truncated output */\n\toutputLines: number;\n\t/** Number of bytes in the truncated output */\n\toutputBytes: number;\n\t/** Whether the last line was partially truncated (only for tail truncation edge case) */\n\tlastLinePartial: boolean;\n\t/** Whether the first line exceeded the byte limit (for head truncation) */\n\tfirstLineExceedsLimit: boolean;\n\t/** The max lines limit that was applied */\n\tmaxLines: number;\n\t/** The max bytes limit that was applied */\n\tmaxBytes: number;\n}\n\nexport interface TruncationOptions {\n\t/** Maximum number of lines (default: 2000) */\n\tmaxLines?: number;\n\t/** Maximum number of bytes (default: 50KB) */\n\tmaxBytes?: number;\n}\n\nfunction splitLinesForCounting(content: string): string[] {\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\tconst lines = content.split(\"\\n\");\n\tif (content.endsWith(\"\\n\")) {\n\t\tlines.pop();\n\t}\n\treturn lines;\n}\n\n/**\n * Format bytes as human-readable size.\n */\nexport function formatSize(bytes: number): string {\n\tif (bytes < 1024) {\n\t\treturn `${bytes}B`;\n\t} else if (bytes < 1024 * 1024) {\n\t\treturn `${(bytes / 1024).toFixed(1)}KB`;\n\t} else {\n\t\treturn `${(bytes / (1024 * 1024)).toFixed(1)}MB`;\n\t}\n}\n\n/**\n * Truncate content from the head (keep first N lines/bytes).\n * Suitable for file reads where you want to see the beginning.\n *\n * Never returns partial lines. If first line exceeds byte limit,\n * returns empty content with firstLineExceedsLimit=true.\n */\nexport function truncateHead(content: string, options: TruncationOptions = {}): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = Buffer.byteLength(content, \"utf-8\");\n\tconst lines = splitLinesForCounting(content);\n\tconst totalLines = lines.length;\n\n\t// Check if no truncation needed\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Check if first line alone exceeds byte limit\n\tconst firstLineBytes = Buffer.byteLength(lines[0], \"utf-8\");\n\tif (firstLineBytes > maxBytes) {\n\t\treturn {\n\t\t\tcontent: \"\",\n\t\t\ttruncated: true,\n\t\t\ttruncatedBy: \"bytes\",\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: 0,\n\t\t\toutputBytes: 0,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: true,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Collect complete lines that fit\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\n\tfor (let i = 0; i < lines.length && i < maxLines; i++) {\n\t\tconst line = lines[i];\n\t\tconst lineBytes = Buffer.byteLength(line, \"utf-8\") + (i > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.push(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\t// If we exited due to line limit\n\tif (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {\n\t\ttruncatedBy = \"lines\";\n\t}\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = Buffer.byteLength(outputContent, \"utf-8\");\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial: false,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n\n/**\n * Truncate content from the tail (keep last N lines/bytes).\n * Suitable for bash output where you want to see the end (errors, final results).\n *\n * May return partial first line if the last line of original content exceeds byte limit.\n */\nexport function truncateTail(content: string, options: TruncationOptions = {}): TruncationResult {\n\tconst maxLines = options.maxLines ?? DEFAULT_MAX_LINES;\n\tconst maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\n\n\tconst totalBytes = Buffer.byteLength(content, \"utf-8\");\n\tconst lines = splitLinesForCounting(content);\n\tconst totalLines = lines.length;\n\n\t// Check if no truncation needed\n\tif (totalLines <= maxLines && totalBytes <= maxBytes) {\n\t\treturn {\n\t\t\tcontent,\n\t\t\ttruncated: false,\n\t\t\ttruncatedBy: null,\n\t\t\ttotalLines,\n\t\t\ttotalBytes,\n\t\t\toutputLines: totalLines,\n\t\t\toutputBytes: totalBytes,\n\t\t\tlastLinePartial: false,\n\t\t\tfirstLineExceedsLimit: false,\n\t\t\tmaxLines,\n\t\t\tmaxBytes,\n\t\t};\n\t}\n\n\t// Work backwards from the end\n\tconst outputLinesArr: string[] = [];\n\tlet outputBytesCount = 0;\n\tlet truncatedBy: \"lines\" | \"bytes\" = \"lines\";\n\tlet lastLinePartial = false;\n\n\tfor (let i = lines.length - 1; i >= 0 && outputLinesArr.length < maxLines; i--) {\n\t\tconst line = lines[i];\n\t\tconst lineBytes = Buffer.byteLength(line, \"utf-8\") + (outputLinesArr.length > 0 ? 1 : 0); // +1 for newline\n\n\t\tif (outputBytesCount + lineBytes > maxBytes) {\n\t\t\ttruncatedBy = \"bytes\";\n\t\t\t// Edge case: if we haven't added ANY lines yet and this line exceeds maxBytes,\n\t\t\t// take the end of the line (partial)\n\t\t\tif (outputLinesArr.length === 0) {\n\t\t\t\tconst truncatedLine = truncateStringToBytesFromEnd(line, maxBytes);\n\t\t\t\toutputLinesArr.unshift(truncatedLine);\n\t\t\t\toutputBytesCount = Buffer.byteLength(truncatedLine, \"utf-8\");\n\t\t\t\tlastLinePartial = true;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\toutputLinesArr.unshift(line);\n\t\toutputBytesCount += lineBytes;\n\t}\n\n\t// If we exited due to line limit\n\tif (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {\n\t\ttruncatedBy = \"lines\";\n\t}\n\n\tconst outputContent = outputLinesArr.join(\"\\n\");\n\tconst finalOutputBytes = Buffer.byteLength(outputContent, \"utf-8\");\n\n\treturn {\n\t\tcontent: outputContent,\n\t\ttruncated: true,\n\t\ttruncatedBy,\n\t\ttotalLines,\n\t\ttotalBytes,\n\t\toutputLines: outputLinesArr.length,\n\t\toutputBytes: finalOutputBytes,\n\t\tlastLinePartial,\n\t\tfirstLineExceedsLimit: false,\n\t\tmaxLines,\n\t\tmaxBytes,\n\t};\n}\n\n/**\n * Truncate a string to fit within a byte limit (from the end).\n * Handles multi-byte UTF-8 characters correctly.\n */\nfunction truncateStringToBytesFromEnd(str: string, maxBytes: number): string {\n\tconst buf = Buffer.from(str, \"utf-8\");\n\tif (buf.length <= maxBytes) {\n\t\treturn str;\n\t}\n\n\t// Start from the end, skip maxBytes back\n\tlet start = buf.length - maxBytes;\n\n\t// Find a valid UTF-8 boundary (start of a character)\n\twhile (start < buf.length && (buf[start] & 0xc0) === 0x80) {\n\t\tstart++;\n\t}\n\n\treturn buf.slice(start).toString(\"utf-8\");\n}\n\n/**\n * Truncate a single line to max characters, adding [truncated] suffix.\n * Used for grep match lines.\n */\nexport function truncateLine(\n\tline: string,\n\tmaxChars: number = GREP_MAX_LINE_LENGTH,\n): { text: string; wasTruncated: boolean } {\n\tif (line.length <= maxChars) {\n\t\treturn { text: line, wasTruncated: false };\n\t}\n\treturn { text: `${line.slice(0, maxChars)}... [truncated]`, wasTruncated: true };\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/write.d.ts b/dist/core/tools/write.d.ts new file mode 100644 index 0000000..d30c83f --- /dev/null +++ b/dist/core/tools/write.d.ts @@ -0,0 +1,26 @@ +import type { AgentTool } from "@earendil-works/pi-agent-core"; +import { type Static, Type } from "typebox"; +import type { ToolDefinition } from "../extensions/types.ts"; +declare const writeSchema: Type.TObject<{ + path: Type.TString; + content: Type.TString; +}>; +export type WriteToolInput = Static; +/** + * Pluggable operations for the write tool. + * Override these to delegate file writing to remote systems (for example SSH). + */ +export interface WriteOperations { + /** Write content to a file */ + writeFile: (absolutePath: string, content: string) => Promise; + /** Create directory recursively */ + mkdir: (dir: string) => Promise; +} +export interface WriteToolOptions { + /** Custom operations for file writing. Default: local filesystem */ + operations?: WriteOperations; +} +export declare function createWriteToolDefinition(cwd: string, options?: WriteToolOptions): ToolDefinition; +export declare function createWriteTool(cwd: string, options?: WriteToolOptions): AgentTool; +export {}; +//# sourceMappingURL=write.d.ts.map \ No newline at end of file diff --git a/dist/core/tools/write.d.ts.map b/dist/core/tools/write.d.ts.map new file mode 100644 index 0000000..0e1b63d --- /dev/null +++ b/dist/core/tools/write.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAI/D,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAMtF,QAAA,MAAM,WAAW;;;EAGf,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAExD;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC/B,8BAA8B;IAC9B,SAAS,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpE,mCAAmC;IACnC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC;AAOD,MAAM,WAAW,gBAAgB;IAChC,oEAAoE;IACpE,UAAU,CAAC,EAAE,eAAe,CAAC;CAC7B;AA6ID,wBAAgB,yBAAyB,CACxC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,gBAAgB,GACxB,cAAc,CAAC,OAAO,WAAW,EAAE,SAAS,CAAC,CA+E/C;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,SAAS,CAAC,OAAO,WAAW,CAAC,CAEtG","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Container, Text } from \"@earendil-works/pi-tui\";\nimport { mkdir as fsMkdir, writeFile as fsWriteFile } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { normalizeDisplayText, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport type WriteToolInput = Static;\n\n/**\n * Pluggable operations for the write tool.\n * Override these to delegate file writing to remote systems (for example SSH).\n */\nexport interface WriteOperations {\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise;\n\t/** Create directory recursively */\n\tmkdir: (dir: string) => Promise;\n}\n\nconst defaultWriteOperations: WriteOperations = {\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\tmkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => {}),\n};\n\nexport interface WriteToolOptions {\n\t/** Custom operations for file writing. Default: local filesystem */\n\toperations?: WriteOperations;\n}\n\ntype WriteHighlightCache = {\n\trawPath: string | null;\n\tlang: string;\n\trawContent: string;\n\tnormalizedLines: string[];\n\thighlightedLines: string[];\n};\n\nclass WriteCallRenderComponent extends Text {\n\tcache?: WriteHighlightCache;\n\n\tconstructor() {\n\t\tsuper(\"\", 0, 0);\n\t}\n}\n\nconst WRITE_PARTIAL_FULL_HIGHLIGHT_LINES = 50;\n\nfunction highlightSingleLine(line: string, lang: string): string {\n\tconst highlighted = highlightCode(line, lang);\n\treturn highlighted[0] ?? \"\";\n}\n\nfunction refreshWriteHighlightPrefix(cache: WriteHighlightCache): void {\n\tconst prefixCount = Math.min(WRITE_PARTIAL_FULL_HIGHLIGHT_LINES, cache.normalizedLines.length);\n\tif (prefixCount === 0) return;\n\tconst prefixSource = cache.normalizedLines.slice(0, prefixCount).join(\"\\n\");\n\tconst prefixHighlighted = highlightCode(prefixSource, cache.lang);\n\tfor (let i = 0; i < prefixCount; i++) {\n\t\tcache.highlightedLines[i] =\n\t\t\tprefixHighlighted[i] ?? highlightSingleLine(cache.normalizedLines[i] ?? \"\", cache.lang);\n\t}\n}\n\nfunction rebuildWriteHighlightCacheFull(rawPath: string | null, fileContent: string): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tconst displayContent = normalizeDisplayText(fileContent);\n\tconst normalized = replaceTabs(displayContent);\n\treturn {\n\t\trawPath,\n\t\tlang,\n\t\trawContent: fileContent,\n\t\tnormalizedLines: normalized.split(\"\\n\"),\n\t\thighlightedLines: highlightCode(normalized, lang),\n\t};\n}\n\nfunction updateWriteHighlightCacheIncremental(\n\tcache: WriteHighlightCache | undefined,\n\trawPath: string | null,\n\tfileContent: string,\n): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tif (!cache) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (cache.lang !== lang || cache.rawPath !== rawPath) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (!fileContent.startsWith(cache.rawContent)) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (fileContent.length === cache.rawContent.length) return cache;\n\n\tconst deltaRaw = fileContent.slice(cache.rawContent.length);\n\tconst deltaDisplay = normalizeDisplayText(deltaRaw);\n\tconst deltaNormalized = replaceTabs(deltaDisplay);\n\tcache.rawContent = fileContent;\n\tif (cache.normalizedLines.length === 0) {\n\t\tcache.normalizedLines.push(\"\");\n\t\tcache.highlightedLines.push(\"\");\n\t}\n\n\tconst segments = deltaNormalized.split(\"\\n\");\n\tconst lastIndex = cache.normalizedLines.length - 1;\n\tcache.normalizedLines[lastIndex] += segments[0];\n\tcache.highlightedLines[lastIndex] = highlightSingleLine(cache.normalizedLines[lastIndex], cache.lang);\n\tfor (let i = 1; i < segments.length; i++) {\n\t\tcache.normalizedLines.push(segments[i]);\n\t\tcache.highlightedLines.push(highlightSingleLine(segments[i], cache.lang));\n\t}\n\trefreshWriteHighlightPrefix(cache);\n\treturn cache;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction formatWriteCall(\n\targs: { path?: string; file_path?: string; content?: string } | undefined,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tcache: WriteHighlightCache | undefined,\n\tcwd: string,\n): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst fileContent = str(args?.content);\n\tconst pathDisplay = renderToolPath(rawPath, theme, cwd);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"write\"))} ${pathDisplay}`;\n\n\tif (fileContent === null) {\n\t\ttext += `\\n\\n${theme.fg(\"error\", \"[invalid content arg - expected string]\")}`;\n\t} else if (fileContent) {\n\t\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\t\tconst renderedLines = lang\n\t\t\t? (cache?.highlightedLines ?? highlightCode(replaceTabs(normalizeDisplayText(fileContent)), lang))\n\t\t\t: normalizeDisplayText(fileContent).split(\"\\n\");\n\t\tconst lines = trimTrailingEmptyLines(renderedLines);\n\t\tconst totalLines = lines.length;\n\t\tconst maxLines = options.expanded ? lines.length : 10;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n\\n${displayLines.map((line) => (lang ? line : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines, ${totalLines} total,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\treturn text;\n}\n\nfunction formatWriteResult(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; isError?: boolean },\n\ttheme: Theme,\n): string | undefined {\n\tif (!result.isError) {\n\t\treturn undefined;\n\t}\n\tconst output = result.content\n\t\t.filter((c) => c.type === \"text\")\n\t\t.map((c) => c.text || \"\")\n\t\t.join(\"\\n\");\n\tif (!output) {\n\t\treturn undefined;\n\t}\n\treturn `\\n${theme.fg(\"error\", output)}`;\n}\n\nexport function createWriteToolDefinition(\n\tcwd: string,\n\toptions?: WriteToolOptions,\n): ToolDefinition {\n\tconst ops = options?.operations ?? defaultWriteOperations;\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tpromptSnippet: \"Create or overwrite files\",\n\t\tpromptGuidelines: [\"Use write only for new files or complete rewrites.\"],\n\t\tparameters: writeSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, content }: { path: string; content: string },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\tconst absolutePath = resolveToCwd(path, cwd);\n\t\t\tconst dir = dirname(absolutePath);\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\t\t\t\t// Create parent directories if needed.\n\t\t\t\tawait ops.mkdir(dir);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Write the file contents.\n\t\t\t\tawait ops.writeFile(absolutePath, content);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Successfully wrote ${content.length} bytes to ${path}` }],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst renderArgs = args as { path?: string; file_path?: string; content?: string } | undefined;\n\t\t\tconst rawPath = str(renderArgs?.file_path ?? renderArgs?.path);\n\t\t\tconst fileContent = str(renderArgs?.content);\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as WriteCallRenderComponent | undefined) ?? new WriteCallRenderComponent();\n\t\t\tif (fileContent !== null) {\n\t\t\t\tcomponent.cache = context.argsComplete\n\t\t\t\t\t? rebuildWriteHighlightCacheFull(rawPath, fileContent)\n\t\t\t\t\t: updateWriteHighlightCacheIncremental(component.cache, rawPath, fileContent);\n\t\t\t} else {\n\t\t\t\tcomponent.cache = undefined;\n\t\t\t}\n\t\t\tcomponent.setText(\n\t\t\t\tformatWriteCall(\n\t\t\t\t\trenderArgs,\n\t\t\t\t\t{ expanded: context.expanded, isPartial: context.isPartial },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcomponent.cache,\n\t\t\t\t\tcontext.cwd,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst output = formatWriteResult({ ...result, isError: context.isError }, theme);\n\t\t\tif (!output) {\n\t\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\t\tcomponent.clear();\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(output);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createWriteTool(cwd: string, options?: WriteToolOptions): AgentTool {\n\treturn wrapToolDefinition(createWriteToolDefinition(cwd, options));\n}\n"]} \ No newline at end of file diff --git a/dist/core/tools/write.js b/dist/core/tools/write.js new file mode 100644 index 0000000..a80b81d --- /dev/null +++ b/dist/core/tools/write.js @@ -0,0 +1,197 @@ +import { Container, Text } from "@earendil-works/pi-tui"; +import { mkdir as fsMkdir, writeFile as fsWriteFile } from "fs/promises"; +import { dirname } from "path"; +import { Type } from "typebox"; +import { keyHint } from "../../modes/interactive/components/keybinding-hints.js"; +import { getLanguageFromPath, highlightCode } from "../../modes/interactive/theme/theme.js"; +import { withFileMutationQueue } from "./file-mutation-queue.js"; +import { resolveToCwd } from "./path-utils.js"; +import { normalizeDisplayText, renderToolPath, replaceTabs, str } from "./render-utils.js"; +import { wrapToolDefinition } from "./tool-definition-wrapper.js"; +const writeSchema = Type.Object({ + path: Type.String({ description: "Path to the file to write (relative or absolute)" }), + content: Type.String({ description: "Content to write to the file" }), +}); +const defaultWriteOperations = { + writeFile: (path, content) => fsWriteFile(path, content, "utf-8"), + mkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => { }), +}; +class WriteCallRenderComponent extends Text { + cache; + constructor() { + super("", 0, 0); + } +} +const WRITE_PARTIAL_FULL_HIGHLIGHT_LINES = 50; +function highlightSingleLine(line, lang) { + const highlighted = highlightCode(line, lang); + return highlighted[0] ?? ""; +} +function refreshWriteHighlightPrefix(cache) { + const prefixCount = Math.min(WRITE_PARTIAL_FULL_HIGHLIGHT_LINES, cache.normalizedLines.length); + if (prefixCount === 0) + return; + const prefixSource = cache.normalizedLines.slice(0, prefixCount).join("\n"); + const prefixHighlighted = highlightCode(prefixSource, cache.lang); + for (let i = 0; i < prefixCount; i++) { + cache.highlightedLines[i] = + prefixHighlighted[i] ?? highlightSingleLine(cache.normalizedLines[i] ?? "", cache.lang); + } +} +function rebuildWriteHighlightCacheFull(rawPath, fileContent) { + const lang = rawPath ? getLanguageFromPath(rawPath) : undefined; + if (!lang) + return undefined; + const displayContent = normalizeDisplayText(fileContent); + const normalized = replaceTabs(displayContent); + return { + rawPath, + lang, + rawContent: fileContent, + normalizedLines: normalized.split("\n"), + highlightedLines: highlightCode(normalized, lang), + }; +} +function updateWriteHighlightCacheIncremental(cache, rawPath, fileContent) { + const lang = rawPath ? getLanguageFromPath(rawPath) : undefined; + if (!lang) + return undefined; + if (!cache) + return rebuildWriteHighlightCacheFull(rawPath, fileContent); + if (cache.lang !== lang || cache.rawPath !== rawPath) + return rebuildWriteHighlightCacheFull(rawPath, fileContent); + if (!fileContent.startsWith(cache.rawContent)) + return rebuildWriteHighlightCacheFull(rawPath, fileContent); + if (fileContent.length === cache.rawContent.length) + return cache; + const deltaRaw = fileContent.slice(cache.rawContent.length); + const deltaDisplay = normalizeDisplayText(deltaRaw); + const deltaNormalized = replaceTabs(deltaDisplay); + cache.rawContent = fileContent; + if (cache.normalizedLines.length === 0) { + cache.normalizedLines.push(""); + cache.highlightedLines.push(""); + } + const segments = deltaNormalized.split("\n"); + const lastIndex = cache.normalizedLines.length - 1; + cache.normalizedLines[lastIndex] += segments[0]; + cache.highlightedLines[lastIndex] = highlightSingleLine(cache.normalizedLines[lastIndex], cache.lang); + for (let i = 1; i < segments.length; i++) { + cache.normalizedLines.push(segments[i]); + cache.highlightedLines.push(highlightSingleLine(segments[i], cache.lang)); + } + refreshWriteHighlightPrefix(cache); + return cache; +} +function trimTrailingEmptyLines(lines) { + let end = lines.length; + while (end > 0 && lines[end - 1] === "") { + end--; + } + return lines.slice(0, end); +} +function formatWriteCall(args, options, theme, cache, cwd) { + const rawPath = str(args?.file_path ?? args?.path); + const fileContent = str(args?.content); + const pathDisplay = renderToolPath(rawPath, theme, cwd); + let text = `${theme.fg("toolTitle", theme.bold("write"))} ${pathDisplay}`; + if (fileContent === null) { + text += `\n\n${theme.fg("error", "[invalid content arg - expected string]")}`; + } + else if (fileContent) { + const lang = rawPath ? getLanguageFromPath(rawPath) : undefined; + const renderedLines = lang + ? (cache?.highlightedLines ?? highlightCode(replaceTabs(normalizeDisplayText(fileContent)), lang)) + : normalizeDisplayText(fileContent).split("\n"); + const lines = trimTrailingEmptyLines(renderedLines); + const totalLines = lines.length; + const maxLines = options.expanded ? lines.length : 10; + const displayLines = lines.slice(0, maxLines); + const remaining = lines.length - maxLines; + text += `\n\n${displayLines.map((line) => (lang ? line : theme.fg("toolOutput", replaceTabs(line)))).join("\n")}`; + if (remaining > 0) { + text += `${theme.fg("muted", `\n... (${remaining} more lines, ${totalLines} total,`)} ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`; + } + } + return text; +} +function formatWriteResult(result, theme) { + if (!result.isError) { + return undefined; + } + const output = result.content + .filter((c) => c.type === "text") + .map((c) => c.text || "") + .join("\n"); + if (!output) { + return undefined; + } + return `\n${theme.fg("error", output)}`; +} +export function createWriteToolDefinition(cwd, options) { + const ops = options?.operations ?? defaultWriteOperations; + return { + name: "write", + label: "write", + description: "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.", + promptSnippet: "Create or overwrite files", + promptGuidelines: ["Use write only for new files or complete rewrites."], + parameters: writeSchema, + async execute(_toolCallId, { path, content }, signal, _onUpdate, _ctx) { + const absolutePath = resolveToCwd(path, cwd); + const dir = dirname(absolutePath); + return withFileMutationQueue(absolutePath, async () => { + // Do not reject from an abort event listener here: that would release the + // mutation queue while an in-flight filesystem operation may still finish. + // Checking signal.aborted after each await observes the same aborts while + // keeping the queue locked until the current operation has settled. + const throwIfAborted = () => { + if (signal?.aborted) + throw new Error("Operation aborted"); + }; + throwIfAborted(); + // Create parent directories if needed. + await ops.mkdir(dir); + throwIfAborted(); + // Write the file contents. + await ops.writeFile(absolutePath, content); + throwIfAborted(); + return { + content: [{ type: "text", text: `Successfully wrote ${content.length} bytes to ${path}` }], + details: undefined, + }; + }); + }, + renderCall(args, theme, context) { + const renderArgs = args; + const rawPath = str(renderArgs?.file_path ?? renderArgs?.path); + const fileContent = str(renderArgs?.content); + const component = context.lastComponent ?? new WriteCallRenderComponent(); + if (fileContent !== null) { + component.cache = context.argsComplete + ? rebuildWriteHighlightCacheFull(rawPath, fileContent) + : updateWriteHighlightCacheIncremental(component.cache, rawPath, fileContent); + } + else { + component.cache = undefined; + } + component.setText(formatWriteCall(renderArgs, { expanded: context.expanded, isPartial: context.isPartial }, theme, component.cache, context.cwd)); + return component; + }, + renderResult(result, _options, theme, context) { + const output = formatWriteResult({ ...result, isError: context.isError }, theme); + if (!output) { + const component = context.lastComponent ?? new Container(); + component.clear(); + return component; + } + const text = context.lastComponent ?? new Text("", 0, 0); + text.setText(output); + return text; + }, + }; +} +export function createWriteTool(cwd, options) { + return wrapToolDefinition(createWriteToolDefinition(cwd, options)); +} +//# sourceMappingURL=write.js.map \ No newline at end of file diff --git a/dist/core/tools/write.js.map b/dist/core/tools/write.js.map new file mode 100644 index 0000000..ac0ea7a --- /dev/null +++ b/dist/core/tools/write.js.map @@ -0,0 +1 @@ +{"version":3,"file":"write.js","sourceRoot":"","sources":["../../../src/core/tools/write.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,KAAK,IAAI,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAc,MAAM,wCAAwC,CAAC;AAExG,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAC3F,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,MAAM,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC;IAC/B,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,kDAAkD,EAAE,CAA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O,CAAC,GAAG,CACX,CACD,CAAC;YACF,OAAO,SAAS,CAAC;QAAA,CACjB;QACD,YAAY,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE;YAC9C,MAAM,MAAM,GAAG,iBAAiB,CAAC,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,EAAE,KAAK,CAAC,CAAC;YACjF,IAAI,CAAC,MAAM,EAAE,CAAC;gBACb,MAAM,SAAS,GAAI,OAAO,CAAC,aAAuC,IAAI,IAAI,SAAS,EAAE,CAAC;gBACtF,SAAS,CAAC,KAAK,EAAE,CAAC;gBAClB,OAAO,SAAS,CAAC;YAClB,CAAC;YACD,MAAM,IAAI,GAAI,OAAO,CAAC,aAAkC,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YACrB,OAAO,IAAI,CAAC;QAAA,CACZ;KACD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,eAAe,CAAC,GAAW,EAAE,OAA0B,EAAiC;IACvG,OAAO,kBAAkB,CAAC,yBAAyB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CACnE","sourcesContent":["import type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport { Container, Text } from \"@earendil-works/pi-tui\";\nimport { mkdir as fsMkdir, writeFile as fsWriteFile } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { withFileMutationQueue } from \"./file-mutation-queue.ts\";\nimport { resolveToCwd } from \"./path-utils.ts\";\nimport { normalizeDisplayText, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\n\nconst writeSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to write (relative or absolute)\" }),\n\tcontent: Type.String({ description: \"Content to write to the file\" }),\n});\n\nexport type WriteToolInput = Static;\n\n/**\n * Pluggable operations for the write tool.\n * Override these to delegate file writing to remote systems (for example SSH).\n */\nexport interface WriteOperations {\n\t/** Write content to a file */\n\twriteFile: (absolutePath: string, content: string) => Promise;\n\t/** Create directory recursively */\n\tmkdir: (dir: string) => Promise;\n}\n\nconst defaultWriteOperations: WriteOperations = {\n\twriteFile: (path, content) => fsWriteFile(path, content, \"utf-8\"),\n\tmkdir: (dir) => fsMkdir(dir, { recursive: true }).then(() => {}),\n};\n\nexport interface WriteToolOptions {\n\t/** Custom operations for file writing. Default: local filesystem */\n\toperations?: WriteOperations;\n}\n\ntype WriteHighlightCache = {\n\trawPath: string | null;\n\tlang: string;\n\trawContent: string;\n\tnormalizedLines: string[];\n\thighlightedLines: string[];\n};\n\nclass WriteCallRenderComponent extends Text {\n\tcache?: WriteHighlightCache;\n\n\tconstructor() {\n\t\tsuper(\"\", 0, 0);\n\t}\n}\n\nconst WRITE_PARTIAL_FULL_HIGHLIGHT_LINES = 50;\n\nfunction highlightSingleLine(line: string, lang: string): string {\n\tconst highlighted = highlightCode(line, lang);\n\treturn highlighted[0] ?? \"\";\n}\n\nfunction refreshWriteHighlightPrefix(cache: WriteHighlightCache): void {\n\tconst prefixCount = Math.min(WRITE_PARTIAL_FULL_HIGHLIGHT_LINES, cache.normalizedLines.length);\n\tif (prefixCount === 0) return;\n\tconst prefixSource = cache.normalizedLines.slice(0, prefixCount).join(\"\\n\");\n\tconst prefixHighlighted = highlightCode(prefixSource, cache.lang);\n\tfor (let i = 0; i < prefixCount; i++) {\n\t\tcache.highlightedLines[i] =\n\t\t\tprefixHighlighted[i] ?? highlightSingleLine(cache.normalizedLines[i] ?? \"\", cache.lang);\n\t}\n}\n\nfunction rebuildWriteHighlightCacheFull(rawPath: string | null, fileContent: string): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tconst displayContent = normalizeDisplayText(fileContent);\n\tconst normalized = replaceTabs(displayContent);\n\treturn {\n\t\trawPath,\n\t\tlang,\n\t\trawContent: fileContent,\n\t\tnormalizedLines: normalized.split(\"\\n\"),\n\t\thighlightedLines: highlightCode(normalized, lang),\n\t};\n}\n\nfunction updateWriteHighlightCacheIncremental(\n\tcache: WriteHighlightCache | undefined,\n\trawPath: string | null,\n\tfileContent: string,\n): WriteHighlightCache | undefined {\n\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tif (!lang) return undefined;\n\tif (!cache) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (cache.lang !== lang || cache.rawPath !== rawPath) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (!fileContent.startsWith(cache.rawContent)) return rebuildWriteHighlightCacheFull(rawPath, fileContent);\n\tif (fileContent.length === cache.rawContent.length) return cache;\n\n\tconst deltaRaw = fileContent.slice(cache.rawContent.length);\n\tconst deltaDisplay = normalizeDisplayText(deltaRaw);\n\tconst deltaNormalized = replaceTabs(deltaDisplay);\n\tcache.rawContent = fileContent;\n\tif (cache.normalizedLines.length === 0) {\n\t\tcache.normalizedLines.push(\"\");\n\t\tcache.highlightedLines.push(\"\");\n\t}\n\n\tconst segments = deltaNormalized.split(\"\\n\");\n\tconst lastIndex = cache.normalizedLines.length - 1;\n\tcache.normalizedLines[lastIndex] += segments[0];\n\tcache.highlightedLines[lastIndex] = highlightSingleLine(cache.normalizedLines[lastIndex], cache.lang);\n\tfor (let i = 1; i < segments.length; i++) {\n\t\tcache.normalizedLines.push(segments[i]);\n\t\tcache.highlightedLines.push(highlightSingleLine(segments[i], cache.lang));\n\t}\n\trefreshWriteHighlightPrefix(cache);\n\treturn cache;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction formatWriteCall(\n\targs: { path?: string; file_path?: string; content?: string } | undefined,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tcache: WriteHighlightCache | undefined,\n\tcwd: string,\n): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst fileContent = str(args?.content);\n\tconst pathDisplay = renderToolPath(rawPath, theme, cwd);\n\tlet text = `${theme.fg(\"toolTitle\", theme.bold(\"write\"))} ${pathDisplay}`;\n\n\tif (fileContent === null) {\n\t\ttext += `\\n\\n${theme.fg(\"error\", \"[invalid content arg - expected string]\")}`;\n\t} else if (fileContent) {\n\t\tconst lang = rawPath ? getLanguageFromPath(rawPath) : undefined;\n\t\tconst renderedLines = lang\n\t\t\t? (cache?.highlightedLines ?? highlightCode(replaceTabs(normalizeDisplayText(fileContent)), lang))\n\t\t\t: normalizeDisplayText(fileContent).split(\"\\n\");\n\t\tconst lines = trimTrailingEmptyLines(renderedLines);\n\t\tconst totalLines = lines.length;\n\t\tconst maxLines = options.expanded ? lines.length : 10;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n\\n${displayLines.map((line) => (lang ? line : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines, ${totalLines} total,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t}\n\t}\n\n\treturn text;\n}\n\nfunction formatWriteResult(\n\tresult: { content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; isError?: boolean },\n\ttheme: Theme,\n): string | undefined {\n\tif (!result.isError) {\n\t\treturn undefined;\n\t}\n\tconst output = result.content\n\t\t.filter((c) => c.type === \"text\")\n\t\t.map((c) => c.text || \"\")\n\t\t.join(\"\\n\");\n\tif (!output) {\n\t\treturn undefined;\n\t}\n\treturn `\\n${theme.fg(\"error\", output)}`;\n}\n\nexport function createWriteToolDefinition(\n\tcwd: string,\n\toptions?: WriteToolOptions,\n): ToolDefinition {\n\tconst ops = options?.operations ?? defaultWriteOperations;\n\treturn {\n\t\tname: \"write\",\n\t\tlabel: \"write\",\n\t\tdescription:\n\t\t\t\"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.\",\n\t\tpromptSnippet: \"Create or overwrite files\",\n\t\tpromptGuidelines: [\"Use write only for new files or complete rewrites.\"],\n\t\tparameters: writeSchema,\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\t{ path, content }: { path: string; content: string },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\t_ctx?,\n\t\t) {\n\t\t\tconst absolutePath = resolveToCwd(path, cwd);\n\t\t\tconst dir = dirname(absolutePath);\n\t\t\treturn withFileMutationQueue(absolutePath, async () => {\n\t\t\t\t// Do not reject from an abort event listener here: that would release the\n\t\t\t\t// mutation queue while an in-flight filesystem operation may still finish.\n\t\t\t\t// Checking signal.aborted after each await observes the same aborts while\n\t\t\t\t// keeping the queue locked until the current operation has settled.\n\t\t\t\tconst throwIfAborted = (): void => {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\t};\n\n\t\t\t\tthrowIfAborted();\n\t\t\t\t// Create parent directories if needed.\n\t\t\t\tawait ops.mkdir(dir);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\t// Write the file contents.\n\t\t\t\tawait ops.writeFile(absolutePath, content);\n\t\t\t\tthrowIfAborted();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Successfully wrote ${content.length} bytes to ${path}` }],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst renderArgs = args as { path?: string; file_path?: string; content?: string } | undefined;\n\t\t\tconst rawPath = str(renderArgs?.file_path ?? renderArgs?.path);\n\t\t\tconst fileContent = str(renderArgs?.content);\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as WriteCallRenderComponent | undefined) ?? new WriteCallRenderComponent();\n\t\t\tif (fileContent !== null) {\n\t\t\t\tcomponent.cache = context.argsComplete\n\t\t\t\t\t? rebuildWriteHighlightCacheFull(rawPath, fileContent)\n\t\t\t\t\t: updateWriteHighlightCacheIncremental(component.cache, rawPath, fileContent);\n\t\t\t} else {\n\t\t\t\tcomponent.cache = undefined;\n\t\t\t}\n\t\t\tcomponent.setText(\n\t\t\t\tformatWriteCall(\n\t\t\t\t\trenderArgs,\n\t\t\t\t\t{ expanded: context.expanded, isPartial: context.isPartial },\n\t\t\t\t\ttheme,\n\t\t\t\t\tcomponent.cache,\n\t\t\t\t\tcontext.cwd,\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn component;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst output = formatWriteResult({ ...result, isError: context.isError }, theme);\n\t\t\tif (!output) {\n\t\t\t\tconst component = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\t\tcomponent.clear();\n\t\t\t\treturn component;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(output);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createWriteTool(cwd: string, options?: WriteToolOptions): AgentTool {\n\treturn wrapToolDefinition(createWriteToolDefinition(cwd, options));\n}\n"]} \ No newline at end of file diff --git a/dist/core/trust-manager.d.ts b/dist/core/trust-manager.d.ts new file mode 100644 index 0000000..feb964d --- /dev/null +++ b/dist/core/trust-manager.d.ts @@ -0,0 +1,36 @@ +export type ProjectTrustDecision = boolean | null; +export interface ProjectTrustStoreEntry { + path: string; + decision: boolean; +} +export interface ProjectTrustUpdate { + path: string; + decision: ProjectTrustDecision; +} +export interface ProjectTrustOption { + label: string; + trusted: boolean; + updates: ProjectTrustUpdate[]; + savedPath?: string; +} +export declare function getProjectTrustParentPath(cwd: string): string | undefined; +export declare function getProjectTrustOptions(cwd: string, options?: { + includeSessionOnly?: boolean; +}): ProjectTrustOption[]; +/** + * Returns true when cwd has project-local resources that must be gated by + * project trust: trust-requiring entries under cwd/.pi, or .agents/skills in + * cwd or one of its ancestors. Returns false when no such project resources + * exist. The user/global ~/.agents/skills directory is always treated as a + * trusted user resource and is ignored here, even when cwd is $HOME. + */ +export declare function hasTrustRequiringProjectResources(cwd: string): boolean; +export declare class ProjectTrustStore { + private trustPath; + constructor(agentDir: string); + get(cwd: string): ProjectTrustDecision; + getEntry(cwd: string): ProjectTrustStoreEntry | null; + set(cwd: string, decision: ProjectTrustDecision): void; + setMany(decisions: ProjectTrustUpdate[]): void; +} +//# sourceMappingURL=trust-manager.d.ts.map \ No newline at end of file diff --git a/dist/core/trust-manager.d.ts.map b/dist/core/trust-manager.d.ts.map new file mode 100644 index 0000000..f3bcf90 --- /dev/null +++ b/dist/core/trust-manager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"trust-manager.d.ts","sourceRoot":"","sources":["../../src/core/trust-manager.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,oBAAoB,GAAG,OAAO,GAAG,IAAI,CAAC;AAElD,MAAM,WAAW,sBAAsB;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,oBAAoB,CAAC;CAC/B;AAED,MAAM,WAAW,kBAAkB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,kBAAkB,EAAE,CAAC;IAC9B,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAkCD,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAIzE;AAED,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;IAAE,kBAAkB,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,kBAAkB,EAAE,CA8BpH;AAkFD;;;;;;GAMG;AACH,wBAAgB,iCAAiC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAsBtE;AAED,qBAAa,iBAAiB;IAC7B,OAAO,CAAC,SAAS,CAAS;IAE1B,YAAY,QAAQ,EAAE,MAAM,EAE3B;IAED,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,oBAAoB,CAErC;IAED,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,sBAAsB,GAAG,IAAI,CAKnD;IAED,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,oBAAoB,GAAG,IAAI,CAErD;IAED,OAAO,CAAC,SAAS,EAAE,kBAAkB,EAAE,GAAG,IAAI,CAa7C;CACD","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { canonicalizePath, resolvePath } from \"../utils/paths.ts\";\n\nexport type ProjectTrustDecision = boolean | null;\n\nexport interface ProjectTrustStoreEntry {\n\tpath: string;\n\tdecision: boolean;\n}\n\nexport interface ProjectTrustUpdate {\n\tpath: string;\n\tdecision: ProjectTrustDecision;\n}\n\nexport interface ProjectTrustOption {\n\tlabel: string;\n\ttrusted: boolean;\n\tupdates: ProjectTrustUpdate[];\n\tsavedPath?: string;\n}\n\ntype TrustFile = Record;\n\nconst TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES = [\n\t\"settings.json\",\n\t\"extensions\",\n\t\"skills\",\n\t\"prompts\",\n\t\"themes\",\n\t\"SYSTEM.md\",\n\t\"APPEND_SYSTEM.md\",\n] as const;\n\nfunction normalizeCwd(cwd: string): string {\n\treturn canonicalizePath(resolvePath(cwd));\n}\n\nfunction findNearestTrustEntry(data: TrustFile, cwd: string): ProjectTrustStoreEntry | null {\n\tlet currentDir = normalizeCwd(cwd);\n\twhile (true) {\n\t\tconst value = data[currentDir];\n\t\tif (value === true || value === false) {\n\t\t\treturn { path: currentDir, decision: value };\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn null;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport function getProjectTrustParentPath(cwd: string): string | undefined {\n\tconst trustPath = normalizeCwd(cwd);\n\tconst parentDir = dirname(trustPath);\n\treturn parentDir === trustPath ? undefined : parentDir;\n}\n\nexport function getProjectTrustOptions(cwd: string, options?: { includeSessionOnly?: boolean }): ProjectTrustOption[] {\n\tconst trustPath = normalizeCwd(cwd);\n\tconst trustOptions: ProjectTrustOption[] = [\n\t\t{ label: \"Trust\", trusted: true, updates: [{ path: trustPath, decision: true }], savedPath: trustPath },\n\t];\n\tconst parentPath = getProjectTrustParentPath(cwd);\n\tif (parentPath !== undefined) {\n\t\ttrustOptions.push({\n\t\t\tlabel: `Trust parent folder (${parentPath})`,\n\t\t\ttrusted: true,\n\t\t\tupdates: [\n\t\t\t\t{ path: parentPath, decision: true },\n\t\t\t\t{ path: trustPath, decision: null },\n\t\t\t],\n\t\t\tsavedPath: parentPath,\n\t\t});\n\t}\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Trust (this session only)\", trusted: true, updates: [] });\n\t}\n\ttrustOptions.push({\n\t\tlabel: \"Do not trust\",\n\t\ttrusted: false,\n\t\tupdates: [{ path: trustPath, decision: false }],\n\t\tsavedPath: trustPath,\n\t});\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Do not trust (this session only)\", trusted: false, updates: [] });\n\t}\n\treturn trustOptions;\n}\n\nfunction readTrustFile(path: string): TrustFile {\n\tif (!existsSync(path)) {\n\t\treturn {};\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(readFileSync(path, \"utf-8\"));\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`Failed to read trust store ${path}: ${message}`);\n\t}\n\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new Error(`Invalid trust store ${path}: expected an object`);\n\t}\n\n\tconst data: TrustFile = {};\n\tfor (const [key, value] of Object.entries(parsed)) {\n\t\tif (value !== true && value !== false && value !== null) {\n\t\t\tthrow new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);\n\t\t}\n\t\tdata[key] = value;\n\t}\n\treturn data;\n}\n\nfunction writeTrustFile(path: string, data: TrustFile): void {\n\tconst sorted: TrustFile = {};\n\tfor (const key of Object.keys(data).sort()) {\n\t\tconst value = data[key];\n\t\tif (value === true || value === false || value === null) {\n\t\t\tsorted[key] = value;\n\t\t}\n\t}\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(sorted, null, 2)}\\n`, \"utf-8\");\n}\n\nfunction acquireTrustLockSync(path: string): () => void {\n\tconst trustDir = dirname(path);\n\tmkdirSync(trustDir, { recursive: true });\n\tconst maxAttempts = 10;\n\tconst delayMs = 20;\n\tlet lastError: unknown;\n\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(trustDir, { realpath: false, lockfilePath: `${path}.lock` });\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t: undefined;\n\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tlastError = error;\n\t\t\tconst start = Date.now();\n\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t// Sleep synchronously to avoid changing trust store callers to async.\n\t\t\t}\n\t\t}\n\t}\n\n\tif (lastError instanceof Error) {\n\t\tthrow lastError;\n\t}\n\tthrow new Error(\"Failed to acquire trust store lock\");\n}\n\nfunction withTrustFileLock(path: string, fn: () => T): T {\n\tconst release = acquireTrustLockSync(path);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\trelease();\n\t}\n}\n\n/**\n * Returns true when cwd has project-local resources that must be gated by\n * project trust: trust-requiring entries under cwd/.pi, or .agents/skills in\n * cwd or one of its ancestors. Returns false when no such project resources\n * exist. The user/global ~/.agents/skills directory is always treated as a\n * trusted user resource and is ignored here, even when cwd is $HOME.\n */\nexport function hasTrustRequiringProjectResources(cwd: string): boolean {\n\tconst homeDir = canonicalizePath(resolvePath(process.env.HOME || homedir()));\n\tconst userAgentsSkillsDir = join(homeDir, \".agents\", \"skills\");\n\tlet currentDir = canonicalizePath(resolvePath(cwd));\n\n\tconst configDir = join(currentDir, CONFIG_DIR_NAME);\n\tif (TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some((entry) => existsSync(join(configDir, entry)))) {\n\t\treturn true;\n\t}\n\n\twhile (true) {\n\t\tconst agentsSkillsDir = join(currentDir, \".agents\", \"skills\");\n\t\tif (agentsSkillsDir !== userAgentsSkillsDir && existsSync(agentsSkillsDir)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn false;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport class ProjectTrustStore {\n\tprivate trustPath: string;\n\n\tconstructor(agentDir: string) {\n\t\tthis.trustPath = join(resolvePath(agentDir), \"trust.json\");\n\t}\n\n\tget(cwd: string): ProjectTrustDecision {\n\t\treturn this.getEntry(cwd)?.decision ?? null;\n\t}\n\n\tgetEntry(cwd: string): ProjectTrustStoreEntry | null {\n\t\treturn withTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\treturn findNearestTrustEntry(data, cwd);\n\t\t});\n\t}\n\n\tset(cwd: string, decision: ProjectTrustDecision): void {\n\t\tthis.setMany([{ path: cwd, decision }]);\n\t}\n\n\tsetMany(decisions: ProjectTrustUpdate[]): void {\n\t\twithTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\tfor (const { path, decision } of decisions) {\n\t\t\t\tconst key = normalizeCwd(path);\n\t\t\t\tif (decision === null) {\n\t\t\t\t\tdelete data[key];\n\t\t\t\t} else {\n\t\t\t\t\tdata[key] = decision;\n\t\t\t\t}\n\t\t\t}\n\t\t\twriteTrustFile(this.trustPath, data);\n\t\t});\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/trust-manager.js b/dist/core/trust-manager.js new file mode 100644 index 0000000..17af938 --- /dev/null +++ b/dist/core/trust-manager.js @@ -0,0 +1,202 @@ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import lockfile from "proper-lockfile"; +import { CONFIG_DIR_NAME } from "../config.js"; +import { canonicalizePath, resolvePath } from "../utils/paths.js"; +const TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES = [ + "settings.json", + "extensions", + "skills", + "prompts", + "themes", + "SYSTEM.md", + "APPEND_SYSTEM.md", +]; +function normalizeCwd(cwd) { + return canonicalizePath(resolvePath(cwd)); +} +function findNearestTrustEntry(data, cwd) { + let currentDir = normalizeCwd(cwd); + while (true) { + const value = data[currentDir]; + if (value === true || value === false) { + return { path: currentDir, decision: value }; + } + const parentDir = dirname(currentDir); + if (parentDir === currentDir) { + return null; + } + currentDir = parentDir; + } +} +export function getProjectTrustParentPath(cwd) { + const trustPath = normalizeCwd(cwd); + const parentDir = dirname(trustPath); + return parentDir === trustPath ? undefined : parentDir; +} +export function getProjectTrustOptions(cwd, options) { + const trustPath = normalizeCwd(cwd); + const trustOptions = [ + { label: "Trust", trusted: true, updates: [{ path: trustPath, decision: true }], savedPath: trustPath }, + ]; + const parentPath = getProjectTrustParentPath(cwd); + if (parentPath !== undefined) { + trustOptions.push({ + label: `Trust parent folder (${parentPath})`, + trusted: true, + updates: [ + { path: parentPath, decision: true }, + { path: trustPath, decision: null }, + ], + savedPath: parentPath, + }); + } + if (options?.includeSessionOnly) { + trustOptions.push({ label: "Trust (this session only)", trusted: true, updates: [] }); + } + trustOptions.push({ + label: "Do not trust", + trusted: false, + updates: [{ path: trustPath, decision: false }], + savedPath: trustPath, + }); + if (options?.includeSessionOnly) { + trustOptions.push({ label: "Do not trust (this session only)", trusted: false, updates: [] }); + } + return trustOptions; +} +function readTrustFile(path) { + if (!existsSync(path)) { + return {}; + } + let parsed; + try { + parsed = JSON.parse(readFileSync(path, "utf-8")); + } + catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`Failed to read trust store ${path}: ${message}`); + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw new Error(`Invalid trust store ${path}: expected an object`); + } + const data = {}; + for (const [key, value] of Object.entries(parsed)) { + if (value !== true && value !== false && value !== null) { + throw new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`); + } + data[key] = value; + } + return data; +} +function writeTrustFile(path, data) { + const sorted = {}; + for (const key of Object.keys(data).sort()) { + const value = data[key]; + if (value === true || value === false || value === null) { + sorted[key] = value; + } + } + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, `${JSON.stringify(sorted, null, 2)}\n`, "utf-8"); +} +function acquireTrustLockSync(path) { + const trustDir = dirname(path); + mkdirSync(trustDir, { recursive: true }); + const maxAttempts = 10; + const delayMs = 20; + let lastError; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + return lockfile.lockSync(trustDir, { realpath: false, lockfilePath: `${path}.lock` }); + } + catch (error) { + const code = typeof error === "object" && error !== null && "code" in error + ? String(error.code) + : undefined; + if (code !== "ELOCKED" || attempt === maxAttempts) { + throw error; + } + lastError = error; + const start = Date.now(); + while (Date.now() - start < delayMs) { + // Sleep synchronously to avoid changing trust store callers to async. + } + } + } + if (lastError instanceof Error) { + throw lastError; + } + throw new Error("Failed to acquire trust store lock"); +} +function withTrustFileLock(path, fn) { + const release = acquireTrustLockSync(path); + try { + return fn(); + } + finally { + release(); + } +} +/** + * Returns true when cwd has project-local resources that must be gated by + * project trust: trust-requiring entries under cwd/.pi, or .agents/skills in + * cwd or one of its ancestors. Returns false when no such project resources + * exist. The user/global ~/.agents/skills directory is always treated as a + * trusted user resource and is ignored here, even when cwd is $HOME. + */ +export function hasTrustRequiringProjectResources(cwd) { + const homeDir = canonicalizePath(resolvePath(process.env.HOME || homedir())); + const userAgentsSkillsDir = join(homeDir, ".agents", "skills"); + let currentDir = canonicalizePath(resolvePath(cwd)); + const configDir = join(currentDir, CONFIG_DIR_NAME); + if (TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some((entry) => existsSync(join(configDir, entry)))) { + return true; + } + while (true) { + const agentsSkillsDir = join(currentDir, ".agents", "skills"); + if (agentsSkillsDir !== userAgentsSkillsDir && existsSync(agentsSkillsDir)) { + return true; + } + const parentDir = dirname(currentDir); + if (parentDir === currentDir) { + return false; + } + currentDir = parentDir; + } +} +export class ProjectTrustStore { + trustPath; + constructor(agentDir) { + this.trustPath = join(resolvePath(agentDir), "trust.json"); + } + get(cwd) { + return this.getEntry(cwd)?.decision ?? null; + } + getEntry(cwd) { + return withTrustFileLock(this.trustPath, () => { + const data = readTrustFile(this.trustPath); + return findNearestTrustEntry(data, cwd); + }); + } + set(cwd, decision) { + this.setMany([{ path: cwd, decision }]); + } + setMany(decisions) { + withTrustFileLock(this.trustPath, () => { + const data = readTrustFile(this.trustPath); + for (const { path, decision } of decisions) { + const key = normalizeCwd(path); + if (decision === null) { + delete data[key]; + } + else { + data[key] = decision; + } + } + writeTrustFile(this.trustPath, data); + }); + } +} +//# sourceMappingURL=trust-manager.js.map \ No newline at end of file diff --git a/dist/core/trust-manager.js.map b/dist/core/trust-manager.js.map new file mode 100644 index 0000000..afef6b3 --- /dev/null +++ b/dist/core/trust-manager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trust-manager.js","sourceRoot":"","sources":["../../src/core/trust-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAuBlE,MAAM,wCAAwC,GAAG;IAChD,eAAe;IACf,YAAY;IACZ,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,WAAW;IACX,kBAAkB;CACT,CAAC;AAEX,SAAS,YAAY,CAAC,GAAW,EAAU;IAC1C,OAAO,gBAAgB,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC;AAAA,CAC1C;AAED,SAAS,qBAAqB,CAAC,IAAe,EAAE,GAAW,EAAiC;IAC3F,IAAI,UAAU,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC;IACnC,OAAO,IAAI,EAAE,CAAC;QACb,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC;QAC/B,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,KAAK,EAAE,CAAC;YACvC,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;QAC9C,CAAC;QAED,MAAM,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;QACtC,IAAI,SAAS,KAAK,UAAU,EAAE,CAAC;YAC9B,OAAO,IAAI,CAAC;QACb,CAAC;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,CAAC;YAC9C,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAC3C,OAAO,qBAAqB,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAAA,CACxC,CAAC,CAAC;IAAA,CACH;IAED,GAAG,CAAC,GAAW,EAAE,QAA8B,EAAQ;QACtD,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC;IAAA,CACxC;IAED,OAAO,CAAC,SAA+B,EAAQ;QAC9C,iBAAiB,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC;YACvC,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAC3C,KAAK,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,SAAS,EAAE,CAAC;gBAC5C,MAAM,GAAG,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;gBAC/B,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;oBACvB,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;gBAClB,CAAC;qBAAM,CAAC;oBACP,IAAI,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC;gBACtB,CAAC;YACF,CAAC;YACD,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QAAA,CACrC,CAAC,CAAC;IAAA,CACH;CACD","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { canonicalizePath, resolvePath } from \"../utils/paths.ts\";\n\nexport type ProjectTrustDecision = boolean | null;\n\nexport interface ProjectTrustStoreEntry {\n\tpath: string;\n\tdecision: boolean;\n}\n\nexport interface ProjectTrustUpdate {\n\tpath: string;\n\tdecision: ProjectTrustDecision;\n}\n\nexport interface ProjectTrustOption {\n\tlabel: string;\n\ttrusted: boolean;\n\tupdates: ProjectTrustUpdate[];\n\tsavedPath?: string;\n}\n\ntype TrustFile = Record;\n\nconst TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES = [\n\t\"settings.json\",\n\t\"extensions\",\n\t\"skills\",\n\t\"prompts\",\n\t\"themes\",\n\t\"SYSTEM.md\",\n\t\"APPEND_SYSTEM.md\",\n] as const;\n\nfunction normalizeCwd(cwd: string): string {\n\treturn canonicalizePath(resolvePath(cwd));\n}\n\nfunction findNearestTrustEntry(data: TrustFile, cwd: string): ProjectTrustStoreEntry | null {\n\tlet currentDir = normalizeCwd(cwd);\n\twhile (true) {\n\t\tconst value = data[currentDir];\n\t\tif (value === true || value === false) {\n\t\t\treturn { path: currentDir, decision: value };\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn null;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport function getProjectTrustParentPath(cwd: string): string | undefined {\n\tconst trustPath = normalizeCwd(cwd);\n\tconst parentDir = dirname(trustPath);\n\treturn parentDir === trustPath ? undefined : parentDir;\n}\n\nexport function getProjectTrustOptions(cwd: string, options?: { includeSessionOnly?: boolean }): ProjectTrustOption[] {\n\tconst trustPath = normalizeCwd(cwd);\n\tconst trustOptions: ProjectTrustOption[] = [\n\t\t{ label: \"Trust\", trusted: true, updates: [{ path: trustPath, decision: true }], savedPath: trustPath },\n\t];\n\tconst parentPath = getProjectTrustParentPath(cwd);\n\tif (parentPath !== undefined) {\n\t\ttrustOptions.push({\n\t\t\tlabel: `Trust parent folder (${parentPath})`,\n\t\t\ttrusted: true,\n\t\t\tupdates: [\n\t\t\t\t{ path: parentPath, decision: true },\n\t\t\t\t{ path: trustPath, decision: null },\n\t\t\t],\n\t\t\tsavedPath: parentPath,\n\t\t});\n\t}\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Trust (this session only)\", trusted: true, updates: [] });\n\t}\n\ttrustOptions.push({\n\t\tlabel: \"Do not trust\",\n\t\ttrusted: false,\n\t\tupdates: [{ path: trustPath, decision: false }],\n\t\tsavedPath: trustPath,\n\t});\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Do not trust (this session only)\", trusted: false, updates: [] });\n\t}\n\treturn trustOptions;\n}\n\nfunction readTrustFile(path: string): TrustFile {\n\tif (!existsSync(path)) {\n\t\treturn {};\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(readFileSync(path, \"utf-8\"));\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`Failed to read trust store ${path}: ${message}`);\n\t}\n\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new Error(`Invalid trust store ${path}: expected an object`);\n\t}\n\n\tconst data: TrustFile = {};\n\tfor (const [key, value] of Object.entries(parsed)) {\n\t\tif (value !== true && value !== false && value !== null) {\n\t\t\tthrow new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);\n\t\t}\n\t\tdata[key] = value;\n\t}\n\treturn data;\n}\n\nfunction writeTrustFile(path: string, data: TrustFile): void {\n\tconst sorted: TrustFile = {};\n\tfor (const key of Object.keys(data).sort()) {\n\t\tconst value = data[key];\n\t\tif (value === true || value === false || value === null) {\n\t\t\tsorted[key] = value;\n\t\t}\n\t}\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(sorted, null, 2)}\\n`, \"utf-8\");\n}\n\nfunction acquireTrustLockSync(path: string): () => void {\n\tconst trustDir = dirname(path);\n\tmkdirSync(trustDir, { recursive: true });\n\tconst maxAttempts = 10;\n\tconst delayMs = 20;\n\tlet lastError: unknown;\n\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(trustDir, { realpath: false, lockfilePath: `${path}.lock` });\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t: undefined;\n\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tlastError = error;\n\t\t\tconst start = Date.now();\n\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t// Sleep synchronously to avoid changing trust store callers to async.\n\t\t\t}\n\t\t}\n\t}\n\n\tif (lastError instanceof Error) {\n\t\tthrow lastError;\n\t}\n\tthrow new Error(\"Failed to acquire trust store lock\");\n}\n\nfunction withTrustFileLock(path: string, fn: () => T): T {\n\tconst release = acquireTrustLockSync(path);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\trelease();\n\t}\n}\n\n/**\n * Returns true when cwd has project-local resources that must be gated by\n * project trust: trust-requiring entries under cwd/.pi, or .agents/skills in\n * cwd or one of its ancestors. Returns false when no such project resources\n * exist. The user/global ~/.agents/skills directory is always treated as a\n * trusted user resource and is ignored here, even when cwd is $HOME.\n */\nexport function hasTrustRequiringProjectResources(cwd: string): boolean {\n\tconst homeDir = canonicalizePath(resolvePath(process.env.HOME || homedir()));\n\tconst userAgentsSkillsDir = join(homeDir, \".agents\", \"skills\");\n\tlet currentDir = canonicalizePath(resolvePath(cwd));\n\n\tconst configDir = join(currentDir, CONFIG_DIR_NAME);\n\tif (TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some((entry) => existsSync(join(configDir, entry)))) {\n\t\treturn true;\n\t}\n\n\twhile (true) {\n\t\tconst agentsSkillsDir = join(currentDir, \".agents\", \"skills\");\n\t\tif (agentsSkillsDir !== userAgentsSkillsDir && existsSync(agentsSkillsDir)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn false;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport class ProjectTrustStore {\n\tprivate trustPath: string;\n\n\tconstructor(agentDir: string) {\n\t\tthis.trustPath = join(resolvePath(agentDir), \"trust.json\");\n\t}\n\n\tget(cwd: string): ProjectTrustDecision {\n\t\treturn this.getEntry(cwd)?.decision ?? null;\n\t}\n\n\tgetEntry(cwd: string): ProjectTrustStoreEntry | null {\n\t\treturn withTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\treturn findNearestTrustEntry(data, cwd);\n\t\t});\n\t}\n\n\tset(cwd: string, decision: ProjectTrustDecision): void {\n\t\tthis.setMany([{ path: cwd, decision }]);\n\t}\n\n\tsetMany(decisions: ProjectTrustUpdate[]): void {\n\t\twithTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\tfor (const { path, decision } of decisions) {\n\t\t\t\tconst key = normalizeCwd(path);\n\t\t\t\tif (decision === null) {\n\t\t\t\t\tdelete data[key];\n\t\t\t\t} else {\n\t\t\t\t\tdata[key] = decision;\n\t\t\t\t}\n\t\t\t}\n\t\t\twriteTrustFile(this.trustPath, data);\n\t\t});\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/core/usage-totals.d.ts b/dist/core/usage-totals.d.ts new file mode 100644 index 0000000..4f5f416 --- /dev/null +++ b/dist/core/usage-totals.d.ts @@ -0,0 +1,19 @@ +import type { Usage } from "@earendil-works/pi-ai/compat"; +import type { SessionEntry } from "./session-manager.ts"; +export interface UsageTotals { + input: number; + output: number; + cacheRead: number; + cacheWrite: number; + cost: number; +} +export declare function createUsageTotals(): UsageTotals; +export declare function addUsageToTotals(totals: UsageTotals, usage: Usage): void; +export interface UsageCostBreakdownEntry { + key: string; + cost: number; + tokens: number; +} +/** Group attributable assistant usage by model and all other usage into a separate bucket. */ +export declare function getUsageCostBreakdown(entries: SessionEntry[]): UsageCostBreakdownEntry[]; +//# sourceMappingURL=usage-totals.d.ts.map \ No newline at end of file diff --git a/dist/core/usage-totals.d.ts.map b/dist/core/usage-totals.d.ts.map new file mode 100644 index 0000000..d685c34 --- /dev/null +++ b/dist/core/usage-totals.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"usage-totals.d.ts","sourceRoot":"","sources":["../../src/core/usage-totals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAEzD,MAAM,WAAW,WAAW;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;CACb;AAED,wBAAgB,iBAAiB,IAAI,WAAW,CAQ/C;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI,CAMxE;AAED,MAAM,WAAW,uBAAuB;IACvC,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CACf;AAED,8FAA8F;AAC9F,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,uBAAuB,EAAE,CAiCxF","sourcesContent":["import type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport type { SessionEntry } from \"./session-manager.ts\";\n\nexport interface UsageTotals {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\tcost: number;\n}\n\nexport function createUsageTotals(): UsageTotals {\n\treturn {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\tcost: 0,\n\t};\n}\n\nexport function addUsageToTotals(totals: UsageTotals, usage: Usage): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.cost += usage.cost.total;\n}\n\nexport interface UsageCostBreakdownEntry {\n\tkey: string;\n\tcost: number;\n\ttokens: number;\n}\n\n/** Group attributable assistant usage by model and all other usage into a separate bucket. */\nexport function getUsageCostBreakdown(entries: SessionEntry[]): UsageCostBreakdownEntry[] {\n\tconst totalsByKey = new Map();\n\n\tfor (const entry of entries) {\n\t\tlet key: string | undefined;\n\t\tlet usage: Usage | undefined;\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tkey = `${entry.message.provider}/${entry.message.responseModel ?? entry.message.model}`;\n\t\t\tusage = entry.message.usage;\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"toolResult\" && entry.message.usage) {\n\t\t\tkey = \"Tools/summaries\";\n\t\t\tusage = entry.message.usage;\n\t\t} else if ((entry.type === \"branch_summary\" || entry.type === \"compaction\") && entry.usage) {\n\t\t\tkey = \"Tools/summaries\";\n\t\t\tusage = entry.usage;\n\t\t}\n\t\tif (!key || !usage) continue;\n\n\t\tlet totals = totalsByKey.get(key);\n\t\tif (!totals) {\n\t\t\ttotals = createUsageTotals();\n\t\t\ttotalsByKey.set(key, totals);\n\t\t}\n\t\taddUsageToTotals(totals, usage);\n\t}\n\n\treturn Array.from(totalsByKey, ([key, totals]) => ({\n\t\tkey,\n\t\tcost: totals.cost,\n\t\ttokens: totals.input + totals.output + totals.cacheRead + totals.cacheWrite,\n\t}))\n\t\t.filter((entry) => entry.cost > 0 || entry.tokens > 0)\n\t\t.sort((a, b) => b.cost - a.cost);\n}\n"]} \ No newline at end of file diff --git a/dist/core/usage-totals.js b/dist/core/usage-totals.js new file mode 100644 index 0000000..2920c46 --- /dev/null +++ b/dist/core/usage-totals.js @@ -0,0 +1,52 @@ +export function createUsageTotals() { + return { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + cost: 0, + }; +} +export function addUsageToTotals(totals, usage) { + totals.input += usage.input; + totals.output += usage.output; + totals.cacheRead += usage.cacheRead; + totals.cacheWrite += usage.cacheWrite; + totals.cost += usage.cost.total; +} +/** Group attributable assistant usage by model and all other usage into a separate bucket. */ +export function getUsageCostBreakdown(entries) { + const totalsByKey = new Map(); + for (const entry of entries) { + let key; + let usage; + if (entry.type === "message" && entry.message.role === "assistant") { + key = `${entry.message.provider}/${entry.message.responseModel ?? entry.message.model}`; + usage = entry.message.usage; + } + else if (entry.type === "message" && entry.message.role === "toolResult" && entry.message.usage) { + key = "Tools/summaries"; + usage = entry.message.usage; + } + else if ((entry.type === "branch_summary" || entry.type === "compaction") && entry.usage) { + key = "Tools/summaries"; + usage = entry.usage; + } + if (!key || !usage) + continue; + let totals = totalsByKey.get(key); + if (!totals) { + totals = createUsageTotals(); + totalsByKey.set(key, totals); + } + addUsageToTotals(totals, usage); + } + return Array.from(totalsByKey, ([key, totals]) => ({ + key, + cost: totals.cost, + tokens: totals.input + totals.output + totals.cacheRead + totals.cacheWrite, + })) + .filter((entry) => entry.cost > 0 || entry.tokens > 0) + .sort((a, b) => b.cost - a.cost); +} +//# sourceMappingURL=usage-totals.js.map \ No newline at end of file diff --git a/dist/core/usage-totals.js.map b/dist/core/usage-totals.js.map new file mode 100644 index 0000000..6c911f6 --- /dev/null +++ b/dist/core/usage-totals.js.map @@ -0,0 +1 @@ +{"version":3,"file":"usage-totals.js","sourceRoot":"","sources":["../../src/core/usage-totals.ts"],"names":[],"mappings":"AAWA,MAAM,UAAU,iBAAiB,GAAgB;IAChD,OAAO;QACN,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;QACb,IAAI,EAAE,CAAC;KACP,CAAC;AAAA,CACF;AAED,MAAM,UAAU,gBAAgB,CAAC,MAAmB,EAAE,KAAY,EAAQ;IACzE,MAAM,CAAC,KAAK,IAAI,KAAK,CAAC,KAAK,CAAC;IAC5B,MAAM,CAAC,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC;IAC9B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,GAAG,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAClC,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,GAAG,iBAAiB,EAAE,CAAC;YAC7B,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC9B,CAAC;QACD,gBAAgB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC;QAClD,GAAG;QACH,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,MAAM,EAAE,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,SAAS,GAAG,MAAM,CAAC,UAAU;KAC3E,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;SACrD,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;AAAA,CAClC","sourcesContent":["import type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport type { SessionEntry } from \"./session-manager.ts\";\n\nexport interface UsageTotals {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\tcost: number;\n}\n\nexport function createUsageTotals(): UsageTotals {\n\treturn {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\tcost: 0,\n\t};\n}\n\nexport function addUsageToTotals(totals: UsageTotals, usage: Usage): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.cost += usage.cost.total;\n}\n\nexport interface UsageCostBreakdownEntry {\n\tkey: string;\n\tcost: number;\n\ttokens: number;\n}\n\n/** Group attributable assistant usage by model and all other usage into a separate bucket. */\nexport function getUsageCostBreakdown(entries: SessionEntry[]): UsageCostBreakdownEntry[] {\n\tconst totalsByKey = new Map();\n\n\tfor (const entry of entries) {\n\t\tlet key: string | undefined;\n\t\tlet usage: Usage | undefined;\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tkey = `${entry.message.provider}/${entry.message.responseModel ?? entry.message.model}`;\n\t\t\tusage = entry.message.usage;\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"toolResult\" && entry.message.usage) {\n\t\t\tkey = \"Tools/summaries\";\n\t\t\tusage = entry.message.usage;\n\t\t} else if ((entry.type === \"branch_summary\" || entry.type === \"compaction\") && entry.usage) {\n\t\t\tkey = \"Tools/summaries\";\n\t\t\tusage = entry.usage;\n\t\t}\n\t\tif (!key || !usage) continue;\n\n\t\tlet totals = totalsByKey.get(key);\n\t\tif (!totals) {\n\t\t\ttotals = createUsageTotals();\n\t\t\ttotalsByKey.set(key, totals);\n\t\t}\n\t\taddUsageToTotals(totals, usage);\n\t}\n\n\treturn Array.from(totalsByKey, ([key, totals]) => ({\n\t\tkey,\n\t\tcost: totals.cost,\n\t\ttokens: totals.input + totals.output + totals.cacheRead + totals.cacheWrite,\n\t}))\n\t\t.filter((entry) => entry.cost > 0 || entry.tokens > 0)\n\t\t.sort((a, b) => b.cost - a.cost);\n}\n"]} \ No newline at end of file diff --git a/dist/extensions/index.d.ts b/dist/extensions/index.d.ts new file mode 100644 index 0000000..eb15670 --- /dev/null +++ b/dist/extensions/index.d.ts @@ -0,0 +1,3 @@ +import type { InlineExtension } from "../core/extensions/types.ts"; +export declare const builtInExtensions: InlineExtension[]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/extensions/index.d.ts.map b/dist/extensions/index.d.ts.map new file mode 100644 index 0000000..8e04409 --- /dev/null +++ b/dist/extensions/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/extensions/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAGnE,eAAO,MAAM,iBAAiB,EAAE,eAAe,EAAmE,CAAC","sourcesContent":["import type { InlineExtension } from \"../core/extensions/types.ts\";\nimport llamaExtension from \"./llama/index.ts\";\n\nexport const builtInExtensions: InlineExtension[] = [{ name: \"llama.cpp\", factory: llamaExtension, hidden: true }];\n"]} \ No newline at end of file diff --git a/dist/extensions/index.js b/dist/extensions/index.js new file mode 100644 index 0000000..c68d9f6 --- /dev/null +++ b/dist/extensions/index.js @@ -0,0 +1,3 @@ +import llamaExtension from "./llama/index.js"; +export const builtInExtensions = [{ name: "llama.cpp", factory: llamaExtension, hidden: true }]; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/extensions/index.js.map b/dist/extensions/index.js.map new file mode 100644 index 0000000..8323f47 --- /dev/null +++ b/dist/extensions/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/extensions/index.ts"],"names":[],"mappings":"AACA,OAAO,cAAc,MAAM,kBAAkB,CAAC;AAE9C,MAAM,CAAC,MAAM,iBAAiB,GAAsB,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC","sourcesContent":["import type { InlineExtension } from \"../core/extensions/types.ts\";\nimport llamaExtension from \"./llama/index.ts\";\n\nexport const builtInExtensions: InlineExtension[] = [{ name: \"llama.cpp\", factory: llamaExtension, hidden: true }];\n"]} \ No newline at end of file diff --git a/dist/extensions/llama/client.d.ts b/dist/extensions/llama/client.d.ts new file mode 100644 index 0000000..5d1c67e --- /dev/null +++ b/dist/extensions/llama/client.d.ts @@ -0,0 +1,61 @@ +export type LlamaModelStatus = "unloaded" | "loading" | "loaded" | "downloading" | "sleeping"; +export interface LlamaModelInfo { + id: string; + aliases?: string[]; + status: { + value: LlamaModelStatus; + args?: string[]; + failed?: boolean; + exit_code?: number; + progress?: Record; + }; + architecture?: { + input_modalities?: string[]; + output_modalities?: string[]; + }; + source?: string; + meta?: { + n_ctx?: number; + n_ctx_train?: number; + size?: number; + ftype?: string; + }; +} +export interface LlamaModelsResponse { + data: LlamaModelInfo[]; + object?: string; +} +export interface LlamaModelEvent { + model: string; + event: string; + data?: unknown; +} +export interface LlamaProgress { + message: string; + ratio?: number; + detail?: string; +} +export declare function formatBytes(bytes: number): string; +export declare function normalizeLlamaServerUrl(value: string): string; +export declare function llamaInferenceUrl(serverUrl: string): string; +export declare class LlamaClient { + readonly serverUrl: string; + private readonly apiKey; + constructor(serverUrl: string, apiKey?: string); + private request; + list(options?: { + reload?: boolean; + signal?: AbortSignal; + }): Promise; + load(model: string, signal?: AbortSignal): Promise; + unload(model: string, signal?: AbortSignal): Promise; + unloadAndWait(model: string, signal?: AbortSignal): Promise; + download(model: string, signal?: AbortSignal): Promise; + watch(onEvent: (event: LlamaModelEvent) => void, signal?: AbortSignal): Promise; + loadAndWait(model: string, onProgress: (progress: LlamaProgress) => void, signal?: AbortSignal): Promise; + downloadAndWait(model: string, onProgress: (progress: LlamaProgress) => void, signal?: AbortSignal): Promise; +} +//# sourceMappingURL=client.d.ts.map \ No newline at end of file diff --git a/dist/extensions/llama/client.d.ts.map b/dist/extensions/llama/client.d.ts.map new file mode 100644 index 0000000..084e3bc --- /dev/null +++ b/dist/extensions/llama/client.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/extensions/llama/client.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,gBAAgB,GAAG,UAAU,GAAG,SAAS,GAAG,QAAQ,GAAG,aAAa,GAAG,UAAU,CAAC;AAE9F,MAAM,WAAW,cAAc;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,CAAC,EAAE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"unloaded\" | \"loading\" | \"loaded\" | \"downloading\" | \"sleeping\";\n\nexport interface LlamaModelInfo {\n\tid: string;\n\taliases?: string[];\n\tstatus: {\n\t\tvalue: LlamaModelStatus;\n\t\targs?: string[];\n\t\tfailed?: boolean;\n\t\texit_code?: number;\n\t\tprogress?: Record;\n\t};\n\tarchitecture?: {\n\t\tinput_modalities?: string[];\n\t\toutput_modalities?: string[];\n\t};\n\tsource?: string;\n\tmeta?: {\n\t\tn_ctx?: number;\n\t\tn_ctx_train?: number;\n\t\tsize?: number;\n\t\tftype?: string;\n\t};\n}\n\nexport interface LlamaModelsResponse {\n\tdata: LlamaModelInfo[];\n\tobject?: string;\n}\n\nexport interface LlamaModelEvent {\n\tmodel: string;\n\tevent: string;\n\tdata?: unknown;\n}\n\nexport interface LlamaProgress {\n\tmessage: string;\n\tratio?: number;\n\tdetail?: string;\n}\n\nfunction errorMessage(payload: unknown, fallback: string): string {\n\tif (typeof payload !== \"object\" || payload === null) return fallback;\n\tconst error = (payload as { error?: unknown }).error;\n\tif (typeof error !== \"object\" || error === null) return fallback;\n\tconst message = (error as { message?: unknown }).message;\n\treturn typeof message === \"string\" && message ? message : fallback;\n}\n\nfunction isModelInfo(value: unknown): value is LlamaModelInfo {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst candidate = value as { id?: unknown; status?: { value?: unknown } };\n\treturn typeof candidate.id === \"string\" && typeof candidate.status?.value === \"string\";\n}\n\nfunction linkSignal(source: AbortSignal | undefined, target: AbortController): () => void {\n\tif (!source) return () => {};\n\tif (source.aborted) {\n\t\ttarget.abort(source.reason);\n\t\treturn () => {};\n\t}\n\tconst abort = () => target.abort(source.reason);\n\tsource.addEventListener(\"abort\", abort, { once: true });\n\treturn () => source.removeEventListener(\"abort\", abort);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(signal.reason ?? new Error(\"Cancelled\"));\n\t\t\treturn;\n\t\t}\n\t\tconst abort = () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(signal?.reason ?? new Error(\"Cancelled\"));\n\t\t};\n\t\tconst timeout = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t});\n}\n\nfunction parseLoadProgress(data: unknown): LlamaProgress | undefined {\n\tif (typeof data !== \"object\" || data === null) return undefined;\n\tconst progress = (data as { progress?: unknown }).progress;\n\tif (typeof progress !== \"object\" || progress === null) return undefined;\n\tconst value = progress as { stages?: unknown; current?: unknown; stage?: unknown; value?: unknown };\n\tconst stage =\n\t\ttypeof value.current === \"string\" ? value.current : typeof value.stage === \"string\" ? value.stage : undefined;\n\tconst stages = Array.isArray(value.stages)\n\t\t? value.stages.filter((entry): entry is string => typeof entry === \"string\")\n\t\t: [];\n\tconst stageRatio = typeof value.value === \"number\" ? Math.max(0, Math.min(1, value.value)) : undefined;\n\tlet ratio = stageRatio;\n\tif (stage && stages.length > 0) {\n\t\tconst index = stages.indexOf(stage);\n\t\tif (index >= 0) ratio = (index + (stageRatio ?? 0)) / stages.length;\n\t}\n\treturn {\n\t\tmessage: stage ? `Loading ${stage.replaceAll(\"_\", \" \")}` : \"Loading model\",\n\t\tratio,\n\t};\n}\n\nfunction parseDownloadProgress(data: unknown): LlamaProgress | undefined {\n\tif (typeof data !== \"object\" || data === null) return undefined;\n\tconst nested = (data as { progress?: unknown }).progress;\n\tconst files = typeof nested === \"object\" && nested !== null ? nested : data;\n\tlet done = 0;\n\tlet total = 0;\n\tfor (const value of Object.values(files as Record)) {\n\t\tif (typeof value !== \"object\" || value === null) continue;\n\t\tconst entry = value as { done?: unknown; total?: unknown };\n\t\tif (typeof entry.done !== \"number\" || typeof entry.total !== \"number\") continue;\n\t\tdone += entry.done;\n\t\ttotal += entry.total;\n\t}\n\tif (total <= 0) return undefined;\n\treturn {\n\t\tmessage: \"Downloading model\",\n\t\tratio: done / total,\n\t\tdetail: `${formatBytes(done)} / ${formatBytes(total)}`,\n\t};\n}\n\nexport function formatBytes(bytes: number): string {\n\tif (bytes < 1024) return `${bytes} B`;\n\tconst units = [\"KiB\", \"MiB\", \"GiB\", \"TiB\"];\n\tlet value = bytes / 1024;\n\tlet unit = units[0]!;\n\tfor (let index = 1; index < units.length && value >= 1024; index++) {\n\t\tvalue /= 1024;\n\t\tunit = units[index]!;\n\t}\n\treturn `${value >= 10 ? value.toFixed(1) : value.toFixed(2)} ${unit}`;\n}\n\nexport function normalizeLlamaServerUrl(value: string): string {\n\tconst url = new URL(value.trim());\n\tif (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n\t\tthrow new Error(\"Server URL must use http or https\");\n\t}\n\turl.hash = \"\";\n\turl.search = \"\";\n\turl.pathname = url.pathname.replace(/\\/+$/u, \"\").replace(/\\/v1$/u, \"\") || \"/\";\n\treturn url.toString().replace(/\\/$/u, \"\");\n}\n\nexport function llamaInferenceUrl(serverUrl: string): string {\n\treturn `${normalizeLlamaServerUrl(serverUrl)}/v1`;\n}\n\nexport class LlamaClient {\n\treadonly serverUrl: string;\n\tprivate readonly apiKey: string | undefined;\n\n\tconstructor(serverUrl: string, apiKey?: string) {\n\t\tthis.serverUrl = normalizeLlamaServerUrl(serverUrl);\n\t\tthis.apiKey = apiKey;\n\t}\n\n\tprivate async request(path: string, init: RequestInit = {}): Promise {\n\t\tconst headers = new Headers(init.headers);\n\t\tif (init.body !== undefined) headers.set(\"Content-Type\", \"application/json\");\n\t\tif (this.apiKey) headers.set(\"Authorization\", `Bearer ${this.apiKey}`);\n\t\tconst timeout = AbortSignal.timeout(15_000);\n\t\tconst signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;\n\t\tconst response = await fetch(`${this.serverUrl}${path}`, { ...init, headers, signal });\n\t\tlet payload: unknown;\n\t\ttry {\n\t\t\tpayload = await response.json();\n\t\t} catch {\n\t\t\tpayload = undefined;\n\t\t}\n\t\tif (!response.ok) throw new Error(errorMessage(payload, `llama.cpp returned HTTP ${response.status}`));\n\t\treturn payload;\n\t}\n\n\tasync list(options: { reload?: boolean; signal?: AbortSignal } = {}): Promise {\n\t\tconst payload = await this.request(`/models${options.reload ? \"?reload=1\" : \"\"}`, { signal: options.signal });\n\t\tif (typeof payload !== \"object\" || payload === null || !Array.isArray((payload as { data?: unknown }).data)) {\n\t\t\tthrow new Error(\"llama.cpp returned an invalid model catalog\");\n\t\t}\n\t\tconst data = (payload as { data: unknown[] }).data;\n\t\tif (!data.every(isModelInfo)) throw new Error(\"Server is not running in llama.cpp router mode\");\n\t\treturn data;\n\t}\n\n\tasync load(model: string, signal?: AbortSignal): Promise {\n\t\tawait this.request(\"/models/load\", { method: \"POST\", body: JSON.stringify({ model }), signal });\n\t}\n\n\tasync unload(model: string, signal?: AbortSignal): Promise {\n\t\tawait this.request(\"/models/unload\", { method: \"POST\", body: JSON.stringify({ model }), signal });\n\t}\n\n\tasync unloadAndWait(model: string, signal?: AbortSignal): Promise {\n\t\tawait this.unload(model, signal);\n\t\twhile (true) {\n\t\t\tconst entry = (await this.list({ signal })).find((candidate) => candidate.id === model);\n\t\t\tif (!entry || entry.status.value === \"unloaded\") return;\n\t\t\tawait sleep(100, signal);\n\t\t}\n\t}\n\n\tasync download(model: string, signal?: AbortSignal): Promise {\n\t\tawait this.request(\"/models\", { method: \"POST\", body: JSON.stringify({ model }), signal });\n\t}\n\n\tasync watch(onEvent: (event: LlamaModelEvent) => void, signal?: AbortSignal): Promise {\n\t\tconst headers = new Headers();\n\t\tif (this.apiKey) headers.set(\"Authorization\", `Bearer ${this.apiKey}`);\n\t\tconst response = await fetch(`${this.serverUrl}/models/sse`, { headers, signal });\n\t\tif (!response.ok || !response.body) throw new Error(`llama.cpp SSE returned HTTP ${response.status}`);\n\t\tconst reader = response.body.getReader();\n\t\tconst decoder = new TextDecoder();\n\t\tlet buffer = \"\";\n\t\twhile (true) {\n\t\t\tconst chunk = await reader.read();\n\t\t\tif (chunk.done) break;\n\t\t\tbuffer += decoder.decode(chunk.value, { stream: true }).replaceAll(\"\\r\\n\", \"\\n\");\n\t\t\tlet boundary = buffer.indexOf(\"\\n\\n\");\n\t\t\twhile (boundary >= 0) {\n\t\t\t\tconst frame = buffer.slice(0, boundary);\n\t\t\t\tbuffer = buffer.slice(boundary + 2);\n\t\t\t\tconst data = frame\n\t\t\t\t\t.split(\"\\n\")\n\t\t\t\t\t.filter((line) => line.startsWith(\"data:\"))\n\t\t\t\t\t.map((line) => line.slice(5).trimStart())\n\t\t\t\t\t.join(\"\\n\");\n\t\t\t\tif (data) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst event = JSON.parse(data) as LlamaModelEvent;\n\t\t\t\t\t\tif (event && typeof event.model === \"string\" && typeof event.event === \"string\") onEvent(event);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Ignore malformed events; catalog polling remains authoritative.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tboundary = buffer.indexOf(\"\\n\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tasync loadAndWait(\n\t\tmodel: string,\n\t\tonProgress: (progress: LlamaProgress) => void,\n\t\tsignal?: AbortSignal,\n\t): Promise {\n\t\tconst watcher = new AbortController();\n\t\tconst unlink = linkSignal(signal, watcher);\n\t\tlet eventLoaded = false;\n\t\tlet eventError: string | undefined;\n\t\tvoid this.watch((event) => {\n\t\t\tif (event.model !== model) return;\n\t\t\tif (event.event !== \"model_status\" && event.event !== \"status_change\") return;\n\t\t\tconst data = event.data as { status?: unknown } | undefined;\n\t\t\tif (data?.status === \"loaded\") eventLoaded = true;\n\t\t\tif (data?.status === \"unloaded\") eventError = \"Model failed to load\";\n\t\t\tconst progress = parseLoadProgress(event.data);\n\t\t\tif (progress) onProgress(progress);\n\t\t}, watcher.signal).catch(() => {});\n\t\ttry {\n\t\t\tawait this.load(model, signal);\n\t\t\tonProgress({ message: \"Loading model\" });\n\t\t\twhile (true) {\n\t\t\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Cancelled\");\n\t\t\t\tconst entry = (await this.list({ signal })).find((candidate) => candidate.id === model);\n\t\t\t\tif (entry?.status.value === \"loaded\") return entry;\n\t\t\t\tif (eventLoaded && !entry) return { id: model, status: { value: \"loaded\" } };\n\t\t\t\tif (entry?.status.failed || eventError) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\tentry?.status.exit_code === undefined\n\t\t\t\t\t\t\t? (eventError ?? \"Model failed to load\")\n\t\t\t\t\t\t\t: `Model exited with code ${entry.status.exit_code}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait sleep(250, signal);\n\t\t\t}\n\t\t} finally {\n\t\t\tunlink();\n\t\t\twatcher.abort();\n\t\t}\n\t}\n\n\tasync downloadAndWait(\n\t\tmodel: string,\n\t\tonProgress: (progress: LlamaProgress) => void,\n\t\tsignal?: AbortSignal,\n\t): Promise {\n\t\tconst watcher = new AbortController();\n\t\tconst unlink = linkSignal(signal, watcher);\n\t\tlet finished = false;\n\t\tlet failure: string | undefined;\n\t\tlet sawDownloading = false;\n\t\tlet polls = 0;\n\t\tvoid this.watch((event) => {\n\t\t\tif (event.model !== model) return;\n\t\t\tif (event.event === \"download_finished\") finished = true;\n\t\t\tif (event.event === \"download_failed\") failure = errorMessage(event.data, \"Download failed\");\n\t\t\tif (event.event === \"download_progress\") {\n\t\t\t\tsawDownloading = true;\n\t\t\t\tconst progress = parseDownloadProgress(event.data);\n\t\t\t\tif (progress) onProgress(progress);\n\t\t\t}\n\t\t}, watcher.signal).catch(() => {});\n\t\ttry {\n\t\t\tawait this.download(model, signal);\n\t\t\tonProgress({ message: \"Downloading model\" });\n\t\t\twhile (true) {\n\t\t\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Cancelled\");\n\t\t\t\tif (failure) throw new Error(failure);\n\t\t\t\tconst models = await this.list({ signal });\n\t\t\t\tpolls++;\n\t\t\t\tconst entry = models.find((candidate) => candidate.id === model);\n\t\t\t\tif (entry?.status.value === \"downloading\") {\n\t\t\t\t\tsawDownloading = true;\n\t\t\t\t\tconst progress = parseDownloadProgress(entry.status.progress);\n\t\t\t\t\tif (progress) onProgress(progress);\n\t\t\t\t} else if (finished || (entry && (sawDownloading || polls >= 2))) {\n\t\t\t\t\treturn this.list({ reload: true, signal });\n\t\t\t\t}\n\t\t\t\tawait sleep(500, signal);\n\t\t\t}\n\t\t} finally {\n\t\t\tunlink();\n\t\t\twatcher.abort();\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/extensions/llama/client.js b/dist/extensions/llama/client.js new file mode 100644 index 0000000..3db1a61 --- /dev/null +++ b/dist/extensions/llama/client.js @@ -0,0 +1,302 @@ +function errorMessage(payload, fallback) { + if (typeof payload !== "object" || payload === null) + return fallback; + const error = payload.error; + if (typeof error !== "object" || error === null) + return fallback; + const message = error.message; + return typeof message === "string" && message ? message : fallback; +} +function isModelInfo(value) { + if (typeof value !== "object" || value === null) + return false; + const candidate = value; + return typeof candidate.id === "string" && typeof candidate.status?.value === "string"; +} +function linkSignal(source, target) { + if (!source) + return () => { }; + if (source.aborted) { + target.abort(source.reason); + return () => { }; + } + const abort = () => target.abort(source.reason); + source.addEventListener("abort", abort, { once: true }); + return () => source.removeEventListener("abort", abort); +} +function sleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason ?? new Error("Cancelled")); + return; + } + const abort = () => { + clearTimeout(timeout); + reject(signal?.reason ?? new Error("Cancelled")); + }; + const timeout = setTimeout(() => { + signal?.removeEventListener("abort", abort); + resolve(); + }, ms); + signal?.addEventListener("abort", abort, { once: true }); + }); +} +function parseLoadProgress(data) { + if (typeof data !== "object" || data === null) + return undefined; + const progress = data.progress; + if (typeof progress !== "object" || progress === null) + return undefined; + const value = progress; + const stage = typeof value.current === "string" ? value.current : typeof value.stage === "string" ? value.stage : undefined; + const stages = Array.isArray(value.stages) + ? value.stages.filter((entry) => typeof entry === "string") + : []; + const stageRatio = typeof value.value === "number" ? Math.max(0, Math.min(1, value.value)) : undefined; + let ratio = stageRatio; + if (stage && stages.length > 0) { + const index = stages.indexOf(stage); + if (index >= 0) + ratio = (index + (stageRatio ?? 0)) / stages.length; + } + return { + message: stage ? `Loading ${stage.replaceAll("_", " ")}` : "Loading model", + ratio, + }; +} +function parseDownloadProgress(data) { + if (typeof data !== "object" || data === null) + return undefined; + const nested = data.progress; + const files = typeof nested === "object" && nested !== null ? nested : data; + let done = 0; + let total = 0; + for (const value of Object.values(files)) { + if (typeof value !== "object" || value === null) + continue; + const entry = value; + if (typeof entry.done !== "number" || typeof entry.total !== "number") + continue; + done += entry.done; + total += entry.total; + } + if (total <= 0) + return undefined; + return { + message: "Downloading model", + ratio: done / total, + detail: `${formatBytes(done)} / ${formatBytes(total)}`, + }; +} +export function formatBytes(bytes) { + if (bytes < 1024) + return `${bytes} B`; + const units = ["KiB", "MiB", "GiB", "TiB"]; + let value = bytes / 1024; + let unit = units[0]; + for (let index = 1; index < units.length && value >= 1024; index++) { + value /= 1024; + unit = units[index]; + } + return `${value >= 10 ? value.toFixed(1) : value.toFixed(2)} ${unit}`; +} +export function normalizeLlamaServerUrl(value) { + const url = new URL(value.trim()); + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new Error("Server URL must use http or https"); + } + url.hash = ""; + url.search = ""; + url.pathname = url.pathname.replace(/\/+$/u, "").replace(/\/v1$/u, "") || "/"; + return url.toString().replace(/\/$/u, ""); +} +export function llamaInferenceUrl(serverUrl) { + return `${normalizeLlamaServerUrl(serverUrl)}/v1`; +} +export class LlamaClient { + serverUrl; + apiKey; + constructor(serverUrl, apiKey) { + this.serverUrl = normalizeLlamaServerUrl(serverUrl); + this.apiKey = apiKey; + } + async request(path, init = {}) { + const headers = new Headers(init.headers); + if (init.body !== undefined) + headers.set("Content-Type", "application/json"); + if (this.apiKey) + headers.set("Authorization", `Bearer ${this.apiKey}`); + const timeout = AbortSignal.timeout(15_000); + const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout; + const response = await fetch(`${this.serverUrl}${path}`, { ...init, headers, signal }); + let payload; + try { + payload = await response.json(); + } + catch { + payload = undefined; + } + if (!response.ok) + throw new Error(errorMessage(payload, `llama.cpp returned HTTP ${response.status}`)); + return payload; + } + async list(options = {}) { + const payload = await this.request(`/models${options.reload ? "?reload=1" : ""}`, { signal: options.signal }); + if (typeof payload !== "object" || payload === null || !Array.isArray(payload.data)) { + throw new Error("llama.cpp returned an invalid model catalog"); + } + const data = payload.data; + if (!data.every(isModelInfo)) + throw new Error("Server is not running in llama.cpp router mode"); + return data; + } + async load(model, signal) { + await this.request("/models/load", { method: "POST", body: JSON.stringify({ model }), signal }); + } + async unload(model, signal) { + await this.request("/models/unload", { method: "POST", body: JSON.stringify({ model }), signal }); + } + async unloadAndWait(model, signal) { + await this.unload(model, signal); + while (true) { + const entry = (await this.list({ signal })).find((candidate) => candidate.id === model); + if (!entry || entry.status.value === "unloaded") + return; + await sleep(100, signal); + } + } + async download(model, signal) { + await this.request("/models", { method: "POST", body: JSON.stringify({ model }), signal }); + } + async watch(onEvent, signal) { + const headers = new Headers(); + if (this.apiKey) + headers.set("Authorization", `Bearer ${this.apiKey}`); + const response = await fetch(`${this.serverUrl}/models/sse`, { headers, signal }); + if (!response.ok || !response.body) + throw new Error(`llama.cpp SSE returned HTTP ${response.status}`); + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + while (true) { + const chunk = await reader.read(); + if (chunk.done) + break; + buffer += decoder.decode(chunk.value, { stream: true }).replaceAll("\r\n", "\n"); + let boundary = buffer.indexOf("\n\n"); + while (boundary >= 0) { + const frame = buffer.slice(0, boundary); + buffer = buffer.slice(boundary + 2); + const data = frame + .split("\n") + .filter((line) => line.startsWith("data:")) + .map((line) => line.slice(5).trimStart()) + .join("\n"); + if (data) { + try { + const event = JSON.parse(data); + if (event && typeof event.model === "string" && typeof event.event === "string") + onEvent(event); + } + catch { + // Ignore malformed events; catalog polling remains authoritative. + } + } + boundary = buffer.indexOf("\n\n"); + } + } + } + async loadAndWait(model, onProgress, signal) { + const watcher = new AbortController(); + const unlink = linkSignal(signal, watcher); + let eventLoaded = false; + let eventError; + void this.watch((event) => { + if (event.model !== model) + return; + if (event.event !== "model_status" && event.event !== "status_change") + return; + const data = event.data; + if (data?.status === "loaded") + eventLoaded = true; + if (data?.status === "unloaded") + eventError = "Model failed to load"; + const progress = parseLoadProgress(event.data); + if (progress) + onProgress(progress); + }, watcher.signal).catch(() => { }); + try { + await this.load(model, signal); + onProgress({ message: "Loading model" }); + while (true) { + if (signal?.aborted) + throw signal.reason ?? new Error("Cancelled"); + const entry = (await this.list({ signal })).find((candidate) => candidate.id === model); + if (entry?.status.value === "loaded") + return entry; + if (eventLoaded && !entry) + return { id: model, status: { value: "loaded" } }; + if (entry?.status.failed || eventError) { + throw new Error(entry?.status.exit_code === undefined + ? (eventError ?? "Model failed to load") + : `Model exited with code ${entry.status.exit_code}`); + } + await sleep(250, signal); + } + } + finally { + unlink(); + watcher.abort(); + } + } + async downloadAndWait(model, onProgress, signal) { + const watcher = new AbortController(); + const unlink = linkSignal(signal, watcher); + let finished = false; + let failure; + let sawDownloading = false; + let polls = 0; + void this.watch((event) => { + if (event.model !== model) + return; + if (event.event === "download_finished") + finished = true; + if (event.event === "download_failed") + failure = errorMessage(event.data, "Download failed"); + if (event.event === "download_progress") { + sawDownloading = true; + const progress = parseDownloadProgress(event.data); + if (progress) + onProgress(progress); + } + }, watcher.signal).catch(() => { }); + try { + await this.download(model, signal); + onProgress({ message: "Downloading model" }); + while (true) { + if (signal?.aborted) + throw signal.reason ?? new Error("Cancelled"); + if (failure) + throw new Error(failure); + const models = await this.list({ signal }); + polls++; + const entry = models.find((candidate) => candidate.id === model); + if (entry?.status.value === "downloading") { + sawDownloading = true; + const progress = parseDownloadProgress(entry.status.progress); + if (progress) + onProgress(progress); + } + else if (finished || (entry && (sawDownloading || polls >= 2))) { + return this.list({ reload: true, signal }); + } + await sleep(500, signal); + } + } + finally { + unlink(); + watcher.abort(); + } + } +} +//# sourceMappingURL=client.js.map \ No newline at end of file diff --git a/dist/extensions/llama/client.js.map b/dist/extensions/llama/client.js.map new file mode 100644 index 0000000..28d3fc2 --- /dev/null +++ b/dist/extensions/llama/client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"client.js","sourceRoot":"","sources":["../../../src/extensions/llama/client.ts"],"names":[],"mappings":"AA0CA,SAAS,YAAY,CAAC,OAAgB,EAAE,QAAgB,EAAU;IACjE,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI;QAAE,OAAO,QAAQ,CAAC;IACrE,MAAM,KAAK,GAAI,OAA+B,CAAC,KAAK,CAAC;IACrD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,QAAQ,CAAC;IACjE,MAAM,OAAO,GAAI,KAA+B,CAAC,OAAO,CAAC;IACzD,OAAO,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC;AAAA,CACnE;AAED,SAAS,WAAW,CAAC,KAAc,EAA2B;IAC7D,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,SAAS,GAAG,KAAuD,CAAC;IAC1E,OAAO,OAAO,SAAS,CAAC,EAAE,KAAK,QAAQ,IAAI,OAAO,SAAS,CAAC,MAAM,EAAE,KAAK,KAAK,QAAQ,CAAC;AAAA,CACvF;AAED,SAAS,UAAU,CAAC,MAA+B,EAAE,MAAuB,EAAc;IACzF,IAAI,CAAC,MAAM;QAAE,OAAO,GAAG,EAAE,CAAC,EAAC,CAAC,CAAC;IAC7B,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC5B,OAAO,G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AAC,SAAS,CAAC,EAAE,KAAK,KAAK,CAAC,CAAC;gBACjE,IAAI,KAAK,EAAE,MAAM,CAAC,KAAK,KAAK,aAAa,EAAE,CAAC;oBAC3C,cAAc,GAAG,IAAI,CAAC;oBACtB,MAAM,QAAQ,GAAG,qBAAqB,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;oBAC9D,IAAI,QAAQ;wBAAE,UAAU,CAAC,QAAQ,CAAC,CAAC;gBACpC,CAAC;qBAAM,IAAI,QAAQ,IAAI,CAAC,KAAK,IAAI,CAAC,cAAc,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;oBAClE,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;gBAC5C,CAAC;gBACD,MAAM,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;YAC1B,CAAC;QACF,CAAC;gBAAS,CAAC;YACV,MAAM,EAAE,CAAC;YACT,OAAO,CAAC,KAAK,EAAE,CAAC;QACjB,CAAC;IAAA,CACD;CACD","sourcesContent":["export type LlamaModelStatus = \"unloaded\" | \"loading\" | \"loaded\" | \"downloading\" | \"sleeping\";\n\nexport interface LlamaModelInfo {\n\tid: string;\n\taliases?: string[];\n\tstatus: {\n\t\tvalue: LlamaModelStatus;\n\t\targs?: string[];\n\t\tfailed?: boolean;\n\t\texit_code?: number;\n\t\tprogress?: Record;\n\t};\n\tarchitecture?: {\n\t\tinput_modalities?: string[];\n\t\toutput_modalities?: string[];\n\t};\n\tsource?: string;\n\tmeta?: {\n\t\tn_ctx?: number;\n\t\tn_ctx_train?: number;\n\t\tsize?: number;\n\t\tftype?: string;\n\t};\n}\n\nexport interface LlamaModelsResponse {\n\tdata: LlamaModelInfo[];\n\tobject?: string;\n}\n\nexport interface LlamaModelEvent {\n\tmodel: string;\n\tevent: string;\n\tdata?: unknown;\n}\n\nexport interface LlamaProgress {\n\tmessage: string;\n\tratio?: number;\n\tdetail?: string;\n}\n\nfunction errorMessage(payload: unknown, fallback: string): string {\n\tif (typeof payload !== \"object\" || payload === null) return fallback;\n\tconst error = (payload as { error?: unknown }).error;\n\tif (typeof error !== \"object\" || error === null) return fallback;\n\tconst message = (error as { message?: unknown }).message;\n\treturn typeof message === \"string\" && message ? message : fallback;\n}\n\nfunction isModelInfo(value: unknown): value is LlamaModelInfo {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst candidate = value as { id?: unknown; status?: { value?: unknown } };\n\treturn typeof candidate.id === \"string\" && typeof candidate.status?.value === \"string\";\n}\n\nfunction linkSignal(source: AbortSignal | undefined, target: AbortController): () => void {\n\tif (!source) return () => {};\n\tif (source.aborted) {\n\t\ttarget.abort(source.reason);\n\t\treturn () => {};\n\t}\n\tconst abort = () => target.abort(source.reason);\n\tsource.addEventListener(\"abort\", abort, { once: true });\n\treturn () => source.removeEventListener(\"abort\", abort);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(signal.reason ?? new Error(\"Cancelled\"));\n\t\t\treturn;\n\t\t}\n\t\tconst abort = () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(signal?.reason ?? new Error(\"Cancelled\"));\n\t\t};\n\t\tconst timeout = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t});\n}\n\nfunction parseLoadProgress(data: unknown): LlamaProgress | undefined {\n\tif (typeof data !== \"object\" || data === null) return undefined;\n\tconst progress = (data as { progress?: unknown }).progress;\n\tif (typeof progress !== \"object\" || progress === null) return undefined;\n\tconst value = progress as { stages?: unknown; current?: unknown; stage?: unknown; value?: unknown };\n\tconst stage =\n\t\ttypeof value.current === \"string\" ? value.current : typeof value.stage === \"string\" ? value.stage : undefined;\n\tconst stages = Array.isArray(value.stages)\n\t\t? value.stages.filter((entry): entry is string => typeof entry === \"string\")\n\t\t: [];\n\tconst stageRatio = typeof value.value === \"number\" ? Math.max(0, Math.min(1, value.value)) : undefined;\n\tlet ratio = stageRatio;\n\tif (stage && stages.length > 0) {\n\t\tconst index = stages.indexOf(stage);\n\t\tif (index >= 0) ratio = (index + (stageRatio ?? 0)) / stages.length;\n\t}\n\treturn {\n\t\tmessage: stage ? `Loading ${stage.replaceAll(\"_\", \" \")}` : \"Loading model\",\n\t\tratio,\n\t};\n}\n\nfunction parseDownloadProgress(data: unknown): LlamaProgress | undefined {\n\tif (typeof data !== \"object\" || data === null) return undefined;\n\tconst nested = (data as { progress?: unknown }).progress;\n\tconst files = typeof nested === \"object\" && nested !== null ? nested : data;\n\tlet done = 0;\n\tlet total = 0;\n\tfor (const value of Object.values(files as Record)) {\n\t\tif (typeof value !== \"object\" || value === null) continue;\n\t\tconst entry = value as { done?: unknown; total?: unknown };\n\t\tif (typeof entry.done !== \"number\" || typeof entry.total !== \"number\") continue;\n\t\tdone += entry.done;\n\t\ttotal += entry.total;\n\t}\n\tif (total <= 0) return undefined;\n\treturn {\n\t\tmessage: \"Downloading model\",\n\t\tratio: done / total,\n\t\tdetail: `${formatBytes(done)} / ${formatBytes(total)}`,\n\t};\n}\n\nexport function formatBytes(bytes: number): string {\n\tif (bytes < 1024) return `${bytes} B`;\n\tconst units = [\"KiB\", \"MiB\", \"GiB\", \"TiB\"];\n\tlet value = bytes / 1024;\n\tlet unit = units[0]!;\n\tfor (let index = 1; index < units.length && value >= 1024; index++) {\n\t\tvalue /= 1024;\n\t\tunit = units[index]!;\n\t}\n\treturn `${value >= 10 ? value.toFixed(1) : value.toFixed(2)} ${unit}`;\n}\n\nexport function normalizeLlamaServerUrl(value: string): string {\n\tconst url = new URL(value.trim());\n\tif (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n\t\tthrow new Error(\"Server URL must use http or https\");\n\t}\n\turl.hash = \"\";\n\turl.search = \"\";\n\turl.pathname = url.pathname.replace(/\\/+$/u, \"\").replace(/\\/v1$/u, \"\") || \"/\";\n\treturn url.toString().replace(/\\/$/u, \"\");\n}\n\nexport function llamaInferenceUrl(serverUrl: string): string {\n\treturn `${normalizeLlamaServerUrl(serverUrl)}/v1`;\n}\n\nexport class LlamaClient {\n\treadonly serverUrl: string;\n\tprivate readonly apiKey: string | undefined;\n\n\tconstructor(serverUrl: string, apiKey?: string) {\n\t\tthis.serverUrl = normalizeLlamaServerUrl(serverUrl);\n\t\tthis.apiKey = apiKey;\n\t}\n\n\tprivate async request(path: string, init: RequestInit = {}): Promise {\n\t\tconst headers = new Headers(init.headers);\n\t\tif (init.body !== undefined) headers.set(\"Content-Type\", \"application/json\");\n\t\tif (this.apiKey) headers.set(\"Authorization\", `Bearer ${this.apiKey}`);\n\t\tconst timeout = AbortSignal.timeout(15_000);\n\t\tconst signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;\n\t\tconst response = await fetch(`${this.serverUrl}${path}`, { ...init, headers, signal });\n\t\tlet payload: unknown;\n\t\ttry {\n\t\t\tpayload = await response.json();\n\t\t} catch {\n\t\t\tpayload = undefined;\n\t\t}\n\t\tif (!response.ok) throw new Error(errorMessage(payload, `llama.cpp returned HTTP ${response.status}`));\n\t\treturn payload;\n\t}\n\n\tasync list(options: { reload?: boolean; signal?: AbortSignal } = {}): Promise {\n\t\tconst payload = await this.request(`/models${options.reload ? \"?reload=1\" : \"\"}`, { signal: options.signal });\n\t\tif (typeof payload !== \"object\" || payload === null || !Array.isArray((payload as { data?: unknown }).data)) {\n\t\t\tthrow new Error(\"llama.cpp returned an invalid model catalog\");\n\t\t}\n\t\tconst data = (payload as { data: unknown[] }).data;\n\t\tif (!data.every(isModelInfo)) throw new Error(\"Server is not running in llama.cpp router mode\");\n\t\treturn data;\n\t}\n\n\tasync load(model: string, signal?: AbortSignal): Promise {\n\t\tawait this.request(\"/models/load\", { method: \"POST\", body: JSON.stringify({ model }), signal });\n\t}\n\n\tasync unload(model: string, signal?: AbortSignal): Promise {\n\t\tawait this.request(\"/models/unload\", { method: \"POST\", body: JSON.stringify({ model }), signal });\n\t}\n\n\tasync unloadAndWait(model: string, signal?: AbortSignal): Promise {\n\t\tawait this.unload(model, signal);\n\t\twhile (true) {\n\t\t\tconst entry = (await this.list({ signal })).find((candidate) => candidate.id === model);\n\t\t\tif (!entry || entry.status.value === \"unloaded\") return;\n\t\t\tawait sleep(100, signal);\n\t\t}\n\t}\n\n\tasync download(model: string, signal?: AbortSignal): Promise {\n\t\tawait this.request(\"/models\", { method: \"POST\", body: JSON.stringify({ model }), signal });\n\t}\n\n\tasync watch(onEvent: (event: LlamaModelEvent) => void, signal?: AbortSignal): Promise {\n\t\tconst headers = new Headers();\n\t\tif (this.apiKey) headers.set(\"Authorization\", `Bearer ${this.apiKey}`);\n\t\tconst response = await fetch(`${this.serverUrl}/models/sse`, { headers, signal });\n\t\tif (!response.ok || !response.body) throw new Error(`llama.cpp SSE returned HTTP ${response.status}`);\n\t\tconst reader = response.body.getReader();\n\t\tconst decoder = new TextDecoder();\n\t\tlet buffer = \"\";\n\t\twhile (true) {\n\t\t\tconst chunk = await reader.read();\n\t\t\tif (chunk.done) break;\n\t\t\tbuffer += decoder.decode(chunk.value, { stream: true }).replaceAll(\"\\r\\n\", \"\\n\");\n\t\t\tlet boundary = buffer.indexOf(\"\\n\\n\");\n\t\t\twhile (boundary >= 0) {\n\t\t\t\tconst frame = buffer.slice(0, boundary);\n\t\t\t\tbuffer = buffer.slice(boundary + 2);\n\t\t\t\tconst data = frame\n\t\t\t\t\t.split(\"\\n\")\n\t\t\t\t\t.filter((line) => line.startsWith(\"data:\"))\n\t\t\t\t\t.map((line) => line.slice(5).trimStart())\n\t\t\t\t\t.join(\"\\n\");\n\t\t\t\tif (data) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst event = JSON.parse(data) as LlamaModelEvent;\n\t\t\t\t\t\tif (event && typeof event.model === \"string\" && typeof event.event === \"string\") onEvent(event);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Ignore malformed events; catalog polling remains authoritative.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tboundary = buffer.indexOf(\"\\n\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tasync loadAndWait(\n\t\tmodel: string,\n\t\tonProgress: (progress: LlamaProgress) => void,\n\t\tsignal?: AbortSignal,\n\t): Promise {\n\t\tconst watcher = new AbortController();\n\t\tconst unlink = linkSignal(signal, watcher);\n\t\tlet eventLoaded = false;\n\t\tlet eventError: string | undefined;\n\t\tvoid this.watch((event) => {\n\t\t\tif (event.model !== model) return;\n\t\t\tif (event.event !== \"model_status\" && event.event !== \"status_change\") return;\n\t\t\tconst data = event.data as { status?: unknown } | undefined;\n\t\t\tif (data?.status === \"loaded\") eventLoaded = true;\n\t\t\tif (data?.status === \"unloaded\") eventError = \"Model failed to load\";\n\t\t\tconst progress = parseLoadProgress(event.data);\n\t\t\tif (progress) onProgress(progress);\n\t\t}, watcher.signal).catch(() => {});\n\t\ttry {\n\t\t\tawait this.load(model, signal);\n\t\t\tonProgress({ message: \"Loading model\" });\n\t\t\twhile (true) {\n\t\t\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Cancelled\");\n\t\t\t\tconst entry = (await this.list({ signal })).find((candidate) => candidate.id === model);\n\t\t\t\tif (entry?.status.value === \"loaded\") return entry;\n\t\t\t\tif (eventLoaded && !entry) return { id: model, status: { value: \"loaded\" } };\n\t\t\t\tif (entry?.status.failed || eventError) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\tentry?.status.exit_code === undefined\n\t\t\t\t\t\t\t? (eventError ?? \"Model failed to load\")\n\t\t\t\t\t\t\t: `Model exited with code ${entry.status.exit_code}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait sleep(250, signal);\n\t\t\t}\n\t\t} finally {\n\t\t\tunlink();\n\t\t\twatcher.abort();\n\t\t}\n\t}\n\n\tasync downloadAndWait(\n\t\tmodel: string,\n\t\tonProgress: (progress: LlamaProgress) => void,\n\t\tsignal?: AbortSignal,\n\t): Promise {\n\t\tconst watcher = new AbortController();\n\t\tconst unlink = linkSignal(signal, watcher);\n\t\tlet finished = false;\n\t\tlet failure: string | undefined;\n\t\tlet sawDownloading = false;\n\t\tlet polls = 0;\n\t\tvoid this.watch((event) => {\n\t\t\tif (event.model !== model) return;\n\t\t\tif (event.event === \"download_finished\") finished = true;\n\t\t\tif (event.event === \"download_failed\") failure = errorMessage(event.data, \"Download failed\");\n\t\t\tif (event.event === \"download_progress\") {\n\t\t\t\tsawDownloading = true;\n\t\t\t\tconst progress = parseDownloadProgress(event.data);\n\t\t\t\tif (progress) onProgress(progress);\n\t\t\t}\n\t\t}, watcher.signal).catch(() => {});\n\t\ttry {\n\t\t\tawait this.download(model, signal);\n\t\t\tonProgress({ message: \"Downloading model\" });\n\t\t\twhile (true) {\n\t\t\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Cancelled\");\n\t\t\t\tif (failure) throw new Error(failure);\n\t\t\t\tconst models = await this.list({ signal });\n\t\t\t\tpolls++;\n\t\t\t\tconst entry = models.find((candidate) => candidate.id === model);\n\t\t\t\tif (entry?.status.value === \"downloading\") {\n\t\t\t\t\tsawDownloading = true;\n\t\t\t\t\tconst progress = parseDownloadProgress(entry.status.progress);\n\t\t\t\t\tif (progress) onProgress(progress);\n\t\t\t\t} else if (finished || (entry && (sawDownloading || polls >= 2))) {\n\t\t\t\t\treturn this.list({ reload: true, signal });\n\t\t\t\t}\n\t\t\t\tawait sleep(500, signal);\n\t\t\t}\n\t\t} finally {\n\t\t\tunlink();\n\t\t\twatcher.abort();\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/extensions/llama/huggingface.d.ts b/dist/extensions/llama/huggingface.d.ts new file mode 100644 index 0000000..85a17ef --- /dev/null +++ b/dist/extensions/llama/huggingface.d.ts @@ -0,0 +1,23 @@ +export interface HuggingFaceModel { + id: string; + downloads: number; +} +export interface HuggingFaceQuantization { + name: string; + size?: number; +} +export interface HuggingFaceModelDetails { + id: string; + gated: false | "auto" | "manual"; + quantizations: HuggingFaceQuantization[]; +} +export declare function findHuggingFaceToken(env?: NodeJS.ProcessEnv): Promise; +export declare class HuggingFaceClient { + private readonly token; + private readonly baseUrl; + constructor(token?: string, baseUrl?: string); + private request; + search(query: string, signal?: AbortSignal): Promise; + details(id: string, signal?: AbortSignal): Promise; +} +//# sourceMappingURL=huggingface.d.ts.map \ No newline at end of file diff --git a/dist/extensions/llama/huggingface.d.ts.map b/dist/extensions/llama/huggingface.d.ts.map new file mode 100644 index 0000000..24b4b1f --- /dev/null +++ b/dist/extensions/llama/huggingface.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"huggingface.d.ts","sourceRoot":"","sources":["../../../src/extensions/llama/huggingface.ts"],"names":[],"mappings":"AASA,MAAM,WAAW,gBAAgB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,uBAAuB;IACvC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,uBAAuB;IACvC,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,KAAK,GAAG,MAAM,GAAG,QAAQ,CAAC;IACjC,aAAa,EAAE,uBAAuB,EAAE,CAAC;CACzC;AAsBD,wBAAsB,oBAAoB,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAe5G;AAED,qBAAa,iBAAiB;IAC7B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAqB;IAC3C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IAEjC,YAAY,KAAK,CAAC,EAAE,MAAM,EAAE,OAAO,SAA2B,EAG7D;YAEa,OAAO;IA4Bf,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAgB7E;IAEK,OAAO,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAuChF;CACD","sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst DEFAULT_HUGGING_FACE_URL = \"https://huggingface.co\";\nconst QUANTIZATION_PATTERN =\n\t/(?:^|[-_.])((?:UD-)?(?:IQ\\d(?:_[A-Z0-9]+)+|Q\\d(?:_[A-Z0-9]+)+|BF16|F16|F32|MXFP\\d(?:_[A-Z0-9]+)*))$/iu;\nconst SHARD_SUFFIX_PATTERN = /-\\d{5}-of-\\d{5}$/u;\n\nexport interface HuggingFaceModel {\n\tid: string;\n\tdownloads: number;\n}\n\nexport interface HuggingFaceQuantization {\n\tname: string;\n\tsize?: number;\n}\n\nexport interface HuggingFaceModelDetails {\n\tid: string;\n\tgated: false | \"auto\" | \"manual\";\n\tquantizations: HuggingFaceQuantization[];\n}\n\nfunction payloadError(payload: unknown, fallback: string): string {\n\tif (typeof payload !== \"object\" || payload === null) return fallback;\n\tconst error = (payload as { error?: unknown }).error;\n\treturn typeof error === \"string\" && error ? error : fallback;\n}\n\nfunction parseRateLimitDelay(value: string | null): number | undefined {\n\tconst match = value?.match(/(?:^|;)t=(\\d+)/u);\n\treturn match ? Number(match[1]) : undefined;\n}\n\nasync function readToken(path: string): Promise {\n\ttry {\n\t\tconst token = (await readFile(path, \"utf8\")).trim();\n\t\treturn token || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport async function findHuggingFaceToken(env: NodeJS.ProcessEnv = process.env): Promise {\n\tconst fromEnvironment = env.HF_TOKEN?.trim();\n\tif (fromEnvironment) return fromEnvironment;\n\n\tconst paths = [\n\t\tenv.HF_TOKEN_PATH,\n\t\tenv.HF_HOME ? join(env.HF_HOME, \"token\") : undefined,\n\t\tenv.XDG_CACHE_HOME ? join(env.XDG_CACHE_HOME, \"huggingface\", \"token\") : undefined,\n\t\tjoin(homedir(), \".cache\", \"huggingface\", \"token\"),\n\t].filter((path): path is string => Boolean(path));\n\tfor (const path of new Set(paths)) {\n\t\tconst token = await readToken(path);\n\t\tif (token) return token;\n\t}\n\treturn undefined;\n}\n\nexport class HuggingFaceClient {\n\tprivate readonly token: string | undefined;\n\tprivate readonly baseUrl: string;\n\n\tconstructor(token?: string, baseUrl = DEFAULT_HUGGING_FACE_URL) {\n\t\tthis.token = token;\n\t\tthis.baseUrl = baseUrl.replace(/\\/+$/u, \"\");\n\t}\n\n\tprivate async request(path: string, signal?: AbortSignal): Promise {\n\t\tconst headers = new Headers();\n\t\tif (this.token) headers.set(\"Authorization\", `Bearer ${this.token}`);\n\t\tconst timeout = AbortSignal.timeout(15_000);\n\t\tconst response = await fetch(`${this.baseUrl}${path}`, {\n\t\t\theaders,\n\t\t\tsignal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n\t\t});\n\t\tlet payload: unknown;\n\t\ttry {\n\t\t\tpayload = await response.json();\n\t\t} catch {\n\t\t\tpayload = undefined;\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tconst fallback = `Hugging Face returned HTTP ${response.status}`;\n\t\t\tif (response.status === 429) {\n\t\t\t\tconst delay =\n\t\t\t\t\tNumber(response.headers.get(\"retry-after\")) || parseRateLimitDelay(response.headers.get(\"ratelimit\"));\n\t\t\t\tthrow new Error(\n\t\t\t\t\tdelay ? `Hugging Face rate limit reached; retry in ${delay}s` : \"Hugging Face rate limit reached\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(payloadError(payload, fallback));\n\t\t}\n\t\treturn payload;\n\t}\n\n\tasync search(query: string, signal?: AbortSignal): Promise {\n\t\tconst params = new URLSearchParams({\n\t\t\tsearch: query,\n\t\t\tfilter: \"gguf\",\n\t\t\tsort: \"downloads\",\n\t\t\tdirection: \"-1\",\n\t\t\tlimit: \"20\",\n\t\t});\n\t\tconst payload = await this.request(`/api/models?${params}`, signal);\n\t\tif (!Array.isArray(payload)) throw new Error(\"Hugging Face returned invalid search results\");\n\t\treturn payload.flatMap((value) => {\n\t\t\tif (typeof value !== \"object\" || value === null || typeof (value as { id?: unknown }).id !== \"string\")\n\t\t\t\treturn [];\n\t\t\tconst model = value as { id: string; downloads?: unknown };\n\t\t\treturn [{ id: model.id, downloads: typeof model.downloads === \"number\" ? model.downloads : 0 }];\n\t\t});\n\t}\n\n\tasync details(id: string, signal?: AbortSignal): Promise {\n\t\tconst encodedId = id.split(\"/\").map(encodeURIComponent).join(\"/\");\n\t\tconst payload = await this.request(`/api/models/${encodedId}?blobs=true`, signal);\n\t\tif (typeof payload !== \"object\" || payload === null) {\n\t\t\tthrow new Error(\"Hugging Face returned invalid model details\");\n\t\t}\n\t\tconst model = payload as { id?: unknown; gated?: unknown; siblings?: unknown };\n\t\tconst sizes = new Map();\n\t\tif (Array.isArray(model.siblings)) {\n\t\t\tfor (const value of model.siblings) {\n\t\t\t\tif (typeof value !== \"object\" || value === null) continue;\n\t\t\t\tconst file = value as { rfilename?: unknown; size?: unknown };\n\t\t\t\tif (typeof file.rfilename !== \"string\" || !file.rfilename.toLowerCase().endsWith(\".gguf\")) continue;\n\t\t\t\tconst filename = file.rfilename.split(\"/\").at(-1)!;\n\t\t\t\tif (filename.toLowerCase().startsWith(\"mmproj\")) continue;\n\t\t\t\tconst stem = filename.slice(0, -5).replace(SHARD_SUFFIX_PATTERN, \"\");\n\t\t\t\tconst quantization = stem.match(QUANTIZATION_PATTERN)?.[1]?.toUpperCase();\n\t\t\t\tif (!quantization) continue;\n\t\t\t\tconst current = sizes.get(quantization) ?? { total: 0, complete: true };\n\t\t\t\tif (typeof file.size === \"number\") current.total += file.size;\n\t\t\t\telse current.complete = false;\n\t\t\t\tsizes.set(quantization, current);\n\t\t\t}\n\t\t}\n\t\tconst quantizations = [...sizes]\n\t\t\t.map(([name, size]) => ({ name, size: size.complete ? size.total : undefined }))\n\t\t\t.sort((left, right) => {\n\t\t\t\tif (left.name === \"Q4_K_M\") return -1;\n\t\t\t\tif (right.name === \"Q4_K_M\") return 1;\n\t\t\t\treturn (\n\t\t\t\t\t(left.size ?? Number.MAX_SAFE_INTEGER) - (right.size ?? Number.MAX_SAFE_INTEGER) ||\n\t\t\t\t\tleft.name.localeCompare(right.name)\n\t\t\t\t);\n\t\t\t});\n\t\treturn {\n\t\t\tid: typeof model.id === \"string\" ? model.id : id,\n\t\t\tgated: model.gated === \"auto\" || model.gated === \"manual\" ? model.gated : false,\n\t\t\tquantizations,\n\t\t};\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/extensions/llama/huggingface.js b/dist/extensions/llama/huggingface.js new file mode 100644 index 0000000..5696c39 --- /dev/null +++ b/dist/extensions/llama/huggingface.js @@ -0,0 +1,141 @@ +import { readFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +const DEFAULT_HUGGING_FACE_URL = "https://huggingface.co"; +const QUANTIZATION_PATTERN = /(?:^|[-_.])((?:UD-)?(?:IQ\d(?:_[A-Z0-9]+)+|Q\d(?:_[A-Z0-9]+)+|BF16|F16|F32|MXFP\d(?:_[A-Z0-9]+)*))$/iu; +const SHARD_SUFFIX_PATTERN = /-\d{5}-of-\d{5}$/u; +function payloadError(payload, fallback) { + if (typeof payload !== "object" || payload === null) + return fallback; + const error = payload.error; + return typeof error === "string" && error ? error : fallback; +} +function parseRateLimitDelay(value) { + const match = value?.match(/(?:^|;)t=(\d+)/u); + return match ? Number(match[1]) : undefined; +} +async function readToken(path) { + try { + const token = (await readFile(path, "utf8")).trim(); + return token || undefined; + } + catch { + return undefined; + } +} +export async function findHuggingFaceToken(env = process.env) { + const fromEnvironment = env.HF_TOKEN?.trim(); + if (fromEnvironment) + return fromEnvironment; + const paths = [ + env.HF_TOKEN_PATH, + env.HF_HOME ? join(env.HF_HOME, "token") : undefined, + env.XDG_CACHE_HOME ? join(env.XDG_CACHE_HOME, "huggingface", "token") : undefined, + join(homedir(), ".cache", "huggingface", "token"), + ].filter((path) => Boolean(path)); + for (const path of new Set(paths)) { + const token = await readToken(path); + if (token) + return token; + } + return undefined; +} +export class HuggingFaceClient { + token; + baseUrl; + constructor(token, baseUrl = DEFAULT_HUGGING_FACE_URL) { + this.token = token; + this.baseUrl = baseUrl.replace(/\/+$/u, ""); + } + async request(path, signal) { + const headers = new Headers(); + if (this.token) + headers.set("Authorization", `Bearer ${this.token}`); + const timeout = AbortSignal.timeout(15_000); + const response = await fetch(`${this.baseUrl}${path}`, { + headers, + signal: signal ? AbortSignal.any([signal, timeout]) : timeout, + }); + let payload; + try { + payload = await response.json(); + } + catch { + payload = undefined; + } + if (!response.ok) { + const fallback = `Hugging Face returned HTTP ${response.status}`; + if (response.status === 429) { + const delay = Number(response.headers.get("retry-after")) || parseRateLimitDelay(response.headers.get("ratelimit")); + throw new Error(delay ? `Hugging Face rate limit reached; retry in ${delay}s` : "Hugging Face rate limit reached"); + } + throw new Error(payloadError(payload, fallback)); + } + return payload; + } + async search(query, signal) { + const params = new URLSearchParams({ + search: query, + filter: "gguf", + sort: "downloads", + direction: "-1", + limit: "20", + }); + const payload = await this.request(`/api/models?${params}`, signal); + if (!Array.isArray(payload)) + throw new Error("Hugging Face returned invalid search results"); + return payload.flatMap((value) => { + if (typeof value !== "object" || value === null || typeof value.id !== "string") + return []; + const model = value; + return [{ id: model.id, downloads: typeof model.downloads === "number" ? model.downloads : 0 }]; + }); + } + async details(id, signal) { + const encodedId = id.split("/").map(encodeURIComponent).join("/"); + const payload = await this.request(`/api/models/${encodedId}?blobs=true`, signal); + if (typeof payload !== "object" || payload === null) { + throw new Error("Hugging Face returned invalid model details"); + } + const model = payload; + const sizes = new Map(); + if (Array.isArray(model.siblings)) { + for (const value of model.siblings) { + if (typeof value !== "object" || value === null) + continue; + const file = value; + if (typeof file.rfilename !== "string" || !file.rfilename.toLowerCase().endsWith(".gguf")) + continue; + const filename = file.rfilename.split("/").at(-1); + if (filename.toLowerCase().startsWith("mmproj")) + continue; + const stem = filename.slice(0, -5).replace(SHARD_SUFFIX_PATTERN, ""); + const quantization = stem.match(QUANTIZATION_PATTERN)?.[1]?.toUpperCase(); + if (!quantization) + continue; + const current = sizes.get(quantization) ?? { total: 0, complete: true }; + if (typeof file.size === "number") + current.total += file.size; + else + current.complete = false; + sizes.set(quantization, current); + } + } + const quantizations = [...sizes] + .map(([name, size]) => ({ name, size: size.complete ? size.total : undefined })) + .sort((left, right) => { + if (left.name === "Q4_K_M") + return -1; + if (right.name === "Q4_K_M") + return 1; + return ((left.size ?? Number.MAX_SAFE_INTEGER) - (right.size ?? Number.MAX_SAFE_INTEGER) || + left.name.localeCompare(right.name)); + }); + return { + id: typeof model.id === "string" ? model.id : id, + gated: model.gated === "auto" || model.gated === "manual" ? model.gated : false, + quantizations, + }; + } +} +//# sourceMappingURL=huggingface.js.map \ No newline at end of file diff --git a/dist/extensions/llama/huggingface.js.map b/dist/extensions/llama/huggingface.js.map new file mode 100644 index 0000000..2a3fe41 --- /dev/null +++ b/dist/extensions/llama/huggingface.js.map @@ -0,0 +1 @@ +{"version":3,"file":"huggingface.js","sourceRoot":"","sources":["../../../src/extensions/llama/huggingface.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,MAAM,wBAAwB,GAAG,wBAAwB,CAAC;AAC1D,MAAM,oBAAoB,GACzB,uGAAuG,CAAC;AACzG,MAAM,oBAAoB,GAAG,mBAAmB,CAAC;AAkBjD,SAAS,YAAY,CAAC,OAAgB,EAAE,QAAgB,EAAU;IACjE,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI;QAAE,OAAO,QAAQ,CAAC;IACrE,MAAM,KAAK,GAAI,OAA+B,CAAC,KAAK,CAAC;I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CAAC,IAAI,CAAC,IAAI,IAAI,MAAM,CAAC,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,IAAI,MAAM,CAAC,gBAAgB,CAAC;gBAChF,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CACnC,CAAC;QAAA,CACF,CAAC,CAAC;QACJ,OAAO;YACN,EAAE,EAAE,OAAO,KAAK,CAAC,EAAE,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE;YAChD,KAAK,EAAE,KAAK,CAAC,KAAK,KAAK,MAAM,IAAI,KAAK,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK;YAC/E,aAAa;SACb,CAAC;IAAA,CACF;CACD","sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst DEFAULT_HUGGING_FACE_URL = \"https://huggingface.co\";\nconst QUANTIZATION_PATTERN =\n\t/(?:^|[-_.])((?:UD-)?(?:IQ\\d(?:_[A-Z0-9]+)+|Q\\d(?:_[A-Z0-9]+)+|BF16|F16|F32|MXFP\\d(?:_[A-Z0-9]+)*))$/iu;\nconst SHARD_SUFFIX_PATTERN = /-\\d{5}-of-\\d{5}$/u;\n\nexport interface HuggingFaceModel {\n\tid: string;\n\tdownloads: number;\n}\n\nexport interface HuggingFaceQuantization {\n\tname: string;\n\tsize?: number;\n}\n\nexport interface HuggingFaceModelDetails {\n\tid: string;\n\tgated: false | \"auto\" | \"manual\";\n\tquantizations: HuggingFaceQuantization[];\n}\n\nfunction payloadError(payload: unknown, fallback: string): string {\n\tif (typeof payload !== \"object\" || payload === null) return fallback;\n\tconst error = (payload as { error?: unknown }).error;\n\treturn typeof error === \"string\" && error ? error : fallback;\n}\n\nfunction parseRateLimitDelay(value: string | null): number | undefined {\n\tconst match = value?.match(/(?:^|;)t=(\\d+)/u);\n\treturn match ? Number(match[1]) : undefined;\n}\n\nasync function readToken(path: string): Promise {\n\ttry {\n\t\tconst token = (await readFile(path, \"utf8\")).trim();\n\t\treturn token || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport async function findHuggingFaceToken(env: NodeJS.ProcessEnv = process.env): Promise {\n\tconst fromEnvironment = env.HF_TOKEN?.trim();\n\tif (fromEnvironment) return fromEnvironment;\n\n\tconst paths = [\n\t\tenv.HF_TOKEN_PATH,\n\t\tenv.HF_HOME ? join(env.HF_HOME, \"token\") : undefined,\n\t\tenv.XDG_CACHE_HOME ? join(env.XDG_CACHE_HOME, \"huggingface\", \"token\") : undefined,\n\t\tjoin(homedir(), \".cache\", \"huggingface\", \"token\"),\n\t].filter((path): path is string => Boolean(path));\n\tfor (const path of new Set(paths)) {\n\t\tconst token = await readToken(path);\n\t\tif (token) return token;\n\t}\n\treturn undefined;\n}\n\nexport class HuggingFaceClient {\n\tprivate readonly token: string | undefined;\n\tprivate readonly baseUrl: string;\n\n\tconstructor(token?: string, baseUrl = DEFAULT_HUGGING_FACE_URL) {\n\t\tthis.token = token;\n\t\tthis.baseUrl = baseUrl.replace(/\\/+$/u, \"\");\n\t}\n\n\tprivate async request(path: string, signal?: AbortSignal): Promise {\n\t\tconst headers = new Headers();\n\t\tif (this.token) headers.set(\"Authorization\", `Bearer ${this.token}`);\n\t\tconst timeout = AbortSignal.timeout(15_000);\n\t\tconst response = await fetch(`${this.baseUrl}${path}`, {\n\t\t\theaders,\n\t\t\tsignal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n\t\t});\n\t\tlet payload: unknown;\n\t\ttry {\n\t\t\tpayload = await response.json();\n\t\t} catch {\n\t\t\tpayload = undefined;\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tconst fallback = `Hugging Face returned HTTP ${response.status}`;\n\t\t\tif (response.status === 429) {\n\t\t\t\tconst delay =\n\t\t\t\t\tNumber(response.headers.get(\"retry-after\")) || parseRateLimitDelay(response.headers.get(\"ratelimit\"));\n\t\t\t\tthrow new Error(\n\t\t\t\t\tdelay ? `Hugging Face rate limit reached; retry in ${delay}s` : \"Hugging Face rate limit reached\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(payloadError(payload, fallback));\n\t\t}\n\t\treturn payload;\n\t}\n\n\tasync search(query: string, signal?: AbortSignal): Promise {\n\t\tconst params = new URLSearchParams({\n\t\t\tsearch: query,\n\t\t\tfilter: \"gguf\",\n\t\t\tsort: \"downloads\",\n\t\t\tdirection: \"-1\",\n\t\t\tlimit: \"20\",\n\t\t});\n\t\tconst payload = await this.request(`/api/models?${params}`, signal);\n\t\tif (!Array.isArray(payload)) throw new Error(\"Hugging Face returned invalid search results\");\n\t\treturn payload.flatMap((value) => {\n\t\t\tif (typeof value !== \"object\" || value === null || typeof (value as { id?: unknown }).id !== \"string\")\n\t\t\t\treturn [];\n\t\t\tconst model = value as { id: string; downloads?: unknown };\n\t\t\treturn [{ id: model.id, downloads: typeof model.downloads === \"number\" ? model.downloads : 0 }];\n\t\t});\n\t}\n\n\tasync details(id: string, signal?: AbortSignal): Promise {\n\t\tconst encodedId = id.split(\"/\").map(encodeURIComponent).join(\"/\");\n\t\tconst payload = await this.request(`/api/models/${encodedId}?blobs=true`, signal);\n\t\tif (typeof payload !== \"object\" || payload === null) {\n\t\t\tthrow new Error(\"Hugging Face returned invalid model details\");\n\t\t}\n\t\tconst model = payload as { id?: unknown; gated?: unknown; siblings?: unknown };\n\t\tconst sizes = new Map();\n\t\tif (Array.isArray(model.siblings)) {\n\t\t\tfor (const value of model.siblings) {\n\t\t\t\tif (typeof value !== \"object\" || value === null) continue;\n\t\t\t\tconst file = value as { rfilename?: unknown; size?: unknown };\n\t\t\t\tif (typeof file.rfilename !== \"string\" || !file.rfilename.toLowerCase().endsWith(\".gguf\")) continue;\n\t\t\t\tconst filename = file.rfilename.split(\"/\").at(-1)!;\n\t\t\t\tif (filename.toLowerCase().startsWith(\"mmproj\")) continue;\n\t\t\t\tconst stem = filename.slice(0, -5).replace(SHARD_SUFFIX_PATTERN, \"\");\n\t\t\t\tconst quantization = stem.match(QUANTIZATION_PATTERN)?.[1]?.toUpperCase();\n\t\t\t\tif (!quantization) continue;\n\t\t\t\tconst current = sizes.get(quantization) ?? { total: 0, complete: true };\n\t\t\t\tif (typeof file.size === \"number\") current.total += file.size;\n\t\t\t\telse current.complete = false;\n\t\t\t\tsizes.set(quantization, current);\n\t\t\t}\n\t\t}\n\t\tconst quantizations = [...sizes]\n\t\t\t.map(([name, size]) => ({ name, size: size.complete ? size.total : undefined }))\n\t\t\t.sort((left, right) => {\n\t\t\t\tif (left.name === \"Q4_K_M\") return -1;\n\t\t\t\tif (right.name === \"Q4_K_M\") return 1;\n\t\t\t\treturn (\n\t\t\t\t\t(left.size ?? Number.MAX_SAFE_INTEGER) - (right.size ?? Number.MAX_SAFE_INTEGER) ||\n\t\t\t\t\tleft.name.localeCompare(right.name)\n\t\t\t\t);\n\t\t\t});\n\t\treturn {\n\t\t\tid: typeof model.id === \"string\" ? model.id : id,\n\t\t\tgated: model.gated === \"auto\" || model.gated === \"manual\" ? model.gated : false,\n\t\t\tquantizations,\n\t\t};\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/extensions/llama/index.d.ts b/dist/extensions/llama/index.d.ts new file mode 100644 index 0000000..b893ef5 --- /dev/null +++ b/dist/extensions/llama/index.d.ts @@ -0,0 +1,3 @@ +import type { ExtensionAPI } from "../../core/extensions/types.ts"; +export default function llamaExtension(pi: ExtensionAPI): void; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/extensions/llama/index.d.ts.map b/dist/extensions/llama/index.d.ts.map new file mode 100644 index 0000000..856f342 --- /dev/null +++ b/dist/extensions/llama/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/llama/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAA2B,MAAM,gCAAgC,CAAC;AAyC5F,MAAM,CAAC,OAAO,UAAU,cAAc,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CAmL7D","sourcesContent":["import type { ExtensionAPI, ExtensionCommandContext } from \"../../core/extensions/types.ts\";\nimport { formatBytes, LlamaClient, type LlamaModelInfo, normalizeLlamaServerUrl } from \"./client.ts\";\nimport { findHuggingFaceToken, HuggingFaceClient } from \"./huggingface.ts\";\nimport { createLlamaProvider, LLAMA_PROVIDER_ID } from \"./provider.ts\";\nimport { type LlamaUi, runWithProgress, showLlamaUi } from \"./ui.ts\";\n\nfunction modelIsLoaded(model: LlamaModelInfo): boolean {\n\treturn model.status.value === \"loaded\" || model.status.value === \"sleeping\";\n}\n\nfunction isConnectionError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tconst message = `${error.name} ${error.message}`.toLowerCase();\n\treturn message.includes(\"fetch failed\") || message.includes(\"timeout\") || message.includes(\"network\");\n}\n\nfunction connectionErrorMessage(error: unknown): string {\n\tif (isConnectionError(error)) return \"Could not connect to the server.\";\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction parseHuggingFaceModel(value: string): { repository: string; quantization?: string } {\n\tconst colon = value.indexOf(\":\", value.indexOf(\"/\") + 1);\n\treturn colon < 0\n\t\t? { repository: value }\n\t\t: { repository: value.slice(0, colon), quantization: value.slice(colon + 1) };\n}\n\nasync function configuredClient(ctx: ExtensionCommandContext): Promise {\n\tconst result = await ctx.modelRegistry.getProviderAuth(LLAMA_PROVIDER_ID);\n\tif (!result) {\n\t\tctx.ui.notify(`Configure llama.cpp with /login ${LLAMA_PROVIDER_ID}`, \"warning\");\n\t\treturn undefined;\n\t}\n\tconst configuredUrl = result.env?.LLAMA_BASE_URL;\n\tconst serverUrl = normalizeLlamaServerUrl(\n\t\ttypeof configuredUrl === \"string\" && configuredUrl ? configuredUrl : (result.auth.baseUrl ?? \"\"),\n\t);\n\treturn new LlamaClient(serverUrl, result.auth.apiKey);\n}\n\nexport default function llamaExtension(pi: ExtensionAPI): void {\n\tconst provider = createLlamaProvider();\n\tpi.registerProvider(provider.provider);\n\n\tconst syncCatalog = async (\n\t\tctx: ExtensionCommandContext,\n\t\tclient: LlamaClient,\n\t\tcatalog?: LlamaModelInfo[],\n\t): Promise => {\n\t\tconst current = catalog ?? (await client.list());\n\t\tprovider.setCatalog(current, client.serverUrl);\n\t\tawait ctx.modelRegistry.refresh();\n\t\treturn current;\n\t};\n\n\tconst loadModel = async (\n\t\tctx: ExtensionCommandContext,\n\t\tui: LlamaUi,\n\t\tclient: LlamaClient,\n\t\tcatalog: LlamaModelInfo[],\n\t\ttarget: LlamaModelInfo,\n\t): Promise => {\n\t\tconst loaded = catalog.filter((model) => model.id !== target.id && modelIsLoaded(model));\n\t\tlet replace = false;\n\t\tif (loaded.length > 0) {\n\t\t\tconst choice = await ui.select(`${loaded.length} model${loaded.length === 1 ? \" is\" : \"s are\"} loaded`, [\n\t\t\t\t\"Unload all and load\",\n\t\t\t\t\"Keep loaded and load\",\n\t\t\t\t\"Cancel\",\n\t\t\t]);\n\t\t\tif (!choice || choice === \"Cancel\") return;\n\t\t\treplace = choice === \"Unload all and load\";\n\t\t}\n\n\t\tconst restoreLoaded = async (): Promise => {\n\t\t\tctx.ui.notify(\"Restoring previously loaded models\");\n\t\t\tfor (const model of loaded) await client.loadAndWait(model.id, () => {});\n\t\t\tawait syncCatalog(ctx, client);\n\t\t};\n\t\tif (replace) {\n\t\t\tfor (const model of loaded) await client.unloadAndWait(model.id);\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await runWithProgress(ui, {\n\t\t\t\ttitle: \"Loading model\",\n\t\t\t\tmodel: target.id,\n\t\t\t\tinitialMessage: \"Starting…\",\n\t\t\t\tcancelTitle: \"Stop loading?\",\n\t\t\t\tcancelMessage: target.id,\n\t\t\t\trun: (signal, update) => client.loadAndWait(target.id, update, signal),\n\t\t\t\tcancel: () => client.unload(target.id),\n\t\t\t});\n\t\t\tif (result.cancelled) {\n\t\t\t\tif (replace) await restoreLoaded();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst refreshed = await syncCatalog(ctx, client);\n\t\t\tconst loadedModel = refreshed.find((model) => model.id === target.id);\n\t\t\tctx.ui.notify(\n\t\t\t\tloadedModel?.status.value === \"loaded\" ? `Loaded ${target.id}` : `Load started for ${target.id}`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (replace) {\n\t\t\t\ttry {\n\t\t\t\t\tawait restoreLoaded();\n\t\t\t\t} catch {\n\t\t\t\t\t// Preserve the original load error.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tconst unloadModel = async (\n\t\tctx: ExtensionCommandContext,\n\t\tui: LlamaUi,\n\t\tclient: LlamaClient,\n\t\tmodel: LlamaModelInfo,\n\t): Promise => {\n\t\tif (!(await ui.confirm(\"Unload model?\", model.id))) return;\n\t\tawait client.unloadAndWait(model.id);\n\t\tawait syncCatalog(ctx, client);\n\t\tctx.ui.notify(`Unloaded ${model.id}`);\n\t};\n\n\tconst downloadModel = async (ctx: ExtensionCommandContext, ui: LlamaUi, client: LlamaClient): Promise => {\n\t\tconst huggingFace = new HuggingFaceClient(await findHuggingFaceToken());\n\t\tconst selected = await ui.searchModels((query, signal) => huggingFace.search(query, signal));\n\t\tif (!selected) return;\n\t\tconst parsed = parseHuggingFaceModel(selected);\n\t\tui.showStatus(\"Loading model details\", parsed.repository);\n\t\tconst details = await huggingFace.details(parsed.repository);\n\t\tif (details.gated) {\n\t\t\tconst approval = details.gated === \"manual\" ? \"Manual approval is required\" : \"Accept the access terms\";\n\t\t\tconst choice = await ui.select(\n\t\t\t\t`Hugging Face access required\\n${details.id}\\n\\n${approval} at:\\nhttps://huggingface.co/${details.id}\\n\\nThe llama.cpp server needs HF_TOKEN with access.`,\n\t\t\t\t[\"Continue\", \"Back\"],\n\t\t\t);\n\t\t\tif (choice !== \"Continue\") return;\n\t\t}\n\t\tlet quantization = parsed.quantization;\n\t\tif (!quantization && details.quantizations.length > 0) {\n\t\t\tconst options = details.quantizations.map((entry) => {\n\t\t\t\tconst detail = [\n\t\t\t\t\tentry.size === undefined ? undefined : formatBytes(entry.size),\n\t\t\t\t\tentry.name === \"Q4_K_M\" ? \"recommended\" : undefined,\n\t\t\t\t]\n\t\t\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t\t\t.join(\" · \");\n\t\t\t\treturn detail ? `${entry.name} · ${detail}` : entry.name;\n\t\t\t});\n\t\t\tconst choice = await ui.select(`Select quantization\\n${details.id}`, options);\n\t\t\tif (!choice) return;\n\t\t\tquantization = details.quantizations[options.indexOf(choice)]?.name;\n\t\t\tif (!quantization) return;\n\t\t}\n\t\tconst model = quantization ? `${details.id}:${quantization}` : details.id;\n\t\tconst result = await runWithProgress(ui, {\n\t\t\ttitle: \"Downloading model\",\n\t\t\tmodel,\n\t\t\tinitialMessage: \"Starting…\",\n\t\t\tcancelTitle: \"Stop download?\",\n\t\t\tcancelMessage: model,\n\t\t\trun: (signal, update) => client.downloadAndWait(model, update, signal),\n\t\t\tcancel: () => client.unload(model),\n\t\t});\n\t\tif (result.cancelled) return;\n\t\tawait syncCatalog(ctx, client, result.value);\n\t\tctx.ui.notify(`Downloaded ${model}`);\n\t};\n\n\tpi.registerCommand(\"llama\", {\n\t\tdescription: \"Manage llama.cpp router models\",\n\t\thandler: async (_args, ctx) => {\n\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\tctx.ui.notify(\"/llama is available in interactive mode\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst client = await configuredClient(ctx);\n\t\t\tif (!client) return;\n\t\t\tawait showLlamaUi(ctx, async (ui) => {\n\t\t\t\tconst readCatalog = async (): Promise => {\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await syncCatalog(ctx, client);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif ((await ui.connectionError(client.serverUrl, connectionErrorMessage(error))) === \"close\") {\n\t\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tlet catalog = await readCatalog();\n\t\t\t\tif (!catalog) return;\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst action = await ui.showModels(client.serverUrl, catalog);\n\t\t\t\t\tif (action.type === \"close\") return;\n\t\t\t\t\tlet actionError: unknown;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (action.type === \"download\") await downloadModel(ctx, ui, client);\n\t\t\t\t\t\telse if (modelIsLoaded(action.model)) await unloadModel(ctx, ui, client, action.model);\n\t\t\t\t\t\telse if (action.model.status.value === \"unloaded\")\n\t\t\t\t\t\t\tawait loadModel(ctx, ui, client, catalog, action.model);\n\t\t\t\t\t\telse ctx.ui.notify(`${action.model.id} is ${action.model.status.value}`, \"warning\");\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tactionError = error;\n\t\t\t\t\t}\n\t\t\t\t\tconst refreshed = await readCatalog();\n\t\t\t\t\tif (!refreshed) return;\n\t\t\t\t\tcatalog = refreshed;\n\t\t\t\t\tif (actionError && !isConnectionError(actionError)) {\n\t\t\t\t\t\tctx.ui.notify(actionError instanceof Error ? actionError.message : String(actionError), \"error\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t});\n}\n"]} \ No newline at end of file diff --git a/dist/extensions/llama/index.js b/dist/extensions/llama/index.js new file mode 100644 index 0000000..b1c102e --- /dev/null +++ b/dist/extensions/llama/index.js @@ -0,0 +1,208 @@ +import { formatBytes, LlamaClient, normalizeLlamaServerUrl } from "./client.js"; +import { findHuggingFaceToken, HuggingFaceClient } from "./huggingface.js"; +import { createLlamaProvider, LLAMA_PROVIDER_ID } from "./provider.js"; +import { runWithProgress, showLlamaUi } from "./ui.js"; +function modelIsLoaded(model) { + return model.status.value === "loaded" || model.status.value === "sleeping"; +} +function isConnectionError(error) { + if (!(error instanceof Error)) + return false; + const message = `${error.name} ${error.message}`.toLowerCase(); + return message.includes("fetch failed") || message.includes("timeout") || message.includes("network"); +} +function connectionErrorMessage(error) { + if (isConnectionError(error)) + return "Could not connect to the server."; + return error instanceof Error ? error.message : String(error); +} +function parseHuggingFaceModel(value) { + const colon = value.indexOf(":", value.indexOf("/") + 1); + return colon < 0 + ? { repository: value } + : { repository: value.slice(0, colon), quantization: value.slice(colon + 1) }; +} +async function configuredClient(ctx) { + const result = await ctx.modelRegistry.getProviderAuth(LLAMA_PROVIDER_ID); + if (!result) { + ctx.ui.notify(`Configure llama.cpp with /login ${LLAMA_PROVIDER_ID}`, "warning"); + return undefined; + } + const configuredUrl = result.env?.LLAMA_BASE_URL; + const serverUrl = normalizeLlamaServerUrl(typeof configuredUrl === "string" && configuredUrl ? configuredUrl : (result.auth.baseUrl ?? "")); + return new LlamaClient(serverUrl, result.auth.apiKey); +} +export default function llamaExtension(pi) { + const provider = createLlamaProvider(); + pi.registerProvider(provider.provider); + const syncCatalog = async (ctx, client, catalog) => { + const current = catalog ?? (await client.list()); + provider.setCatalog(current, client.serverUrl); + await ctx.modelRegistry.refresh(); + return current; + }; + const loadModel = async (ctx, ui, client, catalog, target) => { + const loaded = catalog.filter((model) => model.id !== target.id && modelIsLoaded(model)); + let replace = false; + if (loaded.length > 0) { + const choice = await ui.select(`${loaded.length} model${loaded.length === 1 ? " is" : "s are"} loaded`, [ + "Unload all and load", + "Keep loaded and load", + "Cancel", + ]); + if (!choice || choice === "Cancel") + return; + replace = choice === "Unload all and load"; + } + const restoreLoaded = async () => { + ctx.ui.notify("Restoring previously loaded models"); + for (const model of loaded) + await client.loadAndWait(model.id, () => { }); + await syncCatalog(ctx, client); + }; + if (replace) { + for (const model of loaded) + await client.unloadAndWait(model.id); + } + try { + const result = await runWithProgress(ui, { + title: "Loading model", + model: target.id, + initialMessage: "Starting…", + cancelTitle: "Stop loading?", + cancelMessage: target.id, + run: (signal, update) => client.loadAndWait(target.id, update, signal), + cancel: () => client.unload(target.id), + }); + if (result.cancelled) { + if (replace) + await restoreLoaded(); + return; + } + const refreshed = await syncCatalog(ctx, client); + const loadedModel = refreshed.find((model) => model.id === target.id); + ctx.ui.notify(loadedModel?.status.value === "loaded" ? `Loaded ${target.id}` : `Load started for ${target.id}`); + } + catch (error) { + if (replace) { + try { + await restoreLoaded(); + } + catch { + // Preserve the original load error. + } + } + throw error; + } + }; + const unloadModel = async (ctx, ui, client, model) => { + if (!(await ui.confirm("Unload model?", model.id))) + return; + await client.unloadAndWait(model.id); + await syncCatalog(ctx, client); + ctx.ui.notify(`Unloaded ${model.id}`); + }; + const downloadModel = async (ctx, ui, client) => { + const huggingFace = new HuggingFaceClient(await findHuggingFaceToken()); + const selected = await ui.searchModels((query, signal) => huggingFace.search(query, signal)); + if (!selected) + return; + const parsed = parseHuggingFaceModel(selected); + ui.showStatus("Loading model details", parsed.repository); + const details = await huggingFace.details(parsed.repository); + if (details.gated) { + const approval = details.gated === "manual" ? "Manual approval is required" : "Accept the access terms"; + const choice = await ui.select(`Hugging Face access required\n${details.id}\n\n${approval} at:\nhttps://huggingface.co/${details.id}\n\nThe llama.cpp server needs HF_TOKEN with access.`, ["Continue", "Back"]); + if (choice !== "Continue") + return; + } + let quantization = parsed.quantization; + if (!quantization && details.quantizations.length > 0) { + const options = details.quantizations.map((entry) => { + const detail = [ + entry.size === undefined ? undefined : formatBytes(entry.size), + entry.name === "Q4_K_M" ? "recommended" : undefined, + ] + .filter((value) => Boolean(value)) + .join(" · "); + return detail ? `${entry.name} · ${detail}` : entry.name; + }); + const choice = await ui.select(`Select quantization\n${details.id}`, options); + if (!choice) + return; + quantization = details.quantizations[options.indexOf(choice)]?.name; + if (!quantization) + return; + } + const model = quantization ? `${details.id}:${quantization}` : details.id; + const result = await runWithProgress(ui, { + title: "Downloading model", + model, + initialMessage: "Starting…", + cancelTitle: "Stop download?", + cancelMessage: model, + run: (signal, update) => client.downloadAndWait(model, update, signal), + cancel: () => client.unload(model), + }); + if (result.cancelled) + return; + await syncCatalog(ctx, client, result.value); + ctx.ui.notify(`Downloaded ${model}`); + }; + pi.registerCommand("llama", { + description: "Manage llama.cpp router models", + handler: async (_args, ctx) => { + if (ctx.mode !== "tui") { + ctx.ui.notify("/llama is available in interactive mode", "warning"); + return; + } + const client = await configuredClient(ctx); + if (!client) + return; + await showLlamaUi(ctx, async (ui) => { + const readCatalog = async () => { + while (true) { + try { + return await syncCatalog(ctx, client); + } + catch (error) { + if ((await ui.connectionError(client.serverUrl, connectionErrorMessage(error))) === "close") { + return undefined; + } + } + } + }; + let catalog = await readCatalog(); + if (!catalog) + return; + while (true) { + const action = await ui.showModels(client.serverUrl, catalog); + if (action.type === "close") + return; + let actionError; + try { + if (action.type === "download") + await downloadModel(ctx, ui, client); + else if (modelIsLoaded(action.model)) + await unloadModel(ctx, ui, client, action.model); + else if (action.model.status.value === "unloaded") + await loadModel(ctx, ui, client, catalog, action.model); + else + ctx.ui.notify(`${action.model.id} is ${action.model.status.value}`, "warning"); + } + catch (error) { + actionError = error; + } + const refreshed = await readCatalog(); + if (!refreshed) + return; + catalog = refreshed; + if (actionError && !isConnectionError(actionError)) { + ctx.ui.notify(actionError instanceof Error ? actionError.message : String(actionError), "error"); + } + } + }); + }, + }); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/extensions/llama/index.js.map b/dist/extensions/llama/index.js.map new file mode 100644 index 0000000..21cf76f --- /dev/null +++ b/dist/extensions/llama/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/extensions/llama/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,WAAW,EAAuB,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACrG,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvE,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IAAI,CAAC,SAAS;wBAAE,OAAO;oBACvB,OAAO,GAAG,SAAS,CAAC;oBACpB,IAAI,WAAW,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,EAAE,CAAC;wBACpD,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,WAAW,YAAY,KAAK,CAAC,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC,CAAC;oBAClG,CAAC;gBACF,CAAC;YAAA,CACD,CAAC,CAAC;QAAA,CACH;KACD,CAAC,CAAC;AAAA,CACH","sourcesContent":["import type { ExtensionAPI, ExtensionCommandContext } from \"../../core/extensions/types.ts\";\nimport { formatBytes, LlamaClient, type LlamaModelInfo, normalizeLlamaServerUrl } from \"./client.ts\";\nimport { findHuggingFaceToken, HuggingFaceClient } from \"./huggingface.ts\";\nimport { createLlamaProvider, LLAMA_PROVIDER_ID } from \"./provider.ts\";\nimport { type LlamaUi, runWithProgress, showLlamaUi } from \"./ui.ts\";\n\nfunction modelIsLoaded(model: LlamaModelInfo): boolean {\n\treturn model.status.value === \"loaded\" || model.status.value === \"sleeping\";\n}\n\nfunction isConnectionError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tconst message = `${error.name} ${error.message}`.toLowerCase();\n\treturn message.includes(\"fetch failed\") || message.includes(\"timeout\") || message.includes(\"network\");\n}\n\nfunction connectionErrorMessage(error: unknown): string {\n\tif (isConnectionError(error)) return \"Could not connect to the server.\";\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction parseHuggingFaceModel(value: string): { repository: string; quantization?: string } {\n\tconst colon = value.indexOf(\":\", value.indexOf(\"/\") + 1);\n\treturn colon < 0\n\t\t? { repository: value }\n\t\t: { repository: value.slice(0, colon), quantization: value.slice(colon + 1) };\n}\n\nasync function configuredClient(ctx: ExtensionCommandContext): Promise {\n\tconst result = await ctx.modelRegistry.getProviderAuth(LLAMA_PROVIDER_ID);\n\tif (!result) {\n\t\tctx.ui.notify(`Configure llama.cpp with /login ${LLAMA_PROVIDER_ID}`, \"warning\");\n\t\treturn undefined;\n\t}\n\tconst configuredUrl = result.env?.LLAMA_BASE_URL;\n\tconst serverUrl = normalizeLlamaServerUrl(\n\t\ttypeof configuredUrl === \"string\" && configuredUrl ? configuredUrl : (result.auth.baseUrl ?? \"\"),\n\t);\n\treturn new LlamaClient(serverUrl, result.auth.apiKey);\n}\n\nexport default function llamaExtension(pi: ExtensionAPI): void {\n\tconst provider = createLlamaProvider();\n\tpi.registerProvider(provider.provider);\n\n\tconst syncCatalog = async (\n\t\tctx: ExtensionCommandContext,\n\t\tclient: LlamaClient,\n\t\tcatalog?: LlamaModelInfo[],\n\t): Promise => {\n\t\tconst current = catalog ?? (await client.list());\n\t\tprovider.setCatalog(current, client.serverUrl);\n\t\tawait ctx.modelRegistry.refresh();\n\t\treturn current;\n\t};\n\n\tconst loadModel = async (\n\t\tctx: ExtensionCommandContext,\n\t\tui: LlamaUi,\n\t\tclient: LlamaClient,\n\t\tcatalog: LlamaModelInfo[],\n\t\ttarget: LlamaModelInfo,\n\t): Promise => {\n\t\tconst loaded = catalog.filter((model) => model.id !== target.id && modelIsLoaded(model));\n\t\tlet replace = false;\n\t\tif (loaded.length > 0) {\n\t\t\tconst choice = await ui.select(`${loaded.length} model${loaded.length === 1 ? \" is\" : \"s are\"} loaded`, [\n\t\t\t\t\"Unload all and load\",\n\t\t\t\t\"Keep loaded and load\",\n\t\t\t\t\"Cancel\",\n\t\t\t]);\n\t\t\tif (!choice || choice === \"Cancel\") return;\n\t\t\treplace = choice === \"Unload all and load\";\n\t\t}\n\n\t\tconst restoreLoaded = async (): Promise => {\n\t\t\tctx.ui.notify(\"Restoring previously loaded models\");\n\t\t\tfor (const model of loaded) await client.loadAndWait(model.id, () => {});\n\t\t\tawait syncCatalog(ctx, client);\n\t\t};\n\t\tif (replace) {\n\t\t\tfor (const model of loaded) await client.unloadAndWait(model.id);\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await runWithProgress(ui, {\n\t\t\t\ttitle: \"Loading model\",\n\t\t\t\tmodel: target.id,\n\t\t\t\tinitialMessage: \"Starting…\",\n\t\t\t\tcancelTitle: \"Stop loading?\",\n\t\t\t\tcancelMessage: target.id,\n\t\t\t\trun: (signal, update) => client.loadAndWait(target.id, update, signal),\n\t\t\t\tcancel: () => client.unload(target.id),\n\t\t\t});\n\t\t\tif (result.cancelled) {\n\t\t\t\tif (replace) await restoreLoaded();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst refreshed = await syncCatalog(ctx, client);\n\t\t\tconst loadedModel = refreshed.find((model) => model.id === target.id);\n\t\t\tctx.ui.notify(\n\t\t\t\tloadedModel?.status.value === \"loaded\" ? `Loaded ${target.id}` : `Load started for ${target.id}`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (replace) {\n\t\t\t\ttry {\n\t\t\t\t\tawait restoreLoaded();\n\t\t\t\t} catch {\n\t\t\t\t\t// Preserve the original load error.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t};\n\n\tconst unloadModel = async (\n\t\tctx: ExtensionCommandContext,\n\t\tui: LlamaUi,\n\t\tclient: LlamaClient,\n\t\tmodel: LlamaModelInfo,\n\t): Promise => {\n\t\tif (!(await ui.confirm(\"Unload model?\", model.id))) return;\n\t\tawait client.unloadAndWait(model.id);\n\t\tawait syncCatalog(ctx, client);\n\t\tctx.ui.notify(`Unloaded ${model.id}`);\n\t};\n\n\tconst downloadModel = async (ctx: ExtensionCommandContext, ui: LlamaUi, client: LlamaClient): Promise => {\n\t\tconst huggingFace = new HuggingFaceClient(await findHuggingFaceToken());\n\t\tconst selected = await ui.searchModels((query, signal) => huggingFace.search(query, signal));\n\t\tif (!selected) return;\n\t\tconst parsed = parseHuggingFaceModel(selected);\n\t\tui.showStatus(\"Loading model details\", parsed.repository);\n\t\tconst details = await huggingFace.details(parsed.repository);\n\t\tif (details.gated) {\n\t\t\tconst approval = details.gated === \"manual\" ? \"Manual approval is required\" : \"Accept the access terms\";\n\t\t\tconst choice = await ui.select(\n\t\t\t\t`Hugging Face access required\\n${details.id}\\n\\n${approval} at:\\nhttps://huggingface.co/${details.id}\\n\\nThe llama.cpp server needs HF_TOKEN with access.`,\n\t\t\t\t[\"Continue\", \"Back\"],\n\t\t\t);\n\t\t\tif (choice !== \"Continue\") return;\n\t\t}\n\t\tlet quantization = parsed.quantization;\n\t\tif (!quantization && details.quantizations.length > 0) {\n\t\t\tconst options = details.quantizations.map((entry) => {\n\t\t\t\tconst detail = [\n\t\t\t\t\tentry.size === undefined ? undefined : formatBytes(entry.size),\n\t\t\t\t\tentry.name === \"Q4_K_M\" ? \"recommended\" : undefined,\n\t\t\t\t]\n\t\t\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t\t\t.join(\" · \");\n\t\t\t\treturn detail ? `${entry.name} · ${detail}` : entry.name;\n\t\t\t});\n\t\t\tconst choice = await ui.select(`Select quantization\\n${details.id}`, options);\n\t\t\tif (!choice) return;\n\t\t\tquantization = details.quantizations[options.indexOf(choice)]?.name;\n\t\t\tif (!quantization) return;\n\t\t}\n\t\tconst model = quantization ? `${details.id}:${quantization}` : details.id;\n\t\tconst result = await runWithProgress(ui, {\n\t\t\ttitle: \"Downloading model\",\n\t\t\tmodel,\n\t\t\tinitialMessage: \"Starting…\",\n\t\t\tcancelTitle: \"Stop download?\",\n\t\t\tcancelMessage: model,\n\t\t\trun: (signal, update) => client.downloadAndWait(model, update, signal),\n\t\t\tcancel: () => client.unload(model),\n\t\t});\n\t\tif (result.cancelled) return;\n\t\tawait syncCatalog(ctx, client, result.value);\n\t\tctx.ui.notify(`Downloaded ${model}`);\n\t};\n\n\tpi.registerCommand(\"llama\", {\n\t\tdescription: \"Manage llama.cpp router models\",\n\t\thandler: async (_args, ctx) => {\n\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\tctx.ui.notify(\"/llama is available in interactive mode\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst client = await configuredClient(ctx);\n\t\t\tif (!client) return;\n\t\t\tawait showLlamaUi(ctx, async (ui) => {\n\t\t\t\tconst readCatalog = async (): Promise => {\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await syncCatalog(ctx, client);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif ((await ui.connectionError(client.serverUrl, connectionErrorMessage(error))) === \"close\") {\n\t\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tlet catalog = await readCatalog();\n\t\t\t\tif (!catalog) return;\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst action = await ui.showModels(client.serverUrl, catalog);\n\t\t\t\t\tif (action.type === \"close\") return;\n\t\t\t\t\tlet actionError: unknown;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (action.type === \"download\") await downloadModel(ctx, ui, client);\n\t\t\t\t\t\telse if (modelIsLoaded(action.model)) await unloadModel(ctx, ui, client, action.model);\n\t\t\t\t\t\telse if (action.model.status.value === \"unloaded\")\n\t\t\t\t\t\t\tawait loadModel(ctx, ui, client, catalog, action.model);\n\t\t\t\t\t\telse ctx.ui.notify(`${action.model.id} is ${action.model.status.value}`, \"warning\");\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tactionError = error;\n\t\t\t\t\t}\n\t\t\t\t\tconst refreshed = await readCatalog();\n\t\t\t\t\tif (!refreshed) return;\n\t\t\t\t\tcatalog = refreshed;\n\t\t\t\t\tif (actionError && !isConnectionError(actionError)) {\n\t\t\t\t\t\tctx.ui.notify(actionError instanceof Error ? actionError.message : String(actionError), \"error\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t});\n}\n"]} \ No newline at end of file diff --git a/dist/extensions/llama/provider.d.ts b/dist/extensions/llama/provider.d.ts new file mode 100644 index 0000000..fa17f0f --- /dev/null +++ b/dist/extensions/llama/provider.d.ts @@ -0,0 +1,10 @@ +import type { Provider } from "@earendil-works/pi-ai"; +import { type LlamaModelInfo } from "./client.ts"; +export declare const LLAMA_PROVIDER_ID = "llama.cpp"; +export declare const DEFAULT_LLAMA_SERVER_URL = "http://127.0.0.1:8080"; +export interface LlamaProviderController { + provider: Provider<"openai-completions">; + setCatalog(models: readonly LlamaModelInfo[], serverUrl: string): void; +} +export declare function createLlamaProvider(): LlamaProviderController; +//# sourceMappingURL=provider.d.ts.map \ No newline at end of file diff --git a/dist/extensions/llama/provider.d.ts.map b/dist/extensions/llama/provider.d.ts.map new file mode 100644 index 0000000..3e6d2f1 --- /dev/null +++ b/dist/extensions/llama/provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../src/extensions/llama/provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAKX,QAAQ,EAGR,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAe,KAAK,cAAc,EAA8C,MAAM,aAAa,CAAC;AAE3G,eAAO,MAAM,iBAAiB,cAAc,CAAC;AAC7C,eAAO,MAAM,wBAAwB,0BAA0B,CAAC;AAuChE,MAAM,WAAW,uBAAuB;IACvC,QAAQ,EAAE,QAAQ,CAAC,oBAAoB,CAAC,CAAC;IACzC,UAAU,CAAC,MAAM,EAAE,SAAS,cAAc,EAAE,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CACvE;AAED,wBAAgB,mBAAmB,IAAI,uBAAuB,CA4E7D","sourcesContent":["import type {\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tModel,\n\tProvider,\n\tProviderStreamOptions,\n\tRefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { stream, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { LlamaClient, type LlamaModelInfo, llamaInferenceUrl, normalizeLlamaServerUrl } from \"./client.ts\";\n\nexport const LLAMA_PROVIDER_ID = \"llama.cpp\";\nexport const DEFAULT_LLAMA_SERVER_URL = \"http://127.0.0.1:8080\";\nfunction credentialServerUrl(credential: ApiKeyCredential | undefined): string | undefined {\n\tconst value = credential?.env?.LLAMA_BASE_URL;\n\treturn typeof value === \"string\" && value.trim() ? normalizeLlamaServerUrl(value) : undefined;\n}\n\nasync function resolveServerUrl(\n\tctx: AuthContext,\n\tcredential: ApiKeyCredential | undefined,\n): Promise {\n\tconst configured = credentialServerUrl(credential) ?? (await ctx.env(\"LLAMA_BASE_URL\"))?.trim();\n\treturn configured ? normalizeLlamaServerUrl(configured) : undefined;\n}\n\nfunction toPiModel(model: LlamaModelInfo, serverUrl: string): Model<\"openai-completions\"> {\n\tconst reportedContextWindow = model.meta?.n_ctx ?? model.meta?.n_ctx_train;\n\tconst contextWindow = reportedContextWindow && reportedContextWindow > 0 ? reportedContextWindow : 128000;\n\treturn {\n\t\tid: model.id,\n\t\tname: model.id,\n\t\tapi: \"openai-completions\",\n\t\tprovider: LLAMA_PROVIDER_ID,\n\t\tbaseUrl: llamaInferenceUrl(serverUrl),\n\t\treasoning: false,\n\t\tinput: model.architecture?.input_modalities?.includes(\"image\") ? [\"text\", \"image\"] : [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow,\n\t\tmaxTokens: contextWindow,\n\t\tcompat: {\n\t\t\tsupportsStore: false,\n\t\t\tsupportsDeveloperRole: false,\n\t\t\tsupportsReasoningEffort: false,\n\t\t\tsupportsUsageInStreaming: true,\n\t\t\tsupportsStrictMode: false,\n\t\t\tmaxTokensField: \"max_tokens\",\n\t\t},\n\t};\n}\n\nexport interface LlamaProviderController {\n\tprovider: Provider<\"openai-completions\">;\n\tsetCatalog(models: readonly LlamaModelInfo[], serverUrl: string): void;\n}\n\nexport function createLlamaProvider(): LlamaProviderController {\n\tlet models: readonly Model<\"openai-completions\">[] = [];\n\n\tconst setCatalog = (catalog: readonly LlamaModelInfo[], serverUrl: string): void => {\n\t\tmodels = catalog.filter((model) => model.status.value === \"loaded\").map((model) => toPiModel(model, serverUrl));\n\t};\n\n\tconst provider: Provider<\"openai-completions\"> = {\n\t\tid: LLAMA_PROVIDER_ID,\n\t\tname: \"llama.cpp\",\n\t\tbaseUrl: llamaInferenceUrl(DEFAULT_LLAMA_SERVER_URL),\n\t\tauth: {\n\t\t\tapiKey: {\n\t\t\t\tname: \"llama.cpp server\",\n\t\t\t\tlogin: async (interaction): Promise => {\n\t\t\t\t\tconst enteredUrl = await interaction.prompt({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tmessage: \"llama.cpp server URL\",\n\t\t\t\t\t\tplaceholder: process.env.LLAMA_BASE_URL ?? DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t});\n\t\t\t\t\tconst serverUrl = normalizeLlamaServerUrl(\n\t\t\t\t\t\tenteredUrl.trim() || process.env.LLAMA_BASE_URL || DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t);\n\t\t\t\t\tconst apiKey = (\n\t\t\t\t\t\tawait interaction.prompt({\n\t\t\t\t\t\t\ttype: \"secret\",\n\t\t\t\t\t\t\tmessage: \"API key (optional)\",\n\t\t\t\t\t\t})\n\t\t\t\t\t).trim();\n\t\t\t\t\tawait new LlamaClient(serverUrl, apiKey || undefined).list({ signal: interaction.signal });\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"api_key\",\n\t\t\t\t\t\tkey: apiKey || undefined,\n\t\t\t\t\t\tenv: { LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tcheck: async ({ ctx, credential }) => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\treturn serverUrl\n\t\t\t\t\t\t? { type: \"api_key\", source: credential ? \"stored credential\" : \"LLAMA_BASE_URL\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t\t},\n\t\t\t\tresolve: async ({ ctx, credential }): Promise => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\tif (!serverUrl) return undefined;\n\t\t\t\t\tconst apiKey = credential?.key ?? (await ctx.env(\"LLAMA_API_KEY\")) ?? \"local\";\n\t\t\t\t\treturn {\n\t\t\t\t\t\tauth: { apiKey, baseUrl: llamaInferenceUrl(serverUrl) },\n\t\t\t\t\t\tenv: { ...credential?.env, LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t\tsource: credential ? \"stored credential\" : \"LLAMA_BASE_URL\",\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tgetModels: () => models,\n\t\trefreshModels: async (context: RefreshModelsContext): Promise => {\n\t\t\tconst stored = await context.store.read();\n\t\t\tif (stored) {\n\t\t\t\tmodels = stored.models.filter(\n\t\t\t\t\t(model): model is Model<\"openai-completions\"> =>\n\t\t\t\t\t\tmodel.provider === LLAMA_PROVIDER_ID && model.api === \"openai-completions\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!context.allowNetwork || context.signal?.aborted || context.credential?.type !== \"api_key\") return;\n\t\t\tconst serverUrl = credentialServerUrl(context.credential);\n\t\t\tif (!serverUrl) return;\n\t\t\tconst catalog = await new LlamaClient(serverUrl, context.credential.key).list({ signal: context.signal });\n\t\t\tsetCatalog(catalog, serverUrl);\n\t\t\tif (!context.signal?.aborted) await context.store.write({ models, checkedAt: Date.now() });\n\t\t},\n\t\tstream: (model, context, options) => stream(model, context, options as ProviderStreamOptions | undefined),\n\t\tstreamSimple: (model, context, options) => streamSimple(model, context, options),\n\t};\n\n\treturn { provider, setCatalog };\n}\n"]} \ No newline at end of file diff --git a/dist/extensions/llama/provider.js b/dist/extensions/llama/provider.js new file mode 100644 index 0000000..7b8cdfe --- /dev/null +++ b/dist/extensions/llama/provider.js @@ -0,0 +1,107 @@ +import { stream, streamSimple } from "@earendil-works/pi-ai/compat"; +import { LlamaClient, llamaInferenceUrl, normalizeLlamaServerUrl } from "./client.js"; +export const LLAMA_PROVIDER_ID = "llama.cpp"; +export const DEFAULT_LLAMA_SERVER_URL = "http://127.0.0.1:8080"; +function credentialServerUrl(credential) { + const value = credential?.env?.LLAMA_BASE_URL; + return typeof value === "string" && value.trim() ? normalizeLlamaServerUrl(value) : undefined; +} +async function resolveServerUrl(ctx, credential) { + const configured = credentialServerUrl(credential) ?? (await ctx.env("LLAMA_BASE_URL"))?.trim(); + return configured ? normalizeLlamaServerUrl(configured) : undefined; +} +function toPiModel(model, serverUrl) { + const reportedContextWindow = model.meta?.n_ctx ?? model.meta?.n_ctx_train; + const contextWindow = reportedContextWindow && reportedContextWindow > 0 ? reportedContextWindow : 128000; + return { + id: model.id, + name: model.id, + api: "openai-completions", + provider: LLAMA_PROVIDER_ID, + baseUrl: llamaInferenceUrl(serverUrl), + reasoning: false, + input: model.architecture?.input_modalities?.includes("image") ? ["text", "image"] : ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow, + maxTokens: contextWindow, + compat: { + supportsStore: false, + supportsDeveloperRole: false, + supportsReasoningEffort: false, + supportsUsageInStreaming: true, + supportsStrictMode: false, + maxTokensField: "max_tokens", + }, + }; +} +export function createLlamaProvider() { + let models = []; + const setCatalog = (catalog, serverUrl) => { + models = catalog.filter((model) => model.status.value === "loaded").map((model) => toPiModel(model, serverUrl)); + }; + const provider = { + id: LLAMA_PROVIDER_ID, + name: "llama.cpp", + baseUrl: llamaInferenceUrl(DEFAULT_LLAMA_SERVER_URL), + auth: { + apiKey: { + name: "llama.cpp server", + login: async (interaction) => { + const enteredUrl = await interaction.prompt({ + type: "text", + message: "llama.cpp server URL", + placeholder: process.env.LLAMA_BASE_URL ?? DEFAULT_LLAMA_SERVER_URL, + }); + const serverUrl = normalizeLlamaServerUrl(enteredUrl.trim() || process.env.LLAMA_BASE_URL || DEFAULT_LLAMA_SERVER_URL); + const apiKey = (await interaction.prompt({ + type: "secret", + message: "API key (optional)", + })).trim(); + await new LlamaClient(serverUrl, apiKey || undefined).list({ signal: interaction.signal }); + return { + type: "api_key", + key: apiKey || undefined, + env: { LLAMA_BASE_URL: serverUrl }, + }; + }, + check: async ({ ctx, credential }) => { + const serverUrl = await resolveServerUrl(ctx, credential); + return serverUrl + ? { type: "api_key", source: credential ? "stored credential" : "LLAMA_BASE_URL" } + : undefined; + }, + resolve: async ({ ctx, credential }) => { + const serverUrl = await resolveServerUrl(ctx, credential); + if (!serverUrl) + return undefined; + const apiKey = credential?.key ?? (await ctx.env("LLAMA_API_KEY")) ?? "local"; + return { + auth: { apiKey, baseUrl: llamaInferenceUrl(serverUrl) }, + env: { ...credential?.env, LLAMA_BASE_URL: serverUrl }, + source: credential ? "stored credential" : "LLAMA_BASE_URL", + }; + }, + }, + }, + getModels: () => models, + refreshModels: async (context) => { + const stored = await context.store.read(); + if (stored) { + models = stored.models.filter((model) => model.provider === LLAMA_PROVIDER_ID && model.api === "openai-completions"); + } + if (!context.allowNetwork || context.signal?.aborted || context.credential?.type !== "api_key") + return; + const serverUrl = credentialServerUrl(context.credential); + if (!serverUrl) + return; + const catalog = await new LlamaClient(serverUrl, context.credential.key).list({ signal: context.signal }); + setCatalog(catalog, serverUrl); + if (!context.signal?.aborted) + await context.store.write({ models, checkedAt: Date.now() }); + }, + stream: (model, context, options) => stream(model, context, options), + streamSimple: (model, context, options) => streamSimple(model, context, options), + }; + return { provider, setCatalog }; +} +//# sourceMappingURL=provider.js.map \ No newline at end of file diff --git a/dist/extensions/llama/provider.js.map b/dist/extensions/llama/provider.js.map new file mode 100644 index 0000000..ad236d2 --- /dev/null +++ b/dist/extensions/llama/provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/extensions/llama/provider.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,WAAW,EAAuB,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,aAAa,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AC,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;QAAA,CAC3F;QACD,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAA4C,CAAC;QACzG,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC;KAChF,CAAC;IAEF,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;AAAA,CAChC","sourcesContent":["import type {\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tModel,\n\tProvider,\n\tProviderStreamOptions,\n\tRefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { stream, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport { LlamaClient, type LlamaModelInfo, llamaInferenceUrl, normalizeLlamaServerUrl } from \"./client.ts\";\n\nexport const LLAMA_PROVIDER_ID = \"llama.cpp\";\nexport const DEFAULT_LLAMA_SERVER_URL = \"http://127.0.0.1:8080\";\nfunction credentialServerUrl(credential: ApiKeyCredential | undefined): string | undefined {\n\tconst value = credential?.env?.LLAMA_BASE_URL;\n\treturn typeof value === \"string\" && value.trim() ? normalizeLlamaServerUrl(value) : undefined;\n}\n\nasync function resolveServerUrl(\n\tctx: AuthContext,\n\tcredential: ApiKeyCredential | undefined,\n): Promise {\n\tconst configured = credentialServerUrl(credential) ?? (await ctx.env(\"LLAMA_BASE_URL\"))?.trim();\n\treturn configured ? normalizeLlamaServerUrl(configured) : undefined;\n}\n\nfunction toPiModel(model: LlamaModelInfo, serverUrl: string): Model<\"openai-completions\"> {\n\tconst reportedContextWindow = model.meta?.n_ctx ?? model.meta?.n_ctx_train;\n\tconst contextWindow = reportedContextWindow && reportedContextWindow > 0 ? reportedContextWindow : 128000;\n\treturn {\n\t\tid: model.id,\n\t\tname: model.id,\n\t\tapi: \"openai-completions\",\n\t\tprovider: LLAMA_PROVIDER_ID,\n\t\tbaseUrl: llamaInferenceUrl(serverUrl),\n\t\treasoning: false,\n\t\tinput: model.architecture?.input_modalities?.includes(\"image\") ? [\"text\", \"image\"] : [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow,\n\t\tmaxTokens: contextWindow,\n\t\tcompat: {\n\t\t\tsupportsStore: false,\n\t\t\tsupportsDeveloperRole: false,\n\t\t\tsupportsReasoningEffort: false,\n\t\t\tsupportsUsageInStreaming: true,\n\t\t\tsupportsStrictMode: false,\n\t\t\tmaxTokensField: \"max_tokens\",\n\t\t},\n\t};\n}\n\nexport interface LlamaProviderController {\n\tprovider: Provider<\"openai-completions\">;\n\tsetCatalog(models: readonly LlamaModelInfo[], serverUrl: string): void;\n}\n\nexport function createLlamaProvider(): LlamaProviderController {\n\tlet models: readonly Model<\"openai-completions\">[] = [];\n\n\tconst setCatalog = (catalog: readonly LlamaModelInfo[], serverUrl: string): void => {\n\t\tmodels = catalog.filter((model) => model.status.value === \"loaded\").map((model) => toPiModel(model, serverUrl));\n\t};\n\n\tconst provider: Provider<\"openai-completions\"> = {\n\t\tid: LLAMA_PROVIDER_ID,\n\t\tname: \"llama.cpp\",\n\t\tbaseUrl: llamaInferenceUrl(DEFAULT_LLAMA_SERVER_URL),\n\t\tauth: {\n\t\t\tapiKey: {\n\t\t\t\tname: \"llama.cpp server\",\n\t\t\t\tlogin: async (interaction): Promise => {\n\t\t\t\t\tconst enteredUrl = await interaction.prompt({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tmessage: \"llama.cpp server URL\",\n\t\t\t\t\t\tplaceholder: process.env.LLAMA_BASE_URL ?? DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t});\n\t\t\t\t\tconst serverUrl = normalizeLlamaServerUrl(\n\t\t\t\t\t\tenteredUrl.trim() || process.env.LLAMA_BASE_URL || DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t);\n\t\t\t\t\tconst apiKey = (\n\t\t\t\t\t\tawait interaction.prompt({\n\t\t\t\t\t\t\ttype: \"secret\",\n\t\t\t\t\t\t\tmessage: \"API key (optional)\",\n\t\t\t\t\t\t})\n\t\t\t\t\t).trim();\n\t\t\t\t\tawait new LlamaClient(serverUrl, apiKey || undefined).list({ signal: interaction.signal });\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"api_key\",\n\t\t\t\t\t\tkey: apiKey || undefined,\n\t\t\t\t\t\tenv: { LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tcheck: async ({ ctx, credential }) => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\treturn serverUrl\n\t\t\t\t\t\t? { type: \"api_key\", source: credential ? \"stored credential\" : \"LLAMA_BASE_URL\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t\t},\n\t\t\t\tresolve: async ({ ctx, credential }): Promise => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\tif (!serverUrl) return undefined;\n\t\t\t\t\tconst apiKey = credential?.key ?? (await ctx.env(\"LLAMA_API_KEY\")) ?? \"local\";\n\t\t\t\t\treturn {\n\t\t\t\t\t\tauth: { apiKey, baseUrl: llamaInferenceUrl(serverUrl) },\n\t\t\t\t\t\tenv: { ...credential?.env, LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t\tsource: credential ? \"stored credential\" : \"LLAMA_BASE_URL\",\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tgetModels: () => models,\n\t\trefreshModels: async (context: RefreshModelsContext): Promise => {\n\t\t\tconst stored = await context.store.read();\n\t\t\tif (stored) {\n\t\t\t\tmodels = stored.models.filter(\n\t\t\t\t\t(model): model is Model<\"openai-completions\"> =>\n\t\t\t\t\t\tmodel.provider === LLAMA_PROVIDER_ID && model.api === \"openai-completions\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!context.allowNetwork || context.signal?.aborted || context.credential?.type !== \"api_key\") return;\n\t\t\tconst serverUrl = credentialServerUrl(context.credential);\n\t\t\tif (!serverUrl) return;\n\t\t\tconst catalog = await new LlamaClient(serverUrl, context.credential.key).list({ signal: context.signal });\n\t\t\tsetCatalog(catalog, serverUrl);\n\t\t\tif (!context.signal?.aborted) await context.store.write({ models, checkedAt: Date.now() });\n\t\t},\n\t\tstream: (model, context, options) => stream(model, context, options as ProviderStreamOptions | undefined),\n\t\tstreamSimple: (model, context, options) => streamSimple(model, context, options),\n\t};\n\n\treturn { provider, setCatalog };\n}\n"]} \ No newline at end of file diff --git a/dist/extensions/llama/ui.d.ts b/dist/extensions/llama/ui.d.ts new file mode 100644 index 0000000..0b95cad --- /dev/null +++ b/dist/extensions/llama/ui.d.ts @@ -0,0 +1,42 @@ +import type { ExtensionCommandContext } from "../../core/extensions/types.ts"; +import type { LlamaModelInfo, LlamaProgress } from "./client.ts"; +import type { HuggingFaceModel } from "./huggingface.ts"; +export type LlamaManagerAction = { + type: "model"; + model: LlamaModelInfo; +} | { + type: "download"; +} | { + type: "close"; +}; +interface ProgressState extends LlamaProgress { + title: string; + model: string; +} +export interface LlamaUi { + showModels(serverUrl: string, models: LlamaModelInfo[]): Promise; + select(title: string, options: string[]): Promise; + confirm(title: string, message: string): Promise; + connectionError(serverUrl: string, message: string): Promise<"retry" | "close">; + searchModels(search: (query: string, signal: AbortSignal) => Promise): Promise; + showStatus(title: string, message: string): void; + progress(state: ProgressState): Promise; + updateProgress(state: ProgressState): void; +} +export declare function showLlamaUi(ctx: ExtensionCommandContext, run: (ui: LlamaUi) => Promise): Promise; +export declare function runWithProgress(ui: LlamaUi, options: { + title: string; + model: string; + initialMessage: string; + cancelTitle: string; + cancelMessage: string; + run(signal: AbortSignal, update: (progress: LlamaProgress) => void): Promise; + cancel(): Promise; +}): Promise<{ + cancelled: true; +} | { + cancelled: false; + value: T; +}>; +export {}; +//# sourceMappingURL=ui.d.ts.map \ No newline at end of file diff --git a/dist/extensions/llama/ui.d.ts.map b/dist/extensions/llama/ui.d.ts.map new file mode 100644 index 0000000..ceccfcc --- /dev/null +++ b/dist/extensions/llama/ui.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ui.d.ts","sourceRoot":"","sources":["../../../src/extensions/llama/ui.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAK9E,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAIzD,MAAM,MAAM,kBAAkB,GAAG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,cAAc,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC;AAErH,UAAU,aAAc,SAAQ,aAAa;IAC5C,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACd;AA+CD,MAAM,WAAW,OAAO;IACvB,UAAU,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACrF,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACtE,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1D,eAAe,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,CAAC;IAChF,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"@earendil-works/pi-tui\";\nimport type { ExtensionCommandContext } from \"../../core/extensions/types.ts\";\nimport type { KeybindingsManager } from \"../../core/keybindings.ts\";\nimport { DynamicBorder } from \"../../modes/interactive/components/dynamic-border.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { LlamaModelInfo, LlamaProgress } from \"./client.ts\";\nimport type { HuggingFaceModel } from \"./huggingface.ts\";\n\nconst DOWNLOAD_VALUE = \"\\0download\";\n\nexport type LlamaManagerAction = { type: \"model\"; model: LlamaModelInfo } | { type: \"download\" } | { type: \"close\" };\n\ninterface ProgressState extends LlamaProgress {\n\ttitle: string;\n\tmodel: string;\n}\n\nfunction contextLabel(model: LlamaModelInfo): string | undefined {\n\tconst context = model.meta?.n_ctx ?? model.meta?.n_ctx_train;\n\tif (context) return context >= 1000 ? `${Math.round(context / 1000)}k` : String(context);\n\tconst args = model.status.args ?? [];\n\tfor (let index = 0; index < args.length - 1; index++) {\n\t\tif (args[index] !== \"--ctx-size\" && args[index] !== \"-c\" && args[index] !== \"-ctx\") continue;\n\t\tconst value = Number(args[index + 1]);\n\t\tif (Number.isFinite(value) && value > 0) return value >= 1000 ? `${Math.round(value / 1000)}k` : String(value);\n\t}\n\treturn undefined;\n}\n\nfunction modelDescription(model: LlamaModelInfo): string {\n\tconst details: string[] = [];\n\tconst loaded = model.status.value === \"loaded\" || model.status.value === \"sleeping\";\n\tif (loaded) details.push(\"loaded\");\n\telse if (model.status.value !== \"unloaded\") details.push(model.status.value);\n\tconst context = loaded ? contextLabel(model) : undefined;\n\tif (context) details.push(`${context} context`);\n\treturn details.join(\" · \");\n}\n\nfunction selectTheme(theme: Theme) {\n\treturn {\n\t\tselectedPrefix: (text: string) => theme.fg(\"accent\", text),\n\t\tselectedText: (text: string) => theme.fg(\"accent\", text),\n\t\tdescription: (text: string) => theme.fg(\"muted\", text),\n\t\tscrollInfo: (text: string) => theme.fg(\"dim\", text),\n\t\tnoMatch: (text: string) => theme.fg(\"warning\", text),\n\t};\n}\n\nfunction frame(theme: Theme, title: string, body: Component[], footer?: string): Container {\n\tconst container = new Container();\n\tcontainer.addChild(new DynamicBorder((text: string) => theme.fg(\"accent\", text)));\n\tcontainer.addChild(new Text(theme.fg(\"accent\", theme.bold(title)), 1, 0));\n\tfor (const child of body) container.addChild(child);\n\tif (footer) {\n\t\tcontainer.addChild(new Spacer(1));\n\t\tcontainer.addChild(new Text(theme.fg(\"dim\", footer), 1, 0));\n\t}\n\tcontainer.addChild(new DynamicBorder((text: string) => theme.fg(\"accent\", text)));\n\treturn container;\n}\n\nexport interface LlamaUi {\n\tshowModels(serverUrl: string, models: LlamaModelInfo[]): Promise;\n\tselect(title: string, options: string[]): Promise;\n\tconfirm(title: string, message: string): Promise;\n\tconnectionError(serverUrl: string, message: string): Promise<\"retry\" | \"close\">;\n\tsearchModels(\n\t\tsearch: (query: string, signal: AbortSignal) => Promise,\n\t): Promise;\n\tshowStatus(title: string, message: string): void;\n\tprogress(state: ProgressState): Promise;\n\tupdateProgress(state: ProgressState): void;\n}\n\nfunction compactCount(value: number): string {\n\tif (value >= 1_000_000) return `${(value / 1_000_000).toFixed(value >= 10_000_000 ? 0 : 1)}M`;\n\tif (value >= 1_000) return `${(value / 1_000).toFixed(value >= 100_000 ? 0 : 1)}k`;\n\treturn String(value);\n}\n\nclass HuggingFaceSearch extends Container implements Focusable {\n\tprivate readonly tui: TUI;\n\tprivate readonly theme: Theme;\n\tprivate readonly keybindings: KeybindingsManager;\n\tprivate readonly search: (query: string, signal: AbortSignal) => Promise;\n\tprivate readonly cache: Map;\n\tprivate readonly onSelectModel: (model: string | undefined) => void;\n\tprivate readonly input = new Input();\n\tprivate readonly resultsContainer = new Container();\n\tprivate results: HuggingFaceModel[] = [];\n\tprivate filteredResults: HuggingFaceModel[] = [];\n\tprivate selectedIndex = 0;\n\tprivate query = \"\";\n\tprivate status = \"Type at least 2 characters\";\n\tprivate debounce: ReturnType | undefined;\n\tprivate request: AbortController | undefined;\n\tprivate closed = false;\n\tprivate _focused = false;\n\n\tconstructor(\n\t\ttui: TUI,\n\t\ttheme: Theme,\n\t\tkeybindings: KeybindingsManager,\n\t\tsearch: (query: string, signal: AbortSignal) => Promise,\n\t\tcache: Map,\n\t\tonSelectModel: (model: string | undefined) => void,\n\t) {\n\t\tsuper();\n\t\tthis.tui = tui;\n\t\tthis.theme = theme;\n\t\tthis.keybindings = keybindings;\n\t\tthis.search = search;\n\t\tthis.cache = cache;\n\t\tthis.onSelectModel = onSelectModel;\n\t\tthis.addChild(new Text(theme.fg(\"dim\", \"Model name or owner/repository[:quant]\"), 1, 0));\n\t\tthis.addChild(this.input);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(this.resultsContainer);\n\t\tthis.updateResults();\n\t}\n\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.input.focused = value;\n\t}\n\n\tprivate updateResults(): void {\n\t\tthis.resultsContainer.clear();\n\t\tconst maxVisible = 10;\n\t\tconst start = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(maxVisible / 2), this.filteredResults.length - maxVisible),\n\t\t);\n\t\tconst end = Math.min(start + maxVisible, this.filteredResults.length);\n\t\tfor (let index = start; index < end; index++) {\n\t\t\tconst model = this.filteredResults[index];\n\t\t\tif (!model) continue;\n\t\t\tconst prefix = index === this.selectedIndex ? \"→ \" : \" \";\n\t\t\tconst details = `${compactCount(model.downloads)} downloads`;\n\t\t\tthis.resultsContainer.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\tindex === this.selectedIndex\n\t\t\t\t\t\t? this.theme.fg(\"accent\", `${prefix}${model.id} ${details}`)\n\t\t\t\t\t\t: `${prefix}${model.id}${this.theme.fg(\"muted\", ` ${details}`)}`,\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (start > 0 || end < this.filteredResults.length) {\n\t\t\tthis.resultsContainer.addChild(\n\t\t\t\tnew Text(this.theme.fg(\"dim\", ` (${this.selectedIndex + 1}/${this.filteredResults.length})`), 0, 0),\n\t\t\t);\n\t\t}\n\t\tif (this.filteredResults.length === 0) {\n\t\t\tthis.resultsContainer.addChild(new Text(this.theme.fg(\"dim\", ` ${this.status}`), 0, 0));\n\t\t} else if (this.status === \"Searching Hugging Face…\") {\n\t\t\tthis.resultsContainer.addChild(new Text(this.theme.fg(\"dim\", ` ${this.status}`), 0, 0));\n\t\t}\n\t\tthis.tui.requestRender();\n\t}\n\n\tprivate filterResults(): void {\n\t\tif (this.query) {\n\t\t\tconst matches = new Set(fuzzyFilter(this.results, this.query, (model) => model.id).map((model) => model.id));\n\t\t\tthis.filteredResults = this.results.filter((model) => matches.has(model.id));\n\t\t} else {\n\t\t\tthis.filteredResults = this.results;\n\t\t}\n\t\tthis.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredResults.length - 1));\n\t\tthis.updateResults();\n\t}\n\n\tprivate scheduleSearch(): void {\n\t\tif (this.debounce) clearTimeout(this.debounce);\n\t\tthis.request?.abort();\n\t\tthis.request = undefined;\n\t\tif (this.query.length < 2) {\n\t\t\tthis.status = \"Type at least 2 characters\";\n\t\t\tthis.filterResults();\n\t\t\treturn;\n\t\t}\n\t\tconst cached = this.cache.get(this.query.toLowerCase());\n\t\tif (cached) {\n\t\t\tthis.results = cached;\n\t\t\tthis.status = cached.length === 0 ? \"No GGUF models found\" : \"\";\n\t\t\tthis.filterResults();\n\t\t\treturn;\n\t\t}\n\t\tthis.status = \"Searching Hugging Face…\";\n\t\tthis.filterResults();\n\t\tthis.debounce = setTimeout(() => void this.runSearch(this.query), 500);\n\t}\n\n\tprivate async runSearch(query: string): Promise {\n\t\tconst request = new AbortController();\n\t\tthis.request = request;\n\t\ttry {\n\t\t\tconst results = await this.search(query, request.signal);\n\t\t\tthis.cache.set(query.toLowerCase(), results);\n\t\t\tif (this.closed || request.signal.aborted || this.query !== query) return;\n\t\t\tthis.results = results;\n\t\t\tthis.selectedIndex = 0;\n\t\t\tthis.status = results.length === 0 ? \"No GGUF models found\" : \"\";\n\t\t\tthis.filterResults();\n\t\t} catch (error) {\n\t\t\tif (this.closed || request.signal.aborted || this.query !== query) return;\n\t\t\tthis.results = [];\n\t\t\tthis.status = error instanceof Error ? error.message : String(error);\n\t\t\tthis.filterResults();\n\t\t} finally {\n\t\t\tif (this.request === request) this.request = undefined;\n\t\t}\n\t}\n\n\tprivate close(model: string | undefined): void {\n\t\tif (this.closed) return;\n\t\tthis.closed = true;\n\t\tif (this.debounce) clearTimeout(this.debounce);\n\t\tthis.request?.abort();\n\t\tthis.onSelectModel(model);\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (this.keybindings.matches(data, \"tui.select.up\")) {\n\t\t\tif (this.filteredResults.length > 0) {\n\t\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.filteredResults.length - 1 : this.selectedIndex - 1;\n\t\t\t\tthis.updateResults();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.down\")) {\n\t\t\tif (this.filteredResults.length > 0) {\n\t\t\t\tthis.selectedIndex = this.selectedIndex === this.filteredResults.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t\t\tthis.updateResults();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.confirm\")) {\n\t\t\tconst exact = /^[^/\\s]+\\/[^:\\s]+(?::[^\\s:]+)?$/u.test(this.query) ? this.query : undefined;\n\t\t\tconst selected = exact ?? this.filteredResults[this.selectedIndex]?.id;\n\t\t\tif (selected) this.close(selected);\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.cancel\")) {\n\t\t\tthis.close(undefined);\n\t\t\treturn;\n\t\t}\n\t\tthis.input.handleInput(data);\n\t\tconst query = this.input.getValue().trim();\n\t\tif (query === this.query) return;\n\t\tthis.query = query;\n\t\tthis.scheduleSearch();\n\t}\n}\n\nclass LlamaView implements LlamaUi, Focusable {\n\tprivate readonly tui: TUI;\n\tprivate readonly theme: Theme;\n\tprivate readonly keybindings: KeybindingsManager;\n\tprivate readonly searchCache = new Map();\n\tprivate content: Container;\n\tprivate inputHandler: { handleInput?(data: string): void } | undefined;\n\tprivate inputTarget: Focusable | undefined;\n\tprivate progressPromise: Promise | undefined;\n\tprivate progressResolver: (() => void) | undefined;\n\tprivate showingProgress = false;\n\tprivate _focused = false;\n\n\tconstructor(tui: TUI, theme: Theme, keybindings: KeybindingsManager) {\n\t\tthis.tui = tui;\n\t\tthis.theme = theme;\n\t\tthis.keybindings = keybindings;\n\t\tthis.content = frame(theme, \"llama.cpp models\", [new Text(theme.fg(\"muted\", \"Loading…\"), 1, 1)]);\n\t}\n\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tif (this.inputTarget) this.inputTarget.focused = value;\n\t}\n\n\tprivate setContent(\n\t\tcontent: Container,\n\t\tinputHandler?: { handleInput?(data: string): void },\n\t\tinputTarget?: Focusable,\n\t): void {\n\t\tif (this.inputTarget) this.inputTarget.focused = false;\n\t\tthis.progressPromise = undefined;\n\t\tthis.progressResolver = undefined;\n\t\tthis.showingProgress = false;\n\t\tthis.content = content;\n\t\tthis.inputHandler = inputHandler;\n\t\tthis.inputTarget = inputTarget;\n\t\tif (this.inputTarget) this.inputTarget.focused = this._focused;\n\t\tthis.tui.requestRender();\n\t}\n\n\tshowModels(serverUrl: string, models: LlamaModelInfo[]): Promise {\n\t\tconst sorted = [...models].sort((left, right) => {\n\t\t\tconst loaded = Number(right.status.value === \"loaded\") - Number(left.status.value === \"loaded\");\n\t\t\treturn loaded || left.id.localeCompare(right.id);\n\t\t});\n\t\tconst byId = new Map(sorted.map((model) => [model.id, model]));\n\t\tconst items: SelectItem[] = [\n\t\t\t...sorted.map((model) => ({\n\t\t\t\tvalue: model.id,\n\t\t\t\tlabel: model.id,\n\t\t\t\tdescription: modelDescription(model),\n\t\t\t})),\n\t\t\t{ value: DOWNLOAD_VALUE, label: \"Download model…\", description: \"Hugging Face owner/repository[:quant]\" },\n\t\t];\n\t\treturn new Promise((resolve) => {\n\t\t\tconst list = new SelectList(items, Math.min(items.length, 12), selectTheme(this.theme), {\n\t\t\t\tminPrimaryColumnWidth: 36,\n\t\t\t\tmaxPrimaryColumnWidth: 56,\n\t\t\t});\n\t\t\tlist.onSelect = (item) => {\n\t\t\t\tif (item.value === DOWNLOAD_VALUE) resolve({ type: \"download\" });\n\t\t\t\telse {\n\t\t\t\t\tconst model = byId.get(item.value);\n\t\t\t\t\tif (model) resolve({ type: \"model\", model });\n\t\t\t\t}\n\t\t\t};\n\t\t\tlist.onCancel = () => resolve({ type: \"close\" });\n\t\t\tthis.setContent(\n\t\t\t\tframe(\n\t\t\t\t\tthis.theme,\n\t\t\t\t\t\"llama.cpp models\",\n\t\t\t\t\t[new Text(this.theme.fg(\"dim\", serverUrl), 1, 0), new Spacer(1), list],\n\t\t\t\t\t`${keyHint(\"tui.select.confirm\", \"load/unload/download\")} • ${keyHint(\"tui.select.cancel\", \"close\")}`,\n\t\t\t\t),\n\t\t\t\tlist,\n\t\t\t);\n\t\t});\n\t}\n\n\tselect(title: string, options: string[]): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst list = new SelectList(\n\t\t\t\toptions.map((option) => ({ value: option, label: option })),\n\t\t\t\tMath.min(options.length, 12),\n\t\t\t\tselectTheme(this.theme),\n\t\t\t);\n\t\t\tlist.onSelect = (item) => resolve(item.value);\n\t\t\tlist.onCancel = () => resolve(undefined);\n\t\t\tthis.setContent(\n\t\t\t\tframe(\n\t\t\t\t\tthis.theme,\n\t\t\t\t\ttitle,\n\t\t\t\t\t[new Spacer(1), list],\n\t\t\t\t\t`${keyHint(\"tui.select.confirm\", \"select\")} • ${keyHint(\"tui.select.cancel\", \"cancel\")}`,\n\t\t\t\t),\n\t\t\t\tlist,\n\t\t\t);\n\t\t});\n\t}\n\n\tasync confirm(title: string, message: string): Promise {\n\t\treturn (await this.select(`${title}\\n${message}`, [\"Yes\", \"No\"])) === \"Yes\";\n\t}\n\n\tasync connectionError(serverUrl: string, message: string): Promise<\"retry\" | \"close\"> {\n\t\tconst choice = await this.select(`llama.cpp unavailable\\n${serverUrl}\\n\\n${message}`, [\"Retry\", \"Close\"]);\n\t\treturn choice === \"Retry\" ? \"retry\" : \"close\";\n\t}\n\n\tsearchModels(\n\t\tsearch: (query: string, signal: AbortSignal) => Promise,\n\t): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst component = new HuggingFaceSearch(\n\t\t\t\tthis.tui,\n\t\t\t\tthis.theme,\n\t\t\t\tthis.keybindings,\n\t\t\t\tsearch,\n\t\t\t\tthis.searchCache,\n\t\t\t\tresolve,\n\t\t\t);\n\t\t\tthis.setContent(\n\t\t\t\tframe(\n\t\t\t\t\tthis.theme,\n\t\t\t\t\t\"Download model\",\n\t\t\t\t\t[new Spacer(1), component],\n\t\t\t\t\t`${keyHint(\"tui.select.confirm\", \"select\")} • ${keyHint(\"tui.select.cancel\", \"back\")}`,\n\t\t\t\t),\n\t\t\t\tcomponent,\n\t\t\t\tcomponent,\n\t\t\t);\n\t\t});\n\t}\n\n\tshowStatus(title: string, message: string): void {\n\t\tthis.setContent(frame(this.theme, title, [new Spacer(1), new Text(this.theme.fg(\"muted\", message), 1, 0)]));\n\t}\n\n\tprogress(state: ProgressState): Promise {\n\t\tif (!this.progressPromise) {\n\t\t\tthis.progressPromise = new Promise((resolve) => {\n\t\t\t\tthis.progressResolver = resolve;\n\t\t\t});\n\t\t}\n\t\tthis.showingProgress = true;\n\t\tthis.updateProgress(state);\n\t\treturn this.progressPromise;\n\t}\n\n\tupdateProgress(state: ProgressState): void {\n\t\tif (!this.showingProgress) return;\n\t\tconst body = [\n\t\t\tnew Text(this.theme.fg(\"text\", state.model), 1, 0),\n\t\t\tnew Spacer(1),\n\t\t\tnew Text(this.theme.fg(\"muted\", state.message), 1, 0),\n\t\t];\n\t\tif (state.ratio !== undefined) {\n\t\t\tconst available = 40;\n\t\t\tconst filled = Math.round(Math.max(0, Math.min(1, state.ratio)) * available);\n\t\t\tbody.push(\n\t\t\t\tnew Text(\n\t\t\t\t\tthis.theme.fg(\n\t\t\t\t\t\t\"accent\",\n\t\t\t\t\t\t`${\"█\".repeat(filled)}${\"─\".repeat(available - filled)} ${Math.round(state.ratio * 100)}%`,\n\t\t\t\t\t),\n\t\t\t\t\t1,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (state.detail) body.push(new Text(this.theme.fg(\"dim\", state.detail), 1, 0));\n\t\tthis.content = frame(this.theme, state.title, body, keyHint(\"tui.select.cancel\", \"stop\"));\n\t\tthis.inputHandler = undefined;\n\t\tthis.tui.requestRender();\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (this.progressResolver && this.keybindings.matches(data, \"tui.select.cancel\")) {\n\t\t\tconst resolve = this.progressResolver;\n\t\t\tthis.progressPromise = undefined;\n\t\t\tthis.progressResolver = undefined;\n\t\t\tresolve();\n\t\t\treturn;\n\t\t}\n\t\tthis.inputHandler?.handleInput?.(data);\n\t\tthis.tui.requestRender();\n\t}\n\n\trender(width: number): string[] {\n\t\treturn this.content\n\t\t\t.render(width)\n\t\t\t.map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width, \"\") : line));\n\t}\n\n\tinvalidate(): void {\n\t\tthis.content.invalidate();\n\t}\n}\n\nexport async function showLlamaUi(ctx: ExtensionCommandContext, run: (ui: LlamaUi) => Promise): Promise {\n\tawait ctx.ui.custom((tui, theme, keybindings, done) => {\n\t\tconst view = new LlamaView(tui, theme, keybindings);\n\t\tvoid run(view).then(\n\t\t\t() => done(),\n\t\t\t(error: unknown) => {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t\tdone();\n\t\t\t},\n\t\t);\n\t\treturn view;\n\t});\n}\n\nexport async function runWithProgress(\n\tui: LlamaUi,\n\toptions: {\n\t\ttitle: string;\n\t\tmodel: string;\n\t\tinitialMessage: string;\n\t\tcancelTitle: string;\n\t\tcancelMessage: string;\n\t\trun(signal: AbortSignal, update: (progress: LlamaProgress) => void): Promise;\n\t\tcancel(): Promise;\n\t},\n): Promise<{ cancelled: true } | { cancelled: false; value: T }> {\n\tconst controller = new AbortController();\n\tconst state: ProgressState = { title: options.title, model: options.model, message: options.initialMessage };\n\tconst settled = options\n\t\t.run(controller.signal, (progress) => {\n\t\t\tObject.assign(state, progress);\n\t\t\tui.updateProgress(state);\n\t\t})\n\t\t.then(\n\t\t\t(value) => ({ ok: true as const, value }),\n\t\t\t(error: unknown) => ({ ok: false as const, error }),\n\t\t);\n\tlet completed = false;\n\tsettled.finally(() => {\n\t\tcompleted = true;\n\t});\n\n\twhile (!completed) {\n\t\tconst outcome = await Promise.race([\n\t\t\tsettled.then(() => \"settled\" as const),\n\t\t\tui.progress(state).then(() => \"stop\" as const),\n\t\t]);\n\t\tif (outcome === \"settled\") break;\n\t\tconst stop = await ui.confirm(options.cancelTitle, options.cancelMessage);\n\t\tif (!stop || completed) continue;\n\t\ttry {\n\t\t\tawait options.cancel();\n\t\t} finally {\n\t\t\tcontroller.abort(new Error(\"Cancelled\"));\n\t\t}\n\t\tawait settled;\n\t\treturn { cancelled: true };\n\t}\n\n\tconst result = await settled;\n\tif (!result.ok) throw result.error;\n\treturn { cancelled: false, value: result.value };\n}\n"]} \ No newline at end of file diff --git a/dist/extensions/llama/ui.js b/dist/extensions/llama/ui.js new file mode 100644 index 0000000..4e748af --- /dev/null +++ b/dist/extensions/llama/ui.js @@ -0,0 +1,416 @@ +import { Container, fuzzyFilter, Input, SelectList, Spacer, Text, truncateToWidth, visibleWidth, } from "@earendil-works/pi-tui"; +import { DynamicBorder } from "../../modes/interactive/components/dynamic-border.js"; +import { keyHint } from "../../modes/interactive/components/keybinding-hints.js"; +const DOWNLOAD_VALUE = "\0download"; +function contextLabel(model) { + const context = model.meta?.n_ctx ?? model.meta?.n_ctx_train; + if (context) + return context >= 1000 ? `${Math.round(context / 1000)}k` : String(context); + const args = model.status.args ?? []; + for (let index = 0; index < args.length - 1; index++) { + if (args[index] !== "--ctx-size" && args[index] !== "-c" && args[index] !== "-ctx") + continue; + const value = Number(args[index + 1]); + if (Number.isFinite(value) && value > 0) + return value >= 1000 ? `${Math.round(value / 1000)}k` : String(value); + } + return undefined; +} +function modelDescription(model) { + const details = []; + const loaded = model.status.value === "loaded" || model.status.value === "sleeping"; + if (loaded) + details.push("loaded"); + else if (model.status.value !== "unloaded") + details.push(model.status.value); + const context = loaded ? contextLabel(model) : undefined; + if (context) + details.push(`${context} context`); + return details.join(" · "); +} +function selectTheme(theme) { + return { + selectedPrefix: (text) => theme.fg("accent", text), + selectedText: (text) => theme.fg("accent", text), + description: (text) => theme.fg("muted", text), + scrollInfo: (text) => theme.fg("dim", text), + noMatch: (text) => theme.fg("warning", text), + }; +} +function frame(theme, title, body, footer) { + const container = new Container(); + container.addChild(new DynamicBorder((text) => theme.fg("accent", text))); + container.addChild(new Text(theme.fg("accent", theme.bold(title)), 1, 0)); + for (const child of body) + container.addChild(child); + if (footer) { + container.addChild(new Spacer(1)); + container.addChild(new Text(theme.fg("dim", footer), 1, 0)); + } + container.addChild(new DynamicBorder((text) => theme.fg("accent", text))); + return container; +} +function compactCount(value) { + if (value >= 1_000_000) + return `${(value / 1_000_000).toFixed(value >= 10_000_000 ? 0 : 1)}M`; + if (value >= 1_000) + return `${(value / 1_000).toFixed(value >= 100_000 ? 0 : 1)}k`; + return String(value); +} +class HuggingFaceSearch extends Container { + tui; + theme; + keybindings; + search; + cache; + onSelectModel; + input = new Input(); + resultsContainer = new Container(); + results = []; + filteredResults = []; + selectedIndex = 0; + query = ""; + status = "Type at least 2 characters"; + debounce; + request; + closed = false; + _focused = false; + constructor(tui, theme, keybindings, search, cache, onSelectModel) { + super(); + this.tui = tui; + this.theme = theme; + this.keybindings = keybindings; + this.search = search; + this.cache = cache; + this.onSelectModel = onSelectModel; + this.addChild(new Text(theme.fg("dim", "Model name or owner/repository[:quant]"), 1, 0)); + this.addChild(this.input); + this.addChild(new Spacer(1)); + this.addChild(this.resultsContainer); + this.updateResults(); + } + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + this.input.focused = value; + } + updateResults() { + this.resultsContainer.clear(); + const maxVisible = 10; + const start = Math.max(0, Math.min(this.selectedIndex - Math.floor(maxVisible / 2), this.filteredResults.length - maxVisible)); + const end = Math.min(start + maxVisible, this.filteredResults.length); + for (let index = start; index < end; index++) { + const model = this.filteredResults[index]; + if (!model) + continue; + const prefix = index === this.selectedIndex ? "→ " : " "; + const details = `${compactCount(model.downloads)} downloads`; + this.resultsContainer.addChild(new Text(index === this.selectedIndex + ? this.theme.fg("accent", `${prefix}${model.id} ${details}`) + : `${prefix}${model.id}${this.theme.fg("muted", ` ${details}`)}`, 0, 0)); + } + if (start > 0 || end < this.filteredResults.length) { + this.resultsContainer.addChild(new Text(this.theme.fg("dim", ` (${this.selectedIndex + 1}/${this.filteredResults.length})`), 0, 0)); + } + if (this.filteredResults.length === 0) { + this.resultsContainer.addChild(new Text(this.theme.fg("dim", ` ${this.status}`), 0, 0)); + } + else if (this.status === "Searching Hugging Face…") { + this.resultsContainer.addChild(new Text(this.theme.fg("dim", ` ${this.status}`), 0, 0)); + } + this.tui.requestRender(); + } + filterResults() { + if (this.query) { + const matches = new Set(fuzzyFilter(this.results, this.query, (model) => model.id).map((model) => model.id)); + this.filteredResults = this.results.filter((model) => matches.has(model.id)); + } + else { + this.filteredResults = this.results; + } + this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredResults.length - 1)); + this.updateResults(); + } + scheduleSearch() { + if (this.debounce) + clearTimeout(this.debounce); + this.request?.abort(); + this.request = undefined; + if (this.query.length < 2) { + this.status = "Type at least 2 characters"; + this.filterResults(); + return; + } + const cached = this.cache.get(this.query.toLowerCase()); + if (cached) { + this.results = cached; + this.status = cached.length === 0 ? "No GGUF models found" : ""; + this.filterResults(); + return; + } + this.status = "Searching Hugging Face…"; + this.filterResults(); + this.debounce = setTimeout(() => void this.runSearch(this.query), 500); + } + async runSearch(query) { + const request = new AbortController(); + this.request = request; + try { + const results = await this.search(query, request.signal); + this.cache.set(query.toLowerCase(), results); + if (this.closed || request.signal.aborted || this.query !== query) + return; + this.results = results; + this.selectedIndex = 0; + this.status = results.length === 0 ? "No GGUF models found" : ""; + this.filterResults(); + } + catch (error) { + if (this.closed || request.signal.aborted || this.query !== query) + return; + this.results = []; + this.status = error instanceof Error ? error.message : String(error); + this.filterResults(); + } + finally { + if (this.request === request) + this.request = undefined; + } + } + close(model) { + if (this.closed) + return; + this.closed = true; + if (this.debounce) + clearTimeout(this.debounce); + this.request?.abort(); + this.onSelectModel(model); + } + handleInput(data) { + if (this.keybindings.matches(data, "tui.select.up")) { + if (this.filteredResults.length > 0) { + this.selectedIndex = this.selectedIndex === 0 ? this.filteredResults.length - 1 : this.selectedIndex - 1; + this.updateResults(); + } + return; + } + if (this.keybindings.matches(data, "tui.select.down")) { + if (this.filteredResults.length > 0) { + this.selectedIndex = this.selectedIndex === this.filteredResults.length - 1 ? 0 : this.selectedIndex + 1; + this.updateResults(); + } + return; + } + if (this.keybindings.matches(data, "tui.select.confirm")) { + const exact = /^[^/\s]+\/[^:\s]+(?::[^\s:]+)?$/u.test(this.query) ? this.query : undefined; + const selected = exact ?? this.filteredResults[this.selectedIndex]?.id; + if (selected) + this.close(selected); + return; + } + if (this.keybindings.matches(data, "tui.select.cancel")) { + this.close(undefined); + return; + } + this.input.handleInput(data); + const query = this.input.getValue().trim(); + if (query === this.query) + return; + this.query = query; + this.scheduleSearch(); + } +} +class LlamaView { + tui; + theme; + keybindings; + searchCache = new Map(); + content; + inputHandler; + inputTarget; + progressPromise; + progressResolver; + showingProgress = false; + _focused = false; + constructor(tui, theme, keybindings) { + this.tui = tui; + this.theme = theme; + this.keybindings = keybindings; + this.content = frame(theme, "llama.cpp models", [new Text(theme.fg("muted", "Loading…"), 1, 1)]); + } + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + if (this.inputTarget) + this.inputTarget.focused = value; + } + setContent(content, inputHandler, inputTarget) { + if (this.inputTarget) + this.inputTarget.focused = false; + this.progressPromise = undefined; + this.progressResolver = undefined; + this.showingProgress = false; + this.content = content; + this.inputHandler = inputHandler; + this.inputTarget = inputTarget; + if (this.inputTarget) + this.inputTarget.focused = this._focused; + this.tui.requestRender(); + } + showModels(serverUrl, models) { + const sorted = [...models].sort((left, right) => { + const loaded = Number(right.status.value === "loaded") - Number(left.status.value === "loaded"); + return loaded || left.id.localeCompare(right.id); + }); + const byId = new Map(sorted.map((model) => [model.id, model])); + const items = [ + ...sorted.map((model) => ({ + value: model.id, + label: model.id, + description: modelDescription(model), + })), + { value: DOWNLOAD_VALUE, label: "Download model…", description: "Hugging Face owner/repository[:quant]" }, + ]; + return new Promise((resolve) => { + const list = new SelectList(items, Math.min(items.length, 12), selectTheme(this.theme), { + minPrimaryColumnWidth: 36, + maxPrimaryColumnWidth: 56, + }); + list.onSelect = (item) => { + if (item.value === DOWNLOAD_VALUE) + resolve({ type: "download" }); + else { + const model = byId.get(item.value); + if (model) + resolve({ type: "model", model }); + } + }; + list.onCancel = () => resolve({ type: "close" }); + this.setContent(frame(this.theme, "llama.cpp models", [new Text(this.theme.fg("dim", serverUrl), 1, 0), new Spacer(1), list], `${keyHint("tui.select.confirm", "load/unload/download")} • ${keyHint("tui.select.cancel", "close")}`), list); + }); + } + select(title, options) { + return new Promise((resolve) => { + const list = new SelectList(options.map((option) => ({ value: option, label: option })), Math.min(options.length, 12), selectTheme(this.theme)); + list.onSelect = (item) => resolve(item.value); + list.onCancel = () => resolve(undefined); + this.setContent(frame(this.theme, title, [new Spacer(1), list], `${keyHint("tui.select.confirm", "select")} • ${keyHint("tui.select.cancel", "cancel")}`), list); + }); + } + async confirm(title, message) { + return (await this.select(`${title}\n${message}`, ["Yes", "No"])) === "Yes"; + } + async connectionError(serverUrl, message) { + const choice = await this.select(`llama.cpp unavailable\n${serverUrl}\n\n${message}`, ["Retry", "Close"]); + return choice === "Retry" ? "retry" : "close"; + } + searchModels(search) { + return new Promise((resolve) => { + const component = new HuggingFaceSearch(this.tui, this.theme, this.keybindings, search, this.searchCache, resolve); + this.setContent(frame(this.theme, "Download model", [new Spacer(1), component], `${keyHint("tui.select.confirm", "select")} • ${keyHint("tui.select.cancel", "back")}`), component, component); + }); + } + showStatus(title, message) { + this.setContent(frame(this.theme, title, [new Spacer(1), new Text(this.theme.fg("muted", message), 1, 0)])); + } + progress(state) { + if (!this.progressPromise) { + this.progressPromise = new Promise((resolve) => { + this.progressResolver = resolve; + }); + } + this.showingProgress = true; + this.updateProgress(state); + return this.progressPromise; + } + updateProgress(state) { + if (!this.showingProgress) + return; + const body = [ + new Text(this.theme.fg("text", state.model), 1, 0), + new Spacer(1), + new Text(this.theme.fg("muted", state.message), 1, 0), + ]; + if (state.ratio !== undefined) { + const available = 40; + const filled = Math.round(Math.max(0, Math.min(1, state.ratio)) * available); + body.push(new Text(this.theme.fg("accent", `${"█".repeat(filled)}${"─".repeat(available - filled)} ${Math.round(state.ratio * 100)}%`), 1, 0)); + } + if (state.detail) + body.push(new Text(this.theme.fg("dim", state.detail), 1, 0)); + this.content = frame(this.theme, state.title, body, keyHint("tui.select.cancel", "stop")); + this.inputHandler = undefined; + this.tui.requestRender(); + } + handleInput(data) { + if (this.progressResolver && this.keybindings.matches(data, "tui.select.cancel")) { + const resolve = this.progressResolver; + this.progressPromise = undefined; + this.progressResolver = undefined; + resolve(); + return; + } + this.inputHandler?.handleInput?.(data); + this.tui.requestRender(); + } + render(width) { + return this.content + .render(width) + .map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width, "") : line)); + } + invalidate() { + this.content.invalidate(); + } +} +export async function showLlamaUi(ctx, run) { + await ctx.ui.custom((tui, theme, keybindings, done) => { + const view = new LlamaView(tui, theme, keybindings); + void run(view).then(() => done(), (error) => { + ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); + done(); + }); + return view; + }); +} +export async function runWithProgress(ui, options) { + const controller = new AbortController(); + const state = { title: options.title, model: options.model, message: options.initialMessage }; + const settled = options + .run(controller.signal, (progress) => { + Object.assign(state, progress); + ui.updateProgress(state); + }) + .then((value) => ({ ok: true, value }), (error) => ({ ok: false, error })); + let completed = false; + settled.finally(() => { + completed = true; + }); + while (!completed) { + const outcome = await Promise.race([ + settled.then(() => "settled"), + ui.progress(state).then(() => "stop"), + ]); + if (outcome === "settled") + break; + const stop = await ui.confirm(options.cancelTitle, options.cancelMessage); + if (!stop || completed) + continue; + try { + await options.cancel(); + } + finally { + controller.abort(new Error("Cancelled")); + } + await settled; + return { cancelled: true }; + } + const result = await settled; + if (!result.ok) + throw result.error; + return { cancelled: false, value: result.value }; +} +//# sourceMappingURL=ui.js.map \ No newline at end of file diff --git a/dist/extensions/llama/ui.js.map b/dist/extensions/llama/ui.js.map new file mode 100644 index 0000000..47d075a --- /dev/null +++ b/dist/extensions/llama/ui.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ui.js","sourceRoot":"","sources":["../../../src/extensions/llama/ui.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,SAAS,EAET,WAAW,EACX,KAAK,EAEL,UAAU,EACV,MAAM,EACN,IAAI,EAEJ,eAAe,EACf,YAAY,GACZ,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EAAE,aAAa,EAAE,MAAM,sDAAsD,CAAC;AACrF,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AAKjF,MAAM,cAAc,GAAG,YAAY,CAAC;AASpC,SAAS,YAAY,CAAC,KAAqB,EAAsB;IAChE,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,WAAW,CAAC;IAC7D,IAAI,OAAO;QAAE,OAAO,OAAO,IAAI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AG,EAAE,CAAC,MAAe,CAAC;SAC9C,CAAC,CAAC;QACH,IAAI,OAAO,KAAK,SAAS;YAAE,MAAM;QACjC,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;QAC1E,IAAI,CAAC,IAAI,IAAI,SAAS;YAAE,SAAS;QACjC,IAAI,CAAC;YACJ,MAAM,OAAO,CAAC,MAAM,EAAE,CAAC;QACxB,CAAC;gBAAS,CAAC;YACV,UAAU,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC;QAC1C,CAAC;QACD,MAAM,OAAO,CAAC;QACd,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;IAC5B,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC;IAC7B,IAAI,CAAC,MAAM,CAAC,EAAE;QAAE,MAAM,MAAM,CAAC,KAAK,CAAC;IACnC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC;AAAA,CACjD","sourcesContent":["import {\n\ttype Component,\n\tContainer,\n\ttype Focusable,\n\tfuzzyFilter,\n\tInput,\n\ttype SelectItem,\n\tSelectList,\n\tSpacer,\n\tText,\n\ttype TUI,\n\ttruncateToWidth,\n\tvisibleWidth,\n} from \"@earendil-works/pi-tui\";\nimport type { ExtensionCommandContext } from \"../../core/extensions/types.ts\";\nimport type { KeybindingsManager } from \"../../core/keybindings.ts\";\nimport { DynamicBorder } from \"../../modes/interactive/components/dynamic-border.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { LlamaModelInfo, LlamaProgress } from \"./client.ts\";\nimport type { HuggingFaceModel } from \"./huggingface.ts\";\n\nconst DOWNLOAD_VALUE = \"\\0download\";\n\nexport type LlamaManagerAction = { type: \"model\"; model: LlamaModelInfo } | { type: \"download\" } | { type: \"close\" };\n\ninterface ProgressState extends LlamaProgress {\n\ttitle: string;\n\tmodel: string;\n}\n\nfunction contextLabel(model: LlamaModelInfo): string | undefined {\n\tconst context = model.meta?.n_ctx ?? model.meta?.n_ctx_train;\n\tif (context) return context >= 1000 ? `${Math.round(context / 1000)}k` : String(context);\n\tconst args = model.status.args ?? [];\n\tfor (let index = 0; index < args.length - 1; index++) {\n\t\tif (args[index] !== \"--ctx-size\" && args[index] !== \"-c\" && args[index] !== \"-ctx\") continue;\n\t\tconst value = Number(args[index + 1]);\n\t\tif (Number.isFinite(value) && value > 0) return value >= 1000 ? `${Math.round(value / 1000)}k` : String(value);\n\t}\n\treturn undefined;\n}\n\nfunction modelDescription(model: LlamaModelInfo): string {\n\tconst details: string[] = [];\n\tconst loaded = model.status.value === \"loaded\" || model.status.value === \"sleeping\";\n\tif (loaded) details.push(\"loaded\");\n\telse if (model.status.value !== \"unloaded\") details.push(model.status.value);\n\tconst context = loaded ? contextLabel(model) : undefined;\n\tif (context) details.push(`${context} context`);\n\treturn details.join(\" · \");\n}\n\nfunction selectTheme(theme: Theme) {\n\treturn {\n\t\tselectedPrefix: (text: string) => theme.fg(\"accent\", text),\n\t\tselectedText: (text: string) => theme.fg(\"accent\", text),\n\t\tdescription: (text: string) => theme.fg(\"muted\", text),\n\t\tscrollInfo: (text: string) => theme.fg(\"dim\", text),\n\t\tnoMatch: (text: string) => theme.fg(\"warning\", text),\n\t};\n}\n\nfunction frame(theme: Theme, title: string, body: Component[], footer?: string): Container {\n\tconst container = new Container();\n\tcontainer.addChild(new DynamicBorder((text: string) => theme.fg(\"accent\", text)));\n\tcontainer.addChild(new Text(theme.fg(\"accent\", theme.bold(title)), 1, 0));\n\tfor (const child of body) container.addChild(child);\n\tif (footer) {\n\t\tcontainer.addChild(new Spacer(1));\n\t\tcontainer.addChild(new Text(theme.fg(\"dim\", footer), 1, 0));\n\t}\n\tcontainer.addChild(new DynamicBorder((text: string) => theme.fg(\"accent\", text)));\n\treturn container;\n}\n\nexport interface LlamaUi {\n\tshowModels(serverUrl: string, models: LlamaModelInfo[]): Promise;\n\tselect(title: string, options: string[]): Promise;\n\tconfirm(title: string, message: string): Promise;\n\tconnectionError(serverUrl: string, message: string): Promise<\"retry\" | \"close\">;\n\tsearchModels(\n\t\tsearch: (query: string, signal: AbortSignal) => Promise,\n\t): Promise;\n\tshowStatus(title: string, message: string): void;\n\tprogress(state: ProgressState): Promise;\n\tupdateProgress(state: ProgressState): void;\n}\n\nfunction compactCount(value: number): string {\n\tif (value >= 1_000_000) return `${(value / 1_000_000).toFixed(value >= 10_000_000 ? 0 : 1)}M`;\n\tif (value >= 1_000) return `${(value / 1_000).toFixed(value >= 100_000 ? 0 : 1)}k`;\n\treturn String(value);\n}\n\nclass HuggingFaceSearch extends Container implements Focusable {\n\tprivate readonly tui: TUI;\n\tprivate readonly theme: Theme;\n\tprivate readonly keybindings: KeybindingsManager;\n\tprivate readonly search: (query: string, signal: AbortSignal) => Promise;\n\tprivate readonly cache: Map;\n\tprivate readonly onSelectModel: (model: string | undefined) => void;\n\tprivate readonly input = new Input();\n\tprivate readonly resultsContainer = new Container();\n\tprivate results: HuggingFaceModel[] = [];\n\tprivate filteredResults: HuggingFaceModel[] = [];\n\tprivate selectedIndex = 0;\n\tprivate query = \"\";\n\tprivate status = \"Type at least 2 characters\";\n\tprivate debounce: ReturnType | undefined;\n\tprivate request: AbortController | undefined;\n\tprivate closed = false;\n\tprivate _focused = false;\n\n\tconstructor(\n\t\ttui: TUI,\n\t\ttheme: Theme,\n\t\tkeybindings: KeybindingsManager,\n\t\tsearch: (query: string, signal: AbortSignal) => Promise,\n\t\tcache: Map,\n\t\tonSelectModel: (model: string | undefined) => void,\n\t) {\n\t\tsuper();\n\t\tthis.tui = tui;\n\t\tthis.theme = theme;\n\t\tthis.keybindings = keybindings;\n\t\tthis.search = search;\n\t\tthis.cache = cache;\n\t\tthis.onSelectModel = onSelectModel;\n\t\tthis.addChild(new Text(theme.fg(\"dim\", \"Model name or owner/repository[:quant]\"), 1, 0));\n\t\tthis.addChild(this.input);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(this.resultsContainer);\n\t\tthis.updateResults();\n\t}\n\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.input.focused = value;\n\t}\n\n\tprivate updateResults(): void {\n\t\tthis.resultsContainer.clear();\n\t\tconst maxVisible = 10;\n\t\tconst start = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(maxVisible / 2), this.filteredResults.length - maxVisible),\n\t\t);\n\t\tconst end = Math.min(start + maxVisible, this.filteredResults.length);\n\t\tfor (let index = start; index < end; index++) {\n\t\t\tconst model = this.filteredResults[index];\n\t\t\tif (!model) continue;\n\t\t\tconst prefix = index === this.selectedIndex ? \"→ \" : \" \";\n\t\t\tconst details = `${compactCount(model.downloads)} downloads`;\n\t\t\tthis.resultsContainer.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\tindex === this.selectedIndex\n\t\t\t\t\t\t? this.theme.fg(\"accent\", `${prefix}${model.id} ${details}`)\n\t\t\t\t\t\t: `${prefix}${model.id}${this.theme.fg(\"muted\", ` ${details}`)}`,\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (start > 0 || end < this.filteredResults.length) {\n\t\t\tthis.resultsContainer.addChild(\n\t\t\t\tnew Text(this.theme.fg(\"dim\", ` (${this.selectedIndex + 1}/${this.filteredResults.length})`), 0, 0),\n\t\t\t);\n\t\t}\n\t\tif (this.filteredResults.length === 0) {\n\t\t\tthis.resultsContainer.addChild(new Text(this.theme.fg(\"dim\", ` ${this.status}`), 0, 0));\n\t\t} else if (this.status === \"Searching Hugging Face…\") {\n\t\t\tthis.resultsContainer.addChild(new Text(this.theme.fg(\"dim\", ` ${this.status}`), 0, 0));\n\t\t}\n\t\tthis.tui.requestRender();\n\t}\n\n\tprivate filterResults(): void {\n\t\tif (this.query) {\n\t\t\tconst matches = new Set(fuzzyFilter(this.results, this.query, (model) => model.id).map((model) => model.id));\n\t\t\tthis.filteredResults = this.results.filter((model) => matches.has(model.id));\n\t\t} else {\n\t\t\tthis.filteredResults = this.results;\n\t\t}\n\t\tthis.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredResults.length - 1));\n\t\tthis.updateResults();\n\t}\n\n\tprivate scheduleSearch(): void {\n\t\tif (this.debounce) clearTimeout(this.debounce);\n\t\tthis.request?.abort();\n\t\tthis.request = undefined;\n\t\tif (this.query.length < 2) {\n\t\t\tthis.status = \"Type at least 2 characters\";\n\t\t\tthis.filterResults();\n\t\t\treturn;\n\t\t}\n\t\tconst cached = this.cache.get(this.query.toLowerCase());\n\t\tif (cached) {\n\t\t\tthis.results = cached;\n\t\t\tthis.status = cached.length === 0 ? \"No GGUF models found\" : \"\";\n\t\t\tthis.filterResults();\n\t\t\treturn;\n\t\t}\n\t\tthis.status = \"Searching Hugging Face…\";\n\t\tthis.filterResults();\n\t\tthis.debounce = setTimeout(() => void this.runSearch(this.query), 500);\n\t}\n\n\tprivate async runSearch(query: string): Promise {\n\t\tconst request = new AbortController();\n\t\tthis.request = request;\n\t\ttry {\n\t\t\tconst results = await this.search(query, request.signal);\n\t\t\tthis.cache.set(query.toLowerCase(), results);\n\t\t\tif (this.closed || request.signal.aborted || this.query !== query) return;\n\t\t\tthis.results = results;\n\t\t\tthis.selectedIndex = 0;\n\t\t\tthis.status = results.length === 0 ? \"No GGUF models found\" : \"\";\n\t\t\tthis.filterResults();\n\t\t} catch (error) {\n\t\t\tif (this.closed || request.signal.aborted || this.query !== query) return;\n\t\t\tthis.results = [];\n\t\t\tthis.status = error instanceof Error ? error.message : String(error);\n\t\t\tthis.filterResults();\n\t\t} finally {\n\t\t\tif (this.request === request) this.request = undefined;\n\t\t}\n\t}\n\n\tprivate close(model: string | undefined): void {\n\t\tif (this.closed) return;\n\t\tthis.closed = true;\n\t\tif (this.debounce) clearTimeout(this.debounce);\n\t\tthis.request?.abort();\n\t\tthis.onSelectModel(model);\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (this.keybindings.matches(data, \"tui.select.up\")) {\n\t\t\tif (this.filteredResults.length > 0) {\n\t\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.filteredResults.length - 1 : this.selectedIndex - 1;\n\t\t\t\tthis.updateResults();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.down\")) {\n\t\t\tif (this.filteredResults.length > 0) {\n\t\t\t\tthis.selectedIndex = this.selectedIndex === this.filteredResults.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t\t\tthis.updateResults();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.confirm\")) {\n\t\t\tconst exact = /^[^/\\s]+\\/[^:\\s]+(?::[^\\s:]+)?$/u.test(this.query) ? this.query : undefined;\n\t\t\tconst selected = exact ?? this.filteredResults[this.selectedIndex]?.id;\n\t\t\tif (selected) this.close(selected);\n\t\t\treturn;\n\t\t}\n\t\tif (this.keybindings.matches(data, \"tui.select.cancel\")) {\n\t\t\tthis.close(undefined);\n\t\t\treturn;\n\t\t}\n\t\tthis.input.handleInput(data);\n\t\tconst query = this.input.getValue().trim();\n\t\tif (query === this.query) return;\n\t\tthis.query = query;\n\t\tthis.scheduleSearch();\n\t}\n}\n\nclass LlamaView implements LlamaUi, Focusable {\n\tprivate readonly tui: TUI;\n\tprivate readonly theme: Theme;\n\tprivate readonly keybindings: KeybindingsManager;\n\tprivate readonly searchCache = new Map();\n\tprivate content: Container;\n\tprivate inputHandler: { handleInput?(data: string): void } | undefined;\n\tprivate inputTarget: Focusable | undefined;\n\tprivate progressPromise: Promise | undefined;\n\tprivate progressResolver: (() => void) | undefined;\n\tprivate showingProgress = false;\n\tprivate _focused = false;\n\n\tconstructor(tui: TUI, theme: Theme, keybindings: KeybindingsManager) {\n\t\tthis.tui = tui;\n\t\tthis.theme = theme;\n\t\tthis.keybindings = keybindings;\n\t\tthis.content = frame(theme, \"llama.cpp models\", [new Text(theme.fg(\"muted\", \"Loading…\"), 1, 1)]);\n\t}\n\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tif (this.inputTarget) this.inputTarget.focused = value;\n\t}\n\n\tprivate setContent(\n\t\tcontent: Container,\n\t\tinputHandler?: { handleInput?(data: string): void },\n\t\tinputTarget?: Focusable,\n\t): void {\n\t\tif (this.inputTarget) this.inputTarget.focused = false;\n\t\tthis.progressPromise = undefined;\n\t\tthis.progressResolver = undefined;\n\t\tthis.showingProgress = false;\n\t\tthis.content = content;\n\t\tthis.inputHandler = inputHandler;\n\t\tthis.inputTarget = inputTarget;\n\t\tif (this.inputTarget) this.inputTarget.focused = this._focused;\n\t\tthis.tui.requestRender();\n\t}\n\n\tshowModels(serverUrl: string, models: LlamaModelInfo[]): Promise {\n\t\tconst sorted = [...models].sort((left, right) => {\n\t\t\tconst loaded = Number(right.status.value === \"loaded\") - Number(left.status.value === \"loaded\");\n\t\t\treturn loaded || left.id.localeCompare(right.id);\n\t\t});\n\t\tconst byId = new Map(sorted.map((model) => [model.id, model]));\n\t\tconst items: SelectItem[] = [\n\t\t\t...sorted.map((model) => ({\n\t\t\t\tvalue: model.id,\n\t\t\t\tlabel: model.id,\n\t\t\t\tdescription: modelDescription(model),\n\t\t\t})),\n\t\t\t{ value: DOWNLOAD_VALUE, label: \"Download model…\", description: \"Hugging Face owner/repository[:quant]\" },\n\t\t];\n\t\treturn new Promise((resolve) => {\n\t\t\tconst list = new SelectList(items, Math.min(items.length, 12), selectTheme(this.theme), {\n\t\t\t\tminPrimaryColumnWidth: 36,\n\t\t\t\tmaxPrimaryColumnWidth: 56,\n\t\t\t});\n\t\t\tlist.onSelect = (item) => {\n\t\t\t\tif (item.value === DOWNLOAD_VALUE) resolve({ type: \"download\" });\n\t\t\t\telse {\n\t\t\t\t\tconst model = byId.get(item.value);\n\t\t\t\t\tif (model) resolve({ type: \"model\", model });\n\t\t\t\t}\n\t\t\t};\n\t\t\tlist.onCancel = () => resolve({ type: \"close\" });\n\t\t\tthis.setContent(\n\t\t\t\tframe(\n\t\t\t\t\tthis.theme,\n\t\t\t\t\t\"llama.cpp models\",\n\t\t\t\t\t[new Text(this.theme.fg(\"dim\", serverUrl), 1, 0), new Spacer(1), list],\n\t\t\t\t\t`${keyHint(\"tui.select.confirm\", \"load/unload/download\")} • ${keyHint(\"tui.select.cancel\", \"close\")}`,\n\t\t\t\t),\n\t\t\t\tlist,\n\t\t\t);\n\t\t});\n\t}\n\n\tselect(title: string, options: string[]): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst list = new SelectList(\n\t\t\t\toptions.map((option) => ({ value: option, label: option })),\n\t\t\t\tMath.min(options.length, 12),\n\t\t\t\tselectTheme(this.theme),\n\t\t\t);\n\t\t\tlist.onSelect = (item) => resolve(item.value);\n\t\t\tlist.onCancel = () => resolve(undefined);\n\t\t\tthis.setContent(\n\t\t\t\tframe(\n\t\t\t\t\tthis.theme,\n\t\t\t\t\ttitle,\n\t\t\t\t\t[new Spacer(1), list],\n\t\t\t\t\t`${keyHint(\"tui.select.confirm\", \"select\")} • ${keyHint(\"tui.select.cancel\", \"cancel\")}`,\n\t\t\t\t),\n\t\t\t\tlist,\n\t\t\t);\n\t\t});\n\t}\n\n\tasync confirm(title: string, message: string): Promise {\n\t\treturn (await this.select(`${title}\\n${message}`, [\"Yes\", \"No\"])) === \"Yes\";\n\t}\n\n\tasync connectionError(serverUrl: string, message: string): Promise<\"retry\" | \"close\"> {\n\t\tconst choice = await this.select(`llama.cpp unavailable\\n${serverUrl}\\n\\n${message}`, [\"Retry\", \"Close\"]);\n\t\treturn choice === \"Retry\" ? \"retry\" : \"close\";\n\t}\n\n\tsearchModels(\n\t\tsearch: (query: string, signal: AbortSignal) => Promise,\n\t): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst component = new HuggingFaceSearch(\n\t\t\t\tthis.tui,\n\t\t\t\tthis.theme,\n\t\t\t\tthis.keybindings,\n\t\t\t\tsearch,\n\t\t\t\tthis.searchCache,\n\t\t\t\tresolve,\n\t\t\t);\n\t\t\tthis.setContent(\n\t\t\t\tframe(\n\t\t\t\t\tthis.theme,\n\t\t\t\t\t\"Download model\",\n\t\t\t\t\t[new Spacer(1), component],\n\t\t\t\t\t`${keyHint(\"tui.select.confirm\", \"select\")} • ${keyHint(\"tui.select.cancel\", \"back\")}`,\n\t\t\t\t),\n\t\t\t\tcomponent,\n\t\t\t\tcomponent,\n\t\t\t);\n\t\t});\n\t}\n\n\tshowStatus(title: string, message: string): void {\n\t\tthis.setContent(frame(this.theme, title, [new Spacer(1), new Text(this.theme.fg(\"muted\", message), 1, 0)]));\n\t}\n\n\tprogress(state: ProgressState): Promise {\n\t\tif (!this.progressPromise) {\n\t\t\tthis.progressPromise = new Promise((resolve) => {\n\t\t\t\tthis.progressResolver = resolve;\n\t\t\t});\n\t\t}\n\t\tthis.showingProgress = true;\n\t\tthis.updateProgress(state);\n\t\treturn this.progressPromise;\n\t}\n\n\tupdateProgress(state: ProgressState): void {\n\t\tif (!this.showingProgress) return;\n\t\tconst body = [\n\t\t\tnew Text(this.theme.fg(\"text\", state.model), 1, 0),\n\t\t\tnew Spacer(1),\n\t\t\tnew Text(this.theme.fg(\"muted\", state.message), 1, 0),\n\t\t];\n\t\tif (state.ratio !== undefined) {\n\t\t\tconst available = 40;\n\t\t\tconst filled = Math.round(Math.max(0, Math.min(1, state.ratio)) * available);\n\t\t\tbody.push(\n\t\t\t\tnew Text(\n\t\t\t\t\tthis.theme.fg(\n\t\t\t\t\t\t\"accent\",\n\t\t\t\t\t\t`${\"█\".repeat(filled)}${\"─\".repeat(available - filled)} ${Math.round(state.ratio * 100)}%`,\n\t\t\t\t\t),\n\t\t\t\t\t1,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (state.detail) body.push(new Text(this.theme.fg(\"dim\", state.detail), 1, 0));\n\t\tthis.content = frame(this.theme, state.title, body, keyHint(\"tui.select.cancel\", \"stop\"));\n\t\tthis.inputHandler = undefined;\n\t\tthis.tui.requestRender();\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (this.progressResolver && this.keybindings.matches(data, \"tui.select.cancel\")) {\n\t\t\tconst resolve = this.progressResolver;\n\t\t\tthis.progressPromise = undefined;\n\t\t\tthis.progressResolver = undefined;\n\t\t\tresolve();\n\t\t\treturn;\n\t\t}\n\t\tthis.inputHandler?.handleInput?.(data);\n\t\tthis.tui.requestRender();\n\t}\n\n\trender(width: number): string[] {\n\t\treturn this.content\n\t\t\t.render(width)\n\t\t\t.map((line) => (visibleWidth(line) > width ? truncateToWidth(line, width, \"\") : line));\n\t}\n\n\tinvalidate(): void {\n\t\tthis.content.invalidate();\n\t}\n}\n\nexport async function showLlamaUi(ctx: ExtensionCommandContext, run: (ui: LlamaUi) => Promise): Promise {\n\tawait ctx.ui.custom((tui, theme, keybindings, done) => {\n\t\tconst view = new LlamaView(tui, theme, keybindings);\n\t\tvoid run(view).then(\n\t\t\t() => done(),\n\t\t\t(error: unknown) => {\n\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t\tdone();\n\t\t\t},\n\t\t);\n\t\treturn view;\n\t});\n}\n\nexport async function runWithProgress(\n\tui: LlamaUi,\n\toptions: {\n\t\ttitle: string;\n\t\tmodel: string;\n\t\tinitialMessage: string;\n\t\tcancelTitle: string;\n\t\tcancelMessage: string;\n\t\trun(signal: AbortSignal, update: (progress: LlamaProgress) => void): Promise;\n\t\tcancel(): Promise;\n\t},\n): Promise<{ cancelled: true } | { cancelled: false; value: T }> {\n\tconst controller = new AbortController();\n\tconst state: ProgressState = { title: options.title, model: options.model, message: options.initialMessage };\n\tconst settled = options\n\t\t.run(controller.signal, (progress) => {\n\t\t\tObject.assign(state, progress);\n\t\t\tui.updateProgress(state);\n\t\t})\n\t\t.then(\n\t\t\t(value) => ({ ok: true as const, value }),\n\t\t\t(error: unknown) => ({ ok: false as const, error }),\n\t\t);\n\tlet completed = false;\n\tsettled.finally(() => {\n\t\tcompleted = true;\n\t});\n\n\twhile (!completed) {\n\t\tconst outcome = await Promise.race([\n\t\t\tsettled.then(() => \"settled\" as const),\n\t\t\tui.progress(state).then(() => \"stop\" as const),\n\t\t]);\n\t\tif (outcome === \"settled\") break;\n\t\tconst stop = await ui.confirm(options.cancelTitle, options.cancelMessage);\n\t\tif (!stop || completed) continue;\n\t\ttry {\n\t\t\tawait options.cancel();\n\t\t} finally {\n\t\t\tcontroller.abort(new Error(\"Cancelled\"));\n\t\t}\n\t\tawait settled;\n\t\treturn { cancelled: true };\n\t}\n\n\tconst result = await settled;\n\tif (!result.ok) throw result.error;\n\treturn { cancelled: false, value: result.value };\n}\n"]} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts new file mode 100644 index 0000000..e91e38f --- /dev/null +++ b/dist/index.d.ts @@ -0,0 +1,35 @@ +export { type Args, parseArgs } from "./cli/args.ts"; +export { CONFIG_DIR_NAME, getAgentDir, getDocsPath, getExamplesPath, getPackageDir, getReadmePath, VERSION, } from "./config.ts"; +export { AgentSession, type AgentSessionConfig, type AgentSessionEvent, type AgentSessionEventListener, type ModelCycleResult, type ParsedSkillBlock, type PromptOptions, parseSkillBlock, type SessionStats, } from "./core/agent-session.ts"; +export { readStoredCredential } from "./core/auth-storage.ts"; +export { type BranchPreparation, type BranchSummaryResult, type CollectEntriesResult, type CompactionResult, type CutPointResult, calculateContextTokens, collectEntriesForBranchSummary, compact, DEFAULT_COMPACTION_SETTINGS, estimateTokens, type FileOperations, findCutPoint, findTurnStartIndex, type GenerateBranchSummaryOptions, generateBranchSummary, generateSummary, generateSummaryWithUsage, getLastAssistantUsage, prepareBranchEntries, serializeConversation, shouldCompact, } from "./core/compaction/index.ts"; +export { createEventBus, type EventBus, type EventBusController } from "./core/event-bus.ts"; +export type { AgentEndEvent, AgentSettledEvent, AgentStartEvent, AgentToolResult, AgentToolUpdateCallback, AppKeybinding, AutocompleteProviderFactory, BashToolCallEvent, BeforeAgentStartEvent, BeforeAgentStartEventResult, BeforeProviderHeadersEvent, BeforeProviderRequestEvent, BeforeProviderRequestEventResult, BuildSystemPromptOptions, CompactOptions, ContextEvent, ContextUsage, CustomToolCallEvent, EditToolCallEvent, EntryRenderer, EntryRenderOptions, ExecOptions, ExecResult, Extension, ExtensionActions, ExtensionAPI, ExtensionCommandContext, ExtensionCommandContextActions, ExtensionContext, ExtensionContextActions, ExtensionError, ExtensionEvent, ExtensionFactory, ExtensionFlag, ExtensionHandler, ExtensionRuntime, ExtensionShortcut, ExtensionUIContext, ExtensionUIDialogOptions, ExtensionWidgetOptions, FindToolCallEvent, GrepToolCallEvent, InlineExtension, InputEvent, InputEventResult, InputSource, KeybindingsManager, LoadExtensionsResult, LsToolCallEvent, MessageEndEvent, MessageRenderer, MessageRenderOptions, MessageStartEvent, MessageUpdateEvent, ProjectTrustContext, ProjectTrustEvent, ProjectTrustEventDecision, ProjectTrustEventResult, ProjectTrustHandler, ProviderConfig, ProviderModelConfig, ReadToolCallEvent, RegisteredCommand, RegisteredTool, ResolvedCommand, SessionBeforeCompactEvent, SessionBeforeForkEvent, SessionBeforeSwitchEvent, SessionBeforeTreeEvent, SessionCompactEvent, SessionInfoChangedEvent, SessionShutdownEvent, SessionStartEvent, SessionTreeEvent, SlashCommandInfo, SlashCommandSource, SourceInfo, TerminalInputHandler, ToolCallEvent, ToolCallEventResult, ToolDefinition, ToolExecutionEndEvent, ToolExecutionMode, ToolExecutionStartEvent, ToolExecutionUpdateEvent, ToolInfo, ToolRenderResultOptions, ToolResultEvent, TurnEndEvent, TurnStartEvent, UserBashEvent, UserBashEventResult, WidgetPlacement, WorkingIndicatorOptions, WriteToolCallEvent, } from "./core/extensions/index.ts"; +export { createExtensionRuntime, defineTool, discoverAndLoadExtensions, ExtensionRunner, isBashToolResult, isEditToolResult, isFindToolResult, isGrepToolResult, isLsToolResult, isReadToolResult, isToolCallEventType, isWriteToolResult, wrapRegisteredTool, wrapRegisteredTools, } from "./core/extensions/index.ts"; +export type { ReadonlyFooterDataProvider } from "./core/footer-data-provider.ts"; +export { convertToLlm } from "./core/messages.ts"; +export { ModelRegistry } from "./core/model-registry.ts"; +export { type ModelScopeDiagnostic, type ResolveCliModelResult, type ResolveModelScopeResult, resolveCliModel, resolveModelScopeWithDiagnostics, type ScopedModel, } from "./core/model-resolver.ts"; +export { type CreateModelRuntimeOptions, ModelRuntime, type ModelRuntimeAuthOverrides, } from "./core/model-runtime.ts"; +export type { PackageManager, PathMetadata, ProgressCallback, ProgressEvent, ResolvedPaths, ResolvedResource, } from "./core/package-manager.ts"; +export { DefaultPackageManager } from "./core/package-manager.ts"; +export type { ResourceCollision, ResourceDiagnostic, ResourceLoader } from "./core/resource-loader.ts"; +export { DefaultResourceLoader, loadProjectContextFiles } from "./core/resource-loader.ts"; +export { AgentSessionRuntime, type AgentSessionRuntimeDiagnostic, type AgentSessionServices, type CreateAgentSessionFromServicesOptions, type CreateAgentSessionOptions, type CreateAgentSessionResult, type CreateAgentSessionRuntimeFactory, type CreateAgentSessionRuntimeResult, type CreateAgentSessionServicesOptions, createAgentSession, createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createBashTool, createCodingTools, createEditTool, createFindTool, createGrepTool, createLsTool, createReadOnlyTools, createReadTool, createWriteTool, type PromptTemplate, } from "./core/sdk.ts"; +export { type BranchSummaryEntry, buildContextEntries, buildSessionContext, type CompactionEntry, CURRENT_SESSION_VERSION, type CustomEntry, type CustomMessageEntry, type FileEntry, getLatestCompactionEntry, type ModelChangeEntry, migrateSessionEntries, type NewSessionOptions, parseSessionEntries, type SessionContext, type SessionEntry, type SessionEntryBase, type SessionHeader, type SessionInfo, type SessionInfoEntry, SessionManager, type SessionMessageEntry, type SessionTreeNode, sessionEntryToContextMessages, type ThinkingLevelChangeEntry, } from "./core/session-manager.ts"; +export { type CompactionSettings, type DefaultProjectTrust, type ImageSettings, type PackageSource, type RetrySettings, SettingsManager, type SettingsManagerCreateOptions, } from "./core/settings-manager.ts"; +export { formatSkillsForPrompt, type LoadSkillsFromDirOptions, type LoadSkillsResult, loadSkills, loadSkillsFromDir, type Skill, type SkillFrontmatter, } from "./core/skills.ts"; +export { createSyntheticSourceInfo } from "./core/source-info.ts"; +export { type EditDiffResult, generateDiffString, generateUnifiedPatch } from "./core/tools/edit-diff.ts"; +export { type BashOperations, type BashSpawnContext, type BashSpawnHook, type BashToolDetails, type BashToolInput, type BashToolOptions, createBashToolDefinition, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLocalBashOperations, createLsToolDefinition, createReadToolDefinition, createWriteToolDefinition, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type EditOperations, type EditToolDetails, type EditToolInput, type EditToolOptions, type FindOperations, type FindToolDetails, type FindToolInput, type FindToolOptions, formatSize, type GrepOperations, type GrepToolDetails, type GrepToolInput, type GrepToolOptions, type LsOperations, type LsToolDetails, type LsToolInput, type LsToolOptions, type ReadOperations, type ReadToolDetails, type ReadToolInput, type ReadToolOptions, type ToolsOptions, type TruncationOptions, type TruncationResult, truncateHead, truncateLine, truncateTail, type WriteOperations, type WriteToolInput, type WriteToolOptions, withFileMutationQueue, } from "./core/tools/index.ts"; +export { hasTrustRequiringProjectResources, type ProjectTrustDecision, ProjectTrustStore, type ProjectTrustStoreEntry, type ProjectTrustUpdate, } from "./core/trust-manager.ts"; +export { type MainOptions, main } from "./main.ts"; +export { InteractiveMode, type InteractiveModeOptions, type ModelInfo, type PrintModeOptions, RpcClient, type RpcClientOptions, type RpcCommand, type RpcEventListener, type RpcExtensionUIRequest, type RpcExtensionUIResponse, type RpcResponse, type RpcSessionState, runPrintMode, runRpcMode, } from "./modes/index.ts"; +export { ArminComponent, AssistantMessageComponent, BashExecutionComponent, BorderedLoader, BranchSummaryMessageComponent, CompactionSummaryMessageComponent, CustomEditor, CustomMessageComponent, DynamicBorder, ExtensionEditorComponent, ExtensionInputComponent, ExtensionSelectorComponent, FooterComponent, keyHint, keyText, LoginDialogComponent, ModelSelectorComponent, OAuthSelectorComponent, type RenderDiffOptions, rawKeyHint, renderDiff, SessionSelectorComponent, type SettingsCallbacks, type SettingsConfig, SettingsSelectorComponent, ShowImagesSelectorComponent, SkillInvocationMessageComponent, ThemeSelectorComponent, ThinkingSelectorComponent, ToolExecutionComponent, type ToolExecutionOptions, TreeSelectorComponent, truncateToVisualLines, UserMessageComponent, UserMessageSelectorComponent, type VisualTruncateResult, } from "./modes/interactive/components/index.ts"; +export { getLanguageFromPath, getMarkdownTheme, getSelectListTheme, getSettingsListTheme, highlightCode, initTheme, Theme, type ThemeColor, } from "./modes/interactive/theme/theme.ts"; +export { copyToClipboard } from "./utils/clipboard.ts"; +export { parseFrontmatter, stripFrontmatter } from "./utils/frontmatter.ts"; +export { convertToPng } from "./utils/image-convert.ts"; +export { formatDimensionNote, type ResizedImage, resizeImage } from "./utils/image-resize.ts"; +export { getShellConfig } from "./utils/shell.ts"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/index.d.ts.map b/dist/index.d.ts.map new file mode 100644 index 0000000..95d1f5a --- /dev/null +++ b/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,IAAI,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAGrD,OAAO,EACN,eAAe,EACf,WAAW,EACX,WAAW,EACX,eAAe,EACf,aAAa,EACb,aAAa,EACb,OAAO,GACP,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,YAAY,EACZ,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,yBAAyB,EAC9B,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EAC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AO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC5E,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,KAAK,YAAY,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAE9F,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["// Core session management\n\nexport { type Args, parseArgs } from \"./cli/args.ts\";\n\n// Config paths\nexport {\n\tCONFIG_DIR_NAME,\n\tgetAgentDir,\n\tgetDocsPath,\n\tgetExamplesPath,\n\tgetPackageDir,\n\tgetReadmePath,\n\tVERSION,\n} from \"./config.ts\";\nexport {\n\tAgentSession,\n\ttype AgentSessionConfig,\n\ttype AgentSessionEvent,\n\ttype AgentSessionEventListener,\n\ttype ModelCycleResult,\n\ttype ParsedSkillBlock,\n\ttype PromptOptions,\n\tparseSkillBlock,\n\ttype SessionStats,\n} from \"./core/agent-session.ts\";\nexport { readStoredCredential } from \"./core/auth-storage.ts\";\n// Compaction\nexport {\n\ttype BranchPreparation,\n\ttype BranchSummaryResult,\n\ttype CollectEntriesResult,\n\ttype CompactionResult,\n\ttype CutPointResult,\n\tcalculateContextTokens,\n\tcollectEntriesForBranchSummary,\n\tcompact,\n\tDEFAULT_COMPACTION_SETTINGS,\n\testimateTokens,\n\ttype FileOperations,\n\tfindCutPoint,\n\tfindTurnStartIndex,\n\ttype GenerateBranchSummaryOptions,\n\tgenerateBranchSummary,\n\tgenerateSummary,\n\tgenerateSummaryWithUsage,\n\tgetLastAssistantUsage,\n\tprepareBranchEntries,\n\tserializeConversation,\n\tshouldCompact,\n} from \"./core/compaction/index.ts\";\nexport { createEventBus, type EventBus, type EventBusController } from \"./core/event-bus.ts\";\n// Extension system\nexport type {\n\tAgentEndEvent,\n\tAgentSettledEvent,\n\tAgentStartEvent,\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n\tAppKeybinding,\n\tAutocompleteProviderFactory,\n\tBashToolCallEvent,\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tBeforeProviderHeadersEvent,\n\tBeforeProviderRequestEvent,\n\tBeforeProviderRequestEventResult,\n\tBuildSystemPromptOptions,\n\tCompactOptions,\n\tContextEvent,\n\tContextUsage,\n\tCustomToolCallEvent,\n\tEditToolCallEvent,\n\tEntryRenderer,\n\tEntryRenderOptions,\n\tExecOptions,\n\tExecResult,\n\tExtension,\n\tExtensionActions,\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFactory,\n\tExtensionFlag,\n\tExtensionHandler,\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tFindToolCallEvent,\n\tGrepToolCallEvent,\n\tInlineExtension,\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tKeybindingsManager,\n\tLoadExtensionsResult,\n\tLsToolCallEvent,\n\tMessageEndEvent,\n\tMessageRenderer,\n\tMessageRenderOptions,\n\tMessageStartEvent,\n\tMessageUpdateEvent,\n\tProjectTrustContext,\n\tProjectTrustEvent,\n\tProjectTrustEventDecision,\n\tProjectTrustEventResult,\n\tProjectTrustHandler,\n\tProviderConfig,\n\tProviderModelConfig,\n\tReadToolCallEvent,\n\tRegisteredCommand,\n\tRegisteredTool,\n\tResolvedCommand,\n\tSessionBeforeCompactEvent,\n\tSessionBeforeForkEvent,\n\tSessionBeforeSwitchEvent,\n\tSessionBeforeTreeEvent,\n\tSessionCompactEvent,\n\tSessionInfoChangedEvent,\n\tSessionShutdownEvent,\n\tSessionStartEvent,\n\tSessionTreeEvent,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tSourceInfo,\n\tTerminalInputHandler,\n\tToolCallEvent,\n\tToolCallEventResult,\n\tToolDefinition,\n\tToolExecutionEndEvent,\n\tToolExecutionMode,\n\tToolExecutionStartEvent,\n\tToolExecutionUpdateEvent,\n\tToolInfo,\n\tToolRenderResultOptions,\n\tToolResultEvent,\n\tTurnEndEvent,\n\tTurnStartEvent,\n\tUserBashEvent,\n\tUserBashEventResult,\n\tWidgetPlacement,\n\tWorkingIndicatorOptions,\n\tWriteToolCallEvent,\n} from \"./core/extensions/index.ts\";\nexport {\n\tcreateExtensionRuntime,\n\tdefineTool,\n\tdiscoverAndLoadExtensions,\n\tExtensionRunner,\n\tisBashToolResult,\n\tisEditToolResult,\n\tisFindToolResult,\n\tisGrepToolResult,\n\tisLsToolResult,\n\tisReadToolResult,\n\tisToolCallEventType,\n\tisWriteToolResult,\n\twrapRegisteredTool,\n\twrapRegisteredTools,\n} from \"./core/extensions/index.ts\";\n// Footer data provider (git branch + extension statuses - data not otherwise available to extensions)\nexport type { ReadonlyFooterDataProvider } from \"./core/footer-data-provider.ts\";\nexport { convertToLlm } from \"./core/messages.ts\";\nexport { ModelRegistry } from \"./core/model-registry.ts\";\nexport {\n\ttype ModelScopeDiagnostic,\n\ttype ResolveCliModelResult,\n\ttype ResolveModelScopeResult,\n\tresolveCliModel,\n\tresolveModelScopeWithDiagnostics,\n\ttype ScopedModel,\n} from \"./core/model-resolver.ts\";\nexport {\n\ttype CreateModelRuntimeOptions,\n\tModelRuntime,\n\ttype ModelRuntimeAuthOverrides,\n} from \"./core/model-runtime.ts\";\nexport type {\n\tPackageManager,\n\tPathMetadata,\n\tProgressCallback,\n\tProgressEvent,\n\tResolvedPaths,\n\tResolvedResource,\n} from \"./core/package-manager.ts\";\nexport { DefaultPackageManager } from \"./core/package-manager.ts\";\nexport type { ResourceCollision, ResourceDiagnostic, ResourceLoader } from \"./core/resource-loader.ts\";\nexport { DefaultResourceLoader, loadProjectContextFiles } from \"./core/resource-loader.ts\";\n// SDK for programmatic usage\nexport {\n\tAgentSessionRuntime,\n\ttype AgentSessionRuntimeDiagnostic,\n\ttype AgentSessionServices,\n\ttype CreateAgentSessionFromServicesOptions,\n\ttype CreateAgentSessionOptions,\n\ttype CreateAgentSessionResult,\n\ttype CreateAgentSessionRuntimeFactory,\n\ttype CreateAgentSessionRuntimeResult,\n\ttype CreateAgentSessionServicesOptions,\n\t// Factory\n\tcreateAgentSession,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionRuntime,\n\tcreateAgentSessionServices,\n\tcreateBashTool,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype PromptTemplate,\n} from \"./core/sdk.ts\";\nexport {\n\ttype BranchSummaryEntry,\n\tbuildContextEntries,\n\tbuildSessionContext,\n\ttype CompactionEntry,\n\tCURRENT_SESSION_VERSION,\n\ttype CustomEntry,\n\ttype CustomMessageEntry,\n\ttype FileEntry,\n\tgetLatestCompactionEntry,\n\ttype ModelChangeEntry,\n\tmigrateSessionEntries,\n\ttype NewSessionOptions,\n\tparseSessionEntries,\n\ttype SessionContext,\n\ttype SessionEntry,\n\ttype SessionEntryBase,\n\ttype SessionHeader,\n\ttype SessionInfo,\n\ttype SessionInfoEntry,\n\tSessionManager,\n\ttype SessionMessageEntry,\n\ttype SessionTreeNode,\n\tsessionEntryToContextMessages,\n\ttype ThinkingLevelChangeEntry,\n} from \"./core/session-manager.ts\";\nexport {\n\ttype CompactionSettings,\n\ttype DefaultProjectTrust,\n\ttype ImageSettings,\n\ttype PackageSource,\n\ttype RetrySettings,\n\tSettingsManager,\n\ttype SettingsManagerCreateOptions,\n} from \"./core/settings-manager.ts\";\n// Skills\nexport {\n\tformatSkillsForPrompt,\n\ttype LoadSkillsFromDirOptions,\n\ttype LoadSkillsResult,\n\tloadSkills,\n\tloadSkillsFromDir,\n\ttype Skill,\n\ttype SkillFrontmatter,\n} from \"./core/skills.ts\";\nexport { createSyntheticSourceInfo } from \"./core/source-info.ts\";\nexport { type EditDiffResult, generateDiffString, generateUnifiedPatch } from \"./core/tools/edit-diff.ts\";\n// Tools\nexport {\n\ttype BashOperations,\n\ttype BashSpawnContext,\n\ttype BashSpawnHook,\n\ttype BashToolDetails,\n\ttype BashToolInput,\n\ttype BashToolOptions,\n\tcreateBashToolDefinition,\n\tcreateEditToolDefinition,\n\tcreateFindToolDefinition,\n\tcreateGrepToolDefinition,\n\tcreateLocalBashOperations,\n\tcreateLsToolDefinition,\n\tcreateReadToolDefinition,\n\tcreateWriteToolDefinition,\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\ttype EditOperations,\n\ttype EditToolDetails,\n\ttype EditToolInput,\n\ttype EditToolOptions,\n\ttype FindOperations,\n\ttype FindToolDetails,\n\ttype FindToolInput,\n\ttype FindToolOptions,\n\tformatSize,\n\ttype GrepOperations,\n\ttype GrepToolDetails,\n\ttype GrepToolInput,\n\ttype GrepToolOptions,\n\ttype LsOperations,\n\ttype LsToolDetails,\n\ttype LsToolInput,\n\ttype LsToolOptions,\n\ttype ReadOperations,\n\ttype ReadToolDetails,\n\ttype ReadToolInput,\n\ttype ReadToolOptions,\n\ttype ToolsOptions,\n\ttype TruncationOptions,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n\ttruncateTail,\n\ttype WriteOperations,\n\ttype WriteToolInput,\n\ttype WriteToolOptions,\n\twithFileMutationQueue,\n} from \"./core/tools/index.ts\";\nexport {\n\thasTrustRequiringProjectResources,\n\ttype ProjectTrustDecision,\n\tProjectTrustStore,\n\ttype ProjectTrustStoreEntry,\n\ttype ProjectTrustUpdate,\n} from \"./core/trust-manager.ts\";\n// Main entry point\nexport { type MainOptions, main } from \"./main.ts\";\n// Run modes for programmatic SDK usage\nexport {\n\tInteractiveMode,\n\ttype InteractiveModeOptions,\n\ttype ModelInfo,\n\ttype PrintModeOptions,\n\tRpcClient,\n\ttype RpcClientOptions,\n\ttype RpcCommand,\n\ttype RpcEventListener,\n\ttype RpcExtensionUIRequest,\n\ttype RpcExtensionUIResponse,\n\ttype RpcResponse,\n\ttype RpcSessionState,\n\trunPrintMode,\n\trunRpcMode,\n} from \"./modes/index.ts\";\n// UI components for extensions\nexport {\n\tArminComponent,\n\tAssistantMessageComponent,\n\tBashExecutionComponent,\n\tBorderedLoader,\n\tBranchSummaryMessageComponent,\n\tCompactionSummaryMessageComponent,\n\tCustomEditor,\n\tCustomMessageComponent,\n\tDynamicBorder,\n\tExtensionEditorComponent,\n\tExtensionInputComponent,\n\tExtensionSelectorComponent,\n\tFooterComponent,\n\tkeyHint,\n\tkeyText,\n\tLoginDialogComponent,\n\tModelSelectorComponent,\n\tOAuthSelectorComponent,\n\ttype RenderDiffOptions,\n\trawKeyHint,\n\trenderDiff,\n\tSessionSelectorComponent,\n\ttype SettingsCallbacks,\n\ttype SettingsConfig,\n\tSettingsSelectorComponent,\n\tShowImagesSelectorComponent,\n\tSkillInvocationMessageComponent,\n\tThemeSelectorComponent,\n\tThinkingSelectorComponent,\n\tToolExecutionComponent,\n\ttype ToolExecutionOptions,\n\tTreeSelectorComponent,\n\ttruncateToVisualLines,\n\tUserMessageComponent,\n\tUserMessageSelectorComponent,\n\ttype VisualTruncateResult,\n} from \"./modes/interactive/components/index.ts\";\n// Theme utilities for custom tools and extensions\nexport {\n\tgetLanguageFromPath,\n\tgetMarkdownTheme,\n\tgetSelectListTheme,\n\tgetSettingsListTheme,\n\thighlightCode,\n\tinitTheme,\n\tTheme,\n\ttype ThemeColor,\n} from \"./modes/interactive/theme/theme.ts\";\n// Clipboard utilities\nexport { copyToClipboard } from \"./utils/clipboard.ts\";\nexport { parseFrontmatter, stripFrontmatter } from \"./utils/frontmatter.ts\";\nexport { convertToPng } from \"./utils/image-convert.ts\";\nexport { formatDimensionNote, type ResizedImage, resizeImage } from \"./utils/image-resize.ts\";\n// Shell utilities\nexport { getShellConfig } from \"./utils/shell.ts\";\n"]} \ No newline at end of file diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..a2ee192 --- /dev/null +++ b/dist/index.js @@ -0,0 +1,47 @@ +// Core session management +export { parseArgs } from "./cli/args.js"; +// Config paths +export { CONFIG_DIR_NAME, getAgentDir, getDocsPath, getExamplesPath, getPackageDir, getReadmePath, VERSION, } from "./config.js"; +export { AgentSession, parseSkillBlock, } from "./core/agent-session.js"; +export { readStoredCredential } from "./core/auth-storage.js"; +// Compaction +export { calculateContextTokens, collectEntriesForBranchSummary, compact, DEFAULT_COMPACTION_SETTINGS, estimateTokens, findCutPoint, findTurnStartIndex, generateBranchSummary, generateSummary, generateSummaryWithUsage, getLastAssistantUsage, prepareBranchEntries, serializeConversation, shouldCompact, } from "./core/compaction/index.js"; +export { createEventBus } from "./core/event-bus.js"; +export { createExtensionRuntime, defineTool, discoverAndLoadExtensions, ExtensionRunner, isBashToolResult, isEditToolResult, isFindToolResult, isGrepToolResult, isLsToolResult, isReadToolResult, isToolCallEventType, isWriteToolResult, wrapRegisteredTool, wrapRegisteredTools, } from "./core/extensions/index.js"; +export { convertToLlm } from "./core/messages.js"; +export { ModelRegistry } from "./core/model-registry.js"; +export { resolveCliModel, resolveModelScopeWithDiagnostics, } from "./core/model-resolver.js"; +export { ModelRuntime, } from "./core/model-runtime.js"; +export { DefaultPackageManager } from "./core/package-manager.js"; +export { DefaultResourceLoader, loadProjectContextFiles } from "./core/resource-loader.js"; +// SDK for programmatic usage +export { AgentSessionRuntime, +// Factory +createAgentSession, createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createBashTool, +// Tool factories (for custom cwd) +createCodingTools, createEditTool, createFindTool, createGrepTool, createLsTool, createReadOnlyTools, createReadTool, createWriteTool, } from "./core/sdk.js"; +export { buildContextEntries, buildSessionContext, CURRENT_SESSION_VERSION, getLatestCompactionEntry, migrateSessionEntries, parseSessionEntries, SessionManager, sessionEntryToContextMessages, } from "./core/session-manager.js"; +export { SettingsManager, } from "./core/settings-manager.js"; +// Skills +export { formatSkillsForPrompt, loadSkills, loadSkillsFromDir, } from "./core/skills.js"; +export { createSyntheticSourceInfo } from "./core/source-info.js"; +export { generateDiffString, generateUnifiedPatch } from "./core/tools/edit-diff.js"; +// Tools +export { createBashToolDefinition, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLocalBashOperations, createLsToolDefinition, createReadToolDefinition, createWriteToolDefinition, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead, truncateLine, truncateTail, withFileMutationQueue, } from "./core/tools/index.js"; +export { hasTrustRequiringProjectResources, ProjectTrustStore, } from "./core/trust-manager.js"; +// Main entry point +export { main } from "./main.js"; +// Run modes for programmatic SDK usage +export { InteractiveMode, RpcClient, runPrintMode, runRpcMode, } from "./modes/index.js"; +// UI components for extensions +export { ArminComponent, AssistantMessageComponent, BashExecutionComponent, BorderedLoader, BranchSummaryMessageComponent, CompactionSummaryMessageComponent, CustomEditor, CustomMessageComponent, DynamicBorder, ExtensionEditorComponent, ExtensionInputComponent, ExtensionSelectorComponent, FooterComponent, keyHint, keyText, LoginDialogComponent, ModelSelectorComponent, OAuthSelectorComponent, rawKeyHint, renderDiff, SessionSelectorComponent, SettingsSelectorComponent, ShowImagesSelectorComponent, SkillInvocationMessageComponent, ThemeSelectorComponent, ThinkingSelectorComponent, ToolExecutionComponent, TreeSelectorComponent, truncateToVisualLines, UserMessageComponent, UserMessageSelectorComponent, } from "./modes/interactive/components/index.js"; +// Theme utilities for custom tools and extensions +export { getLanguageFromPath, getMarkdownTheme, getSelectListTheme, getSettingsListTheme, highlightCode, initTheme, Theme, } from "./modes/interactive/theme/theme.js"; +// Clipboard utilities +export { copyToClipboard } from "./utils/clipboard.js"; +export { parseFrontmatter, stripFrontmatter } from "./utils/frontmatter.js"; +export { convertToPng } from "./utils/image-convert.js"; +export { formatDimensionNote, resizeImage } from "./utils/image-resize.js"; +// Shell utilities +export { getShellConfig } from "./utils/shell.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map new file mode 100644 index 0000000..65cfb30 --- /dev/null +++ b/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,0BAA0B;AAE1B,OAAO,EAAa,SAAS,EAAE,MAAM,eAAe,CAAC;AAErD,eAAe;AACf,OAAO,EACN,eAAe,EACf,WAAW,EACX,WAAW,EACX,eAAe,EACf,aAAa,EACb,aAAa,EACb,OAAO,GACP,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,YAAY,EAOZ,eAAe,GAEf,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,aAAa;AACb,OAAO,EAMN,sBAAsB,EACtB,8BAA8B,EAC9B,OAAO,EACP,2BAA2B,EAC3B,cAAc,EAEd,YAAY,EACZ,kBAAkB,EAElB,qBAAqB,EACrB,eAAe,EACf,wBAAwB,EACxB,qBAAqB,EACrB,oBAAoB,EACpB,qBAAqB,EACrB,aAAa,GACb,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,cAAc,EAA0C,MAAM,qBAAqB,CAAC;AAmG7F,OAAO,EACN,sBAAsB,EACtB,UAAU,EACV,yBAAyB,EACzB,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,EACjB,kBAAkB,EAClB,mBAAmB,GACnB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAIN,eAAe,EACf,gCAAgC,GAEhC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAEN,YAAY,GAEZ,MAAM,yBAAyB,CAAC;AASjC,OAAO,EAAE,qBAAq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Z,UAAU,GACV,MAAM,kBAAkB,CAAC;AAC1B,+BAA+B;AAC/B,OAAO,EACN,cAAc,EACd,yBAAyB,EACzB,sBAAsB,EACtB,cAAc,EACd,6BAA6B,EAC7B,iCAAiC,EACjC,YAAY,EACZ,sBAAsB,EACtB,aAAa,EACb,wBAAwB,EACxB,uBAAuB,EACvB,0BAA0B,EAC1B,eAAe,EACf,OAAO,EACP,OAAO,EACP,oBAAoB,EACpB,sBAAsB,EACtB,sBAAsB,EAEtB,UAAU,EACV,UAAU,EACV,wBAAwB,EAGxB,yBAAyB,EACzB,2BAA2B,EAC3B,+BAA+B,EAC/B,sBAAsB,EACtB,yBAAyB,EACzB,sBAAsB,EAEtB,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,4BAA4B,GAE5B,MAAM,yCAAyC,CAAC;AACjD,kDAAkD;AAClD,OAAO,EACN,mBAAmB,EACnB,gBAAgB,EAChB,kBAAkB,EAClB,oBAAoB,EACpB,aAAa,EACb,SAAS,EACT,KAAK,GAEL,MAAM,oCAAoC,CAAC;AAC5C,sBAAsB;AACtB,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC5E,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAqB,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAC9F,kBAAkB;AAClB,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["// Core session management\n\nexport { type Args, parseArgs } from \"./cli/args.ts\";\n\n// Config paths\nexport {\n\tCONFIG_DIR_NAME,\n\tgetAgentDir,\n\tgetDocsPath,\n\tgetExamplesPath,\n\tgetPackageDir,\n\tgetReadmePath,\n\tVERSION,\n} from \"./config.ts\";\nexport {\n\tAgentSession,\n\ttype AgentSessionConfig,\n\ttype AgentSessionEvent,\n\ttype AgentSessionEventListener,\n\ttype ModelCycleResult,\n\ttype ParsedSkillBlock,\n\ttype PromptOptions,\n\tparseSkillBlock,\n\ttype SessionStats,\n} from \"./core/agent-session.ts\";\nexport { readStoredCredential } from \"./core/auth-storage.ts\";\n// Compaction\nexport {\n\ttype BranchPreparation,\n\ttype BranchSummaryResult,\n\ttype CollectEntriesResult,\n\ttype CompactionResult,\n\ttype CutPointResult,\n\tcalculateContextTokens,\n\tcollectEntriesForBranchSummary,\n\tcompact,\n\tDEFAULT_COMPACTION_SETTINGS,\n\testimateTokens,\n\ttype FileOperations,\n\tfindCutPoint,\n\tfindTurnStartIndex,\n\ttype GenerateBranchSummaryOptions,\n\tgenerateBranchSummary,\n\tgenerateSummary,\n\tgenerateSummaryWithUsage,\n\tgetLastAssistantUsage,\n\tprepareBranchEntries,\n\tserializeConversation,\n\tshouldCompact,\n} from \"./core/compaction/index.ts\";\nexport { createEventBus, type EventBus, type EventBusController } from \"./core/event-bus.ts\";\n// Extension system\nexport type {\n\tAgentEndEvent,\n\tAgentSettledEvent,\n\tAgentStartEvent,\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n\tAppKeybinding,\n\tAutocompleteProviderFactory,\n\tBashToolCallEvent,\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tBeforeProviderHeadersEvent,\n\tBeforeProviderRequestEvent,\n\tBeforeProviderRequestEventResult,\n\tBuildSystemPromptOptions,\n\tCompactOptions,\n\tContextEvent,\n\tContextUsage,\n\tCustomToolCallEvent,\n\tEditToolCallEvent,\n\tEntryRenderer,\n\tEntryRenderOptions,\n\tExecOptions,\n\tExecResult,\n\tExtension,\n\tExtensionActions,\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFactory,\n\tExtensionFlag,\n\tExtensionHandler,\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tFindToolCallEvent,\n\tGrepToolCallEvent,\n\tInlineExtension,\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tKeybindingsManager,\n\tLoadExtensionsResult,\n\tLsToolCallEvent,\n\tMessageEndEvent,\n\tMessageRenderer,\n\tMessageRenderOptions,\n\tMessageStartEvent,\n\tMessageUpdateEvent,\n\tProjectTrustContext,\n\tProjectTrustEvent,\n\tProjectTrustEventDecision,\n\tProjectTrustEventResult,\n\tProjectTrustHandler,\n\tProviderConfig,\n\tProviderModelConfig,\n\tReadToolCallEvent,\n\tRegisteredCommand,\n\tRegisteredTool,\n\tResolvedCommand,\n\tSessionBeforeCompactEvent,\n\tSessionBeforeForkEvent,\n\tSessionBeforeSwitchEvent,\n\tSessionBeforeTreeEvent,\n\tSessionCompactEvent,\n\tSessionInfoChangedEvent,\n\tSessionShutdownEvent,\n\tSessionStartEvent,\n\tSessionTreeEvent,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tSourceInfo,\n\tTerminalInputHandler,\n\tToolCallEvent,\n\tToolCallEventResult,\n\tToolDefinition,\n\tToolExecutionEndEvent,\n\tToolExecutionMode,\n\tToolExecutionStartEvent,\n\tToolExecutionUpdateEvent,\n\tToolInfo,\n\tToolRenderResultOptions,\n\tToolResultEvent,\n\tTurnEndEvent,\n\tTurnStartEvent,\n\tUserBashEvent,\n\tUserBashEventResult,\n\tWidgetPlacement,\n\tWorkingIndicatorOptions,\n\tWriteToolCallEvent,\n} from \"./core/extensions/index.ts\";\nexport {\n\tcreateExtensionRuntime,\n\tdefineTool,\n\tdiscoverAndLoadExtensions,\n\tExtensionRunner,\n\tisBashToolResult,\n\tisEditToolResult,\n\tisFindToolResult,\n\tisGrepToolResult,\n\tisLsToolResult,\n\tisReadToolResult,\n\tisToolCallEventType,\n\tisWriteToolResult,\n\twrapRegisteredTool,\n\twrapRegisteredTools,\n} from \"./core/extensions/index.ts\";\n// Footer data provider (git branch + extension statuses - data not otherwise available to extensions)\nexport type { ReadonlyFooterDataProvider } from \"./core/footer-data-provider.ts\";\nexport { convertToLlm } from \"./core/messages.ts\";\nexport { ModelRegistry } from \"./core/model-registry.ts\";\nexport {\n\ttype ModelScopeDiagnostic,\n\ttype ResolveCliModelResult,\n\ttype ResolveModelScopeResult,\n\tresolveCliModel,\n\tresolveModelScopeWithDiagnostics,\n\ttype ScopedModel,\n} from \"./core/model-resolver.ts\";\nexport {\n\ttype CreateModelRuntimeOptions,\n\tModelRuntime,\n\ttype ModelRuntimeAuthOverrides,\n} from \"./core/model-runtime.ts\";\nexport type {\n\tPackageManager,\n\tPathMetadata,\n\tProgressCallback,\n\tProgressEvent,\n\tResolvedPaths,\n\tResolvedResource,\n} from \"./core/package-manager.ts\";\nexport { DefaultPackageManager } from \"./core/package-manager.ts\";\nexport type { ResourceCollision, ResourceDiagnostic, ResourceLoader } from \"./core/resource-loader.ts\";\nexport { DefaultResourceLoader, loadProjectContextFiles } from \"./core/resource-loader.ts\";\n// SDK for programmatic usage\nexport {\n\tAgentSessionRuntime,\n\ttype AgentSessionRuntimeDiagnostic,\n\ttype AgentSessionServices,\n\ttype CreateAgentSessionFromServicesOptions,\n\ttype CreateAgentSessionOptions,\n\ttype CreateAgentSessionResult,\n\ttype CreateAgentSessionRuntimeFactory,\n\ttype CreateAgentSessionRuntimeResult,\n\ttype CreateAgentSessionServicesOptions,\n\t// Factory\n\tcreateAgentSession,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionRuntime,\n\tcreateAgentSessionServices,\n\tcreateBashTool,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\ttype PromptTemplate,\n} from \"./core/sdk.ts\";\nexport {\n\ttype BranchSummaryEntry,\n\tbuildContextEntries,\n\tbuildSessionContext,\n\ttype CompactionEntry,\n\tCURRENT_SESSION_VERSION,\n\ttype CustomEntry,\n\ttype CustomMessageEntry,\n\ttype FileEntry,\n\tgetLatestCompactionEntry,\n\ttype ModelChangeEntry,\n\tmigrateSessionEntries,\n\ttype NewSessionOptions,\n\tparseSessionEntries,\n\ttype SessionContext,\n\ttype SessionEntry,\n\ttype SessionEntryBase,\n\ttype SessionHeader,\n\ttype SessionInfo,\n\ttype SessionInfoEntry,\n\tSessionManager,\n\ttype SessionMessageEntry,\n\ttype SessionTreeNode,\n\tsessionEntryToContextMessages,\n\ttype ThinkingLevelChangeEntry,\n} from \"./core/session-manager.ts\";\nexport {\n\ttype CompactionSettings,\n\ttype DefaultProjectTrust,\n\ttype ImageSettings,\n\ttype PackageSource,\n\ttype RetrySettings,\n\tSettingsManager,\n\ttype SettingsManagerCreateOptions,\n} from \"./core/settings-manager.ts\";\n// Skills\nexport {\n\tformatSkillsForPrompt,\n\ttype LoadSkillsFromDirOptions,\n\ttype LoadSkillsResult,\n\tloadSkills,\n\tloadSkillsFromDir,\n\ttype Skill,\n\ttype SkillFrontmatter,\n} from \"./core/skills.ts\";\nexport { createSyntheticSourceInfo } from \"./core/source-info.ts\";\nexport { type EditDiffResult, generateDiffString, generateUnifiedPatch } from \"./core/tools/edit-diff.ts\";\n// Tools\nexport {\n\ttype BashOperations,\n\ttype BashSpawnContext,\n\ttype BashSpawnHook,\n\ttype BashToolDetails,\n\ttype BashToolInput,\n\ttype BashToolOptions,\n\tcreateBashToolDefinition,\n\tcreateEditToolDefinition,\n\tcreateFindToolDefinition,\n\tcreateGrepToolDefinition,\n\tcreateLocalBashOperations,\n\tcreateLsToolDefinition,\n\tcreateReadToolDefinition,\n\tcreateWriteToolDefinition,\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\ttype EditOperations,\n\ttype EditToolDetails,\n\ttype EditToolInput,\n\ttype EditToolOptions,\n\ttype FindOperations,\n\ttype FindToolDetails,\n\ttype FindToolInput,\n\ttype FindToolOptions,\n\tformatSize,\n\ttype GrepOperations,\n\ttype GrepToolDetails,\n\ttype GrepToolInput,\n\ttype GrepToolOptions,\n\ttype LsOperations,\n\ttype LsToolDetails,\n\ttype LsToolInput,\n\ttype LsToolOptions,\n\ttype ReadOperations,\n\ttype ReadToolDetails,\n\ttype ReadToolInput,\n\ttype ReadToolOptions,\n\ttype ToolsOptions,\n\ttype TruncationOptions,\n\ttype TruncationResult,\n\ttruncateHead,\n\ttruncateLine,\n\ttruncateTail,\n\ttype WriteOperations,\n\ttype WriteToolInput,\n\ttype WriteToolOptions,\n\twithFileMutationQueue,\n} from \"./core/tools/index.ts\";\nexport {\n\thasTrustRequiringProjectResources,\n\ttype ProjectTrustDecision,\n\tProjectTrustStore,\n\ttype ProjectTrustStoreEntry,\n\ttype ProjectTrustUpdate,\n} from \"./core/trust-manager.ts\";\n// Main entry point\nexport { type MainOptions, main } from \"./main.ts\";\n// Run modes for programmatic SDK usage\nexport {\n\tInteractiveMode,\n\ttype InteractiveModeOptions,\n\ttype ModelInfo,\n\ttype PrintModeOptions,\n\tRpcClient,\n\ttype RpcClientOptions,\n\ttype RpcCommand,\n\ttype RpcEventListener,\n\ttype RpcExtensionUIRequest,\n\ttype RpcExtensionUIResponse,\n\ttype RpcResponse,\n\ttype RpcSessionState,\n\trunPrintMode,\n\trunRpcMode,\n} from \"./modes/index.ts\";\n// UI components for extensions\nexport {\n\tArminComponent,\n\tAssistantMessageComponent,\n\tBashExecutionComponent,\n\tBorderedLoader,\n\tBranchSummaryMessageComponent,\n\tCompactionSummaryMessageComponent,\n\tCustomEditor,\n\tCustomMessageComponent,\n\tDynamicBorder,\n\tExtensionEditorComponent,\n\tExtensionInputComponent,\n\tExtensionSelectorComponent,\n\tFooterComponent,\n\tkeyHint,\n\tkeyText,\n\tLoginDialogComponent,\n\tModelSelectorComponent,\n\tOAuthSelectorComponent,\n\ttype RenderDiffOptions,\n\trawKeyHint,\n\trenderDiff,\n\tSessionSelectorComponent,\n\ttype SettingsCallbacks,\n\ttype SettingsConfig,\n\tSettingsSelectorComponent,\n\tShowImagesSelectorComponent,\n\tSkillInvocationMessageComponent,\n\tThemeSelectorComponent,\n\tThinkingSelectorComponent,\n\tToolExecutionComponent,\n\ttype ToolExecutionOptions,\n\tTreeSelectorComponent,\n\ttruncateToVisualLines,\n\tUserMessageComponent,\n\tUserMessageSelectorComponent,\n\ttype VisualTruncateResult,\n} from \"./modes/interactive/components/index.ts\";\n// Theme utilities for custom tools and extensions\nexport {\n\tgetLanguageFromPath,\n\tgetMarkdownTheme,\n\tgetSelectListTheme,\n\tgetSettingsListTheme,\n\thighlightCode,\n\tinitTheme,\n\tTheme,\n\ttype ThemeColor,\n} from \"./modes/interactive/theme/theme.ts\";\n// Clipboard utilities\nexport { copyToClipboard } from \"./utils/clipboard.ts\";\nexport { parseFrontmatter, stripFrontmatter } from \"./utils/frontmatter.ts\";\nexport { convertToPng } from \"./utils/image-convert.ts\";\nexport { formatDimensionNote, type ResizedImage, resizeImage } from \"./utils/image-resize.ts\";\n// Shell utilities\nexport { getShellConfig } from \"./utils/shell.ts\";\n"]} \ No newline at end of file diff --git a/dist/main.d.ts b/dist/main.d.ts new file mode 100644 index 0000000..8584839 --- /dev/null +++ b/dist/main.d.ts @@ -0,0 +1,12 @@ +/** + * Main entry point for the coding agent CLI. + * + * This file handles CLI argument parsing and translates them into + * createAgentSession() options. The SDK does the heavy lifting. + */ +import type { InlineExtension } from "./core/extensions/types.ts"; +export interface MainOptions { + extensionFactories?: InlineExtension[]; +} +export declare function main(args: string[], options?: MainOptions): Promise; +//# sourceMappingURL=main.d.ts.map \ No newline at end of file diff --git a/dist/main.d.ts.map b/dist/main.d.ts.map new file mode 100644 index 0000000..a6f3ba8 --- /dev/null +++ b/dist/main.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA8BH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAielE,MAAM,WAAW,WAAW;IAC3B,kBAAkB,CAAC,EAAE,eAAe,EAAE,CAAC;CACvC;AAED,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,WAAW,iBA2Y/D","sourcesContent":["/**\n * Main entry point for the coding agent CLI.\n *\n * This file handles CLI argument parsing and translates them into\n * createAgentSession() options. The SDK does the heavy lifting.\n */\n\nimport { createInterface } from \"node:readline\";\nimport { type ImageContent, modelsAreEqual } from \"@earendil-works/pi-ai\";\nimport chalk from \"chalk\";\nimport { type Args, type Mode, parseArgs, printHelp } from \"./cli/args.ts\";\nimport {\n\ttype CredentialPrintCommand,\n\tCredentialPrintError,\n\tisCredentialPrintHelp,\n\tparseCredentialPrintCommand,\n\tprintCredentialPrintHelp,\n\tresolveCredentialForPrint,\n\tvalidateCredentialPrintArgs,\n} from \"./cli/credential-print.ts\";\nimport { processFileArguments } from \"./cli/file-processor.ts\";\nimport { buildInitialMessage } from \"./cli/initial-message.ts\";\nimport { listModels } from \"./cli/list-models.ts\";\nimport { createProjectTrustContext } from \"./cli/project-trust.ts\";\nimport { selectSession } from \"./cli/session-picker.ts\";\nimport { shouldRunFirstTimeSetup, showFirstTimeSetup, showStartupSelector } from \"./cli/startup-ui.ts\";\nimport { ENV_SESSION_DIR, expandTildePath, getAgentDir, getPackageDir, VERSION } from \"./config.ts\";\nimport { type CreateAgentSessionRuntimeFactory, createAgentSessionRuntime } from \"./core/agent-session-runtime.ts\";\nimport {\n\ttype AgentSessionRuntimeDiagnostic,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionServices,\n} from \"./core/agent-session-services.ts\";\nimport { formatNoModelsAvailableMessage } from \"./core/auth-guidance.ts\";\nimport { exportFromFile } from \"./core/export-html/index.ts\";\nimport type { InlineExtension } from \"./core/extensions/types.ts\";\nimport { applyHttpProxySettings, configureHttpDispatcher } from \"./core/http-dispatcher.ts\";\nimport { resolveCliModel, resolveModelScope, type ScopedModel } from \"./core/model-resolver.ts\";\nimport { ModelRuntime } from \"./core/model-runtime.ts\";\nimport { restoreStdout, takeOverStdout } from \"./core/output-guard.ts\";\nimport { type AppMode, resolveProjectTrusted } from \"./core/project-trust.ts\";\nimport type { CreateAgentSessionOptions } from \"./core/sdk.ts\";\nimport {\n\tformatMissingSessionCwdPrompt,\n\tgetMissingSessionCwdIssue,\n\tMissingSessionCwdError,\n\ttype SessionCwdIssue,\n} from \"./core/session-cwd.ts\";\nimport { assertValidSessionId, SessionManager } from \"./core/session-manager.ts\";\nimport { SettingsManager } from \"./core/settings-manager.ts\";\nimport { printTimings, resetTimings, time } from \"./core/timings.ts\";\nimport { hasTrustRequiringProjectResources, ProjectTrustStore } from \"./core/trust-manager.ts\";\nimport { builtInExtensions } from \"./extensions/index.ts\";\nimport { runMigrations, showDeprecationWarnings } from \"./migrations.ts\";\nimport { InteractiveMode, runPrintMode, runRpcMode } from \"./modes/index.ts\";\nimport { initTheme, stopThemeWatcher } from \"./modes/interactive/theme/theme.ts\";\nimport { handleConfigCommand, handlePackageCommand } from \"./package-manager-cli.ts\";\nimport { isLocalPath, normalizePath, resolvePath } from \"./utils/paths.ts\";\nimport { cleanupWindowsSelfUpdateQuarantine } from \"./utils/windows-self-update.ts\";\n\nconst EXTENSION_LOAD_FAILURE_HINT = 'Hint: Start without extensions using \"pi -ne\".';\n\n/**\n * Read all content from piped stdin.\n * Returns undefined if stdin is a TTY (interactive terminal).\n */\nasync function readPipedStdin(): Promise {\n\t// If stdin is a TTY, we're running interactively - don't read stdin\n\tif (process.stdin.isTTY) {\n\t\treturn undefined;\n\t}\n\n\treturn new Promise((resolve) => {\n\t\tlet data = \"\";\n\t\tprocess.stdin.setEncoding(\"utf8\");\n\t\tprocess.stdin.on(\"data\", (chunk) => {\n\t\t\tdata += chunk;\n\t\t});\n\t\tprocess.stdin.on(\"end\", () => {\n\t\t\tresolve(data.trim() || undefined);\n\t\t});\n\t\tprocess.stdin.resume();\n\t});\n}\n\nfunction collectSettingsDiagnostics(\n\tsettingsManager: SettingsManager,\n\tcontext: string,\n): AgentSessionRuntimeDiagnostic[] {\n\treturn settingsManager.drainErrors().map(({ scope, error }) => ({\n\t\ttype: \"warning\",\n\t\tmessage: `(${context}, ${scope} settings) ${error.message}`,\n\t}));\n}\n\nfunction reportDiagnostics(diagnostics: readonly AgentSessionRuntimeDiagnostic[]): void {\n\tfor (const diagnostic of diagnostics) {\n\t\tconst color = diagnostic.type === \"error\" ? chalk.red : diagnostic.type === \"warning\" ? chalk.yellow : chalk.dim;\n\t\tconst prefix = diagnostic.type === \"error\" ? \"Error: \" : diagnostic.type === \"warning\" ? \"Warning: \" : \"\";\n\t\tconsole.error(color(`${prefix}${diagnostic.message}`));\n\t}\n}\n\nfunction isTruthyEnvFlag(value: string | undefined): boolean {\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\nfunction resolveAppMode(parsed: Args, stdinIsTTY: boolean, stdoutIsTTY: boolean): AppMode {\n\tif (parsed.mode === \"rpc\") {\n\t\treturn \"rpc\";\n\t}\n\tif (parsed.mode === \"json\") {\n\t\treturn \"json\";\n\t}\n\tif (parsed.print || !stdinIsTTY || !stdoutIsTTY) {\n\t\treturn \"print\";\n\t}\n\treturn \"interactive\";\n}\n\nfunction toPrintOutputMode(appMode: AppMode): Exclude {\n\treturn appMode === \"json\" ? \"json\" : \"text\";\n}\n\nfunction isPlainRuntimeMetadataCommand(parsed: Args): boolean {\n\treturn !parsed.print && parsed.mode === undefined && (parsed.help === true || parsed.listModels !== undefined);\n}\n\nasync function runCredentialPrintCommand(args: string[]): Promise {\n\tif (isCredentialPrintHelp(args)) {\n\t\tprintCredentialPrintHelp();\n\t\treturn true;\n\t}\n\n\tlet command: CredentialPrintCommand | undefined;\n\ttry {\n\t\tcommand = parseCredentialPrintCommand(args);\n\t} catch (error) {\n\t\tconst message = error instanceof CredentialPrintError ? error.message : \"Failed to parse auth command\";\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\tif (!command) return false;\n\n\tconst parsed = parseArgs(command.args);\n\tif (parsed.diagnostics.length > 0) {\n\t\tfor (const diagnostic of parsed.diagnostics) {\n\t\t\tconsole.error(chalk.red(`Error: ${diagnostic.message}`));\n\t\t}\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\n\ttry {\n\t\tvalidateCredentialPrintArgs(parsed);\n\t\tconst modelRuntime = await ModelRuntime.create({ allowModelNetwork: false });\n\t\tconst credential = await resolveCredentialForPrint(parsed, modelRuntime, command.kind, command.minExpiryMs);\n\t\tprocess.stdout.write(`${credential}\\n`);\n\t} catch (error) {\n\t\tconst message = error instanceof CredentialPrintError ? error.message : \"Failed to resolve credential\";\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exitCode = 1;\n\t}\n\treturn true;\n}\n\nasync function prepareInitialMessage(\n\tparsed: Args,\n\tautoResizeImages: boolean,\n\tstdinContent?: string,\n): Promise<{\n\tinitialMessage?: string;\n\tinitialImages?: ImageContent[];\n}> {\n\tif (parsed.fileArgs.length === 0) {\n\t\treturn buildInitialMessage({ parsed, stdinContent });\n\t}\n\n\tconst { text, images } = await processFileArguments(parsed.fileArgs, { autoResizeImages });\n\treturn buildInitialMessage({\n\t\tparsed,\n\t\tfileText: text,\n\t\tfileImages: images,\n\t\tstdinContent,\n\t});\n}\n\n/** Result from resolving a session argument */\ntype ResolvedSession =\n\t| { type: \"path\"; path: string } // Direct file path\n\t| { type: \"local\"; path: string } // Found in current project\n\t| { type: \"global\"; path: string; cwd: string } // Found in different project\n\t| { type: \"not_found\"; arg: string }; // Not found anywhere\n\n/**\n * Resolve a session argument to a file path.\n * If it looks like a path, use as-is. Otherwise try to match as session ID prefix.\n */\nasync function findLocalSessionByExactId(\n\tsessionId: string,\n\tcwd: string,\n\tsessionDir?: string,\n): Promise<{ type: \"local\"; path: string } | undefined> {\n\tconst localSessions = await SessionManager.list(cwd, sessionDir);\n\tconst localMatch = localSessions.find((s) => s.id === sessionId);\n\treturn localMatch ? { type: \"local\", path: localMatch.path } : undefined;\n}\n\nasync function resolveSessionPath(sessionArg: string, cwd: string, sessionDir?: string): Promise {\n\t// If it looks like a file path, resolve it before handing it to the session manager.\n\tif (sessionArg.includes(\"/\") || sessionArg.includes(\"\\\\\") || sessionArg.endsWith(\".jsonl\")) {\n\t\treturn { type: \"path\", path: resolvePath(sessionArg, cwd) };\n\t}\n\n\t// Try to match as session ID in current project first\n\tconst localSessions = await SessionManager.list(cwd, sessionDir);\n\tconst localMatch =\n\t\tlocalSessions.find((s) => s.id === sessionArg) ?? localSessions.find((s) => s.id.startsWith(sessionArg));\n\n\tif (localMatch) {\n\t\treturn { type: \"local\", path: localMatch.path };\n\t}\n\n\t// Try global search across all projects\n\tconst allSessions = await SessionManager.listAll(sessionDir);\n\tconst globalMatch =\n\t\tallSessions.find((s) => s.id === sessionArg) ?? allSessions.find((s) => s.id.startsWith(sessionArg));\n\n\tif (globalMatch) {\n\t\treturn { type: \"global\", path: globalMatch.path, cwd: globalMatch.cwd };\n\t}\n\n\t// Not found anywhere\n\treturn { type: \"not_found\", arg: sessionArg };\n}\n\n/** Prompt user for yes/no confirmation */\nasync function promptConfirm(message: string): Promise {\n\treturn new Promise((resolve) => {\n\t\tconst rl = createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t});\n\t\trl.question(`${message} [y/N] `, (answer) => {\n\t\t\trl.close();\n\t\t\tresolve(answer.toLowerCase() === \"y\" || answer.toLowerCase() === \"yes\");\n\t\t});\n\t});\n}\n\nfunction validateForkFlags(parsed: Args): void {\n\tif (!parsed.fork) return;\n\n\tconst conflictingFlags = [\n\t\tparsed.session ? \"--session\" : undefined,\n\t\tparsed.continue ? \"--continue\" : undefined,\n\t\tparsed.resume ? \"--resume\" : undefined,\n\t\tparsed.noSession ? \"--no-session\" : undefined,\n\t].filter((flag): flag is string => flag !== undefined);\n\n\tif (conflictingFlags.length > 0) {\n\t\tconsole.error(chalk.red(`Error: --fork cannot be combined with ${conflictingFlags.join(\", \")}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nfunction validateSessionIdFlags(parsed: Args): void {\n\tif (parsed.sessionId === undefined) return;\n\n\tconst conflictingFlags = [\n\t\tparsed.session ? \"--session\" : undefined,\n\t\tparsed.continue ? \"--continue\" : undefined,\n\t\tparsed.resume ? \"--resume\" : undefined,\n\t].filter((flag): flag is string => flag !== undefined);\n\n\tif (conflictingFlags.length > 0) {\n\t\tconsole.error(chalk.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(\", \")}`));\n\t\tprocess.exit(1);\n\t}\n\n\ttry {\n\t\tassertValidSessionId(parsed.sessionId);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nfunction openSessionOrExit(path: string, sessionDir?: string): SessionManager {\n\ttry {\n\t\treturn SessionManager.open(path, sessionDir);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nfunction forkSessionOrExit(sourcePath: string, cwd: string, sessionDir?: string, sessionId?: string): SessionManager {\n\ttry {\n\t\treturn SessionManager.forkFrom(sourcePath, cwd, sessionDir, { id: sessionId });\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nasync function createSessionManager(\n\tparsed: Args,\n\tcwd: string,\n\tsessionDir: string | undefined,\n\tsettingsManager: SettingsManager,\n): Promise {\n\tif (parsed.noSession || parsed.help || parsed.listModels !== undefined) {\n\t\treturn SessionManager.inMemory(cwd, parsed.sessionId !== undefined ? { id: parsed.sessionId } : undefined);\n\t}\n\n\tif (parsed.fork) {\n\t\tif (parsed.sessionId) {\n\t\t\tconst existingTarget = await findLocalSessionByExactId(parsed.sessionId, cwd, sessionDir);\n\t\t\tif (existingTarget) {\n\t\t\t\tconsole.error(chalk.red(`Session already exists with id '${parsed.sessionId}'`));\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t}\n\n\t\tconst resolved = await resolveSessionPath(parsed.fork, cwd, sessionDir);\n\n\t\tswitch (resolved.type) {\n\t\t\tcase \"path\":\n\t\t\tcase \"local\":\n\t\t\tcase \"global\":\n\t\t\t\treturn forkSessionOrExit(resolved.path, cwd, sessionDir, parsed.sessionId);\n\n\t\t\tcase \"not_found\":\n\t\t\t\tconsole.error(chalk.red(`No session found matching '${resolved.arg}'`));\n\t\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tif (parsed.session) {\n\t\tconst resolved = await resolveSessionPath(parsed.session, cwd, sessionDir);\n\n\t\tswitch (resolved.type) {\n\t\t\tcase \"path\":\n\t\t\tcase \"local\":\n\t\t\t\treturn openSessionOrExit(resolved.path, sessionDir);\n\n\t\t\tcase \"global\": {\n\t\t\t\tconsole.log(chalk.yellow(`Session found in different project: ${resolved.cwd}`));\n\t\t\t\tconst shouldFork = await promptConfirm(\"Fork this session into current directory?\");\n\t\t\t\tif (!shouldFork) {\n\t\t\t\t\tconsole.log(chalk.dim(\"Aborted.\"));\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t\treturn forkSessionOrExit(resolved.path, cwd, sessionDir);\n\t\t\t}\n\n\t\t\tcase \"not_found\":\n\t\t\t\tconsole.error(chalk.red(`No session found matching '${resolved.arg}'`));\n\t\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tif (parsed.resume) {\n\t\ttry {\n\t\t\tconst selectedPath = await selectSession(\n\t\t\t\t(onProgress) => SessionManager.list(cwd, sessionDir, onProgress),\n\t\t\t\t(onProgress) => SessionManager.listAll(sessionDir, onProgress),\n\t\t\t\tsettingsManager,\n\t\t\t);\n\t\t\tif (!selectedPath) {\n\t\t\t\tconsole.log(chalk.dim(\"No session selected\"));\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t\treturn SessionManager.open(selectedPath, sessionDir);\n\t\t} finally {\n\t\t\tstopThemeWatcher();\n\t\t}\n\t}\n\n\tif (parsed.continue) {\n\t\treturn SessionManager.continueRecent(cwd, sessionDir);\n\t}\n\n\tif (parsed.sessionId) {\n\t\tconst existingSession = await findLocalSessionByExactId(parsed.sessionId, cwd, sessionDir);\n\t\tif (existingSession) {\n\t\t\treturn SessionManager.open(existingSession.path, sessionDir);\n\t\t}\n\t\tconsole.error(\n\t\t\tchalk.yellow(\n\t\t\t\t`Warning: No project session found with id '${parsed.sessionId}'; creating a new session with that id.`,\n\t\t\t),\n\t\t);\n\t}\n\n\treturn SessionManager.create(cwd, sessionDir, { id: parsed.sessionId });\n}\n\nfunction buildSessionOptions(\n\tparsed: Args,\n\tscopedModels: ScopedModel[],\n\thasExistingSession: boolean,\n\tmodelRuntime: ModelRuntime,\n\tsettingsManager: SettingsManager,\n): {\n\toptions: CreateAgentSessionOptions;\n\tcliThinkingFromModel: boolean;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n} {\n\tconst options: CreateAgentSessionOptions = {};\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tlet cliThinkingFromModel = false;\n\n\t// Model from CLI\n\t// - supports --provider --model \n\t// - supports --model /\n\tif (parsed.model) {\n\t\tconst resolved = resolveCliModel({\n\t\t\tcliProvider: parsed.provider,\n\t\t\tcliModel: parsed.model,\n\t\t\tcliThinking: parsed.thinking,\n\t\t\tmodelRuntime,\n\t\t});\n\t\tif (resolved.warning) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: resolved.warning });\n\t\t}\n\t\tif (resolved.error) {\n\t\t\tdiagnostics.push({ type: \"error\", message: resolved.error });\n\t\t}\n\t\tif (resolved.model) {\n\t\t\toptions.model = resolved.model;\n\t\t\t// Allow \"--model :\" as a shorthand.\n\t\t\t// Explicit --thinking still takes precedence (applied later).\n\t\t\tif (!parsed.thinking && resolved.thinkingLevel) {\n\t\t\t\toptions.thinkingLevel = resolved.thinkingLevel;\n\t\t\t\tcliThinkingFromModel = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!options.model && scopedModels.length > 0 && !hasExistingSession) {\n\t\t// Check if saved default is in scoped models - use it if so, otherwise first scoped model\n\t\tconst savedProvider = settingsManager.getDefaultProvider();\n\t\tconst savedModelId = settingsManager.getDefaultModel();\n\t\tconst savedModel = savedProvider && savedModelId ? modelRuntime.getModel(savedProvider, savedModelId) : undefined;\n\t\tconst savedInScope = savedModel ? scopedModels.find((sm) => modelsAreEqual(sm.model, savedModel)) : undefined;\n\n\t\tif (savedInScope) {\n\t\t\toptions.model = savedInScope.model;\n\t\t\t// Use thinking level from scoped model config if explicitly set\n\t\t\tif (!parsed.thinking && savedInScope.thinkingLevel) {\n\t\t\t\toptions.thinkingLevel = savedInScope.thinkingLevel;\n\t\t\t}\n\t\t} else {\n\t\t\toptions.model = scopedModels[0].model;\n\t\t\t// Use thinking level from first scoped model if explicitly set\n\t\t\tif (!parsed.thinking && scopedModels[0].thinkingLevel) {\n\t\t\t\toptions.thinkingLevel = scopedModels[0].thinkingLevel;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Thinking level from CLI (takes precedence over scoped model thinking levels set above)\n\tif (parsed.thinking) {\n\t\toptions.thinkingLevel = parsed.thinking;\n\t}\n\n\t// Scoped models for Ctrl+P cycling\n\t// Keep thinking level undefined when not explicitly set in the model pattern.\n\t// Undefined means \"inherit current session thinking level\" during cycling.\n\tif (scopedModels.length > 0) {\n\t\toptions.scopedModels = scopedModels.map((sm) => ({\n\t\t\tmodel: sm.model,\n\t\t\tthinkingLevel: sm.thinkingLevel,\n\t\t}));\n\t}\n\n\t// API key from CLI - set as a non-persistent runtime override\n\t// (handled by caller before createAgentSession)\n\n\t// Tools\n\tif (parsed.noTools) {\n\t\toptions.noTools = \"all\";\n\t} else if (parsed.noBuiltinTools) {\n\t\toptions.noTools = \"builtin\";\n\t}\n\tif (parsed.tools) {\n\t\toptions.tools = [...parsed.tools];\n\t}\n\tif (parsed.excludeTools) {\n\t\toptions.excludeTools = [...parsed.excludeTools];\n\t}\n\n\treturn { options, cliThinkingFromModel, diagnostics };\n}\n\nfunction resolveCliPaths(cwd: string, paths: string[] | undefined): string[] | undefined {\n\treturn paths?.map((value) => (isLocalPath(value) ? resolvePath(value, cwd) : value));\n}\n\nasync function promptForMissingSessionCwd(\n\tissue: SessionCwdIssue,\n\tsettingsManager: SettingsManager,\n): Promise {\n\treturn showStartupSelector(settingsManager, formatMissingSessionCwdPrompt(issue), [\n\t\t{ label: \"Continue\", value: issue.fallbackCwd },\n\t\t{ label: \"Cancel\", value: undefined },\n\t]);\n}\n\nexport interface MainOptions {\n\textensionFactories?: InlineExtension[];\n}\n\nexport async function main(args: string[], options?: MainOptions) {\n\tresetTimings();\n\tconst extensionFactories = [...builtInExtensions, ...(options?.extensionFactories ?? [])];\n\tconst offlineMode = args.includes(\"--offline\") || isTruthyEnvFlag(process.env.PI_OFFLINE);\n\tif (offlineMode) {\n\t\tprocess.env.PI_OFFLINE = \"1\";\n\t\tprocess.env.PI_SKIP_VERSION_CHECK = \"1\";\n\t}\n\n\tif (process.platform === \"win32\") {\n\t\tcleanupWindowsSelfUpdateQuarantine(getPackageDir());\n\t}\n\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst bootstrapSettingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\tapplyHttpProxySettings(bootstrapSettingsManager.getGlobalSettings().httpProxy);\n\tconfigureHttpDispatcher();\n\n\tif (await handlePackageCommand(args, { extensionFactories })) {\n\t\tconst exitCode = process.exitCode ?? 0;\n\t\tif (process.platform === \"win32\" && exitCode === 0 && args[0] === \"update\") {\n\t\t\t// We normally prefer process.exit(0) for package commands so bad extensions cannot keep\n\t\t\t// one-shot commands alive. On Windows, Node can assert after fetch() if process.exit(0)\n\t\t\t// runs during teardown; let successful `pi update` drain naturally instead.\n\t\t\t// https://github.com/nodejs/node/issues/56645\n\t\t\treturn;\n\t\t}\n\t\tprocess.exit(exitCode);\n\t\treturn;\n\t}\n\n\tif (await handleConfigCommand(args, { extensionFactories })) {\n\t\treturn;\n\t}\n\n\tif (await runCredentialPrintCommand(args)) {\n\t\treturn;\n\t}\n\n\tconst parsed = parseArgs(args);\n\tif (parsed.diagnostics.length > 0) {\n\t\tfor (const d of parsed.diagnostics) {\n\t\t\tconst color = d.type === \"error\" ? chalk.red : chalk.yellow;\n\t\t\tconsole.error(color(`${d.type === \"error\" ? \"Error\" : \"Warning\"}: ${d.message}`));\n\t\t}\n\t\tif (parsed.diagnostics.some((d) => d.type === \"error\")) {\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\ttime(\"parseArgs\");\n\n\tif (parsed.version) {\n\t\tconsole.log(VERSION);\n\t\tprocess.exit(0);\n\t}\n\n\tif (parsed.export) {\n\t\tlet result: string;\n\t\ttry {\n\t\t\tconst outputPath = parsed.messages.length > 0 ? parsed.messages[0] : undefined;\n\t\t\tresult = await exportFromFile(parsed.export, outputPath);\n\t\t} catch (error: unknown) {\n\t\t\tconst message = error instanceof Error ? error.message : \"Failed to export session\";\n\t\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tconsole.log(`Exported to: ${result}`);\n\t\tprocess.exit(0);\n\t}\n\n\tlet appMode = resolveAppMode(parsed, process.stdin.isTTY, process.stdout.isTTY);\n\tconst shouldTakeOverStdout = appMode !== \"interactive\" && !isPlainRuntimeMetadataCommand(parsed);\n\tif (shouldTakeOverStdout) {\n\t\ttakeOverStdout();\n\t}\n\n\tif (parsed.mode === \"rpc\" && parsed.fileArgs.length > 0) {\n\t\tconsole.error(chalk.red(\"Error: @file arguments are not supported in RPC mode\"));\n\t\tprocess.exit(1);\n\t}\n\n\tvalidateForkFlags(parsed);\n\tvalidateSessionIdFlags(parsed);\n\n\t// Run migrations (pass cwd for project-local migrations)\n\tconst { migratedAuthProviders: migratedProviders, deprecationWarnings } = runMigrations(cwd);\n\ttime(\"runMigrations\");\n\n\tconst startupSettingsManager = SettingsManager.create(cwd, agentDir);\n\treportDiagnostics(collectSettingsDiagnostics(startupSettingsManager, \"startup session lookup\"));\n\n\t// Experimental first-time setup: theme choice and analytics opt-in.\n\t// Runs before any runtime services are created so the chosen settings apply everywhere.\n\tif (appMode === \"interactive\" && !parsed.help && parsed.listModels === undefined && shouldRunFirstTimeSetup()) {\n\t\tawait showFirstTimeSetup(startupSettingsManager);\n\t\ttime(\"firstTimeSetup\");\n\t}\n\n\t// Decide the final runtime cwd before creating cwd-bound runtime services.\n\t// --session and --resume may select a session from another project, so project-local\n\t// settings, resources, provider registrations, and models must be resolved only after\n\t// the target session cwd is known. The startup-cwd settings manager is used only for\n\t// sessionDir lookup during session selection.\n\tconst envSessionDir = process.env[ENV_SESSION_DIR];\n\tconst sessionDir =\n\t\t(parsed.sessionDir ? normalizePath(parsed.sessionDir) : undefined) ??\n\t\t(envSessionDir ? expandTildePath(envSessionDir) : undefined) ??\n\t\tstartupSettingsManager.getSessionDir();\n\tlet sessionManager = await createSessionManager(parsed, cwd, sessionDir, startupSettingsManager);\n\tconst missingSessionCwdIssue = getMissingSessionCwdIssue(sessionManager, cwd);\n\tif (missingSessionCwdIssue) {\n\t\tif (appMode === \"interactive\") {\n\t\t\tconst selectedCwd = await promptForMissingSessionCwd(missingSessionCwdIssue, startupSettingsManager);\n\t\t\tif (!selectedCwd) {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t\tsessionManager = SessionManager.open(missingSessionCwdIssue.sessionFile!, sessionDir, selectedCwd);\n\t\t} else {\n\t\t\tconsole.error(chalk.red(new MissingSessionCwdError(missingSessionCwdIssue).message));\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\tif (parsed.name !== undefined) {\n\t\tconst name = parsed.name.trim();\n\t\tif (!name) {\n\t\t\tconsole.error(chalk.red(\"Error: --name requires a non-empty value\"));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tsessionManager.appendSessionInfo(name);\n\t}\n\ttime(\"createSessionManager\");\n\n\tconst trustStore = new ProjectTrustStore(agentDir);\n\tconst sessionCwd = sessionManager.getCwd();\n\tconst autoTrustOnReloadCwd =\n\t\tparsed.projectTrustOverride === undefined && !hasTrustRequiringProjectResources(sessionCwd)\n\t\t\t? sessionCwd\n\t\t\t: undefined;\n\tconst trustPromptMode: AppMode = parsed.help || parsed.listModels !== undefined ? \"print\" : appMode;\n\tconst projectTrustByCwd = new Map();\n\n\tconst resolvedExtensionPaths = resolveCliPaths(cwd, parsed.extensions);\n\tconst resolvedSkillPaths = resolveCliPaths(cwd, parsed.skills);\n\tconst resolvedPromptTemplatePaths = resolveCliPaths(cwd, parsed.promptTemplates);\n\tconst resolvedThemePaths = resolveCliPaths(cwd, parsed.themes);\n\tconst createRuntime: CreateAgentSessionRuntimeFactory = async ({\n\t\tcwd,\n\t\tagentDir,\n\t\tsessionManager,\n\t\tsessionStartEvent,\n\t\tprojectTrustContext,\n\t}) => {\n\t\tconst isInitialRuntime = sessionStartEvent === undefined;\n\t\tconst projectTrustDiagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\t\tconst cachedProjectTrust = projectTrustByCwd.get(cwd);\n\t\tconst hasTrustRequiringResources = hasTrustRequiringProjectResources(cwd);\n\t\tconst shouldResolveProjectTrust =\n\t\t\tparsed.projectTrustOverride === undefined && cachedProjectTrust === undefined && hasTrustRequiringResources;\n\t\tconst projectTrusted = shouldResolveProjectTrust\n\t\t\t? false\n\t\t\t: (cachedProjectTrust ??\n\t\t\t\tparsed.projectTrustOverride ??\n\t\t\t\t(!hasTrustRequiringResources || trustStore.get(cwd) === true));\n\t\tconst runtimeSettingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted });\n\t\tconst services = await createAgentSessionServices({\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tsettingsManager: runtimeSettingsManager,\n\t\t\textensionFlagValues: parsed.unknownFlags,\n\t\t\tresourceLoaderReloadOptions: shouldResolveProjectTrust\n\t\t\t\t? {\n\t\t\t\t\t\tresolveProjectTrust: async ({ extensionsResult }) => {\n\t\t\t\t\t\t\tconst trusted = await resolveProjectTrusted({\n\t\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\t\ttrustStore,\n\t\t\t\t\t\t\t\ttrustOverride: parsed.projectTrustOverride,\n\t\t\t\t\t\t\t\tdefaultProjectTrust: startupSettingsManager.getDefaultProjectTrust(),\n\t\t\t\t\t\t\t\textensionsResult,\n\t\t\t\t\t\t\t\tprojectTrustContext:\n\t\t\t\t\t\t\t\t\tprojectTrustContext ??\n\t\t\t\t\t\t\t\t\tcreateProjectTrustContext({\n\t\t\t\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\t\t\t\tmode: isInitialRuntime ? trustPromptMode : appMode,\n\t\t\t\t\t\t\t\t\t\tsettingsManager: startupSettingsManager,\n\t\t\t\t\t\t\t\t\t\thasUI: isInitialRuntime && trustPromptMode === \"interactive\",\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tonExtensionError: (message) => projectTrustDiagnostics.push({ type: \"warning\", message }),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tprojectTrustByCwd.set(cwd, trusted);\n\t\t\t\t\t\t\treturn trusted;\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t\tresourceLoaderOptions: {\n\t\t\t\tadditionalExtensionPaths: resolvedExtensionPaths,\n\t\t\t\tadditionalSkillPaths: resolvedSkillPaths,\n\t\t\t\tadditionalPromptTemplatePaths: resolvedPromptTemplatePaths,\n\t\t\t\tadditionalThemePaths: resolvedThemePaths,\n\t\t\t\tnoExtensions: parsed.noExtensions,\n\t\t\t\tnoSkills: parsed.noSkills,\n\t\t\t\tnoPromptTemplates: parsed.noPromptTemplates,\n\t\t\t\tnoThemes: parsed.noThemes,\n\t\t\t\tnoContextFiles: parsed.noContextFiles,\n\t\t\t\tsystemPrompt: parsed.systemPrompt,\n\t\t\t\tappendSystemPrompt: parsed.appendSystemPrompt,\n\t\t\t\textensionFactories,\n\t\t\t},\n\t\t});\n\t\tconst { settingsManager, modelRuntime, resourceLoader } = services;\n\t\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [\n\t\t\t...projectTrustDiagnostics,\n\t\t\t...services.diagnostics,\n\t\t\t...collectSettingsDiagnostics(settingsManager, \"runtime creation\"),\n\t\t\t...resourceLoader.getExtensions().errors.map(({ path, error }) => ({\n\t\t\t\ttype: \"error\" as const,\n\t\t\t\tmessage: `Failed to load extension \"${path}\": ${error}`,\n\t\t\t})),\n\t\t];\n\n\t\tconst modelPatterns = parsed.models ?? settingsManager.getEnabledModels();\n\t\tconst scopedModels =\n\t\t\tmodelPatterns && modelPatterns.length > 0 ? await resolveModelScope(modelPatterns, modelRuntime) : [];\n\t\tconst {\n\t\t\toptions: sessionOptions,\n\t\t\tcliThinkingFromModel,\n\t\t\tdiagnostics: sessionOptionDiagnostics,\n\t\t} = buildSessionOptions(\n\t\t\tparsed,\n\t\t\tscopedModels,\n\t\t\tsessionManager.buildSessionContext().messages.length > 0,\n\t\t\tmodelRuntime,\n\t\t\tsettingsManager,\n\t\t);\n\t\tdiagnostics.push(...sessionOptionDiagnostics);\n\n\t\tif (parsed.apiKey) {\n\t\t\tif (!sessionOptions.model) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: \"--api-key requires a model to be specified via --model, --provider/--model, or --models\",\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tawait modelRuntime.setRuntimeApiKey(sessionOptions.model.provider, parsed.apiKey, { allowNetwork: false });\n\t\t\t\tawait services.modelRuntime.getAvailable();\n\t\t\t}\n\t\t}\n\n\t\tconst created = await createAgentSessionFromServices({\n\t\t\tservices,\n\t\t\tsessionManager,\n\t\t\tsessionStartEvent,\n\t\t\tmodel: sessionOptions.model,\n\t\t\tthinkingLevel: sessionOptions.thinkingLevel,\n\t\t\tscopedModels: sessionOptions.scopedModels,\n\t\t\ttools: sessionOptions.tools,\n\t\t\texcludeTools: sessionOptions.excludeTools,\n\t\t\tnoTools: sessionOptions.noTools,\n\t\t\tcustomTools: sessionOptions.customTools,\n\t\t});\n\t\tconst cliThinkingOverride = parsed.thinking !== undefined || cliThinkingFromModel;\n\t\tif (created.session.model && cliThinkingOverride) {\n\t\t\tcreated.session.setThinkingLevel(created.session.thinkingLevel);\n\t\t}\n\n\t\treturn {\n\t\t\t...created,\n\t\t\tservices,\n\t\t\tdiagnostics,\n\t\t};\n\t};\n\ttime(\"createRuntime\");\n\tconst runtime = await createAgentSessionRuntime(createRuntime, {\n\t\tcwd: sessionManager.getCwd(),\n\t\tagentDir,\n\t\tsessionManager,\n\t});\n\ttime(\"createAgentSessionRuntime\");\n\tconst { services, session, modelFallbackMessage } = runtime;\n\tconst { settingsManager, modelRuntime, resourceLoader } = services;\n\tapplyHttpProxySettings(settingsManager.getGlobalSettings().httpProxy);\n\tconfigureHttpDispatcher(settingsManager.getHttpIdleTimeoutMs());\n\n\tif (parsed.help) {\n\t\tconst extensionFlags = resourceLoader\n\t\t\t.getExtensions()\n\t\t\t.extensions.flatMap((extension) => Array.from(extension.flags.values()));\n\t\tprintHelp(extensionFlags);\n\t\tprocess.exit(0);\n\t}\n\n\tif (parsed.listModels !== undefined) {\n\t\tconst searchPattern = typeof parsed.listModels === \"string\" ? parsed.listModels : undefined;\n\t\tawait listModels(modelRuntime, searchPattern);\n\t\tprocess.exit(0);\n\t}\n\n\t// Read piped stdin content (if any) - skip for RPC mode which uses stdin for JSON-RPC\n\tlet stdinContent: string | undefined;\n\tif (appMode !== \"rpc\") {\n\t\tstdinContent = await readPipedStdin();\n\t\tif (stdinContent !== undefined && appMode === \"interactive\") {\n\t\t\tappMode = \"print\";\n\t\t}\n\t}\n\ttime(\"readPipedStdin\");\n\n\tconst { initialMessage, initialImages } = await prepareInitialMessage(\n\t\tparsed,\n\t\tsettingsManager.getImageAutoResize(),\n\t\tstdinContent,\n\t);\n\ttime(\"prepareInitialMessage\");\n\tinitTheme(settingsManager.getTheme(), appMode === \"interactive\");\n\ttime(\"initTheme\");\n\n\t// Show deprecation warnings in interactive mode\n\tif (appMode === \"interactive\" && deprecationWarnings.length > 0) {\n\t\tawait showDeprecationWarnings(deprecationWarnings);\n\t}\n\n\ttime(\"resolveModelScope\");\n\treportDiagnostics(runtime.diagnostics);\n\tif (runtime.diagnostics.some((diagnostic) => diagnostic.type === \"error\")) {\n\t\tif (runtime.diagnostics.some((diagnostic) => diagnostic.message.includes(\"Failed to load extension\"))) {\n\t\t\tconsole.error(chalk.yellow(EXTENSION_LOAD_FAILURE_HINT));\n\t\t}\n\t\tprocess.exit(1);\n\t}\n\ttime(\"createAgentSession\");\n\n\tif (appMode !== \"interactive\" && !session.model) {\n\t\tconsole.error(chalk.red(formatNoModelsAvailableMessage()));\n\t\tprocess.exit(1);\n\t}\n\n\tconst startupBenchmark = isTruthyEnvFlag(process.env.PI_STARTUP_BENCHMARK);\n\tif (startupBenchmark && appMode !== \"interactive\") {\n\t\tconsole.error(chalk.red(\"Error: PI_STARTUP_BENCHMARK only supports interactive mode\"));\n\t\tprocess.exit(1);\n\t}\n\n\t// RPC refreshes catalogs here in the background; interactive mode starts its refresh after TUI initialization.\n\tif (!offlineMode && appMode === \"rpc\") {\n\t\tvoid modelRuntime.refresh().catch(() => {});\n\t}\n\n\tif (appMode === \"rpc\") {\n\t\tprintTimings();\n\t\tawait runRpcMode(runtime);\n\t} else if (appMode === \"interactive\") {\n\t\tconst interactiveMode = new InteractiveMode(runtime, {\n\t\t\tmigratedProviders,\n\t\t\tmodelFallbackMessage,\n\t\t\tautoTrustOnReloadCwd,\n\t\t\tinitialMessage,\n\t\t\tinitialImages,\n\t\t\tinitialMessages: parsed.messages,\n\t\t\tverbose: parsed.verbose,\n\t\t});\n\t\tif (startupBenchmark) {\n\t\t\tawait interactiveMode.init();\n\t\t\ttime(\"interactiveMode.init\");\n\t\t\t// Give the TUI's stdin handler a brief chance to consume terminal query replies\n\t\t\t// (Kitty keyboard protocol, device attributes, cell size) before restoring the terminal.\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 150));\n\t\t\tinteractiveMode.stop();\n\t\t\tstopThemeWatcher();\n\t\t\tprintTimings();\n\t\t\tif (process.stdout.writableLength > 0) {\n\t\t\t\tawait new Promise((resolve) => process.stdout.once(\"drain\", resolve));\n\t\t\t}\n\t\t\tif (process.stderr.writableLength > 0) {\n\t\t\t\tawait new Promise((resolve) => process.stderr.once(\"drain\", resolve));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tprintTimings();\n\t\tawait interactiveMode.run();\n\t} else {\n\t\tprintTimings();\n\t\tconst exitCode = await runPrintMode(runtime, {\n\t\t\tmode: toPrintOutputMode(appMode),\n\t\t\tmessages: parsed.messages,\n\t\t\tinitialMessage,\n\t\t\tinitialImages,\n\t\t});\n\t\tstopThemeWatcher();\n\t\trestoreStdout();\n\t\tif (exitCode !== 0) {\n\t\t\tprocess.exitCode = exitCode;\n\t\t}\n\t\treturn;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/main.js b/dist/main.js new file mode 100644 index 0000000..0fefeba --- /dev/null +++ b/dist/main.js @@ -0,0 +1,747 @@ +/** + * Main entry point for the coding agent CLI. + * + * This file handles CLI argument parsing and translates them into + * createAgentSession() options. The SDK does the heavy lifting. + */ +import { createInterface } from "node:readline"; +import { modelsAreEqual } from "@earendil-works/pi-ai"; +import chalk from "chalk"; +import { parseArgs, printHelp } from "./cli/args.js"; +import { CredentialPrintError, isCredentialPrintHelp, parseCredentialPrintCommand, printCredentialPrintHelp, resolveCredentialForPrint, validateCredentialPrintArgs, } from "./cli/credential-print.js"; +import { processFileArguments } from "./cli/file-processor.js"; +import { buildInitialMessage } from "./cli/initial-message.js"; +import { listModels } from "./cli/list-models.js"; +import { createProjectTrustContext } from "./cli/project-trust.js"; +import { selectSession } from "./cli/session-picker.js"; +import { shouldRunFirstTimeSetup, showFirstTimeSetup, showStartupSelector } from "./cli/startup-ui.js"; +import { ENV_SESSION_DIR, expandTildePath, getAgentDir, getPackageDir, VERSION } from "./config.js"; +import { createAgentSessionRuntime } from "./core/agent-session-runtime.js"; +import { createAgentSessionFromServices, createAgentSessionServices, } from "./core/agent-session-services.js"; +import { formatNoModelsAvailableMessage } from "./core/auth-guidance.js"; +import { exportFromFile } from "./core/export-html/index.js"; +import { applyHttpProxySettings, configureHttpDispatcher } from "./core/http-dispatcher.js"; +import { resolveCliModel, resolveModelScope } from "./core/model-resolver.js"; +import { ModelRuntime } from "./core/model-runtime.js"; +import { restoreStdout, takeOverStdout } from "./core/output-guard.js"; +import { resolveProjectTrusted } from "./core/project-trust.js"; +import { formatMissingSessionCwdPrompt, getMissingSessionCwdIssue, MissingSessionCwdError, } from "./core/session-cwd.js"; +import { assertValidSessionId, SessionManager } from "./core/session-manager.js"; +import { SettingsManager } from "./core/settings-manager.js"; +import { printTimings, resetTimings, time } from "./core/timings.js"; +import { hasTrustRequiringProjectResources, ProjectTrustStore } from "./core/trust-manager.js"; +import { builtInExtensions } from "./extensions/index.js"; +import { runMigrations, showDeprecationWarnings } from "./migrations.js"; +import { InteractiveMode, runPrintMode, runRpcMode } from "./modes/index.js"; +import { initTheme, stopThemeWatcher } from "./modes/interactive/theme/theme.js"; +import { handleConfigCommand, handlePackageCommand } from "./package-manager-cli.js"; +import { isLocalPath, normalizePath, resolvePath } from "./utils/paths.js"; +import { cleanupWindowsSelfUpdateQuarantine } from "./utils/windows-self-update.js"; +const EXTENSION_LOAD_FAILURE_HINT = 'Hint: Start without extensions using "pi -ne".'; +/** + * Read all content from piped stdin. + * Returns undefined if stdin is a TTY (interactive terminal). + */ +async function readPipedStdin() { + // If stdin is a TTY, we're running interactively - don't read stdin + if (process.stdin.isTTY) { + return undefined; + } + return new Promise((resolve) => { + let data = ""; + process.stdin.setEncoding("utf8"); + process.stdin.on("data", (chunk) => { + data += chunk; + }); + process.stdin.on("end", () => { + resolve(data.trim() || undefined); + }); + process.stdin.resume(); + }); +} +function collectSettingsDiagnostics(settingsManager, context) { + return settingsManager.drainErrors().map(({ scope, error }) => ({ + type: "warning", + message: `(${context}, ${scope} settings) ${error.message}`, + })); +} +function reportDiagnostics(diagnostics) { + for (const diagnostic of diagnostics) { + const color = diagnostic.type === "error" ? chalk.red : diagnostic.type === "warning" ? chalk.yellow : chalk.dim; + const prefix = diagnostic.type === "error" ? "Error: " : diagnostic.type === "warning" ? "Warning: " : ""; + console.error(color(`${prefix}${diagnostic.message}`)); + } +} +function isTruthyEnvFlag(value) { + if (!value) + return false; + return value === "1" || value.toLowerCase() === "true" || value.toLowerCase() === "yes"; +} +function resolveAppMode(parsed, stdinIsTTY, stdoutIsTTY) { + if (parsed.mode === "rpc") { + return "rpc"; + } + if (parsed.mode === "json") { + return "json"; + } + if (parsed.print || !stdinIsTTY || !stdoutIsTTY) { + return "print"; + } + return "interactive"; +} +function toPrintOutputMode(appMode) { + return appMode === "json" ? "json" : "text"; +} +function isPlainRuntimeMetadataCommand(parsed) { + return !parsed.print && parsed.mode === undefined && (parsed.help === true || parsed.listModels !== undefined); +} +async function runCredentialPrintCommand(args) { + if (isCredentialPrintHelp(args)) { + printCredentialPrintHelp(); + return true; + } + let command; + try { + command = parseCredentialPrintCommand(args); + } + catch (error) { + const message = error instanceof CredentialPrintError ? error.message : "Failed to parse auth command"; + console.error(chalk.red(`Error: ${message}`)); + process.exitCode = 1; + return true; + } + if (!command) + return false; + const parsed = parseArgs(command.args); + if (parsed.diagnostics.length > 0) { + for (const diagnostic of parsed.diagnostics) { + console.error(chalk.red(`Error: ${diagnostic.message}`)); + } + process.exitCode = 1; + return true; + } + try { + validateCredentialPrintArgs(parsed); + const modelRuntime = await ModelRuntime.create({ allowModelNetwork: false }); + const credential = await resolveCredentialForPrint(parsed, modelRuntime, command.kind, command.minExpiryMs); + process.stdout.write(`${credential}\n`); + } + catch (error) { + const message = error instanceof CredentialPrintError ? error.message : "Failed to resolve credential"; + console.error(chalk.red(`Error: ${message}`)); + process.exitCode = 1; + } + return true; +} +async function prepareInitialMessage(parsed, autoResizeImages, stdinContent) { + if (parsed.fileArgs.length === 0) { + return buildInitialMessage({ parsed, stdinContent }); + } + const { text, images } = await processFileArguments(parsed.fileArgs, { autoResizeImages }); + return buildInitialMessage({ + parsed, + fileText: text, + fileImages: images, + stdinContent, + }); +} +/** + * Resolve a session argument to a file path. + * If it looks like a path, use as-is. Otherwise try to match as session ID prefix. + */ +async function findLocalSessionByExactId(sessionId, cwd, sessionDir) { + const localSessions = await SessionManager.list(cwd, sessionDir); + const localMatch = localSessions.find((s) => s.id === sessionId); + return localMatch ? { type: "local", path: localMatch.path } : undefined; +} +async function resolveSessionPath(sessionArg, cwd, sessionDir) { + // If it looks like a file path, resolve it before handing it to the session manager. + if (sessionArg.includes("/") || sessionArg.includes("\\") || sessionArg.endsWith(".jsonl")) { + return { type: "path", path: resolvePath(sessionArg, cwd) }; + } + // Try to match as session ID in current project first + const localSessions = await SessionManager.list(cwd, sessionDir); + const localMatch = localSessions.find((s) => s.id === sessionArg) ?? localSessions.find((s) => s.id.startsWith(sessionArg)); + if (localMatch) { + return { type: "local", path: localMatch.path }; + } + // Try global search across all projects + const allSessions = await SessionManager.listAll(sessionDir); + const globalMatch = allSessions.find((s) => s.id === sessionArg) ?? allSessions.find((s) => s.id.startsWith(sessionArg)); + if (globalMatch) { + return { type: "global", path: globalMatch.path, cwd: globalMatch.cwd }; + } + // Not found anywhere + return { type: "not_found", arg: sessionArg }; +} +/** Prompt user for yes/no confirmation */ +async function promptConfirm(message) { + return new Promise((resolve) => { + const rl = createInterface({ + input: process.stdin, + output: process.stdout, + }); + rl.question(`${message} [y/N] `, (answer) => { + rl.close(); + resolve(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes"); + }); + }); +} +function validateForkFlags(parsed) { + if (!parsed.fork) + return; + const conflictingFlags = [ + parsed.session ? "--session" : undefined, + parsed.continue ? "--continue" : undefined, + parsed.resume ? "--resume" : undefined, + parsed.noSession ? "--no-session" : undefined, + ].filter((flag) => flag !== undefined); + if (conflictingFlags.length > 0) { + console.error(chalk.red(`Error: --fork cannot be combined with ${conflictingFlags.join(", ")}`)); + process.exit(1); + } +} +function validateSessionIdFlags(parsed) { + if (parsed.sessionId === undefined) + return; + const conflictingFlags = [ + parsed.session ? "--session" : undefined, + parsed.continue ? "--continue" : undefined, + parsed.resume ? "--resume" : undefined, + ].filter((flag) => flag !== undefined); + if (conflictingFlags.length > 0) { + console.error(chalk.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(", ")}`)); + process.exit(1); + } + try { + assertValidSessionId(parsed.sessionId); + } + catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error(chalk.red(`Error: ${message}`)); + process.exit(1); + } +} +function openSessionOrExit(path, sessionDir) { + try { + return SessionManager.open(path, sessionDir); + } + catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error(chalk.red(`Error: ${message}`)); + process.exit(1); + } +} +function forkSessionOrExit(sourcePath, cwd, sessionDir, sessionId) { + try { + return SessionManager.forkFrom(sourcePath, cwd, sessionDir, { id: sessionId }); + } + catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error(chalk.red(`Error: ${message}`)); + process.exit(1); + } +} +async function createSessionManager(parsed, cwd, sessionDir, settingsManager) { + if (parsed.noSession || parsed.help || parsed.listModels !== undefined) { + return SessionManager.inMemory(cwd, parsed.sessionId !== undefined ? { id: parsed.sessionId } : undefined); + } + if (parsed.fork) { + if (parsed.sessionId) { + const existingTarget = await findLocalSessionByExactId(parsed.sessionId, cwd, sessionDir); + if (existingTarget) { + console.error(chalk.red(`Session already exists with id '${parsed.sessionId}'`)); + process.exit(1); + } + } + const resolved = await resolveSessionPath(parsed.fork, cwd, sessionDir); + switch (resolved.type) { + case "path": + case "local": + case "global": + return forkSessionOrExit(resolved.path, cwd, sessionDir, parsed.sessionId); + case "not_found": + console.error(chalk.red(`No session found matching '${resolved.arg}'`)); + process.exit(1); + } + } + if (parsed.session) { + const resolved = await resolveSessionPath(parsed.session, cwd, sessionDir); + switch (resolved.type) { + case "path": + case "local": + return openSessionOrExit(resolved.path, sessionDir); + case "global": { + console.log(chalk.yellow(`Session found in different project: ${resolved.cwd}`)); + const shouldFork = await promptConfirm("Fork this session into current directory?"); + if (!shouldFork) { + console.log(chalk.dim("Aborted.")); + process.exit(0); + } + return forkSessionOrExit(resolved.path, cwd, sessionDir); + } + case "not_found": + console.error(chalk.red(`No session found matching '${resolved.arg}'`)); + process.exit(1); + } + } + if (parsed.resume) { + try { + const selectedPath = await selectSession((onProgress) => SessionManager.list(cwd, sessionDir, onProgress), (onProgress) => SessionManager.listAll(sessionDir, onProgress), settingsManager); + if (!selectedPath) { + console.log(chalk.dim("No session selected")); + process.exit(0); + } + return SessionManager.open(selectedPath, sessionDir); + } + finally { + stopThemeWatcher(); + } + } + if (parsed.continue) { + return SessionManager.continueRecent(cwd, sessionDir); + } + if (parsed.sessionId) { + const existingSession = await findLocalSessionByExactId(parsed.sessionId, cwd, sessionDir); + if (existingSession) { + return SessionManager.open(existingSession.path, sessionDir); + } + console.error(chalk.yellow(`Warning: No project session found with id '${parsed.sessionId}'; creating a new session with that id.`)); + } + return SessionManager.create(cwd, sessionDir, { id: parsed.sessionId }); +} +function buildSessionOptions(parsed, scopedModels, hasExistingSession, modelRuntime, settingsManager) { + const options = {}; + const diagnostics = []; + let cliThinkingFromModel = false; + // Model from CLI + // - supports --provider --model + // - supports --model / + if (parsed.model) { + const resolved = resolveCliModel({ + cliProvider: parsed.provider, + cliModel: parsed.model, + cliThinking: parsed.thinking, + modelRuntime, + }); + if (resolved.warning) { + diagnostics.push({ type: "warning", message: resolved.warning }); + } + if (resolved.error) { + diagnostics.push({ type: "error", message: resolved.error }); + } + if (resolved.model) { + options.model = resolved.model; + // Allow "--model :" as a shorthand. + // Explicit --thinking still takes precedence (applied later). + if (!parsed.thinking && resolved.thinkingLevel) { + options.thinkingLevel = resolved.thinkingLevel; + cliThinkingFromModel = true; + } + } + } + if (!options.model && scopedModels.length > 0 && !hasExistingSession) { + // Check if saved default is in scoped models - use it if so, otherwise first scoped model + const savedProvider = settingsManager.getDefaultProvider(); + const savedModelId = settingsManager.getDefaultModel(); + const savedModel = savedProvider && savedModelId ? modelRuntime.getModel(savedProvider, savedModelId) : undefined; + const savedInScope = savedModel ? scopedModels.find((sm) => modelsAreEqual(sm.model, savedModel)) : undefined; + if (savedInScope) { + options.model = savedInScope.model; + // Use thinking level from scoped model config if explicitly set + if (!parsed.thinking && savedInScope.thinkingLevel) { + options.thinkingLevel = savedInScope.thinkingLevel; + } + } + else { + options.model = scopedModels[0].model; + // Use thinking level from first scoped model if explicitly set + if (!parsed.thinking && scopedModels[0].thinkingLevel) { + options.thinkingLevel = scopedModels[0].thinkingLevel; + } + } + } + // Thinking level from CLI (takes precedence over scoped model thinking levels set above) + if (parsed.thinking) { + options.thinkingLevel = parsed.thinking; + } + // Scoped models for Ctrl+P cycling + // Keep thinking level undefined when not explicitly set in the model pattern. + // Undefined means "inherit current session thinking level" during cycling. + if (scopedModels.length > 0) { + options.scopedModels = scopedModels.map((sm) => ({ + model: sm.model, + thinkingLevel: sm.thinkingLevel, + })); + } + // API key from CLI - set as a non-persistent runtime override + // (handled by caller before createAgentSession) + // Tools + if (parsed.noTools) { + options.noTools = "all"; + } + else if (parsed.noBuiltinTools) { + options.noTools = "builtin"; + } + if (parsed.tools) { + options.tools = [...parsed.tools]; + } + if (parsed.excludeTools) { + options.excludeTools = [...parsed.excludeTools]; + } + return { options, cliThinkingFromModel, diagnostics }; +} +function resolveCliPaths(cwd, paths) { + return paths?.map((value) => (isLocalPath(value) ? resolvePath(value, cwd) : value)); +} +async function promptForMissingSessionCwd(issue, settingsManager) { + return showStartupSelector(settingsManager, formatMissingSessionCwdPrompt(issue), [ + { label: "Continue", value: issue.fallbackCwd }, + { label: "Cancel", value: undefined }, + ]); +} +export async function main(args, options) { + resetTimings(); + const extensionFactories = [...builtInExtensions, ...(options?.extensionFactories ?? [])]; + const offlineMode = args.includes("--offline") || isTruthyEnvFlag(process.env.PI_OFFLINE); + if (offlineMode) { + process.env.PI_OFFLINE = "1"; + process.env.PI_SKIP_VERSION_CHECK = "1"; + } + if (process.platform === "win32") { + cleanupWindowsSelfUpdateQuarantine(getPackageDir()); + } + const cwd = process.cwd(); + const agentDir = getAgentDir(); + const bootstrapSettingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false }); + applyHttpProxySettings(bootstrapSettingsManager.getGlobalSettings().httpProxy); + configureHttpDispatcher(); + if (await handlePackageCommand(args, { extensionFactories })) { + const exitCode = process.exitCode ?? 0; + if (process.platform === "win32" && exitCode === 0 && args[0] === "update") { + // We normally prefer process.exit(0) for package commands so bad extensions cannot keep + // one-shot commands alive. On Windows, Node can assert after fetch() if process.exit(0) + // runs during teardown; let successful `pi update` drain naturally instead. + // https://github.com/nodejs/node/issues/56645 + return; + } + process.exit(exitCode); + return; + } + if (await handleConfigCommand(args, { extensionFactories })) { + return; + } + if (await runCredentialPrintCommand(args)) { + return; + } + const parsed = parseArgs(args); + if (parsed.diagnostics.length > 0) { + for (const d of parsed.diagnostics) { + const color = d.type === "error" ? chalk.red : chalk.yellow; + console.error(color(`${d.type === "error" ? "Error" : "Warning"}: ${d.message}`)); + } + if (parsed.diagnostics.some((d) => d.type === "error")) { + process.exit(1); + } + } + time("parseArgs"); + if (parsed.version) { + console.log(VERSION); + process.exit(0); + } + if (parsed.export) { + let result; + try { + const outputPath = parsed.messages.length > 0 ? parsed.messages[0] : undefined; + result = await exportFromFile(parsed.export, outputPath); + } + catch (error) { + const message = error instanceof Error ? error.message : "Failed to export session"; + console.error(chalk.red(`Error: ${message}`)); + process.exit(1); + } + console.log(`Exported to: ${result}`); + process.exit(0); + } + let appMode = resolveAppMode(parsed, process.stdin.isTTY, process.stdout.isTTY); + const shouldTakeOverStdout = appMode !== "interactive" && !isPlainRuntimeMetadataCommand(parsed); + if (shouldTakeOverStdout) { + takeOverStdout(); + } + if (parsed.mode === "rpc" && parsed.fileArgs.length > 0) { + console.error(chalk.red("Error: @file arguments are not supported in RPC mode")); + process.exit(1); + } + validateForkFlags(parsed); + validateSessionIdFlags(parsed); + // Run migrations (pass cwd for project-local migrations) + const { migratedAuthProviders: migratedProviders, deprecationWarnings } = runMigrations(cwd); + time("runMigrations"); + const startupSettingsManager = SettingsManager.create(cwd, agentDir); + reportDiagnostics(collectSettingsDiagnostics(startupSettingsManager, "startup session lookup")); + // Experimental first-time setup: theme choice and analytics opt-in. + // Runs before any runtime services are created so the chosen settings apply everywhere. + if (appMode === "interactive" && !parsed.help && parsed.listModels === undefined && shouldRunFirstTimeSetup()) { + await showFirstTimeSetup(startupSettingsManager); + time("firstTimeSetup"); + } + // Decide the final runtime cwd before creating cwd-bound runtime services. + // --session and --resume may select a session from another project, so project-local + // settings, resources, provider registrations, and models must be resolved only after + // the target session cwd is known. The startup-cwd settings manager is used only for + // sessionDir lookup during session selection. + const envSessionDir = process.env[ENV_SESSION_DIR]; + const sessionDir = (parsed.sessionDir ? normalizePath(parsed.sessionDir) : undefined) ?? + (envSessionDir ? expandTildePath(envSessionDir) : undefined) ?? + startupSettingsManager.getSessionDir(); + let sessionManager = await createSessionManager(parsed, cwd, sessionDir, startupSettingsManager); + const missingSessionCwdIssue = getMissingSessionCwdIssue(sessionManager, cwd); + if (missingSessionCwdIssue) { + if (appMode === "interactive") { + const selectedCwd = await promptForMissingSessionCwd(missingSessionCwdIssue, startupSettingsManager); + if (!selectedCwd) { + process.exit(0); + } + sessionManager = SessionManager.open(missingSessionCwdIssue.sessionFile, sessionDir, selectedCwd); + } + else { + console.error(chalk.red(new MissingSessionCwdError(missingSessionCwdIssue).message)); + process.exit(1); + } + } + if (parsed.name !== undefined) { + const name = parsed.name.trim(); + if (!name) { + console.error(chalk.red("Error: --name requires a non-empty value")); + process.exit(1); + } + sessionManager.appendSessionInfo(name); + } + time("createSessionManager"); + const trustStore = new ProjectTrustStore(agentDir); + const sessionCwd = sessionManager.getCwd(); + const autoTrustOnReloadCwd = parsed.projectTrustOverride === undefined && !hasTrustRequiringProjectResources(sessionCwd) + ? sessionCwd + : undefined; + const trustPromptMode = parsed.help || parsed.listModels !== undefined ? "print" : appMode; + const projectTrustByCwd = new Map(); + const resolvedExtensionPaths = resolveCliPaths(cwd, parsed.extensions); + const resolvedSkillPaths = resolveCliPaths(cwd, parsed.skills); + const resolvedPromptTemplatePaths = resolveCliPaths(cwd, parsed.promptTemplates); + const resolvedThemePaths = resolveCliPaths(cwd, parsed.themes); + const createRuntime = async ({ cwd, agentDir, sessionManager, sessionStartEvent, projectTrustContext, }) => { + const isInitialRuntime = sessionStartEvent === undefined; + const projectTrustDiagnostics = []; + const cachedProjectTrust = projectTrustByCwd.get(cwd); + const hasTrustRequiringResources = hasTrustRequiringProjectResources(cwd); + const shouldResolveProjectTrust = parsed.projectTrustOverride === undefined && cachedProjectTrust === undefined && hasTrustRequiringResources; + const projectTrusted = shouldResolveProjectTrust + ? false + : (cachedProjectTrust ?? + parsed.projectTrustOverride ?? + (!hasTrustRequiringResources || trustStore.get(cwd) === true)); + const runtimeSettingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted }); + const services = await createAgentSessionServices({ + cwd, + agentDir, + settingsManager: runtimeSettingsManager, + extensionFlagValues: parsed.unknownFlags, + resourceLoaderReloadOptions: shouldResolveProjectTrust + ? { + resolveProjectTrust: async ({ extensionsResult }) => { + const trusted = await resolveProjectTrusted({ + cwd, + trustStore, + trustOverride: parsed.projectTrustOverride, + defaultProjectTrust: startupSettingsManager.getDefaultProjectTrust(), + extensionsResult, + projectTrustContext: projectTrustContext ?? + createProjectTrustContext({ + cwd, + mode: isInitialRuntime ? trustPromptMode : appMode, + settingsManager: startupSettingsManager, + hasUI: isInitialRuntime && trustPromptMode === "interactive", + }), + onExtensionError: (message) => projectTrustDiagnostics.push({ type: "warning", message }), + }); + projectTrustByCwd.set(cwd, trusted); + return trusted; + }, + } + : undefined, + resourceLoaderOptions: { + additionalExtensionPaths: resolvedExtensionPaths, + additionalSkillPaths: resolvedSkillPaths, + additionalPromptTemplatePaths: resolvedPromptTemplatePaths, + additionalThemePaths: resolvedThemePaths, + noExtensions: parsed.noExtensions, + noSkills: parsed.noSkills, + noPromptTemplates: parsed.noPromptTemplates, + noThemes: parsed.noThemes, + noContextFiles: parsed.noContextFiles, + systemPrompt: parsed.systemPrompt, + appendSystemPrompt: parsed.appendSystemPrompt, + extensionFactories, + }, + }); + const { settingsManager, modelRuntime, resourceLoader } = services; + const diagnostics = [ + ...projectTrustDiagnostics, + ...services.diagnostics, + ...collectSettingsDiagnostics(settingsManager, "runtime creation"), + ...resourceLoader.getExtensions().errors.map(({ path, error }) => ({ + type: "error", + message: `Failed to load extension "${path}": ${error}`, + })), + ]; + const modelPatterns = parsed.models ?? settingsManager.getEnabledModels(); + const scopedModels = modelPatterns && modelPatterns.length > 0 ? await resolveModelScope(modelPatterns, modelRuntime) : []; + const { options: sessionOptions, cliThinkingFromModel, diagnostics: sessionOptionDiagnostics, } = buildSessionOptions(parsed, scopedModels, sessionManager.buildSessionContext().messages.length > 0, modelRuntime, settingsManager); + diagnostics.push(...sessionOptionDiagnostics); + if (parsed.apiKey) { + if (!sessionOptions.model) { + diagnostics.push({ + type: "error", + message: "--api-key requires a model to be specified via --model, --provider/--model, or --models", + }); + } + else { + await modelRuntime.setRuntimeApiKey(sessionOptions.model.provider, parsed.apiKey, { allowNetwork: false }); + await services.modelRuntime.getAvailable(); + } + } + const created = await createAgentSessionFromServices({ + services, + sessionManager, + sessionStartEvent, + model: sessionOptions.model, + thinkingLevel: sessionOptions.thinkingLevel, + scopedModels: sessionOptions.scopedModels, + tools: sessionOptions.tools, + excludeTools: sessionOptions.excludeTools, + noTools: sessionOptions.noTools, + customTools: sessionOptions.customTools, + }); + const cliThinkingOverride = parsed.thinking !== undefined || cliThinkingFromModel; + if (created.session.model && cliThinkingOverride) { + created.session.setThinkingLevel(created.session.thinkingLevel); + } + return { + ...created, + services, + diagnostics, + }; + }; + time("createRuntime"); + const runtime = await createAgentSessionRuntime(createRuntime, { + cwd: sessionManager.getCwd(), + agentDir, + sessionManager, + }); + time("createAgentSessionRuntime"); + const { services, session, modelFallbackMessage } = runtime; + const { settingsManager, modelRuntime, resourceLoader } = services; + applyHttpProxySettings(settingsManager.getGlobalSettings().httpProxy); + configureHttpDispatcher(settingsManager.getHttpIdleTimeoutMs()); + if (parsed.help) { + const extensionFlags = resourceLoader + .getExtensions() + .extensions.flatMap((extension) => Array.from(extension.flags.values())); + printHelp(extensionFlags); + process.exit(0); + } + if (parsed.listModels !== undefined) { + const searchPattern = typeof parsed.listModels === "string" ? parsed.listModels : undefined; + await listModels(modelRuntime, searchPattern); + process.exit(0); + } + // Read piped stdin content (if any) - skip for RPC mode which uses stdin for JSON-RPC + let stdinContent; + if (appMode !== "rpc") { + stdinContent = await readPipedStdin(); + if (stdinContent !== undefined && appMode === "interactive") { + appMode = "print"; + } + } + time("readPipedStdin"); + const { initialMessage, initialImages } = await prepareInitialMessage(parsed, settingsManager.getImageAutoResize(), stdinContent); + time("prepareInitialMessage"); + initTheme(settingsManager.getTheme(), appMode === "interactive"); + time("initTheme"); + // Show deprecation warnings in interactive mode + if (appMode === "interactive" && deprecationWarnings.length > 0) { + await showDeprecationWarnings(deprecationWarnings); + } + time("resolveModelScope"); + reportDiagnostics(runtime.diagnostics); + if (runtime.diagnostics.some((diagnostic) => diagnostic.type === "error")) { + if (runtime.diagnostics.some((diagnostic) => diagnostic.message.includes("Failed to load extension"))) { + console.error(chalk.yellow(EXTENSION_LOAD_FAILURE_HINT)); + } + process.exit(1); + } + time("createAgentSession"); + if (appMode !== "interactive" && !session.model) { + console.error(chalk.red(formatNoModelsAvailableMessage())); + process.exit(1); + } + const startupBenchmark = isTruthyEnvFlag(process.env.PI_STARTUP_BENCHMARK); + if (startupBenchmark && appMode !== "interactive") { + console.error(chalk.red("Error: PI_STARTUP_BENCHMARK only supports interactive mode")); + process.exit(1); + } + // RPC refreshes catalogs here in the background; interactive mode starts its refresh after TUI initialization. + if (!offlineMode && appMode === "rpc") { + void modelRuntime.refresh().catch(() => { }); + } + if (appMode === "rpc") { + printTimings(); + await runRpcMode(runtime); + } + else if (appMode === "interactive") { + const interactiveMode = new InteractiveMode(runtime, { + migratedProviders, + modelFallbackMessage, + autoTrustOnReloadCwd, + initialMessage, + initialImages, + initialMessages: parsed.messages, + verbose: parsed.verbose, + }); + if (startupBenchmark) { + await interactiveMode.init(); + time("interactiveMode.init"); + // Give the TUI's stdin handler a brief chance to consume terminal query replies + // (Kitty keyboard protocol, device attributes, cell size) before restoring the terminal. + await new Promise((resolve) => setTimeout(resolve, 150)); + interactiveMode.stop(); + stopThemeWatcher(); + printTimings(); + if (process.stdout.writableLength > 0) { + await new Promise((resolve) => process.stdout.once("drain", resolve)); + } + if (process.stderr.writableLength > 0) { + await new Promise((resolve) => process.stderr.once("drain", resolve)); + } + return; + } + printTimings(); + await interactiveMode.run(); + } + else { + printTimings(); + const exitCode = await runPrintMode(runtime, { + mode: toPrintOutputMode(appMode), + messages: parsed.messages, + initialMessage, + initialImages, + }); + stopThemeWatcher(); + restoreStdout(); + if (exitCode !== 0) { + process.exitCode = exitCode; + } + return; + } +} +//# sourceMappingURL=main.js.map \ No newline at end of file diff --git a/dist/main.js.map b/dist/main.js.map new file mode 100644 index 0000000..e949a22 --- /dev/null +++ b/dist/main.js.map @@ -0,0 +1 @@ +{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAqB,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC1E,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAwB,SAAS,EAAE,SAAS,EAAE,MAAM,e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zB,cAAc;YACd,aAAa;SACb,CAAC,CAAC;QACH,gBAAgB,EAAE,CAAC;QACnB,aAAa,EAAE,CAAC;QAChB,IAAI,QAAQ,KAAK,CAAC,EAAE,CAAC;YACpB,OAAO,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAC7B,CAAC;QACD,OAAO;IACR,CAAC;AAAA,CACD","sourcesContent":["/**\n * Main entry point for the coding agent CLI.\n *\n * This file handles CLI argument parsing and translates them into\n * createAgentSession() options. The SDK does the heavy lifting.\n */\n\nimport { createInterface } from \"node:readline\";\nimport { type ImageContent, modelsAreEqual } from \"@earendil-works/pi-ai\";\nimport chalk from \"chalk\";\nimport { type Args, type Mode, parseArgs, printHelp } from \"./cli/args.ts\";\nimport {\n\ttype CredentialPrintCommand,\n\tCredentialPrintError,\n\tisCredentialPrintHelp,\n\tparseCredentialPrintCommand,\n\tprintCredentialPrintHelp,\n\tresolveCredentialForPrint,\n\tvalidateCredentialPrintArgs,\n} from \"./cli/credential-print.ts\";\nimport { processFileArguments } from \"./cli/file-processor.ts\";\nimport { buildInitialMessage } from \"./cli/initial-message.ts\";\nimport { listModels } from \"./cli/list-models.ts\";\nimport { createProjectTrustContext } from \"./cli/project-trust.ts\";\nimport { selectSession } from \"./cli/session-picker.ts\";\nimport { shouldRunFirstTimeSetup, showFirstTimeSetup, showStartupSelector } from \"./cli/startup-ui.ts\";\nimport { ENV_SESSION_DIR, expandTildePath, getAgentDir, getPackageDir, VERSION } from \"./config.ts\";\nimport { type CreateAgentSessionRuntimeFactory, createAgentSessionRuntime } from \"./core/agent-session-runtime.ts\";\nimport {\n\ttype AgentSessionRuntimeDiagnostic,\n\tcreateAgentSessionFromServices,\n\tcreateAgentSessionServices,\n} from \"./core/agent-session-services.ts\";\nimport { formatNoModelsAvailableMessage } from \"./core/auth-guidance.ts\";\nimport { exportFromFile } from \"./core/export-html/index.ts\";\nimport type { InlineExtension } from \"./core/extensions/types.ts\";\nimport { applyHttpProxySettings, configureHttpDispatcher } from \"./core/http-dispatcher.ts\";\nimport { resolveCliModel, resolveModelScope, type ScopedModel } from \"./core/model-resolver.ts\";\nimport { ModelRuntime } from \"./core/model-runtime.ts\";\nimport { restoreStdout, takeOverStdout } from \"./core/output-guard.ts\";\nimport { type AppMode, resolveProjectTrusted } from \"./core/project-trust.ts\";\nimport type { CreateAgentSessionOptions } from \"./core/sdk.ts\";\nimport {\n\tformatMissingSessionCwdPrompt,\n\tgetMissingSessionCwdIssue,\n\tMissingSessionCwdError,\n\ttype SessionCwdIssue,\n} from \"./core/session-cwd.ts\";\nimport { assertValidSessionId, SessionManager } from \"./core/session-manager.ts\";\nimport { SettingsManager } from \"./core/settings-manager.ts\";\nimport { printTimings, resetTimings, time } from \"./core/timings.ts\";\nimport { hasTrustRequiringProjectResources, ProjectTrustStore } from \"./core/trust-manager.ts\";\nimport { builtInExtensions } from \"./extensions/index.ts\";\nimport { runMigrations, showDeprecationWarnings } from \"./migrations.ts\";\nimport { InteractiveMode, runPrintMode, runRpcMode } from \"./modes/index.ts\";\nimport { initTheme, stopThemeWatcher } from \"./modes/interactive/theme/theme.ts\";\nimport { handleConfigCommand, handlePackageCommand } from \"./package-manager-cli.ts\";\nimport { isLocalPath, normalizePath, resolvePath } from \"./utils/paths.ts\";\nimport { cleanupWindowsSelfUpdateQuarantine } from \"./utils/windows-self-update.ts\";\n\nconst EXTENSION_LOAD_FAILURE_HINT = 'Hint: Start without extensions using \"pi -ne\".';\n\n/**\n * Read all content from piped stdin.\n * Returns undefined if stdin is a TTY (interactive terminal).\n */\nasync function readPipedStdin(): Promise {\n\t// If stdin is a TTY, we're running interactively - don't read stdin\n\tif (process.stdin.isTTY) {\n\t\treturn undefined;\n\t}\n\n\treturn new Promise((resolve) => {\n\t\tlet data = \"\";\n\t\tprocess.stdin.setEncoding(\"utf8\");\n\t\tprocess.stdin.on(\"data\", (chunk) => {\n\t\t\tdata += chunk;\n\t\t});\n\t\tprocess.stdin.on(\"end\", () => {\n\t\t\tresolve(data.trim() || undefined);\n\t\t});\n\t\tprocess.stdin.resume();\n\t});\n}\n\nfunction collectSettingsDiagnostics(\n\tsettingsManager: SettingsManager,\n\tcontext: string,\n): AgentSessionRuntimeDiagnostic[] {\n\treturn settingsManager.drainErrors().map(({ scope, error }) => ({\n\t\ttype: \"warning\",\n\t\tmessage: `(${context}, ${scope} settings) ${error.message}`,\n\t}));\n}\n\nfunction reportDiagnostics(diagnostics: readonly AgentSessionRuntimeDiagnostic[]): void {\n\tfor (const diagnostic of diagnostics) {\n\t\tconst color = diagnostic.type === \"error\" ? chalk.red : diagnostic.type === \"warning\" ? chalk.yellow : chalk.dim;\n\t\tconst prefix = diagnostic.type === \"error\" ? \"Error: \" : diagnostic.type === \"warning\" ? \"Warning: \" : \"\";\n\t\tconsole.error(color(`${prefix}${diagnostic.message}`));\n\t}\n}\n\nfunction isTruthyEnvFlag(value: string | undefined): boolean {\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\nfunction resolveAppMode(parsed: Args, stdinIsTTY: boolean, stdoutIsTTY: boolean): AppMode {\n\tif (parsed.mode === \"rpc\") {\n\t\treturn \"rpc\";\n\t}\n\tif (parsed.mode === \"json\") {\n\t\treturn \"json\";\n\t}\n\tif (parsed.print || !stdinIsTTY || !stdoutIsTTY) {\n\t\treturn \"print\";\n\t}\n\treturn \"interactive\";\n}\n\nfunction toPrintOutputMode(appMode: AppMode): Exclude {\n\treturn appMode === \"json\" ? \"json\" : \"text\";\n}\n\nfunction isPlainRuntimeMetadataCommand(parsed: Args): boolean {\n\treturn !parsed.print && parsed.mode === undefined && (parsed.help === true || parsed.listModels !== undefined);\n}\n\nasync function runCredentialPrintCommand(args: string[]): Promise {\n\tif (isCredentialPrintHelp(args)) {\n\t\tprintCredentialPrintHelp();\n\t\treturn true;\n\t}\n\n\tlet command: CredentialPrintCommand | undefined;\n\ttry {\n\t\tcommand = parseCredentialPrintCommand(args);\n\t} catch (error) {\n\t\tconst message = error instanceof CredentialPrintError ? error.message : \"Failed to parse auth command\";\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\tif (!command) return false;\n\n\tconst parsed = parseArgs(command.args);\n\tif (parsed.diagnostics.length > 0) {\n\t\tfor (const diagnostic of parsed.diagnostics) {\n\t\t\tconsole.error(chalk.red(`Error: ${diagnostic.message}`));\n\t\t}\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\n\ttry {\n\t\tvalidateCredentialPrintArgs(parsed);\n\t\tconst modelRuntime = await ModelRuntime.create({ allowModelNetwork: false });\n\t\tconst credential = await resolveCredentialForPrint(parsed, modelRuntime, command.kind, command.minExpiryMs);\n\t\tprocess.stdout.write(`${credential}\\n`);\n\t} catch (error) {\n\t\tconst message = error instanceof CredentialPrintError ? error.message : \"Failed to resolve credential\";\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exitCode = 1;\n\t}\n\treturn true;\n}\n\nasync function prepareInitialMessage(\n\tparsed: Args,\n\tautoResizeImages: boolean,\n\tstdinContent?: string,\n): Promise<{\n\tinitialMessage?: string;\n\tinitialImages?: ImageContent[];\n}> {\n\tif (parsed.fileArgs.length === 0) {\n\t\treturn buildInitialMessage({ parsed, stdinContent });\n\t}\n\n\tconst { text, images } = await processFileArguments(parsed.fileArgs, { autoResizeImages });\n\treturn buildInitialMessage({\n\t\tparsed,\n\t\tfileText: text,\n\t\tfileImages: images,\n\t\tstdinContent,\n\t});\n}\n\n/** Result from resolving a session argument */\ntype ResolvedSession =\n\t| { type: \"path\"; path: string } // Direct file path\n\t| { type: \"local\"; path: string } // Found in current project\n\t| { type: \"global\"; path: string; cwd: string } // Found in different project\n\t| { type: \"not_found\"; arg: string }; // Not found anywhere\n\n/**\n * Resolve a session argument to a file path.\n * If it looks like a path, use as-is. Otherwise try to match as session ID prefix.\n */\nasync function findLocalSessionByExactId(\n\tsessionId: string,\n\tcwd: string,\n\tsessionDir?: string,\n): Promise<{ type: \"local\"; path: string } | undefined> {\n\tconst localSessions = await SessionManager.list(cwd, sessionDir);\n\tconst localMatch = localSessions.find((s) => s.id === sessionId);\n\treturn localMatch ? { type: \"local\", path: localMatch.path } : undefined;\n}\n\nasync function resolveSessionPath(sessionArg: string, cwd: string, sessionDir?: string): Promise {\n\t// If it looks like a file path, resolve it before handing it to the session manager.\n\tif (sessionArg.includes(\"/\") || sessionArg.includes(\"\\\\\") || sessionArg.endsWith(\".jsonl\")) {\n\t\treturn { type: \"path\", path: resolvePath(sessionArg, cwd) };\n\t}\n\n\t// Try to match as session ID in current project first\n\tconst localSessions = await SessionManager.list(cwd, sessionDir);\n\tconst localMatch =\n\t\tlocalSessions.find((s) => s.id === sessionArg) ?? localSessions.find((s) => s.id.startsWith(sessionArg));\n\n\tif (localMatch) {\n\t\treturn { type: \"local\", path: localMatch.path };\n\t}\n\n\t// Try global search across all projects\n\tconst allSessions = await SessionManager.listAll(sessionDir);\n\tconst globalMatch =\n\t\tallSessions.find((s) => s.id === sessionArg) ?? allSessions.find((s) => s.id.startsWith(sessionArg));\n\n\tif (globalMatch) {\n\t\treturn { type: \"global\", path: globalMatch.path, cwd: globalMatch.cwd };\n\t}\n\n\t// Not found anywhere\n\treturn { type: \"not_found\", arg: sessionArg };\n}\n\n/** Prompt user for yes/no confirmation */\nasync function promptConfirm(message: string): Promise {\n\treturn new Promise((resolve) => {\n\t\tconst rl = createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t});\n\t\trl.question(`${message} [y/N] `, (answer) => {\n\t\t\trl.close();\n\t\t\tresolve(answer.toLowerCase() === \"y\" || answer.toLowerCase() === \"yes\");\n\t\t});\n\t});\n}\n\nfunction validateForkFlags(parsed: Args): void {\n\tif (!parsed.fork) return;\n\n\tconst conflictingFlags = [\n\t\tparsed.session ? \"--session\" : undefined,\n\t\tparsed.continue ? \"--continue\" : undefined,\n\t\tparsed.resume ? \"--resume\" : undefined,\n\t\tparsed.noSession ? \"--no-session\" : undefined,\n\t].filter((flag): flag is string => flag !== undefined);\n\n\tif (conflictingFlags.length > 0) {\n\t\tconsole.error(chalk.red(`Error: --fork cannot be combined with ${conflictingFlags.join(\", \")}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nfunction validateSessionIdFlags(parsed: Args): void {\n\tif (parsed.sessionId === undefined) return;\n\n\tconst conflictingFlags = [\n\t\tparsed.session ? \"--session\" : undefined,\n\t\tparsed.continue ? \"--continue\" : undefined,\n\t\tparsed.resume ? \"--resume\" : undefined,\n\t].filter((flag): flag is string => flag !== undefined);\n\n\tif (conflictingFlags.length > 0) {\n\t\tconsole.error(chalk.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(\", \")}`));\n\t\tprocess.exit(1);\n\t}\n\n\ttry {\n\t\tassertValidSessionId(parsed.sessionId);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nfunction openSessionOrExit(path: string, sessionDir?: string): SessionManager {\n\ttry {\n\t\treturn SessionManager.open(path, sessionDir);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nfunction forkSessionOrExit(sourcePath: string, cwd: string, sessionDir?: string, sessionId?: string): SessionManager {\n\ttry {\n\t\treturn SessionManager.forkFrom(sourcePath, cwd, sessionDir, { id: sessionId });\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nasync function createSessionManager(\n\tparsed: Args,\n\tcwd: string,\n\tsessionDir: string | undefined,\n\tsettingsManager: SettingsManager,\n): Promise {\n\tif (parsed.noSession || parsed.help || parsed.listModels !== undefined) {\n\t\treturn SessionManager.inMemory(cwd, parsed.sessionId !== undefined ? { id: parsed.sessionId } : undefined);\n\t}\n\n\tif (parsed.fork) {\n\t\tif (parsed.sessionId) {\n\t\t\tconst existingTarget = await findLocalSessionByExactId(parsed.sessionId, cwd, sessionDir);\n\t\t\tif (existingTarget) {\n\t\t\t\tconsole.error(chalk.red(`Session already exists with id '${parsed.sessionId}'`));\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t}\n\n\t\tconst resolved = await resolveSessionPath(parsed.fork, cwd, sessionDir);\n\n\t\tswitch (resolved.type) {\n\t\t\tcase \"path\":\n\t\t\tcase \"local\":\n\t\t\tcase \"global\":\n\t\t\t\treturn forkSessionOrExit(resolved.path, cwd, sessionDir, parsed.sessionId);\n\n\t\t\tcase \"not_found\":\n\t\t\t\tconsole.error(chalk.red(`No session found matching '${resolved.arg}'`));\n\t\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tif (parsed.session) {\n\t\tconst resolved = await resolveSessionPath(parsed.session, cwd, sessionDir);\n\n\t\tswitch (resolved.type) {\n\t\t\tcase \"path\":\n\t\t\tcase \"local\":\n\t\t\t\treturn openSessionOrExit(resolved.path, sessionDir);\n\n\t\t\tcase \"global\": {\n\t\t\t\tconsole.log(chalk.yellow(`Session found in different project: ${resolved.cwd}`));\n\t\t\t\tconst shouldFork = await promptConfirm(\"Fork this session into current directory?\");\n\t\t\t\tif (!shouldFork) {\n\t\t\t\t\tconsole.log(chalk.dim(\"Aborted.\"));\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t\treturn forkSessionOrExit(resolved.path, cwd, sessionDir);\n\t\t\t}\n\n\t\t\tcase \"not_found\":\n\t\t\t\tconsole.error(chalk.red(`No session found matching '${resolved.arg}'`));\n\t\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tif (parsed.resume) {\n\t\ttry {\n\t\t\tconst selectedPath = await selectSession(\n\t\t\t\t(onProgress) => SessionManager.list(cwd, sessionDir, onProgress),\n\t\t\t\t(onProgress) => SessionManager.listAll(sessionDir, onProgress),\n\t\t\t\tsettingsManager,\n\t\t\t);\n\t\t\tif (!selectedPath) {\n\t\t\t\tconsole.log(chalk.dim(\"No session selected\"));\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t\treturn SessionManager.open(selectedPath, sessionDir);\n\t\t} finally {\n\t\t\tstopThemeWatcher();\n\t\t}\n\t}\n\n\tif (parsed.continue) {\n\t\treturn SessionManager.continueRecent(cwd, sessionDir);\n\t}\n\n\tif (parsed.sessionId) {\n\t\tconst existingSession = await findLocalSessionByExactId(parsed.sessionId, cwd, sessionDir);\n\t\tif (existingSession) {\n\t\t\treturn SessionManager.open(existingSession.path, sessionDir);\n\t\t}\n\t\tconsole.error(\n\t\t\tchalk.yellow(\n\t\t\t\t`Warning: No project session found with id '${parsed.sessionId}'; creating a new session with that id.`,\n\t\t\t),\n\t\t);\n\t}\n\n\treturn SessionManager.create(cwd, sessionDir, { id: parsed.sessionId });\n}\n\nfunction buildSessionOptions(\n\tparsed: Args,\n\tscopedModels: ScopedModel[],\n\thasExistingSession: boolean,\n\tmodelRuntime: ModelRuntime,\n\tsettingsManager: SettingsManager,\n): {\n\toptions: CreateAgentSessionOptions;\n\tcliThinkingFromModel: boolean;\n\tdiagnostics: AgentSessionRuntimeDiagnostic[];\n} {\n\tconst options: CreateAgentSessionOptions = {};\n\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\tlet cliThinkingFromModel = false;\n\n\t// Model from CLI\n\t// - supports --provider --model \n\t// - supports --model /\n\tif (parsed.model) {\n\t\tconst resolved = resolveCliModel({\n\t\t\tcliProvider: parsed.provider,\n\t\t\tcliModel: parsed.model,\n\t\t\tcliThinking: parsed.thinking,\n\t\t\tmodelRuntime,\n\t\t});\n\t\tif (resolved.warning) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: resolved.warning });\n\t\t}\n\t\tif (resolved.error) {\n\t\t\tdiagnostics.push({ type: \"error\", message: resolved.error });\n\t\t}\n\t\tif (resolved.model) {\n\t\t\toptions.model = resolved.model;\n\t\t\t// Allow \"--model :\" as a shorthand.\n\t\t\t// Explicit --thinking still takes precedence (applied later).\n\t\t\tif (!parsed.thinking && resolved.thinkingLevel) {\n\t\t\t\toptions.thinkingLevel = resolved.thinkingLevel;\n\t\t\t\tcliThinkingFromModel = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!options.model && scopedModels.length > 0 && !hasExistingSession) {\n\t\t// Check if saved default is in scoped models - use it if so, otherwise first scoped model\n\t\tconst savedProvider = settingsManager.getDefaultProvider();\n\t\tconst savedModelId = settingsManager.getDefaultModel();\n\t\tconst savedModel = savedProvider && savedModelId ? modelRuntime.getModel(savedProvider, savedModelId) : undefined;\n\t\tconst savedInScope = savedModel ? scopedModels.find((sm) => modelsAreEqual(sm.model, savedModel)) : undefined;\n\n\t\tif (savedInScope) {\n\t\t\toptions.model = savedInScope.model;\n\t\t\t// Use thinking level from scoped model config if explicitly set\n\t\t\tif (!parsed.thinking && savedInScope.thinkingLevel) {\n\t\t\t\toptions.thinkingLevel = savedInScope.thinkingLevel;\n\t\t\t}\n\t\t} else {\n\t\t\toptions.model = scopedModels[0].model;\n\t\t\t// Use thinking level from first scoped model if explicitly set\n\t\t\tif (!parsed.thinking && scopedModels[0].thinkingLevel) {\n\t\t\t\toptions.thinkingLevel = scopedModels[0].thinkingLevel;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Thinking level from CLI (takes precedence over scoped model thinking levels set above)\n\tif (parsed.thinking) {\n\t\toptions.thinkingLevel = parsed.thinking;\n\t}\n\n\t// Scoped models for Ctrl+P cycling\n\t// Keep thinking level undefined when not explicitly set in the model pattern.\n\t// Undefined means \"inherit current session thinking level\" during cycling.\n\tif (scopedModels.length > 0) {\n\t\toptions.scopedModels = scopedModels.map((sm) => ({\n\t\t\tmodel: sm.model,\n\t\t\tthinkingLevel: sm.thinkingLevel,\n\t\t}));\n\t}\n\n\t// API key from CLI - set as a non-persistent runtime override\n\t// (handled by caller before createAgentSession)\n\n\t// Tools\n\tif (parsed.noTools) {\n\t\toptions.noTools = \"all\";\n\t} else if (parsed.noBuiltinTools) {\n\t\toptions.noTools = \"builtin\";\n\t}\n\tif (parsed.tools) {\n\t\toptions.tools = [...parsed.tools];\n\t}\n\tif (parsed.excludeTools) {\n\t\toptions.excludeTools = [...parsed.excludeTools];\n\t}\n\n\treturn { options, cliThinkingFromModel, diagnostics };\n}\n\nfunction resolveCliPaths(cwd: string, paths: string[] | undefined): string[] | undefined {\n\treturn paths?.map((value) => (isLocalPath(value) ? resolvePath(value, cwd) : value));\n}\n\nasync function promptForMissingSessionCwd(\n\tissue: SessionCwdIssue,\n\tsettingsManager: SettingsManager,\n): Promise {\n\treturn showStartupSelector(settingsManager, formatMissingSessionCwdPrompt(issue), [\n\t\t{ label: \"Continue\", value: issue.fallbackCwd },\n\t\t{ label: \"Cancel\", value: undefined },\n\t]);\n}\n\nexport interface MainOptions {\n\textensionFactories?: InlineExtension[];\n}\n\nexport async function main(args: string[], options?: MainOptions) {\n\tresetTimings();\n\tconst extensionFactories = [...builtInExtensions, ...(options?.extensionFactories ?? [])];\n\tconst offlineMode = args.includes(\"--offline\") || isTruthyEnvFlag(process.env.PI_OFFLINE);\n\tif (offlineMode) {\n\t\tprocess.env.PI_OFFLINE = \"1\";\n\t\tprocess.env.PI_SKIP_VERSION_CHECK = \"1\";\n\t}\n\n\tif (process.platform === \"win32\") {\n\t\tcleanupWindowsSelfUpdateQuarantine(getPackageDir());\n\t}\n\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst bootstrapSettingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\tapplyHttpProxySettings(bootstrapSettingsManager.getGlobalSettings().httpProxy);\n\tconfigureHttpDispatcher();\n\n\tif (await handlePackageCommand(args, { extensionFactories })) {\n\t\tconst exitCode = process.exitCode ?? 0;\n\t\tif (process.platform === \"win32\" && exitCode === 0 && args[0] === \"update\") {\n\t\t\t// We normally prefer process.exit(0) for package commands so bad extensions cannot keep\n\t\t\t// one-shot commands alive. On Windows, Node can assert after fetch() if process.exit(0)\n\t\t\t// runs during teardown; let successful `pi update` drain naturally instead.\n\t\t\t// https://github.com/nodejs/node/issues/56645\n\t\t\treturn;\n\t\t}\n\t\tprocess.exit(exitCode);\n\t\treturn;\n\t}\n\n\tif (await handleConfigCommand(args, { extensionFactories })) {\n\t\treturn;\n\t}\n\n\tif (await runCredentialPrintCommand(args)) {\n\t\treturn;\n\t}\n\n\tconst parsed = parseArgs(args);\n\tif (parsed.diagnostics.length > 0) {\n\t\tfor (const d of parsed.diagnostics) {\n\t\t\tconst color = d.type === \"error\" ? chalk.red : chalk.yellow;\n\t\t\tconsole.error(color(`${d.type === \"error\" ? \"Error\" : \"Warning\"}: ${d.message}`));\n\t\t}\n\t\tif (parsed.diagnostics.some((d) => d.type === \"error\")) {\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\ttime(\"parseArgs\");\n\n\tif (parsed.version) {\n\t\tconsole.log(VERSION);\n\t\tprocess.exit(0);\n\t}\n\n\tif (parsed.export) {\n\t\tlet result: string;\n\t\ttry {\n\t\t\tconst outputPath = parsed.messages.length > 0 ? parsed.messages[0] : undefined;\n\t\t\tresult = await exportFromFile(parsed.export, outputPath);\n\t\t} catch (error: unknown) {\n\t\t\tconst message = error instanceof Error ? error.message : \"Failed to export session\";\n\t\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tconsole.log(`Exported to: ${result}`);\n\t\tprocess.exit(0);\n\t}\n\n\tlet appMode = resolveAppMode(parsed, process.stdin.isTTY, process.stdout.isTTY);\n\tconst shouldTakeOverStdout = appMode !== \"interactive\" && !isPlainRuntimeMetadataCommand(parsed);\n\tif (shouldTakeOverStdout) {\n\t\ttakeOverStdout();\n\t}\n\n\tif (parsed.mode === \"rpc\" && parsed.fileArgs.length > 0) {\n\t\tconsole.error(chalk.red(\"Error: @file arguments are not supported in RPC mode\"));\n\t\tprocess.exit(1);\n\t}\n\n\tvalidateForkFlags(parsed);\n\tvalidateSessionIdFlags(parsed);\n\n\t// Run migrations (pass cwd for project-local migrations)\n\tconst { migratedAuthProviders: migratedProviders, deprecationWarnings } = runMigrations(cwd);\n\ttime(\"runMigrations\");\n\n\tconst startupSettingsManager = SettingsManager.create(cwd, agentDir);\n\treportDiagnostics(collectSettingsDiagnostics(startupSettingsManager, \"startup session lookup\"));\n\n\t// Experimental first-time setup: theme choice and analytics opt-in.\n\t// Runs before any runtime services are created so the chosen settings apply everywhere.\n\tif (appMode === \"interactive\" && !parsed.help && parsed.listModels === undefined && shouldRunFirstTimeSetup()) {\n\t\tawait showFirstTimeSetup(startupSettingsManager);\n\t\ttime(\"firstTimeSetup\");\n\t}\n\n\t// Decide the final runtime cwd before creating cwd-bound runtime services.\n\t// --session and --resume may select a session from another project, so project-local\n\t// settings, resources, provider registrations, and models must be resolved only after\n\t// the target session cwd is known. The startup-cwd settings manager is used only for\n\t// sessionDir lookup during session selection.\n\tconst envSessionDir = process.env[ENV_SESSION_DIR];\n\tconst sessionDir =\n\t\t(parsed.sessionDir ? normalizePath(parsed.sessionDir) : undefined) ??\n\t\t(envSessionDir ? expandTildePath(envSessionDir) : undefined) ??\n\t\tstartupSettingsManager.getSessionDir();\n\tlet sessionManager = await createSessionManager(parsed, cwd, sessionDir, startupSettingsManager);\n\tconst missingSessionCwdIssue = getMissingSessionCwdIssue(sessionManager, cwd);\n\tif (missingSessionCwdIssue) {\n\t\tif (appMode === \"interactive\") {\n\t\t\tconst selectedCwd = await promptForMissingSessionCwd(missingSessionCwdIssue, startupSettingsManager);\n\t\t\tif (!selectedCwd) {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t\tsessionManager = SessionManager.open(missingSessionCwdIssue.sessionFile!, sessionDir, selectedCwd);\n\t\t} else {\n\t\t\tconsole.error(chalk.red(new MissingSessionCwdError(missingSessionCwdIssue).message));\n\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\tif (parsed.name !== undefined) {\n\t\tconst name = parsed.name.trim();\n\t\tif (!name) {\n\t\t\tconsole.error(chalk.red(\"Error: --name requires a non-empty value\"));\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tsessionManager.appendSessionInfo(name);\n\t}\n\ttime(\"createSessionManager\");\n\n\tconst trustStore = new ProjectTrustStore(agentDir);\n\tconst sessionCwd = sessionManager.getCwd();\n\tconst autoTrustOnReloadCwd =\n\t\tparsed.projectTrustOverride === undefined && !hasTrustRequiringProjectResources(sessionCwd)\n\t\t\t? sessionCwd\n\t\t\t: undefined;\n\tconst trustPromptMode: AppMode = parsed.help || parsed.listModels !== undefined ? \"print\" : appMode;\n\tconst projectTrustByCwd = new Map();\n\n\tconst resolvedExtensionPaths = resolveCliPaths(cwd, parsed.extensions);\n\tconst resolvedSkillPaths = resolveCliPaths(cwd, parsed.skills);\n\tconst resolvedPromptTemplatePaths = resolveCliPaths(cwd, parsed.promptTemplates);\n\tconst resolvedThemePaths = resolveCliPaths(cwd, parsed.themes);\n\tconst createRuntime: CreateAgentSessionRuntimeFactory = async ({\n\t\tcwd,\n\t\tagentDir,\n\t\tsessionManager,\n\t\tsessionStartEvent,\n\t\tprojectTrustContext,\n\t}) => {\n\t\tconst isInitialRuntime = sessionStartEvent === undefined;\n\t\tconst projectTrustDiagnostics: AgentSessionRuntimeDiagnostic[] = [];\n\t\tconst cachedProjectTrust = projectTrustByCwd.get(cwd);\n\t\tconst hasTrustRequiringResources = hasTrustRequiringProjectResources(cwd);\n\t\tconst shouldResolveProjectTrust =\n\t\t\tparsed.projectTrustOverride === undefined && cachedProjectTrust === undefined && hasTrustRequiringResources;\n\t\tconst projectTrusted = shouldResolveProjectTrust\n\t\t\t? false\n\t\t\t: (cachedProjectTrust ??\n\t\t\t\tparsed.projectTrustOverride ??\n\t\t\t\t(!hasTrustRequiringResources || trustStore.get(cwd) === true));\n\t\tconst runtimeSettingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted });\n\t\tconst services = await createAgentSessionServices({\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tsettingsManager: runtimeSettingsManager,\n\t\t\textensionFlagValues: parsed.unknownFlags,\n\t\t\tresourceLoaderReloadOptions: shouldResolveProjectTrust\n\t\t\t\t? {\n\t\t\t\t\t\tresolveProjectTrust: async ({ extensionsResult }) => {\n\t\t\t\t\t\t\tconst trusted = await resolveProjectTrusted({\n\t\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\t\ttrustStore,\n\t\t\t\t\t\t\t\ttrustOverride: parsed.projectTrustOverride,\n\t\t\t\t\t\t\t\tdefaultProjectTrust: startupSettingsManager.getDefaultProjectTrust(),\n\t\t\t\t\t\t\t\textensionsResult,\n\t\t\t\t\t\t\t\tprojectTrustContext:\n\t\t\t\t\t\t\t\t\tprojectTrustContext ??\n\t\t\t\t\t\t\t\t\tcreateProjectTrustContext({\n\t\t\t\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\t\t\t\tmode: isInitialRuntime ? trustPromptMode : appMode,\n\t\t\t\t\t\t\t\t\t\tsettingsManager: startupSettingsManager,\n\t\t\t\t\t\t\t\t\t\thasUI: isInitialRuntime && trustPromptMode === \"interactive\",\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tonExtensionError: (message) => projectTrustDiagnostics.push({ type: \"warning\", message }),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tprojectTrustByCwd.set(cwd, trusted);\n\t\t\t\t\t\t\treturn trusted;\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t\tresourceLoaderOptions: {\n\t\t\t\tadditionalExtensionPaths: resolvedExtensionPaths,\n\t\t\t\tadditionalSkillPaths: resolvedSkillPaths,\n\t\t\t\tadditionalPromptTemplatePaths: resolvedPromptTemplatePaths,\n\t\t\t\tadditionalThemePaths: resolvedThemePaths,\n\t\t\t\tnoExtensions: parsed.noExtensions,\n\t\t\t\tnoSkills: parsed.noSkills,\n\t\t\t\tnoPromptTemplates: parsed.noPromptTemplates,\n\t\t\t\tnoThemes: parsed.noThemes,\n\t\t\t\tnoContextFiles: parsed.noContextFiles,\n\t\t\t\tsystemPrompt: parsed.systemPrompt,\n\t\t\t\tappendSystemPrompt: parsed.appendSystemPrompt,\n\t\t\t\textensionFactories,\n\t\t\t},\n\t\t});\n\t\tconst { settingsManager, modelRuntime, resourceLoader } = services;\n\t\tconst diagnostics: AgentSessionRuntimeDiagnostic[] = [\n\t\t\t...projectTrustDiagnostics,\n\t\t\t...services.diagnostics,\n\t\t\t...collectSettingsDiagnostics(settingsManager, \"runtime creation\"),\n\t\t\t...resourceLoader.getExtensions().errors.map(({ path, error }) => ({\n\t\t\t\ttype: \"error\" as const,\n\t\t\t\tmessage: `Failed to load extension \"${path}\": ${error}`,\n\t\t\t})),\n\t\t];\n\n\t\tconst modelPatterns = parsed.models ?? settingsManager.getEnabledModels();\n\t\tconst scopedModels =\n\t\t\tmodelPatterns && modelPatterns.length > 0 ? await resolveModelScope(modelPatterns, modelRuntime) : [];\n\t\tconst {\n\t\t\toptions: sessionOptions,\n\t\t\tcliThinkingFromModel,\n\t\t\tdiagnostics: sessionOptionDiagnostics,\n\t\t} = buildSessionOptions(\n\t\t\tparsed,\n\t\t\tscopedModels,\n\t\t\tsessionManager.buildSessionContext().messages.length > 0,\n\t\t\tmodelRuntime,\n\t\t\tsettingsManager,\n\t\t);\n\t\tdiagnostics.push(...sessionOptionDiagnostics);\n\n\t\tif (parsed.apiKey) {\n\t\t\tif (!sessionOptions.model) {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\tmessage: \"--api-key requires a model to be specified via --model, --provider/--model, or --models\",\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tawait modelRuntime.setRuntimeApiKey(sessionOptions.model.provider, parsed.apiKey, { allowNetwork: false });\n\t\t\t\tawait services.modelRuntime.getAvailable();\n\t\t\t}\n\t\t}\n\n\t\tconst created = await createAgentSessionFromServices({\n\t\t\tservices,\n\t\t\tsessionManager,\n\t\t\tsessionStartEvent,\n\t\t\tmodel: sessionOptions.model,\n\t\t\tthinkingLevel: sessionOptions.thinkingLevel,\n\t\t\tscopedModels: sessionOptions.scopedModels,\n\t\t\ttools: sessionOptions.tools,\n\t\t\texcludeTools: sessionOptions.excludeTools,\n\t\t\tnoTools: sessionOptions.noTools,\n\t\t\tcustomTools: sessionOptions.customTools,\n\t\t});\n\t\tconst cliThinkingOverride = parsed.thinking !== undefined || cliThinkingFromModel;\n\t\tif (created.session.model && cliThinkingOverride) {\n\t\t\tcreated.session.setThinkingLevel(created.session.thinkingLevel);\n\t\t}\n\n\t\treturn {\n\t\t\t...created,\n\t\t\tservices,\n\t\t\tdiagnostics,\n\t\t};\n\t};\n\ttime(\"createRuntime\");\n\tconst runtime = await createAgentSessionRuntime(createRuntime, {\n\t\tcwd: sessionManager.getCwd(),\n\t\tagentDir,\n\t\tsessionManager,\n\t});\n\ttime(\"createAgentSessionRuntime\");\n\tconst { services, session, modelFallbackMessage } = runtime;\n\tconst { settingsManager, modelRuntime, resourceLoader } = services;\n\tapplyHttpProxySettings(settingsManager.getGlobalSettings().httpProxy);\n\tconfigureHttpDispatcher(settingsManager.getHttpIdleTimeoutMs());\n\n\tif (parsed.help) {\n\t\tconst extensionFlags = resourceLoader\n\t\t\t.getExtensions()\n\t\t\t.extensions.flatMap((extension) => Array.from(extension.flags.values()));\n\t\tprintHelp(extensionFlags);\n\t\tprocess.exit(0);\n\t}\n\n\tif (parsed.listModels !== undefined) {\n\t\tconst searchPattern = typeof parsed.listModels === \"string\" ? parsed.listModels : undefined;\n\t\tawait listModels(modelRuntime, searchPattern);\n\t\tprocess.exit(0);\n\t}\n\n\t// Read piped stdin content (if any) - skip for RPC mode which uses stdin for JSON-RPC\n\tlet stdinContent: string | undefined;\n\tif (appMode !== \"rpc\") {\n\t\tstdinContent = await readPipedStdin();\n\t\tif (stdinContent !== undefined && appMode === \"interactive\") {\n\t\t\tappMode = \"print\";\n\t\t}\n\t}\n\ttime(\"readPipedStdin\");\n\n\tconst { initialMessage, initialImages } = await prepareInitialMessage(\n\t\tparsed,\n\t\tsettingsManager.getImageAutoResize(),\n\t\tstdinContent,\n\t);\n\ttime(\"prepareInitialMessage\");\n\tinitTheme(settingsManager.getTheme(), appMode === \"interactive\");\n\ttime(\"initTheme\");\n\n\t// Show deprecation warnings in interactive mode\n\tif (appMode === \"interactive\" && deprecationWarnings.length > 0) {\n\t\tawait showDeprecationWarnings(deprecationWarnings);\n\t}\n\n\ttime(\"resolveModelScope\");\n\treportDiagnostics(runtime.diagnostics);\n\tif (runtime.diagnostics.some((diagnostic) => diagnostic.type === \"error\")) {\n\t\tif (runtime.diagnostics.some((diagnostic) => diagnostic.message.includes(\"Failed to load extension\"))) {\n\t\t\tconsole.error(chalk.yellow(EXTENSION_LOAD_FAILURE_HINT));\n\t\t}\n\t\tprocess.exit(1);\n\t}\n\ttime(\"createAgentSession\");\n\n\tif (appMode !== \"interactive\" && !session.model) {\n\t\tconsole.error(chalk.red(formatNoModelsAvailableMessage()));\n\t\tprocess.exit(1);\n\t}\n\n\tconst startupBenchmark = isTruthyEnvFlag(process.env.PI_STARTUP_BENCHMARK);\n\tif (startupBenchmark && appMode !== \"interactive\") {\n\t\tconsole.error(chalk.red(\"Error: PI_STARTUP_BENCHMARK only supports interactive mode\"));\n\t\tprocess.exit(1);\n\t}\n\n\t// RPC refreshes catalogs here in the background; interactive mode starts its refresh after TUI initialization.\n\tif (!offlineMode && appMode === \"rpc\") {\n\t\tvoid modelRuntime.refresh().catch(() => {});\n\t}\n\n\tif (appMode === \"rpc\") {\n\t\tprintTimings();\n\t\tawait runRpcMode(runtime);\n\t} else if (appMode === \"interactive\") {\n\t\tconst interactiveMode = new InteractiveMode(runtime, {\n\t\t\tmigratedProviders,\n\t\t\tmodelFallbackMessage,\n\t\t\tautoTrustOnReloadCwd,\n\t\t\tinitialMessage,\n\t\t\tinitialImages,\n\t\t\tinitialMessages: parsed.messages,\n\t\t\tverbose: parsed.verbose,\n\t\t});\n\t\tif (startupBenchmark) {\n\t\t\tawait interactiveMode.init();\n\t\t\ttime(\"interactiveMode.init\");\n\t\t\t// Give the TUI's stdin handler a brief chance to consume terminal query replies\n\t\t\t// (Kitty keyboard protocol, device attributes, cell size) before restoring the terminal.\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 150));\n\t\t\tinteractiveMode.stop();\n\t\t\tstopThemeWatcher();\n\t\t\tprintTimings();\n\t\t\tif (process.stdout.writableLength > 0) {\n\t\t\t\tawait new Promise((resolve) => process.stdout.once(\"drain\", resolve));\n\t\t\t}\n\t\t\tif (process.stderr.writableLength > 0) {\n\t\t\t\tawait new Promise((resolve) => process.stderr.once(\"drain\", resolve));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tprintTimings();\n\t\tawait interactiveMode.run();\n\t} else {\n\t\tprintTimings();\n\t\tconst exitCode = await runPrintMode(runtime, {\n\t\t\tmode: toPrintOutputMode(appMode),\n\t\t\tmessages: parsed.messages,\n\t\t\tinitialMessage,\n\t\t\tinitialImages,\n\t\t});\n\t\tstopThemeWatcher();\n\t\trestoreStdout();\n\t\tif (exitCode !== 0) {\n\t\t\tprocess.exitCode = exitCode;\n\t\t}\n\t\treturn;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/migrations.d.ts b/dist/migrations.d.ts new file mode 100644 index 0000000..c187b49 --- /dev/null +++ b/dist/migrations.d.ts @@ -0,0 +1,33 @@ +/** + * One-time migrations that run on startup. + */ +/** + * Migrate legacy oauth.json and settings.json apiKeys to auth.json. + * + * @returns Array of provider names that were migrated + */ +export declare function migrateAuthToAuthJson(): string[]; +/** + * Migrate sessions from ~/.pi/agent/*.jsonl to proper session directories. + * + * Bug in v0.30.0: Sessions were saved to ~/.pi/agent/ instead of + * ~/.pi/agent/sessions//. This migration moves them + * to the correct location based on the cwd in their session header. + * + * See: https://github.com/earendil-works/pi-mono/issues/320 + */ +export declare function migrateSessionsFromAgentRoot(): void; +/** + * Print deprecation warnings and wait for keypress. + */ +export declare function showDeprecationWarnings(warnings: string[]): Promise; +/** + * Run all migrations. Called once on startup. + * + * @returns Object with migration results and deprecation warnings + */ +export declare function runMigrations(cwd: string): { + migratedAuthProviders: string[]; + deprecationWarnings: string[]; +}; +//# sourceMappingURL=migrations.d.ts.map \ No newline at end of file diff --git a/dist/migrations.d.ts.map b/dist/migrations.d.ts.map new file mode 100644 index 0000000..76680c4 --- /dev/null +++ b/dist/migrations.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"migrations.d.ts","sourceRoot":"","sources":["../src/migrations.ts"],"names":[],"mappings":"AAAA;;GAEG;AAaH;;;;GAIG;AACH,wBAAgB,qBAAqB,IAAI,MAAM,EAAE,CAoDhD;AAED;;;;;;;;GAQG;AACH,wBAAgB,4BAA4B,IAAI,IAAI,CA+CnD;AA+ID;;GAEG;AACH,wBAAsB,uBAAuB,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAqB/E;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG;IAC3C,qBAAqB,EAAE,MAAM,EAAE,CAAC;IAChC,mBAAmB,EAAE,MAAM,EAAE,CAAC;CAC9B,CAOA","sourcesContent":["/**\n * One-time migrations that run on startup.\n */\n\nimport chalk from \"chalk\";\nimport { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir, getBinDir } from \"./config.ts\";\nimport { migrateKeybindingsConfig } from \"./core/keybindings.ts\";\n\nconst MIGRATION_GUIDE_URL =\n\t\"https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration\";\nconst EXTENSIONS_DOC_URL =\n\t\"https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/extensions.md\";\n\n/**\n * Migrate legacy oauth.json and settings.json apiKeys to auth.json.\n *\n * @returns Array of provider names that were migrated\n */\nexport function migrateAuthToAuthJson(): string[] {\n\tconst agentDir = getAgentDir();\n\tconst authPath = join(agentDir, \"auth.json\");\n\tconst oauthPath = join(agentDir, \"oauth.json\");\n\tconst settingsPath = join(agentDir, \"settings.json\");\n\n\t// Skip if auth.json already exists\n\tif (existsSync(authPath)) return [];\n\n\tconst migrated: Record = {};\n\tconst providers: string[] = [];\n\n\t// Migrate oauth.json\n\tif (existsSync(oauthPath)) {\n\t\ttry {\n\t\t\tconst oauth = JSON.parse(readFileSync(oauthPath, \"utf-8\"));\n\t\t\tfor (const [provider, cred] of Object.entries(oauth)) {\n\t\t\t\tmigrated[provider] = { type: \"oauth\", ...(cred as object) };\n\t\t\t\tproviders.push(provider);\n\t\t\t}\n\t\t\trenameSync(oauthPath, `${oauthPath}.migrated`);\n\t\t} catch {\n\t\t\t// Skip on error\n\t\t}\n\t}\n\n\t// Migrate settings.json apiKeys\n\tif (existsSync(settingsPath)) {\n\t\ttry {\n\t\t\tconst content = readFileSync(settingsPath, \"utf-8\");\n\t\t\tconst settings = JSON.parse(content);\n\t\t\tif (settings.apiKeys && typeof settings.apiKeys === \"object\") {\n\t\t\t\tfor (const [provider, key] of Object.entries(settings.apiKeys)) {\n\t\t\t\t\tif (!migrated[provider] && typeof key === \"string\") {\n\t\t\t\t\t\tmigrated[provider] = { type: \"api_key\", key };\n\t\t\t\t\t\tproviders.push(provider);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdelete settings.apiKeys;\n\t\t\t\twriteFileSync(settingsPath, JSON.stringify(settings, null, 2));\n\t\t\t}\n\t\t} catch {\n\t\t\t// Skip on error\n\t\t}\n\t}\n\n\tif (Object.keys(migrated).length > 0) {\n\t\tmkdirSync(dirname(authPath), { recursive: true });\n\t\twriteFileSync(authPath, JSON.stringify(migrated, null, 2), { mode: 0o600 });\n\t}\n\n\treturn providers;\n}\n\n/**\n * Migrate sessions from ~/.pi/agent/*.jsonl to proper session directories.\n *\n * Bug in v0.30.0: Sessions were saved to ~/.pi/agent/ instead of\n * ~/.pi/agent/sessions//. This migration moves them\n * to the correct location based on the cwd in their session header.\n *\n * See: https://github.com/earendil-works/pi-mono/issues/320\n */\nexport function migrateSessionsFromAgentRoot(): void {\n\tconst agentDir = getAgentDir();\n\n\t// Find all .jsonl files directly in agentDir (not in subdirectories)\n\tlet files: string[];\n\ttry {\n\t\tfiles = readdirSync(agentDir)\n\t\t\t.filter((f) => f.endsWith(\".jsonl\"))\n\t\t\t.map((f) => join(agentDir, f));\n\t} catch {\n\t\treturn;\n\t}\n\n\tif (files.length === 0) return;\n\n\tfor (const file of files) {\n\t\ttry {\n\t\t\t// Read first line to get session header\n\t\t\tconst content = readFileSync(file, \"utf8\");\n\t\t\tconst firstLine = content.split(\"\\n\")[0];\n\t\t\tif (!firstLine?.trim()) continue;\n\n\t\t\tconst header = JSON.parse(firstLine);\n\t\t\tif (header.type !== \"session\" || !header.cwd) continue;\n\n\t\t\tconst cwd: string = header.cwd;\n\n\t\t\t// Compute the correct session directory (same encoding as session-manager.ts)\n\t\t\tconst safePath = `--${cwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n\t\t\tconst correctDir = join(agentDir, \"sessions\", safePath);\n\n\t\t\t// Create directory if needed\n\t\t\tif (!existsSync(correctDir)) {\n\t\t\t\tmkdirSync(correctDir, { recursive: true });\n\t\t\t}\n\n\t\t\t// Move the file\n\t\t\tconst fileName = file.split(\"/\").pop() || file.split(\"\\\\\").pop();\n\t\t\tconst newPath = join(correctDir, fileName!);\n\n\t\t\tif (existsSync(newPath)) continue; // Skip if target exists\n\n\t\t\trenameSync(file, newPath);\n\t\t} catch {\n\t\t\t// Skip files that can't be migrated\n\t\t}\n\t}\n}\n\n/**\n * Migrate commands/ to prompts/ if needed.\n * Works for both regular directories and symlinks.\n */\nfunction migrateCommandsToPrompts(baseDir: string, label: string): boolean {\n\tconst commandsDir = join(baseDir, \"commands\");\n\tconst promptsDir = join(baseDir, \"prompts\");\n\n\tif (existsSync(commandsDir) && !existsSync(promptsDir)) {\n\t\ttry {\n\t\t\trenameSync(commandsDir, promptsDir);\n\t\t\tconsole.log(chalk.green(`Migrated ${label} commands/ → prompts/`));\n\t\t\treturn true;\n\t\t} catch (err) {\n\t\t\tconsole.log(\n\t\t\t\tchalk.yellow(\n\t\t\t\t\t`Warning: Could not migrate ${label} commands/ to prompts/: ${err instanceof Error ? err.message : err}`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction migrateKeybindingsConfigFile(): void {\n\tconst configPath = join(getAgentDir(), \"keybindings.json\");\n\tif (!existsSync(configPath)) return;\n\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(configPath, \"utf-8\")) as unknown;\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\treturn;\n\t\t}\n\t\tconst { config, migrated } = migrateKeybindingsConfig(parsed as Record);\n\t\tif (!migrated) return;\n\t\twriteFileSync(configPath, `${JSON.stringify(config, null, 2)}\\n`, \"utf-8\");\n\t} catch {\n\t\t// Ignore malformed files during migration\n\t}\n}\n\n/**\n * Move fd/rg binaries from tools/ to bin/ if they exist.\n */\nfunction migrateToolsToBin(): void {\n\tconst agentDir = getAgentDir();\n\tconst toolsDir = join(agentDir, \"tools\");\n\tconst binDir = getBinDir();\n\n\tif (!existsSync(toolsDir)) return;\n\n\tconst binaries = [\"fd\", \"rg\", \"fd.exe\", \"rg.exe\"];\n\tlet movedAny = false;\n\n\tfor (const bin of binaries) {\n\t\tconst oldPath = join(toolsDir, bin);\n\t\tconst newPath = join(binDir, bin);\n\n\t\tif (existsSync(oldPath)) {\n\t\t\tif (!existsSync(binDir)) {\n\t\t\t\tmkdirSync(binDir, { recursive: true });\n\t\t\t}\n\t\t\tif (!existsSync(newPath)) {\n\t\t\t\ttry {\n\t\t\t\t\trenameSync(oldPath, newPath);\n\t\t\t\t\tmovedAny = true;\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore errors\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Target exists, just delete the old one\n\t\t\t\ttry {\n\t\t\t\t\trmSync?.(oldPath, { force: true });\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (movedAny) {\n\t\tconsole.log(chalk.green(`Migrated managed binaries tools/ → bin/`));\n\t}\n}\n\n/**\n * Check for deprecated hooks/ and tools/ directories.\n * Note: tools/ may contain fd/rg binaries extracted by pi, so only warn if it has other files.\n */\nfunction checkDeprecatedExtensionDirs(baseDir: string, label: string): string[] {\n\tconst hooksDir = join(baseDir, \"hooks\");\n\tconst toolsDir = join(baseDir, \"tools\");\n\tconst warnings: string[] = [];\n\n\tif (existsSync(hooksDir)) {\n\t\twarnings.push(`${label} hooks/ directory found. Hooks have been renamed to extensions.`);\n\t}\n\n\tif (existsSync(toolsDir)) {\n\t\t// Check if tools/ contains anything other than fd/rg (which are auto-extracted binaries)\n\t\ttry {\n\t\t\tconst entries = readdirSync(toolsDir);\n\t\t\tconst customTools = entries.filter((e) => {\n\t\t\t\tconst lower = e.toLowerCase();\n\t\t\t\treturn (\n\t\t\t\t\tlower !== \"fd\" && lower !== \"rg\" && lower !== \"fd.exe\" && lower !== \"rg.exe\" && !e.startsWith(\".\") // Ignore .DS_Store and other hidden files\n\t\t\t\t);\n\t\t\t});\n\t\t\tif (customTools.length > 0) {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`${label} tools/ directory contains custom tools. Custom tools have been merged into extensions.`,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore read errors\n\t\t}\n\t}\n\n\treturn warnings;\n}\n\n/**\n * Run extension system migrations (commands→prompts) and collect warnings about deprecated directories.\n */\nfunction migrateExtensionSystem(cwd: string): string[] {\n\tconst agentDir = getAgentDir();\n\tconst projectDir = join(cwd, CONFIG_DIR_NAME);\n\n\t// Migrate commands/ to prompts/\n\tmigrateCommandsToPrompts(agentDir, \"Global\");\n\tmigrateCommandsToPrompts(projectDir, \"Project\");\n\n\t// Check for deprecated directories\n\tconst warnings = [\n\t\t...checkDeprecatedExtensionDirs(agentDir, \"Global\"),\n\t\t...checkDeprecatedExtensionDirs(projectDir, \"Project\"),\n\t];\n\n\treturn warnings;\n}\n\n/**\n * Print deprecation warnings and wait for keypress.\n */\nexport async function showDeprecationWarnings(warnings: string[]): Promise {\n\tif (warnings.length === 0) return;\n\n\tfor (const warning of warnings) {\n\t\tconsole.log(chalk.yellow(`Warning: ${warning}`));\n\t}\n\tconsole.log(chalk.yellow(`\\nMove your extensions to the extensions/ directory.`));\n\tconsole.log(chalk.yellow(`Migration guide: ${MIGRATION_GUIDE_URL}`));\n\tconsole.log(chalk.yellow(`Documentation: ${EXTENSIONS_DOC_URL}`));\n\tconsole.log(chalk.dim(`\\nPress any key to continue...`));\n\n\tawait new Promise((resolve) => {\n\t\tprocess.stdin.setRawMode?.(true);\n\t\tprocess.stdin.resume();\n\t\tprocess.stdin.once(\"data\", () => {\n\t\t\tprocess.stdin.setRawMode?.(false);\n\t\t\tprocess.stdin.pause();\n\t\t\tresolve();\n\t\t});\n\t});\n\tconsole.log();\n}\n\n/**\n * Run all migrations. Called once on startup.\n *\n * @returns Object with migration results and deprecation warnings\n */\nexport function runMigrations(cwd: string): {\n\tmigratedAuthProviders: string[];\n\tdeprecationWarnings: string[];\n} {\n\tconst migratedAuthProviders = migrateAuthToAuthJson();\n\tmigrateSessionsFromAgentRoot();\n\tmigrateToolsToBin();\n\tmigrateKeybindingsConfigFile();\n\tconst deprecationWarnings = migrateExtensionSystem(cwd);\n\treturn { migratedAuthProviders, deprecationWarnings };\n}\n"]} \ No newline at end of file diff --git a/dist/migrations.js b/dist/migrations.js new file mode 100644 index 0000000..e3a5ccf --- /dev/null +++ b/dist/migrations.js @@ -0,0 +1,281 @@ +/** + * One-time migrations that run on startup. + */ +import chalk from "chalk"; +import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs"; +import { dirname, join } from "path"; +import { CONFIG_DIR_NAME, getAgentDir, getBinDir } from "./config.js"; +import { migrateKeybindingsConfig } from "./core/keybindings.js"; +const MIGRATION_GUIDE_URL = "https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration"; +const EXTENSIONS_DOC_URL = "https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/extensions.md"; +/** + * Migrate legacy oauth.json and settings.json apiKeys to auth.json. + * + * @returns Array of provider names that were migrated + */ +export function migrateAuthToAuthJson() { + const agentDir = getAgentDir(); + const authPath = join(agentDir, "auth.json"); + const oauthPath = join(agentDir, "oauth.json"); + const settingsPath = join(agentDir, "settings.json"); + // Skip if auth.json already exists + if (existsSync(authPath)) + return []; + const migrated = {}; + const providers = []; + // Migrate oauth.json + if (existsSync(oauthPath)) { + try { + const oauth = JSON.parse(readFileSync(oauthPath, "utf-8")); + for (const [provider, cred] of Object.entries(oauth)) { + migrated[provider] = { type: "oauth", ...cred }; + providers.push(provider); + } + renameSync(oauthPath, `${oauthPath}.migrated`); + } + catch { + // Skip on error + } + } + // Migrate settings.json apiKeys + if (existsSync(settingsPath)) { + try { + const content = readFileSync(settingsPath, "utf-8"); + const settings = JSON.parse(content); + if (settings.apiKeys && typeof settings.apiKeys === "object") { + for (const [provider, key] of Object.entries(settings.apiKeys)) { + if (!migrated[provider] && typeof key === "string") { + migrated[provider] = { type: "api_key", key }; + providers.push(provider); + } + } + delete settings.apiKeys; + writeFileSync(settingsPath, JSON.stringify(settings, null, 2)); + } + } + catch { + // Skip on error + } + } + if (Object.keys(migrated).length > 0) { + mkdirSync(dirname(authPath), { recursive: true }); + writeFileSync(authPath, JSON.stringify(migrated, null, 2), { mode: 0o600 }); + } + return providers; +} +/** + * Migrate sessions from ~/.pi/agent/*.jsonl to proper session directories. + * + * Bug in v0.30.0: Sessions were saved to ~/.pi/agent/ instead of + * ~/.pi/agent/sessions//. This migration moves them + * to the correct location based on the cwd in their session header. + * + * See: https://github.com/earendil-works/pi-mono/issues/320 + */ +export function migrateSessionsFromAgentRoot() { + const agentDir = getAgentDir(); + // Find all .jsonl files directly in agentDir (not in subdirectories) + let files; + try { + files = readdirSync(agentDir) + .filter((f) => f.endsWith(".jsonl")) + .map((f) => join(agentDir, f)); + } + catch { + return; + } + if (files.length === 0) + return; + for (const file of files) { + try { + // Read first line to get session header + const content = readFileSync(file, "utf8"); + const firstLine = content.split("\n")[0]; + if (!firstLine?.trim()) + continue; + const header = JSON.parse(firstLine); + if (header.type !== "session" || !header.cwd) + continue; + const cwd = header.cwd; + // Compute the correct session directory (same encoding as session-manager.ts) + const safePath = `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`; + const correctDir = join(agentDir, "sessions", safePath); + // Create directory if needed + if (!existsSync(correctDir)) { + mkdirSync(correctDir, { recursive: true }); + } + // Move the file + const fileName = file.split("/").pop() || file.split("\\").pop(); + const newPath = join(correctDir, fileName); + if (existsSync(newPath)) + continue; // Skip if target exists + renameSync(file, newPath); + } + catch { + // Skip files that can't be migrated + } + } +} +/** + * Migrate commands/ to prompts/ if needed. + * Works for both regular directories and symlinks. + */ +function migrateCommandsToPrompts(baseDir, label) { + const commandsDir = join(baseDir, "commands"); + const promptsDir = join(baseDir, "prompts"); + if (existsSync(commandsDir) && !existsSync(promptsDir)) { + try { + renameSync(commandsDir, promptsDir); + console.log(chalk.green(`Migrated ${label} commands/ → prompts/`)); + return true; + } + catch (err) { + console.log(chalk.yellow(`Warning: Could not migrate ${label} commands/ to prompts/: ${err instanceof Error ? err.message : err}`)); + } + } + return false; +} +function migrateKeybindingsConfigFile() { + const configPath = join(getAgentDir(), "keybindings.json"); + if (!existsSync(configPath)) + return; + try { + const parsed = JSON.parse(readFileSync(configPath, "utf-8")); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + return; + } + const { config, migrated } = migrateKeybindingsConfig(parsed); + if (!migrated) + return; + writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf-8"); + } + catch { + // Ignore malformed files during migration + } +} +/** + * Move fd/rg binaries from tools/ to bin/ if they exist. + */ +function migrateToolsToBin() { + const agentDir = getAgentDir(); + const toolsDir = join(agentDir, "tools"); + const binDir = getBinDir(); + if (!existsSync(toolsDir)) + return; + const binaries = ["fd", "rg", "fd.exe", "rg.exe"]; + let movedAny = false; + for (const bin of binaries) { + const oldPath = join(toolsDir, bin); + const newPath = join(binDir, bin); + if (existsSync(oldPath)) { + if (!existsSync(binDir)) { + mkdirSync(binDir, { recursive: true }); + } + if (!existsSync(newPath)) { + try { + renameSync(oldPath, newPath); + movedAny = true; + } + catch { + // Ignore errors + } + } + else { + // Target exists, just delete the old one + try { + rmSync?.(oldPath, { force: true }); + } + catch { + // Ignore + } + } + } + } + if (movedAny) { + console.log(chalk.green(`Migrated managed binaries tools/ → bin/`)); + } +} +/** + * Check for deprecated hooks/ and tools/ directories. + * Note: tools/ may contain fd/rg binaries extracted by pi, so only warn if it has other files. + */ +function checkDeprecatedExtensionDirs(baseDir, label) { + const hooksDir = join(baseDir, "hooks"); + const toolsDir = join(baseDir, "tools"); + const warnings = []; + if (existsSync(hooksDir)) { + warnings.push(`${label} hooks/ directory found. Hooks have been renamed to extensions.`); + } + if (existsSync(toolsDir)) { + // Check if tools/ contains anything other than fd/rg (which are auto-extracted binaries) + try { + const entries = readdirSync(toolsDir); + const customTools = entries.filter((e) => { + const lower = e.toLowerCase(); + return (lower !== "fd" && lower !== "rg" && lower !== "fd.exe" && lower !== "rg.exe" && !e.startsWith(".") // Ignore .DS_Store and other hidden files + ); + }); + if (customTools.length > 0) { + warnings.push(`${label} tools/ directory contains custom tools. Custom tools have been merged into extensions.`); + } + } + catch { + // Ignore read errors + } + } + return warnings; +} +/** + * Run extension system migrations (commands→prompts) and collect warnings about deprecated directories. + */ +function migrateExtensionSystem(cwd) { + const agentDir = getAgentDir(); + const projectDir = join(cwd, CONFIG_DIR_NAME); + // Migrate commands/ to prompts/ + migrateCommandsToPrompts(agentDir, "Global"); + migrateCommandsToPrompts(projectDir, "Project"); + // Check for deprecated directories + const warnings = [ + ...checkDeprecatedExtensionDirs(agentDir, "Global"), + ...checkDeprecatedExtensionDirs(projectDir, "Project"), + ]; + return warnings; +} +/** + * Print deprecation warnings and wait for keypress. + */ +export async function showDeprecationWarnings(warnings) { + if (warnings.length === 0) + return; + for (const warning of warnings) { + console.log(chalk.yellow(`Warning: ${warning}`)); + } + console.log(chalk.yellow(`\nMove your extensions to the extensions/ directory.`)); + console.log(chalk.yellow(`Migration guide: ${MIGRATION_GUIDE_URL}`)); + console.log(chalk.yellow(`Documentation: ${EXTENSIONS_DOC_URL}`)); + console.log(chalk.dim(`\nPress any key to continue...`)); + await new Promise((resolve) => { + process.stdin.setRawMode?.(true); + process.stdin.resume(); + process.stdin.once("data", () => { + process.stdin.setRawMode?.(false); + process.stdin.pause(); + resolve(); + }); + }); + console.log(); +} +/** + * Run all migrations. Called once on startup. + * + * @returns Object with migration results and deprecation warnings + */ +export function runMigrations(cwd) { + const migratedAuthProviders = migrateAuthToAuthJson(); + migrateSessionsFromAgentRoot(); + migrateToolsToBin(); + migrateKeybindingsConfigFile(); + const deprecationWarnings = migrateExtensionSystem(cwd); + return { migratedAuthProviders, deprecationWarnings }; +} +//# sourceMappingURL=migrations.js.map \ No newline at end of file diff --git a/dist/migrations.js.map b/dist/migrations.js.map new file mode 100644 index 0000000..2a1a981 --- /dev/null +++ b/dist/migrations.js.map @@ -0,0 +1 @@ +{"version":3,"file":"migrations.js","sourceRoot":"","sources":["../src/migrations.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACzG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qBAAqB,EAAE,CAAC;IACtD,4BAA4B,EAAE,CAAC;IAC/B,iBAAiB,EAAE,CAAC;IACpB,4BAA4B,EAAE,CAAC;IAC/B,MAAM,mBAAmB,GAAG,sBAAsB,CAAC,GAAG,CAAC,CAAC;IACxD,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,CAAC;AAAA,CACtD","sourcesContent":["/**\n * One-time migrations that run on startup.\n */\n\nimport chalk from \"chalk\";\nimport { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir, getBinDir } from \"./config.ts\";\nimport { migrateKeybindingsConfig } from \"./core/keybindings.ts\";\n\nconst MIGRATION_GUIDE_URL =\n\t\"https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/CHANGELOG.md#extensions-migration\";\nconst EXTENSIONS_DOC_URL =\n\t\"https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/extensions.md\";\n\n/**\n * Migrate legacy oauth.json and settings.json apiKeys to auth.json.\n *\n * @returns Array of provider names that were migrated\n */\nexport function migrateAuthToAuthJson(): string[] {\n\tconst agentDir = getAgentDir();\n\tconst authPath = join(agentDir, \"auth.json\");\n\tconst oauthPath = join(agentDir, \"oauth.json\");\n\tconst settingsPath = join(agentDir, \"settings.json\");\n\n\t// Skip if auth.json already exists\n\tif (existsSync(authPath)) return [];\n\n\tconst migrated: Record = {};\n\tconst providers: string[] = [];\n\n\t// Migrate oauth.json\n\tif (existsSync(oauthPath)) {\n\t\ttry {\n\t\t\tconst oauth = JSON.parse(readFileSync(oauthPath, \"utf-8\"));\n\t\t\tfor (const [provider, cred] of Object.entries(oauth)) {\n\t\t\t\tmigrated[provider] = { type: \"oauth\", ...(cred as object) };\n\t\t\t\tproviders.push(provider);\n\t\t\t}\n\t\t\trenameSync(oauthPath, `${oauthPath}.migrated`);\n\t\t} catch {\n\t\t\t// Skip on error\n\t\t}\n\t}\n\n\t// Migrate settings.json apiKeys\n\tif (existsSync(settingsPath)) {\n\t\ttry {\n\t\t\tconst content = readFileSync(settingsPath, \"utf-8\");\n\t\t\tconst settings = JSON.parse(content);\n\t\t\tif (settings.apiKeys && typeof settings.apiKeys === \"object\") {\n\t\t\t\tfor (const [provider, key] of Object.entries(settings.apiKeys)) {\n\t\t\t\t\tif (!migrated[provider] && typeof key === \"string\") {\n\t\t\t\t\t\tmigrated[provider] = { type: \"api_key\", key };\n\t\t\t\t\t\tproviders.push(provider);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdelete settings.apiKeys;\n\t\t\t\twriteFileSync(settingsPath, JSON.stringify(settings, null, 2));\n\t\t\t}\n\t\t} catch {\n\t\t\t// Skip on error\n\t\t}\n\t}\n\n\tif (Object.keys(migrated).length > 0) {\n\t\tmkdirSync(dirname(authPath), { recursive: true });\n\t\twriteFileSync(authPath, JSON.stringify(migrated, null, 2), { mode: 0o600 });\n\t}\n\n\treturn providers;\n}\n\n/**\n * Migrate sessions from ~/.pi/agent/*.jsonl to proper session directories.\n *\n * Bug in v0.30.0: Sessions were saved to ~/.pi/agent/ instead of\n * ~/.pi/agent/sessions//. This migration moves them\n * to the correct location based on the cwd in their session header.\n *\n * See: https://github.com/earendil-works/pi-mono/issues/320\n */\nexport function migrateSessionsFromAgentRoot(): void {\n\tconst agentDir = getAgentDir();\n\n\t// Find all .jsonl files directly in agentDir (not in subdirectories)\n\tlet files: string[];\n\ttry {\n\t\tfiles = readdirSync(agentDir)\n\t\t\t.filter((f) => f.endsWith(\".jsonl\"))\n\t\t\t.map((f) => join(agentDir, f));\n\t} catch {\n\t\treturn;\n\t}\n\n\tif (files.length === 0) return;\n\n\tfor (const file of files) {\n\t\ttry {\n\t\t\t// Read first line to get session header\n\t\t\tconst content = readFileSync(file, \"utf8\");\n\t\t\tconst firstLine = content.split(\"\\n\")[0];\n\t\t\tif (!firstLine?.trim()) continue;\n\n\t\t\tconst header = JSON.parse(firstLine);\n\t\t\tif (header.type !== \"session\" || !header.cwd) continue;\n\n\t\t\tconst cwd: string = header.cwd;\n\n\t\t\t// Compute the correct session directory (same encoding as session-manager.ts)\n\t\t\tconst safePath = `--${cwd.replace(/^[/\\\\]/, \"\").replace(/[/\\\\:]/g, \"-\")}--`;\n\t\t\tconst correctDir = join(agentDir, \"sessions\", safePath);\n\n\t\t\t// Create directory if needed\n\t\t\tif (!existsSync(correctDir)) {\n\t\t\t\tmkdirSync(correctDir, { recursive: true });\n\t\t\t}\n\n\t\t\t// Move the file\n\t\t\tconst fileName = file.split(\"/\").pop() || file.split(\"\\\\\").pop();\n\t\t\tconst newPath = join(correctDir, fileName!);\n\n\t\t\tif (existsSync(newPath)) continue; // Skip if target exists\n\n\t\t\trenameSync(file, newPath);\n\t\t} catch {\n\t\t\t// Skip files that can't be migrated\n\t\t}\n\t}\n}\n\n/**\n * Migrate commands/ to prompts/ if needed.\n * Works for both regular directories and symlinks.\n */\nfunction migrateCommandsToPrompts(baseDir: string, label: string): boolean {\n\tconst commandsDir = join(baseDir, \"commands\");\n\tconst promptsDir = join(baseDir, \"prompts\");\n\n\tif (existsSync(commandsDir) && !existsSync(promptsDir)) {\n\t\ttry {\n\t\t\trenameSync(commandsDir, promptsDir);\n\t\t\tconsole.log(chalk.green(`Migrated ${label} commands/ → prompts/`));\n\t\t\treturn true;\n\t\t} catch (err) {\n\t\t\tconsole.log(\n\t\t\t\tchalk.yellow(\n\t\t\t\t\t`Warning: Could not migrate ${label} commands/ to prompts/: ${err instanceof Error ? err.message : err}`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction migrateKeybindingsConfigFile(): void {\n\tconst configPath = join(getAgentDir(), \"keybindings.json\");\n\tif (!existsSync(configPath)) return;\n\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(configPath, \"utf-8\")) as unknown;\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\t\treturn;\n\t\t}\n\t\tconst { config, migrated } = migrateKeybindingsConfig(parsed as Record);\n\t\tif (!migrated) return;\n\t\twriteFileSync(configPath, `${JSON.stringify(config, null, 2)}\\n`, \"utf-8\");\n\t} catch {\n\t\t// Ignore malformed files during migration\n\t}\n}\n\n/**\n * Move fd/rg binaries from tools/ to bin/ if they exist.\n */\nfunction migrateToolsToBin(): void {\n\tconst agentDir = getAgentDir();\n\tconst toolsDir = join(agentDir, \"tools\");\n\tconst binDir = getBinDir();\n\n\tif (!existsSync(toolsDir)) return;\n\n\tconst binaries = [\"fd\", \"rg\", \"fd.exe\", \"rg.exe\"];\n\tlet movedAny = false;\n\n\tfor (const bin of binaries) {\n\t\tconst oldPath = join(toolsDir, bin);\n\t\tconst newPath = join(binDir, bin);\n\n\t\tif (existsSync(oldPath)) {\n\t\t\tif (!existsSync(binDir)) {\n\t\t\t\tmkdirSync(binDir, { recursive: true });\n\t\t\t}\n\t\t\tif (!existsSync(newPath)) {\n\t\t\t\ttry {\n\t\t\t\t\trenameSync(oldPath, newPath);\n\t\t\t\t\tmovedAny = true;\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore errors\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Target exists, just delete the old one\n\t\t\t\ttry {\n\t\t\t\t\trmSync?.(oldPath, { force: true });\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (movedAny) {\n\t\tconsole.log(chalk.green(`Migrated managed binaries tools/ → bin/`));\n\t}\n}\n\n/**\n * Check for deprecated hooks/ and tools/ directories.\n * Note: tools/ may contain fd/rg binaries extracted by pi, so only warn if it has other files.\n */\nfunction checkDeprecatedExtensionDirs(baseDir: string, label: string): string[] {\n\tconst hooksDir = join(baseDir, \"hooks\");\n\tconst toolsDir = join(baseDir, \"tools\");\n\tconst warnings: string[] = [];\n\n\tif (existsSync(hooksDir)) {\n\t\twarnings.push(`${label} hooks/ directory found. Hooks have been renamed to extensions.`);\n\t}\n\n\tif (existsSync(toolsDir)) {\n\t\t// Check if tools/ contains anything other than fd/rg (which are auto-extracted binaries)\n\t\ttry {\n\t\t\tconst entries = readdirSync(toolsDir);\n\t\t\tconst customTools = entries.filter((e) => {\n\t\t\t\tconst lower = e.toLowerCase();\n\t\t\t\treturn (\n\t\t\t\t\tlower !== \"fd\" && lower !== \"rg\" && lower !== \"fd.exe\" && lower !== \"rg.exe\" && !e.startsWith(\".\") // Ignore .DS_Store and other hidden files\n\t\t\t\t);\n\t\t\t});\n\t\t\tif (customTools.length > 0) {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`${label} tools/ directory contains custom tools. Custom tools have been merged into extensions.`,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore read errors\n\t\t}\n\t}\n\n\treturn warnings;\n}\n\n/**\n * Run extension system migrations (commands→prompts) and collect warnings about deprecated directories.\n */\nfunction migrateExtensionSystem(cwd: string): string[] {\n\tconst agentDir = getAgentDir();\n\tconst projectDir = join(cwd, CONFIG_DIR_NAME);\n\n\t// Migrate commands/ to prompts/\n\tmigrateCommandsToPrompts(agentDir, \"Global\");\n\tmigrateCommandsToPrompts(projectDir, \"Project\");\n\n\t// Check for deprecated directories\n\tconst warnings = [\n\t\t...checkDeprecatedExtensionDirs(agentDir, \"Global\"),\n\t\t...checkDeprecatedExtensionDirs(projectDir, \"Project\"),\n\t];\n\n\treturn warnings;\n}\n\n/**\n * Print deprecation warnings and wait for keypress.\n */\nexport async function showDeprecationWarnings(warnings: string[]): Promise {\n\tif (warnings.length === 0) return;\n\n\tfor (const warning of warnings) {\n\t\tconsole.log(chalk.yellow(`Warning: ${warning}`));\n\t}\n\tconsole.log(chalk.yellow(`\\nMove your extensions to the extensions/ directory.`));\n\tconsole.log(chalk.yellow(`Migration guide: ${MIGRATION_GUIDE_URL}`));\n\tconsole.log(chalk.yellow(`Documentation: ${EXTENSIONS_DOC_URL}`));\n\tconsole.log(chalk.dim(`\\nPress any key to continue...`));\n\n\tawait new Promise((resolve) => {\n\t\tprocess.stdin.setRawMode?.(true);\n\t\tprocess.stdin.resume();\n\t\tprocess.stdin.once(\"data\", () => {\n\t\t\tprocess.stdin.setRawMode?.(false);\n\t\t\tprocess.stdin.pause();\n\t\t\tresolve();\n\t\t});\n\t});\n\tconsole.log();\n}\n\n/**\n * Run all migrations. Called once on startup.\n *\n * @returns Object with migration results and deprecation warnings\n */\nexport function runMigrations(cwd: string): {\n\tmigratedAuthProviders: string[];\n\tdeprecationWarnings: string[];\n} {\n\tconst migratedAuthProviders = migrateAuthToAuthJson();\n\tmigrateSessionsFromAgentRoot();\n\tmigrateToolsToBin();\n\tmigrateKeybindingsConfigFile();\n\tconst deprecationWarnings = migrateExtensionSystem(cwd);\n\treturn { migratedAuthProviders, deprecationWarnings };\n}\n"]} \ No newline at end of file diff --git a/dist/modes/index.d.ts b/dist/modes/index.d.ts new file mode 100644 index 0000000..d89a144 --- /dev/null +++ b/dist/modes/index.d.ts @@ -0,0 +1,9 @@ +/** + * Run modes for the coding agent. + */ +export { InteractiveMode, type InteractiveModeOptions } from "./interactive/interactive-mode.ts"; +export { type PrintModeOptions, runPrintMode } from "./print-mode.ts"; +export { type ModelInfo, RpcClient, type RpcClientOptions, type RpcEventListener } from "./rpc/rpc-client.ts"; +export { runRpcMode } from "./rpc/rpc-mode.ts"; +export type { RpcCommand, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcResponse, RpcSessionState, } from "./rpc/rpc-types.ts"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/modes/index.d.ts.map b/dist/modes/index.d.ts.map new file mode 100644 index 0000000..6729d14 --- /dev/null +++ b/dist/modes/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/modes/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,MAAM,mCAAmC,CAAC;AACjG,OAAO,EAAE,KAAK,gBAAgB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACtE,OAAO,EAAE,KAAK,SAAS,EAAE,SAAS,EAAE,KAAK,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC9G,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,YAAY,EACX,UAAU,EACV,qBAAqB,EACrB,sBAAsB,EACtB,WAAW,EACX,eAAe,GACf,MAAM,oBAAoB,CAAC","sourcesContent":["/**\n * Run modes for the coding agent.\n */\n\nexport { InteractiveMode, type InteractiveModeOptions } from \"./interactive/interactive-mode.ts\";\nexport { type PrintModeOptions, runPrintMode } from \"./print-mode.ts\";\nexport { type ModelInfo, RpcClient, type RpcClientOptions, type RpcEventListener } from \"./rpc/rpc-client.ts\";\nexport { runRpcMode } from \"./rpc/rpc-mode.ts\";\nexport type {\n\tRpcCommand,\n\tRpcExtensionUIRequest,\n\tRpcExtensionUIResponse,\n\tRpcResponse,\n\tRpcSessionState,\n} from \"./rpc/rpc-types.ts\";\n"]} \ No newline at end of file diff --git a/dist/modes/index.js b/dist/modes/index.js new file mode 100644 index 0000000..10528c3 --- /dev/null +++ b/dist/modes/index.js @@ -0,0 +1,8 @@ +/** + * Run modes for the coding agent. + */ +export { InteractiveMode } from "./interactive/interactive-mode.js"; +export { runPrintMode } from "./print-mode.js"; +export { RpcClient } from "./rpc/rpc-client.js"; +export { runRpcMode } from "./rpc/rpc-mode.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/modes/index.js.map b/dist/modes/index.js.map new file mode 100644 index 0000000..2753c87 --- /dev/null +++ b/dist/modes/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/modes/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,eAAe,EAA+B,MAAM,mCAAmC,CAAC;AACjG,OAAO,EAAyB,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACtE,OAAO,EAAkB,SAAS,EAAgD,MAAM,qBAAqB,CAAC;AAC9G,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC","sourcesContent":["/**\n * Run modes for the coding agent.\n */\n\nexport { InteractiveMode, type InteractiveModeOptions } from \"./interactive/interactive-mode.ts\";\nexport { type PrintModeOptions, runPrintMode } from \"./print-mode.ts\";\nexport { type ModelInfo, RpcClient, type RpcClientOptions, type RpcEventListener } from \"./rpc/rpc-client.ts\";\nexport { runRpcMode } from \"./rpc/rpc-mode.ts\";\nexport type {\n\tRpcCommand,\n\tRpcExtensionUIRequest,\n\tRpcExtensionUIResponse,\n\tRpcResponse,\n\tRpcSessionState,\n} from \"./rpc/rpc-types.ts\";\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/assets/clankolas.png b/dist/modes/interactive/assets/clankolas.png new file mode 100644 index 0000000..d3dc65d Binary files /dev/null and b/dist/modes/interactive/assets/clankolas.png differ diff --git a/dist/modes/interactive/components/armin.d.ts b/dist/modes/interactive/components/armin.d.ts new file mode 100644 index 0000000..a826c51 --- /dev/null +++ b/dist/modes/interactive/components/armin.d.ts @@ -0,0 +1,34 @@ +/** + * Armin says hi! A fun easter egg with animated XBM art. + */ +import type { Component, TUI } from "@earendil-works/pi-tui"; +export declare class ArminComponent implements Component { + private ui; + private interval; + private effect; + private finalGrid; + private currentGrid; + private effectState; + private cachedLines; + private cachedWidth; + private gridVersion; + private cachedVersion; + constructor(ui: TUI); + invalidate(): void; + render(width: number): string[]; + private createEmptyGrid; + private initEffect; + private startAnimation; + private stopAnimation; + private tickEffect; + private tickTypewriter; + private tickScanline; + private tickRain; + private tickFade; + private tickCrt; + private tickGlitch; + private tickDissolve; + private updateDisplay; + dispose(): void; +} +//# sourceMappingURL=armin.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/armin.d.ts.map b/dist/modes/interactive/components/armin.d.ts.map new file mode 100644 index 0000000..5d0765b --- /dev/null +++ b/dist/modes/interactive/components/armin.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"armin.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/armin.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAuD7D,qBAAa,cAAe,YAAW,SAAS;IAC/C,OAAO,CAAC,EAAE,CAAM;IAChB,OAAO,CAAC,QAAQ,CAA+C;IAC/D,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,SAAS,CAAa;IAC9B,OAAO,CAAC,WAAW,CAAa;IAChC,OAAO,CAAC,WAAW,CAA+B;IAClD,OAAO,CAAC,WAAW,CAAgB;IACnC,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,aAAa,CAAM;IAE3B,YAAY,EAAE,EAAE,GAAG,EAQlB;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAwB9B;IAED,OAAO,CAAC,eAAe;IAIvB,OAAO,CAAC,UAAU;IAgElB,OAAO,CAAC,cAAc;IAYtB,OAAO,CAAC,aAAa;IAOrB,OAAO,CAAC,UAAU;IAqBlB,OAAO,CAAC,cAAc;IActB,OAAO,CAAC,YAAY;IAYpB,OAAO,CAAC,QAAQ;IAmDhB,OAAO,CAAC,QAAQ;IAahB,OAAO,CAAC,OAAO;IAoBf,OAAO,CAAC,UAAU;IAgClB,OAAO,CAAC,YAAY;IAapB,OAAO,CAAC,aAAa;IAIrB,OAAO,IAAI,IAAI,CAEd;CACD","sourcesContent":["/**\n * Armin says hi! A fun easter egg with animated XBM art.\n */\n\nimport type { Component, TUI } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\n\n// XBM image: 31x36 pixels, LSB first, 1=background, 0=foreground\nconst WIDTH = 31;\nconst HEIGHT = 36;\nconst BITS = [\n\t0xff, 0xff, 0xff, 0x7f, 0xff, 0xf0, 0xff, 0x7f, 0xff, 0xed, 0xff, 0x7f, 0xff, 0xdb, 0xff, 0x7f, 0xff, 0xb7, 0xff,\n\t0x7f, 0xff, 0x77, 0xfe, 0x7f, 0x3f, 0xf8, 0xfe, 0x7f, 0xdf, 0xff, 0xfe, 0x7f, 0xdf, 0x3f, 0xfc, 0x7f, 0x9f, 0xc3,\n\t0xfb, 0x7f, 0x6f, 0xfc, 0xf4, 0x7f, 0xf7, 0x0f, 0xf7, 0x7f, 0xf7, 0xff, 0xf7, 0x7f, 0xf7, 0xff, 0xe3, 0x7f, 0xf7,\n\t0x07, 0xe8, 0x7f, 0xef, 0xf8, 0x67, 0x70, 0x0f, 0xff, 0xbb, 0x6f, 0xf1, 0x00, 0xd0, 0x5b, 0xfd, 0x3f, 0xec, 0x53,\n\t0xc1, 0xff, 0xef, 0x57, 0x9f, 0xfd, 0xee, 0x5f, 0x9f, 0xfc, 0xae, 0x5f, 0x1f, 0x78, 0xac, 0x5f, 0x3f, 0x00, 0x50,\n\t0x6c, 0x7f, 0x00, 0xdc, 0x77, 0xff, 0xc0, 0x3f, 0x78, 0xff, 0x01, 0xf8, 0x7f, 0xff, 0x03, 0x9c, 0x78, 0xff, 0x07,\n\t0x8c, 0x7c, 0xff, 0x0f, 0xce, 0x78, 0xff, 0xff, 0xcf, 0x7f, 0xff, 0xff, 0xcf, 0x78, 0xff, 0xff, 0xdf, 0x78, 0xff,\n\t0xff, 0xdf, 0x7d, 0xff, 0xff, 0x3f, 0x7e, 0xff, 0xff, 0xff, 0x7f,\n];\n\nconst BYTES_PER_ROW = Math.ceil(WIDTH / 8);\nconst DISPLAY_HEIGHT = Math.ceil(HEIGHT / 2); // Half-block rendering\n\ntype Effect = \"typewriter\" | \"scanline\" | \"rain\" | \"fade\" | \"crt\" | \"glitch\" | \"dissolve\";\n\nconst EFFECTS: Effect[] = [\"typewriter\", \"scanline\", \"rain\", \"fade\", \"crt\", \"glitch\", \"dissolve\"];\n\n// Get pixel at (x, y): true = foreground, false = background\nfunction getPixel(x: number, y: number): boolean {\n\tif (y >= HEIGHT) return false;\n\tconst byteIndex = y * BYTES_PER_ROW + Math.floor(x / 8);\n\tconst bitIndex = x % 8;\n\treturn ((BITS[byteIndex] >> bitIndex) & 1) === 0;\n}\n\n// Get the character for a cell (2 vertical pixels packed)\nfunction getChar(x: number, row: number): string {\n\tconst upper = getPixel(x, row * 2);\n\tconst lower = getPixel(x, row * 2 + 1);\n\tif (upper && lower) return \"█\";\n\tif (upper) return \"▀\";\n\tif (lower) return \"▄\";\n\treturn \" \";\n}\n\n// Build the final image grid\nfunction buildFinalGrid(): string[][] {\n\tconst grid: string[][] = [];\n\tfor (let row = 0; row < DISPLAY_HEIGHT; row++) {\n\t\tconst line: string[] = [];\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tline.push(getChar(x, row));\n\t\t}\n\t\tgrid.push(line);\n\t}\n\treturn grid;\n}\n\nexport class ArminComponent implements Component {\n\tprivate ui: TUI;\n\tprivate interval: ReturnType | null = null;\n\tprivate effect: Effect;\n\tprivate finalGrid: string[][];\n\tprivate currentGrid: string[][];\n\tprivate effectState: Record = {};\n\tprivate cachedLines: string[] = [];\n\tprivate cachedWidth = 0;\n\tprivate gridVersion = 0;\n\tprivate cachedVersion = -1;\n\n\tconstructor(ui: TUI) {\n\t\tthis.ui = ui;\n\t\tthis.effect = EFFECTS[Math.floor(Math.random() * EFFECTS.length)];\n\t\tthis.finalGrid = buildFinalGrid();\n\t\tthis.currentGrid = this.createEmptyGrid();\n\n\t\tthis.initEffect();\n\t\tthis.startAnimation();\n\t}\n\n\tinvalidate(): void {\n\t\tthis.cachedWidth = 0;\n\t}\n\n\trender(width: number): string[] {\n\t\tif (width === this.cachedWidth && this.cachedVersion === this.gridVersion) {\n\t\t\treturn this.cachedLines;\n\t\t}\n\n\t\tconst padding = 1;\n\t\tconst availableWidth = width - padding;\n\n\t\tthis.cachedLines = this.currentGrid.map((row) => {\n\t\t\t// Clip row to available width before applying color\n\t\t\tconst clipped = row.slice(0, availableWidth).join(\"\");\n\t\t\tconst padRight = Math.max(0, width - padding - clipped.length);\n\t\t\treturn ` ${theme.fg(\"accent\", clipped)}${\" \".repeat(padRight)}`;\n\t\t});\n\n\t\t// Add \"ARMIN SAYS HI\" at the end\n\t\tconst message = \"ARMIN SAYS HI\";\n\t\tconst msgPadRight = Math.max(0, width - padding - message.length);\n\t\tthis.cachedLines.push(` ${theme.fg(\"accent\", message)}${\" \".repeat(msgPadRight)}`);\n\n\t\tthis.cachedWidth = width;\n\t\tthis.cachedVersion = this.gridVersion;\n\n\t\treturn this.cachedLines;\n\t}\n\n\tprivate createEmptyGrid(): string[][] {\n\t\treturn Array.from({ length: DISPLAY_HEIGHT }, () => Array(WIDTH).fill(\" \"));\n\t}\n\n\tprivate initEffect(): void {\n\t\tswitch (this.effect) {\n\t\t\tcase \"typewriter\":\n\t\t\t\tthis.effectState = { pos: 0 };\n\t\t\t\tbreak;\n\t\t\tcase \"scanline\":\n\t\t\t\tthis.effectState = { row: 0 };\n\t\t\t\tbreak;\n\t\t\tcase \"rain\":\n\t\t\t\t// Track falling position for each column\n\t\t\t\tthis.effectState = {\n\t\t\t\t\tdrops: Array.from({ length: WIDTH }, () => ({\n\t\t\t\t\t\ty: -Math.floor(Math.random() * DISPLAY_HEIGHT * 2),\n\t\t\t\t\t\tsettled: 0,\n\t\t\t\t\t})),\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\tcase \"fade\": {\n\t\t\t\t// Shuffle all pixel positions\n\t\t\t\tconst positions: [number, number][] = [];\n\t\t\t\tfor (let row = 0; row < DISPLAY_HEIGHT; row++) {\n\t\t\t\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\t\t\t\tpositions.push([row, x]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Fisher-Yates shuffle\n\t\t\t\tfor (let i = positions.length - 1; i > 0; i--) {\n\t\t\t\t\tconst j = Math.floor(Math.random() * (i + 1));\n\t\t\t\t\t[positions[i], positions[j]] = [positions[j], positions[i]];\n\t\t\t\t}\n\t\t\t\tthis.effectState = { positions, idx: 0 };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"crt\":\n\t\t\t\tthis.effectState = { expansion: 0 };\n\t\t\t\tbreak;\n\t\t\tcase \"glitch\":\n\t\t\t\tthis.effectState = { phase: 0, glitchFrames: 8 };\n\t\t\t\tbreak;\n\t\t\tcase \"dissolve\": {\n\t\t\t\t// Start with random noise\n\t\t\t\tthis.currentGrid = Array.from({ length: DISPLAY_HEIGHT }, () =>\n\t\t\t\t\tArray.from({ length: WIDTH }, () => {\n\t\t\t\t\t\tconst chars = [\" \", \"░\", \"▒\", \"▓\", \"█\", \"▀\", \"▄\"];\n\t\t\t\t\t\treturn chars[Math.floor(Math.random() * chars.length)];\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\t// Shuffle positions for gradual resolve\n\t\t\t\tconst dissolvePositions: [number, number][] = [];\n\t\t\t\tfor (let row = 0; row < DISPLAY_HEIGHT; row++) {\n\t\t\t\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\t\t\t\tdissolvePositions.push([row, x]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (let i = dissolvePositions.length - 1; i > 0; i--) {\n\t\t\t\t\tconst j = Math.floor(Math.random() * (i + 1));\n\t\t\t\t\t[dissolvePositions[i], dissolvePositions[j]] = [dissolvePositions[j], dissolvePositions[i]];\n\t\t\t\t}\n\t\t\t\tthis.effectState = { positions: dissolvePositions, idx: 0 };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate startAnimation(): void {\n\t\tconst fps = this.effect === \"glitch\" ? 60 : 30;\n\t\tthis.interval = setInterval(() => {\n\t\t\tconst done = this.tickEffect();\n\t\t\tthis.updateDisplay();\n\t\t\tthis.ui.requestRender();\n\t\t\tif (done) {\n\t\t\t\tthis.stopAnimation();\n\t\t\t}\n\t\t}, 1000 / fps);\n\t}\n\n\tprivate stopAnimation(): void {\n\t\tif (this.interval) {\n\t\t\tclearInterval(this.interval);\n\t\t\tthis.interval = null;\n\t\t}\n\t}\n\n\tprivate tickEffect(): boolean {\n\t\tswitch (this.effect) {\n\t\t\tcase \"typewriter\":\n\t\t\t\treturn this.tickTypewriter();\n\t\t\tcase \"scanline\":\n\t\t\t\treturn this.tickScanline();\n\t\t\tcase \"rain\":\n\t\t\t\treturn this.tickRain();\n\t\t\tcase \"fade\":\n\t\t\t\treturn this.tickFade();\n\t\t\tcase \"crt\":\n\t\t\t\treturn this.tickCrt();\n\t\t\tcase \"glitch\":\n\t\t\t\treturn this.tickGlitch();\n\t\t\tcase \"dissolve\":\n\t\t\t\treturn this.tickDissolve();\n\t\t\tdefault:\n\t\t\t\treturn true;\n\t\t}\n\t}\n\n\tprivate tickTypewriter(): boolean {\n\t\tconst state = this.effectState as { pos: number };\n\t\tconst pixelsPerFrame = 3;\n\n\t\tfor (let i = 0; i < pixelsPerFrame; i++) {\n\t\t\tconst row = Math.floor(state.pos / WIDTH);\n\t\t\tconst x = state.pos % WIDTH;\n\t\t\tif (row >= DISPLAY_HEIGHT) return true;\n\t\t\tthis.currentGrid[row][x] = this.finalGrid[row][x];\n\t\t\tstate.pos++;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate tickScanline(): boolean {\n\t\tconst state = this.effectState as { row: number };\n\t\tif (state.row >= DISPLAY_HEIGHT) return true;\n\n\t\t// Copy row\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tthis.currentGrid[state.row][x] = this.finalGrid[state.row][x];\n\t\t}\n\t\tstate.row++;\n\t\treturn false;\n\t}\n\n\tprivate tickRain(): boolean {\n\t\tconst state = this.effectState as {\n\t\t\tdrops: { y: number; settled: number }[];\n\t\t};\n\n\t\tlet allSettled = true;\n\t\tthis.currentGrid = this.createEmptyGrid();\n\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tconst drop = state.drops[x];\n\n\t\t\t// Draw settled pixels\n\t\t\tfor (let row = DISPLAY_HEIGHT - 1; row >= DISPLAY_HEIGHT - drop.settled; row--) {\n\t\t\t\tif (row >= 0) {\n\t\t\t\t\tthis.currentGrid[row][x] = this.finalGrid[row][x];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check if this column is done\n\t\t\tif (drop.settled >= DISPLAY_HEIGHT) continue;\n\n\t\t\tallSettled = false;\n\n\t\t\t// Find the target row for this column (lowest non-space pixel)\n\t\t\tlet targetRow = -1;\n\t\t\tfor (let row = DISPLAY_HEIGHT - 1 - drop.settled; row >= 0; row--) {\n\t\t\t\tif (this.finalGrid[row][x] !== \" \") {\n\t\t\t\t\ttargetRow = row;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Move drop down\n\t\t\tdrop.y++;\n\n\t\t\t// Draw falling drop\n\t\t\tif (drop.y >= 0 && drop.y < DISPLAY_HEIGHT) {\n\t\t\t\tif (targetRow >= 0 && drop.y >= targetRow) {\n\t\t\t\t\t// Settle\n\t\t\t\t\tdrop.settled = DISPLAY_HEIGHT - targetRow;\n\t\t\t\t\tdrop.y = -Math.floor(Math.random() * 5) - 1;\n\t\t\t\t} else {\n\t\t\t\t\t// Still falling\n\t\t\t\t\tthis.currentGrid[drop.y][x] = \"▓\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn allSettled;\n\t}\n\n\tprivate tickFade(): boolean {\n\t\tconst state = this.effectState as { positions: [number, number][]; idx: number };\n\t\tconst pixelsPerFrame = 15;\n\n\t\tfor (let i = 0; i < pixelsPerFrame; i++) {\n\t\t\tif (state.idx >= state.positions.length) return true;\n\t\t\tconst [row, x] = state.positions[state.idx];\n\t\t\tthis.currentGrid[row][x] = this.finalGrid[row][x];\n\t\t\tstate.idx++;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate tickCrt(): boolean {\n\t\tconst state = this.effectState as { expansion: number };\n\t\tconst midRow = Math.floor(DISPLAY_HEIGHT / 2);\n\n\t\tthis.currentGrid = this.createEmptyGrid();\n\n\t\t// Draw from middle expanding outward\n\t\tconst top = midRow - state.expansion;\n\t\tconst bottom = midRow + state.expansion;\n\n\t\tfor (let row = Math.max(0, top); row <= Math.min(DISPLAY_HEIGHT - 1, bottom); row++) {\n\t\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\t\tthis.currentGrid[row][x] = this.finalGrid[row][x];\n\t\t\t}\n\t\t}\n\n\t\tstate.expansion++;\n\t\treturn state.expansion > DISPLAY_HEIGHT;\n\t}\n\n\tprivate tickGlitch(): boolean {\n\t\tconst state = this.effectState as { phase: number; glitchFrames: number };\n\n\t\tif (state.phase < state.glitchFrames) {\n\t\t\t// Glitch phase: show corrupted version\n\t\t\tthis.currentGrid = this.finalGrid.map((row) => {\n\t\t\t\tconst offset = Math.floor(Math.random() * 7) - 3;\n\t\t\t\tconst glitchRow = [...row];\n\n\t\t\t\t// Random horizontal offset\n\t\t\t\tif (Math.random() < 0.3) {\n\t\t\t\t\tconst shifted = glitchRow.slice(offset).concat(glitchRow.slice(0, offset));\n\t\t\t\t\treturn shifted.slice(0, WIDTH);\n\t\t\t\t}\n\n\t\t\t\t// Random vertical swap\n\t\t\t\tif (Math.random() < 0.2) {\n\t\t\t\t\tconst swapRow = Math.floor(Math.random() * DISPLAY_HEIGHT);\n\t\t\t\t\treturn [...this.finalGrid[swapRow]];\n\t\t\t\t}\n\n\t\t\t\treturn glitchRow;\n\t\t\t});\n\t\t\tstate.phase++;\n\t\t\treturn false;\n\t\t}\n\n\t\t// Final frame: show clean image\n\t\tthis.currentGrid = this.finalGrid.map((row) => [...row]);\n\t\treturn true;\n\t}\n\n\tprivate tickDissolve(): boolean {\n\t\tconst state = this.effectState as { positions: [number, number][]; idx: number };\n\t\tconst pixelsPerFrame = 20;\n\n\t\tfor (let i = 0; i < pixelsPerFrame; i++) {\n\t\t\tif (state.idx >= state.positions.length) return true;\n\t\t\tconst [row, x] = state.positions[state.idx];\n\t\t\tthis.currentGrid[row][x] = this.finalGrid[row][x];\n\t\t\tstate.idx++;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate updateDisplay(): void {\n\t\tthis.gridVersion++;\n\t}\n\n\tdispose(): void {\n\t\tthis.stopAnimation();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/armin.js b/dist/modes/interactive/components/armin.js new file mode 100644 index 0000000..ea67c20 --- /dev/null +++ b/dist/modes/interactive/components/armin.js @@ -0,0 +1,333 @@ +/** + * Armin says hi! A fun easter egg with animated XBM art. + */ +import { theme } from "../theme/theme.js"; +// XBM image: 31x36 pixels, LSB first, 1=background, 0=foreground +const WIDTH = 31; +const HEIGHT = 36; +const BITS = [ + 0xff, 0xff, 0xff, 0x7f, 0xff, 0xf0, 0xff, 0x7f, 0xff, 0xed, 0xff, 0x7f, 0xff, 0xdb, 0xff, 0x7f, 0xff, 0xb7, 0xff, + 0x7f, 0xff, 0x77, 0xfe, 0x7f, 0x3f, 0xf8, 0xfe, 0x7f, 0xdf, 0xff, 0xfe, 0x7f, 0xdf, 0x3f, 0xfc, 0x7f, 0x9f, 0xc3, + 0xfb, 0x7f, 0x6f, 0xfc, 0xf4, 0x7f, 0xf7, 0x0f, 0xf7, 0x7f, 0xf7, 0xff, 0xf7, 0x7f, 0xf7, 0xff, 0xe3, 0x7f, 0xf7, + 0x07, 0xe8, 0x7f, 0xef, 0xf8, 0x67, 0x70, 0x0f, 0xff, 0xbb, 0x6f, 0xf1, 0x00, 0xd0, 0x5b, 0xfd, 0x3f, 0xec, 0x53, + 0xc1, 0xff, 0xef, 0x57, 0x9f, 0xfd, 0xee, 0x5f, 0x9f, 0xfc, 0xae, 0x5f, 0x1f, 0x78, 0xac, 0x5f, 0x3f, 0x00, 0x50, + 0x6c, 0x7f, 0x00, 0xdc, 0x77, 0xff, 0xc0, 0x3f, 0x78, 0xff, 0x01, 0xf8, 0x7f, 0xff, 0x03, 0x9c, 0x78, 0xff, 0x07, + 0x8c, 0x7c, 0xff, 0x0f, 0xce, 0x78, 0xff, 0xff, 0xcf, 0x7f, 0xff, 0xff, 0xcf, 0x78, 0xff, 0xff, 0xdf, 0x78, 0xff, + 0xff, 0xdf, 0x7d, 0xff, 0xff, 0x3f, 0x7e, 0xff, 0xff, 0xff, 0x7f, +]; +const BYTES_PER_ROW = Math.ceil(WIDTH / 8); +const DISPLAY_HEIGHT = Math.ceil(HEIGHT / 2); // Half-block rendering +const EFFECTS = ["typewriter", "scanline", "rain", "fade", "crt", "glitch", "dissolve"]; +// Get pixel at (x, y): true = foreground, false = background +function getPixel(x, y) { + if (y >= HEIGHT) + return false; + const byteIndex = y * BYTES_PER_ROW + Math.floor(x / 8); + const bitIndex = x % 8; + return ((BITS[byteIndex] >> bitIndex) & 1) === 0; +} +// Get the character for a cell (2 vertical pixels packed) +function getChar(x, row) { + const upper = getPixel(x, row * 2); + const lower = getPixel(x, row * 2 + 1); + if (upper && lower) + return "█"; + if (upper) + return "▀"; + if (lower) + return "▄"; + return " "; +} +// Build the final image grid +function buildFinalGrid() { + const grid = []; + for (let row = 0; row < DISPLAY_HEIGHT; row++) { + const line = []; + for (let x = 0; x < WIDTH; x++) { + line.push(getChar(x, row)); + } + grid.push(line); + } + return grid; +} +export class ArminComponent { + ui; + interval = null; + effect; + finalGrid; + currentGrid; + effectState = {}; + cachedLines = []; + cachedWidth = 0; + gridVersion = 0; + cachedVersion = -1; + constructor(ui) { + this.ui = ui; + this.effect = EFFECTS[Math.floor(Math.random() * EFFECTS.length)]; + this.finalGrid = buildFinalGrid(); + this.currentGrid = this.createEmptyGrid(); + this.initEffect(); + this.startAnimation(); + } + invalidate() { + this.cachedWidth = 0; + } + render(width) { + if (width === this.cachedWidth && this.cachedVersion === this.gridVersion) { + return this.cachedLines; + } + const padding = 1; + const availableWidth = width - padding; + this.cachedLines = this.currentGrid.map((row) => { + // Clip row to available width before applying color + const clipped = row.slice(0, availableWidth).join(""); + const padRight = Math.max(0, width - padding - clipped.length); + return ` ${theme.fg("accent", clipped)}${" ".repeat(padRight)}`; + }); + // Add "ARMIN SAYS HI" at the end + const message = "ARMIN SAYS HI"; + const msgPadRight = Math.max(0, width - padding - message.length); + this.cachedLines.push(` ${theme.fg("accent", message)}${" ".repeat(msgPadRight)}`); + this.cachedWidth = width; + this.cachedVersion = this.gridVersion; + return this.cachedLines; + } + createEmptyGrid() { + return Array.from({ length: DISPLAY_HEIGHT }, () => Array(WIDTH).fill(" ")); + } + initEffect() { + switch (this.effect) { + case "typewriter": + this.effectState = { pos: 0 }; + break; + case "scanline": + this.effectState = { row: 0 }; + break; + case "rain": + // Track falling position for each column + this.effectState = { + drops: Array.from({ length: WIDTH }, () => ({ + y: -Math.floor(Math.random() * DISPLAY_HEIGHT * 2), + settled: 0, + })), + }; + break; + case "fade": { + // Shuffle all pixel positions + const positions = []; + for (let row = 0; row < DISPLAY_HEIGHT; row++) { + for (let x = 0; x < WIDTH; x++) { + positions.push([row, x]); + } + } + // Fisher-Yates shuffle + for (let i = positions.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [positions[i], positions[j]] = [positions[j], positions[i]]; + } + this.effectState = { positions, idx: 0 }; + break; + } + case "crt": + this.effectState = { expansion: 0 }; + break; + case "glitch": + this.effectState = { phase: 0, glitchFrames: 8 }; + break; + case "dissolve": { + // Start with random noise + this.currentGrid = Array.from({ length: DISPLAY_HEIGHT }, () => Array.from({ length: WIDTH }, () => { + const chars = [" ", "░", "▒", "▓", "█", "▀", "▄"]; + return chars[Math.floor(Math.random() * chars.length)]; + })); + // Shuffle positions for gradual resolve + const dissolvePositions = []; + for (let row = 0; row < DISPLAY_HEIGHT; row++) { + for (let x = 0; x < WIDTH; x++) { + dissolvePositions.push([row, x]); + } + } + for (let i = dissolvePositions.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [dissolvePositions[i], dissolvePositions[j]] = [dissolvePositions[j], dissolvePositions[i]]; + } + this.effectState = { positions: dissolvePositions, idx: 0 }; + break; + } + } + } + startAnimation() { + const fps = this.effect === "glitch" ? 60 : 30; + this.interval = setInterval(() => { + const done = this.tickEffect(); + this.updateDisplay(); + this.ui.requestRender(); + if (done) { + this.stopAnimation(); + } + }, 1000 / fps); + } + stopAnimation() { + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + } + tickEffect() { + switch (this.effect) { + case "typewriter": + return this.tickTypewriter(); + case "scanline": + return this.tickScanline(); + case "rain": + return this.tickRain(); + case "fade": + return this.tickFade(); + case "crt": + return this.tickCrt(); + case "glitch": + return this.tickGlitch(); + case "dissolve": + return this.tickDissolve(); + default: + return true; + } + } + tickTypewriter() { + const state = this.effectState; + const pixelsPerFrame = 3; + for (let i = 0; i < pixelsPerFrame; i++) { + const row = Math.floor(state.pos / WIDTH); + const x = state.pos % WIDTH; + if (row >= DISPLAY_HEIGHT) + return true; + this.currentGrid[row][x] = this.finalGrid[row][x]; + state.pos++; + } + return false; + } + tickScanline() { + const state = this.effectState; + if (state.row >= DISPLAY_HEIGHT) + return true; + // Copy row + for (let x = 0; x < WIDTH; x++) { + this.currentGrid[state.row][x] = this.finalGrid[state.row][x]; + } + state.row++; + return false; + } + tickRain() { + const state = this.effectState; + let allSettled = true; + this.currentGrid = this.createEmptyGrid(); + for (let x = 0; x < WIDTH; x++) { + const drop = state.drops[x]; + // Draw settled pixels + for (let row = DISPLAY_HEIGHT - 1; row >= DISPLAY_HEIGHT - drop.settled; row--) { + if (row >= 0) { + this.currentGrid[row][x] = this.finalGrid[row][x]; + } + } + // Check if this column is done + if (drop.settled >= DISPLAY_HEIGHT) + continue; + allSettled = false; + // Find the target row for this column (lowest non-space pixel) + let targetRow = -1; + for (let row = DISPLAY_HEIGHT - 1 - drop.settled; row >= 0; row--) { + if (this.finalGrid[row][x] !== " ") { + targetRow = row; + break; + } + } + // Move drop down + drop.y++; + // Draw falling drop + if (drop.y >= 0 && drop.y < DISPLAY_HEIGHT) { + if (targetRow >= 0 && drop.y >= targetRow) { + // Settle + drop.settled = DISPLAY_HEIGHT - targetRow; + drop.y = -Math.floor(Math.random() * 5) - 1; + } + else { + // Still falling + this.currentGrid[drop.y][x] = "▓"; + } + } + } + return allSettled; + } + tickFade() { + const state = this.effectState; + const pixelsPerFrame = 15; + for (let i = 0; i < pixelsPerFrame; i++) { + if (state.idx >= state.positions.length) + return true; + const [row, x] = state.positions[state.idx]; + this.currentGrid[row][x] = this.finalGrid[row][x]; + state.idx++; + } + return false; + } + tickCrt() { + const state = this.effectState; + const midRow = Math.floor(DISPLAY_HEIGHT / 2); + this.currentGrid = this.createEmptyGrid(); + // Draw from middle expanding outward + const top = midRow - state.expansion; + const bottom = midRow + state.expansion; + for (let row = Math.max(0, top); row <= Math.min(DISPLAY_HEIGHT - 1, bottom); row++) { + for (let x = 0; x < WIDTH; x++) { + this.currentGrid[row][x] = this.finalGrid[row][x]; + } + } + state.expansion++; + return state.expansion > DISPLAY_HEIGHT; + } + tickGlitch() { + const state = this.effectState; + if (state.phase < state.glitchFrames) { + // Glitch phase: show corrupted version + this.currentGrid = this.finalGrid.map((row) => { + const offset = Math.floor(Math.random() * 7) - 3; + const glitchRow = [...row]; + // Random horizontal offset + if (Math.random() < 0.3) { + const shifted = glitchRow.slice(offset).concat(glitchRow.slice(0, offset)); + return shifted.slice(0, WIDTH); + } + // Random vertical swap + if (Math.random() < 0.2) { + const swapRow = Math.floor(Math.random() * DISPLAY_HEIGHT); + return [...this.finalGrid[swapRow]]; + } + return glitchRow; + }); + state.phase++; + return false; + } + // Final frame: show clean image + this.currentGrid = this.finalGrid.map((row) => [...row]); + return true; + } + tickDissolve() { + const state = this.effectState; + const pixelsPerFrame = 20; + for (let i = 0; i < pixelsPerFrame; i++) { + if (state.idx >= state.positions.length) + return true; + const [row, x] = state.positions[state.idx]; + this.currentGrid[row][x] = this.finalGrid[row][x]; + state.idx++; + } + return false; + } + updateDisplay() { + this.gridVersion++; + } + dispose() { + this.stopAnimation(); + } +} +//# sourceMappingURL=armin.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/armin.js.map b/dist/modes/interactive/components/armin.js.map new file mode 100644 index 0000000..f626259 --- /dev/null +++ b/dist/modes/interactive/components/armin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"armin.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/armin.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C,iEAAiE;AACjE,MAAM,KAAK,GAAG,EAAE,CAAC;AACjB,MAAM,MAAM,GAAG,EAAE,CAAC;AAClB,MAAM,IAAI,GAAG;IACZ,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI;IAChH,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,I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AAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;QACzD,OAAO,IAAI,CAAC;IAAA,CACZ;IAEO,YAAY,GAAY;QAC/B,MAAM,KAAK,GAAG,IAAI,CAAC,WAA6D,CAAC;QACjF,MAAM,cAAc,GAAG,EAAE,CAAC;QAE1B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,EAAE,EAAE,CAAC;YACzC,IAAI,KAAK,CAAC,GAAG,IAAI,KAAK,CAAC,SAAS,CAAC,MAAM;gBAAE,OAAO,IAAI,CAAC;YACrD,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC5C,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YAClD,KAAK,CAAC,GAAG,EAAE,CAAC;QACb,CAAC;QACD,OAAO,KAAK,CAAC;IAAA,CACb;IAEO,aAAa,GAAS;QAC7B,IAAI,CAAC,WAAW,EAAE,CAAC;IAAA,CACnB;IAED,OAAO,GAAS;QACf,IAAI,CAAC,aAAa,EAAE,CAAC;IAAA,CACrB;CACD","sourcesContent":["/**\n * Armin says hi! A fun easter egg with animated XBM art.\n */\n\nimport type { Component, TUI } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\n\n// XBM image: 31x36 pixels, LSB first, 1=background, 0=foreground\nconst WIDTH = 31;\nconst HEIGHT = 36;\nconst BITS = [\n\t0xff, 0xff, 0xff, 0x7f, 0xff, 0xf0, 0xff, 0x7f, 0xff, 0xed, 0xff, 0x7f, 0xff, 0xdb, 0xff, 0x7f, 0xff, 0xb7, 0xff,\n\t0x7f, 0xff, 0x77, 0xfe, 0x7f, 0x3f, 0xf8, 0xfe, 0x7f, 0xdf, 0xff, 0xfe, 0x7f, 0xdf, 0x3f, 0xfc, 0x7f, 0x9f, 0xc3,\n\t0xfb, 0x7f, 0x6f, 0xfc, 0xf4, 0x7f, 0xf7, 0x0f, 0xf7, 0x7f, 0xf7, 0xff, 0xf7, 0x7f, 0xf7, 0xff, 0xe3, 0x7f, 0xf7,\n\t0x07, 0xe8, 0x7f, 0xef, 0xf8, 0x67, 0x70, 0x0f, 0xff, 0xbb, 0x6f, 0xf1, 0x00, 0xd0, 0x5b, 0xfd, 0x3f, 0xec, 0x53,\n\t0xc1, 0xff, 0xef, 0x57, 0x9f, 0xfd, 0xee, 0x5f, 0x9f, 0xfc, 0xae, 0x5f, 0x1f, 0x78, 0xac, 0x5f, 0x3f, 0x00, 0x50,\n\t0x6c, 0x7f, 0x00, 0xdc, 0x77, 0xff, 0xc0, 0x3f, 0x78, 0xff, 0x01, 0xf8, 0x7f, 0xff, 0x03, 0x9c, 0x78, 0xff, 0x07,\n\t0x8c, 0x7c, 0xff, 0x0f, 0xce, 0x78, 0xff, 0xff, 0xcf, 0x7f, 0xff, 0xff, 0xcf, 0x78, 0xff, 0xff, 0xdf, 0x78, 0xff,\n\t0xff, 0xdf, 0x7d, 0xff, 0xff, 0x3f, 0x7e, 0xff, 0xff, 0xff, 0x7f,\n];\n\nconst BYTES_PER_ROW = Math.ceil(WIDTH / 8);\nconst DISPLAY_HEIGHT = Math.ceil(HEIGHT / 2); // Half-block rendering\n\ntype Effect = \"typewriter\" | \"scanline\" | \"rain\" | \"fade\" | \"crt\" | \"glitch\" | \"dissolve\";\n\nconst EFFECTS: Effect[] = [\"typewriter\", \"scanline\", \"rain\", \"fade\", \"crt\", \"glitch\", \"dissolve\"];\n\n// Get pixel at (x, y): true = foreground, false = background\nfunction getPixel(x: number, y: number): boolean {\n\tif (y >= HEIGHT) return false;\n\tconst byteIndex = y * BYTES_PER_ROW + Math.floor(x / 8);\n\tconst bitIndex = x % 8;\n\treturn ((BITS[byteIndex] >> bitIndex) & 1) === 0;\n}\n\n// Get the character for a cell (2 vertical pixels packed)\nfunction getChar(x: number, row: number): string {\n\tconst upper = getPixel(x, row * 2);\n\tconst lower = getPixel(x, row * 2 + 1);\n\tif (upper && lower) return \"█\";\n\tif (upper) return \"▀\";\n\tif (lower) return \"▄\";\n\treturn \" \";\n}\n\n// Build the final image grid\nfunction buildFinalGrid(): string[][] {\n\tconst grid: string[][] = [];\n\tfor (let row = 0; row < DISPLAY_HEIGHT; row++) {\n\t\tconst line: string[] = [];\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tline.push(getChar(x, row));\n\t\t}\n\t\tgrid.push(line);\n\t}\n\treturn grid;\n}\n\nexport class ArminComponent implements Component {\n\tprivate ui: TUI;\n\tprivate interval: ReturnType | null = null;\n\tprivate effect: Effect;\n\tprivate finalGrid: string[][];\n\tprivate currentGrid: string[][];\n\tprivate effectState: Record = {};\n\tprivate cachedLines: string[] = [];\n\tprivate cachedWidth = 0;\n\tprivate gridVersion = 0;\n\tprivate cachedVersion = -1;\n\n\tconstructor(ui: TUI) {\n\t\tthis.ui = ui;\n\t\tthis.effect = EFFECTS[Math.floor(Math.random() * EFFECTS.length)];\n\t\tthis.finalGrid = buildFinalGrid();\n\t\tthis.currentGrid = this.createEmptyGrid();\n\n\t\tthis.initEffect();\n\t\tthis.startAnimation();\n\t}\n\n\tinvalidate(): void {\n\t\tthis.cachedWidth = 0;\n\t}\n\n\trender(width: number): string[] {\n\t\tif (width === this.cachedWidth && this.cachedVersion === this.gridVersion) {\n\t\t\treturn this.cachedLines;\n\t\t}\n\n\t\tconst padding = 1;\n\t\tconst availableWidth = width - padding;\n\n\t\tthis.cachedLines = this.currentGrid.map((row) => {\n\t\t\t// Clip row to available width before applying color\n\t\t\tconst clipped = row.slice(0, availableWidth).join(\"\");\n\t\t\tconst padRight = Math.max(0, width - padding - clipped.length);\n\t\t\treturn ` ${theme.fg(\"accent\", clipped)}${\" \".repeat(padRight)}`;\n\t\t});\n\n\t\t// Add \"ARMIN SAYS HI\" at the end\n\t\tconst message = \"ARMIN SAYS HI\";\n\t\tconst msgPadRight = Math.max(0, width - padding - message.length);\n\t\tthis.cachedLines.push(` ${theme.fg(\"accent\", message)}${\" \".repeat(msgPadRight)}`);\n\n\t\tthis.cachedWidth = width;\n\t\tthis.cachedVersion = this.gridVersion;\n\n\t\treturn this.cachedLines;\n\t}\n\n\tprivate createEmptyGrid(): string[][] {\n\t\treturn Array.from({ length: DISPLAY_HEIGHT }, () => Array(WIDTH).fill(\" \"));\n\t}\n\n\tprivate initEffect(): void {\n\t\tswitch (this.effect) {\n\t\t\tcase \"typewriter\":\n\t\t\t\tthis.effectState = { pos: 0 };\n\t\t\t\tbreak;\n\t\t\tcase \"scanline\":\n\t\t\t\tthis.effectState = { row: 0 };\n\t\t\t\tbreak;\n\t\t\tcase \"rain\":\n\t\t\t\t// Track falling position for each column\n\t\t\t\tthis.effectState = {\n\t\t\t\t\tdrops: Array.from({ length: WIDTH }, () => ({\n\t\t\t\t\t\ty: -Math.floor(Math.random() * DISPLAY_HEIGHT * 2),\n\t\t\t\t\t\tsettled: 0,\n\t\t\t\t\t})),\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\tcase \"fade\": {\n\t\t\t\t// Shuffle all pixel positions\n\t\t\t\tconst positions: [number, number][] = [];\n\t\t\t\tfor (let row = 0; row < DISPLAY_HEIGHT; row++) {\n\t\t\t\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\t\t\t\tpositions.push([row, x]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Fisher-Yates shuffle\n\t\t\t\tfor (let i = positions.length - 1; i > 0; i--) {\n\t\t\t\t\tconst j = Math.floor(Math.random() * (i + 1));\n\t\t\t\t\t[positions[i], positions[j]] = [positions[j], positions[i]];\n\t\t\t\t}\n\t\t\t\tthis.effectState = { positions, idx: 0 };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"crt\":\n\t\t\t\tthis.effectState = { expansion: 0 };\n\t\t\t\tbreak;\n\t\t\tcase \"glitch\":\n\t\t\t\tthis.effectState = { phase: 0, glitchFrames: 8 };\n\t\t\t\tbreak;\n\t\t\tcase \"dissolve\": {\n\t\t\t\t// Start with random noise\n\t\t\t\tthis.currentGrid = Array.from({ length: DISPLAY_HEIGHT }, () =>\n\t\t\t\t\tArray.from({ length: WIDTH }, () => {\n\t\t\t\t\t\tconst chars = [\" \", \"░\", \"▒\", \"▓\", \"█\", \"▀\", \"▄\"];\n\t\t\t\t\t\treturn chars[Math.floor(Math.random() * chars.length)];\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\t// Shuffle positions for gradual resolve\n\t\t\t\tconst dissolvePositions: [number, number][] = [];\n\t\t\t\tfor (let row = 0; row < DISPLAY_HEIGHT; row++) {\n\t\t\t\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\t\t\t\tdissolvePositions.push([row, x]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (let i = dissolvePositions.length - 1; i > 0; i--) {\n\t\t\t\t\tconst j = Math.floor(Math.random() * (i + 1));\n\t\t\t\t\t[dissolvePositions[i], dissolvePositions[j]] = [dissolvePositions[j], dissolvePositions[i]];\n\t\t\t\t}\n\t\t\t\tthis.effectState = { positions: dissolvePositions, idx: 0 };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate startAnimation(): void {\n\t\tconst fps = this.effect === \"glitch\" ? 60 : 30;\n\t\tthis.interval = setInterval(() => {\n\t\t\tconst done = this.tickEffect();\n\t\t\tthis.updateDisplay();\n\t\t\tthis.ui.requestRender();\n\t\t\tif (done) {\n\t\t\t\tthis.stopAnimation();\n\t\t\t}\n\t\t}, 1000 / fps);\n\t}\n\n\tprivate stopAnimation(): void {\n\t\tif (this.interval) {\n\t\t\tclearInterval(this.interval);\n\t\t\tthis.interval = null;\n\t\t}\n\t}\n\n\tprivate tickEffect(): boolean {\n\t\tswitch (this.effect) {\n\t\t\tcase \"typewriter\":\n\t\t\t\treturn this.tickTypewriter();\n\t\t\tcase \"scanline\":\n\t\t\t\treturn this.tickScanline();\n\t\t\tcase \"rain\":\n\t\t\t\treturn this.tickRain();\n\t\t\tcase \"fade\":\n\t\t\t\treturn this.tickFade();\n\t\t\tcase \"crt\":\n\t\t\t\treturn this.tickCrt();\n\t\t\tcase \"glitch\":\n\t\t\t\treturn this.tickGlitch();\n\t\t\tcase \"dissolve\":\n\t\t\t\treturn this.tickDissolve();\n\t\t\tdefault:\n\t\t\t\treturn true;\n\t\t}\n\t}\n\n\tprivate tickTypewriter(): boolean {\n\t\tconst state = this.effectState as { pos: number };\n\t\tconst pixelsPerFrame = 3;\n\n\t\tfor (let i = 0; i < pixelsPerFrame; i++) {\n\t\t\tconst row = Math.floor(state.pos / WIDTH);\n\t\t\tconst x = state.pos % WIDTH;\n\t\t\tif (row >= DISPLAY_HEIGHT) return true;\n\t\t\tthis.currentGrid[row][x] = this.finalGrid[row][x];\n\t\t\tstate.pos++;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate tickScanline(): boolean {\n\t\tconst state = this.effectState as { row: number };\n\t\tif (state.row >= DISPLAY_HEIGHT) return true;\n\n\t\t// Copy row\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tthis.currentGrid[state.row][x] = this.finalGrid[state.row][x];\n\t\t}\n\t\tstate.row++;\n\t\treturn false;\n\t}\n\n\tprivate tickRain(): boolean {\n\t\tconst state = this.effectState as {\n\t\t\tdrops: { y: number; settled: number }[];\n\t\t};\n\n\t\tlet allSettled = true;\n\t\tthis.currentGrid = this.createEmptyGrid();\n\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tconst drop = state.drops[x];\n\n\t\t\t// Draw settled pixels\n\t\t\tfor (let row = DISPLAY_HEIGHT - 1; row >= DISPLAY_HEIGHT - drop.settled; row--) {\n\t\t\t\tif (row >= 0) {\n\t\t\t\t\tthis.currentGrid[row][x] = this.finalGrid[row][x];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check if this column is done\n\t\t\tif (drop.settled >= DISPLAY_HEIGHT) continue;\n\n\t\t\tallSettled = false;\n\n\t\t\t// Find the target row for this column (lowest non-space pixel)\n\t\t\tlet targetRow = -1;\n\t\t\tfor (let row = DISPLAY_HEIGHT - 1 - drop.settled; row >= 0; row--) {\n\t\t\t\tif (this.finalGrid[row][x] !== \" \") {\n\t\t\t\t\ttargetRow = row;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Move drop down\n\t\t\tdrop.y++;\n\n\t\t\t// Draw falling drop\n\t\t\tif (drop.y >= 0 && drop.y < DISPLAY_HEIGHT) {\n\t\t\t\tif (targetRow >= 0 && drop.y >= targetRow) {\n\t\t\t\t\t// Settle\n\t\t\t\t\tdrop.settled = DISPLAY_HEIGHT - targetRow;\n\t\t\t\t\tdrop.y = -Math.floor(Math.random() * 5) - 1;\n\t\t\t\t} else {\n\t\t\t\t\t// Still falling\n\t\t\t\t\tthis.currentGrid[drop.y][x] = \"▓\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn allSettled;\n\t}\n\n\tprivate tickFade(): boolean {\n\t\tconst state = this.effectState as { positions: [number, number][]; idx: number };\n\t\tconst pixelsPerFrame = 15;\n\n\t\tfor (let i = 0; i < pixelsPerFrame; i++) {\n\t\t\tif (state.idx >= state.positions.length) return true;\n\t\t\tconst [row, x] = state.positions[state.idx];\n\t\t\tthis.currentGrid[row][x] = this.finalGrid[row][x];\n\t\t\tstate.idx++;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate tickCrt(): boolean {\n\t\tconst state = this.effectState as { expansion: number };\n\t\tconst midRow = Math.floor(DISPLAY_HEIGHT / 2);\n\n\t\tthis.currentGrid = this.createEmptyGrid();\n\n\t\t// Draw from middle expanding outward\n\t\tconst top = midRow - state.expansion;\n\t\tconst bottom = midRow + state.expansion;\n\n\t\tfor (let row = Math.max(0, top); row <= Math.min(DISPLAY_HEIGHT - 1, bottom); row++) {\n\t\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\t\tthis.currentGrid[row][x] = this.finalGrid[row][x];\n\t\t\t}\n\t\t}\n\n\t\tstate.expansion++;\n\t\treturn state.expansion > DISPLAY_HEIGHT;\n\t}\n\n\tprivate tickGlitch(): boolean {\n\t\tconst state = this.effectState as { phase: number; glitchFrames: number };\n\n\t\tif (state.phase < state.glitchFrames) {\n\t\t\t// Glitch phase: show corrupted version\n\t\t\tthis.currentGrid = this.finalGrid.map((row) => {\n\t\t\t\tconst offset = Math.floor(Math.random() * 7) - 3;\n\t\t\t\tconst glitchRow = [...row];\n\n\t\t\t\t// Random horizontal offset\n\t\t\t\tif (Math.random() < 0.3) {\n\t\t\t\t\tconst shifted = glitchRow.slice(offset).concat(glitchRow.slice(0, offset));\n\t\t\t\t\treturn shifted.slice(0, WIDTH);\n\t\t\t\t}\n\n\t\t\t\t// Random vertical swap\n\t\t\t\tif (Math.random() < 0.2) {\n\t\t\t\t\tconst swapRow = Math.floor(Math.random() * DISPLAY_HEIGHT);\n\t\t\t\t\treturn [...this.finalGrid[swapRow]];\n\t\t\t\t}\n\n\t\t\t\treturn glitchRow;\n\t\t\t});\n\t\t\tstate.phase++;\n\t\t\treturn false;\n\t\t}\n\n\t\t// Final frame: show clean image\n\t\tthis.currentGrid = this.finalGrid.map((row) => [...row]);\n\t\treturn true;\n\t}\n\n\tprivate tickDissolve(): boolean {\n\t\tconst state = this.effectState as { positions: [number, number][]; idx: number };\n\t\tconst pixelsPerFrame = 20;\n\n\t\tfor (let i = 0; i < pixelsPerFrame; i++) {\n\t\t\tif (state.idx >= state.positions.length) return true;\n\t\t\tconst [row, x] = state.positions[state.idx];\n\t\t\tthis.currentGrid[row][x] = this.finalGrid[row][x];\n\t\t\tstate.idx++;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate updateDisplay(): void {\n\t\tthis.gridVersion++;\n\t}\n\n\tdispose(): void {\n\t\tthis.stopAnimation();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/assistant-message.d.ts b/dist/modes/interactive/components/assistant-message.d.ts new file mode 100644 index 0000000..8856a5f --- /dev/null +++ b/dist/modes/interactive/components/assistant-message.d.ts @@ -0,0 +1,22 @@ +import type { AssistantMessage } from "@earendil-works/pi-ai"; +import { Container, type MarkdownTheme } from "@earendil-works/pi-tui"; +/** + * Component that renders a complete assistant message + */ +export declare class AssistantMessageComponent extends Container { + private contentContainer; + private hideThinkingBlock; + private markdownTheme; + private hiddenThinkingLabel; + private outputPad; + private lastMessage?; + private hasToolCalls; + constructor(message?: AssistantMessage, hideThinkingBlock?: boolean, markdownTheme?: MarkdownTheme, hiddenThinkingLabel?: string, outputPad?: number); + invalidate(): void; + setHideThinkingBlock(hide: boolean): void; + setHiddenThinkingLabel(label: string): void; + setOutputPad(padding: number): void; + render(width: number): string[]; + updateContent(message: AssistantMessage): void; +} +//# sourceMappingURL=assistant-message.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/assistant-message.d.ts.map b/dist/modes/interactive/components/assistant-message.d.ts.map new file mode 100644 index 0000000..fd3b707 --- /dev/null +++ b/dist/modes/interactive/components/assistant-message.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"assistant-message.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/assistant-message.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAY,KAAK,aAAa,EAAgB,MAAM,wBAAwB,CAAC;AAO/F;;GAEG;AACH,qBAAa,yBAA0B,SAAQ,SAAS;IACvD,OAAO,CAAC,gBAAgB,CAAY;IACpC,OAAO,CAAC,iBAAiB,CAAU;IACnC,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,mBAAmB,CAAS;IACpC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,WAAW,CAAC,CAAmB;IACvC,OAAO,CAAC,YAAY,CAAS;IAE7B,YACC,OAAO,CAAC,EAAE,gBAAgB,EAC1B,iBAAiB,UAAQ,EACzB,aAAa,GAAE,aAAkC,EACjD,mBAAmB,SAAgB,EACnC,SAAS,SAAI,EAgBb;IAEQ,UAAU,IAAI,IAAI,CAK1B;IAED,oBAAoB,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAKxC;IAED,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAK1C;IAED,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAKlC;IAEQ,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CASvC;IAED,aAAa,CAAC,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAgG7C;CACD","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai\";\nimport { Container, Markdown, type MarkdownTheme, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport { getMarkdownTheme, theme } from \"../theme/theme.ts\";\n\nconst OSC133_ZONE_START = \"\\x1b]133;A\\x07\";\nconst OSC133_ZONE_END = \"\\x1b]133;B\\x07\";\nconst OSC133_ZONE_FINAL = \"\\x1b]133;C\\x07\";\n\n/**\n * Component that renders a complete assistant message\n */\nexport class AssistantMessageComponent extends Container {\n\tprivate contentContainer: Container;\n\tprivate hideThinkingBlock: boolean;\n\tprivate markdownTheme: MarkdownTheme;\n\tprivate hiddenThinkingLabel: string;\n\tprivate outputPad: number;\n\tprivate lastMessage?: AssistantMessage;\n\tprivate hasToolCalls = false;\n\n\tconstructor(\n\t\tmessage?: AssistantMessage,\n\t\thideThinkingBlock = false,\n\t\tmarkdownTheme: MarkdownTheme = getMarkdownTheme(),\n\t\thiddenThinkingLabel = \"Thinking...\",\n\t\toutputPad = 1,\n\t) {\n\t\tsuper();\n\n\t\tthis.hideThinkingBlock = hideThinkingBlock;\n\t\tthis.markdownTheme = markdownTheme;\n\t\tthis.hiddenThinkingLabel = hiddenThinkingLabel;\n\t\tthis.outputPad = outputPad;\n\n\t\t// Container for text/thinking content\n\t\tthis.contentContainer = new Container();\n\t\tthis.addChild(this.contentContainer);\n\n\t\tif (message) {\n\t\t\tthis.updateContent(message);\n\t\t}\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tif (this.lastMessage) {\n\t\t\tthis.updateContent(this.lastMessage);\n\t\t}\n\t}\n\n\tsetHideThinkingBlock(hide: boolean): void {\n\t\tthis.hideThinkingBlock = hide;\n\t\tif (this.lastMessage) {\n\t\t\tthis.updateContent(this.lastMessage);\n\t\t}\n\t}\n\n\tsetHiddenThinkingLabel(label: string): void {\n\t\tthis.hiddenThinkingLabel = label;\n\t\tif (this.lastMessage) {\n\t\t\tthis.updateContent(this.lastMessage);\n\t\t}\n\t}\n\n\tsetOutputPad(padding: number): void {\n\t\tthis.outputPad = padding;\n\t\tif (this.lastMessage) {\n\t\t\tthis.updateContent(this.lastMessage);\n\t\t}\n\t}\n\n\toverride render(width: number): string[] {\n\t\tconst lines = super.render(width);\n\t\tif (this.hasToolCalls || lines.length === 0) {\n\t\t\treturn lines;\n\t\t}\n\n\t\tlines[0] = OSC133_ZONE_START + lines[0];\n\t\tlines[lines.length - 1] = OSC133_ZONE_END + OSC133_ZONE_FINAL + lines[lines.length - 1];\n\t\treturn lines;\n\t}\n\n\tupdateContent(message: AssistantMessage): void {\n\t\tthis.lastMessage = message;\n\n\t\t// Clear content container\n\t\tthis.contentContainer.clear();\n\n\t\tconst hasVisibleContent = message.content.some(\n\t\t\t(c) => (c.type === \"text\" && c.text.trim()) || (c.type === \"thinking\" && c.thinking.trim()),\n\t\t);\n\n\t\tif (hasVisibleContent) {\n\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t}\n\n\t\t// Render content in order\n\t\tfor (let i = 0; i < message.content.length; i++) {\n\t\t\tconst content = message.content[i];\n\t\t\tif (content.type === \"text\" && content.text.trim()) {\n\t\t\t\t// Assistant text messages with no background - trim the text\n\t\t\t\t// Set paddingY=0 to avoid extra spacing before tool executions\n\t\t\t\tthis.contentContainer.addChild(new Markdown(content.text.trim(), this.outputPad, 0, this.markdownTheme));\n\t\t\t} else if (content.type === \"thinking\") {\n\t\t\t\tconst thinkingBlocks: string[] = [];\n\t\t\t\tfor (; i < message.content.length; i++) {\n\t\t\t\t\tconst thinkingContent = message.content[i];\n\t\t\t\t\tif (thinkingContent.type !== \"thinking\") {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst thinking = thinkingContent.thinking.trim();\n\t\t\t\t\tif (thinking) {\n\t\t\t\t\t\tthinkingBlocks.push(thinking);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ti--;\n\n\t\t\t\tif (thinkingBlocks.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Add spacing only when another visible assistant content block follows.\n\t\t\t\t// This avoids a superfluous blank line before separately-rendered tool execution blocks.\n\t\t\t\tconst hasVisibleContentAfter = message.content\n\t\t\t\t\t.slice(i + 1)\n\t\t\t\t\t.some((c) => (c.type === \"text\" && c.text.trim()) || (c.type === \"thinking\" && c.thinking.trim()));\n\n\t\t\t\tif (this.hideThinkingBlock) {\n\t\t\t\t\t// Show one static label for each run of thinking blocks when hidden.\n\t\t\t\t\tthis.contentContainer.addChild(\n\t\t\t\t\t\tnew Text(theme.italic(theme.fg(\"thinkingText\", this.hiddenThinkingLabel)), this.outputPad, 0),\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\t// Render each run of thinking blocks as one Markdown section.\n\t\t\t\t\tthis.contentContainer.addChild(\n\t\t\t\t\t\tnew Markdown(thinkingBlocks.join(\"\\n\\n\"), this.outputPad, 0, this.markdownTheme, {\n\t\t\t\t\t\t\tcolor: (text: string) => theme.fg(\"thinkingText\", text),\n\t\t\t\t\t\t\titalic: true,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (hasVisibleContentAfter) {\n\t\t\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check if incomplete/failed - show after partial content.\n\t\t// For aborted/error tool calls, tool execution components show the error.\n\t\t// Length stops can happen before a tool call is complete, so surface them here too.\n\t\tconst hasToolCalls = message.content.some((c) => c.type === \"toolCall\");\n\t\tthis.hasToolCalls = hasToolCalls;\n\t\tif (message.stopReason === \"length\") {\n\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t\tthis.contentContainer.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\ttheme.fg(\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t\"Error: Model stopped because it reached the maximum output token limit. The response may be incomplete.\",\n\t\t\t\t\t),\n\t\t\t\t\tthis.outputPad,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t} else if (!hasToolCalls) {\n\t\t\tif (message.stopReason === \"aborted\") {\n\t\t\t\tconst abortMessage =\n\t\t\t\t\tmessage.errorMessage && message.errorMessage !== \"Request was aborted\"\n\t\t\t\t\t\t? message.errorMessage\n\t\t\t\t\t\t: \"Operation aborted\";\n\t\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t\t\tthis.contentContainer.addChild(new Text(theme.fg(\"error\", abortMessage), this.outputPad, 0));\n\t\t\t} else if (message.stopReason === \"error\") {\n\t\t\t\tconst errorMsg = message.errorMessage || \"Unknown error\";\n\t\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t\t\tthis.contentContainer.addChild(new Text(theme.fg(\"error\", `Error: ${errorMsg}`), this.outputPad, 0));\n\t\t\t}\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/assistant-message.js b/dist/modes/interactive/components/assistant-message.js new file mode 100644 index 0000000..2ec54e1 --- /dev/null +++ b/dist/modes/interactive/components/assistant-message.js @@ -0,0 +1,141 @@ +import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui"; +import { getMarkdownTheme, theme } from "../theme/theme.js"; +const OSC133_ZONE_START = "\x1b]133;A\x07"; +const OSC133_ZONE_END = "\x1b]133;B\x07"; +const OSC133_ZONE_FINAL = "\x1b]133;C\x07"; +/** + * Component that renders a complete assistant message + */ +export class AssistantMessageComponent extends Container { + contentContainer; + hideThinkingBlock; + markdownTheme; + hiddenThinkingLabel; + outputPad; + lastMessage; + hasToolCalls = false; + constructor(message, hideThinkingBlock = false, markdownTheme = getMarkdownTheme(), hiddenThinkingLabel = "Thinking...", outputPad = 1) { + super(); + this.hideThinkingBlock = hideThinkingBlock; + this.markdownTheme = markdownTheme; + this.hiddenThinkingLabel = hiddenThinkingLabel; + this.outputPad = outputPad; + // Container for text/thinking content + this.contentContainer = new Container(); + this.addChild(this.contentContainer); + if (message) { + this.updateContent(message); + } + } + invalidate() { + super.invalidate(); + if (this.lastMessage) { + this.updateContent(this.lastMessage); + } + } + setHideThinkingBlock(hide) { + this.hideThinkingBlock = hide; + if (this.lastMessage) { + this.updateContent(this.lastMessage); + } + } + setHiddenThinkingLabel(label) { + this.hiddenThinkingLabel = label; + if (this.lastMessage) { + this.updateContent(this.lastMessage); + } + } + setOutputPad(padding) { + this.outputPad = padding; + if (this.lastMessage) { + this.updateContent(this.lastMessage); + } + } + render(width) { + const lines = super.render(width); + if (this.hasToolCalls || lines.length === 0) { + return lines; + } + lines[0] = OSC133_ZONE_START + lines[0]; + lines[lines.length - 1] = OSC133_ZONE_END + OSC133_ZONE_FINAL + lines[lines.length - 1]; + return lines; + } + updateContent(message) { + this.lastMessage = message; + // Clear content container + this.contentContainer.clear(); + const hasVisibleContent = message.content.some((c) => (c.type === "text" && c.text.trim()) || (c.type === "thinking" && c.thinking.trim())); + if (hasVisibleContent) { + this.contentContainer.addChild(new Spacer(1)); + } + // Render content in order + for (let i = 0; i < message.content.length; i++) { + const content = message.content[i]; + if (content.type === "text" && content.text.trim()) { + // Assistant text messages with no background - trim the text + // Set paddingY=0 to avoid extra spacing before tool executions + this.contentContainer.addChild(new Markdown(content.text.trim(), this.outputPad, 0, this.markdownTheme)); + } + else if (content.type === "thinking") { + const thinkingBlocks = []; + for (; i < message.content.length; i++) { + const thinkingContent = message.content[i]; + if (thinkingContent.type !== "thinking") { + break; + } + const thinking = thinkingContent.thinking.trim(); + if (thinking) { + thinkingBlocks.push(thinking); + } + } + i--; + if (thinkingBlocks.length === 0) { + continue; + } + // Add spacing only when another visible assistant content block follows. + // This avoids a superfluous blank line before separately-rendered tool execution blocks. + const hasVisibleContentAfter = message.content + .slice(i + 1) + .some((c) => (c.type === "text" && c.text.trim()) || (c.type === "thinking" && c.thinking.trim())); + if (this.hideThinkingBlock) { + // Show one static label for each run of thinking blocks when hidden. + this.contentContainer.addChild(new Text(theme.italic(theme.fg("thinkingText", this.hiddenThinkingLabel)), this.outputPad, 0)); + } + else { + // Render each run of thinking blocks as one Markdown section. + this.contentContainer.addChild(new Markdown(thinkingBlocks.join("\n\n"), this.outputPad, 0, this.markdownTheme, { + color: (text) => theme.fg("thinkingText", text), + italic: true, + })); + } + if (hasVisibleContentAfter) { + this.contentContainer.addChild(new Spacer(1)); + } + } + } + // Check if incomplete/failed - show after partial content. + // For aborted/error tool calls, tool execution components show the error. + // Length stops can happen before a tool call is complete, so surface them here too. + const hasToolCalls = message.content.some((c) => c.type === "toolCall"); + this.hasToolCalls = hasToolCalls; + if (message.stopReason === "length") { + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(theme.fg("error", "Error: Model stopped because it reached the maximum output token limit. The response may be incomplete."), this.outputPad, 0)); + } + else if (!hasToolCalls) { + if (message.stopReason === "aborted") { + const abortMessage = message.errorMessage && message.errorMessage !== "Request was aborted" + ? message.errorMessage + : "Operation aborted"; + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(theme.fg("error", abortMessage), this.outputPad, 0)); + } + else if (message.stopReason === "error") { + const errorMsg = message.errorMessage || "Unknown error"; + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(theme.fg("error", `Error: ${errorMsg}`), this.outputPad, 0)); + } + } + } +} +//# sourceMappingURL=assistant-message.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/assistant-message.js.map b/dist/modes/interactive/components/assistant-message.js.map new file mode 100644 index 0000000..66e2c6a --- /dev/null +++ b/dist/modes/interactive/components/assistant-message.js.map @@ -0,0 +1 @@ +{"version":3,"file":"assistant-message.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/assistant-message.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAsB,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAC/F,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE5D,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;AAC3C,MAAM,eAAe,GAAG,gBAAgB,CAAC;AACzC,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;AAE3C;;GAEG;AACH,MAAM,OAAO,yBAA0B,SAAQ,SAAS;IAC/C,gBAAgB,CAAY;IAC5B,iBAAiB,CAAU;IAC3B,aAAa,CAAgB;IAC7B,mBAAmB,CAAS;IAC5B,SAAS,CAAS;IAClB,WAAW,CAAoB;IAC/B,YAAY,GAAG,KAAK,CAAC;IAE7B,YACC,OAA0B,EAC1B,iBAAiB,GAAG,KAAK,EACzB,aAAa,GAAkB,gBAAgB,EAAE,EACjD,mBAAmB,GAAG,aAAa,EACnC,SAAS,GAAG,CAAC,EACZ;QACD,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;QAC/C,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAE3B,sCAAsC;QACtC,IAAI,CAAC,gBAAgB,GAAG,IAAI,SAAS,EAAE,CAAC;QACxC,IAAI,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AAI,OAAO,CAAC,YAAY,KAAK,qBAAqB;oBACrE,CAAC,CAAC,OAAO,CAAC,YAAY;oBACtB,CAAC,CAAC,mBAAmB,CAAC;gBACxB,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC9C,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC;YAC9F,CAAC;iBAAM,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,EAAE,CAAC;gBAC3C,MAAM,QAAQ,GAAG,OAAO,CAAC,YAAY,IAAI,eAAe,CAAC;gBACzD,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC9C,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,QAAQ,EAAE,CAAC,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC;YACtG,CAAC;QACF,CAAC;IAAA,CACD;CACD","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai\";\nimport { Container, Markdown, type MarkdownTheme, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport { getMarkdownTheme, theme } from \"../theme/theme.ts\";\n\nconst OSC133_ZONE_START = \"\\x1b]133;A\\x07\";\nconst OSC133_ZONE_END = \"\\x1b]133;B\\x07\";\nconst OSC133_ZONE_FINAL = \"\\x1b]133;C\\x07\";\n\n/**\n * Component that renders a complete assistant message\n */\nexport class AssistantMessageComponent extends Container {\n\tprivate contentContainer: Container;\n\tprivate hideThinkingBlock: boolean;\n\tprivate markdownTheme: MarkdownTheme;\n\tprivate hiddenThinkingLabel: string;\n\tprivate outputPad: number;\n\tprivate lastMessage?: AssistantMessage;\n\tprivate hasToolCalls = false;\n\n\tconstructor(\n\t\tmessage?: AssistantMessage,\n\t\thideThinkingBlock = false,\n\t\tmarkdownTheme: MarkdownTheme = getMarkdownTheme(),\n\t\thiddenThinkingLabel = \"Thinking...\",\n\t\toutputPad = 1,\n\t) {\n\t\tsuper();\n\n\t\tthis.hideThinkingBlock = hideThinkingBlock;\n\t\tthis.markdownTheme = markdownTheme;\n\t\tthis.hiddenThinkingLabel = hiddenThinkingLabel;\n\t\tthis.outputPad = outputPad;\n\n\t\t// Container for text/thinking content\n\t\tthis.contentContainer = new Container();\n\t\tthis.addChild(this.contentContainer);\n\n\t\tif (message) {\n\t\t\tthis.updateContent(message);\n\t\t}\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tif (this.lastMessage) {\n\t\t\tthis.updateContent(this.lastMessage);\n\t\t}\n\t}\n\n\tsetHideThinkingBlock(hide: boolean): void {\n\t\tthis.hideThinkingBlock = hide;\n\t\tif (this.lastMessage) {\n\t\t\tthis.updateContent(this.lastMessage);\n\t\t}\n\t}\n\n\tsetHiddenThinkingLabel(label: string): void {\n\t\tthis.hiddenThinkingLabel = label;\n\t\tif (this.lastMessage) {\n\t\t\tthis.updateContent(this.lastMessage);\n\t\t}\n\t}\n\n\tsetOutputPad(padding: number): void {\n\t\tthis.outputPad = padding;\n\t\tif (this.lastMessage) {\n\t\t\tthis.updateContent(this.lastMessage);\n\t\t}\n\t}\n\n\toverride render(width: number): string[] {\n\t\tconst lines = super.render(width);\n\t\tif (this.hasToolCalls || lines.length === 0) {\n\t\t\treturn lines;\n\t\t}\n\n\t\tlines[0] = OSC133_ZONE_START + lines[0];\n\t\tlines[lines.length - 1] = OSC133_ZONE_END + OSC133_ZONE_FINAL + lines[lines.length - 1];\n\t\treturn lines;\n\t}\n\n\tupdateContent(message: AssistantMessage): void {\n\t\tthis.lastMessage = message;\n\n\t\t// Clear content container\n\t\tthis.contentContainer.clear();\n\n\t\tconst hasVisibleContent = message.content.some(\n\t\t\t(c) => (c.type === \"text\" && c.text.trim()) || (c.type === \"thinking\" && c.thinking.trim()),\n\t\t);\n\n\t\tif (hasVisibleContent) {\n\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t}\n\n\t\t// Render content in order\n\t\tfor (let i = 0; i < message.content.length; i++) {\n\t\t\tconst content = message.content[i];\n\t\t\tif (content.type === \"text\" && content.text.trim()) {\n\t\t\t\t// Assistant text messages with no background - trim the text\n\t\t\t\t// Set paddingY=0 to avoid extra spacing before tool executions\n\t\t\t\tthis.contentContainer.addChild(new Markdown(content.text.trim(), this.outputPad, 0, this.markdownTheme));\n\t\t\t} else if (content.type === \"thinking\") {\n\t\t\t\tconst thinkingBlocks: string[] = [];\n\t\t\t\tfor (; i < message.content.length; i++) {\n\t\t\t\t\tconst thinkingContent = message.content[i];\n\t\t\t\t\tif (thinkingContent.type !== \"thinking\") {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst thinking = thinkingContent.thinking.trim();\n\t\t\t\t\tif (thinking) {\n\t\t\t\t\t\tthinkingBlocks.push(thinking);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ti--;\n\n\t\t\t\tif (thinkingBlocks.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Add spacing only when another visible assistant content block follows.\n\t\t\t\t// This avoids a superfluous blank line before separately-rendered tool execution blocks.\n\t\t\t\tconst hasVisibleContentAfter = message.content\n\t\t\t\t\t.slice(i + 1)\n\t\t\t\t\t.some((c) => (c.type === \"text\" && c.text.trim()) || (c.type === \"thinking\" && c.thinking.trim()));\n\n\t\t\t\tif (this.hideThinkingBlock) {\n\t\t\t\t\t// Show one static label for each run of thinking blocks when hidden.\n\t\t\t\t\tthis.contentContainer.addChild(\n\t\t\t\t\t\tnew Text(theme.italic(theme.fg(\"thinkingText\", this.hiddenThinkingLabel)), this.outputPad, 0),\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\t// Render each run of thinking blocks as one Markdown section.\n\t\t\t\t\tthis.contentContainer.addChild(\n\t\t\t\t\t\tnew Markdown(thinkingBlocks.join(\"\\n\\n\"), this.outputPad, 0, this.markdownTheme, {\n\t\t\t\t\t\t\tcolor: (text: string) => theme.fg(\"thinkingText\", text),\n\t\t\t\t\t\t\titalic: true,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (hasVisibleContentAfter) {\n\t\t\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check if incomplete/failed - show after partial content.\n\t\t// For aborted/error tool calls, tool execution components show the error.\n\t\t// Length stops can happen before a tool call is complete, so surface them here too.\n\t\tconst hasToolCalls = message.content.some((c) => c.type === \"toolCall\");\n\t\tthis.hasToolCalls = hasToolCalls;\n\t\tif (message.stopReason === \"length\") {\n\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t\tthis.contentContainer.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\ttheme.fg(\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t\"Error: Model stopped because it reached the maximum output token limit. The response may be incomplete.\",\n\t\t\t\t\t),\n\t\t\t\t\tthis.outputPad,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t} else if (!hasToolCalls) {\n\t\t\tif (message.stopReason === \"aborted\") {\n\t\t\t\tconst abortMessage =\n\t\t\t\t\tmessage.errorMessage && message.errorMessage !== \"Request was aborted\"\n\t\t\t\t\t\t? message.errorMessage\n\t\t\t\t\t\t: \"Operation aborted\";\n\t\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t\t\tthis.contentContainer.addChild(new Text(theme.fg(\"error\", abortMessage), this.outputPad, 0));\n\t\t\t} else if (message.stopReason === \"error\") {\n\t\t\t\tconst errorMsg = message.errorMessage || \"Unknown error\";\n\t\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t\t\tthis.contentContainer.addChild(new Text(theme.fg(\"error\", `Error: ${errorMsg}`), this.outputPad, 0));\n\t\t\t}\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/bash-execution.d.ts b/dist/modes/interactive/components/bash-execution.d.ts new file mode 100644 index 0000000..d86b55e --- /dev/null +++ b/dist/modes/interactive/components/bash-execution.d.ts @@ -0,0 +1,34 @@ +/** + * Component for displaying bash command execution with streaming output. + */ +import { Container, type TUI } from "@earendil-works/pi-tui"; +import { type TruncationResult } from "../../../core/tools/truncate.ts"; +export declare class BashExecutionComponent extends Container { + private command; + private outputLines; + private status; + private exitCode; + private loader; + private truncationResult?; + private fullOutputPath?; + private expanded; + private contentContainer; + constructor(command: string, ui: TUI, excludeFromContext?: boolean); + /** + * Set whether the output is expanded (shows full output) or collapsed (preview only). + */ + setExpanded(expanded: boolean): void; + invalidate(): void; + appendOutput(chunk: string): void; + setComplete(exitCode: number | undefined, cancelled: boolean, truncationResult?: TruncationResult, fullOutputPath?: string): void; + private updateDisplay; + /** + * Get the raw output for creating BashExecutionMessage. + */ + getOutput(): string; + /** + * Get the command that was executed. + */ + getCommand(): string; +} +//# sourceMappingURL=bash-execution.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/bash-execution.d.ts.map b/dist/modes/interactive/components/bash-execution.d.ts.map new file mode 100644 index 0000000..60643b4 --- /dev/null +++ b/dist/modes/interactive/components/bash-execution.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bash-execution.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/bash-execution.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,SAAS,EAAwB,KAAK,GAAG,EAAE,MAAM,wBAAwB,CAAC;AACnF,OAAO,EAGN,KAAK,gBAAgB,EAErB,MAAM,iCAAiC,CAAC;AAUzC,qBAAa,sBAAuB,SAAQ,SAAS;IACpD,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,WAAW,CAAgB;IACnC,OAAO,CAAC,MAAM,CAA6D;IAC3E,OAAO,CAAC,QAAQ,CAAiC;IACjD,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,gBAAgB,CAAC,CAAmB;IAC5C,OAAO,CAAC,cAAc,CAAC,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,gBAAgB,CAAY;IAEpC,YAAY,OAAO,EAAE,MAAM,EAAE,EAAE,EAAE,GAAG,EAAE,kBAAkB,UAAQ,EAiC/D;IAED;;OAEG;IACH,WAAW,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI,CAGnC;IAEQ,UAAU,IAAI,IAAI,CAG1B;IAED,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAgBhC;IAED,WAAW,CACV,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,SAAS,EAAE,OAAO,EAClB,gBAAgB,CAAC,EAAE,gBAAgB,EACnC,cAAc,CAAC,EAAE,MAAM,GACrB,IAAI,CAcN;IAED,OAAO,CAAC,aAAa;IAwFrB;;OAEG;IACH,SAAS,IAAI,MAAM,CAElB;IAED;;OAEG;IACH,UAAU,IAAI,MAAM,CAEnB;CACD","sourcesContent":["/**\n * Component for displaying bash command execution with streaming output.\n */\n\nimport { Container, Loader, Spacer, Text, type TUI } from \"@earendil-works/pi-tui\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\ttype TruncationResult,\n\ttruncateTail,\n} from \"../../../core/tools/truncate.ts\";\nimport { stripAnsi } from \"../../../utils/ansi.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint, keyText } from \"./keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"./visual-truncate.ts\";\n\n// Preview line limit when not expanded (matches tool execution behavior)\nconst PREVIEW_LINES = 20;\n\nexport class BashExecutionComponent extends Container {\n\tprivate command: string;\n\tprivate outputLines: string[] = [];\n\tprivate status: \"running\" | \"complete\" | \"cancelled\" | \"error\" = \"running\";\n\tprivate exitCode: number | undefined = undefined;\n\tprivate loader: Loader;\n\tprivate truncationResult?: TruncationResult;\n\tprivate fullOutputPath?: string;\n\tprivate expanded = false;\n\tprivate contentContainer: Container;\n\n\tconstructor(command: string, ui: TUI, excludeFromContext = false) {\n\t\tsuper();\n\t\tthis.command = command;\n\n\t\t// Use dim border for excluded-from-context commands (!! prefix)\n\t\tconst colorKey = excludeFromContext ? \"dim\" : \"bashMode\";\n\t\tconst borderColor = (str: string) => theme.fg(colorKey, str);\n\n\t\t// Add spacer\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Top border\n\t\tthis.addChild(new DynamicBorder(borderColor));\n\n\t\t// Content container (holds dynamic content between borders)\n\t\tthis.contentContainer = new Container();\n\t\tthis.addChild(this.contentContainer);\n\n\t\t// Command header\n\t\tconst header = new Text(theme.fg(colorKey, theme.bold(`$ ${command}`)), 1, 0);\n\t\tthis.contentContainer.addChild(header);\n\n\t\t// Loader\n\t\tthis.loader = new Loader(\n\t\t\tui,\n\t\t\t(spinner) => theme.fg(colorKey, spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t`Running... (${keyText(\"tui.select.cancel\")} to cancel)`, // Plain text for loader\n\t\t);\n\t\tthis.contentContainer.addChild(this.loader);\n\n\t\t// Bottom border\n\t\tthis.addChild(new DynamicBorder(borderColor));\n\t}\n\n\t/**\n\t * Set whether the output is expanded (shows full output) or collapsed (preview only).\n\t */\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.expanded = expanded;\n\t\tthis.updateDisplay();\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.updateDisplay();\n\t}\n\n\tappendOutput(chunk: string): void {\n\t\t// Strip ANSI codes and normalize line endings\n\t\t// Note: binary data is already sanitized in tui-renderer.ts executeBashCommand\n\t\tconst clean = stripAnsi(chunk).replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n\n\t\t// Append to output lines\n\t\tconst newLines = clean.split(\"\\n\");\n\t\tif (this.outputLines.length > 0 && newLines.length > 0) {\n\t\t\t// Append first chunk to last line (incomplete line continuation)\n\t\t\tthis.outputLines[this.outputLines.length - 1] += newLines[0];\n\t\t\tthis.outputLines.push(...newLines.slice(1));\n\t\t} else {\n\t\t\tthis.outputLines.push(...newLines);\n\t\t}\n\n\t\tthis.updateDisplay();\n\t}\n\n\tsetComplete(\n\t\texitCode: number | undefined,\n\t\tcancelled: boolean,\n\t\ttruncationResult?: TruncationResult,\n\t\tfullOutputPath?: string,\n\t): void {\n\t\tthis.exitCode = exitCode;\n\t\tthis.status = cancelled\n\t\t\t? \"cancelled\"\n\t\t\t: exitCode !== 0 && exitCode !== undefined && exitCode !== null\n\t\t\t\t? \"error\"\n\t\t\t\t: \"complete\";\n\t\tthis.truncationResult = truncationResult;\n\t\tthis.fullOutputPath = fullOutputPath;\n\n\t\t// Stop loader\n\t\tthis.loader.stop();\n\n\t\tthis.updateDisplay();\n\t}\n\n\tprivate updateDisplay(): void {\n\t\t// Apply truncation for LLM context limits (same limits as bash tool)\n\t\tconst fullOutput = this.outputLines.join(\"\\n\");\n\t\tconst contextTruncation = truncateTail(fullOutput, {\n\t\t\tmaxLines: DEFAULT_MAX_LINES,\n\t\t\tmaxBytes: DEFAULT_MAX_BYTES,\n\t\t});\n\n\t\t// Get the lines to potentially display (after context truncation)\n\t\tconst availableLines = contextTruncation.content ? contextTruncation.content.split(\"\\n\") : [];\n\n\t\t// Apply preview truncation based on expanded state\n\t\tconst previewLogicalLines = availableLines.slice(-PREVIEW_LINES);\n\t\tconst hiddenLineCount = availableLines.length - previewLogicalLines.length;\n\n\t\t// Rebuild content container\n\t\tthis.contentContainer.clear();\n\n\t\t// Command header\n\t\tconst header = new Text(theme.fg(\"bashMode\", theme.bold(`$ ${this.command}`)), 1, 0);\n\t\tthis.contentContainer.addChild(header);\n\n\t\t// Output\n\t\tif (availableLines.length > 0) {\n\t\t\tif (this.expanded) {\n\t\t\t\t// Show all lines\n\t\t\t\tconst displayText = availableLines.map((line) => theme.fg(\"muted\", line)).join(\"\\n\");\n\t\t\t\tthis.contentContainer.addChild(new Text(`\\n${displayText}`, 1, 0));\n\t\t\t} else {\n\t\t\t\t// Use shared visual truncation utility with width-aware caching\n\t\t\t\tconst styledOutput = previewLogicalLines.map((line) => theme.fg(\"muted\", line)).join(\"\\n\");\n\t\t\t\tconst styledInput = `\\n${styledOutput}`;\n\t\t\t\tlet cachedWidth: number | undefined;\n\t\t\t\tlet cachedLines: string[] | undefined;\n\t\t\t\tthis.contentContainer.addChild({\n\t\t\t\t\trender: (width: number) => {\n\t\t\t\t\t\tif (cachedLines === undefined || cachedWidth !== width) {\n\t\t\t\t\t\t\tconst result = truncateToVisualLines(styledInput, PREVIEW_LINES, width, 1);\n\t\t\t\t\t\t\tcachedLines = result.visualLines;\n\t\t\t\t\t\t\tcachedWidth = width;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn cachedLines ?? [];\n\t\t\t\t\t},\n\t\t\t\t\tinvalidate: () => {\n\t\t\t\t\t\tcachedWidth = undefined;\n\t\t\t\t\t\tcachedLines = undefined;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Loader or status\n\t\tif (this.status === \"running\") {\n\t\t\tthis.contentContainer.addChild(this.loader);\n\t\t} else {\n\t\t\tconst statusParts: string[] = [];\n\n\t\t\t// Show how many lines are hidden (collapsed preview)\n\t\t\tif (hiddenLineCount > 0) {\n\t\t\t\tif (this.expanded) {\n\t\t\t\t\tstatusParts.push(\n\t\t\t\t\t\t`${theme.fg(\"muted\", \"(\")}${keyHint(\"app.tools.expand\", \"to collapse\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tstatusParts.push(\n\t\t\t\t\t\t`${theme.fg(\"muted\", `... ${hiddenLineCount} more lines (`)}${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.status === \"cancelled\") {\n\t\t\t\tstatusParts.push(theme.fg(\"warning\", \"(cancelled)\"));\n\t\t\t} else if (this.status === \"error\") {\n\t\t\t\tstatusParts.push(theme.fg(\"error\", `(exit ${this.exitCode})`));\n\t\t\t}\n\n\t\t\t// Add truncation warning (context truncation, not preview truncation)\n\t\t\tconst wasTruncated = this.truncationResult?.truncated || contextTruncation.truncated;\n\t\t\tif (wasTruncated && this.fullOutputPath) {\n\t\t\t\tstatusParts.push(theme.fg(\"warning\", `Output truncated. Full output: ${this.fullOutputPath}`));\n\t\t\t}\n\n\t\t\tif (statusParts.length > 0) {\n\t\t\t\tthis.contentContainer.addChild(new Text(`\\n${statusParts.join(\"\\n\")}`, 1, 0));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get the raw output for creating BashExecutionMessage.\n\t */\n\tgetOutput(): string {\n\t\treturn this.outputLines.join(\"\\n\");\n\t}\n\n\t/**\n\t * Get the command that was executed.\n\t */\n\tgetCommand(): string {\n\t\treturn this.command;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/bash-execution.js b/dist/modes/interactive/components/bash-execution.js new file mode 100644 index 0000000..d8e5ddb --- /dev/null +++ b/dist/modes/interactive/components/bash-execution.js @@ -0,0 +1,175 @@ +/** + * Component for displaying bash command execution with streaming output. + */ +import { Container, Loader, Spacer, Text } from "@earendil-works/pi-tui"; +import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, truncateTail, } from "../../../core/tools/truncate.js"; +import { stripAnsi } from "../../../utils/ansi.js"; +import { theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyHint, keyText } from "./keybinding-hints.js"; +import { truncateToVisualLines } from "./visual-truncate.js"; +// Preview line limit when not expanded (matches tool execution behavior) +const PREVIEW_LINES = 20; +export class BashExecutionComponent extends Container { + command; + outputLines = []; + status = "running"; + exitCode = undefined; + loader; + truncationResult; + fullOutputPath; + expanded = false; + contentContainer; + constructor(command, ui, excludeFromContext = false) { + super(); + this.command = command; + // Use dim border for excluded-from-context commands (!! prefix) + const colorKey = excludeFromContext ? "dim" : "bashMode"; + const borderColor = (str) => theme.fg(colorKey, str); + // Add spacer + this.addChild(new Spacer(1)); + // Top border + this.addChild(new DynamicBorder(borderColor)); + // Content container (holds dynamic content between borders) + this.contentContainer = new Container(); + this.addChild(this.contentContainer); + // Command header + const header = new Text(theme.fg(colorKey, theme.bold(`$ ${command}`)), 1, 0); + this.contentContainer.addChild(header); + // Loader + this.loader = new Loader(ui, (spinner) => theme.fg(colorKey, spinner), (text) => theme.fg("muted", text), `Running... (${keyText("tui.select.cancel")} to cancel)`); + this.contentContainer.addChild(this.loader); + // Bottom border + this.addChild(new DynamicBorder(borderColor)); + } + /** + * Set whether the output is expanded (shows full output) or collapsed (preview only). + */ + setExpanded(expanded) { + this.expanded = expanded; + this.updateDisplay(); + } + invalidate() { + super.invalidate(); + this.updateDisplay(); + } + appendOutput(chunk) { + // Strip ANSI codes and normalize line endings + // Note: binary data is already sanitized in tui-renderer.ts executeBashCommand + const clean = stripAnsi(chunk).replace(/\r\n/g, "\n").replace(/\r/g, "\n"); + // Append to output lines + const newLines = clean.split("\n"); + if (this.outputLines.length > 0 && newLines.length > 0) { + // Append first chunk to last line (incomplete line continuation) + this.outputLines[this.outputLines.length - 1] += newLines[0]; + this.outputLines.push(...newLines.slice(1)); + } + else { + this.outputLines.push(...newLines); + } + this.updateDisplay(); + } + setComplete(exitCode, cancelled, truncationResult, fullOutputPath) { + this.exitCode = exitCode; + this.status = cancelled + ? "cancelled" + : exitCode !== 0 && exitCode !== undefined && exitCode !== null + ? "error" + : "complete"; + this.truncationResult = truncationResult; + this.fullOutputPath = fullOutputPath; + // Stop loader + this.loader.stop(); + this.updateDisplay(); + } + updateDisplay() { + // Apply truncation for LLM context limits (same limits as bash tool) + const fullOutput = this.outputLines.join("\n"); + const contextTruncation = truncateTail(fullOutput, { + maxLines: DEFAULT_MAX_LINES, + maxBytes: DEFAULT_MAX_BYTES, + }); + // Get the lines to potentially display (after context truncation) + const availableLines = contextTruncation.content ? contextTruncation.content.split("\n") : []; + // Apply preview truncation based on expanded state + const previewLogicalLines = availableLines.slice(-PREVIEW_LINES); + const hiddenLineCount = availableLines.length - previewLogicalLines.length; + // Rebuild content container + this.contentContainer.clear(); + // Command header + const header = new Text(theme.fg("bashMode", theme.bold(`$ ${this.command}`)), 1, 0); + this.contentContainer.addChild(header); + // Output + if (availableLines.length > 0) { + if (this.expanded) { + // Show all lines + const displayText = availableLines.map((line) => theme.fg("muted", line)).join("\n"); + this.contentContainer.addChild(new Text(`\n${displayText}`, 1, 0)); + } + else { + // Use shared visual truncation utility with width-aware caching + const styledOutput = previewLogicalLines.map((line) => theme.fg("muted", line)).join("\n"); + const styledInput = `\n${styledOutput}`; + let cachedWidth; + let cachedLines; + this.contentContainer.addChild({ + render: (width) => { + if (cachedLines === undefined || cachedWidth !== width) { + const result = truncateToVisualLines(styledInput, PREVIEW_LINES, width, 1); + cachedLines = result.visualLines; + cachedWidth = width; + } + return cachedLines ?? []; + }, + invalidate: () => { + cachedWidth = undefined; + cachedLines = undefined; + }, + }); + } + } + // Loader or status + if (this.status === "running") { + this.contentContainer.addChild(this.loader); + } + else { + const statusParts = []; + // Show how many lines are hidden (collapsed preview) + if (hiddenLineCount > 0) { + if (this.expanded) { + statusParts.push(`${theme.fg("muted", "(")}${keyHint("app.tools.expand", "to collapse")}${theme.fg("muted", ")")}`); + } + else { + statusParts.push(`${theme.fg("muted", `... ${hiddenLineCount} more lines (`)}${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`); + } + } + if (this.status === "cancelled") { + statusParts.push(theme.fg("warning", "(cancelled)")); + } + else if (this.status === "error") { + statusParts.push(theme.fg("error", `(exit ${this.exitCode})`)); + } + // Add truncation warning (context truncation, not preview truncation) + const wasTruncated = this.truncationResult?.truncated || contextTruncation.truncated; + if (wasTruncated && this.fullOutputPath) { + statusParts.push(theme.fg("warning", `Output truncated. Full output: ${this.fullOutputPath}`)); + } + if (statusParts.length > 0) { + this.contentContainer.addChild(new Text(`\n${statusParts.join("\n")}`, 1, 0)); + } + } + } + /** + * Get the raw output for creating BashExecutionMessage. + */ + getOutput() { + return this.outputLines.join("\n"); + } + /** + * Get the command that was executed. + */ + getCommand() { + return this.command; + } +} +//# sourceMappingURL=bash-execution.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/bash-execution.js.map b/dist/modes/interactive/components/bash-execution.js.map new file mode 100644 index 0000000..3ef34ea --- /dev/null +++ b/dist/modes/interactive/components/bash-execution.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bash-execution.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/bash-execution.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAY,MAAM,wBAAwB,CAAC;AACnF,OAAO,EACN,iBAAiB,EACjB,iBAAiB,EAEjB,YAAY,GACZ,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,yEAAyE;AACzE,MAAM,aAAa,GAAG,EAAE,CAAC;AAEzB,MAAM,OAAO,sBAAuB,SAAQ,SAAS;IAC5C,OAAO,CAAS;IAChB,WAAW,GAAa,EAAE,CAAC;IAC3B,MAAM,GAAmD,SAAS,CAAC;IACnE,QAAQ,GAAuB,SAAS,CA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,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,SAAS,IAAI,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC;YAChE,CAAC;YAED,sEAAsE;YACtE,MAAM,YAAY,GAAG,IAAI,CAAC,gBAAgB,EAAE,SAAS,IAAI,iBAAiB,CAAC,SAAS,CAAC;YACrF,IAAI,YAAY,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;gBACzC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,SAAS,EAAE,kCAAkC,IAAI,CAAC,cAAc,EAAE,CAAC,CAAC,CAAC;YAChG,CAAC;YAED,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC5B,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC/E,CAAC;QACF,CAAC;IAAA,CACD;IAED;;OAEG;IACH,SAAS,GAAW;QACnB,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAAA,CACnC;IAED;;OAEG;IACH,UAAU,GAAW;QACpB,OAAO,IAAI,CAAC,OAAO,CAAC;IAAA,CACpB;CACD","sourcesContent":["/**\n * Component for displaying bash command execution with streaming output.\n */\n\nimport { Container, Loader, Spacer, Text, type TUI } from \"@earendil-works/pi-tui\";\nimport {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\ttype TruncationResult,\n\ttruncateTail,\n} from \"../../../core/tools/truncate.ts\";\nimport { stripAnsi } from \"../../../utils/ansi.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint, keyText } from \"./keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"./visual-truncate.ts\";\n\n// Preview line limit when not expanded (matches tool execution behavior)\nconst PREVIEW_LINES = 20;\n\nexport class BashExecutionComponent extends Container {\n\tprivate command: string;\n\tprivate outputLines: string[] = [];\n\tprivate status: \"running\" | \"complete\" | \"cancelled\" | \"error\" = \"running\";\n\tprivate exitCode: number | undefined = undefined;\n\tprivate loader: Loader;\n\tprivate truncationResult?: TruncationResult;\n\tprivate fullOutputPath?: string;\n\tprivate expanded = false;\n\tprivate contentContainer: Container;\n\n\tconstructor(command: string, ui: TUI, excludeFromContext = false) {\n\t\tsuper();\n\t\tthis.command = command;\n\n\t\t// Use dim border for excluded-from-context commands (!! prefix)\n\t\tconst colorKey = excludeFromContext ? \"dim\" : \"bashMode\";\n\t\tconst borderColor = (str: string) => theme.fg(colorKey, str);\n\n\t\t// Add spacer\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Top border\n\t\tthis.addChild(new DynamicBorder(borderColor));\n\n\t\t// Content container (holds dynamic content between borders)\n\t\tthis.contentContainer = new Container();\n\t\tthis.addChild(this.contentContainer);\n\n\t\t// Command header\n\t\tconst header = new Text(theme.fg(colorKey, theme.bold(`$ ${command}`)), 1, 0);\n\t\tthis.contentContainer.addChild(header);\n\n\t\t// Loader\n\t\tthis.loader = new Loader(\n\t\t\tui,\n\t\t\t(spinner) => theme.fg(colorKey, spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t`Running... (${keyText(\"tui.select.cancel\")} to cancel)`, // Plain text for loader\n\t\t);\n\t\tthis.contentContainer.addChild(this.loader);\n\n\t\t// Bottom border\n\t\tthis.addChild(new DynamicBorder(borderColor));\n\t}\n\n\t/**\n\t * Set whether the output is expanded (shows full output) or collapsed (preview only).\n\t */\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.expanded = expanded;\n\t\tthis.updateDisplay();\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.updateDisplay();\n\t}\n\n\tappendOutput(chunk: string): void {\n\t\t// Strip ANSI codes and normalize line endings\n\t\t// Note: binary data is already sanitized in tui-renderer.ts executeBashCommand\n\t\tconst clean = stripAnsi(chunk).replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n\n\t\t// Append to output lines\n\t\tconst newLines = clean.split(\"\\n\");\n\t\tif (this.outputLines.length > 0 && newLines.length > 0) {\n\t\t\t// Append first chunk to last line (incomplete line continuation)\n\t\t\tthis.outputLines[this.outputLines.length - 1] += newLines[0];\n\t\t\tthis.outputLines.push(...newLines.slice(1));\n\t\t} else {\n\t\t\tthis.outputLines.push(...newLines);\n\t\t}\n\n\t\tthis.updateDisplay();\n\t}\n\n\tsetComplete(\n\t\texitCode: number | undefined,\n\t\tcancelled: boolean,\n\t\ttruncationResult?: TruncationResult,\n\t\tfullOutputPath?: string,\n\t): void {\n\t\tthis.exitCode = exitCode;\n\t\tthis.status = cancelled\n\t\t\t? \"cancelled\"\n\t\t\t: exitCode !== 0 && exitCode !== undefined && exitCode !== null\n\t\t\t\t? \"error\"\n\t\t\t\t: \"complete\";\n\t\tthis.truncationResult = truncationResult;\n\t\tthis.fullOutputPath = fullOutputPath;\n\n\t\t// Stop loader\n\t\tthis.loader.stop();\n\n\t\tthis.updateDisplay();\n\t}\n\n\tprivate updateDisplay(): void {\n\t\t// Apply truncation for LLM context limits (same limits as bash tool)\n\t\tconst fullOutput = this.outputLines.join(\"\\n\");\n\t\tconst contextTruncation = truncateTail(fullOutput, {\n\t\t\tmaxLines: DEFAULT_MAX_LINES,\n\t\t\tmaxBytes: DEFAULT_MAX_BYTES,\n\t\t});\n\n\t\t// Get the lines to potentially display (after context truncation)\n\t\tconst availableLines = contextTruncation.content ? contextTruncation.content.split(\"\\n\") : [];\n\n\t\t// Apply preview truncation based on expanded state\n\t\tconst previewLogicalLines = availableLines.slice(-PREVIEW_LINES);\n\t\tconst hiddenLineCount = availableLines.length - previewLogicalLines.length;\n\n\t\t// Rebuild content container\n\t\tthis.contentContainer.clear();\n\n\t\t// Command header\n\t\tconst header = new Text(theme.fg(\"bashMode\", theme.bold(`$ ${this.command}`)), 1, 0);\n\t\tthis.contentContainer.addChild(header);\n\n\t\t// Output\n\t\tif (availableLines.length > 0) {\n\t\t\tif (this.expanded) {\n\t\t\t\t// Show all lines\n\t\t\t\tconst displayText = availableLines.map((line) => theme.fg(\"muted\", line)).join(\"\\n\");\n\t\t\t\tthis.contentContainer.addChild(new Text(`\\n${displayText}`, 1, 0));\n\t\t\t} else {\n\t\t\t\t// Use shared visual truncation utility with width-aware caching\n\t\t\t\tconst styledOutput = previewLogicalLines.map((line) => theme.fg(\"muted\", line)).join(\"\\n\");\n\t\t\t\tconst styledInput = `\\n${styledOutput}`;\n\t\t\t\tlet cachedWidth: number | undefined;\n\t\t\t\tlet cachedLines: string[] | undefined;\n\t\t\t\tthis.contentContainer.addChild({\n\t\t\t\t\trender: (width: number) => {\n\t\t\t\t\t\tif (cachedLines === undefined || cachedWidth !== width) {\n\t\t\t\t\t\t\tconst result = truncateToVisualLines(styledInput, PREVIEW_LINES, width, 1);\n\t\t\t\t\t\t\tcachedLines = result.visualLines;\n\t\t\t\t\t\t\tcachedWidth = width;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn cachedLines ?? [];\n\t\t\t\t\t},\n\t\t\t\t\tinvalidate: () => {\n\t\t\t\t\t\tcachedWidth = undefined;\n\t\t\t\t\t\tcachedLines = undefined;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Loader or status\n\t\tif (this.status === \"running\") {\n\t\t\tthis.contentContainer.addChild(this.loader);\n\t\t} else {\n\t\t\tconst statusParts: string[] = [];\n\n\t\t\t// Show how many lines are hidden (collapsed preview)\n\t\t\tif (hiddenLineCount > 0) {\n\t\t\t\tif (this.expanded) {\n\t\t\t\t\tstatusParts.push(\n\t\t\t\t\t\t`${theme.fg(\"muted\", \"(\")}${keyHint(\"app.tools.expand\", \"to collapse\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tstatusParts.push(\n\t\t\t\t\t\t`${theme.fg(\"muted\", `... ${hiddenLineCount} more lines (`)}${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.status === \"cancelled\") {\n\t\t\t\tstatusParts.push(theme.fg(\"warning\", \"(cancelled)\"));\n\t\t\t} else if (this.status === \"error\") {\n\t\t\t\tstatusParts.push(theme.fg(\"error\", `(exit ${this.exitCode})`));\n\t\t\t}\n\n\t\t\t// Add truncation warning (context truncation, not preview truncation)\n\t\t\tconst wasTruncated = this.truncationResult?.truncated || contextTruncation.truncated;\n\t\t\tif (wasTruncated && this.fullOutputPath) {\n\t\t\t\tstatusParts.push(theme.fg(\"warning\", `Output truncated. Full output: ${this.fullOutputPath}`));\n\t\t\t}\n\n\t\t\tif (statusParts.length > 0) {\n\t\t\t\tthis.contentContainer.addChild(new Text(`\\n${statusParts.join(\"\\n\")}`, 1, 0));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get the raw output for creating BashExecutionMessage.\n\t */\n\tgetOutput(): string {\n\t\treturn this.outputLines.join(\"\\n\");\n\t}\n\n\t/**\n\t * Get the command that was executed.\n\t */\n\tgetCommand(): string {\n\t\treturn this.command;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/bordered-loader.d.ts b/dist/modes/interactive/components/bordered-loader.d.ts new file mode 100644 index 0000000..e1ee9f8 --- /dev/null +++ b/dist/modes/interactive/components/bordered-loader.d.ts @@ -0,0 +1,16 @@ +import { Container, type TUI } from "@earendil-works/pi-tui"; +import type { Theme } from "../theme/theme.ts"; +/** Loader wrapped with borders for extension UI */ +export declare class BorderedLoader extends Container { + private loader; + private cancellable; + private signalController?; + constructor(tui: TUI, theme: Theme, message: string, options?: { + cancellable?: boolean; + }); + get signal(): AbortSignal; + set onAbort(fn: (() => void) | undefined); + handleInput(data: string): void; + dispose(): void; +} +//# sourceMappingURL=bordered-loader.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/bordered-loader.d.ts.map b/dist/modes/interactive/components/bordered-loader.d.ts.map new file mode 100644 index 0000000..fdfcae9 --- /dev/null +++ b/dist/modes/interactive/components/bordered-loader.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bordered-loader.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/bordered-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,SAAS,EAAwB,KAAK,GAAG,EAAE,MAAM,wBAAwB,CAAC;AACtG,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAI/C,mDAAmD;AACnD,qBAAa,cAAe,SAAQ,SAAS;IAC5C,OAAO,CAAC,MAAM,CAA6B;IAC3C,OAAO,CAAC,WAAW,CAAU;IAC7B,OAAO,CAAC,gBAAgB,CAAC,CAAkB;IAE3C,YAAY,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE,OAAO,CAAA;KAAE,EA4BvF;IAED,IAAI,MAAM,IAAI,WAAW,CAKxB;IAED,IAAI,OAAO,CAAC,EAAE,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,EAIvC;IAED,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAI9B;IAED,OAAO,IAAI,IAAI,CAMd;CACD","sourcesContent":["import { CancellableLoader, Container, Loader, Spacer, Text, type TUI } from \"@earendil-works/pi-tui\";\nimport type { Theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint } from \"./keybinding-hints.ts\";\n\n/** Loader wrapped with borders for extension UI */\nexport class BorderedLoader extends Container {\n\tprivate loader: CancellableLoader | Loader;\n\tprivate cancellable: boolean;\n\tprivate signalController?: AbortController;\n\n\tconstructor(tui: TUI, theme: Theme, message: string, options?: { cancellable?: boolean }) {\n\t\tsuper();\n\t\tthis.cancellable = options?.cancellable ?? true;\n\t\tconst borderColor = (s: string) => theme.fg(\"border\", s);\n\t\tthis.addChild(new DynamicBorder(borderColor));\n\t\tif (this.cancellable) {\n\t\t\tthis.loader = new CancellableLoader(\n\t\t\t\ttui,\n\t\t\t\t(s) => theme.fg(\"accent\", s),\n\t\t\t\t(s) => theme.fg(\"muted\", s),\n\t\t\t\tmessage,\n\t\t\t);\n\t\t} else {\n\t\t\tthis.signalController = new AbortController();\n\t\t\tthis.loader = new Loader(\n\t\t\t\ttui,\n\t\t\t\t(s) => theme.fg(\"accent\", s),\n\t\t\t\t(s) => theme.fg(\"muted\", s),\n\t\t\t\tmessage,\n\t\t\t);\n\t\t}\n\t\tthis.addChild(this.loader);\n\t\tif (this.cancellable) {\n\t\t\tthis.addChild(new Spacer(1));\n\t\t\tthis.addChild(new Text(keyHint(\"tui.select.cancel\", \"cancel\"), 1, 0));\n\t\t}\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder(borderColor));\n\t}\n\n\tget signal(): AbortSignal {\n\t\tif (this.cancellable) {\n\t\t\treturn (this.loader as CancellableLoader).signal;\n\t\t}\n\t\treturn this.signalController?.signal ?? new AbortController().signal;\n\t}\n\n\tset onAbort(fn: (() => void) | undefined) {\n\t\tif (this.cancellable) {\n\t\t\t(this.loader as CancellableLoader).onAbort = fn;\n\t\t}\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (this.cancellable) {\n\t\t\t(this.loader as CancellableLoader).handleInput(data);\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tif (\"dispose\" in this.loader && typeof this.loader.dispose === \"function\") {\n\t\t\tthis.loader.dispose();\n\t\t} else if (\"stop\" in this.loader && typeof this.loader.stop === \"function\") {\n\t\t\tthis.loader.stop();\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/bordered-loader.js b/dist/modes/interactive/components/bordered-loader.js new file mode 100644 index 0000000..bc1c2fe --- /dev/null +++ b/dist/modes/interactive/components/bordered-loader.js @@ -0,0 +1,54 @@ +import { CancellableLoader, Container, Loader, Spacer, Text } from "@earendil-works/pi-tui"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyHint } from "./keybinding-hints.js"; +/** Loader wrapped with borders for extension UI */ +export class BorderedLoader extends Container { + loader; + cancellable; + signalController; + constructor(tui, theme, message, options) { + super(); + this.cancellable = options?.cancellable ?? true; + const borderColor = (s) => theme.fg("border", s); + this.addChild(new DynamicBorder(borderColor)); + if (this.cancellable) { + this.loader = new CancellableLoader(tui, (s) => theme.fg("accent", s), (s) => theme.fg("muted", s), message); + } + else { + this.signalController = new AbortController(); + this.loader = new Loader(tui, (s) => theme.fg("accent", s), (s) => theme.fg("muted", s), message); + } + this.addChild(this.loader); + if (this.cancellable) { + this.addChild(new Spacer(1)); + this.addChild(new Text(keyHint("tui.select.cancel", "cancel"), 1, 0)); + } + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder(borderColor)); + } + get signal() { + if (this.cancellable) { + return this.loader.signal; + } + return this.signalController?.signal ?? new AbortController().signal; + } + set onAbort(fn) { + if (this.cancellable) { + this.loader.onAbort = fn; + } + } + handleInput(data) { + if (this.cancellable) { + this.loader.handleInput(data); + } + } + dispose() { + if ("dispose" in this.loader && typeof this.loader.dispose === "function") { + this.loader.dispose(); + } + else if ("stop" in this.loader && typeof this.loader.stop === "function") { + this.loader.stop(); + } + } +} +//# sourceMappingURL=bordered-loader.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/bordered-loader.js.map b/dist/modes/interactive/components/bordered-loader.js.map new file mode 100644 index 0000000..3f63467 --- /dev/null +++ b/dist/modes/interactive/components/bordered-loader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bordered-loader.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/bordered-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM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MAAM,IAAI,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YAC5E,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;QACpB,CAAC;IAAA,CACD;CACD","sourcesContent":["import { CancellableLoader, Container, Loader, Spacer, Text, type TUI } from \"@earendil-works/pi-tui\";\nimport type { Theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint } from \"./keybinding-hints.ts\";\n\n/** Loader wrapped with borders for extension UI */\nexport class BorderedLoader extends Container {\n\tprivate loader: CancellableLoader | Loader;\n\tprivate cancellable: boolean;\n\tprivate signalController?: AbortController;\n\n\tconstructor(tui: TUI, theme: Theme, message: string, options?: { cancellable?: boolean }) {\n\t\tsuper();\n\t\tthis.cancellable = options?.cancellable ?? true;\n\t\tconst borderColor = (s: string) => theme.fg(\"border\", s);\n\t\tthis.addChild(new DynamicBorder(borderColor));\n\t\tif (this.cancellable) {\n\t\t\tthis.loader = new CancellableLoader(\n\t\t\t\ttui,\n\t\t\t\t(s) => theme.fg(\"accent\", s),\n\t\t\t\t(s) => theme.fg(\"muted\", s),\n\t\t\t\tmessage,\n\t\t\t);\n\t\t} else {\n\t\t\tthis.signalController = new AbortController();\n\t\t\tthis.loader = new Loader(\n\t\t\t\ttui,\n\t\t\t\t(s) => theme.fg(\"accent\", s),\n\t\t\t\t(s) => theme.fg(\"muted\", s),\n\t\t\t\tmessage,\n\t\t\t);\n\t\t}\n\t\tthis.addChild(this.loader);\n\t\tif (this.cancellable) {\n\t\t\tthis.addChild(new Spacer(1));\n\t\t\tthis.addChild(new Text(keyHint(\"tui.select.cancel\", \"cancel\"), 1, 0));\n\t\t}\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder(borderColor));\n\t}\n\n\tget signal(): AbortSignal {\n\t\tif (this.cancellable) {\n\t\t\treturn (this.loader as CancellableLoader).signal;\n\t\t}\n\t\treturn this.signalController?.signal ?? new AbortController().signal;\n\t}\n\n\tset onAbort(fn: (() => void) | undefined) {\n\t\tif (this.cancellable) {\n\t\t\t(this.loader as CancellableLoader).onAbort = fn;\n\t\t}\n\t}\n\n\thandleInput(data: string): void {\n\t\tif (this.cancellable) {\n\t\t\t(this.loader as CancellableLoader).handleInput(data);\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tif (\"dispose\" in this.loader && typeof this.loader.dispose === \"function\") {\n\t\t\tthis.loader.dispose();\n\t\t} else if (\"stop\" in this.loader && typeof this.loader.stop === \"function\") {\n\t\t\tthis.loader.stop();\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/branch-summary-message.d.ts b/dist/modes/interactive/components/branch-summary-message.d.ts new file mode 100644 index 0000000..6ad1710 --- /dev/null +++ b/dist/modes/interactive/components/branch-summary-message.d.ts @@ -0,0 +1,16 @@ +import { Box, type MarkdownTheme } from "@earendil-works/pi-tui"; +import type { BranchSummaryMessage } from "../../../core/messages.ts"; +/** + * Component that renders a branch summary message with collapsed/expanded state. + * Uses same background color as custom messages for visual consistency. + */ +export declare class BranchSummaryMessageComponent extends Box { + private expanded; + private message; + private markdownTheme; + constructor(message: BranchSummaryMessage, markdownTheme?: MarkdownTheme); + setExpanded(expanded: boolean): void; + invalidate(): void; + private updateDisplay; +} +//# sourceMappingURL=branch-summary-message.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/branch-summary-message.d.ts.map b/dist/modes/interactive/components/branch-summary-message.d.ts.map new file mode 100644 index 0000000..45193cd --- /dev/null +++ b/dist/modes/interactive/components/branch-summary-message.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"branch-summary-message.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/branch-summary-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAY,KAAK,aAAa,EAAgB,MAAM,wBAAwB,CAAC;AACzF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAItE;;;GAGG;AACH,qBAAa,6BAA8B,SAAQ,GAAG;IACrD,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,OAAO,CAAuB;IACtC,OAAO,CAAC,aAAa,CAAgB;IAErC,YAAY,OAAO,EAAE,oBAAoB,EAAE,aAAa,GAAE,aAAkC,EAK3F;IAED,WAAW,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI,CAGnC;IAEQ,UAAU,IAAI,IAAI,CAG1B;IAED,OAAO,CAAC,aAAa;CA0BrB","sourcesContent":["import { Box, Markdown, type MarkdownTheme, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { BranchSummaryMessage } from \"../../../core/messages.ts\";\nimport { getMarkdownTheme, theme } from \"../theme/theme.ts\";\nimport { keyText } from \"./keybinding-hints.ts\";\n\n/**\n * Component that renders a branch summary message with collapsed/expanded state.\n * Uses same background color as custom messages for visual consistency.\n */\nexport class BranchSummaryMessageComponent extends Box {\n\tprivate expanded = false;\n\tprivate message: BranchSummaryMessage;\n\tprivate markdownTheme: MarkdownTheme;\n\n\tconstructor(message: BranchSummaryMessage, markdownTheme: MarkdownTheme = getMarkdownTheme()) {\n\t\tsuper(1, 1, (t) => theme.bg(\"customMessageBg\", t));\n\t\tthis.message = message;\n\t\tthis.markdownTheme = markdownTheme;\n\t\tthis.updateDisplay();\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.expanded = expanded;\n\t\tthis.updateDisplay();\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.updateDisplay();\n\t}\n\n\tprivate updateDisplay(): void {\n\t\tthis.clear();\n\n\t\tconst label = theme.fg(\"customMessageLabel\", `\\x1b[1m[branch]\\x1b[22m`);\n\t\tthis.addChild(new Text(label, 0, 0));\n\t\tthis.addChild(new Spacer(1));\n\n\t\tif (this.expanded) {\n\t\t\tconst header = \"**Branch Summary**\\n\\n\";\n\t\t\tthis.addChild(\n\t\t\t\tnew Markdown(header + this.message.summary, 0, 0, this.markdownTheme, {\n\t\t\t\t\tcolor: (text: string) => theme.fg(\"customMessageText\", text),\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\tthis.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\ttheme.fg(\"customMessageText\", \"Branch summary (\") +\n\t\t\t\t\t\ttheme.fg(\"dim\", keyText(\"app.tools.expand\")) +\n\t\t\t\t\t\ttheme.fg(\"customMessageText\", \" to expand)\"),\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/branch-summary-message.js b/dist/modes/interactive/components/branch-summary-message.js new file mode 100644 index 0000000..e23ca6d --- /dev/null +++ b/dist/modes/interactive/components/branch-summary-message.js @@ -0,0 +1,44 @@ +import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui"; +import { getMarkdownTheme, theme } from "../theme/theme.js"; +import { keyText } from "./keybinding-hints.js"; +/** + * Component that renders a branch summary message with collapsed/expanded state. + * Uses same background color as custom messages for visual consistency. + */ +export class BranchSummaryMessageComponent extends Box { + expanded = false; + message; + markdownTheme; + constructor(message, markdownTheme = getMarkdownTheme()) { + super(1, 1, (t) => theme.bg("customMessageBg", t)); + this.message = message; + this.markdownTheme = markdownTheme; + this.updateDisplay(); + } + setExpanded(expanded) { + this.expanded = expanded; + this.updateDisplay(); + } + invalidate() { + super.invalidate(); + this.updateDisplay(); + } + updateDisplay() { + this.clear(); + const label = theme.fg("customMessageLabel", `\x1b[1m[branch]\x1b[22m`); + this.addChild(new Text(label, 0, 0)); + this.addChild(new Spacer(1)); + if (this.expanded) { + const header = "**Branch Summary**\n\n"; + this.addChild(new Markdown(header + this.message.summary, 0, 0, this.markdownTheme, { + color: (text) => theme.fg("customMessageText", text), + })); + } + else { + this.addChild(new Text(theme.fg("customMessageText", "Branch summary (") + + theme.fg("dim", keyText("app.tools.expand")) + + theme.fg("customMessageText", " to expand)"), 0, 0)); + } + } +} +//# sourceMappingURL=branch-summary-message.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/branch-summary-message.js.map b/dist/modes/interactive/components/branch-summary-message.js.map new file mode 100644 index 0000000..43a94fd --- /dev/null +++ b/dist/modes/interactive/components/branch-summary-message.js.map @@ -0,0 +1 @@ +{"version":3,"file":"branch-summary-message.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/branch-summary-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAsB,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAEzF,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAEhD;;;GAGG;AACH,MAAM,OAAO,6BAA8B,SAAQ,GAAG;IAC7C,QAAQ,GAAG,KAAK,CAAC;IACjB,OAAO,CAAuB;IAC9B,aAAa,CAAgB;IAErC,YAAY,OAA6B,EAAE,aAAa,GAAkB,gBAAgB,EAAE,EAAE;QAC7F,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,iBAAiB,EAAE,CAAC,CAAC,CAAC,CAAC;QACnD,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,aAAa,EAAE,CAAC;IAAA,CACrB;IAED,WAAW,CAAC,QAAiB,EAAQ;QACpC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,aAAa,EAAE,CAAC;IAAA,CACrB;IAEQ,UAAU,GAAS;QAC3B,KAAK,CAAC,UAAU,EAAE,CAAC;QACnB,IAAI,CAAC,aAAa,EAAE,CAAC;IAAA,CACrB;IAEO,aAAa,GAAS;QAC7B,IAAI,CAAC,KAAK,EAAE,CAAC;QAEb,MAAM,KAAK,GAAG,KAAK,CAAC,EAAE,CAAC,oBAAoB,EAAE,yBAAyB,CAAC,CAAC;QACxE,IAAI,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QACrC,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAE7B,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YACnB,MAAM,MAAM,GAAG,wBAAwB,CAAC;YACxC,IAAI,CAAC,QAAQ,CACZ,IAAI,QAAQ,CAAC,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,aAAa,EAAE;gBACrE,KAAK,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,mBAAmB,EAAE,IAAI,CAAC;aAC5D,CAAC,CACF,CAAC;QACH,CAAC;aAAM,CAAC;YACP,IAAI,CAAC,QAAQ,CACZ,IAAI,IAAI,CACP,KAAK,CAAC,EAAE,CAAC,mBAAmB,EAAE,kBAAkB,CAAC;gBAChD,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,kBAAkB,CAAC,CAAC;gBAC5C,KAAK,CAAC,EAAE,CAAC,mBAAmB,EAAE,aAAa,CAAC,EAC7C,CAAC,EACD,CAAC,CACD,CACD,CAAC;QACH,CAAC;IAAA,CACD;CACD","sourcesContent":["import { Box, Markdown, type MarkdownTheme, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { BranchSummaryMessage } from \"../../../core/messages.ts\";\nimport { getMarkdownTheme, theme } from \"../theme/theme.ts\";\nimport { keyText } from \"./keybinding-hints.ts\";\n\n/**\n * Component that renders a branch summary message with collapsed/expanded state.\n * Uses same background color as custom messages for visual consistency.\n */\nexport class BranchSummaryMessageComponent extends Box {\n\tprivate expanded = false;\n\tprivate message: BranchSummaryMessage;\n\tprivate markdownTheme: MarkdownTheme;\n\n\tconstructor(message: BranchSummaryMessage, markdownTheme: MarkdownTheme = getMarkdownTheme()) {\n\t\tsuper(1, 1, (t) => theme.bg(\"customMessageBg\", t));\n\t\tthis.message = message;\n\t\tthis.markdownTheme = markdownTheme;\n\t\tthis.updateDisplay();\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.expanded = expanded;\n\t\tthis.updateDisplay();\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.updateDisplay();\n\t}\n\n\tprivate updateDisplay(): void {\n\t\tthis.clear();\n\n\t\tconst label = theme.fg(\"customMessageLabel\", `\\x1b[1m[branch]\\x1b[22m`);\n\t\tthis.addChild(new Text(label, 0, 0));\n\t\tthis.addChild(new Spacer(1));\n\n\t\tif (this.expanded) {\n\t\t\tconst header = \"**Branch Summary**\\n\\n\";\n\t\t\tthis.addChild(\n\t\t\t\tnew Markdown(header + this.message.summary, 0, 0, this.markdownTheme, {\n\t\t\t\t\tcolor: (text: string) => theme.fg(\"customMessageText\", text),\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\tthis.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\ttheme.fg(\"customMessageText\", \"Branch summary (\") +\n\t\t\t\t\t\ttheme.fg(\"dim\", keyText(\"app.tools.expand\")) +\n\t\t\t\t\t\ttheme.fg(\"customMessageText\", \" to expand)\"),\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/compaction-summary-message.d.ts b/dist/modes/interactive/components/compaction-summary-message.d.ts new file mode 100644 index 0000000..88bfa50 --- /dev/null +++ b/dist/modes/interactive/components/compaction-summary-message.d.ts @@ -0,0 +1,16 @@ +import { Box, type MarkdownTheme } from "@earendil-works/pi-tui"; +import type { CompactionSummaryMessage } from "../../../core/messages.ts"; +/** + * Component that renders a compaction message with collapsed/expanded state. + * Uses same background color as custom messages for visual consistency. + */ +export declare class CompactionSummaryMessageComponent extends Box { + private expanded; + private message; + private markdownTheme; + constructor(message: CompactionSummaryMessage, markdownTheme?: MarkdownTheme); + setExpanded(expanded: boolean): void; + invalidate(): void; + private updateDisplay; +} +//# sourceMappingURL=compaction-summary-message.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/compaction-summary-message.d.ts.map b/dist/modes/interactive/components/compaction-summary-message.d.ts.map new file mode 100644 index 0000000..70b480f --- /dev/null +++ b/dist/modes/interactive/components/compaction-summary-message.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"compaction-summary-message.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/compaction-summary-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAY,KAAK,aAAa,EAAgB,MAAM,wBAAwB,CAAC;AACzF,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAI1E;;;GAGG;AACH,qBAAa,iCAAkC,SAAQ,GAAG;IACzD,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,OAAO,CAA2B;IAC1C,OAAO,CAAC,aAAa,CAAgB;IAErC,YAAY,OAAO,EAAE,wBAAwB,EAAE,aAAa,GAAE,aAAkC,EAK/F;IAED,WAAW,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI,CAGnC;IAEQ,UAAU,IAAI,IAAI,CAG1B;IAED,OAAO,CAAC,aAAa;CA2BrB","sourcesContent":["import { Box, Markdown, type MarkdownTheme, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { CompactionSummaryMessage } from \"../../../core/messages.ts\";\nimport { getMarkdownTheme, theme } from \"../theme/theme.ts\";\nimport { keyText } from \"./keybinding-hints.ts\";\n\n/**\n * Component that renders a compaction message with collapsed/expanded state.\n * Uses same background color as custom messages for visual consistency.\n */\nexport class CompactionSummaryMessageComponent extends Box {\n\tprivate expanded = false;\n\tprivate message: CompactionSummaryMessage;\n\tprivate markdownTheme: MarkdownTheme;\n\n\tconstructor(message: CompactionSummaryMessage, markdownTheme: MarkdownTheme = getMarkdownTheme()) {\n\t\tsuper(1, 1, (t) => theme.bg(\"customMessageBg\", t));\n\t\tthis.message = message;\n\t\tthis.markdownTheme = markdownTheme;\n\t\tthis.updateDisplay();\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.expanded = expanded;\n\t\tthis.updateDisplay();\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.updateDisplay();\n\t}\n\n\tprivate updateDisplay(): void {\n\t\tthis.clear();\n\n\t\tconst tokenStr = this.message.tokensBefore.toLocaleString();\n\t\tconst label = theme.fg(\"customMessageLabel\", `\\x1b[1m[compaction]\\x1b[22m`);\n\t\tthis.addChild(new Text(label, 0, 0));\n\t\tthis.addChild(new Spacer(1));\n\n\t\tif (this.expanded) {\n\t\t\tconst header = `**Compacted from ${tokenStr} tokens**\\n\\n`;\n\t\t\tthis.addChild(\n\t\t\t\tnew Markdown(header + this.message.summary, 0, 0, this.markdownTheme, {\n\t\t\t\t\tcolor: (text: string) => theme.fg(\"customMessageText\", text),\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\tthis.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\ttheme.fg(\"customMessageText\", `Compacted from ${tokenStr} tokens (`) +\n\t\t\t\t\t\ttheme.fg(\"dim\", keyText(\"app.tools.expand\")) +\n\t\t\t\t\t\ttheme.fg(\"customMessageText\", \" to expand)\"),\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/compaction-summary-message.js b/dist/modes/interactive/components/compaction-summary-message.js new file mode 100644 index 0000000..48c2271 --- /dev/null +++ b/dist/modes/interactive/components/compaction-summary-message.js @@ -0,0 +1,45 @@ +import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui"; +import { getMarkdownTheme, theme } from "../theme/theme.js"; +import { keyText } from "./keybinding-hints.js"; +/** + * Component that renders a compaction message with collapsed/expanded state. + * Uses same background color as custom messages for visual consistency. + */ +export class CompactionSummaryMessageComponent extends Box { + expanded = false; + message; + markdownTheme; + constructor(message, markdownTheme = getMarkdownTheme()) { + super(1, 1, (t) => theme.bg("customMessageBg", t)); + this.message = message; + this.markdownTheme = markdownTheme; + this.updateDisplay(); + } + setExpanded(expanded) { + this.expanded = expanded; + this.updateDisplay(); + } + invalidate() { + super.invalidate(); + this.updateDisplay(); + } + updateDisplay() { + this.clear(); + const tokenStr = this.message.tokensBefore.toLocaleString(); + const label = theme.fg("customMessageLabel", `\x1b[1m[compaction]\x1b[22m`); + this.addChild(new Text(label, 0, 0)); + this.addChild(new Spacer(1)); + if (this.expanded) { + const header = `**Compacted from ${tokenStr} tokens**\n\n`; + this.addChild(new Markdown(header + this.message.summary, 0, 0, this.markdownTheme, { + color: (text) => theme.fg("customMessageText", text), + })); + } + else { + this.addChild(new Text(theme.fg("customMessageText", `Compacted from ${tokenStr} tokens (`) + + theme.fg("dim", keyText("app.tools.expand")) + + theme.fg("customMessageText", " to expand)"), 0, 0)); + } + } +} +//# sourceMappingURL=compaction-summary-message.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/compaction-summary-message.js.map b/dist/modes/interactive/components/compaction-summary-message.js.map new file mode 100644 index 0000000..133eacc --- /dev/null +++ b/dist/modes/interactive/components/compaction-summary-message.js.map @@ -0,0 +1 @@ +{"version":3,"file":"compaction-summary-message.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/compaction-summary-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAsB,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAEzF,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,MAAM,uBAA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,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,aAAa,EAAE;gBACrE,KAAK,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,mBAAmB,EAAE,IAAI,CAAC;aAC5D,CAAC,CACF,CAAC;QACH,CAAC;aAAM,CAAC;YACP,IAAI,CAAC,QAAQ,CACZ,IAAI,IAAI,CACP,KAAK,CAAC,EAAE,CAAC,mBAAmB,EAAE,kBAAkB,QAAQ,WAAW,CAAC;gBACnE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,kBAAkB,CAAC,CAAC;gBAC5C,KAAK,CAAC,EAAE,CAAC,mBAAmB,EAAE,aAAa,CAAC,EAC7C,CAAC,EACD,CAAC,CACD,CACD,CAAC;QACH,CAAC;IAAA,CACD;CACD","sourcesContent":["import { Box, Markdown, type MarkdownTheme, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { CompactionSummaryMessage } from \"../../../core/messages.ts\";\nimport { getMarkdownTheme, theme } from \"../theme/theme.ts\";\nimport { keyText } from \"./keybinding-hints.ts\";\n\n/**\n * Component that renders a compaction message with collapsed/expanded state.\n * Uses same background color as custom messages for visual consistency.\n */\nexport class CompactionSummaryMessageComponent extends Box {\n\tprivate expanded = false;\n\tprivate message: CompactionSummaryMessage;\n\tprivate markdownTheme: MarkdownTheme;\n\n\tconstructor(message: CompactionSummaryMessage, markdownTheme: MarkdownTheme = getMarkdownTheme()) {\n\t\tsuper(1, 1, (t) => theme.bg(\"customMessageBg\", t));\n\t\tthis.message = message;\n\t\tthis.markdownTheme = markdownTheme;\n\t\tthis.updateDisplay();\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.expanded = expanded;\n\t\tthis.updateDisplay();\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.updateDisplay();\n\t}\n\n\tprivate updateDisplay(): void {\n\t\tthis.clear();\n\n\t\tconst tokenStr = this.message.tokensBefore.toLocaleString();\n\t\tconst label = theme.fg(\"customMessageLabel\", `\\x1b[1m[compaction]\\x1b[22m`);\n\t\tthis.addChild(new Text(label, 0, 0));\n\t\tthis.addChild(new Spacer(1));\n\n\t\tif (this.expanded) {\n\t\t\tconst header = `**Compacted from ${tokenStr} tokens**\\n\\n`;\n\t\t\tthis.addChild(\n\t\t\t\tnew Markdown(header + this.message.summary, 0, 0, this.markdownTheme, {\n\t\t\t\t\tcolor: (text: string) => theme.fg(\"customMessageText\", text),\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\tthis.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\ttheme.fg(\"customMessageText\", `Compacted from ${tokenStr} tokens (`) +\n\t\t\t\t\t\ttheme.fg(\"dim\", keyText(\"app.tools.expand\")) +\n\t\t\t\t\t\ttheme.fg(\"customMessageText\", \" to expand)\"),\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/config-selector.d.ts b/dist/modes/interactive/components/config-selector.d.ts new file mode 100644 index 0000000..8048ccf --- /dev/null +++ b/dist/modes/interactive/components/config-selector.d.ts @@ -0,0 +1,102 @@ +/** + * TUI component for managing package resources (enable/disable) + */ +import { type Component, Container, type Focusable } from "@earendil-works/pi-tui"; +import type { PathMetadata, ResolvedPaths } from "../../../core/package-manager.ts"; +import type { SettingsManager } from "../../../core/settings-manager.ts"; +type ResourceType = "extensions" | "skills" | "prompts" | "themes"; +type ConfigWriteScope = "global" | "project"; +export type ScopedResolvedPaths = Record; +interface ResourceItem { + path: string; + enabled: boolean; + metadata: PathMetadata; + resourceType: ResourceType; + displayName: string; + groupKey: string; + subgroupKey: string; +} +interface ResourceSubgroup { + type: ResourceType; + label: string; + items: ResourceItem[]; +} +interface ResourceGroup { + key: string; + label: string; + scope: "user" | "project" | "temporary"; + origin: "package" | "top-level"; + source: string; + subgroups: ResourceSubgroup[]; +} +declare class ResourceList implements Component, Focusable { + private groupsByScope; + private flatItems; + private filteredItems; + private selectedIndex; + private searchInput; + private maxVisible; + private settingsManager; + private cwd; + private agentDir; + private writeScope; + private inheritedEnabledByKey; + onCancel?: () => void; + onExit?: () => void; + onToggle?: (item: ResourceItem, newEnabled: boolean) => void; + onSwitchMode?: () => void; + private _focused; + get focused(): boolean; + set focused(value: boolean); + constructor(groupsByScope: Record, settingsManager: SettingsManager, cwd: string, agentDir: string, terminalHeight?: number, writeScope?: ConfigWriteScope); + setWriteScope(writeScope: ConfigWriteScope): void; + private get groups(); + private buildInheritedEnabledMap; + private buildFlatList; + private findNextItem; + private filterItems; + private selectFirstItem; + updateItem(item: ResourceItem, enabled: boolean): void; + invalidate(): void; + render(width: number): string[]; + handleInput(data: string): void; + private toggleResource; + private toggleTopLevelResource; + private togglePackageResource; + private renderCheckbox; + private getItemSuffix; + private isDimmedItem; + private setProjectResourceOverride; + private setProjectTopLevelOverride; + private setProjectTopLevelPaths; + private setProjectPackageOverride; + private getNextOverrideState; + private getProjectOverrideState; + private getOverrideStateFromEntries; + private getInheritedEnabled; + private isInheritedGlobalItem; + private getTopLevelOverridePatterns; + private getResourcePatternForScope; + private createPackageOverrideSource; + private packageSourceStringMatches; + private findMatchingPackageSource; + private getPatternEntryTarget; + private getResourceItemKey; + private getItemScope; + private getTopLevelBaseDir; + private getResourcePattern; + private getPackageResourcePattern; +} +export declare class ConfigSelectorComponent extends Container implements Focusable { + private header; + private resourceList; + private writeScope; + private _focused; + get focused(): boolean; + set focused(value: boolean); + constructor(resolvedPaths: ScopedResolvedPaths, settingsManager: SettingsManager, cwd: string, agentDir: string, onClose: () => void, onExit: () => void, requestRender: () => void, terminalHeight?: number, writeScope?: ConfigWriteScope, projectModeAvailable?: boolean); + private switchWriteScope; + getResourceList(): ResourceList; +} +export {}; +//# sourceMappingURL=config-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/config-selector.d.ts.map b/dist/modes/interactive/components/config-selector.d.ts.map new file mode 100644 index 0000000..6dd44c6 --- /dev/null +++ b/dist/modes/interactive/components/config-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"config-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/config-selector.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EACN,KAAK,SAAS,EACd,SAAS,EACT,KAAK,SAAS,EAOd,MAAM,wBAAwB,CAAC;AAEhC,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAoB,MAAM,kCAAkC,CAAC;AACtG,OAAO,KAAK,EAAiB,eAAe,EAAE,MAAM,mCAAmC,CAAC;AAMxF,KAAK,YAAY,GAAG,YAAY,GAAG,QAAQ,GAAG,SAAS,GAAG,QAAQ,CAAC;AACnE,KAAK,gBAAgB,GAAG,QAAQ,GAAG,SAAS,CAAC;AAG7C,MAAM,MAAM,mBAAmB,GAAG,MAAM,CAAC,gBAAgB,EAAE,aAAa,CAAC,CAAC;AAW1E,UAAU,YAAY;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,YAAY,CAAC;IACvB,YAAY,EAAE,YAAY,CAAC;IAC3B,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,UAAU,gBAAgB;IACzB,IAAI,EAAE,YAAY,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,YAAY,EAAE,CAAC;CACtB;AAED,UAAU,aAAa;IACtB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,WAAW,CAAC;IACxC,MAAM,EAAE,SAAS,GAAG,WAAW,CAAC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,gBAAgB,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M,EAChB,OAAO,EAAE,MAAM,IAAI,EACnB,MAAM,EAAE,MAAM,IAAI,EAClB,aAAa,EAAE,MAAM,IAAI,EACzB,cAAc,CAAC,EAAE,MAAM,EACvB,UAAU,GAAE,gBAA2B,EACvC,oBAAoB,UAAO,EAyC3B;IAED,OAAO,CAAC,gBAAgB;IAMxB,eAAe,IAAI,YAAY,CAE9B;CACD","sourcesContent":["/**\n * TUI component for managing package resources (enable/disable)\n */\n\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, relative } from \"node:path\";\nimport {\n\ttype Component,\n\tContainer,\n\ttype Focusable,\n\tgetKeybindings,\n\tInput,\n\tmatchesKey,\n\tSpacer,\n\ttruncateToWidth,\n\tvisibleWidth,\n} from \"@earendil-works/pi-tui\";\nimport { CONFIG_DIR_NAME } from \"../../../config.ts\";\nimport type { PathMetadata, ResolvedPaths, ResolvedResource } from \"../../../core/package-manager.ts\";\nimport type { PackageSource, SettingsManager } from \"../../../core/settings-manager.ts\";\nimport { canonicalizePath, isLocalPath, resolvePath } from \"../../../utils/paths.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint, rawKeyHint } from \"./keybinding-hints.ts\";\n\ntype ResourceType = \"extensions\" | \"skills\" | \"prompts\" | \"themes\";\ntype ConfigWriteScope = \"global\" | \"project\";\ntype SettingsScope = \"user\" | \"project\";\ntype ProjectOverrideState = \"inherit\" | \"load\" | \"unload\";\nexport type ScopedResolvedPaths = Record;\n\nconst RESOURCE_TYPES = [\"extensions\", \"skills\", \"prompts\", \"themes\"] as const satisfies readonly ResourceType[];\n\nconst RESOURCE_TYPE_LABELS: Record = {\n\textensions: \"Extensions\",\n\tskills: \"Skills\",\n\tprompts: \"Prompts\",\n\tthemes: \"Themes\",\n};\n\ninterface ResourceItem {\n\tpath: string;\n\tenabled: boolean;\n\tmetadata: PathMetadata;\n\tresourceType: ResourceType;\n\tdisplayName: string;\n\tgroupKey: string;\n\tsubgroupKey: string;\n}\n\ninterface ResourceSubgroup {\n\ttype: ResourceType;\n\tlabel: string;\n\titems: ResourceItem[];\n}\n\ninterface ResourceGroup {\n\tkey: string;\n\tlabel: string;\n\tscope: \"user\" | \"project\" | \"temporary\";\n\torigin: \"package\" | \"top-level\";\n\tsource: string;\n\tsubgroups: ResourceSubgroup[];\n}\n\nfunction formatBaseDir(baseDir: string): string {\n\tconst homeDir = homedir();\n\tlet displayPath: string;\n\n\tif (baseDir === homeDir) {\n\t\tdisplayPath = \"~\";\n\t} else if (baseDir.startsWith(homeDir)) {\n\t\t// Replace home prefix with ~, normalize separators for display\n\t\tconst rest = baseDir.slice(homeDir.length);\n\t\tdisplayPath = `~${rest.replace(/\\\\/g, \"/\")}`;\n\t} else {\n\t\tdisplayPath = baseDir.replace(/\\\\/g, \"/\");\n\t}\n\n\treturn displayPath.endsWith(\"/\") ? displayPath : `${displayPath}/`;\n}\n\nfunction getGroupLabel(metadata: PathMetadata, agentDir: string): string {\n\tif (metadata.origin === \"package\") {\n\t\treturn `${metadata.source} (${metadata.scope})`;\n\t}\n\t// Top-level resources\n\tif (metadata.source === \"auto\") {\n\t\tif (metadata.baseDir) {\n\t\t\treturn metadata.scope === \"user\"\n\t\t\t\t? `User (${formatBaseDir(metadata.baseDir)})`\n\t\t\t\t: `Project (${formatBaseDir(metadata.baseDir)})`;\n\t\t}\n\t\treturn metadata.scope === \"user\" ? `User (${formatBaseDir(agentDir)})` : `Project (${CONFIG_DIR_NAME}/)`;\n\t}\n\treturn metadata.scope === \"user\" ? \"User settings\" : \"Project settings\";\n}\n\nfunction buildGroups(resolved: ResolvedPaths, agentDir: string): ResourceGroup[] {\n\tconst groupMap = new Map();\n\n\tconst addToGroup = (resources: ResolvedResource[], resourceType: ResourceType) => {\n\t\tfor (const res of resources) {\n\t\t\tconst { path, enabled, metadata } = res;\n\t\t\tconst groupKey = `${metadata.origin}:${metadata.scope}:${metadata.source}:${metadata.baseDir ?? \"\"}`;\n\n\t\t\tif (!groupMap.has(groupKey)) {\n\t\t\t\tgroupMap.set(groupKey, {\n\t\t\t\t\tkey: groupKey,\n\t\t\t\t\tlabel: getGroupLabel(metadata, agentDir),\n\t\t\t\t\tscope: metadata.scope,\n\t\t\t\t\torigin: metadata.origin,\n\t\t\t\t\tsource: metadata.source,\n\t\t\t\t\tsubgroups: [],\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst group = groupMap.get(groupKey)!;\n\t\t\tconst subgroupKey = `${groupKey}:${resourceType}`;\n\n\t\t\tlet subgroup = group.subgroups.find((sg) => sg.type === resourceType);\n\t\t\tif (!subgroup) {\n\t\t\t\tsubgroup = {\n\t\t\t\t\ttype: resourceType,\n\t\t\t\t\tlabel: RESOURCE_TYPE_LABELS[resourceType],\n\t\t\t\t\titems: [],\n\t\t\t\t};\n\t\t\t\tgroup.subgroups.push(subgroup);\n\t\t\t}\n\n\t\t\tconst fileName = basename(path);\n\t\t\tconst parentFolder = basename(dirname(path));\n\t\t\tlet displayName: string;\n\t\t\tif (resourceType === \"extensions\" && parentFolder !== \"extensions\") {\n\t\t\t\tdisplayName = `${parentFolder}/${fileName}`;\n\t\t\t} else if (resourceType === \"skills\" && fileName === \"SKILL.md\") {\n\t\t\t\tdisplayName = parentFolder;\n\t\t\t} else {\n\t\t\t\tdisplayName = fileName;\n\t\t\t}\n\t\t\tsubgroup.items.push({\n\t\t\t\tpath,\n\t\t\t\tenabled,\n\t\t\t\tmetadata,\n\t\t\t\tresourceType,\n\t\t\t\tdisplayName,\n\t\t\t\tgroupKey,\n\t\t\t\tsubgroupKey,\n\t\t\t});\n\t\t}\n\t};\n\n\taddToGroup(resolved.extensions, \"extensions\");\n\taddToGroup(resolved.skills, \"skills\");\n\taddToGroup(resolved.prompts, \"prompts\");\n\taddToGroup(resolved.themes, \"themes\");\n\n\t// Sort groups: packages first, then top-level; user before project\n\tconst groups = Array.from(groupMap.values());\n\tgroups.sort((a, b) => {\n\t\tif (a.origin !== b.origin) {\n\t\t\treturn a.origin === \"package\" ? -1 : 1;\n\t\t}\n\t\tif (a.scope !== b.scope) {\n\t\t\treturn a.scope === \"user\" ? -1 : 1;\n\t\t}\n\t\treturn a.source.localeCompare(b.source);\n\t});\n\n\t// Sort subgroups within each group by type order, and items by name\n\tconst typeOrder: Record = { extensions: 0, skills: 1, prompts: 2, themes: 3 };\n\tfor (const group of groups) {\n\t\tgroup.subgroups.sort((a, b) => typeOrder[a.type] - typeOrder[b.type]);\n\t\tfor (const subgroup of group.subgroups) {\n\t\t\tsubgroup.items.sort((a, b) => a.displayName.localeCompare(b.displayName));\n\t\t}\n\t}\n\n\treturn groups;\n}\n\ntype FlatEntry =\n\t| { type: \"group\"; group: ResourceGroup }\n\t| { type: \"subgroup\"; subgroup: ResourceSubgroup; group: ResourceGroup }\n\t| { type: \"item\"; item: ResourceItem };\n\nclass ConfigSelectorHeader implements Component {\n\tprivate writeScope: ConfigWriteScope;\n\tprivate projectModeAvailable: boolean;\n\n\tconstructor(writeScope: ConfigWriteScope, projectModeAvailable: boolean) {\n\t\tthis.writeScope = writeScope;\n\t\tthis.projectModeAvailable = projectModeAvailable;\n\t}\n\n\tsetWriteScope(writeScope: ConfigWriteScope): void {\n\t\tthis.writeScope = writeScope;\n\t}\n\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst title = theme.bold(this.writeScope === \"project\" ? \"Project Local Resources\" : \"Global Resources\");\n\t\tconst sep = theme.fg(\"muted\", \" · \");\n\t\tconst switchHint = this.projectModeAvailable ? keyHint(\"tui.input.tab\", \"switch mode\") + sep : \"\";\n\t\tconst actionHint =\n\t\t\tthis.writeScope === \"project\" ? rawKeyHint(\"space\", \"cycle inherit/+/-\") : rawKeyHint(\"space\", \"toggle\");\n\t\tconst hint = switchHint + actionHint + sep + rawKeyHint(\"esc\", \"close\");\n\t\tconst spacing = Math.max(1, width - visibleWidth(title) - visibleWidth(hint));\n\t\tconst scopeHint =\n\t\t\tthis.writeScope === \"project\"\n\t\t\t\t? theme.fg(\"muted\", `${CONFIG_DIR_NAME}/settings.json · inherited global resources are dimmed`)\n\t\t\t\t: theme.fg(\"muted\", `~/${CONFIG_DIR_NAME}/agent/settings.json`);\n\n\t\treturn [\n\t\t\ttruncateToWidth(`${title}${\" \".repeat(spacing)}${hint}`, width, \"\"),\n\t\t\ttruncateToWidth(scopeHint, width, \"\"),\n\t\t];\n\t}\n}\n\nclass ResourceList implements Component, Focusable {\n\tprivate groupsByScope: Record;\n\tprivate flatItems: FlatEntry[] = [];\n\tprivate filteredItems: FlatEntry[] = [];\n\tprivate selectedIndex = 0;\n\tprivate searchInput: Input;\n\tprivate maxVisible: number;\n\tprivate settingsManager: SettingsManager;\n\tprivate cwd: string;\n\tprivate agentDir: string;\n\tprivate writeScope: ConfigWriteScope;\n\tprivate inheritedEnabledByKey: Map;\n\n\tpublic onCancel?: () => void;\n\tpublic onExit?: () => void;\n\tpublic onToggle?: (item: ResourceItem, newEnabled: boolean) => void;\n\tpublic onSwitchMode?: () => void;\n\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.searchInput.focused = value;\n\t}\n\n\tconstructor(\n\t\tgroupsByScope: Record,\n\t\tsettingsManager: SettingsManager,\n\t\tcwd: string,\n\t\tagentDir: string,\n\t\tterminalHeight?: number,\n\t\twriteScope: ConfigWriteScope = \"global\",\n\t) {\n\t\tthis.groupsByScope = groupsByScope;\n\t\tthis.settingsManager = settingsManager;\n\t\tthis.cwd = cwd;\n\t\tthis.agentDir = agentDir;\n\t\tthis.writeScope = writeScope;\n\t\tthis.inheritedEnabledByKey = this.buildInheritedEnabledMap(groupsByScope.global);\n\t\tthis.searchInput = new Input();\n\t\t// 8 lines of chrome: top spacer + top border + spacer + header (2 lines) + spacer + bottom spacer + bottom border\n\t\tconst chrome = 8;\n\t\tthis.maxVisible = Math.max(5, (terminalHeight ?? 24) - chrome);\n\t\tthis.buildFlatList();\n\t\tthis.filteredItems = [...this.flatItems];\n\t}\n\n\tsetWriteScope(writeScope: ConfigWriteScope): void {\n\t\tthis.writeScope = writeScope;\n\t\tthis.buildFlatList();\n\t\tthis.filterItems(this.searchInput.getValue());\n\t}\n\n\tprivate get groups(): ResourceGroup[] {\n\t\treturn this.groupsByScope[this.writeScope];\n\t}\n\n\tprivate buildInheritedEnabledMap(groups: ResourceGroup[]): Map {\n\t\tconst result = new Map();\n\t\tfor (const group of groups) {\n\t\t\tfor (const subgroup of group.subgroups) {\n\t\t\t\tfor (const item of subgroup.items) {\n\t\t\t\t\tresult.set(this.getResourceItemKey(item), item.enabled);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate buildFlatList(): void {\n\t\tthis.flatItems = [];\n\t\tfor (const group of this.groups) {\n\t\t\tthis.flatItems.push({ type: \"group\", group });\n\t\t\tfor (const subgroup of group.subgroups) {\n\t\t\t\tthis.flatItems.push({ type: \"subgroup\", subgroup, group });\n\t\t\t\tfor (const item of subgroup.items) {\n\t\t\t\t\tthis.flatItems.push({ type: \"item\", item });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Start selection on first item (not header)\n\t\tthis.selectedIndex = this.flatItems.findIndex((e) => e.type === \"item\");\n\t\tif (this.selectedIndex < 0) this.selectedIndex = 0;\n\t}\n\n\tprivate findNextItem(fromIndex: number, direction: 1 | -1): number {\n\t\tlet idx = fromIndex + direction;\n\t\twhile (idx >= 0 && idx < this.filteredItems.length) {\n\t\t\tif (this.filteredItems[idx].type === \"item\") {\n\t\t\t\treturn idx;\n\t\t\t}\n\t\t\tidx += direction;\n\t\t}\n\t\treturn fromIndex; // Stay at current if no item found\n\t}\n\n\tprivate filterItems(query: string): void {\n\t\tif (!query.trim()) {\n\t\t\tthis.filteredItems = [...this.flatItems];\n\t\t\tthis.selectFirstItem();\n\t\t\treturn;\n\t\t}\n\n\t\tconst lowerQuery = query.toLowerCase();\n\t\tconst matchingItems = new Set();\n\t\tconst matchingSubgroups = new Set();\n\t\tconst matchingGroups = new Set();\n\n\t\tfor (const entry of this.flatItems) {\n\t\t\tif (entry.type === \"item\") {\n\t\t\t\tconst item = entry.item;\n\t\t\t\tif (\n\t\t\t\t\titem.displayName.toLowerCase().includes(lowerQuery) ||\n\t\t\t\t\titem.resourceType.toLowerCase().includes(lowerQuery) ||\n\t\t\t\t\titem.path.toLowerCase().includes(lowerQuery)\n\t\t\t\t) {\n\t\t\t\t\tmatchingItems.add(item);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Find which subgroups and groups contain matching items\n\t\tfor (const group of this.groups) {\n\t\t\tfor (const subgroup of group.subgroups) {\n\t\t\t\tfor (const item of subgroup.items) {\n\t\t\t\t\tif (matchingItems.has(item)) {\n\t\t\t\t\t\tmatchingSubgroups.add(subgroup);\n\t\t\t\t\t\tmatchingGroups.add(group);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.filteredItems = [];\n\t\tfor (const entry of this.flatItems) {\n\t\t\tif (entry.type === \"group\" && matchingGroups.has(entry.group)) {\n\t\t\t\tthis.filteredItems.push(entry);\n\t\t\t} else if (entry.type === \"subgroup\" && matchingSubgroups.has(entry.subgroup)) {\n\t\t\t\tthis.filteredItems.push(entry);\n\t\t\t} else if (entry.type === \"item\" && matchingItems.has(entry.item)) {\n\t\t\t\tthis.filteredItems.push(entry);\n\t\t\t}\n\t\t}\n\n\t\tthis.selectFirstItem();\n\t}\n\n\tprivate selectFirstItem(): void {\n\t\tconst firstItemIndex = this.filteredItems.findIndex((e) => e.type === \"item\");\n\t\tthis.selectedIndex = firstItemIndex >= 0 ? firstItemIndex : 0;\n\t}\n\n\tupdateItem(item: ResourceItem, enabled: boolean): void {\n\t\titem.enabled = enabled;\n\t\t// Update in groups too\n\t\tfor (const group of this.groups) {\n\t\t\tfor (const subgroup of group.subgroups) {\n\t\t\t\tconst found = subgroup.items.find((i) => i.path === item.path && i.resourceType === item.resourceType);\n\t\t\t\tif (found) {\n\t\t\t\t\tfound.enabled = enabled;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\n\t\t// Search input\n\t\tlines.push(...this.searchInput.render(width));\n\t\tlines.push(\"\");\n\n\t\tif (this.filteredItems.length === 0) {\n\t\t\tlines.push(theme.fg(\"muted\", \" No resources found\"));\n\t\t\treturn lines;\n\t\t}\n\n\t\t// Calculate visible range\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredItems.length - this.maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisible, this.filteredItems.length);\n\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst entry = this.filteredItems[i];\n\t\t\tconst isSelected = i === this.selectedIndex;\n\n\t\t\tif (entry.type === \"group\") {\n\t\t\t\t// Main group header (no cursor)\n\t\t\t\tconst inherited = this.writeScope === \"project\" && entry.group.scope === \"user\";\n\t\t\t\tconst label = theme.bold(`${entry.group.label}${inherited ? \" · inherited global\" : \"\"}`);\n\t\t\t\tconst groupLine = theme.fg(inherited ? \"dim\" : \"accent\", label);\n\t\t\t\tlines.push(truncateToWidth(` ${groupLine}`, width, \"\"));\n\t\t\t} else if (entry.type === \"subgroup\") {\n\t\t\t\t// Subgroup header (indented, no cursor)\n\t\t\t\tconst color = this.writeScope === \"project\" && entry.group.scope === \"user\" ? \"dim\" : \"muted\";\n\t\t\t\tconst subgroupLine = theme.fg(color, entry.subgroup.label);\n\t\t\t\tlines.push(truncateToWidth(` ${subgroupLine}`, width, \"\"));\n\t\t\t} else {\n\t\t\t\t// Resource item (cursor only on items)\n\t\t\t\tconst item = entry.item;\n\t\t\t\tconst cursor = isSelected ? \"> \" : \" \";\n\t\t\t\tconst dimmed = this.isDimmedItem(item);\n\t\t\t\tconst nameText = isSelected && !dimmed ? theme.bold(item.displayName) : item.displayName;\n\t\t\t\tconst name = dimmed ? theme.fg(\"dim\", nameText) : nameText;\n\t\t\t\tlines.push(\n\t\t\t\t\ttruncateToWidth(\n\t\t\t\t\t\t`${cursor} ${this.renderCheckbox(item)} ${name}${this.getItemSuffix(item)}`,\n\t\t\t\t\t\twidth,\n\t\t\t\t\t\t\"...\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Scroll indicator\n\t\tif (startIndex > 0 || endIndex < this.filteredItems.length) {\n\t\t\tconst itemCount = this.filteredItems.filter((e) => e.type === \"item\").length;\n\t\t\tconst currentItemIndex =\n\t\t\t\tthis.filteredItems.slice(0, this.selectedIndex).filter((e) => e.type === \"item\").length + 1;\n\t\t\tlines.push(theme.fg(\"dim\", ` (${currentItemIndex}/${itemCount})`));\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\thandleInput(data: string): void {\n\t\tconst kb = getKeybindings();\n\n\t\tif (kb.matches(data, \"tui.select.up\")) {\n\t\t\tthis.selectedIndex = this.findNextItem(this.selectedIndex, -1);\n\t\t\treturn;\n\t\t}\n\t\tif (kb.matches(data, \"tui.select.down\")) {\n\t\t\tthis.selectedIndex = this.findNextItem(this.selectedIndex, 1);\n\t\t\treturn;\n\t\t}\n\t\tif (kb.matches(data, \"tui.select.pageUp\")) {\n\t\t\t// Jump up by maxVisible, then find nearest item\n\t\t\tlet target = Math.max(0, this.selectedIndex - this.maxVisible);\n\t\t\twhile (target < this.filteredItems.length && this.filteredItems[target].type !== \"item\") {\n\t\t\t\ttarget++;\n\t\t\t}\n\t\t\tif (target < this.filteredItems.length) {\n\t\t\t\tthis.selectedIndex = target;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (kb.matches(data, \"tui.select.pageDown\")) {\n\t\t\t// Jump down by maxVisible, then find nearest item\n\t\t\tlet target = Math.min(this.filteredItems.length - 1, this.selectedIndex + this.maxVisible);\n\t\t\twhile (target >= 0 && this.filteredItems[target].type !== \"item\") {\n\t\t\t\ttarget--;\n\t\t\t}\n\t\t\tif (target >= 0) {\n\t\t\t\tthis.selectedIndex = target;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (kb.matches(data, \"tui.select.cancel\")) {\n\t\t\tthis.onCancel?.();\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, \"ctrl+c\")) {\n\t\t\tthis.onExit?.();\n\t\t\treturn;\n\t\t}\n\t\tif (kb.matches(data, \"tui.input.tab\")) {\n\t\t\tthis.onSwitchMode?.();\n\t\t\treturn;\n\t\t}\n\t\tif (data === \" \" || kb.matches(data, \"tui.select.confirm\")) {\n\t\t\tconst entry = this.filteredItems[this.selectedIndex];\n\t\t\tif (entry?.type === \"item\" && (this.writeScope === \"project\" || this.getItemScope(entry.item) === \"user\")) {\n\t\t\t\tconst newEnabled = this.toggleResource(entry.item);\n\t\t\t\tif (newEnabled !== undefined) {\n\t\t\t\t\tthis.updateItem(entry.item, newEnabled);\n\t\t\t\t\tthis.onToggle?.(entry.item, newEnabled);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Pass to search input\n\t\tthis.searchInput.handleInput(data);\n\t\tthis.filterItems(this.searchInput.getValue());\n\t}\n\n\tprivate toggleResource(item: ResourceItem): boolean | undefined {\n\t\tif (this.writeScope === \"project\") {\n\t\t\tconst state = this.getNextOverrideState(item);\n\t\t\tif (!this.setProjectResourceOverride(item, state)) return undefined;\n\t\t\treturn state === \"inherit\" ? this.getInheritedEnabled(item) : state === \"load\";\n\t\t}\n\n\t\tconst enabled = !item.enabled;\n\t\tif (item.metadata.origin === \"top-level\") {\n\t\t\tthis.toggleTopLevelResource(item, enabled);\n\t\t} else {\n\t\t\tthis.togglePackageResource(item, enabled);\n\t\t}\n\t\treturn enabled;\n\t}\n\n\tprivate toggleTopLevelResource(item: ResourceItem, enabled: boolean): void {\n\t\tconst scope = item.metadata.scope as \"user\" | \"project\";\n\t\tconst settings =\n\t\t\tscope === \"project\" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings();\n\n\t\tconst arrayKey = item.resourceType as \"extensions\" | \"skills\" | \"prompts\" | \"themes\";\n\t\tconst current = (settings[arrayKey] ?? []) as string[];\n\n\t\t// Generate pattern for this resource\n\t\tconst pattern = this.getResourcePattern(item);\n\t\tconst disablePattern = `-${pattern}`;\n\t\tconst enablePattern = `+${pattern}`;\n\n\t\t// Filter out existing patterns for this resource\n\t\tconst updated = current.filter((p) => {\n\t\t\tconst stripped = p.startsWith(\"!\") || p.startsWith(\"+\") || p.startsWith(\"-\") ? p.slice(1) : p;\n\t\t\treturn stripped !== pattern;\n\t\t});\n\n\t\tif (enabled) {\n\t\t\tupdated.push(enablePattern);\n\t\t} else {\n\t\t\tupdated.push(disablePattern);\n\t\t}\n\n\t\tif (scope === \"project\") {\n\t\t\tif (arrayKey === \"extensions\") {\n\t\t\t\tthis.settingsManager.setProjectExtensionPaths(updated);\n\t\t\t} else if (arrayKey === \"skills\") {\n\t\t\t\tthis.settingsManager.setProjectSkillPaths(updated);\n\t\t\t} else if (arrayKey === \"prompts\") {\n\t\t\t\tthis.settingsManager.setProjectPromptTemplatePaths(updated);\n\t\t\t} else if (arrayKey === \"themes\") {\n\t\t\t\tthis.settingsManager.setProjectThemePaths(updated);\n\t\t\t}\n\t\t} else {\n\t\t\tif (arrayKey === \"extensions\") {\n\t\t\t\tthis.settingsManager.setExtensionPaths(updated);\n\t\t\t} else if (arrayKey === \"skills\") {\n\t\t\t\tthis.settingsManager.setSkillPaths(updated);\n\t\t\t} else if (arrayKey === \"prompts\") {\n\t\t\t\tthis.settingsManager.setPromptTemplatePaths(updated);\n\t\t\t} else if (arrayKey === \"themes\") {\n\t\t\t\tthis.settingsManager.setThemePaths(updated);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate togglePackageResource(item: ResourceItem, enabled: boolean): void {\n\t\tconst scope = item.metadata.scope as \"user\" | \"project\";\n\t\tconst settings =\n\t\t\tscope === \"project\" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings();\n\n\t\tconst packages = [...(settings.packages ?? [])] as PackageSource[];\n\t\tconst pkgIndex = packages.findIndex((pkg) => {\n\t\t\tconst source = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\treturn source === item.metadata.source;\n\t\t});\n\n\t\tif (pkgIndex === -1) return;\n\n\t\tlet pkg = packages[pkgIndex];\n\n\t\t// Convert string to object form if needed\n\t\tif (typeof pkg === \"string\") {\n\t\t\tpkg = { source: pkg };\n\t\t\tpackages[pkgIndex] = pkg;\n\t\t}\n\n\t\t// Get the resource array for this type\n\t\tconst arrayKey = item.resourceType as \"extensions\" | \"skills\" | \"prompts\" | \"themes\";\n\t\tconst current = (pkg[arrayKey] ?? []) as string[];\n\n\t\t// Generate pattern relative to package root\n\t\tconst pattern = this.getPackageResourcePattern(item);\n\t\tconst disablePattern = `-${pattern}`;\n\t\tconst enablePattern = `+${pattern}`;\n\n\t\t// Filter out existing patterns for this resource\n\t\tconst updated = current.filter((p) => {\n\t\t\tconst stripped = p.startsWith(\"!\") || p.startsWith(\"+\") || p.startsWith(\"-\") ? p.slice(1) : p;\n\t\t\treturn stripped !== pattern;\n\t\t});\n\n\t\tif (enabled) {\n\t\t\tupdated.push(enablePattern);\n\t\t} else {\n\t\t\tupdated.push(disablePattern);\n\t\t}\n\n\t\t(pkg as Record)[arrayKey] = updated.length > 0 ? updated : undefined;\n\n\t\t// Clean up empty filter object\n\t\tconst hasFilters = [\"extensions\", \"skills\", \"prompts\", \"themes\"].some(\n\t\t\t(k) => (pkg as Record)[k] !== undefined,\n\t\t);\n\t\tif (!hasFilters) {\n\t\t\tpackages[pkgIndex] = (pkg as { source: string }).source;\n\t\t}\n\n\t\tif (scope === \"project\") {\n\t\t\tthis.settingsManager.setProjectPackages(packages);\n\t\t} else {\n\t\t\tthis.settingsManager.setPackages(packages);\n\t\t}\n\t}\n\n\tprivate renderCheckbox(item: ResourceItem): string {\n\t\tif (this.writeScope === \"project\") {\n\t\t\tconst state = this.getProjectOverrideState(item);\n\t\t\tif (state === \"load\") return theme.fg(\"success\", \"[+]\");\n\t\t\tif (state === \"unload\") return theme.fg(\"warning\", \"[-]\");\n\t\t\treturn theme.fg(\"dim\", item.enabled ? \"[x]\" : \"[ ]\");\n\t\t}\n\t\treturn item.enabled ? theme.fg(\"success\", \"[x]\") : theme.fg(\"dim\", \"[ ]\");\n\t}\n\n\tprivate getItemSuffix(item: ResourceItem): string {\n\t\tif (this.writeScope !== \"project\") return \"\";\n\t\tconst state = this.getProjectOverrideState(item);\n\t\tif (state === \"load\") return theme.fg(\"muted\", \" project load\");\n\t\tif (state === \"unload\") return theme.fg(\"muted\", \" project unload\");\n\t\treturn this.isInheritedGlobalItem(item) ? theme.fg(\"dim\", \" inherited global\") : \"\";\n\t}\n\n\tprivate isDimmedItem(item: ResourceItem): boolean {\n\t\treturn (\n\t\t\tthis.writeScope === \"project\" &&\n\t\t\tthis.isInheritedGlobalItem(item) &&\n\t\t\tthis.getProjectOverrideState(item) === \"inherit\"\n\t\t);\n\t}\n\n\tprivate setProjectResourceOverride(item: ResourceItem, state: ProjectOverrideState): boolean {\n\t\treturn item.metadata.origin === \"top-level\"\n\t\t\t? this.setProjectTopLevelOverride(item, state)\n\t\t\t: this.setProjectPackageOverride(item, state);\n\t}\n\n\tprivate setProjectTopLevelOverride(item: ResourceItem, state: ProjectOverrideState): boolean {\n\t\tconst current = (this.settingsManager.getProjectSettings()[item.resourceType] ?? []) as string[];\n\t\tconst pattern = this.isInheritedGlobalItem(item) ? item.path : this.getResourcePatternForScope(item, \"project\");\n\t\tconst patterns = this.getTopLevelOverridePatterns(item, \"project\");\n\t\tconst updated = current.filter((entry) => {\n\t\t\tconst target = this.getPatternEntryTarget(entry);\n\t\t\tif ((entry.startsWith(\"!\") || entry.startsWith(\"+\") || entry.startsWith(\"-\")) && patterns.has(target))\n\t\t\t\treturn false;\n\t\t\treturn !(state === \"inherit\" && this.isInheritedGlobalItem(item) && target === pattern);\n\t\t});\n\t\tif (state !== \"inherit\") {\n\t\t\tif (this.isInheritedGlobalItem(item) && !updated.includes(pattern)) updated.push(pattern);\n\t\t\tupdated.push(`${state === \"load\" ? \"+\" : \"-\"}${pattern}`);\n\t\t}\n\t\tthis.setProjectTopLevelPaths(item.resourceType, updated);\n\t\treturn true;\n\t}\n\n\tprivate setProjectTopLevelPaths(key: ResourceType, paths: string[]): void {\n\t\tif (key === \"extensions\") this.settingsManager.setProjectExtensionPaths(paths);\n\t\telse if (key === \"skills\") this.settingsManager.setProjectSkillPaths(paths);\n\t\telse if (key === \"prompts\") this.settingsManager.setProjectPromptTemplatePaths(paths);\n\t\telse this.settingsManager.setProjectThemePaths(paths);\n\t}\n\n\tprivate setProjectPackageOverride(item: ResourceItem, state: ProjectOverrideState): boolean {\n\t\tconst packages = [...(this.settingsManager.getProjectSettings().packages ?? [])] as PackageSource[];\n\t\tlet pkgIndex = packages.findIndex((pkg) =>\n\t\t\tthis.packageSourceStringMatches(\n\t\t\t\titem.metadata.source,\n\t\t\t\tthis.getItemScope(item),\n\t\t\t\ttypeof pkg === \"string\" ? pkg : pkg.source,\n\t\t\t\t\"project\",\n\t\t\t),\n\t\t);\n\t\tif (pkgIndex === -1) {\n\t\t\tif (state === \"inherit\") return false;\n\t\t\tpackages.push(this.createPackageOverrideSource(item));\n\t\t\tpkgIndex = packages.length - 1;\n\t\t}\n\t\tlet pkg = packages[pkgIndex];\n\t\tif (pkg === undefined) return false;\n\t\tif (typeof pkg === \"string\") {\n\t\t\tpkg = { source: pkg };\n\t\t\tpackages[pkgIndex] = pkg;\n\t\t}\n\t\tconst pattern = this.getPackageResourcePattern(item);\n\t\tconst updated = ((pkg[item.resourceType] ?? []) as string[]).filter(\n\t\t\t(entry) => this.getPatternEntryTarget(entry) !== pattern,\n\t\t);\n\t\tif (state !== \"inherit\") updated.push(`${state === \"load\" ? \"+\" : \"-\"}${pattern}`);\n\t\t(pkg as Record)[item.resourceType] = updated.length > 0 ? updated : undefined;\n\t\tif (!RESOURCE_TYPES.some((key) => (pkg as Record)[key] !== undefined)) {\n\t\t\tif (pkg.autoload === false) packages.splice(pkgIndex, 1);\n\t\t\telse packages[pkgIndex] = pkg.source;\n\t\t}\n\t\tthis.settingsManager.setProjectPackages(packages);\n\t\treturn true;\n\t}\n\n\tprivate getNextOverrideState(item: ResourceItem): ProjectOverrideState {\n\t\tconst state = this.getProjectOverrideState(item);\n\t\tconst inheritedEnabled = this.getInheritedEnabled(item);\n\t\tif (state === \"inherit\") return inheritedEnabled ? \"unload\" : \"load\";\n\t\tif (state === \"unload\") return inheritedEnabled ? \"load\" : \"inherit\";\n\t\treturn inheritedEnabled ? \"inherit\" : \"unload\";\n\t}\n\n\tprivate getProjectOverrideState(item: ResourceItem): ProjectOverrideState {\n\t\tif (this.writeScope !== \"project\") return \"inherit\";\n\t\tif (item.metadata.origin === \"top-level\") {\n\t\t\treturn this.getOverrideStateFromEntries(\n\t\t\t\t(this.settingsManager.getProjectSettings()[item.resourceType] ?? []) as string[],\n\t\t\t\tthis.getTopLevelOverridePatterns(item, \"project\"),\n\t\t\t\tfalse,\n\t\t\t);\n\t\t}\n\t\tconst pkg = this.findMatchingPackageSource(item, \"project\");\n\t\tif (typeof pkg !== \"object\") return \"inherit\";\n\t\tconst entries = pkg[item.resourceType];\n\t\tif (entries === undefined) return \"inherit\";\n\t\treturn this.getOverrideStateFromEntries(\n\t\t\tentries,\n\t\t\tnew Set([this.getPackageResourcePattern(item)]),\n\t\t\tpkg.autoload !== false,\n\t\t);\n\t}\n\n\tprivate getOverrideStateFromEntries(\n\t\tentries: string[],\n\t\tpatterns: Set,\n\t\temptyArrayIsUnload: boolean,\n\t): ProjectOverrideState {\n\t\tif (entries.length === 0 && emptyArrayIsUnload) return \"unload\";\n\t\tlet state: ProjectOverrideState = \"inherit\";\n\t\tfor (const entry of entries) {\n\t\t\tif (!patterns.has(this.getPatternEntryTarget(entry))) continue;\n\t\t\tif (entry.startsWith(\"!\") || entry.startsWith(\"-\")) state = \"unload\";\n\t\t\telse state = \"load\";\n\t\t}\n\t\treturn state;\n\t}\n\n\tprivate getInheritedEnabled(item: ResourceItem): boolean {\n\t\treturn (\n\t\t\tthis.inheritedEnabledByKey.get(this.getResourceItemKey(item)) ??\n\t\t\t(this.getItemScope(item) === \"user\" ? item.enabled : true)\n\t\t);\n\t}\n\n\tprivate isInheritedGlobalItem(item: ResourceItem): boolean {\n\t\treturn this.getItemScope(item) === \"user\" || this.inheritedEnabledByKey.has(this.getResourceItemKey(item));\n\t}\n\n\tprivate getTopLevelOverridePatterns(item: ResourceItem, scope: SettingsScope): Set {\n\t\tconst baseDir = this.getTopLevelBaseDir(scope);\n\t\tconst patterns = new Set([\n\t\t\tthis.getResourcePatternForScope(item, scope),\n\t\t\titem.path,\n\t\t\trelative(baseDir, item.path),\n\t\t]);\n\t\tif (item.metadata.baseDir) patterns.add(relative(item.metadata.baseDir, item.path));\n\t\treturn patterns;\n\t}\n\n\tprivate getResourcePatternForScope(item: ResourceItem, scope: SettingsScope): string {\n\t\tconst sourceScope = this.getItemScope(item);\n\t\tif (scope !== sourceScope) return item.path;\n\t\tconst baseDir = item.metadata.baseDir ?? this.getTopLevelBaseDir(sourceScope);\n\t\treturn relative(baseDir, item.path);\n\t}\n\n\tprivate createPackageOverrideSource(item: ResourceItem): PackageSource {\n\t\tconst source = item.metadata.source;\n\t\tif (!isLocalPath(source)) return { source, autoload: false };\n\t\tconst sourcePath = resolvePath(source, this.getTopLevelBaseDir(this.getItemScope(item)), { trim: true });\n\t\treturn { source: relative(this.getTopLevelBaseDir(\"project\"), sourcePath) || \".\", autoload: false };\n\t}\n\n\tprivate packageSourceStringMatches(\n\t\tleftSource: string,\n\t\tleftScope: SettingsScope,\n\t\trightSource: string,\n\t\trightScope: SettingsScope,\n\t): boolean {\n\t\tif (leftSource === rightSource) return true;\n\t\tif (!isLocalPath(leftSource) || !isLocalPath(rightSource)) return false;\n\t\tconst left = resolvePath(leftSource, this.getTopLevelBaseDir(leftScope), { trim: true });\n\t\tconst right = resolvePath(rightSource, this.getTopLevelBaseDir(rightScope), { trim: true });\n\t\treturn left === right;\n\t}\n\n\tprivate findMatchingPackageSource(item: ResourceItem, targetScope: SettingsScope): PackageSource | undefined {\n\t\tconst settings =\n\t\t\ttargetScope === \"project\"\n\t\t\t\t? this.settingsManager.getProjectSettings()\n\t\t\t\t: this.settingsManager.getGlobalSettings();\n\t\treturn (settings.packages ?? []).find((pkg) =>\n\t\t\tthis.packageSourceStringMatches(\n\t\t\t\titem.metadata.source,\n\t\t\t\tthis.getItemScope(item),\n\t\t\t\ttypeof pkg === \"string\" ? pkg : pkg.source,\n\t\t\t\ttargetScope,\n\t\t\t),\n\t\t);\n\t}\n\n\tprivate getPatternEntryTarget(entry: string): string {\n\t\treturn entry.startsWith(\"!\") || entry.startsWith(\"+\") || entry.startsWith(\"-\") ? entry.slice(1) : entry;\n\t}\n\n\tprivate getResourceItemKey(item: ResourceItem): string {\n\t\treturn `${item.resourceType}:${canonicalizePath(item.path)}`;\n\t}\n\n\tprivate getItemScope(item: ResourceItem): SettingsScope {\n\t\treturn item.metadata.scope === \"project\" ? \"project\" : \"user\";\n\t}\n\n\tprivate getTopLevelBaseDir(scope: \"user\" | \"project\"): string {\n\t\treturn scope === \"project\" ? join(this.cwd, CONFIG_DIR_NAME) : this.agentDir;\n\t}\n\n\tprivate getResourcePattern(item: ResourceItem): string {\n\t\tconst scope = item.metadata.scope as \"user\" | \"project\";\n\t\tconst baseDir = item.metadata.baseDir ?? this.getTopLevelBaseDir(scope);\n\t\treturn relative(baseDir, item.path);\n\t}\n\n\tprivate getPackageResourcePattern(item: ResourceItem): string {\n\t\tconst baseDir = item.metadata.baseDir ?? dirname(item.path);\n\t\treturn relative(baseDir, item.path);\n\t}\n}\n\nexport class ConfigSelectorComponent extends Container implements Focusable {\n\tprivate header: ConfigSelectorHeader;\n\tprivate resourceList: ResourceList;\n\tprivate writeScope: ConfigWriteScope;\n\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.resourceList.focused = value;\n\t}\n\n\tconstructor(\n\t\tresolvedPaths: ScopedResolvedPaths,\n\t\tsettingsManager: SettingsManager,\n\t\tcwd: string,\n\t\tagentDir: string,\n\t\tonClose: () => void,\n\t\tonExit: () => void,\n\t\trequestRender: () => void,\n\t\tterminalHeight?: number,\n\t\twriteScope: ConfigWriteScope = \"global\",\n\t\tprojectModeAvailable = true,\n\t) {\n\t\tsuper();\n\n\t\tthis.writeScope = writeScope;\n\t\tconst groupsByScope = {\n\t\t\tglobal: buildGroups(resolvedPaths.global, agentDir),\n\t\t\tproject: buildGroups(resolvedPaths.project, agentDir),\n\t\t};\n\n\t\t// Add header\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.header = new ConfigSelectorHeader(this.writeScope, projectModeAvailable);\n\t\tthis.addChild(this.header);\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Resource list\n\t\tthis.resourceList = new ResourceList(\n\t\t\tgroupsByScope,\n\t\t\tsettingsManager,\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tterminalHeight,\n\t\t\tthis.writeScope,\n\t\t);\n\t\tthis.resourceList.onCancel = onClose;\n\t\tthis.resourceList.onExit = onExit;\n\t\tthis.resourceList.onToggle = () => requestRender();\n\t\tif (projectModeAvailable) {\n\t\t\tthis.resourceList.onSwitchMode = () => {\n\t\t\t\tthis.switchWriteScope();\n\t\t\t\trequestRender();\n\t\t\t};\n\t\t}\n\t\tthis.addChild(this.resourceList);\n\n\t\t// Bottom border\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tprivate switchWriteScope(): void {\n\t\tthis.writeScope = this.writeScope === \"global\" ? \"project\" : \"global\";\n\t\tthis.header.setWriteScope(this.writeScope);\n\t\tthis.resourceList.setWriteScope(this.writeScope);\n\t}\n\n\tgetResourceList(): ResourceList {\n\t\treturn this.resourceList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/config-selector.js b/dist/modes/interactive/components/config-selector.js new file mode 100644 index 0000000..6f7ed6a --- /dev/null +++ b/dist/modes/interactive/components/config-selector.js @@ -0,0 +1,761 @@ +/** + * TUI component for managing package resources (enable/disable) + */ +import { homedir } from "node:os"; +import { basename, dirname, join, relative } from "node:path"; +import { Container, getKeybindings, Input, matchesKey, Spacer, truncateToWidth, visibleWidth, } from "@earendil-works/pi-tui"; +import { CONFIG_DIR_NAME } from "../../../config.js"; +import { canonicalizePath, isLocalPath, resolvePath } from "../../../utils/paths.js"; +import { theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyHint, rawKeyHint } from "./keybinding-hints.js"; +const RESOURCE_TYPES = ["extensions", "skills", "prompts", "themes"]; +const RESOURCE_TYPE_LABELS = { + extensions: "Extensions", + skills: "Skills", + prompts: "Prompts", + themes: "Themes", +}; +function formatBaseDir(baseDir) { + const homeDir = homedir(); + let displayPath; + if (baseDir === homeDir) { + displayPath = "~"; + } + else if (baseDir.startsWith(homeDir)) { + // Replace home prefix with ~, normalize separators for display + const rest = baseDir.slice(homeDir.length); + displayPath = `~${rest.replace(/\\/g, "/")}`; + } + else { + displayPath = baseDir.replace(/\\/g, "/"); + } + return displayPath.endsWith("/") ? displayPath : `${displayPath}/`; +} +function getGroupLabel(metadata, agentDir) { + if (metadata.origin === "package") { + return `${metadata.source} (${metadata.scope})`; + } + // Top-level resources + if (metadata.source === "auto") { + if (metadata.baseDir) { + return metadata.scope === "user" + ? `User (${formatBaseDir(metadata.baseDir)})` + : `Project (${formatBaseDir(metadata.baseDir)})`; + } + return metadata.scope === "user" ? `User (${formatBaseDir(agentDir)})` : `Project (${CONFIG_DIR_NAME}/)`; + } + return metadata.scope === "user" ? "User settings" : "Project settings"; +} +function buildGroups(resolved, agentDir) { + const groupMap = new Map(); + const addToGroup = (resources, resourceType) => { + for (const res of resources) { + const { path, enabled, metadata } = res; + const groupKey = `${metadata.origin}:${metadata.scope}:${metadata.source}:${metadata.baseDir ?? ""}`; + if (!groupMap.has(groupKey)) { + groupMap.set(groupKey, { + key: groupKey, + label: getGroupLabel(metadata, agentDir), + scope: metadata.scope, + origin: metadata.origin, + source: metadata.source, + subgroups: [], + }); + } + const group = groupMap.get(groupKey); + const subgroupKey = `${groupKey}:${resourceType}`; + let subgroup = group.subgroups.find((sg) => sg.type === resourceType); + if (!subgroup) { + subgroup = { + type: resourceType, + label: RESOURCE_TYPE_LABELS[resourceType], + items: [], + }; + group.subgroups.push(subgroup); + } + const fileName = basename(path); + const parentFolder = basename(dirname(path)); + let displayName; + if (resourceType === "extensions" && parentFolder !== "extensions") { + displayName = `${parentFolder}/${fileName}`; + } + else if (resourceType === "skills" && fileName === "SKILL.md") { + displayName = parentFolder; + } + else { + displayName = fileName; + } + subgroup.items.push({ + path, + enabled, + metadata, + resourceType, + displayName, + groupKey, + subgroupKey, + }); + } + }; + addToGroup(resolved.extensions, "extensions"); + addToGroup(resolved.skills, "skills"); + addToGroup(resolved.prompts, "prompts"); + addToGroup(resolved.themes, "themes"); + // Sort groups: packages first, then top-level; user before project + const groups = Array.from(groupMap.values()); + groups.sort((a, b) => { + if (a.origin !== b.origin) { + return a.origin === "package" ? -1 : 1; + } + if (a.scope !== b.scope) { + return a.scope === "user" ? -1 : 1; + } + return a.source.localeCompare(b.source); + }); + // Sort subgroups within each group by type order, and items by name + const typeOrder = { extensions: 0, skills: 1, prompts: 2, themes: 3 }; + for (const group of groups) { + group.subgroups.sort((a, b) => typeOrder[a.type] - typeOrder[b.type]); + for (const subgroup of group.subgroups) { + subgroup.items.sort((a, b) => a.displayName.localeCompare(b.displayName)); + } + } + return groups; +} +class ConfigSelectorHeader { + writeScope; + projectModeAvailable; + constructor(writeScope, projectModeAvailable) { + this.writeScope = writeScope; + this.projectModeAvailable = projectModeAvailable; + } + setWriteScope(writeScope) { + this.writeScope = writeScope; + } + invalidate() { } + render(width) { + const title = theme.bold(this.writeScope === "project" ? "Project Local Resources" : "Global Resources"); + const sep = theme.fg("muted", " · "); + const switchHint = this.projectModeAvailable ? keyHint("tui.input.tab", "switch mode") + sep : ""; + const actionHint = this.writeScope === "project" ? rawKeyHint("space", "cycle inherit/+/-") : rawKeyHint("space", "toggle"); + const hint = switchHint + actionHint + sep + rawKeyHint("esc", "close"); + const spacing = Math.max(1, width - visibleWidth(title) - visibleWidth(hint)); + const scopeHint = this.writeScope === "project" + ? theme.fg("muted", `${CONFIG_DIR_NAME}/settings.json · inherited global resources are dimmed`) + : theme.fg("muted", `~/${CONFIG_DIR_NAME}/agent/settings.json`); + return [ + truncateToWidth(`${title}${" ".repeat(spacing)}${hint}`, width, ""), + truncateToWidth(scopeHint, width, ""), + ]; + } +} +class ResourceList { + groupsByScope; + flatItems = []; + filteredItems = []; + selectedIndex = 0; + searchInput; + maxVisible; + settingsManager; + cwd; + agentDir; + writeScope; + inheritedEnabledByKey; + onCancel; + onExit; + onToggle; + onSwitchMode; + _focused = false; + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + this.searchInput.focused = value; + } + constructor(groupsByScope, settingsManager, cwd, agentDir, terminalHeight, writeScope = "global") { + this.groupsByScope = groupsByScope; + this.settingsManager = settingsManager; + this.cwd = cwd; + this.agentDir = agentDir; + this.writeScope = writeScope; + this.inheritedEnabledByKey = this.buildInheritedEnabledMap(groupsByScope.global); + this.searchInput = new Input(); + // 8 lines of chrome: top spacer + top border + spacer + header (2 lines) + spacer + bottom spacer + bottom border + const chrome = 8; + this.maxVisible = Math.max(5, (terminalHeight ?? 24) - chrome); + this.buildFlatList(); + this.filteredItems = [...this.flatItems]; + } + setWriteScope(writeScope) { + this.writeScope = writeScope; + this.buildFlatList(); + this.filterItems(this.searchInput.getValue()); + } + get groups() { + return this.groupsByScope[this.writeScope]; + } + buildInheritedEnabledMap(groups) { + const result = new Map(); + for (const group of groups) { + for (const subgroup of group.subgroups) { + for (const item of subgroup.items) { + result.set(this.getResourceItemKey(item), item.enabled); + } + } + } + return result; + } + buildFlatList() { + this.flatItems = []; + for (const group of this.groups) { + this.flatItems.push({ type: "group", group }); + for (const subgroup of group.subgroups) { + this.flatItems.push({ type: "subgroup", subgroup, group }); + for (const item of subgroup.items) { + this.flatItems.push({ type: "item", item }); + } + } + } + // Start selection on first item (not header) + this.selectedIndex = this.flatItems.findIndex((e) => e.type === "item"); + if (this.selectedIndex < 0) + this.selectedIndex = 0; + } + findNextItem(fromIndex, direction) { + let idx = fromIndex + direction; + while (idx >= 0 && idx < this.filteredItems.length) { + if (this.filteredItems[idx].type === "item") { + return idx; + } + idx += direction; + } + return fromIndex; // Stay at current if no item found + } + filterItems(query) { + if (!query.trim()) { + this.filteredItems = [...this.flatItems]; + this.selectFirstItem(); + return; + } + const lowerQuery = query.toLowerCase(); + const matchingItems = new Set(); + const matchingSubgroups = new Set(); + const matchingGroups = new Set(); + for (const entry of this.flatItems) { + if (entry.type === "item") { + const item = entry.item; + if (item.displayName.toLowerCase().includes(lowerQuery) || + item.resourceType.toLowerCase().includes(lowerQuery) || + item.path.toLowerCase().includes(lowerQuery)) { + matchingItems.add(item); + } + } + } + // Find which subgroups and groups contain matching items + for (const group of this.groups) { + for (const subgroup of group.subgroups) { + for (const item of subgroup.items) { + if (matchingItems.has(item)) { + matchingSubgroups.add(subgroup); + matchingGroups.add(group); + } + } + } + } + this.filteredItems = []; + for (const entry of this.flatItems) { + if (entry.type === "group" && matchingGroups.has(entry.group)) { + this.filteredItems.push(entry); + } + else if (entry.type === "subgroup" && matchingSubgroups.has(entry.subgroup)) { + this.filteredItems.push(entry); + } + else if (entry.type === "item" && matchingItems.has(entry.item)) { + this.filteredItems.push(entry); + } + } + this.selectFirstItem(); + } + selectFirstItem() { + const firstItemIndex = this.filteredItems.findIndex((e) => e.type === "item"); + this.selectedIndex = firstItemIndex >= 0 ? firstItemIndex : 0; + } + updateItem(item, enabled) { + item.enabled = enabled; + // Update in groups too + for (const group of this.groups) { + for (const subgroup of group.subgroups) { + const found = subgroup.items.find((i) => i.path === item.path && i.resourceType === item.resourceType); + if (found) { + found.enabled = enabled; + return; + } + } + } + } + invalidate() { } + render(width) { + const lines = []; + // Search input + lines.push(...this.searchInput.render(width)); + lines.push(""); + if (this.filteredItems.length === 0) { + lines.push(theme.fg("muted", " No resources found")); + return lines; + } + // Calculate visible range + const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredItems.length - this.maxVisible)); + const endIndex = Math.min(startIndex + this.maxVisible, this.filteredItems.length); + for (let i = startIndex; i < endIndex; i++) { + const entry = this.filteredItems[i]; + const isSelected = i === this.selectedIndex; + if (entry.type === "group") { + // Main group header (no cursor) + const inherited = this.writeScope === "project" && entry.group.scope === "user"; + const label = theme.bold(`${entry.group.label}${inherited ? " · inherited global" : ""}`); + const groupLine = theme.fg(inherited ? "dim" : "accent", label); + lines.push(truncateToWidth(` ${groupLine}`, width, "")); + } + else if (entry.type === "subgroup") { + // Subgroup header (indented, no cursor) + const color = this.writeScope === "project" && entry.group.scope === "user" ? "dim" : "muted"; + const subgroupLine = theme.fg(color, entry.subgroup.label); + lines.push(truncateToWidth(` ${subgroupLine}`, width, "")); + } + else { + // Resource item (cursor only on items) + const item = entry.item; + const cursor = isSelected ? "> " : " "; + const dimmed = this.isDimmedItem(item); + const nameText = isSelected && !dimmed ? theme.bold(item.displayName) : item.displayName; + const name = dimmed ? theme.fg("dim", nameText) : nameText; + lines.push(truncateToWidth(`${cursor} ${this.renderCheckbox(item)} ${name}${this.getItemSuffix(item)}`, width, "...")); + } + } + // Scroll indicator + if (startIndex > 0 || endIndex < this.filteredItems.length) { + const itemCount = this.filteredItems.filter((e) => e.type === "item").length; + const currentItemIndex = this.filteredItems.slice(0, this.selectedIndex).filter((e) => e.type === "item").length + 1; + lines.push(theme.fg("dim", ` (${currentItemIndex}/${itemCount})`)); + } + return lines; + } + handleInput(data) { + const kb = getKeybindings(); + if (kb.matches(data, "tui.select.up")) { + this.selectedIndex = this.findNextItem(this.selectedIndex, -1); + return; + } + if (kb.matches(data, "tui.select.down")) { + this.selectedIndex = this.findNextItem(this.selectedIndex, 1); + return; + } + if (kb.matches(data, "tui.select.pageUp")) { + // Jump up by maxVisible, then find nearest item + let target = Math.max(0, this.selectedIndex - this.maxVisible); + while (target < this.filteredItems.length && this.filteredItems[target].type !== "item") { + target++; + } + if (target < this.filteredItems.length) { + this.selectedIndex = target; + } + return; + } + if (kb.matches(data, "tui.select.pageDown")) { + // Jump down by maxVisible, then find nearest item + let target = Math.min(this.filteredItems.length - 1, this.selectedIndex + this.maxVisible); + while (target >= 0 && this.filteredItems[target].type !== "item") { + target--; + } + if (target >= 0) { + this.selectedIndex = target; + } + return; + } + if (kb.matches(data, "tui.select.cancel")) { + this.onCancel?.(); + return; + } + if (matchesKey(data, "ctrl+c")) { + this.onExit?.(); + return; + } + if (kb.matches(data, "tui.input.tab")) { + this.onSwitchMode?.(); + return; + } + if (data === " " || kb.matches(data, "tui.select.confirm")) { + const entry = this.filteredItems[this.selectedIndex]; + if (entry?.type === "item" && (this.writeScope === "project" || this.getItemScope(entry.item) === "user")) { + const newEnabled = this.toggleResource(entry.item); + if (newEnabled !== undefined) { + this.updateItem(entry.item, newEnabled); + this.onToggle?.(entry.item, newEnabled); + } + } + return; + } + // Pass to search input + this.searchInput.handleInput(data); + this.filterItems(this.searchInput.getValue()); + } + toggleResource(item) { + if (this.writeScope === "project") { + const state = this.getNextOverrideState(item); + if (!this.setProjectResourceOverride(item, state)) + return undefined; + return state === "inherit" ? this.getInheritedEnabled(item) : state === "load"; + } + const enabled = !item.enabled; + if (item.metadata.origin === "top-level") { + this.toggleTopLevelResource(item, enabled); + } + else { + this.togglePackageResource(item, enabled); + } + return enabled; + } + toggleTopLevelResource(item, enabled) { + const scope = item.metadata.scope; + const settings = scope === "project" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings(); + const arrayKey = item.resourceType; + const current = (settings[arrayKey] ?? []); + // Generate pattern for this resource + const pattern = this.getResourcePattern(item); + const disablePattern = `-${pattern}`; + const enablePattern = `+${pattern}`; + // Filter out existing patterns for this resource + const updated = current.filter((p) => { + const stripped = p.startsWith("!") || p.startsWith("+") || p.startsWith("-") ? p.slice(1) : p; + return stripped !== pattern; + }); + if (enabled) { + updated.push(enablePattern); + } + else { + updated.push(disablePattern); + } + if (scope === "project") { + if (arrayKey === "extensions") { + this.settingsManager.setProjectExtensionPaths(updated); + } + else if (arrayKey === "skills") { + this.settingsManager.setProjectSkillPaths(updated); + } + else if (arrayKey === "prompts") { + this.settingsManager.setProjectPromptTemplatePaths(updated); + } + else if (arrayKey === "themes") { + this.settingsManager.setProjectThemePaths(updated); + } + } + else { + if (arrayKey === "extensions") { + this.settingsManager.setExtensionPaths(updated); + } + else if (arrayKey === "skills") { + this.settingsManager.setSkillPaths(updated); + } + else if (arrayKey === "prompts") { + this.settingsManager.setPromptTemplatePaths(updated); + } + else if (arrayKey === "themes") { + this.settingsManager.setThemePaths(updated); + } + } + } + togglePackageResource(item, enabled) { + const scope = item.metadata.scope; + const settings = scope === "project" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings(); + const packages = [...(settings.packages ?? [])]; + const pkgIndex = packages.findIndex((pkg) => { + const source = typeof pkg === "string" ? pkg : pkg.source; + return source === item.metadata.source; + }); + if (pkgIndex === -1) + return; + let pkg = packages[pkgIndex]; + // Convert string to object form if needed + if (typeof pkg === "string") { + pkg = { source: pkg }; + packages[pkgIndex] = pkg; + } + // Get the resource array for this type + const arrayKey = item.resourceType; + const current = (pkg[arrayKey] ?? []); + // Generate pattern relative to package root + const pattern = this.getPackageResourcePattern(item); + const disablePattern = `-${pattern}`; + const enablePattern = `+${pattern}`; + // Filter out existing patterns for this resource + const updated = current.filter((p) => { + const stripped = p.startsWith("!") || p.startsWith("+") || p.startsWith("-") ? p.slice(1) : p; + return stripped !== pattern; + }); + if (enabled) { + updated.push(enablePattern); + } + else { + updated.push(disablePattern); + } + pkg[arrayKey] = updated.length > 0 ? updated : undefined; + // Clean up empty filter object + const hasFilters = ["extensions", "skills", "prompts", "themes"].some((k) => pkg[k] !== undefined); + if (!hasFilters) { + packages[pkgIndex] = pkg.source; + } + if (scope === "project") { + this.settingsManager.setProjectPackages(packages); + } + else { + this.settingsManager.setPackages(packages); + } + } + renderCheckbox(item) { + if (this.writeScope === "project") { + const state = this.getProjectOverrideState(item); + if (state === "load") + return theme.fg("success", "[+]"); + if (state === "unload") + return theme.fg("warning", "[-]"); + return theme.fg("dim", item.enabled ? "[x]" : "[ ]"); + } + return item.enabled ? theme.fg("success", "[x]") : theme.fg("dim", "[ ]"); + } + getItemSuffix(item) { + if (this.writeScope !== "project") + return ""; + const state = this.getProjectOverrideState(item); + if (state === "load") + return theme.fg("muted", " project load"); + if (state === "unload") + return theme.fg("muted", " project unload"); + return this.isInheritedGlobalItem(item) ? theme.fg("dim", " inherited global") : ""; + } + isDimmedItem(item) { + return (this.writeScope === "project" && + this.isInheritedGlobalItem(item) && + this.getProjectOverrideState(item) === "inherit"); + } + setProjectResourceOverride(item, state) { + return item.metadata.origin === "top-level" + ? this.setProjectTopLevelOverride(item, state) + : this.setProjectPackageOverride(item, state); + } + setProjectTopLevelOverride(item, state) { + const current = (this.settingsManager.getProjectSettings()[item.resourceType] ?? []); + const pattern = this.isInheritedGlobalItem(item) ? item.path : this.getResourcePatternForScope(item, "project"); + const patterns = this.getTopLevelOverridePatterns(item, "project"); + const updated = current.filter((entry) => { + const target = this.getPatternEntryTarget(entry); + if ((entry.startsWith("!") || entry.startsWith("+") || entry.startsWith("-")) && patterns.has(target)) + return false; + return !(state === "inherit" && this.isInheritedGlobalItem(item) && target === pattern); + }); + if (state !== "inherit") { + if (this.isInheritedGlobalItem(item) && !updated.includes(pattern)) + updated.push(pattern); + updated.push(`${state === "load" ? "+" : "-"}${pattern}`); + } + this.setProjectTopLevelPaths(item.resourceType, updated); + return true; + } + setProjectTopLevelPaths(key, paths) { + if (key === "extensions") + this.settingsManager.setProjectExtensionPaths(paths); + else if (key === "skills") + this.settingsManager.setProjectSkillPaths(paths); + else if (key === "prompts") + this.settingsManager.setProjectPromptTemplatePaths(paths); + else + this.settingsManager.setProjectThemePaths(paths); + } + setProjectPackageOverride(item, state) { + const packages = [...(this.settingsManager.getProjectSettings().packages ?? [])]; + let pkgIndex = packages.findIndex((pkg) => this.packageSourceStringMatches(item.metadata.source, this.getItemScope(item), typeof pkg === "string" ? pkg : pkg.source, "project")); + if (pkgIndex === -1) { + if (state === "inherit") + return false; + packages.push(this.createPackageOverrideSource(item)); + pkgIndex = packages.length - 1; + } + let pkg = packages[pkgIndex]; + if (pkg === undefined) + return false; + if (typeof pkg === "string") { + pkg = { source: pkg }; + packages[pkgIndex] = pkg; + } + const pattern = this.getPackageResourcePattern(item); + const updated = (pkg[item.resourceType] ?? []).filter((entry) => this.getPatternEntryTarget(entry) !== pattern); + if (state !== "inherit") + updated.push(`${state === "load" ? "+" : "-"}${pattern}`); + pkg[item.resourceType] = updated.length > 0 ? updated : undefined; + if (!RESOURCE_TYPES.some((key) => pkg[key] !== undefined)) { + if (pkg.autoload === false) + packages.splice(pkgIndex, 1); + else + packages[pkgIndex] = pkg.source; + } + this.settingsManager.setProjectPackages(packages); + return true; + } + getNextOverrideState(item) { + const state = this.getProjectOverrideState(item); + const inheritedEnabled = this.getInheritedEnabled(item); + if (state === "inherit") + return inheritedEnabled ? "unload" : "load"; + if (state === "unload") + return inheritedEnabled ? "load" : "inherit"; + return inheritedEnabled ? "inherit" : "unload"; + } + getProjectOverrideState(item) { + if (this.writeScope !== "project") + return "inherit"; + if (item.metadata.origin === "top-level") { + return this.getOverrideStateFromEntries((this.settingsManager.getProjectSettings()[item.resourceType] ?? []), this.getTopLevelOverridePatterns(item, "project"), false); + } + const pkg = this.findMatchingPackageSource(item, "project"); + if (typeof pkg !== "object") + return "inherit"; + const entries = pkg[item.resourceType]; + if (entries === undefined) + return "inherit"; + return this.getOverrideStateFromEntries(entries, new Set([this.getPackageResourcePattern(item)]), pkg.autoload !== false); + } + getOverrideStateFromEntries(entries, patterns, emptyArrayIsUnload) { + if (entries.length === 0 && emptyArrayIsUnload) + return "unload"; + let state = "inherit"; + for (const entry of entries) { + if (!patterns.has(this.getPatternEntryTarget(entry))) + continue; + if (entry.startsWith("!") || entry.startsWith("-")) + state = "unload"; + else + state = "load"; + } + return state; + } + getInheritedEnabled(item) { + return (this.inheritedEnabledByKey.get(this.getResourceItemKey(item)) ?? + (this.getItemScope(item) === "user" ? item.enabled : true)); + } + isInheritedGlobalItem(item) { + return this.getItemScope(item) === "user" || this.inheritedEnabledByKey.has(this.getResourceItemKey(item)); + } + getTopLevelOverridePatterns(item, scope) { + const baseDir = this.getTopLevelBaseDir(scope); + const patterns = new Set([ + this.getResourcePatternForScope(item, scope), + item.path, + relative(baseDir, item.path), + ]); + if (item.metadata.baseDir) + patterns.add(relative(item.metadata.baseDir, item.path)); + return patterns; + } + getResourcePatternForScope(item, scope) { + const sourceScope = this.getItemScope(item); + if (scope !== sourceScope) + return item.path; + const baseDir = item.metadata.baseDir ?? this.getTopLevelBaseDir(sourceScope); + return relative(baseDir, item.path); + } + createPackageOverrideSource(item) { + const source = item.metadata.source; + if (!isLocalPath(source)) + return { source, autoload: false }; + const sourcePath = resolvePath(source, this.getTopLevelBaseDir(this.getItemScope(item)), { trim: true }); + return { source: relative(this.getTopLevelBaseDir("project"), sourcePath) || ".", autoload: false }; + } + packageSourceStringMatches(leftSource, leftScope, rightSource, rightScope) { + if (leftSource === rightSource) + return true; + if (!isLocalPath(leftSource) || !isLocalPath(rightSource)) + return false; + const left = resolvePath(leftSource, this.getTopLevelBaseDir(leftScope), { trim: true }); + const right = resolvePath(rightSource, this.getTopLevelBaseDir(rightScope), { trim: true }); + return left === right; + } + findMatchingPackageSource(item, targetScope) { + const settings = targetScope === "project" + ? this.settingsManager.getProjectSettings() + : this.settingsManager.getGlobalSettings(); + return (settings.packages ?? []).find((pkg) => this.packageSourceStringMatches(item.metadata.source, this.getItemScope(item), typeof pkg === "string" ? pkg : pkg.source, targetScope)); + } + getPatternEntryTarget(entry) { + return entry.startsWith("!") || entry.startsWith("+") || entry.startsWith("-") ? entry.slice(1) : entry; + } + getResourceItemKey(item) { + return `${item.resourceType}:${canonicalizePath(item.path)}`; + } + getItemScope(item) { + return item.metadata.scope === "project" ? "project" : "user"; + } + getTopLevelBaseDir(scope) { + return scope === "project" ? join(this.cwd, CONFIG_DIR_NAME) : this.agentDir; + } + getResourcePattern(item) { + const scope = item.metadata.scope; + const baseDir = item.metadata.baseDir ?? this.getTopLevelBaseDir(scope); + return relative(baseDir, item.path); + } + getPackageResourcePattern(item) { + const baseDir = item.metadata.baseDir ?? dirname(item.path); + return relative(baseDir, item.path); + } +} +export class ConfigSelectorComponent extends Container { + header; + resourceList; + writeScope; + _focused = false; + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + this.resourceList.focused = value; + } + constructor(resolvedPaths, settingsManager, cwd, agentDir, onClose, onExit, requestRender, terminalHeight, writeScope = "global", projectModeAvailable = true) { + super(); + this.writeScope = writeScope; + const groupsByScope = { + global: buildGroups(resolvedPaths.global, agentDir), + project: buildGroups(resolvedPaths.project, agentDir), + }; + // Add header + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder()); + this.addChild(new Spacer(1)); + this.header = new ConfigSelectorHeader(this.writeScope, projectModeAvailable); + this.addChild(this.header); + this.addChild(new Spacer(1)); + // Resource list + this.resourceList = new ResourceList(groupsByScope, settingsManager, cwd, agentDir, terminalHeight, this.writeScope); + this.resourceList.onCancel = onClose; + this.resourceList.onExit = onExit; + this.resourceList.onToggle = () => requestRender(); + if (projectModeAvailable) { + this.resourceList.onSwitchMode = () => { + this.switchWriteScope(); + requestRender(); + }; + } + this.addChild(this.resourceList); + // Bottom border + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder()); + } + switchWriteScope() { + this.writeScope = this.writeScope === "global" ? "project" : "global"; + this.header.setWriteScope(this.writeScope); + this.resourceList.setWriteScope(this.writeScope); + } + getResourceList() { + return this.resourceList; + } +} +//# sourceMappingURL=config-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/config-selector.js.map b/dist/modes/interactive/components/config-selector.js.map new file mode 100644 index 0000000..96ee821 --- /dev/null +++ b/dist/modes/interactive/components/config-selector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/config-selector.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAC9D,OAAO,EAEN,SAAS,EAET,cAAc,EACd,KAAK,EACL,UAAU,EACV,MAAM,EACN,eAAe,EACf,YAAY,GACZ,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAGrD,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACrF,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAQ5D,MAAM,cAAc,GAAG,CAAC,YAAY,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAA4C,CAAC;AAEhH,MAAM,oBAAoB,GAAiC;IAC1D,UAAU,EAAE,YAAY;IACxB,MAAM,EAAE,QAAQ;IAChB,OAAO,EAAE,SAAS;IAClB,MAAM,EAAE,QAAQ;CAChB,CAAC;AA2BF,SAAS,aAAa,CAAC,OAAe,EAAU;IAC/C,MAAM,O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AG,EACH,QAAQ,EACR,cAAc,EACd,IAAI,CAAC,UAAU,CACf,CAAC;QACF,IAAI,CAAC,YAAY,CAAC,QAAQ,GAAG,OAAO,CAAC;QACrC,IAAI,CAAC,YAAY,CAAC,MAAM,GAAG,MAAM,CAAC;QAClC,IAAI,CAAC,YAAY,CAAC,QAAQ,GAAG,GAAG,EAAE,CAAC,aAAa,EAAE,CAAC;QACnD,IAAI,oBAAoB,EAAE,CAAC;YAC1B,IAAI,CAAC,YAAY,CAAC,YAAY,GAAG,GAAG,EAAE,CAAC;gBACtC,IAAI,CAAC,gBAAgB,EAAE,CAAC;gBACxB,aAAa,EAAE,CAAC;YAAA,CAChB,CAAC;QACH,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QAEjC,gBAAgB;QAChB,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;IAAA,CACnC;IAEO,gBAAgB,GAAS;QAChC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC;QACtE,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,CAAC,YAAY,CAAC,aAAa,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAAA,CACjD;IAED,eAAe,GAAiB;QAC/B,OAAO,IAAI,CAAC,YAAY,CAAC;IAAA,CACzB;CACD","sourcesContent":["/**\n * TUI component for managing package resources (enable/disable)\n */\n\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, relative } from \"node:path\";\nimport {\n\ttype Component,\n\tContainer,\n\ttype Focusable,\n\tgetKeybindings,\n\tInput,\n\tmatchesKey,\n\tSpacer,\n\ttruncateToWidth,\n\tvisibleWidth,\n} from \"@earendil-works/pi-tui\";\nimport { CONFIG_DIR_NAME } from \"../../../config.ts\";\nimport type { PathMetadata, ResolvedPaths, ResolvedResource } from \"../../../core/package-manager.ts\";\nimport type { PackageSource, SettingsManager } from \"../../../core/settings-manager.ts\";\nimport { canonicalizePath, isLocalPath, resolvePath } from \"../../../utils/paths.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint, rawKeyHint } from \"./keybinding-hints.ts\";\n\ntype ResourceType = \"extensions\" | \"skills\" | \"prompts\" | \"themes\";\ntype ConfigWriteScope = \"global\" | \"project\";\ntype SettingsScope = \"user\" | \"project\";\ntype ProjectOverrideState = \"inherit\" | \"load\" | \"unload\";\nexport type ScopedResolvedPaths = Record;\n\nconst RESOURCE_TYPES = [\"extensions\", \"skills\", \"prompts\", \"themes\"] as const satisfies readonly ResourceType[];\n\nconst RESOURCE_TYPE_LABELS: Record = {\n\textensions: \"Extensions\",\n\tskills: \"Skills\",\n\tprompts: \"Prompts\",\n\tthemes: \"Themes\",\n};\n\ninterface ResourceItem {\n\tpath: string;\n\tenabled: boolean;\n\tmetadata: PathMetadata;\n\tresourceType: ResourceType;\n\tdisplayName: string;\n\tgroupKey: string;\n\tsubgroupKey: string;\n}\n\ninterface ResourceSubgroup {\n\ttype: ResourceType;\n\tlabel: string;\n\titems: ResourceItem[];\n}\n\ninterface ResourceGroup {\n\tkey: string;\n\tlabel: string;\n\tscope: \"user\" | \"project\" | \"temporary\";\n\torigin: \"package\" | \"top-level\";\n\tsource: string;\n\tsubgroups: ResourceSubgroup[];\n}\n\nfunction formatBaseDir(baseDir: string): string {\n\tconst homeDir = homedir();\n\tlet displayPath: string;\n\n\tif (baseDir === homeDir) {\n\t\tdisplayPath = \"~\";\n\t} else if (baseDir.startsWith(homeDir)) {\n\t\t// Replace home prefix with ~, normalize separators for display\n\t\tconst rest = baseDir.slice(homeDir.length);\n\t\tdisplayPath = `~${rest.replace(/\\\\/g, \"/\")}`;\n\t} else {\n\t\tdisplayPath = baseDir.replace(/\\\\/g, \"/\");\n\t}\n\n\treturn displayPath.endsWith(\"/\") ? displayPath : `${displayPath}/`;\n}\n\nfunction getGroupLabel(metadata: PathMetadata, agentDir: string): string {\n\tif (metadata.origin === \"package\") {\n\t\treturn `${metadata.source} (${metadata.scope})`;\n\t}\n\t// Top-level resources\n\tif (metadata.source === \"auto\") {\n\t\tif (metadata.baseDir) {\n\t\t\treturn metadata.scope === \"user\"\n\t\t\t\t? `User (${formatBaseDir(metadata.baseDir)})`\n\t\t\t\t: `Project (${formatBaseDir(metadata.baseDir)})`;\n\t\t}\n\t\treturn metadata.scope === \"user\" ? `User (${formatBaseDir(agentDir)})` : `Project (${CONFIG_DIR_NAME}/)`;\n\t}\n\treturn metadata.scope === \"user\" ? \"User settings\" : \"Project settings\";\n}\n\nfunction buildGroups(resolved: ResolvedPaths, agentDir: string): ResourceGroup[] {\n\tconst groupMap = new Map();\n\n\tconst addToGroup = (resources: ResolvedResource[], resourceType: ResourceType) => {\n\t\tfor (const res of resources) {\n\t\t\tconst { path, enabled, metadata } = res;\n\t\t\tconst groupKey = `${metadata.origin}:${metadata.scope}:${metadata.source}:${metadata.baseDir ?? \"\"}`;\n\n\t\t\tif (!groupMap.has(groupKey)) {\n\t\t\t\tgroupMap.set(groupKey, {\n\t\t\t\t\tkey: groupKey,\n\t\t\t\t\tlabel: getGroupLabel(metadata, agentDir),\n\t\t\t\t\tscope: metadata.scope,\n\t\t\t\t\torigin: metadata.origin,\n\t\t\t\t\tsource: metadata.source,\n\t\t\t\t\tsubgroups: [],\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst group = groupMap.get(groupKey)!;\n\t\t\tconst subgroupKey = `${groupKey}:${resourceType}`;\n\n\t\t\tlet subgroup = group.subgroups.find((sg) => sg.type === resourceType);\n\t\t\tif (!subgroup) {\n\t\t\t\tsubgroup = {\n\t\t\t\t\ttype: resourceType,\n\t\t\t\t\tlabel: RESOURCE_TYPE_LABELS[resourceType],\n\t\t\t\t\titems: [],\n\t\t\t\t};\n\t\t\t\tgroup.subgroups.push(subgroup);\n\t\t\t}\n\n\t\t\tconst fileName = basename(path);\n\t\t\tconst parentFolder = basename(dirname(path));\n\t\t\tlet displayName: string;\n\t\t\tif (resourceType === \"extensions\" && parentFolder !== \"extensions\") {\n\t\t\t\tdisplayName = `${parentFolder}/${fileName}`;\n\t\t\t} else if (resourceType === \"skills\" && fileName === \"SKILL.md\") {\n\t\t\t\tdisplayName = parentFolder;\n\t\t\t} else {\n\t\t\t\tdisplayName = fileName;\n\t\t\t}\n\t\t\tsubgroup.items.push({\n\t\t\t\tpath,\n\t\t\t\tenabled,\n\t\t\t\tmetadata,\n\t\t\t\tresourceType,\n\t\t\t\tdisplayName,\n\t\t\t\tgroupKey,\n\t\t\t\tsubgroupKey,\n\t\t\t});\n\t\t}\n\t};\n\n\taddToGroup(resolved.extensions, \"extensions\");\n\taddToGroup(resolved.skills, \"skills\");\n\taddToGroup(resolved.prompts, \"prompts\");\n\taddToGroup(resolved.themes, \"themes\");\n\n\t// Sort groups: packages first, then top-level; user before project\n\tconst groups = Array.from(groupMap.values());\n\tgroups.sort((a, b) => {\n\t\tif (a.origin !== b.origin) {\n\t\t\treturn a.origin === \"package\" ? -1 : 1;\n\t\t}\n\t\tif (a.scope !== b.scope) {\n\t\t\treturn a.scope === \"user\" ? -1 : 1;\n\t\t}\n\t\treturn a.source.localeCompare(b.source);\n\t});\n\n\t// Sort subgroups within each group by type order, and items by name\n\tconst typeOrder: Record = { extensions: 0, skills: 1, prompts: 2, themes: 3 };\n\tfor (const group of groups) {\n\t\tgroup.subgroups.sort((a, b) => typeOrder[a.type] - typeOrder[b.type]);\n\t\tfor (const subgroup of group.subgroups) {\n\t\t\tsubgroup.items.sort((a, b) => a.displayName.localeCompare(b.displayName));\n\t\t}\n\t}\n\n\treturn groups;\n}\n\ntype FlatEntry =\n\t| { type: \"group\"; group: ResourceGroup }\n\t| { type: \"subgroup\"; subgroup: ResourceSubgroup; group: ResourceGroup }\n\t| { type: \"item\"; item: ResourceItem };\n\nclass ConfigSelectorHeader implements Component {\n\tprivate writeScope: ConfigWriteScope;\n\tprivate projectModeAvailable: boolean;\n\n\tconstructor(writeScope: ConfigWriteScope, projectModeAvailable: boolean) {\n\t\tthis.writeScope = writeScope;\n\t\tthis.projectModeAvailable = projectModeAvailable;\n\t}\n\n\tsetWriteScope(writeScope: ConfigWriteScope): void {\n\t\tthis.writeScope = writeScope;\n\t}\n\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst title = theme.bold(this.writeScope === \"project\" ? \"Project Local Resources\" : \"Global Resources\");\n\t\tconst sep = theme.fg(\"muted\", \" · \");\n\t\tconst switchHint = this.projectModeAvailable ? keyHint(\"tui.input.tab\", \"switch mode\") + sep : \"\";\n\t\tconst actionHint =\n\t\t\tthis.writeScope === \"project\" ? rawKeyHint(\"space\", \"cycle inherit/+/-\") : rawKeyHint(\"space\", \"toggle\");\n\t\tconst hint = switchHint + actionHint + sep + rawKeyHint(\"esc\", \"close\");\n\t\tconst spacing = Math.max(1, width - visibleWidth(title) - visibleWidth(hint));\n\t\tconst scopeHint =\n\t\t\tthis.writeScope === \"project\"\n\t\t\t\t? theme.fg(\"muted\", `${CONFIG_DIR_NAME}/settings.json · inherited global resources are dimmed`)\n\t\t\t\t: theme.fg(\"muted\", `~/${CONFIG_DIR_NAME}/agent/settings.json`);\n\n\t\treturn [\n\t\t\ttruncateToWidth(`${title}${\" \".repeat(spacing)}${hint}`, width, \"\"),\n\t\t\ttruncateToWidth(scopeHint, width, \"\"),\n\t\t];\n\t}\n}\n\nclass ResourceList implements Component, Focusable {\n\tprivate groupsByScope: Record;\n\tprivate flatItems: FlatEntry[] = [];\n\tprivate filteredItems: FlatEntry[] = [];\n\tprivate selectedIndex = 0;\n\tprivate searchInput: Input;\n\tprivate maxVisible: number;\n\tprivate settingsManager: SettingsManager;\n\tprivate cwd: string;\n\tprivate agentDir: string;\n\tprivate writeScope: ConfigWriteScope;\n\tprivate inheritedEnabledByKey: Map;\n\n\tpublic onCancel?: () => void;\n\tpublic onExit?: () => void;\n\tpublic onToggle?: (item: ResourceItem, newEnabled: boolean) => void;\n\tpublic onSwitchMode?: () => void;\n\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.searchInput.focused = value;\n\t}\n\n\tconstructor(\n\t\tgroupsByScope: Record,\n\t\tsettingsManager: SettingsManager,\n\t\tcwd: string,\n\t\tagentDir: string,\n\t\tterminalHeight?: number,\n\t\twriteScope: ConfigWriteScope = \"global\",\n\t) {\n\t\tthis.groupsByScope = groupsByScope;\n\t\tthis.settingsManager = settingsManager;\n\t\tthis.cwd = cwd;\n\t\tthis.agentDir = agentDir;\n\t\tthis.writeScope = writeScope;\n\t\tthis.inheritedEnabledByKey = this.buildInheritedEnabledMap(groupsByScope.global);\n\t\tthis.searchInput = new Input();\n\t\t// 8 lines of chrome: top spacer + top border + spacer + header (2 lines) + spacer + bottom spacer + bottom border\n\t\tconst chrome = 8;\n\t\tthis.maxVisible = Math.max(5, (terminalHeight ?? 24) - chrome);\n\t\tthis.buildFlatList();\n\t\tthis.filteredItems = [...this.flatItems];\n\t}\n\n\tsetWriteScope(writeScope: ConfigWriteScope): void {\n\t\tthis.writeScope = writeScope;\n\t\tthis.buildFlatList();\n\t\tthis.filterItems(this.searchInput.getValue());\n\t}\n\n\tprivate get groups(): ResourceGroup[] {\n\t\treturn this.groupsByScope[this.writeScope];\n\t}\n\n\tprivate buildInheritedEnabledMap(groups: ResourceGroup[]): Map {\n\t\tconst result = new Map();\n\t\tfor (const group of groups) {\n\t\t\tfor (const subgroup of group.subgroups) {\n\t\t\t\tfor (const item of subgroup.items) {\n\t\t\t\t\tresult.set(this.getResourceItemKey(item), item.enabled);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate buildFlatList(): void {\n\t\tthis.flatItems = [];\n\t\tfor (const group of this.groups) {\n\t\t\tthis.flatItems.push({ type: \"group\", group });\n\t\t\tfor (const subgroup of group.subgroups) {\n\t\t\t\tthis.flatItems.push({ type: \"subgroup\", subgroup, group });\n\t\t\t\tfor (const item of subgroup.items) {\n\t\t\t\t\tthis.flatItems.push({ type: \"item\", item });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Start selection on first item (not header)\n\t\tthis.selectedIndex = this.flatItems.findIndex((e) => e.type === \"item\");\n\t\tif (this.selectedIndex < 0) this.selectedIndex = 0;\n\t}\n\n\tprivate findNextItem(fromIndex: number, direction: 1 | -1): number {\n\t\tlet idx = fromIndex + direction;\n\t\twhile (idx >= 0 && idx < this.filteredItems.length) {\n\t\t\tif (this.filteredItems[idx].type === \"item\") {\n\t\t\t\treturn idx;\n\t\t\t}\n\t\t\tidx += direction;\n\t\t}\n\t\treturn fromIndex; // Stay at current if no item found\n\t}\n\n\tprivate filterItems(query: string): void {\n\t\tif (!query.trim()) {\n\t\t\tthis.filteredItems = [...this.flatItems];\n\t\t\tthis.selectFirstItem();\n\t\t\treturn;\n\t\t}\n\n\t\tconst lowerQuery = query.toLowerCase();\n\t\tconst matchingItems = new Set();\n\t\tconst matchingSubgroups = new Set();\n\t\tconst matchingGroups = new Set();\n\n\t\tfor (const entry of this.flatItems) {\n\t\t\tif (entry.type === \"item\") {\n\t\t\t\tconst item = entry.item;\n\t\t\t\tif (\n\t\t\t\t\titem.displayName.toLowerCase().includes(lowerQuery) ||\n\t\t\t\t\titem.resourceType.toLowerCase().includes(lowerQuery) ||\n\t\t\t\t\titem.path.toLowerCase().includes(lowerQuery)\n\t\t\t\t) {\n\t\t\t\t\tmatchingItems.add(item);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Find which subgroups and groups contain matching items\n\t\tfor (const group of this.groups) {\n\t\t\tfor (const subgroup of group.subgroups) {\n\t\t\t\tfor (const item of subgroup.items) {\n\t\t\t\t\tif (matchingItems.has(item)) {\n\t\t\t\t\t\tmatchingSubgroups.add(subgroup);\n\t\t\t\t\t\tmatchingGroups.add(group);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.filteredItems = [];\n\t\tfor (const entry of this.flatItems) {\n\t\t\tif (entry.type === \"group\" && matchingGroups.has(entry.group)) {\n\t\t\t\tthis.filteredItems.push(entry);\n\t\t\t} else if (entry.type === \"subgroup\" && matchingSubgroups.has(entry.subgroup)) {\n\t\t\t\tthis.filteredItems.push(entry);\n\t\t\t} else if (entry.type === \"item\" && matchingItems.has(entry.item)) {\n\t\t\t\tthis.filteredItems.push(entry);\n\t\t\t}\n\t\t}\n\n\t\tthis.selectFirstItem();\n\t}\n\n\tprivate selectFirstItem(): void {\n\t\tconst firstItemIndex = this.filteredItems.findIndex((e) => e.type === \"item\");\n\t\tthis.selectedIndex = firstItemIndex >= 0 ? firstItemIndex : 0;\n\t}\n\n\tupdateItem(item: ResourceItem, enabled: boolean): void {\n\t\titem.enabled = enabled;\n\t\t// Update in groups too\n\t\tfor (const group of this.groups) {\n\t\t\tfor (const subgroup of group.subgroups) {\n\t\t\t\tconst found = subgroup.items.find((i) => i.path === item.path && i.resourceType === item.resourceType);\n\t\t\t\tif (found) {\n\t\t\t\t\tfound.enabled = enabled;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\n\t\t// Search input\n\t\tlines.push(...this.searchInput.render(width));\n\t\tlines.push(\"\");\n\n\t\tif (this.filteredItems.length === 0) {\n\t\t\tlines.push(theme.fg(\"muted\", \" No resources found\"));\n\t\t\treturn lines;\n\t\t}\n\n\t\t// Calculate visible range\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredItems.length - this.maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisible, this.filteredItems.length);\n\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst entry = this.filteredItems[i];\n\t\t\tconst isSelected = i === this.selectedIndex;\n\n\t\t\tif (entry.type === \"group\") {\n\t\t\t\t// Main group header (no cursor)\n\t\t\t\tconst inherited = this.writeScope === \"project\" && entry.group.scope === \"user\";\n\t\t\t\tconst label = theme.bold(`${entry.group.label}${inherited ? \" · inherited global\" : \"\"}`);\n\t\t\t\tconst groupLine = theme.fg(inherited ? \"dim\" : \"accent\", label);\n\t\t\t\tlines.push(truncateToWidth(` ${groupLine}`, width, \"\"));\n\t\t\t} else if (entry.type === \"subgroup\") {\n\t\t\t\t// Subgroup header (indented, no cursor)\n\t\t\t\tconst color = this.writeScope === \"project\" && entry.group.scope === \"user\" ? \"dim\" : \"muted\";\n\t\t\t\tconst subgroupLine = theme.fg(color, entry.subgroup.label);\n\t\t\t\tlines.push(truncateToWidth(` ${subgroupLine}`, width, \"\"));\n\t\t\t} else {\n\t\t\t\t// Resource item (cursor only on items)\n\t\t\t\tconst item = entry.item;\n\t\t\t\tconst cursor = isSelected ? \"> \" : \" \";\n\t\t\t\tconst dimmed = this.isDimmedItem(item);\n\t\t\t\tconst nameText = isSelected && !dimmed ? theme.bold(item.displayName) : item.displayName;\n\t\t\t\tconst name = dimmed ? theme.fg(\"dim\", nameText) : nameText;\n\t\t\t\tlines.push(\n\t\t\t\t\ttruncateToWidth(\n\t\t\t\t\t\t`${cursor} ${this.renderCheckbox(item)} ${name}${this.getItemSuffix(item)}`,\n\t\t\t\t\t\twidth,\n\t\t\t\t\t\t\"...\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Scroll indicator\n\t\tif (startIndex > 0 || endIndex < this.filteredItems.length) {\n\t\t\tconst itemCount = this.filteredItems.filter((e) => e.type === \"item\").length;\n\t\t\tconst currentItemIndex =\n\t\t\t\tthis.filteredItems.slice(0, this.selectedIndex).filter((e) => e.type === \"item\").length + 1;\n\t\t\tlines.push(theme.fg(\"dim\", ` (${currentItemIndex}/${itemCount})`));\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\thandleInput(data: string): void {\n\t\tconst kb = getKeybindings();\n\n\t\tif (kb.matches(data, \"tui.select.up\")) {\n\t\t\tthis.selectedIndex = this.findNextItem(this.selectedIndex, -1);\n\t\t\treturn;\n\t\t}\n\t\tif (kb.matches(data, \"tui.select.down\")) {\n\t\t\tthis.selectedIndex = this.findNextItem(this.selectedIndex, 1);\n\t\t\treturn;\n\t\t}\n\t\tif (kb.matches(data, \"tui.select.pageUp\")) {\n\t\t\t// Jump up by maxVisible, then find nearest item\n\t\t\tlet target = Math.max(0, this.selectedIndex - this.maxVisible);\n\t\t\twhile (target < this.filteredItems.length && this.filteredItems[target].type !== \"item\") {\n\t\t\t\ttarget++;\n\t\t\t}\n\t\t\tif (target < this.filteredItems.length) {\n\t\t\t\tthis.selectedIndex = target;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (kb.matches(data, \"tui.select.pageDown\")) {\n\t\t\t// Jump down by maxVisible, then find nearest item\n\t\t\tlet target = Math.min(this.filteredItems.length - 1, this.selectedIndex + this.maxVisible);\n\t\t\twhile (target >= 0 && this.filteredItems[target].type !== \"item\") {\n\t\t\t\ttarget--;\n\t\t\t}\n\t\t\tif (target >= 0) {\n\t\t\t\tthis.selectedIndex = target;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (kb.matches(data, \"tui.select.cancel\")) {\n\t\t\tthis.onCancel?.();\n\t\t\treturn;\n\t\t}\n\t\tif (matchesKey(data, \"ctrl+c\")) {\n\t\t\tthis.onExit?.();\n\t\t\treturn;\n\t\t}\n\t\tif (kb.matches(data, \"tui.input.tab\")) {\n\t\t\tthis.onSwitchMode?.();\n\t\t\treturn;\n\t\t}\n\t\tif (data === \" \" || kb.matches(data, \"tui.select.confirm\")) {\n\t\t\tconst entry = this.filteredItems[this.selectedIndex];\n\t\t\tif (entry?.type === \"item\" && (this.writeScope === \"project\" || this.getItemScope(entry.item) === \"user\")) {\n\t\t\t\tconst newEnabled = this.toggleResource(entry.item);\n\t\t\t\tif (newEnabled !== undefined) {\n\t\t\t\t\tthis.updateItem(entry.item, newEnabled);\n\t\t\t\t\tthis.onToggle?.(entry.item, newEnabled);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Pass to search input\n\t\tthis.searchInput.handleInput(data);\n\t\tthis.filterItems(this.searchInput.getValue());\n\t}\n\n\tprivate toggleResource(item: ResourceItem): boolean | undefined {\n\t\tif (this.writeScope === \"project\") {\n\t\t\tconst state = this.getNextOverrideState(item);\n\t\t\tif (!this.setProjectResourceOverride(item, state)) return undefined;\n\t\t\treturn state === \"inherit\" ? this.getInheritedEnabled(item) : state === \"load\";\n\t\t}\n\n\t\tconst enabled = !item.enabled;\n\t\tif (item.metadata.origin === \"top-level\") {\n\t\t\tthis.toggleTopLevelResource(item, enabled);\n\t\t} else {\n\t\t\tthis.togglePackageResource(item, enabled);\n\t\t}\n\t\treturn enabled;\n\t}\n\n\tprivate toggleTopLevelResource(item: ResourceItem, enabled: boolean): void {\n\t\tconst scope = item.metadata.scope as \"user\" | \"project\";\n\t\tconst settings =\n\t\t\tscope === \"project\" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings();\n\n\t\tconst arrayKey = item.resourceType as \"extensions\" | \"skills\" | \"prompts\" | \"themes\";\n\t\tconst current = (settings[arrayKey] ?? []) as string[];\n\n\t\t// Generate pattern for this resource\n\t\tconst pattern = this.getResourcePattern(item);\n\t\tconst disablePattern = `-${pattern}`;\n\t\tconst enablePattern = `+${pattern}`;\n\n\t\t// Filter out existing patterns for this resource\n\t\tconst updated = current.filter((p) => {\n\t\t\tconst stripped = p.startsWith(\"!\") || p.startsWith(\"+\") || p.startsWith(\"-\") ? p.slice(1) : p;\n\t\t\treturn stripped !== pattern;\n\t\t});\n\n\t\tif (enabled) {\n\t\t\tupdated.push(enablePattern);\n\t\t} else {\n\t\t\tupdated.push(disablePattern);\n\t\t}\n\n\t\tif (scope === \"project\") {\n\t\t\tif (arrayKey === \"extensions\") {\n\t\t\t\tthis.settingsManager.setProjectExtensionPaths(updated);\n\t\t\t} else if (arrayKey === \"skills\") {\n\t\t\t\tthis.settingsManager.setProjectSkillPaths(updated);\n\t\t\t} else if (arrayKey === \"prompts\") {\n\t\t\t\tthis.settingsManager.setProjectPromptTemplatePaths(updated);\n\t\t\t} else if (arrayKey === \"themes\") {\n\t\t\t\tthis.settingsManager.setProjectThemePaths(updated);\n\t\t\t}\n\t\t} else {\n\t\t\tif (arrayKey === \"extensions\") {\n\t\t\t\tthis.settingsManager.setExtensionPaths(updated);\n\t\t\t} else if (arrayKey === \"skills\") {\n\t\t\t\tthis.settingsManager.setSkillPaths(updated);\n\t\t\t} else if (arrayKey === \"prompts\") {\n\t\t\t\tthis.settingsManager.setPromptTemplatePaths(updated);\n\t\t\t} else if (arrayKey === \"themes\") {\n\t\t\t\tthis.settingsManager.setThemePaths(updated);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate togglePackageResource(item: ResourceItem, enabled: boolean): void {\n\t\tconst scope = item.metadata.scope as \"user\" | \"project\";\n\t\tconst settings =\n\t\t\tscope === \"project\" ? this.settingsManager.getProjectSettings() : this.settingsManager.getGlobalSettings();\n\n\t\tconst packages = [...(settings.packages ?? [])] as PackageSource[];\n\t\tconst pkgIndex = packages.findIndex((pkg) => {\n\t\t\tconst source = typeof pkg === \"string\" ? pkg : pkg.source;\n\t\t\treturn source === item.metadata.source;\n\t\t});\n\n\t\tif (pkgIndex === -1) return;\n\n\t\tlet pkg = packages[pkgIndex];\n\n\t\t// Convert string to object form if needed\n\t\tif (typeof pkg === \"string\") {\n\t\t\tpkg = { source: pkg };\n\t\t\tpackages[pkgIndex] = pkg;\n\t\t}\n\n\t\t// Get the resource array for this type\n\t\tconst arrayKey = item.resourceType as \"extensions\" | \"skills\" | \"prompts\" | \"themes\";\n\t\tconst current = (pkg[arrayKey] ?? []) as string[];\n\n\t\t// Generate pattern relative to package root\n\t\tconst pattern = this.getPackageResourcePattern(item);\n\t\tconst disablePattern = `-${pattern}`;\n\t\tconst enablePattern = `+${pattern}`;\n\n\t\t// Filter out existing patterns for this resource\n\t\tconst updated = current.filter((p) => {\n\t\t\tconst stripped = p.startsWith(\"!\") || p.startsWith(\"+\") || p.startsWith(\"-\") ? p.slice(1) : p;\n\t\t\treturn stripped !== pattern;\n\t\t});\n\n\t\tif (enabled) {\n\t\t\tupdated.push(enablePattern);\n\t\t} else {\n\t\t\tupdated.push(disablePattern);\n\t\t}\n\n\t\t(pkg as Record)[arrayKey] = updated.length > 0 ? updated : undefined;\n\n\t\t// Clean up empty filter object\n\t\tconst hasFilters = [\"extensions\", \"skills\", \"prompts\", \"themes\"].some(\n\t\t\t(k) => (pkg as Record)[k] !== undefined,\n\t\t);\n\t\tif (!hasFilters) {\n\t\t\tpackages[pkgIndex] = (pkg as { source: string }).source;\n\t\t}\n\n\t\tif (scope === \"project\") {\n\t\t\tthis.settingsManager.setProjectPackages(packages);\n\t\t} else {\n\t\t\tthis.settingsManager.setPackages(packages);\n\t\t}\n\t}\n\n\tprivate renderCheckbox(item: ResourceItem): string {\n\t\tif (this.writeScope === \"project\") {\n\t\t\tconst state = this.getProjectOverrideState(item);\n\t\t\tif (state === \"load\") return theme.fg(\"success\", \"[+]\");\n\t\t\tif (state === \"unload\") return theme.fg(\"warning\", \"[-]\");\n\t\t\treturn theme.fg(\"dim\", item.enabled ? \"[x]\" : \"[ ]\");\n\t\t}\n\t\treturn item.enabled ? theme.fg(\"success\", \"[x]\") : theme.fg(\"dim\", \"[ ]\");\n\t}\n\n\tprivate getItemSuffix(item: ResourceItem): string {\n\t\tif (this.writeScope !== \"project\") return \"\";\n\t\tconst state = this.getProjectOverrideState(item);\n\t\tif (state === \"load\") return theme.fg(\"muted\", \" project load\");\n\t\tif (state === \"unload\") return theme.fg(\"muted\", \" project unload\");\n\t\treturn this.isInheritedGlobalItem(item) ? theme.fg(\"dim\", \" inherited global\") : \"\";\n\t}\n\n\tprivate isDimmedItem(item: ResourceItem): boolean {\n\t\treturn (\n\t\t\tthis.writeScope === \"project\" &&\n\t\t\tthis.isInheritedGlobalItem(item) &&\n\t\t\tthis.getProjectOverrideState(item) === \"inherit\"\n\t\t);\n\t}\n\n\tprivate setProjectResourceOverride(item: ResourceItem, state: ProjectOverrideState): boolean {\n\t\treturn item.metadata.origin === \"top-level\"\n\t\t\t? this.setProjectTopLevelOverride(item, state)\n\t\t\t: this.setProjectPackageOverride(item, state);\n\t}\n\n\tprivate setProjectTopLevelOverride(item: ResourceItem, state: ProjectOverrideState): boolean {\n\t\tconst current = (this.settingsManager.getProjectSettings()[item.resourceType] ?? []) as string[];\n\t\tconst pattern = this.isInheritedGlobalItem(item) ? item.path : this.getResourcePatternForScope(item, \"project\");\n\t\tconst patterns = this.getTopLevelOverridePatterns(item, \"project\");\n\t\tconst updated = current.filter((entry) => {\n\t\t\tconst target = this.getPatternEntryTarget(entry);\n\t\t\tif ((entry.startsWith(\"!\") || entry.startsWith(\"+\") || entry.startsWith(\"-\")) && patterns.has(target))\n\t\t\t\treturn false;\n\t\t\treturn !(state === \"inherit\" && this.isInheritedGlobalItem(item) && target === pattern);\n\t\t});\n\t\tif (state !== \"inherit\") {\n\t\t\tif (this.isInheritedGlobalItem(item) && !updated.includes(pattern)) updated.push(pattern);\n\t\t\tupdated.push(`${state === \"load\" ? \"+\" : \"-\"}${pattern}`);\n\t\t}\n\t\tthis.setProjectTopLevelPaths(item.resourceType, updated);\n\t\treturn true;\n\t}\n\n\tprivate setProjectTopLevelPaths(key: ResourceType, paths: string[]): void {\n\t\tif (key === \"extensions\") this.settingsManager.setProjectExtensionPaths(paths);\n\t\telse if (key === \"skills\") this.settingsManager.setProjectSkillPaths(paths);\n\t\telse if (key === \"prompts\") this.settingsManager.setProjectPromptTemplatePaths(paths);\n\t\telse this.settingsManager.setProjectThemePaths(paths);\n\t}\n\n\tprivate setProjectPackageOverride(item: ResourceItem, state: ProjectOverrideState): boolean {\n\t\tconst packages = [...(this.settingsManager.getProjectSettings().packages ?? [])] as PackageSource[];\n\t\tlet pkgIndex = packages.findIndex((pkg) =>\n\t\t\tthis.packageSourceStringMatches(\n\t\t\t\titem.metadata.source,\n\t\t\t\tthis.getItemScope(item),\n\t\t\t\ttypeof pkg === \"string\" ? pkg : pkg.source,\n\t\t\t\t\"project\",\n\t\t\t),\n\t\t);\n\t\tif (pkgIndex === -1) {\n\t\t\tif (state === \"inherit\") return false;\n\t\t\tpackages.push(this.createPackageOverrideSource(item));\n\t\t\tpkgIndex = packages.length - 1;\n\t\t}\n\t\tlet pkg = packages[pkgIndex];\n\t\tif (pkg === undefined) return false;\n\t\tif (typeof pkg === \"string\") {\n\t\t\tpkg = { source: pkg };\n\t\t\tpackages[pkgIndex] = pkg;\n\t\t}\n\t\tconst pattern = this.getPackageResourcePattern(item);\n\t\tconst updated = ((pkg[item.resourceType] ?? []) as string[]).filter(\n\t\t\t(entry) => this.getPatternEntryTarget(entry) !== pattern,\n\t\t);\n\t\tif (state !== \"inherit\") updated.push(`${state === \"load\" ? \"+\" : \"-\"}${pattern}`);\n\t\t(pkg as Record)[item.resourceType] = updated.length > 0 ? updated : undefined;\n\t\tif (!RESOURCE_TYPES.some((key) => (pkg as Record)[key] !== undefined)) {\n\t\t\tif (pkg.autoload === false) packages.splice(pkgIndex, 1);\n\t\t\telse packages[pkgIndex] = pkg.source;\n\t\t}\n\t\tthis.settingsManager.setProjectPackages(packages);\n\t\treturn true;\n\t}\n\n\tprivate getNextOverrideState(item: ResourceItem): ProjectOverrideState {\n\t\tconst state = this.getProjectOverrideState(item);\n\t\tconst inheritedEnabled = this.getInheritedEnabled(item);\n\t\tif (state === \"inherit\") return inheritedEnabled ? \"unload\" : \"load\";\n\t\tif (state === \"unload\") return inheritedEnabled ? \"load\" : \"inherit\";\n\t\treturn inheritedEnabled ? \"inherit\" : \"unload\";\n\t}\n\n\tprivate getProjectOverrideState(item: ResourceItem): ProjectOverrideState {\n\t\tif (this.writeScope !== \"project\") return \"inherit\";\n\t\tif (item.metadata.origin === \"top-level\") {\n\t\t\treturn this.getOverrideStateFromEntries(\n\t\t\t\t(this.settingsManager.getProjectSettings()[item.resourceType] ?? []) as string[],\n\t\t\t\tthis.getTopLevelOverridePatterns(item, \"project\"),\n\t\t\t\tfalse,\n\t\t\t);\n\t\t}\n\t\tconst pkg = this.findMatchingPackageSource(item, \"project\");\n\t\tif (typeof pkg !== \"object\") return \"inherit\";\n\t\tconst entries = pkg[item.resourceType];\n\t\tif (entries === undefined) return \"inherit\";\n\t\treturn this.getOverrideStateFromEntries(\n\t\t\tentries,\n\t\t\tnew Set([this.getPackageResourcePattern(item)]),\n\t\t\tpkg.autoload !== false,\n\t\t);\n\t}\n\n\tprivate getOverrideStateFromEntries(\n\t\tentries: string[],\n\t\tpatterns: Set,\n\t\temptyArrayIsUnload: boolean,\n\t): ProjectOverrideState {\n\t\tif (entries.length === 0 && emptyArrayIsUnload) return \"unload\";\n\t\tlet state: ProjectOverrideState = \"inherit\";\n\t\tfor (const entry of entries) {\n\t\t\tif (!patterns.has(this.getPatternEntryTarget(entry))) continue;\n\t\t\tif (entry.startsWith(\"!\") || entry.startsWith(\"-\")) state = \"unload\";\n\t\t\telse state = \"load\";\n\t\t}\n\t\treturn state;\n\t}\n\n\tprivate getInheritedEnabled(item: ResourceItem): boolean {\n\t\treturn (\n\t\t\tthis.inheritedEnabledByKey.get(this.getResourceItemKey(item)) ??\n\t\t\t(this.getItemScope(item) === \"user\" ? item.enabled : true)\n\t\t);\n\t}\n\n\tprivate isInheritedGlobalItem(item: ResourceItem): boolean {\n\t\treturn this.getItemScope(item) === \"user\" || this.inheritedEnabledByKey.has(this.getResourceItemKey(item));\n\t}\n\n\tprivate getTopLevelOverridePatterns(item: ResourceItem, scope: SettingsScope): Set {\n\t\tconst baseDir = this.getTopLevelBaseDir(scope);\n\t\tconst patterns = new Set([\n\t\t\tthis.getResourcePatternForScope(item, scope),\n\t\t\titem.path,\n\t\t\trelative(baseDir, item.path),\n\t\t]);\n\t\tif (item.metadata.baseDir) patterns.add(relative(item.metadata.baseDir, item.path));\n\t\treturn patterns;\n\t}\n\n\tprivate getResourcePatternForScope(item: ResourceItem, scope: SettingsScope): string {\n\t\tconst sourceScope = this.getItemScope(item);\n\t\tif (scope !== sourceScope) return item.path;\n\t\tconst baseDir = item.metadata.baseDir ?? this.getTopLevelBaseDir(sourceScope);\n\t\treturn relative(baseDir, item.path);\n\t}\n\n\tprivate createPackageOverrideSource(item: ResourceItem): PackageSource {\n\t\tconst source = item.metadata.source;\n\t\tif (!isLocalPath(source)) return { source, autoload: false };\n\t\tconst sourcePath = resolvePath(source, this.getTopLevelBaseDir(this.getItemScope(item)), { trim: true });\n\t\treturn { source: relative(this.getTopLevelBaseDir(\"project\"), sourcePath) || \".\", autoload: false };\n\t}\n\n\tprivate packageSourceStringMatches(\n\t\tleftSource: string,\n\t\tleftScope: SettingsScope,\n\t\trightSource: string,\n\t\trightScope: SettingsScope,\n\t): boolean {\n\t\tif (leftSource === rightSource) return true;\n\t\tif (!isLocalPath(leftSource) || !isLocalPath(rightSource)) return false;\n\t\tconst left = resolvePath(leftSource, this.getTopLevelBaseDir(leftScope), { trim: true });\n\t\tconst right = resolvePath(rightSource, this.getTopLevelBaseDir(rightScope), { trim: true });\n\t\treturn left === right;\n\t}\n\n\tprivate findMatchingPackageSource(item: ResourceItem, targetScope: SettingsScope): PackageSource | undefined {\n\t\tconst settings =\n\t\t\ttargetScope === \"project\"\n\t\t\t\t? this.settingsManager.getProjectSettings()\n\t\t\t\t: this.settingsManager.getGlobalSettings();\n\t\treturn (settings.packages ?? []).find((pkg) =>\n\t\t\tthis.packageSourceStringMatches(\n\t\t\t\titem.metadata.source,\n\t\t\t\tthis.getItemScope(item),\n\t\t\t\ttypeof pkg === \"string\" ? pkg : pkg.source,\n\t\t\t\ttargetScope,\n\t\t\t),\n\t\t);\n\t}\n\n\tprivate getPatternEntryTarget(entry: string): string {\n\t\treturn entry.startsWith(\"!\") || entry.startsWith(\"+\") || entry.startsWith(\"-\") ? entry.slice(1) : entry;\n\t}\n\n\tprivate getResourceItemKey(item: ResourceItem): string {\n\t\treturn `${item.resourceType}:${canonicalizePath(item.path)}`;\n\t}\n\n\tprivate getItemScope(item: ResourceItem): SettingsScope {\n\t\treturn item.metadata.scope === \"project\" ? \"project\" : \"user\";\n\t}\n\n\tprivate getTopLevelBaseDir(scope: \"user\" | \"project\"): string {\n\t\treturn scope === \"project\" ? join(this.cwd, CONFIG_DIR_NAME) : this.agentDir;\n\t}\n\n\tprivate getResourcePattern(item: ResourceItem): string {\n\t\tconst scope = item.metadata.scope as \"user\" | \"project\";\n\t\tconst baseDir = item.metadata.baseDir ?? this.getTopLevelBaseDir(scope);\n\t\treturn relative(baseDir, item.path);\n\t}\n\n\tprivate getPackageResourcePattern(item: ResourceItem): string {\n\t\tconst baseDir = item.metadata.baseDir ?? dirname(item.path);\n\t\treturn relative(baseDir, item.path);\n\t}\n}\n\nexport class ConfigSelectorComponent extends Container implements Focusable {\n\tprivate header: ConfigSelectorHeader;\n\tprivate resourceList: ResourceList;\n\tprivate writeScope: ConfigWriteScope;\n\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.resourceList.focused = value;\n\t}\n\n\tconstructor(\n\t\tresolvedPaths: ScopedResolvedPaths,\n\t\tsettingsManager: SettingsManager,\n\t\tcwd: string,\n\t\tagentDir: string,\n\t\tonClose: () => void,\n\t\tonExit: () => void,\n\t\trequestRender: () => void,\n\t\tterminalHeight?: number,\n\t\twriteScope: ConfigWriteScope = \"global\",\n\t\tprojectModeAvailable = true,\n\t) {\n\t\tsuper();\n\n\t\tthis.writeScope = writeScope;\n\t\tconst groupsByScope = {\n\t\t\tglobal: buildGroups(resolvedPaths.global, agentDir),\n\t\t\tproject: buildGroups(resolvedPaths.project, agentDir),\n\t\t};\n\n\t\t// Add header\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.header = new ConfigSelectorHeader(this.writeScope, projectModeAvailable);\n\t\tthis.addChild(this.header);\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Resource list\n\t\tthis.resourceList = new ResourceList(\n\t\t\tgroupsByScope,\n\t\t\tsettingsManager,\n\t\t\tcwd,\n\t\t\tagentDir,\n\t\t\tterminalHeight,\n\t\t\tthis.writeScope,\n\t\t);\n\t\tthis.resourceList.onCancel = onClose;\n\t\tthis.resourceList.onExit = onExit;\n\t\tthis.resourceList.onToggle = () => requestRender();\n\t\tif (projectModeAvailable) {\n\t\t\tthis.resourceList.onSwitchMode = () => {\n\t\t\t\tthis.switchWriteScope();\n\t\t\t\trequestRender();\n\t\t\t};\n\t\t}\n\t\tthis.addChild(this.resourceList);\n\n\t\t// Bottom border\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tprivate switchWriteScope(): void {\n\t\tthis.writeScope = this.writeScope === \"global\" ? \"project\" : \"global\";\n\t\tthis.header.setWriteScope(this.writeScope);\n\t\tthis.resourceList.setWriteScope(this.writeScope);\n\t}\n\n\tgetResourceList(): ResourceList {\n\t\treturn this.resourceList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/countdown-timer.d.ts b/dist/modes/interactive/components/countdown-timer.d.ts new file mode 100644 index 0000000..110624b --- /dev/null +++ b/dist/modes/interactive/components/countdown-timer.d.ts @@ -0,0 +1,14 @@ +/** + * Reusable countdown timer for dialog components. + */ +import type { TUI } from "@earendil-works/pi-tui"; +export declare class CountdownTimer { + private intervalId; + private remainingSeconds; + private tui; + private onTick; + private onExpire; + constructor(timeoutMs: number, tui: TUI | undefined, onTick: (seconds: number) => void, onExpire: () => void); + dispose(): void; +} +//# sourceMappingURL=countdown-timer.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/countdown-timer.d.ts.map b/dist/modes/interactive/components/countdown-timer.d.ts.map new file mode 100644 index 0000000..a40de6e --- /dev/null +++ b/dist/modes/interactive/components/countdown-timer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"countdown-timer.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/countdown-timer.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAElD,qBAAa,cAAc;IAC1B,OAAO,CAAC,UAAU,CAA6C;IAC/D,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,GAAG,CAAkB;IAC7B,OAAO,CAAC,MAAM,CAA4B;IAC1C,OAAO,CAAC,QAAQ,CAAa;IAE7B,YAAY,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,GAAG,SAAS,EAAE,MAAM,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,EAiB3G;IAED,OAAO,IAAI,IAAI,CAKd;CACD","sourcesContent":["/**\n * Reusable countdown timer for dialog components.\n */\n\nimport type { TUI } from \"@earendil-works/pi-tui\";\n\nexport class CountdownTimer {\n\tprivate intervalId: ReturnType | undefined;\n\tprivate remainingSeconds: number;\n\tprivate tui: TUI | undefined;\n\tprivate onTick: (seconds: number) => void;\n\tprivate onExpire: () => void;\n\n\tconstructor(timeoutMs: number, tui: TUI | undefined, onTick: (seconds: number) => void, onExpire: () => void) {\n\t\tthis.tui = tui;\n\t\tthis.onTick = onTick;\n\t\tthis.onExpire = onExpire;\n\t\tthis.remainingSeconds = Math.ceil(timeoutMs / 1000);\n\t\tthis.onTick(this.remainingSeconds);\n\n\t\tthis.intervalId = setInterval(() => {\n\t\t\tthis.remainingSeconds--;\n\t\t\tthis.onTick(this.remainingSeconds);\n\t\t\tthis.tui?.requestRender();\n\n\t\t\tif (this.remainingSeconds <= 0) {\n\t\t\t\tthis.dispose();\n\t\t\t\tthis.onExpire();\n\t\t\t}\n\t\t}, 1000);\n\t}\n\n\tdispose(): void {\n\t\tif (this.intervalId) {\n\t\t\tclearInterval(this.intervalId);\n\t\t\tthis.intervalId = undefined;\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/countdown-timer.js b/dist/modes/interactive/components/countdown-timer.js new file mode 100644 index 0000000..602dcd9 --- /dev/null +++ b/dist/modes/interactive/components/countdown-timer.js @@ -0,0 +1,33 @@ +/** + * Reusable countdown timer for dialog components. + */ +export class CountdownTimer { + intervalId; + remainingSeconds; + tui; + onTick; + onExpire; + constructor(timeoutMs, tui, onTick, onExpire) { + this.tui = tui; + this.onTick = onTick; + this.onExpire = onExpire; + this.remainingSeconds = Math.ceil(timeoutMs / 1000); + this.onTick(this.remainingSeconds); + this.intervalId = setInterval(() => { + this.remainingSeconds--; + this.onTick(this.remainingSeconds); + this.tui?.requestRender(); + if (this.remainingSeconds <= 0) { + this.dispose(); + this.onExpire(); + } + }, 1000); + } + dispose() { + if (this.intervalId) { + clearInterval(this.intervalId); + this.intervalId = undefined; + } + } +} +//# sourceMappingURL=countdown-timer.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/countdown-timer.js.map b/dist/modes/interactive/components/countdown-timer.js.map new file mode 100644 index 0000000..7beb5fa --- /dev/null +++ b/dist/modes/interactive/components/countdown-timer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"countdown-timer.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/countdown-timer.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,MAAM,OAAO,cAAc;IAClB,UAAU,CAA6C;IACvD,gBAAgB,CAAS;IACzB,GAAG,CAAkB;IACrB,MAAM,CAA4B;IAClC,QAAQ,CAAa;IAE7B,YAAY,SAAiB,EAAE,GAAoB,EAAE,MAAiC,EAAE,QAAoB,EAAE;QAC7G,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;QACpD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;QAEnC,IAAI,CAAC,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;YACnC,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACxB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;YACnC,IAAI,CAAC,GAAG,EAAE,aAAa,EAAE,CAAC;YAE1B,IAAI,IAAI,CAAC,gBAAgB,IAAI,CAAC,EAAE,CAAC;gBAChC,IAAI,CAAC,OAAO,EAAE,CAAC;gBACf,IAAI,CAAC,QAAQ,EAAE,CAAC;YACjB,CAAC;QAAA,CACD,EAAE,IAAI,CAAC,CAAC;IAAA,CACT;IAED,OAAO,GAAS;QACf,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACrB,aAAa,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC/B,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC7B,CAAC;IAAA,CACD;CACD","sourcesContent":["/**\n * Reusable countdown timer for dialog components.\n */\n\nimport type { TUI } from \"@earendil-works/pi-tui\";\n\nexport class CountdownTimer {\n\tprivate intervalId: ReturnType | undefined;\n\tprivate remainingSeconds: number;\n\tprivate tui: TUI | undefined;\n\tprivate onTick: (seconds: number) => void;\n\tprivate onExpire: () => void;\n\n\tconstructor(timeoutMs: number, tui: TUI | undefined, onTick: (seconds: number) => void, onExpire: () => void) {\n\t\tthis.tui = tui;\n\t\tthis.onTick = onTick;\n\t\tthis.onExpire = onExpire;\n\t\tthis.remainingSeconds = Math.ceil(timeoutMs / 1000);\n\t\tthis.onTick(this.remainingSeconds);\n\n\t\tthis.intervalId = setInterval(() => {\n\t\t\tthis.remainingSeconds--;\n\t\t\tthis.onTick(this.remainingSeconds);\n\t\t\tthis.tui?.requestRender();\n\n\t\t\tif (this.remainingSeconds <= 0) {\n\t\t\t\tthis.dispose();\n\t\t\t\tthis.onExpire();\n\t\t\t}\n\t\t}, 1000);\n\t}\n\n\tdispose(): void {\n\t\tif (this.intervalId) {\n\t\t\tclearInterval(this.intervalId);\n\t\t\tthis.intervalId = undefined;\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/custom-editor.d.ts b/dist/modes/interactive/components/custom-editor.d.ts new file mode 100644 index 0000000..807c6a2 --- /dev/null +++ b/dist/modes/interactive/components/custom-editor.d.ts @@ -0,0 +1,21 @@ +import { Editor, type EditorOptions, type EditorTheme, type TUI } from "@earendil-works/pi-tui"; +import type { AppKeybinding, KeybindingsManager } from "../../../core/keybindings.ts"; +/** + * Custom editor that handles app-level keybindings for coding-agent. + */ +export declare class CustomEditor extends Editor { + private keybindings; + actionHandlers: Map void>; + onEscape?: () => void; + onCtrlD?: () => void; + onPasteImage?: () => void; + /** Handler for extension-registered shortcuts. Returns true if handled. */ + onExtensionShortcut?: (data: string) => boolean; + constructor(tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager, options?: EditorOptions); + /** + * Register a handler for an app action. + */ + onAction(action: AppKeybinding, handler: () => void): void; + handleInput(data: string): void; +} +//# sourceMappingURL=custom-editor.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/custom-editor.d.ts.map b/dist/modes/interactive/components/custom-editor.d.ts.map new file mode 100644 index 0000000..8d5bd0d --- /dev/null +++ b/dist/modes/interactive/components/custom-editor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"custom-editor.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/custom-editor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,aAAa,EAAE,KAAK,WAAW,EAAE,KAAK,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAChG,OAAO,KAAK,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAEtF;;GAEG;AACH,qBAAa,YAAa,SAAQ,MAAM;IACvC,OAAO,CAAC,WAAW,CAAqB;IACjC,cAAc,EAAE,GAAG,CAAC,aAAa,EAAE,MAAM,IAAI,CAAC,CAAa;IAG3D,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;IACtB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;IACjC,2EAA2E;IACpE,mBAAmB,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IAEvD,YAAY,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,kBAAkB,EAAE,OAAO,CAAC,EAAE,aAAa,EAGjG;IAED;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,IAAI,GAAG,IAAI,CAEzD;IAED,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAiD9B;CACD","sourcesContent":["import { Editor, type EditorOptions, type EditorTheme, type TUI } from \"@earendil-works/pi-tui\";\nimport type { AppKeybinding, KeybindingsManager } from \"../../../core/keybindings.ts\";\n\n/**\n * Custom editor that handles app-level keybindings for coding-agent.\n */\nexport class CustomEditor extends Editor {\n\tprivate keybindings: KeybindingsManager;\n\tpublic actionHandlers: Map void> = new Map();\n\n\t// Special handlers that can be dynamically replaced\n\tpublic onEscape?: () => void;\n\tpublic onCtrlD?: () => void;\n\tpublic onPasteImage?: () => void;\n\t/** Handler for extension-registered shortcuts. Returns true if handled. */\n\tpublic onExtensionShortcut?: (data: string) => boolean;\n\n\tconstructor(tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager, options?: EditorOptions) {\n\t\tsuper(tui, theme, options);\n\t\tthis.keybindings = keybindings;\n\t}\n\n\t/**\n\t * Register a handler for an app action.\n\t */\n\tonAction(action: AppKeybinding, handler: () => void): void {\n\t\tthis.actionHandlers.set(action, handler);\n\t}\n\n\thandleInput(data: string): void {\n\t\t// Check extension-registered shortcuts first\n\t\tif (this.onExtensionShortcut?.(data)) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Check for clipboard paste keybinding\n\t\tif (this.keybindings.matches(data, \"app.clipboard.pasteImage\")) {\n\t\t\tthis.onPasteImage?.();\n\t\t\treturn;\n\t\t}\n\n\t\t// Check app keybindings first\n\n\t\t// Escape/interrupt - only if autocomplete is NOT active\n\t\tif (this.keybindings.matches(data, \"app.interrupt\")) {\n\t\t\tif (!this.isShowingAutocomplete()) {\n\t\t\t\t// Use dynamic onEscape if set, otherwise registered handler\n\t\t\t\tconst handler = this.onEscape ?? this.actionHandlers.get(\"app.interrupt\");\n\t\t\t\tif (handler) {\n\t\t\t\t\thandler();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Let parent handle escape for autocomplete cancellation\n\t\t\tsuper.handleInput(data);\n\t\t\treturn;\n\t\t}\n\n\t\t// Exit (Ctrl+D) - only when editor is empty\n\t\tif (this.keybindings.matches(data, \"app.exit\")) {\n\t\t\tif (this.getText().length === 0) {\n\t\t\t\tconst handler = this.onCtrlD ?? this.actionHandlers.get(\"app.exit\");\n\t\t\t\tif (handler) handler();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Fall through to editor handling for delete-char-forward when not empty\n\t\t}\n\n\t\t// Check all other app actions\n\t\tfor (const [action, handler] of this.actionHandlers) {\n\t\t\tif (action !== \"app.interrupt\" && action !== \"app.exit\" && this.keybindings.matches(data, action)) {\n\t\t\t\thandler();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Pass to parent for editor handling\n\t\tsuper.handleInput(data);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/custom-editor.js b/dist/modes/interactive/components/custom-editor.js new file mode 100644 index 0000000..229c753 --- /dev/null +++ b/dist/modes/interactive/components/custom-editor.js @@ -0,0 +1,70 @@ +import { Editor } from "@earendil-works/pi-tui"; +/** + * Custom editor that handles app-level keybindings for coding-agent. + */ +export class CustomEditor extends Editor { + keybindings; + actionHandlers = new Map(); + // Special handlers that can be dynamically replaced + onEscape; + onCtrlD; + onPasteImage; + /** Handler for extension-registered shortcuts. Returns true if handled. */ + onExtensionShortcut; + constructor(tui, theme, keybindings, options) { + super(tui, theme, options); + this.keybindings = keybindings; + } + /** + * Register a handler for an app action. + */ + onAction(action, handler) { + this.actionHandlers.set(action, handler); + } + handleInput(data) { + // Check extension-registered shortcuts first + if (this.onExtensionShortcut?.(data)) { + return; + } + // Check for clipboard paste keybinding + if (this.keybindings.matches(data, "app.clipboard.pasteImage")) { + this.onPasteImage?.(); + return; + } + // Check app keybindings first + // Escape/interrupt - only if autocomplete is NOT active + if (this.keybindings.matches(data, "app.interrupt")) { + if (!this.isShowingAutocomplete()) { + // Use dynamic onEscape if set, otherwise registered handler + const handler = this.onEscape ?? this.actionHandlers.get("app.interrupt"); + if (handler) { + handler(); + return; + } + } + // Let parent handle escape for autocomplete cancellation + super.handleInput(data); + return; + } + // Exit (Ctrl+D) - only when editor is empty + if (this.keybindings.matches(data, "app.exit")) { + if (this.getText().length === 0) { + const handler = this.onCtrlD ?? this.actionHandlers.get("app.exit"); + if (handler) + handler(); + return; + } + // Fall through to editor handling for delete-char-forward when not empty + } + // Check all other app actions + for (const [action, handler] of this.actionHandlers) { + if (action !== "app.interrupt" && action !== "app.exit" && this.keybindings.matches(data, action)) { + handler(); + return; + } + } + // Pass to parent for editor handling + super.handleInput(data); + } +} +//# sourceMappingURL=custom-editor.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/custom-editor.js.map b/dist/modes/interactive/components/custom-editor.js.map new file mode 100644 index 0000000..8e9534f --- /dev/null +++ b/dist/modes/interactive/components/custom-editor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"custom-editor.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/custom-editor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAkD,MAAM,wBAAwB,CAAC;AAGhG;;GAEG;AACH,MAAM,OAAO,YAAa,SAAQ,MAAM;IAC/B,WAAW,CAAqB;IACjC,cAAc,GAAmC,IAAI,GAAG,EAAE,CAAC;IAElE,oDAAoD;IAC7C,QAAQ,CAAc;IACtB,OAAO,CAAc;IACrB,YAAY,CAAc;IACjC,2EAA2E;IACpE,mBAAmB,CAA6B;IAEvD,YAAY,GAAQ,EAAE,KAAkB,EAAE,WAA+B,EAAE,OAAuB,EAAE;QACnG,KAAK,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IAAA,CAC/B;IAED;;OAEG;IACH,QAAQ,CAAC,MAAqB,EAAE,OAAmB,EAAQ;QAC1D,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAAA,CACzC;IAED,WAAW,CAAC,IAAY,EAAQ;QAC/B,6CAA6C;QAC7C,IAAI,IAAI,CAAC,mBAAmB,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;YACtC,OAAO;QACR,CAAC;QAED,uCAAuC;QACvC,IAAI,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,EAAE,0BAA0B,CAAC,EAAE,CAAC;YAChE,IAAI,CAAC,YAAY,EAAE,EAAE,CAAC;YACtB,OAAO;QACR,CAAC;QAED,8BAA8B;QAE9B,wDAAwD;QACxD,IAAI,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,EAAE,eAAe,CAAC,EAAE,CAAC;YACrD,IAAI,CAAC,IAAI,CAAC,qBAAqB,EAAE,EAAE,CAAC;gBACnC,4DAA4D;gBAC5D,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;gBAC1E,IAAI,OAAO,EAAE,CAAC;oBACb,OAAO,EAAE,CAAC;oBACV,OAAO;gBACR,CAAC;YACF,CAAC;YACD,yDAAyD;YACzD,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;YACxB,OAAO;QACR,CAAC;QAED,4CAA4C;QAC5C,IAAI,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,CAAC;YAChD,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBACjC,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;gBACpE,IAAI,OAAO;oBAAE,OAAO,EAAE,CAAC;gBACvB,OAAO;YACR,CAAC;YACD,yEAAyE;QAC1E,CAAC;QAED,8BAA8B;QAC9B,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACrD,IAAI,MAAM,KAAK,eAAe,IAAI,MAAM,KAAK,UAAU,IAAI,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,CAAC;gBACnG,OAAO,EAAE,CAAC;gBACV,OAAO;YACR,CAAC;QACF,CAAC;QAED,qCAAqC;QACrC,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;IAAA,CACxB;CACD","sourcesContent":["import { Editor, type EditorOptions, type EditorTheme, type TUI } from \"@earendil-works/pi-tui\";\nimport type { AppKeybinding, KeybindingsManager } from \"../../../core/keybindings.ts\";\n\n/**\n * Custom editor that handles app-level keybindings for coding-agent.\n */\nexport class CustomEditor extends Editor {\n\tprivate keybindings: KeybindingsManager;\n\tpublic actionHandlers: Map void> = new Map();\n\n\t// Special handlers that can be dynamically replaced\n\tpublic onEscape?: () => void;\n\tpublic onCtrlD?: () => void;\n\tpublic onPasteImage?: () => void;\n\t/** Handler for extension-registered shortcuts. Returns true if handled. */\n\tpublic onExtensionShortcut?: (data: string) => boolean;\n\n\tconstructor(tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager, options?: EditorOptions) {\n\t\tsuper(tui, theme, options);\n\t\tthis.keybindings = keybindings;\n\t}\n\n\t/**\n\t * Register a handler for an app action.\n\t */\n\tonAction(action: AppKeybinding, handler: () => void): void {\n\t\tthis.actionHandlers.set(action, handler);\n\t}\n\n\thandleInput(data: string): void {\n\t\t// Check extension-registered shortcuts first\n\t\tif (this.onExtensionShortcut?.(data)) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Check for clipboard paste keybinding\n\t\tif (this.keybindings.matches(data, \"app.clipboard.pasteImage\")) {\n\t\t\tthis.onPasteImage?.();\n\t\t\treturn;\n\t\t}\n\n\t\t// Check app keybindings first\n\n\t\t// Escape/interrupt - only if autocomplete is NOT active\n\t\tif (this.keybindings.matches(data, \"app.interrupt\")) {\n\t\t\tif (!this.isShowingAutocomplete()) {\n\t\t\t\t// Use dynamic onEscape if set, otherwise registered handler\n\t\t\t\tconst handler = this.onEscape ?? this.actionHandlers.get(\"app.interrupt\");\n\t\t\t\tif (handler) {\n\t\t\t\t\thandler();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Let parent handle escape for autocomplete cancellation\n\t\t\tsuper.handleInput(data);\n\t\t\treturn;\n\t\t}\n\n\t\t// Exit (Ctrl+D) - only when editor is empty\n\t\tif (this.keybindings.matches(data, \"app.exit\")) {\n\t\t\tif (this.getText().length === 0) {\n\t\t\t\tconst handler = this.onCtrlD ?? this.actionHandlers.get(\"app.exit\");\n\t\t\t\tif (handler) handler();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Fall through to editor handling for delete-char-forward when not empty\n\t\t}\n\n\t\t// Check all other app actions\n\t\tfor (const [action, handler] of this.actionHandlers) {\n\t\t\tif (action !== \"app.interrupt\" && action !== \"app.exit\" && this.keybindings.matches(data, action)) {\n\t\t\t\thandler();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Pass to parent for editor handling\n\t\tsuper.handleInput(data);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/custom-entry.d.ts b/dist/modes/interactive/components/custom-entry.d.ts new file mode 100644 index 0000000..d5ff98c --- /dev/null +++ b/dist/modes/interactive/components/custom-entry.d.ts @@ -0,0 +1,19 @@ +import { Container } from "@earendil-works/pi-tui"; +import type { EntryRenderer } from "../../../core/extensions/types.ts"; +import type { CustomEntry } from "../../../core/session-manager.ts"; +/** + * Component that renders a custom session entry from extensions. + * The host owns transcript spacing; renderer output should provide only its content. + */ +export declare class CustomEntryComponent extends Container { + private entry; + private renderer; + private customComponent?; + private _expanded; + constructor(entry: CustomEntry, renderer: EntryRenderer); + hasContent(): boolean; + setExpanded(expanded: boolean): void; + invalidate(): void; + private rebuild; +} +//# sourceMappingURL=custom-entry.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/custom-entry.d.ts.map b/dist/modes/interactive/components/custom-entry.d.ts.map new file mode 100644 index 0000000..44d3389 --- /dev/null +++ b/dist/modes/interactive/components/custom-entry.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"custom-entry.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/custom-entry.ts"],"names":[],"mappings":"AACA,OAAO,EAAO,SAAS,EAAgB,MAAM,wBAAwB,CAAC;AACtE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AAGpE;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,SAAS;IAClD,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,eAAe,CAAC,CAAY;IACpC,OAAO,CAAC,SAAS,CAAS;IAE1B,YAAY,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE,QAAQ,EAAE,aAAa,EAK/D;IAED,UAAU,IAAI,OAAO,CAEpB;IAED,WAAW,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI,CAKnC;IAEQ,UAAU,IAAI,IAAI,CAG1B;IAED,OAAO,CAAC,OAAO;CAsBf","sourcesContent":["import type { Component } from \"@earendil-works/pi-tui\";\nimport { Box, Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { EntryRenderer } from \"../../../core/extensions/types.ts\";\nimport type { CustomEntry } from \"../../../core/session-manager.ts\";\nimport { theme } from \"../theme/theme.ts\";\n\n/**\n * Component that renders a custom session entry from extensions.\n * The host owns transcript spacing; renderer output should provide only its content.\n */\nexport class CustomEntryComponent extends Container {\n\tprivate entry: CustomEntry;\n\tprivate renderer: EntryRenderer;\n\tprivate customComponent?: Component;\n\tprivate _expanded = false;\n\n\tconstructor(entry: CustomEntry, renderer: EntryRenderer) {\n\t\tsuper();\n\t\tthis.entry = entry;\n\t\tthis.renderer = renderer;\n\t\tthis.rebuild();\n\t}\n\n\thasContent(): boolean {\n\t\treturn this.customComponent !== undefined;\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tif (this._expanded !== expanded) {\n\t\t\tthis._expanded = expanded;\n\t\t\tthis.rebuild();\n\t\t}\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.rebuild();\n\t}\n\n\tprivate rebuild(): void {\n\t\tthis.clear();\n\t\tthis.customComponent = undefined;\n\n\t\tlet component: Component | undefined;\n\t\ttry {\n\t\t\tcomponent = this.renderer(this.entry, { expanded: this._expanded }, theme);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconst box = new Box(1, 1, (text) => theme.bg(\"customMessageBg\", text));\n\t\t\tbox.addChild(new Text(theme.fg(\"error\", `[${this.entry.customType}] renderer failed: ${message}`), 0, 0));\n\t\t\tcomponent = box;\n\t\t}\n\n\t\tif (!component) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.customComponent = component;\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(component);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/custom-entry.js b/dist/modes/interactive/components/custom-entry.js new file mode 100644 index 0000000..fa38f12 --- /dev/null +++ b/dist/modes/interactive/components/custom-entry.js @@ -0,0 +1,52 @@ +import { Box, Container, Spacer, Text } from "@earendil-works/pi-tui"; +import { theme } from "../theme/theme.js"; +/** + * Component that renders a custom session entry from extensions. + * The host owns transcript spacing; renderer output should provide only its content. + */ +export class CustomEntryComponent extends Container { + entry; + renderer; + customComponent; + _expanded = false; + constructor(entry, renderer) { + super(); + this.entry = entry; + this.renderer = renderer; + this.rebuild(); + } + hasContent() { + return this.customComponent !== undefined; + } + setExpanded(expanded) { + if (this._expanded !== expanded) { + this._expanded = expanded; + this.rebuild(); + } + } + invalidate() { + super.invalidate(); + this.rebuild(); + } + rebuild() { + this.clear(); + this.customComponent = undefined; + let component; + try { + component = this.renderer(this.entry, { expanded: this._expanded }, theme); + } + catch (error) { + const message = error instanceof Error ? error.message : String(error); + const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text)); + box.addChild(new Text(theme.fg("error", `[${this.entry.customType}] renderer failed: ${message}`), 0, 0)); + component = box; + } + if (!component) { + return; + } + this.customComponent = component; + this.addChild(new Spacer(1)); + this.addChild(component); + } +} +//# sourceMappingURL=custom-entry.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/custom-entry.js.map b/dist/modes/interactive/components/custom-entry.js.map new file mode 100644 index 0000000..245a4a1 --- /dev/null +++ b/dist/modes/interactive/components/custom-entry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"custom-entry.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/custom-entry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,IA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,CAAC;YACvE,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,iBAAiB,EAAE,IAAI,CAAC,CAAC,CAAC;YACvE,GAAG,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,IAAI,CAAC,KAAK,CAAC,UAAU,sBAAsB,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAC1G,SAAS,GAAG,GAAG,CAAC;QACjB,CAAC;QAED,IAAI,CAAC,SAAS,EAAE,CAAC;YAChB,OAAO;QACR,CAAC;QAED,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;IAAA,CACzB;CACD","sourcesContent":["import type { Component } from \"@earendil-works/pi-tui\";\nimport { Box, Container, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { EntryRenderer } from \"../../../core/extensions/types.ts\";\nimport type { CustomEntry } from \"../../../core/session-manager.ts\";\nimport { theme } from \"../theme/theme.ts\";\n\n/**\n * Component that renders a custom session entry from extensions.\n * The host owns transcript spacing; renderer output should provide only its content.\n */\nexport class CustomEntryComponent extends Container {\n\tprivate entry: CustomEntry;\n\tprivate renderer: EntryRenderer;\n\tprivate customComponent?: Component;\n\tprivate _expanded = false;\n\n\tconstructor(entry: CustomEntry, renderer: EntryRenderer) {\n\t\tsuper();\n\t\tthis.entry = entry;\n\t\tthis.renderer = renderer;\n\t\tthis.rebuild();\n\t}\n\n\thasContent(): boolean {\n\t\treturn this.customComponent !== undefined;\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tif (this._expanded !== expanded) {\n\t\t\tthis._expanded = expanded;\n\t\t\tthis.rebuild();\n\t\t}\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.rebuild();\n\t}\n\n\tprivate rebuild(): void {\n\t\tthis.clear();\n\t\tthis.customComponent = undefined;\n\n\t\tlet component: Component | undefined;\n\t\ttry {\n\t\t\tcomponent = this.renderer(this.entry, { expanded: this._expanded }, theme);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconst box = new Box(1, 1, (text) => theme.bg(\"customMessageBg\", text));\n\t\t\tbox.addChild(new Text(theme.fg(\"error\", `[${this.entry.customType}] renderer failed: ${message}`), 0, 0));\n\t\t\tcomponent = box;\n\t\t}\n\n\t\tif (!component) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.customComponent = component;\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(component);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/custom-message.d.ts b/dist/modes/interactive/components/custom-message.d.ts new file mode 100644 index 0000000..4f55bb8 --- /dev/null +++ b/dist/modes/interactive/components/custom-message.d.ts @@ -0,0 +1,22 @@ +import { Container, type MarkdownTheme } from "@earendil-works/pi-tui"; +import type { MessageRenderer } from "../../../core/extensions/types.ts"; +import type { CustomMessage } from "../../../core/messages.ts"; +/** + * Component that renders a custom message entry from extensions. + * Uses distinct styling to differentiate from user messages. + */ +export declare class CustomMessageComponent extends Container { + private message; + private customRenderer?; + private box; + private customComponent?; + private markdownTheme; + private _expanded; + private outputPad; + constructor(message: CustomMessage, customRenderer?: MessageRenderer, markdownTheme?: MarkdownTheme, outputPad?: number); + setExpanded(expanded: boolean): void; + setOutputPad(outputPad: number): void; + invalidate(): void; + private rebuild; +} +//# sourceMappingURL=custom-message.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/custom-message.d.ts.map b/dist/modes/interactive/components/custom-message.d.ts.map new file mode 100644 index 0000000..89d1d38 --- /dev/null +++ b/dist/modes/interactive/components/custom-message.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"custom-message.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/custom-message.ts"],"names":[],"mappings":"AAEA,OAAO,EAAO,SAAS,EAAY,KAAK,aAAa,EAAgB,MAAM,wBAAwB,CAAC;AACpG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAG/D;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,SAAS;IACpD,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,cAAc,CAAC,CAAkB;IACzC,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,eAAe,CAAC,CAAY;IACpC,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,SAAS,CAAS;IAE1B,YACC,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC,EAC/B,cAAc,CAAC,EAAE,eAAe,EAChC,aAAa,GAAE,aAAkC,EACjD,SAAS,SAAI,EAcb;IAED,WAAW,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI,CAKnC;IAED,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAKpC;IAEQ,UAAU,IAAI,IAAI,CAG1B;IAED,OAAO,CAAC,OAAO;CAqDf","sourcesContent":["import type { TextContent } from \"@earendil-works/pi-ai\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { Box, Container, Markdown, type MarkdownTheme, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { MessageRenderer } from \"../../../core/extensions/types.ts\";\nimport type { CustomMessage } from \"../../../core/messages.ts\";\nimport { getMarkdownTheme, theme } from \"../theme/theme.ts\";\n\n/**\n * Component that renders a custom message entry from extensions.\n * Uses distinct styling to differentiate from user messages.\n */\nexport class CustomMessageComponent extends Container {\n\tprivate message: CustomMessage;\n\tprivate customRenderer?: MessageRenderer;\n\tprivate box: Box;\n\tprivate customComponent?: Component;\n\tprivate markdownTheme: MarkdownTheme;\n\tprivate _expanded = false;\n\tprivate outputPad: number;\n\n\tconstructor(\n\t\tmessage: CustomMessage,\n\t\tcustomRenderer?: MessageRenderer,\n\t\tmarkdownTheme: MarkdownTheme = getMarkdownTheme(),\n\t\toutputPad = 1,\n\t) {\n\t\tsuper();\n\t\tthis.message = message;\n\t\tthis.customRenderer = customRenderer;\n\t\tthis.markdownTheme = markdownTheme;\n\t\tthis.outputPad = outputPad;\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create box with purple background (used for default rendering)\n\t\tthis.box = new Box(1, 1, (t) => theme.bg(\"customMessageBg\", t));\n\n\t\tthis.rebuild();\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tif (this._expanded !== expanded) {\n\t\t\tthis._expanded = expanded;\n\t\t\tthis.rebuild();\n\t\t}\n\t}\n\n\tsetOutputPad(outputPad: number): void {\n\t\tif (this.outputPad !== outputPad) {\n\t\t\tthis.outputPad = outputPad;\n\t\t\tthis.rebuild();\n\t\t}\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.rebuild();\n\t}\n\n\tprivate rebuild(): void {\n\t\t// Remove previous content component\n\t\tif (this.customComponent) {\n\t\t\tthis.removeChild(this.customComponent);\n\t\t\tthis.customComponent = undefined;\n\t\t}\n\t\tthis.removeChild(this.box);\n\n\t\t// Try custom renderer first - it handles its own styling\n\t\tif (this.customRenderer) {\n\t\t\ttry {\n\t\t\t\tconst component = this.customRenderer(\n\t\t\t\t\tthis.message,\n\t\t\t\t\t{ expanded: this._expanded, outputPad: this.outputPad },\n\t\t\t\t\ttheme,\n\t\t\t\t);\n\t\t\t\tif (component) {\n\t\t\t\t\t// Custom renderer provides its own styled component\n\t\t\t\t\tthis.customComponent = component;\n\t\t\t\t\tthis.addChild(component);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Fall through to default rendering\n\t\t\t}\n\t\t}\n\n\t\t// Default rendering uses our box\n\t\tthis.addChild(this.box);\n\t\tthis.box.clear();\n\n\t\t// Default rendering: label + content\n\t\tconst label = theme.fg(\"customMessageLabel\", `\\x1b[1m[${this.message.customType}]\\x1b[22m`);\n\t\tthis.box.addChild(new Text(label, 0, 0));\n\t\tthis.box.addChild(new Spacer(1));\n\n\t\t// Extract text content\n\t\tlet text: string;\n\t\tif (typeof this.message.content === \"string\") {\n\t\t\ttext = this.message.content;\n\t\t} else {\n\t\t\ttext = this.message.content\n\t\t\t\t.filter((c): c is TextContent => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\\n\");\n\t\t}\n\n\t\tthis.box.addChild(\n\t\t\tnew Markdown(text, 0, 0, this.markdownTheme, {\n\t\t\t\tcolor: (text: string) => theme.fg(\"customMessageText\", text),\n\t\t\t}),\n\t\t);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/custom-message.js b/dist/modes/interactive/components/custom-message.js new file mode 100644 index 0000000..7c6fb37 --- /dev/null +++ b/dist/modes/interactive/components/custom-message.js @@ -0,0 +1,87 @@ +import { Box, Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui"; +import { getMarkdownTheme, theme } from "../theme/theme.js"; +/** + * Component that renders a custom message entry from extensions. + * Uses distinct styling to differentiate from user messages. + */ +export class CustomMessageComponent extends Container { + message; + customRenderer; + box; + customComponent; + markdownTheme; + _expanded = false; + outputPad; + constructor(message, customRenderer, markdownTheme = getMarkdownTheme(), outputPad = 1) { + super(); + this.message = message; + this.customRenderer = customRenderer; + this.markdownTheme = markdownTheme; + this.outputPad = outputPad; + this.addChild(new Spacer(1)); + // Create box with purple background (used for default rendering) + this.box = new Box(1, 1, (t) => theme.bg("customMessageBg", t)); + this.rebuild(); + } + setExpanded(expanded) { + if (this._expanded !== expanded) { + this._expanded = expanded; + this.rebuild(); + } + } + setOutputPad(outputPad) { + if (this.outputPad !== outputPad) { + this.outputPad = outputPad; + this.rebuild(); + } + } + invalidate() { + super.invalidate(); + this.rebuild(); + } + rebuild() { + // Remove previous content component + if (this.customComponent) { + this.removeChild(this.customComponent); + this.customComponent = undefined; + } + this.removeChild(this.box); + // Try custom renderer first - it handles its own styling + if (this.customRenderer) { + try { + const component = this.customRenderer(this.message, { expanded: this._expanded, outputPad: this.outputPad }, theme); + if (component) { + // Custom renderer provides its own styled component + this.customComponent = component; + this.addChild(component); + return; + } + } + catch { + // Fall through to default rendering + } + } + // Default rendering uses our box + this.addChild(this.box); + this.box.clear(); + // Default rendering: label + content + const label = theme.fg("customMessageLabel", `\x1b[1m[${this.message.customType}]\x1b[22m`); + this.box.addChild(new Text(label, 0, 0)); + this.box.addChild(new Spacer(1)); + // Extract text content + let text; + if (typeof this.message.content === "string") { + text = this.message.content; + } + else { + text = this.message.content + .filter((c) => c.type === "text") + .map((c) => c.text) + .join("\n"); + } + this.box.addChild(new Markdown(text, 0, 0, this.markdownTheme, { + color: (text) => theme.fg("customMessageText", text), + })); + } +} +//# sourceMappingURL=custom-message.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/custom-message.js.map b/dist/modes/interactive/components/custom-message.js.map new file mode 100644 index 0000000..bc7565d --- /dev/null +++ b/dist/modes/interactive/components/custom-message.js.map @@ -0,0 +1 @@ +{"version":3,"file":"custom-message.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/custom-message.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,QAAQ,EAAsB,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAGpG,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE5D;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,SAAS;IAC5C,OAAO,CAAyB;IAChC,cAAc,CAAmB;IACjC,GAAG,CAAM;IACT,eAAe,CAAa;IAC5B,aAAa,CAAgB;IAC7B,SAAS,GAAG,KAA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AM,CAAC;YACP,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO;iBACzB,MAAM,CAAC,CAAC,CAAC,EAAoB,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;iBAClD,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;iBAClB,IAAI,CAAC,IAAI,CAAC,CAAC;QACd,CAAC;QAED,IAAI,CAAC,GAAG,CAAC,QAAQ,CAChB,IAAI,QAAQ,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,aAAa,EAAE;YAC5C,KAAK,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,mBAAmB,EAAE,IAAI,CAAC;SAC5D,CAAC,CACF,CAAC;IAAA,CACF;CACD","sourcesContent":["import type { TextContent } from \"@earendil-works/pi-ai\";\nimport type { Component } from \"@earendil-works/pi-tui\";\nimport { Box, Container, Markdown, type MarkdownTheme, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { MessageRenderer } from \"../../../core/extensions/types.ts\";\nimport type { CustomMessage } from \"../../../core/messages.ts\";\nimport { getMarkdownTheme, theme } from \"../theme/theme.ts\";\n\n/**\n * Component that renders a custom message entry from extensions.\n * Uses distinct styling to differentiate from user messages.\n */\nexport class CustomMessageComponent extends Container {\n\tprivate message: CustomMessage;\n\tprivate customRenderer?: MessageRenderer;\n\tprivate box: Box;\n\tprivate customComponent?: Component;\n\tprivate markdownTheme: MarkdownTheme;\n\tprivate _expanded = false;\n\tprivate outputPad: number;\n\n\tconstructor(\n\t\tmessage: CustomMessage,\n\t\tcustomRenderer?: MessageRenderer,\n\t\tmarkdownTheme: MarkdownTheme = getMarkdownTheme(),\n\t\toutputPad = 1,\n\t) {\n\t\tsuper();\n\t\tthis.message = message;\n\t\tthis.customRenderer = customRenderer;\n\t\tthis.markdownTheme = markdownTheme;\n\t\tthis.outputPad = outputPad;\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create box with purple background (used for default rendering)\n\t\tthis.box = new Box(1, 1, (t) => theme.bg(\"customMessageBg\", t));\n\n\t\tthis.rebuild();\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tif (this._expanded !== expanded) {\n\t\t\tthis._expanded = expanded;\n\t\t\tthis.rebuild();\n\t\t}\n\t}\n\n\tsetOutputPad(outputPad: number): void {\n\t\tif (this.outputPad !== outputPad) {\n\t\t\tthis.outputPad = outputPad;\n\t\t\tthis.rebuild();\n\t\t}\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.rebuild();\n\t}\n\n\tprivate rebuild(): void {\n\t\t// Remove previous content component\n\t\tif (this.customComponent) {\n\t\t\tthis.removeChild(this.customComponent);\n\t\t\tthis.customComponent = undefined;\n\t\t}\n\t\tthis.removeChild(this.box);\n\n\t\t// Try custom renderer first - it handles its own styling\n\t\tif (this.customRenderer) {\n\t\t\ttry {\n\t\t\t\tconst component = this.customRenderer(\n\t\t\t\t\tthis.message,\n\t\t\t\t\t{ expanded: this._expanded, outputPad: this.outputPad },\n\t\t\t\t\ttheme,\n\t\t\t\t);\n\t\t\t\tif (component) {\n\t\t\t\t\t// Custom renderer provides its own styled component\n\t\t\t\t\tthis.customComponent = component;\n\t\t\t\t\tthis.addChild(component);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Fall through to default rendering\n\t\t\t}\n\t\t}\n\n\t\t// Default rendering uses our box\n\t\tthis.addChild(this.box);\n\t\tthis.box.clear();\n\n\t\t// Default rendering: label + content\n\t\tconst label = theme.fg(\"customMessageLabel\", `\\x1b[1m[${this.message.customType}]\\x1b[22m`);\n\t\tthis.box.addChild(new Text(label, 0, 0));\n\t\tthis.box.addChild(new Spacer(1));\n\n\t\t// Extract text content\n\t\tlet text: string;\n\t\tif (typeof this.message.content === \"string\") {\n\t\t\ttext = this.message.content;\n\t\t} else {\n\t\t\ttext = this.message.content\n\t\t\t\t.filter((c): c is TextContent => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\\n\");\n\t\t}\n\n\t\tthis.box.addChild(\n\t\t\tnew Markdown(text, 0, 0, this.markdownTheme, {\n\t\t\t\tcolor: (text: string) => theme.fg(\"customMessageText\", text),\n\t\t\t}),\n\t\t);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/daxnuts.d.ts b/dist/modes/interactive/components/daxnuts.d.ts new file mode 100644 index 0000000..bcb5dcb --- /dev/null +++ b/dist/modes/interactive/components/daxnuts.d.ts @@ -0,0 +1,23 @@ +/** + * POWERED BY DAXNUTS - Easter egg for OpenCode + Kimi K2.5 + * + * A heartfelt tribute to dax (@thdxr) for providing free Kimi K2.5 access via OpenCode. + */ +import type { Component, TUI } from "@earendil-works/pi-tui"; +export declare class DaxnutsComponent implements Component { + private ui; + private image; + private interval; + private tick; + private maxTicks; + private cachedLines; + private cachedWidth; + private cachedTick; + constructor(ui: TUI); + invalidate(): void; + private startAnimation; + private stopAnimation; + render(width: number): string[]; + dispose(): void; +} +//# sourceMappingURL=daxnuts.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/daxnuts.d.ts.map b/dist/modes/interactive/components/daxnuts.d.ts.map new file mode 100644 index 0000000..d9d1ea4 --- /dev/null +++ b/dist/modes/interactive/components/daxnuts.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"daxnuts.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/daxnuts.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAkD7D,qBAAa,gBAAiB,YAAW,SAAS;IACjD,OAAO,CAAC,EAAE,CAAM;IAChB,OAAO,CAAC,KAAK,CAAW;IACxB,OAAO,CAAC,QAAQ,CAA+C;IAC/D,OAAO,CAAC,IAAI,CAAK;IACjB,OAAO,CAAC,QAAQ,CAAM;IACtB,OAAO,CAAC,WAAW,CAAgB;IACnC,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,UAAU,CAAM;IAExB,YAAY,EAAE,EAAE,GAAG,EAIlB;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,OAAO,CAAC,cAAc;IAWtB,OAAO,CAAC,aAAa;IAOrB,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAgE9B;IAED,OAAO,IAAI,IAAI,CAEd;CACD","sourcesContent":["/**\n * POWERED BY DAXNUTS - Easter egg for OpenCode + Kimi K2.5\n *\n * A heartfelt tribute to dax (@thdxr) for providing free Kimi K2.5 access via OpenCode.\n */\n\nimport type { Component, TUI } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\n\n// 32x32 RGB image of dax, hex encoded (3 bytes per pixel)\nconst DAX_HEX =\n\t\"bbbab8b9b9b6b9b8b5bcbbb8b8b7b4b7b5b2b6b5b2b8b7b4b7b6b3b6b4b1bdbcb8bab8b6bbb8b5b8b5b1bbb8b4c2bebbc1bebac0bdbabfbcb9c1bebabfbebbc0bfbcc0bdbabbb8b5c1bfbcbfbcb8bbb9b6bfbcb8c2bfbcc1bfbcbfbbb8bdb9b6b8b7b5b9b8b5b8b8b5b5b5b2b6b5b2b8b7b4b9b8b5b9b8b5b6b5b3bab8b5bcbab7bbb9b6bbb8b5bfb9b5bdb2abbcb0a8beb2aabeb5afbfbab6bebab7c0bfbcbebdbabebbb8c0bdbabfbebbc2bebbbdbab7c3c0bdc3c0bdc1bebbc2bebabfbcb8bab9b6b7b6b3b2b1aeb6b5b2b5b4b1b5b4b2b6b5b2b7b6b4b9b8b6b7b6b3bbbab7b2afaba5988fb49e90b09481b79a88b39683b09583b7a395bfb6b0c0bdbabdbbb8bebcb9c1bfbcc0bebbbdbab7bebbb8c2bfbcc0bdbac0bcb9bdb9b6c0bcb8b5b4b2b4b3b0bab9b6b9b9b6b5b4b1b5b4b1b6b5b3b9b8b5b9b8b6b9b8b6b2aeaa968174a6836eaa856eab846eaf8973ac8973b08f79b18f7ab39786b7a89dbbb3aebfbab6c2c0bdbebcb9bfbdbac3c1bdc2bebbc0bcb9bdb9b6c1bdbabfbbb8b4b3b0b9b8b5b8b7b5b4b3b1b5b4b1b8b7b4b8b7b5bab9b6bbbab7b1afad8c7a719d735ca47860a87d65a98069ae8972ae8c75af8d77aa826ba98067aa8974b39e90b6a79dbbb2adc0bdbac1bfbdbfbbb8c1bdb9bebab6c0bdb9bfbbb8c1bdbab4b2b0b7b6b4b7b6b3b4b2b0bab9b7b6b5b2b6b5b2bab9b6bab9b6958c87977663aa836bac8772b08f7aad8c77b2917db0917db0907cac8971a77d64a87f67ac8972b29887b8a89dbfbab5bfbdbac1bebac0bcb9c0bcb9c0bcb9c1bebabebab7b8b7b4b7b6b4b5b4b1b5b4b2b7b6b3b5b4b2bab9b7bab9b6b4b1ada88f7fad8973ae8d78b19684b19685b29786b69a89b29582b1917daa856ea87e66a97e66ad866ea9826baf9280b8ada6bdbbb8bebab7bfbbb8c1bdbabfbbb8bcb8b4bcb8b5b6b4b2b7b5b3b6b5b2b8b7b4b3b2afb8b7b4b6b5b2b3b2b0b3a59aab856fad8d78b0917eb19886b49b8bb49a89b39785b0917eaf8f7cab866fa77d65a77a61a87d64a9816ab08f79b5a296c1bcb8c3bfbcc2bebbbebab7bfbbb7bdbab6c2bebab8b7b4b7b6b4b6b5b3b7b6b3b6b5b2b9b8b6b4b3b1b6b1acac8f7ca9826bae8f7aaf9583b49c8cb49c8bb79d8cb59987b19380ad8e79ae8c77af8e78ac8771a3775faa826bae8972b39888bbb6b2bebbb8bfbbb8bfbbb8c0bdb9bebbb7c0bdb9b6b5b2b9b8b5b4b3b1b8b7b5b4b3b0b7b6b4b6b5b3b1a7a0aa8772a77d65a88570b49887b19b8d9c887c907a6d987f71aa907faf917daf8e7aad8c78ac8b77a8836ca9836cac8770b49b8abdb6b2c0bcb9c0bdb9bfbbb8bebab7bfbcb9bebab7b9b8b6b5b4b2b9b8b5b8b7b5b8b7b4b7b6b4b5b4b2b3a9a2ad8973a1755da9856fb398858c776a65544b776358725d526e594d9c7f6eb1907ba68672ad8e7aab8771ac856db18f79b3a092beb9b5c1bdbabdb9b5bebab7bfbbb7bebab7bcb9b6b7b6b4b6b6b3b8b7b4b5b4b2b8b6b4b7b6b3b4b3b0b4aba4a6826ba3775fb08e79b19584a88e7daa8e7db29481ad8f7c997e6da38674ac8d79ac8e7aae917f9a7c6a896a599a7c6ab3a398c1bdbabdb9b6bcb8b5bebab6bebab7bdb9b5bdb9b6b5b4b1b7b5b3b5b4b2b7b6b3b7b6b4b3b3b0b3b2b0b4aca5a7846fa97f68ae8f7bae9383b59c8bb2937fae8e79ac8b76af927eaf927eb29683b39885b2988891786a72594c6e594d978d86bdbab7bab7b3c0bcb9c0bcb9bebab7bebbb7bdb9b6b3b2b0b4b3b0b5b4b2b4b4b1b4b3b1b4b3b1b4b3b0b6ada5aa8670a57a62ad8e7ab29b8cb69d8dab856fa9826aa88069ab8771af907db49987b19684b29886b59987b39480b09787b5a9a1bcb8b5bebab7bdb9b5bebab7bfbbb8bfbbb7bbb7b4b3b2afb8b7b5b8b7b5b3b2b0b5b4b2b6b5b3b6b4b1afa299a98975a9826baf907cb39988b49a89af8e7aac8973aa856eaf8c74b1917dae907dac907db39988b29785b49785b7a090b9aca3bfbab7bcb8b5bdb9b6bcb8b4bcb8b5bdb9b5bcb8b4b5b4b2b6b5b3b4b3b0b4b3b0b9b8b5b8b6b4908b88887467aa8f7ea78976ad8973b08b74b59885b69e8eb29888b1917cb1917db1937fae907cb19686b39a8ab29886b59b8ab8a192b6aaa3b7b2afbcb8b4bcb8b5bbb7b4c0bcb9bebab7c0bcb9b6b5b2b6b5b3b4b3b0bab9b7b7b6b4b1b0ae7b716ba083709b806f716158967764b08870b29481b69b8ab69f8fb39a89b69f90b49d8db39a89b29988b49c8cb6a090b8a496baa49593867f8f8986bfbbb7bdb9b5bcb7b4bab6b3b9b5b2bab6b2b4b3b1b3b3b0b6b5b3b8b7b5b4b2b0a7a5a38f837dae917ea084725a504c63544da28370b39784b59e8db2a093a698909b918b998e8790857e95877dad998bb39c8cb5a091b9a2938d827c95908dbebab6bbb7b3bdbab7bbb7b4bdb9b6bbb7b4b4b3b0b5b4b1b8b7b5b6b5b3b8b8b5b4b2af968f8ab29a8bab9485544b483a323073655d96887f70655f61595547403e453e3c453f3d57504f655e5b90847db39c8db7a090b6a09189807aaba6a3bdb9b6c0bcb9bebab7bcb7b4bebab7bbb7b4b3b2b0b6b5b3b2b1afb7b6b4b8b7b4b5b4b1aeaba8b5a89fac998d4d44412d25244d46444e4744322b293a3230423937433a37352d2a59504c534b48524a48988a81b59f8fb19c8d827974b2afacbdb9b5bcb8b4bdb9b5bcb8b5bdb9b6bab6b2b8b7b5b5b4b2b6b6b3b9b8b5b7b6b3b6b5b2b8b6b3b9b4b1b2a9a26c64612d25242d2625312a28352d2c453d3a78675c8d7a6ea09792aea6a0615854332b29524a479f8e82b09d90a49b96c1bdb9bebab7bfbbb8bbb8b4b9b5b1b8b4b0b9b4b0b7b6b4b8b7b5b8b7b4b6b5b3b8b6b3bab9b6b9b8b5b4b3b0b7b5b2a5a29f453d3b261e1d261f1e2e2625413936857268977865b19482b5a69caca5a07c7572453d3b746963a0948cc5bfbbc0bbb8beb9b6bbb7b3bbb6b3b7b3afb8b4b0b9b5b1b7b6b3b6b5b3b5b4b2b5b4b2b7b6b3b7b6b3b8b6b3b4b2afb7b6b3b3b1ae6d6765251f1e1e18172a22212d2523443b3971625ab19888b09482a89182877e792c25243e3634766d6abeb9b5bfbbb7bebab6bcb7b3bbb6b3b9b5b1b7b3afb8b4b0b4b3b0b5b4b1b5b4b1b4b3b1b5b4b2b8b6b4b5b3b0b9b6b4b5b4b1b6b4b27f79762a2322221c1b2d2524221b1a443e3c47413f6f676281766f867971675e5a3e37352a222166605dbab7b3bdb9b5beb9b5bcb7b3bcb7b3b9b4b0bab6b2bab6b2b5b3b0b6b4b2b3b2afb7b6b3b4b4b1b4b3b0b6b4b1b5b4b1b4b3b0b9b6b29a8c8252474230292828201f181212322c2c231e1d1c16162c26252923222d26252d2523332b2a8e8885bcb8b5bcb7b3bbb6b2bcb7b3b9b4b1b9b5b1b7b2afb7b2ae7a838e9b9b9caeadacb3b2b0b3b2afb7b7b4b6b5b3b6b6b3b7b6b3b9ada4a991808e7b6f50453f2b24231a14142923221f19181d17161f18182620201d17162a22215d5654b7b3b0bbb7b3bbb6b2b8b4b0bab5b1bbb6b2bab5b1b8b4b0bab6b22c496b4c5d735f68766e727a828285929090adaba8b7b2aeb6a59ab39682a28470a387748e76674e403a1a14141d1716181211221c1c1f1918221c1b2f2827342d2c8d8884bab6b3b9b5b2bab5b1bab5b1b9b4b0bab6b2b8b4b0b9b4b0b7b2ae325e8b365f8a3a5d833f5b7a545f70646469706b6aa08f84b08e78b18e769f7e689e7f6b9e816d907766584940362d2a1c1615201b1a1a1413201a1a251e1d393331a39e9bbab5b1bcb7b3bab6b2b8b3afb8b4b0b9b4b0b9b4b1bab5b2b5b0ac3d6c9843729d44719c426e98415f805a64716f6a699d8677b1927eb3947faa89749d7a649f7f6ba487749e837186716454463f2c25231e181837302e3a33317a7471beb9b6bcb8b4bbb6b2b6b2aebab5b1b9b5b1b8b3afbab6b2b6b1adb5aeaa4877a14c7aa44e7ba345719a3a5d80586b7f767475927b6eb1927faf8e79b08e78a78169a07861a17f6aa58570a688749b83738270666f66618a8480a49e99b7b2aebab6b2bcb8b4b9b5b1b7b2aebab5b1b9b4b0b6b1aeb6b1adb2aca8b2aca84876a04a78a2517fa74771973a5d80405c7a6161677c695fac8a75b08d77b4917aaf8971ad876fa5816aa6846ea78670a98a76ac9484ab9f96b2aca8bdb8b4bcb7b3bcb8b4bcb8b4b8b3afb7b2aeb9b4b0b8b3afb8b2aeb6afabb3aeaab2aeaa4878a14b7aa34c7ba44a759b3d63873b5f825b67766f5f569c7e6caf8c77b18f79b28f78b5927caf8e78a98872aa8a76a98a76ac917fada199b7b0acb9b3afbfb9b5c1bab6bdb6b2b8b3afbab5b1b9b4b0b6afabb7b1adb3ada9b3aeaab0aba8\";\n\nconst WIDTH = 32;\nconst HEIGHT = 32;\n\nfunction parseImage(): number[][][] {\n\tconst pixels: number[][][] = [];\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\tconst row: number[][] = [];\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tconst idx = (y * WIDTH + x) * 6;\n\t\t\tconst r = parseInt(DAX_HEX.slice(idx, idx + 2), 16);\n\t\t\tconst g = parseInt(DAX_HEX.slice(idx + 2, idx + 4), 16);\n\t\t\tconst b = parseInt(DAX_HEX.slice(idx + 4, idx + 6), 16);\n\t\t\trow.push([r, g, b]);\n\t\t}\n\t\tpixels.push(row);\n\t}\n\treturn pixels;\n}\n\nfunction rgb(r: number, g: number, b: number, bg = false): string {\n\treturn `\\x1b[${bg ? 48 : 38};2;${r};${g};${b}m`;\n}\n\nconst RESET = \"\\x1b[0m\";\n\nfunction buildImage(): string[] {\n\tconst pixels = parseImage();\n\tconst lines: string[] = [];\n\n\t// Use half-block chars: ▄ with bg=top pixel, fg=bottom pixel\n\tfor (let row = 0; row < HEIGHT; row += 2) {\n\t\tlet line = \"\";\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tconst top = pixels[row][x];\n\t\t\tconst bottom = pixels[row + 1]?.[x] ?? top;\n\t\t\tline += `${rgb(bottom[0], bottom[1], bottom[2])}${rgb(top[0], top[1], top[2], true)}▄`;\n\t\t}\n\t\tline += RESET;\n\t\tlines.push(line);\n\t}\n\treturn lines;\n}\n\nexport class DaxnutsComponent implements Component {\n\tprivate ui: TUI;\n\tprivate image: string[];\n\tprivate interval: ReturnType | null = null;\n\tprivate tick = 0;\n\tprivate maxTicks = 25; // ~2 seconds at 80ms\n\tprivate cachedLines: string[] = [];\n\tprivate cachedWidth = 0;\n\tprivate cachedTick = -1;\n\n\tconstructor(ui: TUI) {\n\t\tthis.ui = ui;\n\t\tthis.image = buildImage();\n\t\tthis.startAnimation();\n\t}\n\n\tinvalidate(): void {\n\t\tthis.cachedWidth = 0;\n\t}\n\n\tprivate startAnimation(): void {\n\t\tthis.interval = setInterval(() => {\n\t\t\tthis.tick++;\n\t\t\tif (this.tick >= this.maxTicks) {\n\t\t\t\tthis.stopAnimation();\n\t\t\t}\n\t\t\tthis.cachedWidth = 0;\n\t\t\tthis.ui.requestRender();\n\t\t}, 80);\n\t}\n\n\tprivate stopAnimation(): void {\n\t\tif (this.interval) {\n\t\t\tclearInterval(this.interval);\n\t\t\tthis.interval = null;\n\t\t}\n\t}\n\n\trender(width: number): string[] {\n\t\tif (width === this.cachedWidth && this.cachedTick === this.tick) {\n\t\t\treturn this.cachedLines;\n\t\t}\n\n\t\tconst t = theme;\n\t\tconst lines: string[] = [];\n\n\t\tconst center = (s: string) => {\n\t\t\tconst visible = s.replace(/\\x1b\\[[0-9;]*m/g, \"\").length;\n\t\t\tconst left = Math.max(0, Math.floor((width - visible) / 2));\n\t\t\treturn \" \".repeat(left) + s;\n\t\t};\n\n\t\tlines.push(\"\");\n\n\t\t// Scanline reveal effect: show rows progressively\n\t\tconst revealedRows = Math.min(\n\t\t\tthis.image.length,\n\t\t\tMath.floor((this.tick / this.maxTicks) * (this.image.length + 3)),\n\t\t);\n\n\t\tfor (let i = 0; i < this.image.length; i++) {\n\t\t\tif (i < revealedRows) {\n\t\t\t\tlines.push(center(this.image[i]));\n\t\t\t} else {\n\t\t\t\t// Show scan line\n\t\t\t\tif (i === revealedRows) {\n\t\t\t\t\tconst scanline = \"▓\".repeat(WIDTH);\n\t\t\t\t\tlines.push(center(rgb(100, 200, 255) + scanline + RESET));\n\t\t\t\t} else {\n\t\t\t\t\tlines.push(center(\" \".repeat(WIDTH)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlines.push(\"\");\n\n\t\t// Fade in text after image is revealed\n\t\tconst textPhase = Math.max(0, this.tick - this.maxTicks * 0.6);\n\t\tif (textPhase > 0 || this.tick >= this.maxTicks) {\n\t\t\tlines.push(center(t.fg(\"accent\", \"Free Kimi K2.5 via OpenCode Zen\")));\n\t\t\tlines.push(center(t.fg(\"success\", '\"Powered by daxnuts\"')));\n\t\t\tlines.push(center(t.fg(\"muted\", \"— @thdxr\")));\n\t\t} else {\n\t\t\tlines.push(\"\");\n\t\t\tlines.push(\"\");\n\t\t\tlines.push(\"\");\n\t\t}\n\n\t\tlines.push(\"\");\n\t\tif (textPhase > 2 || this.tick >= this.maxTicks) {\n\t\t\tlines.push(center(t.fg(\"dim\", \"Try OpenCode\")));\n\t\t\tlines.push(center(t.fg(\"mdLink\", \"https://mistral.ai/news/mistral-vibe-2-0\")));\n\t\t} else {\n\t\t\tlines.push(\"\");\n\t\t\tlines.push(\"\");\n\t\t}\n\t\tlines.push(\"\");\n\n\t\tthis.cachedLines = lines;\n\t\tthis.cachedWidth = width;\n\t\tthis.cachedTick = this.tick;\n\t\treturn lines;\n\t}\n\n\tdispose(): void {\n\t\tthis.stopAnimation();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/daxnuts.js b/dist/modes/interactive/components/daxnuts.js new file mode 100644 index 0000000..134fca8 --- /dev/null +++ b/dist/modes/interactive/components/daxnuts.js @@ -0,0 +1,140 @@ +/** + * POWERED BY DAXNUTS - Easter egg for OpenCode + Kimi K2.5 + * + * A heartfelt tribute to dax (@thdxr) for providing free Kimi K2.5 access via OpenCode. + */ +import { theme } from "../theme/theme.js"; +// 32x32 RGB image of dax, hex encoded (3 bytes per pixel) +const DAX_HEX = "bbbab8b9b9b6b9b8b5bcbbb8b8b7b4b7b5b2b6b5b2b8b7b4b7b6b3b6b4b1bdbcb8bab8b6bbb8b5b8b5b1bbb8b4c2bebbc1bebac0bdbabfbcb9c1bebabfbebbc0bfbcc0bdbabbb8b5c1bfbcbfbcb8bbb9b6bfbcb8c2bfbcc1bfbcbfbbb8bdb9b6b8b7b5b9b8b5b8b8b5b5b5b2b6b5b2b8b7b4b9b8b5b9b8b5b6b5b3bab8b5bcbab7bbb9b6bbb8b5bfb9b5bdb2abbcb0a8beb2aabeb5afbfbab6bebab7c0bfbcbebdbabebbb8c0bdbabfbebbc2bebbbdbab7c3c0bdc3c0bdc1bebbc2bebabfbcb8bab9b6b7b6b3b2b1aeb6b5b2b5b4b1b5b4b2b6b5b2b7b6b4b9b8b6b7b6b3bbbab7b2afaba5988fb49e90b09481b79a88b39683b09583b7a395bfb6b0c0bdbabdbbb8bebcb9c1bfbcc0bebbbdbab7bebbb8c2bfbcc0bdbac0bcb9bdb9b6c0bcb8b5b4b2b4b3b0bab9b6b9b9b6b5b4b1b5b4b1b6b5b3b9b8b5b9b8b6b9b8b6b2aeaa968174a6836eaa856eab846eaf8973ac8973b08f79b18f7ab39786b7a89dbbb3aebfbab6c2c0bdbebcb9bfbdbac3c1bdc2bebbc0bcb9bdb9b6c1bdbabfbbb8b4b3b0b9b8b5b8b7b5b4b3b1b5b4b1b8b7b4b8b7b5bab9b6bbbab7b1afad8c7a719d735ca47860a87d65a98069ae8972ae8c75af8d77aa826ba98067aa8974b39e90b6a79dbbb2adc0bdbac1bfbdbfbbb8c1bdb9bebab6c0bdb9bfbbb8c1bdbab4b2b0b7b6b4b7b6b3b4b2b0bab9b7b6b5b2b6b5b2bab9b6bab9b6958c87977663aa836bac8772b08f7aad8c77b2917db0917db0907cac8971a77d64a87f67ac8972b29887b8a89dbfbab5bfbdbac1bebac0bcb9c0bcb9c0bcb9c1bebabebab7b8b7b4b7b6b4b5b4b1b5b4b2b7b6b3b5b4b2bab9b7bab9b6b4b1ada88f7fad8973ae8d78b19684b19685b29786b69a89b29582b1917daa856ea87e66a97e66ad866ea9826baf9280b8ada6bdbbb8bebab7bfbbb8c1bdbabfbbb8bcb8b4bcb8b5b6b4b2b7b5b3b6b5b2b8b7b4b3b2afb8b7b4b6b5b2b3b2b0b3a59aab856fad8d78b0917eb19886b49b8bb49a89b39785b0917eaf8f7cab866fa77d65a77a61a87d64a9816ab08f79b5a296c1bcb8c3bfbcc2bebbbebab7bfbbb7bdbab6c2bebab8b7b4b7b6b4b6b5b3b7b6b3b6b5b2b9b8b6b4b3b1b6b1acac8f7ca9826bae8f7aaf9583b49c8cb49c8bb79d8cb59987b19380ad8e79ae8c77af8e78ac8771a3775faa826bae8972b39888bbb6b2bebbb8bfbbb8bfbbb8c0bdb9bebbb7c0bdb9b6b5b2b9b8b5b4b3b1b8b7b5b4b3b0b7b6b4b6b5b3b1a7a0aa8772a77d65a88570b49887b19b8d9c887c907a6d987f71aa907faf917daf8e7aad8c78ac8b77a8836ca9836cac8770b49b8abdb6b2c0bcb9c0bdb9bfbbb8bebab7bfbcb9bebab7b9b8b6b5b4b2b9b8b5b8b7b5b8b7b4b7b6b4b5b4b2b3a9a2ad8973a1755da9856fb398858c776a65544b776358725d526e594d9c7f6eb1907ba68672ad8e7aab8771ac856db18f79b3a092beb9b5c1bdbabdb9b5bebab7bfbbb7bebab7bcb9b6b7b6b4b6b6b3b8b7b4b5b4b2b8b6b4b7b6b3b4b3b0b4aba4a6826ba3775fb08e79b19584a88e7daa8e7db29481ad8f7c997e6da38674ac8d79ac8e7aae917f9a7c6a896a599a7c6ab3a398c1bdbabdb9b6bcb8b5bebab6bebab7bdb9b5bdb9b6b5b4b1b7b5b3b5b4b2b7b6b3b7b6b4b3b3b0b3b2b0b4aca5a7846fa97f68ae8f7bae9383b59c8bb2937fae8e79ac8b76af927eaf927eb29683b39885b2988891786a72594c6e594d978d86bdbab7bab7b3c0bcb9c0bcb9bebab7bebbb7bdb9b6b3b2b0b4b3b0b5b4b2b4b4b1b4b3b1b4b3b1b4b3b0b6ada5aa8670a57a62ad8e7ab29b8cb69d8dab856fa9826aa88069ab8771af907db49987b19684b29886b59987b39480b09787b5a9a1bcb8b5bebab7bdb9b5bebab7bfbbb8bfbbb7bbb7b4b3b2afb8b7b5b8b7b5b3b2b0b5b4b2b6b5b3b6b4b1afa299a98975a9826baf907cb39988b49a89af8e7aac8973aa856eaf8c74b1917dae907dac907db39988b29785b49785b7a090b9aca3bfbab7bcb8b5bdb9b6bcb8b4bcb8b5bdb9b5bcb8b4b5b4b2b6b5b3b4b3b0b4b3b0b9b8b5b8b6b4908b88887467aa8f7ea78976ad8973b08b74b59885b69e8eb29888b1917cb1917db1937fae907cb19686b39a8ab29886b59b8ab8a192b6aaa3b7b2afbcb8b4bcb8b5bbb7b4c0bcb9bebab7c0bcb9b6b5b2b6b5b3b4b3b0bab9b7b7b6b4b1b0ae7b716ba083709b806f716158967764b08870b29481b69b8ab69f8fb39a89b69f90b49d8db39a89b29988b49c8cb6a090b8a496baa49593867f8f8986bfbbb7bdb9b5bcb7b4bab6b3b9b5b2bab6b2b4b3b1b3b3b0b6b5b3b8b7b5b4b2b0a7a5a38f837dae917ea084725a504c63544da28370b39784b59e8db2a093a698909b918b998e8790857e95877dad998bb39c8cb5a091b9a2938d827c95908dbebab6bbb7b3bdbab7bbb7b4bdb9b6bbb7b4b4b3b0b5b4b1b8b7b5b6b5b3b8b8b5b4b2af968f8ab29a8bab9485544b483a323073655d96887f70655f61595547403e453e3c453f3d57504f655e5b90847db39c8db7a090b6a09189807aaba6a3bdb9b6c0bcb9bebab7bcb7b4bebab7bbb7b4b3b2b0b6b5b3b2b1afb7b6b4b8b7b4b5b4b1aeaba8b5a89fac998d4d44412d25244d46444e4744322b293a3230423937433a37352d2a59504c534b48524a48988a81b59f8fb19c8d827974b2afacbdb9b5bcb8b4bdb9b5bcb8b5bdb9b6bab6b2b8b7b5b5b4b2b6b6b3b9b8b5b7b6b3b6b5b2b8b6b3b9b4b1b2a9a26c64612d25242d2625312a28352d2c453d3a78675c8d7a6ea09792aea6a0615854332b29524a479f8e82b09d90a49b96c1bdb9bebab7bfbbb8bbb8b4b9b5b1b8b4b0b9b4b0b7b6b4b8b7b5b8b7b4b6b5b3b8b6b3bab9b6b9b8b5b4b3b0b7b5b2a5a29f453d3b261e1d261f1e2e2625413936857268977865b19482b5a69caca5a07c7572453d3b746963a0948cc5bfbbc0bbb8beb9b6bbb7b3bbb6b3b7b3afb8b4b0b9b5b1b7b6b3b6b5b3b5b4b2b5b4b2b7b6b3b7b6b3b8b6b3b4b2afb7b6b3b3b1ae6d6765251f1e1e18172a22212d2523443b3971625ab19888b09482a89182877e792c25243e3634766d6abeb9b5bfbbb7bebab6bcb7b3bbb6b3b9b5b1b7b3afb8b4b0b4b3b0b5b4b1b5b4b1b4b3b1b5b4b2b8b6b4b5b3b0b9b6b4b5b4b1b6b4b27f79762a2322221c1b2d2524221b1a443e3c47413f6f676281766f867971675e5a3e37352a222166605dbab7b3bdb9b5beb9b5bcb7b3bcb7b3b9b4b0bab6b2bab6b2b5b3b0b6b4b2b3b2afb7b6b3b4b4b1b4b3b0b6b4b1b5b4b1b4b3b0b9b6b29a8c8252474230292828201f181212322c2c231e1d1c16162c26252923222d26252d2523332b2a8e8885bcb8b5bcb7b3bbb6b2bcb7b3b9b4b1b9b5b1b7b2afb7b2ae7a838e9b9b9caeadacb3b2b0b3b2afb7b7b4b6b5b3b6b6b3b7b6b3b9ada4a991808e7b6f50453f2b24231a14142923221f19181d17161f18182620201d17162a22215d5654b7b3b0bbb7b3bbb6b2b8b4b0bab5b1bbb6b2bab5b1b8b4b0bab6b22c496b4c5d735f68766e727a828285929090adaba8b7b2aeb6a59ab39682a28470a387748e76674e403a1a14141d1716181211221c1c1f1918221c1b2f2827342d2c8d8884bab6b3b9b5b2bab5b1bab5b1b9b4b0bab6b2b8b4b0b9b4b0b7b2ae325e8b365f8a3a5d833f5b7a545f70646469706b6aa08f84b08e78b18e769f7e689e7f6b9e816d907766584940362d2a1c1615201b1a1a1413201a1a251e1d393331a39e9bbab5b1bcb7b3bab6b2b8b3afb8b4b0b9b4b0b9b4b1bab5b2b5b0ac3d6c9843729d44719c426e98415f805a64716f6a699d8677b1927eb3947faa89749d7a649f7f6ba487749e837186716454463f2c25231e181837302e3a33317a7471beb9b6bcb8b4bbb6b2b6b2aebab5b1b9b5b1b8b3afbab6b2b6b1adb5aeaa4877a14c7aa44e7ba345719a3a5d80586b7f767475927b6eb1927faf8e79b08e78a78169a07861a17f6aa58570a688749b83738270666f66618a8480a49e99b7b2aebab6b2bcb8b4b9b5b1b7b2aebab5b1b9b4b0b6b1aeb6b1adb2aca8b2aca84876a04a78a2517fa74771973a5d80405c7a6161677c695fac8a75b08d77b4917aaf8971ad876fa5816aa6846ea78670a98a76ac9484ab9f96b2aca8bdb8b4bcb7b3bcb8b4bcb8b4b8b3afb7b2aeb9b4b0b8b3afb8b2aeb6afabb3aeaab2aeaa4878a14b7aa34c7ba44a759b3d63873b5f825b67766f5f569c7e6caf8c77b18f79b28f78b5927caf8e78a98872aa8a76a98a76ac917fada199b7b0acb9b3afbfb9b5c1bab6bdb6b2b8b3afbab5b1b9b4b0b6afabb7b1adb3ada9b3aeaab0aba8"; +const WIDTH = 32; +const HEIGHT = 32; +function parseImage() { + const pixels = []; + for (let y = 0; y < HEIGHT; y++) { + const row = []; + for (let x = 0; x < WIDTH; x++) { + const idx = (y * WIDTH + x) * 6; + const r = parseInt(DAX_HEX.slice(idx, idx + 2), 16); + const g = parseInt(DAX_HEX.slice(idx + 2, idx + 4), 16); + const b = parseInt(DAX_HEX.slice(idx + 4, idx + 6), 16); + row.push([r, g, b]); + } + pixels.push(row); + } + return pixels; +} +function rgb(r, g, b, bg = false) { + return `\x1b[${bg ? 48 : 38};2;${r};${g};${b}m`; +} +const RESET = "\x1b[0m"; +function buildImage() { + const pixels = parseImage(); + const lines = []; + // Use half-block chars: ▄ with bg=top pixel, fg=bottom pixel + for (let row = 0; row < HEIGHT; row += 2) { + let line = ""; + for (let x = 0; x < WIDTH; x++) { + const top = pixels[row][x]; + const bottom = pixels[row + 1]?.[x] ?? top; + line += `${rgb(bottom[0], bottom[1], bottom[2])}${rgb(top[0], top[1], top[2], true)}▄`; + } + line += RESET; + lines.push(line); + } + return lines; +} +export class DaxnutsComponent { + ui; + image; + interval = null; + tick = 0; + maxTicks = 25; // ~2 seconds at 80ms + cachedLines = []; + cachedWidth = 0; + cachedTick = -1; + constructor(ui) { + this.ui = ui; + this.image = buildImage(); + this.startAnimation(); + } + invalidate() { + this.cachedWidth = 0; + } + startAnimation() { + this.interval = setInterval(() => { + this.tick++; + if (this.tick >= this.maxTicks) { + this.stopAnimation(); + } + this.cachedWidth = 0; + this.ui.requestRender(); + }, 80); + } + stopAnimation() { + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + } + render(width) { + if (width === this.cachedWidth && this.cachedTick === this.tick) { + return this.cachedLines; + } + const t = theme; + const lines = []; + const center = (s) => { + const visible = s.replace(/\x1b\[[0-9;]*m/g, "").length; + const left = Math.max(0, Math.floor((width - visible) / 2)); + return " ".repeat(left) + s; + }; + lines.push(""); + // Scanline reveal effect: show rows progressively + const revealedRows = Math.min(this.image.length, Math.floor((this.tick / this.maxTicks) * (this.image.length + 3))); + for (let i = 0; i < this.image.length; i++) { + if (i < revealedRows) { + lines.push(center(this.image[i])); + } + else { + // Show scan line + if (i === revealedRows) { + const scanline = "▓".repeat(WIDTH); + lines.push(center(rgb(100, 200, 255) + scanline + RESET)); + } + else { + lines.push(center(" ".repeat(WIDTH))); + } + } + } + lines.push(""); + // Fade in text after image is revealed + const textPhase = Math.max(0, this.tick - this.maxTicks * 0.6); + if (textPhase > 0 || this.tick >= this.maxTicks) { + lines.push(center(t.fg("accent", "Free Kimi K2.5 via OpenCode Zen"))); + lines.push(center(t.fg("success", '"Powered by daxnuts"'))); + lines.push(center(t.fg("muted", "— @thdxr"))); + } + else { + lines.push(""); + lines.push(""); + lines.push(""); + } + lines.push(""); + if (textPhase > 2 || this.tick >= this.maxTicks) { + lines.push(center(t.fg("dim", "Try OpenCode"))); + lines.push(center(t.fg("mdLink", "https://mistral.ai/news/mistral-vibe-2-0"))); + } + else { + lines.push(""); + lines.push(""); + } + lines.push(""); + this.cachedLines = lines; + this.cachedWidth = width; + this.cachedTick = this.tick; + return lines; + } + dispose() { + this.stopAnimation(); + } +} +//# sourceMappingURL=daxnuts.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/daxnuts.js.map b/dist/modes/interactive/components/daxnuts.js.map new file mode 100644 index 0000000..4128b12 --- /dev/null +++ b/dist/modes/interactive/components/daxnuts.js.map @@ -0,0 +1 @@ +{"version":3,"file":"daxnuts.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/daxnuts.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C,0DAA0D;AAC1D,MAAM,OAAO,GACZ,kgMAAkgM,CAAC;AAEpgM,MAAM,KAAK,GAAG,EAAE,CAAC;AACjB,MAAM,MAAM,GAAG,EAAE,CAAC;AAElB,SAAS,UAAU,GAAiB;IACnC,MAAM,MAAM,GAAiB,EAAE,CAAC;IAChC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACjC,MAAM,GAAG,GAAe,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;YAChC,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;YAChC,MAAM,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YACpD,MAAM,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YACxD,MAAM,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC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I,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YACjD,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC,CAAC,CAAC;YAChD,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,EAAE,0CAA0C,CAAC,CAAC,CAAC,CAAC;QAChF,CAAC;aAAM,CAAC;YACP,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACf,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAChB,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAEf,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;QACzB,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;QACzB,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC;QAC5B,OAAO,KAAK,CAAC;IAAA,CACb;IAED,OAAO,GAAS;QACf,IAAI,CAAC,aAAa,EAAE,CAAC;IAAA,CACrB;CACD","sourcesContent":["/**\n * POWERED BY DAXNUTS - Easter egg for OpenCode + Kimi K2.5\n *\n * A heartfelt tribute to dax (@thdxr) for providing free Kimi K2.5 access via OpenCode.\n */\n\nimport type { Component, TUI } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\n\n// 32x32 RGB image of dax, hex encoded (3 bytes per pixel)\nconst DAX_HEX =\n\t\"bbbab8b9b9b6b9b8b5bcbbb8b8b7b4b7b5b2b6b5b2b8b7b4b7b6b3b6b4b1bdbcb8bab8b6bbb8b5b8b5b1bbb8b4c2bebbc1bebac0bdbabfbcb9c1bebabfbebbc0bfbcc0bdbabbb8b5c1bfbcbfbcb8bbb9b6bfbcb8c2bfbcc1bfbcbfbbb8bdb9b6b8b7b5b9b8b5b8b8b5b5b5b2b6b5b2b8b7b4b9b8b5b9b8b5b6b5b3bab8b5bcbab7bbb9b6bbb8b5bfb9b5bdb2abbcb0a8beb2aabeb5afbfbab6bebab7c0bfbcbebdbabebbb8c0bdbabfbebbc2bebbbdbab7c3c0bdc3c0bdc1bebbc2bebabfbcb8bab9b6b7b6b3b2b1aeb6b5b2b5b4b1b5b4b2b6b5b2b7b6b4b9b8b6b7b6b3bbbab7b2afaba5988fb49e90b09481b79a88b39683b09583b7a395bfb6b0c0bdbabdbbb8bebcb9c1bfbcc0bebbbdbab7bebbb8c2bfbcc0bdbac0bcb9bdb9b6c0bcb8b5b4b2b4b3b0bab9b6b9b9b6b5b4b1b5b4b1b6b5b3b9b8b5b9b8b6b9b8b6b2aeaa968174a6836eaa856eab846eaf8973ac8973b08f79b18f7ab39786b7a89dbbb3aebfbab6c2c0bdbebcb9bfbdbac3c1bdc2bebbc0bcb9bdb9b6c1bdbabfbbb8b4b3b0b9b8b5b8b7b5b4b3b1b5b4b1b8b7b4b8b7b5bab9b6bbbab7b1afad8c7a719d735ca47860a87d65a98069ae8972ae8c75af8d77aa826ba98067aa8974b39e90b6a79dbbb2adc0bdbac1bfbdbfbbb8c1bdb9bebab6c0bdb9bfbbb8c1bdbab4b2b0b7b6b4b7b6b3b4b2b0bab9b7b6b5b2b6b5b2bab9b6bab9b6958c87977663aa836bac8772b08f7aad8c77b2917db0917db0907cac8971a77d64a87f67ac8972b29887b8a89dbfbab5bfbdbac1bebac0bcb9c0bcb9c0bcb9c1bebabebab7b8b7b4b7b6b4b5b4b1b5b4b2b7b6b3b5b4b2bab9b7bab9b6b4b1ada88f7fad8973ae8d78b19684b19685b29786b69a89b29582b1917daa856ea87e66a97e66ad866ea9826baf9280b8ada6bdbbb8bebab7bfbbb8c1bdbabfbbb8bcb8b4bcb8b5b6b4b2b7b5b3b6b5b2b8b7b4b3b2afb8b7b4b6b5b2b3b2b0b3a59aab856fad8d78b0917eb19886b49b8bb49a89b39785b0917eaf8f7cab866fa77d65a77a61a87d64a9816ab08f79b5a296c1bcb8c3bfbcc2bebbbebab7bfbbb7bdbab6c2bebab8b7b4b7b6b4b6b5b3b7b6b3b6b5b2b9b8b6b4b3b1b6b1acac8f7ca9826bae8f7aaf9583b49c8cb49c8bb79d8cb59987b19380ad8e79ae8c77af8e78ac8771a3775faa826bae8972b39888bbb6b2bebbb8bfbbb8bfbbb8c0bdb9bebbb7c0bdb9b6b5b2b9b8b5b4b3b1b8b7b5b4b3b0b7b6b4b6b5b3b1a7a0aa8772a77d65a88570b49887b19b8d9c887c907a6d987f71aa907faf917daf8e7aad8c78ac8b77a8836ca9836cac8770b49b8abdb6b2c0bcb9c0bdb9bfbbb8bebab7bfbcb9bebab7b9b8b6b5b4b2b9b8b5b8b7b5b8b7b4b7b6b4b5b4b2b3a9a2ad8973a1755da9856fb398858c776a65544b776358725d526e594d9c7f6eb1907ba68672ad8e7aab8771ac856db18f79b3a092beb9b5c1bdbabdb9b5bebab7bfbbb7bebab7bcb9b6b7b6b4b6b6b3b8b7b4b5b4b2b8b6b4b7b6b3b4b3b0b4aba4a6826ba3775fb08e79b19584a88e7daa8e7db29481ad8f7c997e6da38674ac8d79ac8e7aae917f9a7c6a896a599a7c6ab3a398c1bdbabdb9b6bcb8b5bebab6bebab7bdb9b5bdb9b6b5b4b1b7b5b3b5b4b2b7b6b3b7b6b4b3b3b0b3b2b0b4aca5a7846fa97f68ae8f7bae9383b59c8bb2937fae8e79ac8b76af927eaf927eb29683b39885b2988891786a72594c6e594d978d86bdbab7bab7b3c0bcb9c0bcb9bebab7bebbb7bdb9b6b3b2b0b4b3b0b5b4b2b4b4b1b4b3b1b4b3b1b4b3b0b6ada5aa8670a57a62ad8e7ab29b8cb69d8dab856fa9826aa88069ab8771af907db49987b19684b29886b59987b39480b09787b5a9a1bcb8b5bebab7bdb9b5bebab7bfbbb8bfbbb7bbb7b4b3b2afb8b7b5b8b7b5b3b2b0b5b4b2b6b5b3b6b4b1afa299a98975a9826baf907cb39988b49a89af8e7aac8973aa856eaf8c74b1917dae907dac907db39988b29785b49785b7a090b9aca3bfbab7bcb8b5bdb9b6bcb8b4bcb8b5bdb9b5bcb8b4b5b4b2b6b5b3b4b3b0b4b3b0b9b8b5b8b6b4908b88887467aa8f7ea78976ad8973b08b74b59885b69e8eb29888b1917cb1917db1937fae907cb19686b39a8ab29886b59b8ab8a192b6aaa3b7b2afbcb8b4bcb8b5bbb7b4c0bcb9bebab7c0bcb9b6b5b2b6b5b3b4b3b0bab9b7b7b6b4b1b0ae7b716ba083709b806f716158967764b08870b29481b69b8ab69f8fb39a89b69f90b49d8db39a89b29988b49c8cb6a090b8a496baa49593867f8f8986bfbbb7bdb9b5bcb7b4bab6b3b9b5b2bab6b2b4b3b1b3b3b0b6b5b3b8b7b5b4b2b0a7a5a38f837dae917ea084725a504c63544da28370b39784b59e8db2a093a698909b918b998e8790857e95877dad998bb39c8cb5a091b9a2938d827c95908dbebab6bbb7b3bdbab7bbb7b4bdb9b6bbb7b4b4b3b0b5b4b1b8b7b5b6b5b3b8b8b5b4b2af968f8ab29a8bab9485544b483a323073655d96887f70655f61595547403e453e3c453f3d57504f655e5b90847db39c8db7a090b6a09189807aaba6a3bdb9b6c0bcb9bebab7bcb7b4bebab7bbb7b4b3b2b0b6b5b3b2b1afb7b6b4b8b7b4b5b4b1aeaba8b5a89fac998d4d44412d25244d46444e4744322b293a3230423937433a37352d2a59504c534b48524a48988a81b59f8fb19c8d827974b2afacbdb9b5bcb8b4bdb9b5bcb8b5bdb9b6bab6b2b8b7b5b5b4b2b6b6b3b9b8b5b7b6b3b6b5b2b8b6b3b9b4b1b2a9a26c64612d25242d2625312a28352d2c453d3a78675c8d7a6ea09792aea6a0615854332b29524a479f8e82b09d90a49b96c1bdb9bebab7bfbbb8bbb8b4b9b5b1b8b4b0b9b4b0b7b6b4b8b7b5b8b7b4b6b5b3b8b6b3bab9b6b9b8b5b4b3b0b7b5b2a5a29f453d3b261e1d261f1e2e2625413936857268977865b19482b5a69caca5a07c7572453d3b746963a0948cc5bfbbc0bbb8beb9b6bbb7b3bbb6b3b7b3afb8b4b0b9b5b1b7b6b3b6b5b3b5b4b2b5b4b2b7b6b3b7b6b3b8b6b3b4b2afb7b6b3b3b1ae6d6765251f1e1e18172a22212d2523443b3971625ab19888b09482a89182877e792c25243e3634766d6abeb9b5bfbbb7bebab6bcb7b3bbb6b3b9b5b1b7b3afb8b4b0b4b3b0b5b4b1b5b4b1b4b3b1b5b4b2b8b6b4b5b3b0b9b6b4b5b4b1b6b4b27f79762a2322221c1b2d2524221b1a443e3c47413f6f676281766f867971675e5a3e37352a222166605dbab7b3bdb9b5beb9b5bcb7b3bcb7b3b9b4b0bab6b2bab6b2b5b3b0b6b4b2b3b2afb7b6b3b4b4b1b4b3b0b6b4b1b5b4b1b4b3b0b9b6b29a8c8252474230292828201f181212322c2c231e1d1c16162c26252923222d26252d2523332b2a8e8885bcb8b5bcb7b3bbb6b2bcb7b3b9b4b1b9b5b1b7b2afb7b2ae7a838e9b9b9caeadacb3b2b0b3b2afb7b7b4b6b5b3b6b6b3b7b6b3b9ada4a991808e7b6f50453f2b24231a14142923221f19181d17161f18182620201d17162a22215d5654b7b3b0bbb7b3bbb6b2b8b4b0bab5b1bbb6b2bab5b1b8b4b0bab6b22c496b4c5d735f68766e727a828285929090adaba8b7b2aeb6a59ab39682a28470a387748e76674e403a1a14141d1716181211221c1c1f1918221c1b2f2827342d2c8d8884bab6b3b9b5b2bab5b1bab5b1b9b4b0bab6b2b8b4b0b9b4b0b7b2ae325e8b365f8a3a5d833f5b7a545f70646469706b6aa08f84b08e78b18e769f7e689e7f6b9e816d907766584940362d2a1c1615201b1a1a1413201a1a251e1d393331a39e9bbab5b1bcb7b3bab6b2b8b3afb8b4b0b9b4b0b9b4b1bab5b2b5b0ac3d6c9843729d44719c426e98415f805a64716f6a699d8677b1927eb3947faa89749d7a649f7f6ba487749e837186716454463f2c25231e181837302e3a33317a7471beb9b6bcb8b4bbb6b2b6b2aebab5b1b9b5b1b8b3afbab6b2b6b1adb5aeaa4877a14c7aa44e7ba345719a3a5d80586b7f767475927b6eb1927faf8e79b08e78a78169a07861a17f6aa58570a688749b83738270666f66618a8480a49e99b7b2aebab6b2bcb8b4b9b5b1b7b2aebab5b1b9b4b0b6b1aeb6b1adb2aca8b2aca84876a04a78a2517fa74771973a5d80405c7a6161677c695fac8a75b08d77b4917aaf8971ad876fa5816aa6846ea78670a98a76ac9484ab9f96b2aca8bdb8b4bcb7b3bcb8b4bcb8b4b8b3afb7b2aeb9b4b0b8b3afb8b2aeb6afabb3aeaab2aeaa4878a14b7aa34c7ba44a759b3d63873b5f825b67766f5f569c7e6caf8c77b18f79b28f78b5927caf8e78a98872aa8a76a98a76ac917fada199b7b0acb9b3afbfb9b5c1bab6bdb6b2b8b3afbab5b1b9b4b0b6afabb7b1adb3ada9b3aeaab0aba8\";\n\nconst WIDTH = 32;\nconst HEIGHT = 32;\n\nfunction parseImage(): number[][][] {\n\tconst pixels: number[][][] = [];\n\tfor (let y = 0; y < HEIGHT; y++) {\n\t\tconst row: number[][] = [];\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tconst idx = (y * WIDTH + x) * 6;\n\t\t\tconst r = parseInt(DAX_HEX.slice(idx, idx + 2), 16);\n\t\t\tconst g = parseInt(DAX_HEX.slice(idx + 2, idx + 4), 16);\n\t\t\tconst b = parseInt(DAX_HEX.slice(idx + 4, idx + 6), 16);\n\t\t\trow.push([r, g, b]);\n\t\t}\n\t\tpixels.push(row);\n\t}\n\treturn pixels;\n}\n\nfunction rgb(r: number, g: number, b: number, bg = false): string {\n\treturn `\\x1b[${bg ? 48 : 38};2;${r};${g};${b}m`;\n}\n\nconst RESET = \"\\x1b[0m\";\n\nfunction buildImage(): string[] {\n\tconst pixels = parseImage();\n\tconst lines: string[] = [];\n\n\t// Use half-block chars: ▄ with bg=top pixel, fg=bottom pixel\n\tfor (let row = 0; row < HEIGHT; row += 2) {\n\t\tlet line = \"\";\n\t\tfor (let x = 0; x < WIDTH; x++) {\n\t\t\tconst top = pixels[row][x];\n\t\t\tconst bottom = pixels[row + 1]?.[x] ?? top;\n\t\t\tline += `${rgb(bottom[0], bottom[1], bottom[2])}${rgb(top[0], top[1], top[2], true)}▄`;\n\t\t}\n\t\tline += RESET;\n\t\tlines.push(line);\n\t}\n\treturn lines;\n}\n\nexport class DaxnutsComponent implements Component {\n\tprivate ui: TUI;\n\tprivate image: string[];\n\tprivate interval: ReturnType | null = null;\n\tprivate tick = 0;\n\tprivate maxTicks = 25; // ~2 seconds at 80ms\n\tprivate cachedLines: string[] = [];\n\tprivate cachedWidth = 0;\n\tprivate cachedTick = -1;\n\n\tconstructor(ui: TUI) {\n\t\tthis.ui = ui;\n\t\tthis.image = buildImage();\n\t\tthis.startAnimation();\n\t}\n\n\tinvalidate(): void {\n\t\tthis.cachedWidth = 0;\n\t}\n\n\tprivate startAnimation(): void {\n\t\tthis.interval = setInterval(() => {\n\t\t\tthis.tick++;\n\t\t\tif (this.tick >= this.maxTicks) {\n\t\t\t\tthis.stopAnimation();\n\t\t\t}\n\t\t\tthis.cachedWidth = 0;\n\t\t\tthis.ui.requestRender();\n\t\t}, 80);\n\t}\n\n\tprivate stopAnimation(): void {\n\t\tif (this.interval) {\n\t\t\tclearInterval(this.interval);\n\t\t\tthis.interval = null;\n\t\t}\n\t}\n\n\trender(width: number): string[] {\n\t\tif (width === this.cachedWidth && this.cachedTick === this.tick) {\n\t\t\treturn this.cachedLines;\n\t\t}\n\n\t\tconst t = theme;\n\t\tconst lines: string[] = [];\n\n\t\tconst center = (s: string) => {\n\t\t\tconst visible = s.replace(/\\x1b\\[[0-9;]*m/g, \"\").length;\n\t\t\tconst left = Math.max(0, Math.floor((width - visible) / 2));\n\t\t\treturn \" \".repeat(left) + s;\n\t\t};\n\n\t\tlines.push(\"\");\n\n\t\t// Scanline reveal effect: show rows progressively\n\t\tconst revealedRows = Math.min(\n\t\t\tthis.image.length,\n\t\t\tMath.floor((this.tick / this.maxTicks) * (this.image.length + 3)),\n\t\t);\n\n\t\tfor (let i = 0; i < this.image.length; i++) {\n\t\t\tif (i < revealedRows) {\n\t\t\t\tlines.push(center(this.image[i]));\n\t\t\t} else {\n\t\t\t\t// Show scan line\n\t\t\t\tif (i === revealedRows) {\n\t\t\t\t\tconst scanline = \"▓\".repeat(WIDTH);\n\t\t\t\t\tlines.push(center(rgb(100, 200, 255) + scanline + RESET));\n\t\t\t\t} else {\n\t\t\t\t\tlines.push(center(\" \".repeat(WIDTH)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlines.push(\"\");\n\n\t\t// Fade in text after image is revealed\n\t\tconst textPhase = Math.max(0, this.tick - this.maxTicks * 0.6);\n\t\tif (textPhase > 0 || this.tick >= this.maxTicks) {\n\t\t\tlines.push(center(t.fg(\"accent\", \"Free Kimi K2.5 via OpenCode Zen\")));\n\t\t\tlines.push(center(t.fg(\"success\", '\"Powered by daxnuts\"')));\n\t\t\tlines.push(center(t.fg(\"muted\", \"— @thdxr\")));\n\t\t} else {\n\t\t\tlines.push(\"\");\n\t\t\tlines.push(\"\");\n\t\t\tlines.push(\"\");\n\t\t}\n\n\t\tlines.push(\"\");\n\t\tif (textPhase > 2 || this.tick >= this.maxTicks) {\n\t\t\tlines.push(center(t.fg(\"dim\", \"Try OpenCode\")));\n\t\t\tlines.push(center(t.fg(\"mdLink\", \"https://mistral.ai/news/mistral-vibe-2-0\")));\n\t\t} else {\n\t\t\tlines.push(\"\");\n\t\t\tlines.push(\"\");\n\t\t}\n\t\tlines.push(\"\");\n\n\t\tthis.cachedLines = lines;\n\t\tthis.cachedWidth = width;\n\t\tthis.cachedTick = this.tick;\n\t\treturn lines;\n\t}\n\n\tdispose(): void {\n\t\tthis.stopAnimation();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/diff.d.ts b/dist/modes/interactive/components/diff.d.ts new file mode 100644 index 0000000..a755a47 --- /dev/null +++ b/dist/modes/interactive/components/diff.d.ts @@ -0,0 +1,12 @@ +export interface RenderDiffOptions { + /** File path (unused, kept for API compatibility) */ + filePath?: string; +} +/** + * Render a diff string with colored lines and intra-line change highlighting. + * - Context lines: dim/gray + * - Removed lines: red, with inverse on changed tokens + * - Added lines: green, with inverse on changed tokens + */ +export declare function renderDiff(diffText: string, _options?: RenderDiffOptions): string; +//# sourceMappingURL=diff.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/diff.d.ts.map b/dist/modes/interactive/components/diff.d.ts.map new file mode 100644 index 0000000..8009c16 --- /dev/null +++ b/dist/modes/interactive/components/diff.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"diff.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/diff.ts"],"names":[],"mappings":"AAmEA,MAAM,WAAW,iBAAiB;IACjC,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,GAAE,iBAAsB,GAAG,MAAM,CAoErF","sourcesContent":["import * as Diff from \"diff\";\nimport { theme } from \"../theme/theme.ts\";\n\n/**\n * Parse diff line to extract prefix, line number, and content.\n * Format: \"+123 content\" or \"-123 content\" or \" 123 content\" or \" ...\"\n */\nfunction parseDiffLine(line: string): { prefix: string; lineNum: string; content: string } | null {\n\tconst match = line.match(/^([+-\\s])(\\s*\\d*)\\s(.*)$/);\n\tif (!match) return null;\n\treturn { prefix: match[1], lineNum: match[2], content: match[3] };\n}\n\n/**\n * Replace tabs with spaces for consistent rendering.\n */\nfunction replaceTabs(text: string): string {\n\treturn text.replace(/\\t/g, \" \");\n}\n\n/**\n * Compute word-level diff and render with inverse on changed parts.\n * Uses diffWords which groups whitespace with adjacent words for cleaner highlighting.\n * Strips leading whitespace from inverse to avoid highlighting indentation.\n */\nfunction renderIntraLineDiff(oldContent: string, newContent: string): { removedLine: string; addedLine: string } {\n\tconst wordDiff = Diff.diffWords(oldContent, newContent);\n\n\tlet removedLine = \"\";\n\tlet addedLine = \"\";\n\tlet isFirstRemoved = true;\n\tlet isFirstAdded = true;\n\n\tfor (const part of wordDiff) {\n\t\tif (part.removed) {\n\t\t\tlet value = part.value;\n\t\t\t// Strip leading whitespace from the first removed part\n\t\t\tif (isFirstRemoved) {\n\t\t\t\tconst leadingWs = value.match(/^(\\s*)/)?.[1] || \"\";\n\t\t\t\tvalue = value.slice(leadingWs.length);\n\t\t\t\tremovedLine += leadingWs;\n\t\t\t\tisFirstRemoved = false;\n\t\t\t}\n\t\t\tif (value) {\n\t\t\t\tremovedLine += theme.inverse(value);\n\t\t\t}\n\t\t} else if (part.added) {\n\t\t\tlet value = part.value;\n\t\t\t// Strip leading whitespace from the first added part\n\t\t\tif (isFirstAdded) {\n\t\t\t\tconst leadingWs = value.match(/^(\\s*)/)?.[1] || \"\";\n\t\t\t\tvalue = value.slice(leadingWs.length);\n\t\t\t\taddedLine += leadingWs;\n\t\t\t\tisFirstAdded = false;\n\t\t\t}\n\t\t\tif (value) {\n\t\t\t\taddedLine += theme.inverse(value);\n\t\t\t}\n\t\t} else {\n\t\t\tremovedLine += part.value;\n\t\t\taddedLine += part.value;\n\t\t}\n\t}\n\n\treturn { removedLine, addedLine };\n}\n\nexport interface RenderDiffOptions {\n\t/** File path (unused, kept for API compatibility) */\n\tfilePath?: string;\n}\n\n/**\n * Render a diff string with colored lines and intra-line change highlighting.\n * - Context lines: dim/gray\n * - Removed lines: red, with inverse on changed tokens\n * - Added lines: green, with inverse on changed tokens\n */\nexport function renderDiff(diffText: string, _options: RenderDiffOptions = {}): string {\n\tconst lines = diffText.split(\"\\n\");\n\tconst result: string[] = [];\n\n\tlet i = 0;\n\twhile (i < lines.length) {\n\t\tconst line = lines[i];\n\t\tconst parsed = parseDiffLine(line);\n\n\t\tif (!parsed) {\n\t\t\tresult.push(theme.fg(\"toolDiffContext\", line));\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (parsed.prefix === \"-\") {\n\t\t\t// Collect consecutive removed lines\n\t\t\tconst removedLines: { lineNum: string; content: string }[] = [];\n\t\t\twhile (i < lines.length) {\n\t\t\t\tconst p = parseDiffLine(lines[i]);\n\t\t\t\tif (!p || p.prefix !== \"-\") break;\n\t\t\t\tremovedLines.push({ lineNum: p.lineNum, content: p.content });\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\t// Collect consecutive added lines\n\t\t\tconst addedLines: { lineNum: string; content: string }[] = [];\n\t\t\twhile (i < lines.length) {\n\t\t\t\tconst p = parseDiffLine(lines[i]);\n\t\t\t\tif (!p || p.prefix !== \"+\") break;\n\t\t\t\taddedLines.push({ lineNum: p.lineNum, content: p.content });\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\t// Only do intra-line diffing when there's exactly one removed and one added line\n\t\t\t// (indicating a single line modification). Otherwise, show lines as-is.\n\t\t\tif (removedLines.length === 1 && addedLines.length === 1) {\n\t\t\t\tconst removed = removedLines[0];\n\t\t\t\tconst added = addedLines[0];\n\n\t\t\t\tconst { removedLine, addedLine } = renderIntraLineDiff(\n\t\t\t\t\treplaceTabs(removed.content),\n\t\t\t\t\treplaceTabs(added.content),\n\t\t\t\t);\n\n\t\t\t\tresult.push(theme.fg(\"toolDiffRemoved\", `-${removed.lineNum} ${removedLine}`));\n\t\t\t\tresult.push(theme.fg(\"toolDiffAdded\", `+${added.lineNum} ${addedLine}`));\n\t\t\t} else {\n\t\t\t\t// Show all removed lines first, then all added lines\n\t\t\t\tfor (const removed of removedLines) {\n\t\t\t\t\tresult.push(theme.fg(\"toolDiffRemoved\", `-${removed.lineNum} ${replaceTabs(removed.content)}`));\n\t\t\t\t}\n\t\t\t\tfor (const added of addedLines) {\n\t\t\t\t\tresult.push(theme.fg(\"toolDiffAdded\", `+${added.lineNum} ${replaceTabs(added.content)}`));\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (parsed.prefix === \"+\") {\n\t\t\t// Standalone added line\n\t\t\tresult.push(theme.fg(\"toolDiffAdded\", `+${parsed.lineNum} ${replaceTabs(parsed.content)}`));\n\t\t\ti++;\n\t\t} else {\n\t\t\t// Context line\n\t\t\tresult.push(theme.fg(\"toolDiffContext\", ` ${parsed.lineNum} ${replaceTabs(parsed.content)}`));\n\t\t\ti++;\n\t\t}\n\t}\n\n\treturn result.join(\"\\n\");\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/diff.js b/dist/modes/interactive/components/diff.js new file mode 100644 index 0000000..9b1b38f --- /dev/null +++ b/dist/modes/interactive/components/diff.js @@ -0,0 +1,133 @@ +import * as Diff from "diff"; +import { theme } from "../theme/theme.js"; +/** + * Parse diff line to extract prefix, line number, and content. + * Format: "+123 content" or "-123 content" or " 123 content" or " ..." + */ +function parseDiffLine(line) { + const match = line.match(/^([+-\s])(\s*\d*)\s(.*)$/); + if (!match) + return null; + return { prefix: match[1], lineNum: match[2], content: match[3] }; +} +/** + * Replace tabs with spaces for consistent rendering. + */ +function replaceTabs(text) { + return text.replace(/\t/g, " "); +} +/** + * Compute word-level diff and render with inverse on changed parts. + * Uses diffWords which groups whitespace with adjacent words for cleaner highlighting. + * Strips leading whitespace from inverse to avoid highlighting indentation. + */ +function renderIntraLineDiff(oldContent, newContent) { + const wordDiff = Diff.diffWords(oldContent, newContent); + let removedLine = ""; + let addedLine = ""; + let isFirstRemoved = true; + let isFirstAdded = true; + for (const part of wordDiff) { + if (part.removed) { + let value = part.value; + // Strip leading whitespace from the first removed part + if (isFirstRemoved) { + const leadingWs = value.match(/^(\s*)/)?.[1] || ""; + value = value.slice(leadingWs.length); + removedLine += leadingWs; + isFirstRemoved = false; + } + if (value) { + removedLine += theme.inverse(value); + } + } + else if (part.added) { + let value = part.value; + // Strip leading whitespace from the first added part + if (isFirstAdded) { + const leadingWs = value.match(/^(\s*)/)?.[1] || ""; + value = value.slice(leadingWs.length); + addedLine += leadingWs; + isFirstAdded = false; + } + if (value) { + addedLine += theme.inverse(value); + } + } + else { + removedLine += part.value; + addedLine += part.value; + } + } + return { removedLine, addedLine }; +} +/** + * Render a diff string with colored lines and intra-line change highlighting. + * - Context lines: dim/gray + * - Removed lines: red, with inverse on changed tokens + * - Added lines: green, with inverse on changed tokens + */ +export function renderDiff(diffText, _options = {}) { + const lines = diffText.split("\n"); + const result = []; + let i = 0; + while (i < lines.length) { + const line = lines[i]; + const parsed = parseDiffLine(line); + if (!parsed) { + result.push(theme.fg("toolDiffContext", line)); + i++; + continue; + } + if (parsed.prefix === "-") { + // Collect consecutive removed lines + const removedLines = []; + while (i < lines.length) { + const p = parseDiffLine(lines[i]); + if (!p || p.prefix !== "-") + break; + removedLines.push({ lineNum: p.lineNum, content: p.content }); + i++; + } + // Collect consecutive added lines + const addedLines = []; + while (i < lines.length) { + const p = parseDiffLine(lines[i]); + if (!p || p.prefix !== "+") + break; + addedLines.push({ lineNum: p.lineNum, content: p.content }); + i++; + } + // Only do intra-line diffing when there's exactly one removed and one added line + // (indicating a single line modification). Otherwise, show lines as-is. + if (removedLines.length === 1 && addedLines.length === 1) { + const removed = removedLines[0]; + const added = addedLines[0]; + const { removedLine, addedLine } = renderIntraLineDiff(replaceTabs(removed.content), replaceTabs(added.content)); + result.push(theme.fg("toolDiffRemoved", `-${removed.lineNum} ${removedLine}`)); + result.push(theme.fg("toolDiffAdded", `+${added.lineNum} ${addedLine}`)); + } + else { + // Show all removed lines first, then all added lines + for (const removed of removedLines) { + result.push(theme.fg("toolDiffRemoved", `-${removed.lineNum} ${replaceTabs(removed.content)}`)); + } + for (const added of addedLines) { + result.push(theme.fg("toolDiffAdded", `+${added.lineNum} ${replaceTabs(added.content)}`)); + } + } + } + else if (parsed.prefix === "+") { + // Standalone added line + result.push(theme.fg("toolDiffAdded", `+${parsed.lineNum} ${replaceTabs(parsed.content)}`)); + i++; + } + else { + // Context line + result.push(theme.fg("toolDiffContext", ` ${parsed.lineNum} ${replaceTabs(parsed.content)}`)); + i++; + } + } + return result.join("\n"); +} +//# sourceMappingURL=diff.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/diff.js.map b/dist/modes/interactive/components/diff.js.map new file mode 100644 index 0000000..bb6537c --- /dev/null +++ b/dist/modes/interactive/components/diff.js.map @@ -0,0 +1 @@ +{"version":3,"file":"diff.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/diff.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C;;;GAGG;AACH,SAAS,aAAa,CAAC,IAAY,EAA+D;IACjG,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;IACrD,IAAI,CAAC,KAAK;QAAE,OAAO,IAAI,CAAC;IACxB,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AAAA,CAClE;AAED;;GAEG;AACH,SAAS,WAAW,CAAC,IAAY,EAAU;IAC1C,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AAAA,CAClC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAAC,UAAkB,EAAE,UAAkB,EAA8C;IAChH,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;IAExD,IAAI,WAAW,GAAG,EAAE,CAAC;IACrB,IAAI,SAAS,GAAG,EAAE,CAAC;IACnB,IAAI,cAAc,GAAG,IAAI,CAAC;IAC1B,IAAI,YAAY,GAAG,IAAI,CAAC;IAExB,KAAK,MAAM,IAAI,IAAI,QAAQ,EAAE,CAAC;QAC7B,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,IAAI,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;YACvB,uDAAuD;YACvD,IAAI,cAAc,EAAE,CAAC;gBACpB,MAAM,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,C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EAAE,IAAI,MAAM,CAAC,OAAO,IAAI,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;YAC5F,CAAC,EAAE,CAAC;QACL,CAAC;aAAM,CAAC;YACP,eAAe;YACf,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,iBAAiB,EAAE,IAAI,MAAM,CAAC,OAAO,IAAI,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;YAC9F,CAAC,EAAE,CAAC;QACL,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACzB","sourcesContent":["import * as Diff from \"diff\";\nimport { theme } from \"../theme/theme.ts\";\n\n/**\n * Parse diff line to extract prefix, line number, and content.\n * Format: \"+123 content\" or \"-123 content\" or \" 123 content\" or \" ...\"\n */\nfunction parseDiffLine(line: string): { prefix: string; lineNum: string; content: string } | null {\n\tconst match = line.match(/^([+-\\s])(\\s*\\d*)\\s(.*)$/);\n\tif (!match) return null;\n\treturn { prefix: match[1], lineNum: match[2], content: match[3] };\n}\n\n/**\n * Replace tabs with spaces for consistent rendering.\n */\nfunction replaceTabs(text: string): string {\n\treturn text.replace(/\\t/g, \" \");\n}\n\n/**\n * Compute word-level diff and render with inverse on changed parts.\n * Uses diffWords which groups whitespace with adjacent words for cleaner highlighting.\n * Strips leading whitespace from inverse to avoid highlighting indentation.\n */\nfunction renderIntraLineDiff(oldContent: string, newContent: string): { removedLine: string; addedLine: string } {\n\tconst wordDiff = Diff.diffWords(oldContent, newContent);\n\n\tlet removedLine = \"\";\n\tlet addedLine = \"\";\n\tlet isFirstRemoved = true;\n\tlet isFirstAdded = true;\n\n\tfor (const part of wordDiff) {\n\t\tif (part.removed) {\n\t\t\tlet value = part.value;\n\t\t\t// Strip leading whitespace from the first removed part\n\t\t\tif (isFirstRemoved) {\n\t\t\t\tconst leadingWs = value.match(/^(\\s*)/)?.[1] || \"\";\n\t\t\t\tvalue = value.slice(leadingWs.length);\n\t\t\t\tremovedLine += leadingWs;\n\t\t\t\tisFirstRemoved = false;\n\t\t\t}\n\t\t\tif (value) {\n\t\t\t\tremovedLine += theme.inverse(value);\n\t\t\t}\n\t\t} else if (part.added) {\n\t\t\tlet value = part.value;\n\t\t\t// Strip leading whitespace from the first added part\n\t\t\tif (isFirstAdded) {\n\t\t\t\tconst leadingWs = value.match(/^(\\s*)/)?.[1] || \"\";\n\t\t\t\tvalue = value.slice(leadingWs.length);\n\t\t\t\taddedLine += leadingWs;\n\t\t\t\tisFirstAdded = false;\n\t\t\t}\n\t\t\tif (value) {\n\t\t\t\taddedLine += theme.inverse(value);\n\t\t\t}\n\t\t} else {\n\t\t\tremovedLine += part.value;\n\t\t\taddedLine += part.value;\n\t\t}\n\t}\n\n\treturn { removedLine, addedLine };\n}\n\nexport interface RenderDiffOptions {\n\t/** File path (unused, kept for API compatibility) */\n\tfilePath?: string;\n}\n\n/**\n * Render a diff string with colored lines and intra-line change highlighting.\n * - Context lines: dim/gray\n * - Removed lines: red, with inverse on changed tokens\n * - Added lines: green, with inverse on changed tokens\n */\nexport function renderDiff(diffText: string, _options: RenderDiffOptions = {}): string {\n\tconst lines = diffText.split(\"\\n\");\n\tconst result: string[] = [];\n\n\tlet i = 0;\n\twhile (i < lines.length) {\n\t\tconst line = lines[i];\n\t\tconst parsed = parseDiffLine(line);\n\n\t\tif (!parsed) {\n\t\t\tresult.push(theme.fg(\"toolDiffContext\", line));\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (parsed.prefix === \"-\") {\n\t\t\t// Collect consecutive removed lines\n\t\t\tconst removedLines: { lineNum: string; content: string }[] = [];\n\t\t\twhile (i < lines.length) {\n\t\t\t\tconst p = parseDiffLine(lines[i]);\n\t\t\t\tif (!p || p.prefix !== \"-\") break;\n\t\t\t\tremovedLines.push({ lineNum: p.lineNum, content: p.content });\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\t// Collect consecutive added lines\n\t\t\tconst addedLines: { lineNum: string; content: string }[] = [];\n\t\t\twhile (i < lines.length) {\n\t\t\t\tconst p = parseDiffLine(lines[i]);\n\t\t\t\tif (!p || p.prefix !== \"+\") break;\n\t\t\t\taddedLines.push({ lineNum: p.lineNum, content: p.content });\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\t// Only do intra-line diffing when there's exactly one removed and one added line\n\t\t\t// (indicating a single line modification). Otherwise, show lines as-is.\n\t\t\tif (removedLines.length === 1 && addedLines.length === 1) {\n\t\t\t\tconst removed = removedLines[0];\n\t\t\t\tconst added = addedLines[0];\n\n\t\t\t\tconst { removedLine, addedLine } = renderIntraLineDiff(\n\t\t\t\t\treplaceTabs(removed.content),\n\t\t\t\t\treplaceTabs(added.content),\n\t\t\t\t);\n\n\t\t\t\tresult.push(theme.fg(\"toolDiffRemoved\", `-${removed.lineNum} ${removedLine}`));\n\t\t\t\tresult.push(theme.fg(\"toolDiffAdded\", `+${added.lineNum} ${addedLine}`));\n\t\t\t} else {\n\t\t\t\t// Show all removed lines first, then all added lines\n\t\t\t\tfor (const removed of removedLines) {\n\t\t\t\t\tresult.push(theme.fg(\"toolDiffRemoved\", `-${removed.lineNum} ${replaceTabs(removed.content)}`));\n\t\t\t\t}\n\t\t\t\tfor (const added of addedLines) {\n\t\t\t\t\tresult.push(theme.fg(\"toolDiffAdded\", `+${added.lineNum} ${replaceTabs(added.content)}`));\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (parsed.prefix === \"+\") {\n\t\t\t// Standalone added line\n\t\t\tresult.push(theme.fg(\"toolDiffAdded\", `+${parsed.lineNum} ${replaceTabs(parsed.content)}`));\n\t\t\ti++;\n\t\t} else {\n\t\t\t// Context line\n\t\t\tresult.push(theme.fg(\"toolDiffContext\", ` ${parsed.lineNum} ${replaceTabs(parsed.content)}`));\n\t\t\ti++;\n\t\t}\n\t}\n\n\treturn result.join(\"\\n\");\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/dynamic-border.d.ts b/dist/modes/interactive/components/dynamic-border.d.ts new file mode 100644 index 0000000..eb57697 --- /dev/null +++ b/dist/modes/interactive/components/dynamic-border.d.ts @@ -0,0 +1,15 @@ +import type { Component } from "@earendil-works/pi-tui"; +/** + * Dynamic border component that adjusts to viewport width. + * + * Note: When used from extensions loaded via jiti, the global `theme` may be undefined + * because jiti creates a separate module cache. Always pass an explicit color + * function when using DynamicBorder in components exported for extension use. + */ +export declare class DynamicBorder implements Component { + private color; + constructor(color?: (str: string) => string); + invalidate(): void; + render(width: number): string[]; +} +//# sourceMappingURL=dynamic-border.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/dynamic-border.d.ts.map b/dist/modes/interactive/components/dynamic-border.d.ts.map new file mode 100644 index 0000000..0534f8e --- /dev/null +++ b/dist/modes/interactive/components/dynamic-border.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dynamic-border.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/dynamic-border.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAGxD;;;;;;GAMG;AACH,qBAAa,aAAc,YAAW,SAAS;IAC9C,OAAO,CAAC,KAAK,CAA0B;IAEvC,YAAY,KAAK,GAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAyC,EAE5E;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAE9B;CACD","sourcesContent":["import type { Component } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\n\n/**\n * Dynamic border component that adjusts to viewport width.\n *\n * Note: When used from extensions loaded via jiti, the global `theme` may be undefined\n * because jiti creates a separate module cache. Always pass an explicit color\n * function when using DynamicBorder in components exported for extension use.\n */\nexport class DynamicBorder implements Component {\n\tprivate color: (str: string) => string;\n\n\tconstructor(color: (str: string) => string = (str) => theme.fg(\"border\", str)) {\n\t\tthis.color = color;\n\t}\n\n\tinvalidate(): void {\n\t\t// No cached state to invalidate currently\n\t}\n\n\trender(width: number): string[] {\n\t\treturn [this.color(\"─\".repeat(Math.max(1, width)))];\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/dynamic-border.js b/dist/modes/interactive/components/dynamic-border.js new file mode 100644 index 0000000..5e79c5f --- /dev/null +++ b/dist/modes/interactive/components/dynamic-border.js @@ -0,0 +1,21 @@ +import { theme } from "../theme/theme.js"; +/** + * Dynamic border component that adjusts to viewport width. + * + * Note: When used from extensions loaded via jiti, the global `theme` may be undefined + * because jiti creates a separate module cache. Always pass an explicit color + * function when using DynamicBorder in components exported for extension use. + */ +export class DynamicBorder { + color; + constructor(color = (str) => theme.fg("border", str)) { + this.color = color; + } + invalidate() { + // No cached state to invalidate currently + } + render(width) { + return [this.color("─".repeat(Math.max(1, width)))]; + } +} +//# sourceMappingURL=dynamic-border.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/dynamic-border.js.map b/dist/modes/interactive/components/dynamic-border.js.map new file mode 100644 index 0000000..d80c085 --- /dev/null +++ b/dist/modes/interactive/components/dynamic-border.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dynamic-border.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/dynamic-border.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C;;;;;;GAMG;AACH,MAAM,OAAO,aAAa;IACjB,KAAK,CAA0B;IAEvC,YAAY,KAAK,GAA4B,CAAC,GAAG,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE;QAC9E,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IAAA,CACnB;IAED,UAAU,GAAS;QAClB,0CAA0C;IADvB,CAEnB;IAED,MAAM,CAAC,KAAa,EAAY;QAC/B,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,KAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAAA,CACpD;CACD","sourcesContent":["import type { Component } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\n\n/**\n * Dynamic border component that adjusts to viewport width.\n *\n * Note: When used from extensions loaded via jiti, the global `theme` may be undefined\n * because jiti creates a separate module cache. Always pass an explicit color\n * function when using DynamicBorder in components exported for extension use.\n */\nexport class DynamicBorder implements Component {\n\tprivate color: (str: string) => string;\n\n\tconstructor(color: (str: string) => string = (str) => theme.fg(\"border\", str)) {\n\t\tthis.color = color;\n\t}\n\n\tinvalidate(): void {\n\t\t// No cached state to invalidate currently\n\t}\n\n\trender(width: number): string[] {\n\t\treturn [this.color(\"─\".repeat(Math.max(1, width)))];\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/earendil-announcement.d.ts b/dist/modes/interactive/components/earendil-announcement.d.ts new file mode 100644 index 0000000..511b342 --- /dev/null +++ b/dist/modes/interactive/components/earendil-announcement.d.ts @@ -0,0 +1,5 @@ +import { Container } from "@earendil-works/pi-tui"; +export declare class EarendilAnnouncementComponent extends Container { + constructor(); +} +//# sourceMappingURL=earendil-announcement.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/earendil-announcement.d.ts.map b/dist/modes/interactive/components/earendil-announcement.d.ts.map new file mode 100644 index 0000000..9420355 --- /dev/null +++ b/dist/modes/interactive/components/earendil-announcement.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"earendil-announcement.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/earendil-announcement.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAuB,MAAM,wBAAwB,CAAC;AAyBxE,qBAAa,6BAA8B,SAAQ,SAAS;IAC3D,cAwBC;CACD","sourcesContent":["import * as fs from \"node:fs\";\nimport { Container, Image, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport { getBundledInteractiveAssetPath } from \"../../../config.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\n\nconst BLOG_URL = \"https://mariozechner.at/posts/2026-04-08-ive-sold-out/\";\nconst IMAGE_FILENAME = \"clankolas.png\";\n\nlet cachedImageBase64: string | undefined;\nlet attemptedImageLoad = false;\n\nfunction loadImageBase64(): string | undefined {\n\tif (attemptedImageLoad) {\n\t\treturn cachedImageBase64;\n\t}\n\n\tattemptedImageLoad = true;\n\ttry {\n\t\tcachedImageBase64 = fs.readFileSync(getBundledInteractiveAssetPath(IMAGE_FILENAME)).toString(\"base64\");\n\t} catch {\n\t\tcachedImageBase64 = undefined;\n\t}\n\treturn cachedImageBase64;\n}\n\nexport class EarendilAnnouncementComponent extends Container {\n\tconstructor() {\n\t\tsuper();\n\n\t\tthis.addChild(new DynamicBorder((text) => theme.fg(\"accent\", text)));\n\t\tthis.addChild(new Text(theme.bold(theme.fg(\"accent\", \"pi has joined Earendil\")), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.fg(\"muted\", \"Read the blog post:\"), 1, 0));\n\t\tthis.addChild(new Text(theme.fg(\"mdLink\", BLOG_URL), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\n\t\tconst imageBase64 = loadImageBase64();\n\t\tif (imageBase64) {\n\t\t\tthis.addChild(\n\t\t\t\tnew Image(\n\t\t\t\t\timageBase64,\n\t\t\t\t\t\"image/png\",\n\t\t\t\t\t{ fallbackColor: (text) => theme.fg(\"muted\", text) },\n\t\t\t\t\t{ maxWidthCells: 56, filename: IMAGE_FILENAME },\n\t\t\t\t),\n\t\t\t);\n\t\t\tthis.addChild(new Spacer(1));\n\t\t}\n\n\t\tthis.addChild(new DynamicBorder((text) => theme.fg(\"accent\", text)));\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/earendil-announcement.js b/dist/modes/interactive/components/earendil-announcement.js new file mode 100644 index 0000000..6c022b3 --- /dev/null +++ b/dist/modes/interactive/components/earendil-announcement.js @@ -0,0 +1,40 @@ +import * as fs from "node:fs"; +import { Container, Image, Spacer, Text } from "@earendil-works/pi-tui"; +import { getBundledInteractiveAssetPath } from "../../../config.js"; +import { theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +const BLOG_URL = "https://mariozechner.at/posts/2026-04-08-ive-sold-out/"; +const IMAGE_FILENAME = "clankolas.png"; +let cachedImageBase64; +let attemptedImageLoad = false; +function loadImageBase64() { + if (attemptedImageLoad) { + return cachedImageBase64; + } + attemptedImageLoad = true; + try { + cachedImageBase64 = fs.readFileSync(getBundledInteractiveAssetPath(IMAGE_FILENAME)).toString("base64"); + } + catch { + cachedImageBase64 = undefined; + } + return cachedImageBase64; +} +export class EarendilAnnouncementComponent extends Container { + constructor() { + super(); + this.addChild(new DynamicBorder((text) => theme.fg("accent", text))); + this.addChild(new Text(theme.bold(theme.fg("accent", "pi has joined Earendil")), 1, 0)); + this.addChild(new Spacer(1)); + this.addChild(new Text(theme.fg("muted", "Read the blog post:"), 1, 0)); + this.addChild(new Text(theme.fg("mdLink", BLOG_URL), 1, 0)); + this.addChild(new Spacer(1)); + const imageBase64 = loadImageBase64(); + if (imageBase64) { + this.addChild(new Image(imageBase64, "image/png", { fallbackColor: (text) => theme.fg("muted", text) }, { maxWidthCells: 56, filename: IMAGE_FILENAME })); + this.addChild(new Spacer(1)); + } + this.addChild(new DynamicBorder((text) => theme.fg("accent", text))); + } +} +//# sourceMappingURL=earendil-announcement.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/earendil-announcement.js.map b/dist/modes/interactive/components/earendil-announcement.js.map new file mode 100644 index 0000000..95b6506 --- /dev/null +++ b/dist/modes/interactive/components/earendil-announcement.js.map @@ -0,0 +1 @@ +{"version":3,"file":"earendil-announcement.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/earendil-announcement.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,M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CAAC,CAAC,CAAC;QAC7B,IAAI,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,qBAAqB,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QACxE,IAAI,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QAC5D,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAE7B,MAAM,WAAW,GAAG,eAAe,EAAE,CAAC;QACtC,IAAI,WAAW,EAAE,CAAC;YACjB,IAAI,CAAC,QAAQ,CACZ,IAAI,KAAK,CACR,WAAW,EACX,WAAW,EACX,EAAE,aAAa,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE,EACpD,EAAE,aAAa,EAAE,EAAE,EAAE,QAAQ,EAAE,cAAc,EAAE,CAC/C,CACD,CAAC;YACF,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAC9B,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IAAA,CACrE;CACD","sourcesContent":["import * as fs from \"node:fs\";\nimport { Container, Image, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport { getBundledInteractiveAssetPath } from \"../../../config.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\n\nconst BLOG_URL = \"https://mariozechner.at/posts/2026-04-08-ive-sold-out/\";\nconst IMAGE_FILENAME = \"clankolas.png\";\n\nlet cachedImageBase64: string | undefined;\nlet attemptedImageLoad = false;\n\nfunction loadImageBase64(): string | undefined {\n\tif (attemptedImageLoad) {\n\t\treturn cachedImageBase64;\n\t}\n\n\tattemptedImageLoad = true;\n\ttry {\n\t\tcachedImageBase64 = fs.readFileSync(getBundledInteractiveAssetPath(IMAGE_FILENAME)).toString(\"base64\");\n\t} catch {\n\t\tcachedImageBase64 = undefined;\n\t}\n\treturn cachedImageBase64;\n}\n\nexport class EarendilAnnouncementComponent extends Container {\n\tconstructor() {\n\t\tsuper();\n\n\t\tthis.addChild(new DynamicBorder((text) => theme.fg(\"accent\", text)));\n\t\tthis.addChild(new Text(theme.bold(theme.fg(\"accent\", \"pi has joined Earendil\")), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.fg(\"muted\", \"Read the blog post:\"), 1, 0));\n\t\tthis.addChild(new Text(theme.fg(\"mdLink\", BLOG_URL), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\n\t\tconst imageBase64 = loadImageBase64();\n\t\tif (imageBase64) {\n\t\t\tthis.addChild(\n\t\t\t\tnew Image(\n\t\t\t\t\timageBase64,\n\t\t\t\t\t\"image/png\",\n\t\t\t\t\t{ fallbackColor: (text) => theme.fg(\"muted\", text) },\n\t\t\t\t\t{ maxWidthCells: 56, filename: IMAGE_FILENAME },\n\t\t\t\t),\n\t\t\t);\n\t\t\tthis.addChild(new Spacer(1));\n\t\t}\n\n\t\tthis.addChild(new DynamicBorder((text) => theme.fg(\"accent\", text)));\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/extension-editor.d.ts b/dist/modes/interactive/components/extension-editor.d.ts new file mode 100644 index 0000000..6c48220 --- /dev/null +++ b/dist/modes/interactive/components/extension-editor.d.ts @@ -0,0 +1,21 @@ +/** + * Multi-line editor component for extensions. + * Supports Ctrl+G for external editor. + */ +import { Container, type EditorOptions, type Focusable, type TUI } from "@earendil-works/pi-tui"; +import type { KeybindingsManager } from "../../../core/keybindings.ts"; +export declare class ExtensionEditorComponent extends Container implements Focusable { + private editor; + private onSubmitCallback; + private onCancelCallback; + private tui; + private keybindings; + private externalEditorCommand; + private _focused; + get focused(): boolean; + set focused(value: boolean); + constructor(tui: TUI, keybindings: KeybindingsManager, title: string, prefill: string | undefined, onSubmit: (value: string) => void, onCancel: () => void, options?: EditorOptions, externalEditorCommand?: string); + handleInput(keyData: string): void; + private handleOpenExternalEditor; +} +//# sourceMappingURL=extension-editor.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/extension-editor.d.ts.map b/dist/modes/interactive/components/extension-editor.d.ts.map new file mode 100644 index 0000000..eb5a3ab --- /dev/null +++ b/dist/modes/interactive/components/extension-editor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"extension-editor.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/extension-editor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACN,SAAS,EAET,KAAK,aAAa,EAClB,KAAK,SAAS,EAId,KAAK,GAAG,EACR,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAMvE,qBAAa,wBAAyB,SAAQ,SAAU,YAAW,SAAS;IAC3E,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,gBAAgB,CAA0B;IAClD,OAAO,CAAC,gBAAgB,CAAa;IACrC,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,qBAAqB,CAAS;IAEtC,OAAO,CAAC,QAAQ,CAAS;IACzB,IAAI,OAAO,IAAI,OAAO,CAErB;IACD,IAAI,OAAO,CAAC,KAAK,EAAE,OAAO,EAGzB;IAED,YACC,GAAG,EAAE,GAAG,EACR,WAAW,EAAE,kBAAkB,EAC/B,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,MAAM,GAAG,SAAS,EAC3B,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,EACjC,QAAQ,EAAE,MAAM,IAAI,EACpB,OAAO,CAAC,EAAE,aAAa,EACvB,qBAAqB,CAAC,EAAE,MAAM,EAiD9B;IAED,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAgBjC;YAEa,wBAAwB;CAgBtC","sourcesContent":["/**\n * Multi-line editor component for extensions.\n * Supports Ctrl+G for external editor.\n */\n\nimport {\n\tContainer,\n\tEditor,\n\ttype EditorOptions,\n\ttype Focusable,\n\tgetKeybindings,\n\tSpacer,\n\tText,\n\ttype TUI,\n} from \"@earendil-works/pi-tui\";\nimport type { KeybindingsManager } from \"../../../core/keybindings.ts\";\nimport { editInExternalEditor } from \"../external-editor.ts\";\nimport { getEditorTheme, theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint } from \"./keybinding-hints.ts\";\n\nexport class ExtensionEditorComponent extends Container implements Focusable {\n\tprivate editor: Editor;\n\tprivate onSubmitCallback: (value: string) => void;\n\tprivate onCancelCallback: () => void;\n\tprivate tui: TUI;\n\tprivate keybindings: KeybindingsManager;\n\tprivate externalEditorCommand: string;\n\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.editor.focused = value;\n\t}\n\n\tconstructor(\n\t\ttui: TUI,\n\t\tkeybindings: KeybindingsManager,\n\t\ttitle: string,\n\t\tprefill: string | undefined,\n\t\tonSubmit: (value: string) => void,\n\t\tonCancel: () => void,\n\t\toptions?: EditorOptions,\n\t\texternalEditorCommand?: string,\n\t) {\n\t\tsuper();\n\n\t\tthis.tui = tui;\n\t\tthis.keybindings = keybindings;\n\t\tthis.externalEditorCommand =\n\t\t\texternalEditorCommand ||\n\t\t\tprocess.env.VISUAL ||\n\t\t\tprocess.env.EDITOR ||\n\t\t\t(process.platform === \"win32\" ? \"notepad\" : \"nano\");\n\t\tthis.onSubmitCallback = onSubmit;\n\t\tthis.onCancelCallback = onCancel;\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add title\n\t\tthis.addChild(new Text(theme.fg(\"accent\", title), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create editor\n\t\tthis.editor = new Editor(tui, getEditorTheme(), options);\n\t\tif (prefill) {\n\t\t\tthis.editor.setText(prefill);\n\t\t}\n\t\t// Wire up Enter to submit (Shift+Enter for newlines, like the main editor)\n\t\tthis.editor.onSubmit = (text: string) => {\n\t\t\tthis.onSubmitCallback(text);\n\t\t};\n\t\tthis.addChild(this.editor);\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add hint\n\t\tconst hint =\n\t\t\tkeyHint(\"tui.select.confirm\", \"submit\") +\n\t\t\t\" \" +\n\t\t\tkeyHint(\"tui.input.newLine\", \"newline\") +\n\t\t\t\" \" +\n\t\t\tkeyHint(\"tui.select.cancel\", \"cancel\") +\n\t\t\t` ${keyHint(\"app.editor.external\", \"external editor\")}`;\n\t\tthis.addChild(new Text(hint, 1, 0));\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\t// Escape or Ctrl+C to cancel\n\t\tif (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.onCancelCallback();\n\t\t\treturn;\n\t\t}\n\n\t\t// External editor (app keybinding)\n\t\tif (this.keybindings.matches(keyData, \"app.editor.external\")) {\n\t\t\tvoid this.handleOpenExternalEditor();\n\t\t\treturn;\n\t\t}\n\n\t\t// Forward to editor\n\t\tthis.editor.handleInput(keyData);\n\t}\n\n\tprivate async handleOpenExternalEditor(): Promise {\n\t\tconst content = this.editor.getText();\n\t\tthis.tui.stop();\n\t\ttry {\n\t\t\tconst result = await editInExternalEditor({\n\t\t\t\tcommand: this.externalEditorCommand,\n\t\t\t\tcontent,\n\t\t\t});\n\t\t\tif (result.status === \"complete\") {\n\t\t\t\tthis.editor.setText(result.content);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.tui.start();\n\t\t\tthis.tui.requestRender(true);\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/extension-editor.js b/dist/modes/interactive/components/extension-editor.js new file mode 100644 index 0000000..e583bb8 --- /dev/null +++ b/dist/modes/interactive/components/extension-editor.js @@ -0,0 +1,98 @@ +/** + * Multi-line editor component for extensions. + * Supports Ctrl+G for external editor. + */ +import { Container, Editor, getKeybindings, Spacer, Text, } from "@earendil-works/pi-tui"; +import { editInExternalEditor } from "../external-editor.js"; +import { getEditorTheme, theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyHint } from "./keybinding-hints.js"; +export class ExtensionEditorComponent extends Container { + editor; + onSubmitCallback; + onCancelCallback; + tui; + keybindings; + externalEditorCommand; + _focused = false; + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + this.editor.focused = value; + } + constructor(tui, keybindings, title, prefill, onSubmit, onCancel, options, externalEditorCommand) { + super(); + this.tui = tui; + this.keybindings = keybindings; + this.externalEditorCommand = + externalEditorCommand || + process.env.VISUAL || + process.env.EDITOR || + (process.platform === "win32" ? "notepad" : "nano"); + this.onSubmitCallback = onSubmit; + this.onCancelCallback = onCancel; + // Add top border + this.addChild(new DynamicBorder()); + this.addChild(new Spacer(1)); + // Add title + this.addChild(new Text(theme.fg("accent", title), 1, 0)); + this.addChild(new Spacer(1)); + // Create editor + this.editor = new Editor(tui, getEditorTheme(), options); + if (prefill) { + this.editor.setText(prefill); + } + // Wire up Enter to submit (Shift+Enter for newlines, like the main editor) + this.editor.onSubmit = (text) => { + this.onSubmitCallback(text); + }; + this.addChild(this.editor); + this.addChild(new Spacer(1)); + // Add hint + const hint = keyHint("tui.select.confirm", "submit") + + " " + + keyHint("tui.input.newLine", "newline") + + " " + + keyHint("tui.select.cancel", "cancel") + + ` ${keyHint("app.editor.external", "external editor")}`; + this.addChild(new Text(hint, 1, 0)); + this.addChild(new Spacer(1)); + // Add bottom border + this.addChild(new DynamicBorder()); + } + handleInput(keyData) { + const kb = getKeybindings(); + // Escape or Ctrl+C to cancel + if (kb.matches(keyData, "tui.select.cancel")) { + this.onCancelCallback(); + return; + } + // External editor (app keybinding) + if (this.keybindings.matches(keyData, "app.editor.external")) { + void this.handleOpenExternalEditor(); + return; + } + // Forward to editor + this.editor.handleInput(keyData); + } + async handleOpenExternalEditor() { + const content = this.editor.getText(); + this.tui.stop(); + try { + const result = await editInExternalEditor({ + command: this.externalEditorCommand, + content, + }); + if (result.status === "complete") { + this.editor.setText(result.content); + } + } + finally { + this.tui.start(); + this.tui.requestRender(true); + } + } +} +//# sourceMappingURL=extension-editor.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/extension-editor.js.map b/dist/modes/interactive/components/extension-editor.js.map new file mode 100644 index 0000000..9d50b4f --- /dev/null +++ b/dist/modes/interactive/components/extension-editor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"extension-editor.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/extension-editor.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACN,SAAS,EACT,MAAM,EAGN,cAAc,EACd,MAAM,EACN,IAAI,GAEJ,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAEhD,MAAM,OAAO,wBAAyB,SAAQ,SAAS;IAC9C,MAAM,CAAS;IACf,gBAAgB,CAA0B;IAC1C,gBAAgB,CAAa;IAC7B,GAAG,CAAM;IACT,WAAW,CAAqB;IAChC,qBAAqB,CAAS;IAE9B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AAC,OAAO,EAAE,qBAAqB,CAAC,EAAE,CAAC;YAC9D,KAAK,IAAI,CAAC,wBAAwB,EAAE,CAAC;YACrC,OAAO;QACR,CAAC;QAED,oBAAoB;QACpB,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAAA,CACjC;IAEO,KAAK,CAAC,wBAAwB,GAAkB;QACvD,MAAM,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACtC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;QAChB,IAAI,CAAC;YACJ,MAAM,MAAM,GAAG,MAAM,oBAAoB,CAAC;gBACzC,OAAO,EAAE,IAAI,CAAC,qBAAqB;gBACnC,OAAO;aACP,CAAC,CAAC;YACH,IAAI,MAAM,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;gBAClC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YACrC,CAAC;QACF,CAAC;gBAAS,CAAC;YACV,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC;YACjB,IAAI,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QAC9B,CAAC;IAAA,CACD;CACD","sourcesContent":["/**\n * Multi-line editor component for extensions.\n * Supports Ctrl+G for external editor.\n */\n\nimport {\n\tContainer,\n\tEditor,\n\ttype EditorOptions,\n\ttype Focusable,\n\tgetKeybindings,\n\tSpacer,\n\tText,\n\ttype TUI,\n} from \"@earendil-works/pi-tui\";\nimport type { KeybindingsManager } from \"../../../core/keybindings.ts\";\nimport { editInExternalEditor } from \"../external-editor.ts\";\nimport { getEditorTheme, theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint } from \"./keybinding-hints.ts\";\n\nexport class ExtensionEditorComponent extends Container implements Focusable {\n\tprivate editor: Editor;\n\tprivate onSubmitCallback: (value: string) => void;\n\tprivate onCancelCallback: () => void;\n\tprivate tui: TUI;\n\tprivate keybindings: KeybindingsManager;\n\tprivate externalEditorCommand: string;\n\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.editor.focused = value;\n\t}\n\n\tconstructor(\n\t\ttui: TUI,\n\t\tkeybindings: KeybindingsManager,\n\t\ttitle: string,\n\t\tprefill: string | undefined,\n\t\tonSubmit: (value: string) => void,\n\t\tonCancel: () => void,\n\t\toptions?: EditorOptions,\n\t\texternalEditorCommand?: string,\n\t) {\n\t\tsuper();\n\n\t\tthis.tui = tui;\n\t\tthis.keybindings = keybindings;\n\t\tthis.externalEditorCommand =\n\t\t\texternalEditorCommand ||\n\t\t\tprocess.env.VISUAL ||\n\t\t\tprocess.env.EDITOR ||\n\t\t\t(process.platform === \"win32\" ? \"notepad\" : \"nano\");\n\t\tthis.onSubmitCallback = onSubmit;\n\t\tthis.onCancelCallback = onCancel;\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add title\n\t\tthis.addChild(new Text(theme.fg(\"accent\", title), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create editor\n\t\tthis.editor = new Editor(tui, getEditorTheme(), options);\n\t\tif (prefill) {\n\t\t\tthis.editor.setText(prefill);\n\t\t}\n\t\t// Wire up Enter to submit (Shift+Enter for newlines, like the main editor)\n\t\tthis.editor.onSubmit = (text: string) => {\n\t\t\tthis.onSubmitCallback(text);\n\t\t};\n\t\tthis.addChild(this.editor);\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add hint\n\t\tconst hint =\n\t\t\tkeyHint(\"tui.select.confirm\", \"submit\") +\n\t\t\t\" \" +\n\t\t\tkeyHint(\"tui.input.newLine\", \"newline\") +\n\t\t\t\" \" +\n\t\t\tkeyHint(\"tui.select.cancel\", \"cancel\") +\n\t\t\t` ${keyHint(\"app.editor.external\", \"external editor\")}`;\n\t\tthis.addChild(new Text(hint, 1, 0));\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\t// Escape or Ctrl+C to cancel\n\t\tif (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.onCancelCallback();\n\t\t\treturn;\n\t\t}\n\n\t\t// External editor (app keybinding)\n\t\tif (this.keybindings.matches(keyData, \"app.editor.external\")) {\n\t\t\tvoid this.handleOpenExternalEditor();\n\t\t\treturn;\n\t\t}\n\n\t\t// Forward to editor\n\t\tthis.editor.handleInput(keyData);\n\t}\n\n\tprivate async handleOpenExternalEditor(): Promise {\n\t\tconst content = this.editor.getText();\n\t\tthis.tui.stop();\n\t\ttry {\n\t\t\tconst result = await editInExternalEditor({\n\t\t\t\tcommand: this.externalEditorCommand,\n\t\t\t\tcontent,\n\t\t\t});\n\t\t\tif (result.status === \"complete\") {\n\t\t\t\tthis.editor.setText(result.content);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.tui.start();\n\t\t\tthis.tui.requestRender(true);\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/extension-input.d.ts b/dist/modes/interactive/components/extension-input.d.ts new file mode 100644 index 0000000..d41b2ce --- /dev/null +++ b/dist/modes/interactive/components/extension-input.d.ts @@ -0,0 +1,23 @@ +/** + * Simple text input component for extensions. + */ +import { Container, type Focusable, type TUI } from "@earendil-works/pi-tui"; +export interface ExtensionInputOptions { + tui?: TUI; + timeout?: number; +} +export declare class ExtensionInputComponent extends Container implements Focusable { + private input; + private onSubmitCallback; + private onCancelCallback; + private titleText; + private baseTitle; + private countdown; + private _focused; + get focused(): boolean; + set focused(value: boolean); + constructor(title: string, _placeholder: string | undefined, onSubmit: (value: string) => void, onCancel: () => void, opts?: ExtensionInputOptions); + handleInput(keyData: string): void; + dispose(): void; +} +//# sourceMappingURL=extension-input.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/extension-input.d.ts.map b/dist/modes/interactive/components/extension-input.d.ts.map new file mode 100644 index 0000000..521e6b1 --- /dev/null +++ b/dist/modes/interactive/components/extension-input.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"extension-input.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/extension-input.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,SAAS,EAAE,KAAK,SAAS,EAAuC,KAAK,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAMlH,MAAM,WAAW,qBAAqB;IACrC,GAAG,CAAC,EAAE,GAAG,CAAC;IACV,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,qBAAa,uBAAwB,SAAQ,SAAU,YAAW,SAAS;IAC1E,OAAO,CAAC,KAAK,CAAQ;IACrB,OAAO,CAAC,gBAAgB,CAA0B;IAClD,OAAO,CAAC,gBAAgB,CAAa;IACrC,OAAO,CAAC,SAAS,CAAO;IACxB,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,SAAS,CAA6B;IAG9C,OAAO,CAAC,QAAQ,CAAS;IACzB,IAAI,OAAO,IAAI,OAAO,CAErB;IACD,IAAI,OAAO,CAAC,KAAK,EAAE,OAAO,EAGzB;IAED,YACC,KAAK,EAAE,MAAM,EACb,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,EACjC,QAAQ,EAAE,MAAM,IAAI,EACpB,IAAI,CAAC,EAAE,qBAAqB,EAgC5B;IAED,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CASjC;IAED,OAAO,IAAI,IAAI,CAEd;CACD","sourcesContent":["/**\n * Simple text input component for extensions.\n */\n\nimport { Container, type Focusable, getKeybindings, Input, Spacer, Text, type TUI } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\nimport { CountdownTimer } from \"./countdown-timer.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint } from \"./keybinding-hints.ts\";\n\nexport interface ExtensionInputOptions {\n\ttui?: TUI;\n\ttimeout?: number;\n}\n\nexport class ExtensionInputComponent extends Container implements Focusable {\n\tprivate input: Input;\n\tprivate onSubmitCallback: (value: string) => void;\n\tprivate onCancelCallback: () => void;\n\tprivate titleText: Text;\n\tprivate baseTitle: string;\n\tprivate countdown: CountdownTimer | undefined;\n\n\t// Focusable implementation - propagate to input for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.input.focused = value;\n\t}\n\n\tconstructor(\n\t\ttitle: string,\n\t\t_placeholder: string | undefined,\n\t\tonSubmit: (value: string) => void,\n\t\tonCancel: () => void,\n\t\topts?: ExtensionInputOptions,\n\t) {\n\t\tsuper();\n\n\t\tthis.onSubmitCallback = onSubmit;\n\t\tthis.onCancelCallback = onCancel;\n\t\tthis.baseTitle = title;\n\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\tthis.titleText = new Text(theme.fg(\"accent\", title), 1, 0);\n\t\tthis.addChild(this.titleText);\n\t\tthis.addChild(new Spacer(1));\n\n\t\tif (opts?.timeout && opts.timeout > 0 && opts.tui) {\n\t\t\tthis.countdown = new CountdownTimer(\n\t\t\t\topts.timeout,\n\t\t\t\topts.tui,\n\t\t\t\t(s) => this.titleText.setText(theme.fg(\"accent\", `${this.baseTitle} (${s}s)`)),\n\t\t\t\t() => this.onCancelCallback(),\n\t\t\t);\n\t\t}\n\n\t\tthis.input = new Input();\n\t\tthis.addChild(this.input);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(\n\t\t\tnew Text(`${keyHint(\"tui.select.confirm\", \"submit\")} ${keyHint(\"tui.select.cancel\", \"cancel\")}`, 1, 0),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"tui.select.confirm\") || keyData === \"\\n\") {\n\t\t\tthis.onSubmitCallback(this.input.getValue());\n\t\t} else if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.onCancelCallback();\n\t\t} else {\n\t\t\tthis.input.handleInput(keyData);\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.countdown?.dispose();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/extension-input.js b/dist/modes/interactive/components/extension-input.js new file mode 100644 index 0000000..333722f --- /dev/null +++ b/dist/modes/interactive/components/extension-input.js @@ -0,0 +1,61 @@ +/** + * Simple text input component for extensions. + */ +import { Container, getKeybindings, Input, Spacer, Text } from "@earendil-works/pi-tui"; +import { theme } from "../theme/theme.js"; +import { CountdownTimer } from "./countdown-timer.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyHint } from "./keybinding-hints.js"; +export class ExtensionInputComponent extends Container { + input; + onSubmitCallback; + onCancelCallback; + titleText; + baseTitle; + countdown; + // Focusable implementation - propagate to input for IME cursor positioning + _focused = false; + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + this.input.focused = value; + } + constructor(title, _placeholder, onSubmit, onCancel, opts) { + super(); + this.onSubmitCallback = onSubmit; + this.onCancelCallback = onCancel; + this.baseTitle = title; + this.addChild(new DynamicBorder()); + this.addChild(new Spacer(1)); + this.titleText = new Text(theme.fg("accent", title), 1, 0); + this.addChild(this.titleText); + this.addChild(new Spacer(1)); + if (opts?.timeout && opts.timeout > 0 && opts.tui) { + this.countdown = new CountdownTimer(opts.timeout, opts.tui, (s) => this.titleText.setText(theme.fg("accent", `${this.baseTitle} (${s}s)`)), () => this.onCancelCallback()); + } + this.input = new Input(); + this.addChild(this.input); + this.addChild(new Spacer(1)); + this.addChild(new Text(`${keyHint("tui.select.confirm", "submit")} ${keyHint("tui.select.cancel", "cancel")}`, 1, 0)); + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder()); + } + handleInput(keyData) { + const kb = getKeybindings(); + if (kb.matches(keyData, "tui.select.confirm") || keyData === "\n") { + this.onSubmitCallback(this.input.getValue()); + } + else if (kb.matches(keyData, "tui.select.cancel")) { + this.onCancelCallback(); + } + else { + this.input.handleInput(keyData); + } + } + dispose() { + this.countdown?.dispose(); + } +} +//# sourceMappingURL=extension-input.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/extension-input.js.map b/dist/modes/interactive/components/extension-input.js.map new file mode 100644 index 0000000..9074ebf --- /dev/null +++ b/dist/modes/interactive/components/extension-input.js.map @@ -0,0 +1 @@ +{"version":3,"file":"extension-input.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/extension-input.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,SAAS,EAAkB,cAAc,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAY,MAAM,wBAAwB,CAAC;AAClH,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAOhD,MAAM,OAAO,uBAAwB,SAAQ,SAAS;IAC7C,KAAK,CAAQ;IACb,gBAAgB,CAA0B;IAC1C,gBAAgB,CAAa;IAC7B,SAAS,CAAO;IAChB,SAAS,CAAS;IAClB,SAAS,CAA6B;IAE9C,2EAA2E;IACnE,QAAQ,GAAG,KAAK,CAAC;IACzB,IAAI,OAAO,GAAY;QACtB,OAAO,IAAI,CAAC,QAAQ,CAAC;IAAA,CACrB;IACD,IAAI,OAAO,CAAC,KAAc,EAAE;QAC3B,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;QACtB,IAAI,CAAC,K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QAC1B,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,CAAC,QAAQ,CACZ,IAAI,IAAI,CAAC,GAAG,OAAO,CAAC,oBAAoB,EAAE,QAAQ,CAAC,KAAK,OAAO,CAAC,mBAAmB,EAAE,QAAQ,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CACvG,CAAC;QACF,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;IAAA,CACnC;IAED,WAAW,CAAC,OAAe,EAAQ;QAClC,MAAM,EAAE,GAAG,cAAc,EAAE,CAAC;QAC5B,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,oBAAoB,CAAC,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;YACnE,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;QAC9C,CAAC;aAAM,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,EAAE,CAAC;YACrD,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACzB,CAAC;aAAM,CAAC;YACP,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACjC,CAAC;IAAA,CACD;IAED,OAAO,GAAS;QACf,IAAI,CAAC,SAAS,EAAE,OAAO,EAAE,CAAC;IAAA,CAC1B;CACD","sourcesContent":["/**\n * Simple text input component for extensions.\n */\n\nimport { Container, type Focusable, getKeybindings, Input, Spacer, Text, type TUI } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\nimport { CountdownTimer } from \"./countdown-timer.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint } from \"./keybinding-hints.ts\";\n\nexport interface ExtensionInputOptions {\n\ttui?: TUI;\n\ttimeout?: number;\n}\n\nexport class ExtensionInputComponent extends Container implements Focusable {\n\tprivate input: Input;\n\tprivate onSubmitCallback: (value: string) => void;\n\tprivate onCancelCallback: () => void;\n\tprivate titleText: Text;\n\tprivate baseTitle: string;\n\tprivate countdown: CountdownTimer | undefined;\n\n\t// Focusable implementation - propagate to input for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.input.focused = value;\n\t}\n\n\tconstructor(\n\t\ttitle: string,\n\t\t_placeholder: string | undefined,\n\t\tonSubmit: (value: string) => void,\n\t\tonCancel: () => void,\n\t\topts?: ExtensionInputOptions,\n\t) {\n\t\tsuper();\n\n\t\tthis.onSubmitCallback = onSubmit;\n\t\tthis.onCancelCallback = onCancel;\n\t\tthis.baseTitle = title;\n\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\tthis.titleText = new Text(theme.fg(\"accent\", title), 1, 0);\n\t\tthis.addChild(this.titleText);\n\t\tthis.addChild(new Spacer(1));\n\n\t\tif (opts?.timeout && opts.timeout > 0 && opts.tui) {\n\t\t\tthis.countdown = new CountdownTimer(\n\t\t\t\topts.timeout,\n\t\t\t\topts.tui,\n\t\t\t\t(s) => this.titleText.setText(theme.fg(\"accent\", `${this.baseTitle} (${s}s)`)),\n\t\t\t\t() => this.onCancelCallback(),\n\t\t\t);\n\t\t}\n\n\t\tthis.input = new Input();\n\t\tthis.addChild(this.input);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(\n\t\t\tnew Text(`${keyHint(\"tui.select.confirm\", \"submit\")} ${keyHint(\"tui.select.cancel\", \"cancel\")}`, 1, 0),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"tui.select.confirm\") || keyData === \"\\n\") {\n\t\t\tthis.onSubmitCallback(this.input.getValue());\n\t\t} else if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.onCancelCallback();\n\t\t} else {\n\t\t\tthis.input.handleInput(keyData);\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.countdown?.dispose();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/extension-selector.d.ts b/dist/modes/interactive/components/extension-selector.d.ts new file mode 100644 index 0000000..c966996 --- /dev/null +++ b/dist/modes/interactive/components/extension-selector.d.ts @@ -0,0 +1,26 @@ +/** + * Generic selector component for extensions. + * Displays a list of string options with keyboard navigation. + */ +import { Container, type TUI } from "@earendil-works/pi-tui"; +export interface ExtensionSelectorOptions { + tui?: TUI; + timeout?: number; + onToggleToolsExpanded?: () => void; +} +export declare class ExtensionSelectorComponent extends Container { + private options; + private selectedIndex; + private listContainer; + private onSelectCallback; + private onCancelCallback; + private titleText; + private baseTitle; + private countdown; + private onToggleToolsExpanded; + constructor(title: string, options: string[], onSelect: (option: string) => void, onCancel: () => void, opts?: ExtensionSelectorOptions); + private updateList; + handleInput(keyData: string): void; + dispose(): void; +} +//# sourceMappingURL=extension-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/extension-selector.d.ts.map b/dist/modes/interactive/components/extension-selector.d.ts.map new file mode 100644 index 0000000..969dc7f --- /dev/null +++ b/dist/modes/interactive/components/extension-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"extension-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/extension-selector.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,SAAS,EAAgC,KAAK,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAM3F,MAAM,WAAW,wBAAwB;IACxC,GAAG,CAAC,EAAE,GAAG,CAAC;IACV,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,qBAAqB,CAAC,EAAE,MAAM,IAAI,CAAC;CACnC;AAED,qBAAa,0BAA2B,SAAQ,SAAS;IACxD,OAAO,CAAC,OAAO,CAAW;IAC1B,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,aAAa,CAAY;IACjC,OAAO,CAAC,gBAAgB,CAA2B;IACnD,OAAO,CAAC,gBAAgB,CAAa;IACrC,OAAO,CAAC,SAAS,CAAO;IACxB,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,SAAS,CAA6B;IAC9C,OAAO,CAAC,qBAAqB,CAA2B;IAExD,YACC,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,MAAM,EAAE,EACjB,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,EAClC,QAAQ,EAAE,MAAM,IAAI,EACpB,IAAI,CAAC,EAAE,wBAAwB,EA4C/B;IAED,OAAO,CAAC,UAAU;IAWlB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAgBjC;IAED,OAAO,IAAI,IAAI,CAEd;CACD","sourcesContent":["/**\n * Generic selector component for extensions.\n * Displays a list of string options with keyboard navigation.\n */\n\nimport { Container, getKeybindings, Spacer, Text, type TUI } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\nimport { CountdownTimer } from \"./countdown-timer.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint, rawKeyHint } from \"./keybinding-hints.ts\";\n\nexport interface ExtensionSelectorOptions {\n\ttui?: TUI;\n\ttimeout?: number;\n\tonToggleToolsExpanded?: () => void;\n}\n\nexport class ExtensionSelectorComponent extends Container {\n\tprivate options: string[];\n\tprivate selectedIndex = 0;\n\tprivate listContainer: Container;\n\tprivate onSelectCallback: (option: string) => void;\n\tprivate onCancelCallback: () => void;\n\tprivate titleText: Text;\n\tprivate baseTitle: string;\n\tprivate countdown: CountdownTimer | undefined;\n\tprivate onToggleToolsExpanded: (() => void) | undefined;\n\n\tconstructor(\n\t\ttitle: string,\n\t\toptions: string[],\n\t\tonSelect: (option: string) => void,\n\t\tonCancel: () => void,\n\t\topts?: ExtensionSelectorOptions,\n\t) {\n\t\tsuper();\n\n\t\tthis.options = options;\n\t\tthis.onSelectCallback = onSelect;\n\t\tthis.onCancelCallback = onCancel;\n\t\tthis.onToggleToolsExpanded = opts?.onToggleToolsExpanded;\n\t\tthis.baseTitle = title;\n\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\tthis.titleText = new Text(theme.fg(\"accent\", theme.bold(title)), 1, 0);\n\t\tthis.addChild(this.titleText);\n\t\tthis.addChild(new Spacer(1));\n\n\t\tif (opts?.timeout && opts.timeout > 0 && opts.tui) {\n\t\t\tthis.countdown = new CountdownTimer(\n\t\t\t\topts.timeout,\n\t\t\t\topts.tui,\n\t\t\t\t(s) => this.titleText.setText(theme.fg(\"accent\", theme.bold(`${this.baseTitle} (${s}s)`))),\n\t\t\t\t() => this.onCancelCallback(),\n\t\t\t);\n\t\t}\n\n\t\tthis.listContainer = new Container();\n\t\tthis.addChild(this.listContainer);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(\n\t\t\tnew Text(\n\t\t\t\trawKeyHint(\"↑↓\", \"navigate\") +\n\t\t\t\t\t\" \" +\n\t\t\t\t\tkeyHint(\"tui.select.confirm\", \"select\") +\n\t\t\t\t\t\" \" +\n\t\t\t\t\tkeyHint(\"tui.select.cancel\", \"cancel\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\tthis.updateList();\n\t}\n\n\tprivate updateList(): void {\n\t\tthis.listContainer.clear();\n\t\tfor (let i = 0; i < this.options.length; i++) {\n\t\t\tconst isSelected = i === this.selectedIndex;\n\t\t\tconst text = isSelected\n\t\t\t\t? theme.fg(\"accent\", \"→ \") + theme.fg(\"accent\", this.options[i])\n\t\t\t\t: ` ${theme.fg(\"text\", this.options[i])}`;\n\t\t\tthis.listContainer.addChild(new Text(text, 1, 0));\n\t\t}\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"app.tools.expand\")) {\n\t\t\tthis.onToggleToolsExpanded?.();\n\t\t} else if (kb.matches(keyData, \"tui.select.up\") || keyData === \"k\") {\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - 1);\n\t\t\tthis.updateList();\n\t\t} else if (kb.matches(keyData, \"tui.select.down\") || keyData === \"j\") {\n\t\t\tthis.selectedIndex = Math.min(this.options.length - 1, this.selectedIndex + 1);\n\t\t\tthis.updateList();\n\t\t} else if (kb.matches(keyData, \"tui.select.confirm\") || keyData === \"\\n\") {\n\t\t\tconst selected = this.options[this.selectedIndex];\n\t\t\tif (selected) this.onSelectCallback(selected);\n\t\t} else if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.onCancelCallback();\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.countdown?.dispose();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/extension-selector.js b/dist/modes/interactive/components/extension-selector.js new file mode 100644 index 0000000..8220e06 --- /dev/null +++ b/dist/modes/interactive/components/extension-selector.js @@ -0,0 +1,83 @@ +/** + * Generic selector component for extensions. + * Displays a list of string options with keyboard navigation. + */ +import { Container, getKeybindings, Spacer, Text } from "@earendil-works/pi-tui"; +import { theme } from "../theme/theme.js"; +import { CountdownTimer } from "./countdown-timer.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyHint, rawKeyHint } from "./keybinding-hints.js"; +export class ExtensionSelectorComponent extends Container { + options; + selectedIndex = 0; + listContainer; + onSelectCallback; + onCancelCallback; + titleText; + baseTitle; + countdown; + onToggleToolsExpanded; + constructor(title, options, onSelect, onCancel, opts) { + super(); + this.options = options; + this.onSelectCallback = onSelect; + this.onCancelCallback = onCancel; + this.onToggleToolsExpanded = opts?.onToggleToolsExpanded; + this.baseTitle = title; + this.addChild(new DynamicBorder()); + this.addChild(new Spacer(1)); + this.titleText = new Text(theme.fg("accent", theme.bold(title)), 1, 0); + this.addChild(this.titleText); + this.addChild(new Spacer(1)); + if (opts?.timeout && opts.timeout > 0 && opts.tui) { + this.countdown = new CountdownTimer(opts.timeout, opts.tui, (s) => this.titleText.setText(theme.fg("accent", theme.bold(`${this.baseTitle} (${s}s)`))), () => this.onCancelCallback()); + } + this.listContainer = new Container(); + this.addChild(this.listContainer); + this.addChild(new Spacer(1)); + this.addChild(new Text(rawKeyHint("↑↓", "navigate") + + " " + + keyHint("tui.select.confirm", "select") + + " " + + keyHint("tui.select.cancel", "cancel"), 1, 0)); + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder()); + this.updateList(); + } + updateList() { + this.listContainer.clear(); + for (let i = 0; i < this.options.length; i++) { + const isSelected = i === this.selectedIndex; + const text = isSelected + ? theme.fg("accent", "→ ") + theme.fg("accent", this.options[i]) + : ` ${theme.fg("text", this.options[i])}`; + this.listContainer.addChild(new Text(text, 1, 0)); + } + } + handleInput(keyData) { + const kb = getKeybindings(); + if (kb.matches(keyData, "app.tools.expand")) { + this.onToggleToolsExpanded?.(); + } + else if (kb.matches(keyData, "tui.select.up") || keyData === "k") { + this.selectedIndex = Math.max(0, this.selectedIndex - 1); + this.updateList(); + } + else if (kb.matches(keyData, "tui.select.down") || keyData === "j") { + this.selectedIndex = Math.min(this.options.length - 1, this.selectedIndex + 1); + this.updateList(); + } + else if (kb.matches(keyData, "tui.select.confirm") || keyData === "\n") { + const selected = this.options[this.selectedIndex]; + if (selected) + this.onSelectCallback(selected); + } + else if (kb.matches(keyData, "tui.select.cancel")) { + this.onCancelCallback(); + } + } + dispose() { + this.countdown?.dispose(); + } +} +//# sourceMappingURL=extension-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/extension-selector.js.map b/dist/modes/interactive/components/extension-selector.js.map new file mode 100644 index 0000000..ef9c15b --- /dev/null +++ b/dist/modes/interactive/components/extension-selector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"extension-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/extension-selector.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,EAAE,IAAI,EAAY,MAAM,wBAAwB,CAAC;AAC3F,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAQ5D,MAAM,OAAO,0BAA2B,SAAQ,SAAS;IAChD,OAAO,CAAW;IAClB,aAAa,GAAG,CAAC,CAAC;IAClB,aAAa,CAAY;IACzB,gBAAgB,CAA2B;IAC3C,gBAAgB,CAAa;IAC7B,SAAS,CAAO;IAChB,SAAS,CAAS;IAClB,SAAS,CAA6B;IACtC,qBAAqB,CAA2B;IAExD,YACC,KAAa,EACb,OAAiB,EACjB,QAAkC,EAClC,QAAoB,EACpB,IAA+B,EAC9B;QACD,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,gBAAgB,GAAG,QAAQ,CAAC;QACjC,IAAI,CAAC,gBAAgB,GAAG,QAAQ,CAAC;QACjC,IAAI,CAAC,qBAAqB,GAAG,IAAI,EAAE,qBAAqB,CAAC;QACzD,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QAEvB,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;QACnC,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAE7B,IAAI,CAAC,SAAS,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,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IAAI,OAAO,KAAK,GAAG,EAAE,CAAC;YACtE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,IAAI,CAAC,aAAa,GAAG,CAAC,CAAC,CAAC;YAC/E,IAAI,CAAC,UAAU,EAAE,CAAC;QACnB,CAAC;aAAM,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,oBAAoB,CAAC,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;YAC1E,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;YAClD,IAAI,QAAQ;gBAAE,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;QAC/C,CAAC;aAAM,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,EAAE,CAAC;YACrD,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACzB,CAAC;IAAA,CACD;IAED,OAAO,GAAS;QACf,IAAI,CAAC,SAAS,EAAE,OAAO,EAAE,CAAC;IAAA,CAC1B;CACD","sourcesContent":["/**\n * Generic selector component for extensions.\n * Displays a list of string options with keyboard navigation.\n */\n\nimport { Container, getKeybindings, Spacer, Text, type TUI } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\nimport { CountdownTimer } from \"./countdown-timer.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint, rawKeyHint } from \"./keybinding-hints.ts\";\n\nexport interface ExtensionSelectorOptions {\n\ttui?: TUI;\n\ttimeout?: number;\n\tonToggleToolsExpanded?: () => void;\n}\n\nexport class ExtensionSelectorComponent extends Container {\n\tprivate options: string[];\n\tprivate selectedIndex = 0;\n\tprivate listContainer: Container;\n\tprivate onSelectCallback: (option: string) => void;\n\tprivate onCancelCallback: () => void;\n\tprivate titleText: Text;\n\tprivate baseTitle: string;\n\tprivate countdown: CountdownTimer | undefined;\n\tprivate onToggleToolsExpanded: (() => void) | undefined;\n\n\tconstructor(\n\t\ttitle: string,\n\t\toptions: string[],\n\t\tonSelect: (option: string) => void,\n\t\tonCancel: () => void,\n\t\topts?: ExtensionSelectorOptions,\n\t) {\n\t\tsuper();\n\n\t\tthis.options = options;\n\t\tthis.onSelectCallback = onSelect;\n\t\tthis.onCancelCallback = onCancel;\n\t\tthis.onToggleToolsExpanded = opts?.onToggleToolsExpanded;\n\t\tthis.baseTitle = title;\n\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\tthis.titleText = new Text(theme.fg(\"accent\", theme.bold(title)), 1, 0);\n\t\tthis.addChild(this.titleText);\n\t\tthis.addChild(new Spacer(1));\n\n\t\tif (opts?.timeout && opts.timeout > 0 && opts.tui) {\n\t\t\tthis.countdown = new CountdownTimer(\n\t\t\t\topts.timeout,\n\t\t\t\topts.tui,\n\t\t\t\t(s) => this.titleText.setText(theme.fg(\"accent\", theme.bold(`${this.baseTitle} (${s}s)`))),\n\t\t\t\t() => this.onCancelCallback(),\n\t\t\t);\n\t\t}\n\n\t\tthis.listContainer = new Container();\n\t\tthis.addChild(this.listContainer);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(\n\t\t\tnew Text(\n\t\t\t\trawKeyHint(\"↑↓\", \"navigate\") +\n\t\t\t\t\t\" \" +\n\t\t\t\t\tkeyHint(\"tui.select.confirm\", \"select\") +\n\t\t\t\t\t\" \" +\n\t\t\t\t\tkeyHint(\"tui.select.cancel\", \"cancel\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\tthis.updateList();\n\t}\n\n\tprivate updateList(): void {\n\t\tthis.listContainer.clear();\n\t\tfor (let i = 0; i < this.options.length; i++) {\n\t\t\tconst isSelected = i === this.selectedIndex;\n\t\t\tconst text = isSelected\n\t\t\t\t? theme.fg(\"accent\", \"→ \") + theme.fg(\"accent\", this.options[i])\n\t\t\t\t: ` ${theme.fg(\"text\", this.options[i])}`;\n\t\t\tthis.listContainer.addChild(new Text(text, 1, 0));\n\t\t}\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"app.tools.expand\")) {\n\t\t\tthis.onToggleToolsExpanded?.();\n\t\t} else if (kb.matches(keyData, \"tui.select.up\") || keyData === \"k\") {\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - 1);\n\t\t\tthis.updateList();\n\t\t} else if (kb.matches(keyData, \"tui.select.down\") || keyData === \"j\") {\n\t\t\tthis.selectedIndex = Math.min(this.options.length - 1, this.selectedIndex + 1);\n\t\t\tthis.updateList();\n\t\t} else if (kb.matches(keyData, \"tui.select.confirm\") || keyData === \"\\n\") {\n\t\t\tconst selected = this.options[this.selectedIndex];\n\t\t\tif (selected) this.onSelectCallback(selected);\n\t\t} else if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.onCancelCallback();\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.countdown?.dispose();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/first-time-setup.d.ts b/dist/modes/interactive/components/first-time-setup.d.ts new file mode 100644 index 0000000..948ea3d --- /dev/null +++ b/dist/modes/interactive/components/first-time-setup.d.ts @@ -0,0 +1,25 @@ +import { Container } from "@earendil-works/pi-tui"; +import { type TerminalTheme } from "../theme/theme.ts"; +export interface FirstTimeSetupResult { + theme: TerminalTheme; + shareAnalytics: boolean; +} +export interface FirstTimeSetupOptions { + detectedTheme: TerminalTheme; + onThemePreview: (themeName: TerminalTheme) => void; + onSubmit: (result: FirstTimeSetupResult) => void; + onCancel: () => void; +} +/** First-time setup dialog: theme choice and analytics opt-in. */ +export declare class FirstTimeSetupComponent extends Container { + private step; + private themeIndex; + private analyticsIndex; + private readonly options; + constructor(options: FirstTimeSetupOptions); + private update; + private addOptionList; + private moveSelection; + handleInput(keyData: string): void; +} +//# sourceMappingURL=first-time-setup.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/first-time-setup.d.ts.map b/dist/modes/interactive/components/first-time-setup.d.ts.map new file mode 100644 index 0000000..166b438 --- /dev/null +++ b/dist/modes/interactive/components/first-time-setup.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"first-time-setup.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/first-time-setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAgC,MAAM,wBAAwB,CAAC;AAEjF,OAAO,EAAE,KAAK,aAAa,EAAS,MAAM,mBAAmB,CAAC;AAI9D,MAAM,WAAW,oBAAoB;IACpC,KAAK,EAAE,aAAa,CAAC;IACrB,cAAc,EAAE,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,qBAAqB;IACrC,aAAa,EAAE,aAAa,CAAC;IAC7B,cAAc,EAAE,CAAC,SAAS,EAAE,aAAa,KAAK,IAAI,CAAC;IACnD,QAAQ,EAAE,CAAC,MAAM,EAAE,oBAAoB,KAAK,IAAI,CAAC;IACjD,QAAQ,EAAE,MAAM,IAAI,CAAC;CACrB;AAcD,kEAAkE;AAClE,qBAAa,uBAAwB,SAAQ,SAAS;IACrD,OAAO,CAAC,IAAI,CAAkC;IAC9C,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwB;IAEhD,YAAY,OAAO,EAAE,qBAAqB,EAQzC;IAGD,OAAO,CAAC,MAAM;IAsDd,OAAO,CAAC,aAAa;IASrB,OAAO,CAAC,aAAa;IAarB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAmBjC;CACD","sourcesContent":["import { Container, getKeybindings, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport { APP_NAME } from \"../../../config.ts\";\nimport { type TerminalTheme, theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint, rawKeyHint } from \"./keybinding-hints.ts\";\n\nexport interface FirstTimeSetupResult {\n\ttheme: TerminalTheme;\n\tshareAnalytics: boolean;\n}\n\nexport interface FirstTimeSetupOptions {\n\tdetectedTheme: TerminalTheme;\n\tonThemePreview: (themeName: TerminalTheme) => void;\n\tonSubmit: (result: FirstTimeSetupResult) => void;\n\tonCancel: () => void;\n}\n\nconst THEME_OPTIONS: Array<{ value: TerminalTheme; label: string }> = [\n\t{ value: \"dark\", label: \"Dark\" },\n\t{ value: \"light\", label: \"Light\" },\n];\n\nconst ANALYTICS_OPTIONS: Array<{ value: boolean; label: string }> = [\n\t{ value: true, label: \"Share anonymous usage data\" },\n\t{ value: false, label: \"Don't share\" },\n];\n\nconst SETUP_LOGO_LINES = [\"██████\", \"██ ██\", \"████ ██\", \"██ ██\"];\n\n/** First-time setup dialog: theme choice and analytics opt-in. */\nexport class FirstTimeSetupComponent extends Container {\n\tprivate step: \"theme\" | \"analytics\" = \"theme\";\n\tprivate themeIndex: number;\n\tprivate analyticsIndex = 0;\n\tprivate readonly options: FirstTimeSetupOptions;\n\n\tconstructor(options: FirstTimeSetupOptions) {\n\t\tsuper();\n\t\tthis.options = options;\n\t\tthis.themeIndex = Math.max(\n\t\t\t0,\n\t\t\tTHEME_OPTIONS.findIndex((option) => option.value === options.detectedTheme),\n\t\t);\n\t\tthis.update();\n\t}\n\n\t// Rebuild the whole dialog on every change so theme previews recolor all text.\n\tprivate update(): void {\n\t\tthis.clear();\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.fg(\"accent\", SETUP_LOGO_LINES.join(\"\\n\")), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(\n\t\t\tnew Text(theme.fg(\"accent\", theme.bold(`Welcome to ${APP_NAME}, the minimal coding agent.`)), 1, 0),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\n\t\tif (this.step === \"theme\") {\n\t\t\tthis.addChild(new Text(theme.fg(\"text\", \"Pick a theme.\"), 1, 0));\n\t\t\tthis.addChild(new Text(theme.fg(\"muted\", `Detected system appearance: ${this.options.detectedTheme}`), 1, 0));\n\t\t\tthis.addChild(new Spacer(1));\n\t\t\tthis.addOptionList(\n\t\t\t\tTHEME_OPTIONS.map((option) => option.label),\n\t\t\t\tthis.themeIndex,\n\t\t\t);\n\t\t} else {\n\t\t\tthis.addChild(new Text(theme.fg(\"text\", \"Opt-in to anonymous usage data sharing?\"), 1, 0));\n\t\t\tthis.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\ttheme.fg(\n\t\t\t\t\t\t\"muted\",\n\t\t\t\t\t\t\"Opting in stores a tracking identifier in settings.json and enables anonymous\\nusage analytics. This helps us to better debug, reproduce, and resolve issues\\nand bugs within Pi. You can observe what is shared using /privacy and make\\nchanges anytime in settings.json.\",\n\t\t\t\t\t),\n\t\t\t\t\t1,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t\tthis.addChild(new Spacer(1));\n\t\t\tthis.addOptionList(\n\t\t\t\tANALYTICS_OPTIONS.map((option) => option.label),\n\t\t\t\tthis.analyticsIndex,\n\t\t\t);\n\t\t}\n\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(\n\t\t\tnew Text(\n\t\t\t\trawKeyHint(\"↑↓\", \"navigate\") +\n\t\t\t\t\t\" \" +\n\t\t\t\t\tkeyHint(\"tui.select.confirm\", this.step === \"theme\" ? \"continue\" : \"finish\") +\n\t\t\t\t\t\" \" +\n\t\t\t\t\tkeyHint(\"tui.select.cancel\", \"skip setup\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tprivate addOptionList(labels: string[], selectedIndex: number): void {\n\t\tfor (let i = 0; i < labels.length; i++) {\n\t\t\tconst isSelected = i === selectedIndex;\n\t\t\tconst prefix = isSelected ? theme.fg(\"accent\", \"→ \") : \" \";\n\t\t\tconst label = isSelected ? theme.fg(\"accent\", labels[i]) : theme.fg(\"text\", labels[i]);\n\t\t\tthis.addChild(new Text(`${prefix}${label}`, 1, 0));\n\t\t}\n\t}\n\n\tprivate moveSelection(delta: number): void {\n\t\tif (this.step === \"theme\") {\n\t\t\tconst next = Math.max(0, Math.min(THEME_OPTIONS.length - 1, this.themeIndex + delta));\n\t\t\tif (next !== this.themeIndex) {\n\t\t\t\tthis.themeIndex = next;\n\t\t\t\tthis.options.onThemePreview(THEME_OPTIONS[this.themeIndex].value);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.analyticsIndex = Math.max(0, Math.min(ANALYTICS_OPTIONS.length - 1, this.analyticsIndex + delta));\n\t\t}\n\t\tthis.update();\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"tui.select.up\") || keyData === \"k\") {\n\t\t\tthis.moveSelection(-1);\n\t\t} else if (kb.matches(keyData, \"tui.select.down\") || keyData === \"j\") {\n\t\t\tthis.moveSelection(1);\n\t\t} else if (kb.matches(keyData, \"tui.select.confirm\") || keyData === \"\\n\") {\n\t\t\tif (this.step === \"theme\") {\n\t\t\t\tthis.step = \"analytics\";\n\t\t\t\tthis.update();\n\t\t\t} else {\n\t\t\t\tthis.options.onSubmit({\n\t\t\t\t\ttheme: THEME_OPTIONS[this.themeIndex].value,\n\t\t\t\t\tshareAnalytics: ANALYTICS_OPTIONS[this.analyticsIndex].value,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.options.onCancel();\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/first-time-setup.js b/dist/modes/interactive/components/first-time-setup.js new file mode 100644 index 0000000..57f12d0 --- /dev/null +++ b/dist/modes/interactive/components/first-time-setup.js @@ -0,0 +1,103 @@ +import { Container, getKeybindings, Spacer, Text } from "@earendil-works/pi-tui"; +import { APP_NAME } from "../../../config.js"; +import { theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyHint, rawKeyHint } from "./keybinding-hints.js"; +const THEME_OPTIONS = [ + { value: "dark", label: "Dark" }, + { value: "light", label: "Light" }, +]; +const ANALYTICS_OPTIONS = [ + { value: true, label: "Share anonymous usage data" }, + { value: false, label: "Don't share" }, +]; +const SETUP_LOGO_LINES = ["██████", "██ ██", "████ ██", "██ ██"]; +/** First-time setup dialog: theme choice and analytics opt-in. */ +export class FirstTimeSetupComponent extends Container { + step = "theme"; + themeIndex; + analyticsIndex = 0; + options; + constructor(options) { + super(); + this.options = options; + this.themeIndex = Math.max(0, THEME_OPTIONS.findIndex((option) => option.value === options.detectedTheme)); + this.update(); + } + // Rebuild the whole dialog on every change so theme previews recolor all text. + update() { + this.clear(); + this.addChild(new DynamicBorder()); + this.addChild(new Spacer(1)); + this.addChild(new Text(theme.fg("accent", SETUP_LOGO_LINES.join("\n")), 1, 0)); + this.addChild(new Spacer(1)); + this.addChild(new Text(theme.fg("accent", theme.bold(`Welcome to ${APP_NAME}, the minimal coding agent.`)), 1, 0)); + this.addChild(new Spacer(1)); + if (this.step === "theme") { + this.addChild(new Text(theme.fg("text", "Pick a theme."), 1, 0)); + this.addChild(new Text(theme.fg("muted", `Detected system appearance: ${this.options.detectedTheme}`), 1, 0)); + this.addChild(new Spacer(1)); + this.addOptionList(THEME_OPTIONS.map((option) => option.label), this.themeIndex); + } + else { + this.addChild(new Text(theme.fg("text", "Opt-in to anonymous usage data sharing?"), 1, 0)); + this.addChild(new Text(theme.fg("muted", "Opting in stores a tracking identifier in settings.json and enables anonymous\nusage analytics. This helps us to better debug, reproduce, and resolve issues\nand bugs within Pi. You can observe what is shared using /privacy and make\nchanges anytime in settings.json."), 1, 0)); + this.addChild(new Spacer(1)); + this.addOptionList(ANALYTICS_OPTIONS.map((option) => option.label), this.analyticsIndex); + } + this.addChild(new Spacer(1)); + this.addChild(new Text(rawKeyHint("↑↓", "navigate") + + " " + + keyHint("tui.select.confirm", this.step === "theme" ? "continue" : "finish") + + " " + + keyHint("tui.select.cancel", "skip setup"), 1, 0)); + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder()); + } + addOptionList(labels, selectedIndex) { + for (let i = 0; i < labels.length; i++) { + const isSelected = i === selectedIndex; + const prefix = isSelected ? theme.fg("accent", "→ ") : " "; + const label = isSelected ? theme.fg("accent", labels[i]) : theme.fg("text", labels[i]); + this.addChild(new Text(`${prefix}${label}`, 1, 0)); + } + } + moveSelection(delta) { + if (this.step === "theme") { + const next = Math.max(0, Math.min(THEME_OPTIONS.length - 1, this.themeIndex + delta)); + if (next !== this.themeIndex) { + this.themeIndex = next; + this.options.onThemePreview(THEME_OPTIONS[this.themeIndex].value); + } + } + else { + this.analyticsIndex = Math.max(0, Math.min(ANALYTICS_OPTIONS.length - 1, this.analyticsIndex + delta)); + } + this.update(); + } + handleInput(keyData) { + const kb = getKeybindings(); + if (kb.matches(keyData, "tui.select.up") || keyData === "k") { + this.moveSelection(-1); + } + else if (kb.matches(keyData, "tui.select.down") || keyData === "j") { + this.moveSelection(1); + } + else if (kb.matches(keyData, "tui.select.confirm") || keyData === "\n") { + if (this.step === "theme") { + this.step = "analytics"; + this.update(); + } + else { + this.options.onSubmit({ + theme: THEME_OPTIONS[this.themeIndex].value, + shareAnalytics: ANALYTICS_OPTIONS[this.analyticsIndex].value, + }); + } + } + else if (kb.matches(keyData, "tui.select.cancel")) { + this.options.onCancel(); + } + } +} +//# sourceMappingURL=first-time-setup.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/first-time-setup.js.map b/dist/modes/interactive/components/first-time-setup.js.map new file mode 100644 index 0000000..fcacb56 --- /dev/null +++ b/dist/modes/interactive/components/first-time-setup.js.map @@ -0,0 +1 @@ +{"version":3,"file":"first-time-setup.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/first-time-set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;QACxG,CAAC;QACD,IAAI,CAAC,MAAM,EAAE,CAAC;IAAA,CACd;IAED,WAAW,CAAC,OAAe,EAAQ;QAClC,MAAM,EAAE,GAAG,cAAc,EAAE,CAAC;QAC5B,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,eAAe,CAAC,IAAI,OAAO,KAAK,GAAG,EAAE,CAAC;YAC7D,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC;QACxB,CAAC;aAAM,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,iBAAiB,CAAC,IAAI,OAAO,KAAK,GAAG,EAAE,CAAC;YACtE,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;QACvB,CAAC;aAAM,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,oBAAoB,CAAC,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;YAC1E,IAAI,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;gBAC3B,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC;gBACxB,IAAI,CAAC,MAAM,EAAE,CAAC;YACf,CAAC;iBAAM,CAAC;gBACP,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC;oBACrB,KAAK,EAAE,aAAa,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,KAAK;oBAC3C,cAAc,EAAE,iBAAiB,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC,KAAK;iBAC5D,CAAC,CAAC;YACJ,CAAC;QACF,CAAC;aAAM,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,EAAE,CAAC;YACrD,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;QACzB,CAAC;IAAA,CACD;CACD","sourcesContent":["import { Container, getKeybindings, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport { APP_NAME } from \"../../../config.ts\";\nimport { type TerminalTheme, theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint, rawKeyHint } from \"./keybinding-hints.ts\";\n\nexport interface FirstTimeSetupResult {\n\ttheme: TerminalTheme;\n\tshareAnalytics: boolean;\n}\n\nexport interface FirstTimeSetupOptions {\n\tdetectedTheme: TerminalTheme;\n\tonThemePreview: (themeName: TerminalTheme) => void;\n\tonSubmit: (result: FirstTimeSetupResult) => void;\n\tonCancel: () => void;\n}\n\nconst THEME_OPTIONS: Array<{ value: TerminalTheme; label: string }> = [\n\t{ value: \"dark\", label: \"Dark\" },\n\t{ value: \"light\", label: \"Light\" },\n];\n\nconst ANALYTICS_OPTIONS: Array<{ value: boolean; label: string }> = [\n\t{ value: true, label: \"Share anonymous usage data\" },\n\t{ value: false, label: \"Don't share\" },\n];\n\nconst SETUP_LOGO_LINES = [\"██████\", \"██ ██\", \"████ ██\", \"██ ██\"];\n\n/** First-time setup dialog: theme choice and analytics opt-in. */\nexport class FirstTimeSetupComponent extends Container {\n\tprivate step: \"theme\" | \"analytics\" = \"theme\";\n\tprivate themeIndex: number;\n\tprivate analyticsIndex = 0;\n\tprivate readonly options: FirstTimeSetupOptions;\n\n\tconstructor(options: FirstTimeSetupOptions) {\n\t\tsuper();\n\t\tthis.options = options;\n\t\tthis.themeIndex = Math.max(\n\t\t\t0,\n\t\t\tTHEME_OPTIONS.findIndex((option) => option.value === options.detectedTheme),\n\t\t);\n\t\tthis.update();\n\t}\n\n\t// Rebuild the whole dialog on every change so theme previews recolor all text.\n\tprivate update(): void {\n\t\tthis.clear();\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.fg(\"accent\", SETUP_LOGO_LINES.join(\"\\n\")), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(\n\t\t\tnew Text(theme.fg(\"accent\", theme.bold(`Welcome to ${APP_NAME}, the minimal coding agent.`)), 1, 0),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\n\t\tif (this.step === \"theme\") {\n\t\t\tthis.addChild(new Text(theme.fg(\"text\", \"Pick a theme.\"), 1, 0));\n\t\t\tthis.addChild(new Text(theme.fg(\"muted\", `Detected system appearance: ${this.options.detectedTheme}`), 1, 0));\n\t\t\tthis.addChild(new Spacer(1));\n\t\t\tthis.addOptionList(\n\t\t\t\tTHEME_OPTIONS.map((option) => option.label),\n\t\t\t\tthis.themeIndex,\n\t\t\t);\n\t\t} else {\n\t\t\tthis.addChild(new Text(theme.fg(\"text\", \"Opt-in to anonymous usage data sharing?\"), 1, 0));\n\t\t\tthis.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\ttheme.fg(\n\t\t\t\t\t\t\"muted\",\n\t\t\t\t\t\t\"Opting in stores a tracking identifier in settings.json and enables anonymous\\nusage analytics. This helps us to better debug, reproduce, and resolve issues\\nand bugs within Pi. You can observe what is shared using /privacy and make\\nchanges anytime in settings.json.\",\n\t\t\t\t\t),\n\t\t\t\t\t1,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t\tthis.addChild(new Spacer(1));\n\t\t\tthis.addOptionList(\n\t\t\t\tANALYTICS_OPTIONS.map((option) => option.label),\n\t\t\t\tthis.analyticsIndex,\n\t\t\t);\n\t\t}\n\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(\n\t\t\tnew Text(\n\t\t\t\trawKeyHint(\"↑↓\", \"navigate\") +\n\t\t\t\t\t\" \" +\n\t\t\t\t\tkeyHint(\"tui.select.confirm\", this.step === \"theme\" ? \"continue\" : \"finish\") +\n\t\t\t\t\t\" \" +\n\t\t\t\t\tkeyHint(\"tui.select.cancel\", \"skip setup\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tprivate addOptionList(labels: string[], selectedIndex: number): void {\n\t\tfor (let i = 0; i < labels.length; i++) {\n\t\t\tconst isSelected = i === selectedIndex;\n\t\t\tconst prefix = isSelected ? theme.fg(\"accent\", \"→ \") : \" \";\n\t\t\tconst label = isSelected ? theme.fg(\"accent\", labels[i]) : theme.fg(\"text\", labels[i]);\n\t\t\tthis.addChild(new Text(`${prefix}${label}`, 1, 0));\n\t\t}\n\t}\n\n\tprivate moveSelection(delta: number): void {\n\t\tif (this.step === \"theme\") {\n\t\t\tconst next = Math.max(0, Math.min(THEME_OPTIONS.length - 1, this.themeIndex + delta));\n\t\t\tif (next !== this.themeIndex) {\n\t\t\t\tthis.themeIndex = next;\n\t\t\t\tthis.options.onThemePreview(THEME_OPTIONS[this.themeIndex].value);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.analyticsIndex = Math.max(0, Math.min(ANALYTICS_OPTIONS.length - 1, this.analyticsIndex + delta));\n\t\t}\n\t\tthis.update();\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"tui.select.up\") || keyData === \"k\") {\n\t\t\tthis.moveSelection(-1);\n\t\t} else if (kb.matches(keyData, \"tui.select.down\") || keyData === \"j\") {\n\t\t\tthis.moveSelection(1);\n\t\t} else if (kb.matches(keyData, \"tui.select.confirm\") || keyData === \"\\n\") {\n\t\t\tif (this.step === \"theme\") {\n\t\t\t\tthis.step = \"analytics\";\n\t\t\t\tthis.update();\n\t\t\t} else {\n\t\t\t\tthis.options.onSubmit({\n\t\t\t\t\ttheme: THEME_OPTIONS[this.themeIndex].value,\n\t\t\t\t\tshareAnalytics: ANALYTICS_OPTIONS[this.analyticsIndex].value,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.options.onCancel();\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/footer.d.ts b/dist/modes/interactive/components/footer.d.ts new file mode 100644 index 0000000..fc2b1dd --- /dev/null +++ b/dist/modes/interactive/components/footer.d.ts @@ -0,0 +1,32 @@ +import { type Component } from "@earendil-works/pi-tui"; +import type { AgentSession } from "../../../core/agent-session.ts"; +import type { ReadonlyFooterDataProvider } from "../../../core/footer-data-provider.ts"; +/** + * Format token counts for compact footer display. + */ +export declare function formatTokens(count: number): string; +export declare function formatCwdForFooter(cwd: string, home: string | undefined): string; +/** + * Footer component that shows pwd, token stats, and context usage. + * Computes token/context stats from session, gets git branch and extension statuses from provider. + */ +export declare class FooterComponent implements Component { + private autoCompactEnabled; + private session; + private footerData; + constructor(session: AgentSession, footerData: ReadonlyFooterDataProvider); + setSession(session: AgentSession): void; + setAutoCompactEnabled(enabled: boolean): void; + /** + * No-op: git branch caching now handled by provider. + * Kept for compatibility with existing call sites in interactive-mode. + */ + invalidate(): void; + /** + * Clean up resources. + * Git watcher cleanup now handled by provider. + */ + dispose(): void; + render(width: number): string[]; +} +//# sourceMappingURL=footer.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/footer.d.ts.map b/dist/modes/interactive/components/footer.d.ts.map new file mode 100644 index 0000000..2de41fe --- /dev/null +++ b/dist/modes/interactive/components/footer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"footer.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/footer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,SAAS,EAAiC,MAAM,wBAAwB,CAAC;AACvF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAEnE,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AAgBxF;;GAEG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAMlD;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAYhF;AAED;;;GAGG;AACH,qBAAa,eAAgB,YAAW,SAAS;IAChD,OAAO,CAAC,kBAAkB,CAAQ;IAClC,OAAO,CAAC,OAAO,CAAe;IAC9B,OAAO,CAAC,UAAU,CAA6B;IAE/C,YAAY,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,0BAA0B,EAGxE;IAED,UAAU,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAEtC;IAED,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAE5C;IAED;;;OAGG;IACH,UAAU,IAAI,IAAI,CAEjB;IAED;;;OAGG;IACH,OAAO,IAAI,IAAI,CAEd;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAgK9B;CACD","sourcesContent":["import { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport { type Component, truncateToWidth, visibleWidth } from \"@earendil-works/pi-tui\";\nimport type { AgentSession } from \"../../../core/agent-session.ts\";\nimport { areExperimentalFeaturesEnabled } from \"../../../core/experimental.ts\";\nimport type { ReadonlyFooterDataProvider } from \"../../../core/footer-data-provider.ts\";\nimport { addUsageToTotals, createUsageTotals } from \"../../../core/usage-totals.ts\";\nimport { theme } from \"../theme/theme.ts\";\n\n/**\n * Sanitize text for display in a single-line status.\n * Removes newlines, tabs, carriage returns, and other control characters.\n */\nfunction sanitizeStatusText(text: string): string {\n\t// Replace newlines, tabs, carriage returns with space, then collapse multiple spaces\n\treturn text\n\t\t.replace(/[\\r\\n\\t]/g, \" \")\n\t\t.replace(/ +/g, \" \")\n\t\t.trim();\n}\n\n/**\n * Format token counts for compact footer display.\n */\nexport function formatTokens(count: number): string {\n\tif (count < 1000) return count.toString();\n\tif (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n\tif (count < 1000000) return `${Math.round(count / 1000)}k`;\n\tif (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;\n\treturn `${Math.round(count / 1000000)}M`;\n}\n\nexport function formatCwdForFooter(cwd: string, home: string | undefined): string {\n\tif (!home) return cwd;\n\n\tconst resolvedCwd = resolve(cwd);\n\tconst resolvedHome = resolve(home);\n\tconst relativeToHome = relative(resolvedHome, resolvedCwd);\n\tconst isInsideHome =\n\t\trelativeToHome === \"\" ||\n\t\t(relativeToHome !== \"..\" && !relativeToHome.startsWith(`..${sep}`) && !isAbsolute(relativeToHome));\n\n\tif (!isInsideHome) return cwd;\n\treturn relativeToHome === \"\" ? \"~\" : `~${sep}${relativeToHome}`;\n}\n\n/**\n * Footer component that shows pwd, token stats, and context usage.\n * Computes token/context stats from session, gets git branch and extension statuses from provider.\n */\nexport class FooterComponent implements Component {\n\tprivate autoCompactEnabled = true;\n\tprivate session: AgentSession;\n\tprivate footerData: ReadonlyFooterDataProvider;\n\n\tconstructor(session: AgentSession, footerData: ReadonlyFooterDataProvider) {\n\t\tthis.session = session;\n\t\tthis.footerData = footerData;\n\t}\n\n\tsetSession(session: AgentSession): void {\n\t\tthis.session = session;\n\t}\n\n\tsetAutoCompactEnabled(enabled: boolean): void {\n\t\tthis.autoCompactEnabled = enabled;\n\t}\n\n\t/**\n\t * No-op: git branch caching now handled by provider.\n\t * Kept for compatibility with existing call sites in interactive-mode.\n\t */\n\tinvalidate(): void {\n\t\t// No-op: git branch is cached/invalidated by provider\n\t}\n\n\t/**\n\t * Clean up resources.\n\t * Git watcher cleanup now handled by provider.\n\t */\n\tdispose(): void {\n\t\t// Git watcher cleanup handled by provider\n\t}\n\n\trender(width: number): string[] {\n\t\tconst state = this.session.state;\n\n\t\t// Calculate cumulative usage from ALL session entries (not just post-compaction messages)\n\t\tconst usageTotals = createUsageTotals();\n\t\tlet latestCacheHitRate: number | undefined;\n\n\t\tfor (const entry of this.session.sessionManager.getEntries()) {\n\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\taddUsageToTotals(usageTotals, entry.message.usage);\n\n\t\t\t\tconst latestPromptTokens =\n\t\t\t\t\tentry.message.usage.input + entry.message.usage.cacheRead + entry.message.usage.cacheWrite;\n\t\t\t\tlatestCacheHitRate =\n\t\t\t\t\tlatestPromptTokens > 0 ? (entry.message.usage.cacheRead / latestPromptTokens) * 100 : undefined;\n\t\t\t} else if (entry.type === \"message\" && entry.message.role === \"toolResult\" && entry.message.usage) {\n\t\t\t\taddUsageToTotals(usageTotals, entry.message.usage);\n\t\t\t} else if ((entry.type === \"branch_summary\" || entry.type === \"compaction\") && entry.usage) {\n\t\t\t\taddUsageToTotals(usageTotals, entry.usage);\n\t\t\t}\n\t\t}\n\n\t\t// Calculate context usage from session (handles compaction correctly).\n\t\t// After compaction, tokens are unknown until the next LLM response.\n\t\tconst contextUsage = this.session.getContextUsage();\n\t\tconst contextWindow = contextUsage?.contextWindow ?? state.model?.contextWindow ?? 0;\n\t\tconst contextPercentValue = contextUsage?.percent ?? 0;\n\t\tconst contextPercent = contextUsage?.percent !== null ? contextPercentValue.toFixed(1) : \"?\";\n\n\t\t// Replace home directory with ~\n\t\tlet pwd = formatCwdForFooter(this.session.sessionManager.getCwd(), process.env.HOME || process.env.USERPROFILE);\n\n\t\t// Add git branch if available\n\t\tconst branch = this.footerData.getGitBranch();\n\t\tif (branch) {\n\t\t\tpwd = `${pwd} (${branch})`;\n\t\t}\n\n\t\t// Add session name if set\n\t\tconst sessionName = this.session.sessionManager.getSessionName();\n\t\tif (sessionName) {\n\t\t\tpwd = `${pwd} • ${sessionName}`;\n\t\t}\n\n\t\t// Build stats line\n\t\tconst statsParts = [];\n\t\tif (usageTotals.input) statsParts.push(`↑${formatTokens(usageTotals.input)}`);\n\t\tif (usageTotals.output) statsParts.push(`↓${formatTokens(usageTotals.output)}`);\n\t\tif (usageTotals.cacheRead) statsParts.push(`R${formatTokens(usageTotals.cacheRead)}`);\n\t\tif (usageTotals.cacheWrite) statsParts.push(`W${formatTokens(usageTotals.cacheWrite)}`);\n\t\tif ((usageTotals.cacheRead > 0 || usageTotals.cacheWrite > 0) && latestCacheHitRate !== undefined) {\n\t\t\tstatsParts.push(`CH${latestCacheHitRate.toFixed(1)}%`);\n\t\t}\n\n\t\t// Kimi Coding is subscription-backed despite using API-key authentication.\n\t\tconst usingSubscription = state.model\n\t\t\t? state.model.provider === \"kimi-coding\" || this.session.modelRuntime.isUsingOAuth(state.model.provider)\n\t\t\t: false;\n\t\tif (usageTotals.cost || usingSubscription) {\n\t\t\tconst costStr = `$${usageTotals.cost.toFixed(3)}${usingSubscription ? \" (sub)\" : \"\"}`;\n\t\t\tstatsParts.push(costStr);\n\t\t}\n\n\t\t// Colorize context percentage based on usage\n\t\tlet contextPercentStr: string;\n\t\tconst autoIndicator = this.autoCompactEnabled ? \" (auto)\" : \"\";\n\t\tconst contextPercentDisplay =\n\t\t\tcontextPercent === \"?\"\n\t\t\t\t? `?/${formatTokens(contextWindow)}${autoIndicator}`\n\t\t\t\t: `${contextPercent}%/${formatTokens(contextWindow)}${autoIndicator}`;\n\t\tif (contextPercentValue > 90) {\n\t\t\tcontextPercentStr = theme.fg(\"error\", contextPercentDisplay);\n\t\t} else if (contextPercentValue > 70) {\n\t\t\tcontextPercentStr = theme.fg(\"warning\", contextPercentDisplay);\n\t\t} else {\n\t\t\tcontextPercentStr = contextPercentDisplay;\n\t\t}\n\t\tstatsParts.push(contextPercentStr);\n\t\tif (areExperimentalFeaturesEnabled()) {\n\t\t\tstatsParts.push(`${theme.fg(\"dim\", \"•\")} ${theme.bold(theme.fg(\"warning\", \"xp\"))}`);\n\t\t}\n\n\t\tlet statsLeft = statsParts.join(\" \");\n\n\t\t// Add model name on the right side, plus thinking level if model supports it\n\t\tconst modelName = state.model?.id || \"no-model\";\n\n\t\tlet statsLeftWidth = visibleWidth(statsLeft);\n\n\t\t// If statsLeft is too wide, truncate it\n\t\tif (statsLeftWidth > width) {\n\t\t\tstatsLeft = truncateToWidth(statsLeft, width, \"...\");\n\t\t\tstatsLeftWidth = visibleWidth(statsLeft);\n\t\t}\n\n\t\t// Calculate available space for padding (minimum 2 spaces between stats and model)\n\t\tconst minPadding = 2;\n\n\t\t// Add thinking level indicator if model supports reasoning\n\t\tlet rightSideWithoutProvider = modelName;\n\t\tif (state.model?.reasoning) {\n\t\t\tconst thinkingLevel = state.thinkingLevel || \"off\";\n\t\t\trightSideWithoutProvider =\n\t\t\t\tthinkingLevel === \"off\" ? `${modelName} • thinking off` : `${modelName} • ${thinkingLevel}`;\n\t\t}\n\n\t\t// Prepend the provider in parentheses if there are multiple providers and there's enough room\n\t\tlet rightSide = rightSideWithoutProvider;\n\t\tif (this.footerData.getAvailableProviderCount() > 1 && state.model) {\n\t\t\trightSide = `(${state.model!.provider}) ${rightSideWithoutProvider}`;\n\t\t\tif (statsLeftWidth + minPadding + visibleWidth(rightSide) > width) {\n\t\t\t\t// Too wide, fall back\n\t\t\t\trightSide = rightSideWithoutProvider;\n\t\t\t}\n\t\t}\n\n\t\tconst rightSideWidth = visibleWidth(rightSide);\n\t\tconst totalNeeded = statsLeftWidth + minPadding + rightSideWidth;\n\n\t\tlet statsLine: string;\n\t\tif (totalNeeded <= width) {\n\t\t\t// Both fit - add padding to right-align model\n\t\t\tconst padding = \" \".repeat(width - statsLeftWidth - rightSideWidth);\n\t\t\tstatsLine = statsLeft + padding + rightSide;\n\t\t} else {\n\t\t\t// Need to truncate right side\n\t\t\tconst availableForRight = width - statsLeftWidth - minPadding;\n\t\t\tif (availableForRight > 0) {\n\t\t\t\tconst truncatedRight = truncateToWidth(rightSide, availableForRight, \"\");\n\t\t\t\tconst truncatedRightWidth = visibleWidth(truncatedRight);\n\t\t\t\tconst padding = \" \".repeat(Math.max(0, width - statsLeftWidth - truncatedRightWidth));\n\t\t\t\tstatsLine = statsLeft + padding + truncatedRight;\n\t\t\t} else {\n\t\t\t\t// Not enough space for right side at all\n\t\t\t\tstatsLine = statsLeft;\n\t\t\t}\n\t\t}\n\n\t\t// Apply dim to each part separately. statsLeft may contain color codes (for context %)\n\t\t// that end with a reset, which would clear an outer dim wrapper. So we dim the parts\n\t\t// before and after the colored section independently.\n\t\tconst dimStatsLeft = theme.fg(\"dim\", statsLeft);\n\t\tconst remainder = statsLine.slice(statsLeft.length); // padding + rightSide\n\t\tconst dimRemainder = theme.fg(\"dim\", remainder);\n\n\t\tconst pwdLine = truncateToWidth(theme.fg(\"dim\", pwd), width, theme.fg(\"dim\", \"...\"));\n\t\tconst lines = [pwdLine, dimStatsLeft + dimRemainder];\n\n\t\t// Add extension statuses on a single line, sorted by key alphabetically\n\t\tconst extensionStatuses = this.footerData.getExtensionStatuses();\n\t\tif (extensionStatuses.size > 0) {\n\t\t\tconst sortedStatuses = Array.from(extensionStatuses.entries())\n\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t.map(([, text]) => sanitizeStatusText(text));\n\t\t\tconst statusLine = sortedStatuses.join(\" \");\n\t\t\t// Truncate to terminal width with dim ellipsis for consistency with footer style\n\t\t\tlines.push(truncateToWidth(statusLine, width, theme.fg(\"dim\", \"...\")));\n\t\t}\n\n\t\treturn lines;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/footer.js b/dist/modes/interactive/components/footer.js new file mode 100644 index 0000000..92f4894 --- /dev/null +++ b/dist/modes/interactive/components/footer.js @@ -0,0 +1,222 @@ +import { isAbsolute, relative, resolve, sep } from "node:path"; +import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; +import { areExperimentalFeaturesEnabled } from "../../../core/experimental.js"; +import { addUsageToTotals, createUsageTotals } from "../../../core/usage-totals.js"; +import { theme } from "../theme/theme.js"; +/** + * Sanitize text for display in a single-line status. + * Removes newlines, tabs, carriage returns, and other control characters. + */ +function sanitizeStatusText(text) { + // Replace newlines, tabs, carriage returns with space, then collapse multiple spaces + return text + .replace(/[\r\n\t]/g, " ") + .replace(/ +/g, " ") + .trim(); +} +/** + * Format token counts for compact footer display. + */ +export function formatTokens(count) { + if (count < 1000) + return count.toString(); + if (count < 10000) + return `${(count / 1000).toFixed(1)}k`; + if (count < 1000000) + return `${Math.round(count / 1000)}k`; + if (count < 10000000) + return `${(count / 1000000).toFixed(1)}M`; + return `${Math.round(count / 1000000)}M`; +} +export function formatCwdForFooter(cwd, home) { + if (!home) + return cwd; + const resolvedCwd = resolve(cwd); + const resolvedHome = resolve(home); + const relativeToHome = relative(resolvedHome, resolvedCwd); + const isInsideHome = relativeToHome === "" || + (relativeToHome !== ".." && !relativeToHome.startsWith(`..${sep}`) && !isAbsolute(relativeToHome)); + if (!isInsideHome) + return cwd; + return relativeToHome === "" ? "~" : `~${sep}${relativeToHome}`; +} +/** + * Footer component that shows pwd, token stats, and context usage. + * Computes token/context stats from session, gets git branch and extension statuses from provider. + */ +export class FooterComponent { + autoCompactEnabled = true; + session; + footerData; + constructor(session, footerData) { + this.session = session; + this.footerData = footerData; + } + setSession(session) { + this.session = session; + } + setAutoCompactEnabled(enabled) { + this.autoCompactEnabled = enabled; + } + /** + * No-op: git branch caching now handled by provider. + * Kept for compatibility with existing call sites in interactive-mode. + */ + invalidate() { + // No-op: git branch is cached/invalidated by provider + } + /** + * Clean up resources. + * Git watcher cleanup now handled by provider. + */ + dispose() { + // Git watcher cleanup handled by provider + } + render(width) { + const state = this.session.state; + // Calculate cumulative usage from ALL session entries (not just post-compaction messages) + const usageTotals = createUsageTotals(); + let latestCacheHitRate; + for (const entry of this.session.sessionManager.getEntries()) { + if (entry.type === "message" && entry.message.role === "assistant") { + addUsageToTotals(usageTotals, entry.message.usage); + const latestPromptTokens = entry.message.usage.input + entry.message.usage.cacheRead + entry.message.usage.cacheWrite; + latestCacheHitRate = + latestPromptTokens > 0 ? (entry.message.usage.cacheRead / latestPromptTokens) * 100 : undefined; + } + else if (entry.type === "message" && entry.message.role === "toolResult" && entry.message.usage) { + addUsageToTotals(usageTotals, entry.message.usage); + } + else if ((entry.type === "branch_summary" || entry.type === "compaction") && entry.usage) { + addUsageToTotals(usageTotals, entry.usage); + } + } + // Calculate context usage from session (handles compaction correctly). + // After compaction, tokens are unknown until the next LLM response. + const contextUsage = this.session.getContextUsage(); + const contextWindow = contextUsage?.contextWindow ?? state.model?.contextWindow ?? 0; + const contextPercentValue = contextUsage?.percent ?? 0; + const contextPercent = contextUsage?.percent !== null ? contextPercentValue.toFixed(1) : "?"; + // Replace home directory with ~ + let pwd = formatCwdForFooter(this.session.sessionManager.getCwd(), process.env.HOME || process.env.USERPROFILE); + // Add git branch if available + const branch = this.footerData.getGitBranch(); + if (branch) { + pwd = `${pwd} (${branch})`; + } + // Add session name if set + const sessionName = this.session.sessionManager.getSessionName(); + if (sessionName) { + pwd = `${pwd} • ${sessionName}`; + } + // Build stats line + const statsParts = []; + if (usageTotals.input) + statsParts.push(`↑${formatTokens(usageTotals.input)}`); + if (usageTotals.output) + statsParts.push(`↓${formatTokens(usageTotals.output)}`); + if (usageTotals.cacheRead) + statsParts.push(`R${formatTokens(usageTotals.cacheRead)}`); + if (usageTotals.cacheWrite) + statsParts.push(`W${formatTokens(usageTotals.cacheWrite)}`); + if ((usageTotals.cacheRead > 0 || usageTotals.cacheWrite > 0) && latestCacheHitRate !== undefined) { + statsParts.push(`CH${latestCacheHitRate.toFixed(1)}%`); + } + // Kimi Coding is subscription-backed despite using API-key authentication. + const usingSubscription = state.model + ? state.model.provider === "kimi-coding" || this.session.modelRuntime.isUsingOAuth(state.model.provider) + : false; + if (usageTotals.cost || usingSubscription) { + const costStr = `$${usageTotals.cost.toFixed(3)}${usingSubscription ? " (sub)" : ""}`; + statsParts.push(costStr); + } + // Colorize context percentage based on usage + let contextPercentStr; + const autoIndicator = this.autoCompactEnabled ? " (auto)" : ""; + const contextPercentDisplay = contextPercent === "?" + ? `?/${formatTokens(contextWindow)}${autoIndicator}` + : `${contextPercent}%/${formatTokens(contextWindow)}${autoIndicator}`; + if (contextPercentValue > 90) { + contextPercentStr = theme.fg("error", contextPercentDisplay); + } + else if (contextPercentValue > 70) { + contextPercentStr = theme.fg("warning", contextPercentDisplay); + } + else { + contextPercentStr = contextPercentDisplay; + } + statsParts.push(contextPercentStr); + if (areExperimentalFeaturesEnabled()) { + statsParts.push(`${theme.fg("dim", "•")} ${theme.bold(theme.fg("warning", "xp"))}`); + } + let statsLeft = statsParts.join(" "); + // Add model name on the right side, plus thinking level if model supports it + const modelName = state.model?.id || "no-model"; + let statsLeftWidth = visibleWidth(statsLeft); + // If statsLeft is too wide, truncate it + if (statsLeftWidth > width) { + statsLeft = truncateToWidth(statsLeft, width, "..."); + statsLeftWidth = visibleWidth(statsLeft); + } + // Calculate available space for padding (minimum 2 spaces between stats and model) + const minPadding = 2; + // Add thinking level indicator if model supports reasoning + let rightSideWithoutProvider = modelName; + if (state.model?.reasoning) { + const thinkingLevel = state.thinkingLevel || "off"; + rightSideWithoutProvider = + thinkingLevel === "off" ? `${modelName} • thinking off` : `${modelName} • ${thinkingLevel}`; + } + // Prepend the provider in parentheses if there are multiple providers and there's enough room + let rightSide = rightSideWithoutProvider; + if (this.footerData.getAvailableProviderCount() > 1 && state.model) { + rightSide = `(${state.model.provider}) ${rightSideWithoutProvider}`; + if (statsLeftWidth + minPadding + visibleWidth(rightSide) > width) { + // Too wide, fall back + rightSide = rightSideWithoutProvider; + } + } + const rightSideWidth = visibleWidth(rightSide); + const totalNeeded = statsLeftWidth + minPadding + rightSideWidth; + let statsLine; + if (totalNeeded <= width) { + // Both fit - add padding to right-align model + const padding = " ".repeat(width - statsLeftWidth - rightSideWidth); + statsLine = statsLeft + padding + rightSide; + } + else { + // Need to truncate right side + const availableForRight = width - statsLeftWidth - minPadding; + if (availableForRight > 0) { + const truncatedRight = truncateToWidth(rightSide, availableForRight, ""); + const truncatedRightWidth = visibleWidth(truncatedRight); + const padding = " ".repeat(Math.max(0, width - statsLeftWidth - truncatedRightWidth)); + statsLine = statsLeft + padding + truncatedRight; + } + else { + // Not enough space for right side at all + statsLine = statsLeft; + } + } + // Apply dim to each part separately. statsLeft may contain color codes (for context %) + // that end with a reset, which would clear an outer dim wrapper. So we dim the parts + // before and after the colored section independently. + const dimStatsLeft = theme.fg("dim", statsLeft); + const remainder = statsLine.slice(statsLeft.length); // padding + rightSide + const dimRemainder = theme.fg("dim", remainder); + const pwdLine = truncateToWidth(theme.fg("dim", pwd), width, theme.fg("dim", "...")); + const lines = [pwdLine, dimStatsLeft + dimRemainder]; + // Add extension statuses on a single line, sorted by key alphabetically + const extensionStatuses = this.footerData.getExtensionStatuses(); + if (extensionStatuses.size > 0) { + const sortedStatuses = Array.from(extensionStatuses.entries()) + .sort(([a], [b]) => a.localeCompare(b)) + .map(([, text]) => sanitizeStatusText(text)); + const statusLine = sortedStatuses.join(" "); + // Truncate to terminal width with dim ellipsis for consistency with footer style + lines.push(truncateToWidth(statusLine, width, theme.fg("dim", "..."))); + } + return lines; + } +} +//# sourceMappingURL=footer.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/footer.js.map b/dist/modes/interactive/components/footer.js.map new file mode 100644 index 0000000..c2eeccc --- /dev/null +++ b/dist/modes/interactive/components/footer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"footer.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/footer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAkB,eAAe,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAEvF,OAAO,EAAE,8BAA8B,EAAE,MAAM,+BAA+B,CAAC;AAE/E,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AACpF,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C;;;GAGG;AACH,SAAS,kBAAkB,CAAC,IAAY,EAAU;IACjD,qFAAqF;IACrF,OAAO,IAAI;SACT,OAAO,CAAC,WAAW,EAAE,GAAG,CAAC;SACzB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,IAAI,EAAE,CAAC;AAAA,CACT;AAED;;GAEG;AACH,MAAM,UAAU,YAAY,CAAC,KAAa,EAAU;IACnD,IAAI,KAAK,GAAG,IAAI;QAAE,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;IAC1C,IAAI,KAAK,GAAG,KAAK;QAAE,OAAO,GAAG,CAAC,KAAK,GAA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AAG,IAAI,CAAC,UAAU,CAAC,oBAAoB,EAAE,CAAC;QACjE,IAAI,iBAAiB,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;YAChC,MAAM,cAAc,GAAG,KAAK,CAAC,IAAI,CAAC,iBAAiB,CAAC,OAAO,EAAE,CAAC;iBAC5D,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;iBACtC,GAAG,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC,CAAC;YAC9C,MAAM,UAAU,GAAG,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAC5C,iFAAiF;YACjF,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,UAAU,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;QACxE,CAAC;QAED,OAAO,KAAK,CAAC;IAAA,CACb;CACD","sourcesContent":["import { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport { type Component, truncateToWidth, visibleWidth } from \"@earendil-works/pi-tui\";\nimport type { AgentSession } from \"../../../core/agent-session.ts\";\nimport { areExperimentalFeaturesEnabled } from \"../../../core/experimental.ts\";\nimport type { ReadonlyFooterDataProvider } from \"../../../core/footer-data-provider.ts\";\nimport { addUsageToTotals, createUsageTotals } from \"../../../core/usage-totals.ts\";\nimport { theme } from \"../theme/theme.ts\";\n\n/**\n * Sanitize text for display in a single-line status.\n * Removes newlines, tabs, carriage returns, and other control characters.\n */\nfunction sanitizeStatusText(text: string): string {\n\t// Replace newlines, tabs, carriage returns with space, then collapse multiple spaces\n\treturn text\n\t\t.replace(/[\\r\\n\\t]/g, \" \")\n\t\t.replace(/ +/g, \" \")\n\t\t.trim();\n}\n\n/**\n * Format token counts for compact footer display.\n */\nexport function formatTokens(count: number): string {\n\tif (count < 1000) return count.toString();\n\tif (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n\tif (count < 1000000) return `${Math.round(count / 1000)}k`;\n\tif (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;\n\treturn `${Math.round(count / 1000000)}M`;\n}\n\nexport function formatCwdForFooter(cwd: string, home: string | undefined): string {\n\tif (!home) return cwd;\n\n\tconst resolvedCwd = resolve(cwd);\n\tconst resolvedHome = resolve(home);\n\tconst relativeToHome = relative(resolvedHome, resolvedCwd);\n\tconst isInsideHome =\n\t\trelativeToHome === \"\" ||\n\t\t(relativeToHome !== \"..\" && !relativeToHome.startsWith(`..${sep}`) && !isAbsolute(relativeToHome));\n\n\tif (!isInsideHome) return cwd;\n\treturn relativeToHome === \"\" ? \"~\" : `~${sep}${relativeToHome}`;\n}\n\n/**\n * Footer component that shows pwd, token stats, and context usage.\n * Computes token/context stats from session, gets git branch and extension statuses from provider.\n */\nexport class FooterComponent implements Component {\n\tprivate autoCompactEnabled = true;\n\tprivate session: AgentSession;\n\tprivate footerData: ReadonlyFooterDataProvider;\n\n\tconstructor(session: AgentSession, footerData: ReadonlyFooterDataProvider) {\n\t\tthis.session = session;\n\t\tthis.footerData = footerData;\n\t}\n\n\tsetSession(session: AgentSession): void {\n\t\tthis.session = session;\n\t}\n\n\tsetAutoCompactEnabled(enabled: boolean): void {\n\t\tthis.autoCompactEnabled = enabled;\n\t}\n\n\t/**\n\t * No-op: git branch caching now handled by provider.\n\t * Kept for compatibility with existing call sites in interactive-mode.\n\t */\n\tinvalidate(): void {\n\t\t// No-op: git branch is cached/invalidated by provider\n\t}\n\n\t/**\n\t * Clean up resources.\n\t * Git watcher cleanup now handled by provider.\n\t */\n\tdispose(): void {\n\t\t// Git watcher cleanup handled by provider\n\t}\n\n\trender(width: number): string[] {\n\t\tconst state = this.session.state;\n\n\t\t// Calculate cumulative usage from ALL session entries (not just post-compaction messages)\n\t\tconst usageTotals = createUsageTotals();\n\t\tlet latestCacheHitRate: number | undefined;\n\n\t\tfor (const entry of this.session.sessionManager.getEntries()) {\n\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\taddUsageToTotals(usageTotals, entry.message.usage);\n\n\t\t\t\tconst latestPromptTokens =\n\t\t\t\t\tentry.message.usage.input + entry.message.usage.cacheRead + entry.message.usage.cacheWrite;\n\t\t\t\tlatestCacheHitRate =\n\t\t\t\t\tlatestPromptTokens > 0 ? (entry.message.usage.cacheRead / latestPromptTokens) * 100 : undefined;\n\t\t\t} else if (entry.type === \"message\" && entry.message.role === \"toolResult\" && entry.message.usage) {\n\t\t\t\taddUsageToTotals(usageTotals, entry.message.usage);\n\t\t\t} else if ((entry.type === \"branch_summary\" || entry.type === \"compaction\") && entry.usage) {\n\t\t\t\taddUsageToTotals(usageTotals, entry.usage);\n\t\t\t}\n\t\t}\n\n\t\t// Calculate context usage from session (handles compaction correctly).\n\t\t// After compaction, tokens are unknown until the next LLM response.\n\t\tconst contextUsage = this.session.getContextUsage();\n\t\tconst contextWindow = contextUsage?.contextWindow ?? state.model?.contextWindow ?? 0;\n\t\tconst contextPercentValue = contextUsage?.percent ?? 0;\n\t\tconst contextPercent = contextUsage?.percent !== null ? contextPercentValue.toFixed(1) : \"?\";\n\n\t\t// Replace home directory with ~\n\t\tlet pwd = formatCwdForFooter(this.session.sessionManager.getCwd(), process.env.HOME || process.env.USERPROFILE);\n\n\t\t// Add git branch if available\n\t\tconst branch = this.footerData.getGitBranch();\n\t\tif (branch) {\n\t\t\tpwd = `${pwd} (${branch})`;\n\t\t}\n\n\t\t// Add session name if set\n\t\tconst sessionName = this.session.sessionManager.getSessionName();\n\t\tif (sessionName) {\n\t\t\tpwd = `${pwd} • ${sessionName}`;\n\t\t}\n\n\t\t// Build stats line\n\t\tconst statsParts = [];\n\t\tif (usageTotals.input) statsParts.push(`↑${formatTokens(usageTotals.input)}`);\n\t\tif (usageTotals.output) statsParts.push(`↓${formatTokens(usageTotals.output)}`);\n\t\tif (usageTotals.cacheRead) statsParts.push(`R${formatTokens(usageTotals.cacheRead)}`);\n\t\tif (usageTotals.cacheWrite) statsParts.push(`W${formatTokens(usageTotals.cacheWrite)}`);\n\t\tif ((usageTotals.cacheRead > 0 || usageTotals.cacheWrite > 0) && latestCacheHitRate !== undefined) {\n\t\t\tstatsParts.push(`CH${latestCacheHitRate.toFixed(1)}%`);\n\t\t}\n\n\t\t// Kimi Coding is subscription-backed despite using API-key authentication.\n\t\tconst usingSubscription = state.model\n\t\t\t? state.model.provider === \"kimi-coding\" || this.session.modelRuntime.isUsingOAuth(state.model.provider)\n\t\t\t: false;\n\t\tif (usageTotals.cost || usingSubscription) {\n\t\t\tconst costStr = `$${usageTotals.cost.toFixed(3)}${usingSubscription ? \" (sub)\" : \"\"}`;\n\t\t\tstatsParts.push(costStr);\n\t\t}\n\n\t\t// Colorize context percentage based on usage\n\t\tlet contextPercentStr: string;\n\t\tconst autoIndicator = this.autoCompactEnabled ? \" (auto)\" : \"\";\n\t\tconst contextPercentDisplay =\n\t\t\tcontextPercent === \"?\"\n\t\t\t\t? `?/${formatTokens(contextWindow)}${autoIndicator}`\n\t\t\t\t: `${contextPercent}%/${formatTokens(contextWindow)}${autoIndicator}`;\n\t\tif (contextPercentValue > 90) {\n\t\t\tcontextPercentStr = theme.fg(\"error\", contextPercentDisplay);\n\t\t} else if (contextPercentValue > 70) {\n\t\t\tcontextPercentStr = theme.fg(\"warning\", contextPercentDisplay);\n\t\t} else {\n\t\t\tcontextPercentStr = contextPercentDisplay;\n\t\t}\n\t\tstatsParts.push(contextPercentStr);\n\t\tif (areExperimentalFeaturesEnabled()) {\n\t\t\tstatsParts.push(`${theme.fg(\"dim\", \"•\")} ${theme.bold(theme.fg(\"warning\", \"xp\"))}`);\n\t\t}\n\n\t\tlet statsLeft = statsParts.join(\" \");\n\n\t\t// Add model name on the right side, plus thinking level if model supports it\n\t\tconst modelName = state.model?.id || \"no-model\";\n\n\t\tlet statsLeftWidth = visibleWidth(statsLeft);\n\n\t\t// If statsLeft is too wide, truncate it\n\t\tif (statsLeftWidth > width) {\n\t\t\tstatsLeft = truncateToWidth(statsLeft, width, \"...\");\n\t\t\tstatsLeftWidth = visibleWidth(statsLeft);\n\t\t}\n\n\t\t// Calculate available space for padding (minimum 2 spaces between stats and model)\n\t\tconst minPadding = 2;\n\n\t\t// Add thinking level indicator if model supports reasoning\n\t\tlet rightSideWithoutProvider = modelName;\n\t\tif (state.model?.reasoning) {\n\t\t\tconst thinkingLevel = state.thinkingLevel || \"off\";\n\t\t\trightSideWithoutProvider =\n\t\t\t\tthinkingLevel === \"off\" ? `${modelName} • thinking off` : `${modelName} • ${thinkingLevel}`;\n\t\t}\n\n\t\t// Prepend the provider in parentheses if there are multiple providers and there's enough room\n\t\tlet rightSide = rightSideWithoutProvider;\n\t\tif (this.footerData.getAvailableProviderCount() > 1 && state.model) {\n\t\t\trightSide = `(${state.model!.provider}) ${rightSideWithoutProvider}`;\n\t\t\tif (statsLeftWidth + minPadding + visibleWidth(rightSide) > width) {\n\t\t\t\t// Too wide, fall back\n\t\t\t\trightSide = rightSideWithoutProvider;\n\t\t\t}\n\t\t}\n\n\t\tconst rightSideWidth = visibleWidth(rightSide);\n\t\tconst totalNeeded = statsLeftWidth + minPadding + rightSideWidth;\n\n\t\tlet statsLine: string;\n\t\tif (totalNeeded <= width) {\n\t\t\t// Both fit - add padding to right-align model\n\t\t\tconst padding = \" \".repeat(width - statsLeftWidth - rightSideWidth);\n\t\t\tstatsLine = statsLeft + padding + rightSide;\n\t\t} else {\n\t\t\t// Need to truncate right side\n\t\t\tconst availableForRight = width - statsLeftWidth - minPadding;\n\t\t\tif (availableForRight > 0) {\n\t\t\t\tconst truncatedRight = truncateToWidth(rightSide, availableForRight, \"\");\n\t\t\t\tconst truncatedRightWidth = visibleWidth(truncatedRight);\n\t\t\t\tconst padding = \" \".repeat(Math.max(0, width - statsLeftWidth - truncatedRightWidth));\n\t\t\t\tstatsLine = statsLeft + padding + truncatedRight;\n\t\t\t} else {\n\t\t\t\t// Not enough space for right side at all\n\t\t\t\tstatsLine = statsLeft;\n\t\t\t}\n\t\t}\n\n\t\t// Apply dim to each part separately. statsLeft may contain color codes (for context %)\n\t\t// that end with a reset, which would clear an outer dim wrapper. So we dim the parts\n\t\t// before and after the colored section independently.\n\t\tconst dimStatsLeft = theme.fg(\"dim\", statsLeft);\n\t\tconst remainder = statsLine.slice(statsLeft.length); // padding + rightSide\n\t\tconst dimRemainder = theme.fg(\"dim\", remainder);\n\n\t\tconst pwdLine = truncateToWidth(theme.fg(\"dim\", pwd), width, theme.fg(\"dim\", \"...\"));\n\t\tconst lines = [pwdLine, dimStatsLeft + dimRemainder];\n\n\t\t// Add extension statuses on a single line, sorted by key alphabetically\n\t\tconst extensionStatuses = this.footerData.getExtensionStatuses();\n\t\tif (extensionStatuses.size > 0) {\n\t\t\tconst sortedStatuses = Array.from(extensionStatuses.entries())\n\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t.map(([, text]) => sanitizeStatusText(text));\n\t\t\tconst statusLine = sortedStatuses.join(\" \");\n\t\t\t// Truncate to terminal width with dim ellipsis for consistency with footer style\n\t\t\tlines.push(truncateToWidth(statusLine, width, theme.fg(\"dim\", \"...\")));\n\t\t}\n\n\t\treturn lines;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/index.d.ts b/dist/modes/interactive/components/index.d.ts new file mode 100644 index 0000000..478f53b --- /dev/null +++ b/dist/modes/interactive/components/index.d.ts @@ -0,0 +1,34 @@ +export { ArminComponent } from "./armin.ts"; +export { AssistantMessageComponent } from "./assistant-message.ts"; +export { BashExecutionComponent } from "./bash-execution.ts"; +export { BorderedLoader } from "./bordered-loader.ts"; +export { BranchSummaryMessageComponent } from "./branch-summary-message.ts"; +export { CompactionSummaryMessageComponent } from "./compaction-summary-message.ts"; +export { CustomEditor } from "./custom-editor.ts"; +export { CustomMessageComponent } from "./custom-message.ts"; +export { DaxnutsComponent } from "./daxnuts.ts"; +export { type RenderDiffOptions, renderDiff } from "./diff.ts"; +export { DynamicBorder } from "./dynamic-border.ts"; +export { ExtensionEditorComponent } from "./extension-editor.ts"; +export { ExtensionInputComponent } from "./extension-input.ts"; +export { ExtensionSelectorComponent } from "./extension-selector.ts"; +export { FirstTimeSetupComponent, type FirstTimeSetupOptions, type FirstTimeSetupResult, } from "./first-time-setup.ts"; +export { FooterComponent } from "./footer.ts"; +export { keyHint, keyText, rawKeyHint } from "./keybinding-hints.ts"; +export { LoginDialogComponent } from "./login-dialog.ts"; +export { ModelSelectorComponent } from "./model-selector.ts"; +export { OAuthSelectorComponent } from "./oauth-selector.ts"; +export { type ModelsCallbacks, type ModelsConfig, ScopedModelsSelectorComponent } from "./scoped-models-selector.ts"; +export { SessionSelectorComponent } from "./session-selector.ts"; +export { type SettingsCallbacks, type SettingsConfig, SettingsSelectorComponent } from "./settings-selector.ts"; +export { ShowImagesSelectorComponent } from "./show-images-selector.ts"; +export { SkillInvocationMessageComponent } from "./skill-invocation-message.ts"; +export { ThemeSelectorComponent } from "./theme-selector.ts"; +export { ThinkingSelectorComponent } from "./thinking-selector.ts"; +export { ToolExecutionComponent, type ToolExecutionOptions } from "./tool-execution.ts"; +export { TreeSelectorComponent } from "./tree-selector.ts"; +export { TrustSelectorComponent } from "./trust-selector.ts"; +export { UserMessageComponent } from "./user-message.ts"; +export { UserMessageSelectorComponent } from "./user-message-selector.ts"; +export { truncateToVisualLines, type VisualTruncateResult } from "./visual-truncate.ts"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/index.d.ts.map b/dist/modes/interactive/components/index.d.ts.map new file mode 100644 index 0000000..5f9837f --- /dev/null +++ b/dist/modes/interactive/components/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;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AO,EAAE,KAAK,iBAAiB,EAAE,KAAK,cAAc,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AAChH,OAAO,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AACxE,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,KAAK,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACxF,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,qBAAqB,EAAE,KAAK,oBAAoB,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["// UI Components for extensions\nexport { ArminComponent } from \"./armin.ts\";\nexport { AssistantMessageComponent } from \"./assistant-message.ts\";\nexport { BashExecutionComponent } from \"./bash-execution.ts\";\nexport { BorderedLoader } from \"./bordered-loader.ts\";\nexport { BranchSummaryMessageComponent } from \"./branch-summary-message.ts\";\nexport { CompactionSummaryMessageComponent } from \"./compaction-summary-message.ts\";\nexport { CustomEditor } from \"./custom-editor.ts\";\nexport { CustomMessageComponent } from \"./custom-message.ts\";\nexport { DaxnutsComponent } from \"./daxnuts.ts\";\nexport { type RenderDiffOptions, renderDiff } from \"./diff.ts\";\nexport { DynamicBorder } from \"./dynamic-border.ts\";\nexport { ExtensionEditorComponent } from \"./extension-editor.ts\";\nexport { ExtensionInputComponent } from \"./extension-input.ts\";\nexport { ExtensionSelectorComponent } from \"./extension-selector.ts\";\nexport {\n\tFirstTimeSetupComponent,\n\ttype FirstTimeSetupOptions,\n\ttype FirstTimeSetupResult,\n} from \"./first-time-setup.ts\";\nexport { FooterComponent } from \"./footer.ts\";\nexport { keyHint, keyText, rawKeyHint } from \"./keybinding-hints.ts\";\nexport { LoginDialogComponent } from \"./login-dialog.ts\";\nexport { ModelSelectorComponent } from \"./model-selector.ts\";\nexport { OAuthSelectorComponent } from \"./oauth-selector.ts\";\nexport { type ModelsCallbacks, type ModelsConfig, ScopedModelsSelectorComponent } from \"./scoped-models-selector.ts\";\nexport { SessionSelectorComponent } from \"./session-selector.ts\";\nexport { type SettingsCallbacks, type SettingsConfig, SettingsSelectorComponent } from \"./settings-selector.ts\";\nexport { ShowImagesSelectorComponent } from \"./show-images-selector.ts\";\nexport { SkillInvocationMessageComponent } from \"./skill-invocation-message.ts\";\nexport { ThemeSelectorComponent } from \"./theme-selector.ts\";\nexport { ThinkingSelectorComponent } from \"./thinking-selector.ts\";\nexport { ToolExecutionComponent, type ToolExecutionOptions } from \"./tool-execution.ts\";\nexport { TreeSelectorComponent } from \"./tree-selector.ts\";\nexport { TrustSelectorComponent } from \"./trust-selector.ts\";\nexport { UserMessageComponent } from \"./user-message.ts\";\nexport { UserMessageSelectorComponent } from \"./user-message-selector.ts\";\nexport { truncateToVisualLines, type VisualTruncateResult } from \"./visual-truncate.ts\";\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/index.js b/dist/modes/interactive/components/index.js new file mode 100644 index 0000000..f265f72 --- /dev/null +++ b/dist/modes/interactive/components/index.js @@ -0,0 +1,35 @@ +// UI Components for extensions +export { ArminComponent } from "./armin.js"; +export { AssistantMessageComponent } from "./assistant-message.js"; +export { BashExecutionComponent } from "./bash-execution.js"; +export { BorderedLoader } from "./bordered-loader.js"; +export { BranchSummaryMessageComponent } from "./branch-summary-message.js"; +export { CompactionSummaryMessageComponent } from "./compaction-summary-message.js"; +export { CustomEditor } from "./custom-editor.js"; +export { CustomMessageComponent } from "./custom-message.js"; +export { DaxnutsComponent } from "./daxnuts.js"; +export { renderDiff } from "./diff.js"; +export { DynamicBorder } from "./dynamic-border.js"; +export { ExtensionEditorComponent } from "./extension-editor.js"; +export { ExtensionInputComponent } from "./extension-input.js"; +export { ExtensionSelectorComponent } from "./extension-selector.js"; +export { FirstTimeSetupComponent, } from "./first-time-setup.js"; +export { FooterComponent } from "./footer.js"; +export { keyHint, keyText, rawKeyHint } from "./keybinding-hints.js"; +export { LoginDialogComponent } from "./login-dialog.js"; +export { ModelSelectorComponent } from "./model-selector.js"; +export { OAuthSelectorComponent } from "./oauth-selector.js"; +export { ScopedModelsSelectorComponent } from "./scoped-models-selector.js"; +export { SessionSelectorComponent } from "./session-selector.js"; +export { SettingsSelectorComponent } from "./settings-selector.js"; +export { ShowImagesSelectorComponent } from "./show-images-selector.js"; +export { SkillInvocationMessageComponent } from "./skill-invocation-message.js"; +export { ThemeSelectorComponent } from "./theme-selector.js"; +export { ThinkingSelectorComponent } from "./thinking-selector.js"; +export { ToolExecutionComponent } from "./tool-execution.js"; +export { TreeSelectorComponent } from "./tree-selector.js"; +export { TrustSelectorComponent } from "./trust-selector.js"; +export { UserMessageComponent } from "./user-message.js"; +export { UserMessageSelectorComponent } from "./user-message-selector.js"; +export { truncateToVisualLines } from "./visual-truncate.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/index.js.map b/dist/modes/interactive/components/index.js.map new file mode 100644 index 0000000..09136c0 --- /dev/null +++ b/dist/modes/interactive/components/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/index.ts"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,6BAA6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BAAsB,EAA6B,MAAM,qBAAqB,CAAC;AACxF,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,qBAAqB,EAA6B,MAAM,sBAAsB,CAAC","sourcesContent":["// UI Components for extensions\nexport { ArminComponent } from \"./armin.ts\";\nexport { AssistantMessageComponent } from \"./assistant-message.ts\";\nexport { BashExecutionComponent } from \"./bash-execution.ts\";\nexport { BorderedLoader } from \"./bordered-loader.ts\";\nexport { BranchSummaryMessageComponent } from \"./branch-summary-message.ts\";\nexport { CompactionSummaryMessageComponent } from \"./compaction-summary-message.ts\";\nexport { CustomEditor } from \"./custom-editor.ts\";\nexport { CustomMessageComponent } from \"./custom-message.ts\";\nexport { DaxnutsComponent } from \"./daxnuts.ts\";\nexport { type RenderDiffOptions, renderDiff } from \"./diff.ts\";\nexport { DynamicBorder } from \"./dynamic-border.ts\";\nexport { ExtensionEditorComponent } from \"./extension-editor.ts\";\nexport { ExtensionInputComponent } from \"./extension-input.ts\";\nexport { ExtensionSelectorComponent } from \"./extension-selector.ts\";\nexport {\n\tFirstTimeSetupComponent,\n\ttype FirstTimeSetupOptions,\n\ttype FirstTimeSetupResult,\n} from \"./first-time-setup.ts\";\nexport { FooterComponent } from \"./footer.ts\";\nexport { keyHint, keyText, rawKeyHint } from \"./keybinding-hints.ts\";\nexport { LoginDialogComponent } from \"./login-dialog.ts\";\nexport { ModelSelectorComponent } from \"./model-selector.ts\";\nexport { OAuthSelectorComponent } from \"./oauth-selector.ts\";\nexport { type ModelsCallbacks, type ModelsConfig, ScopedModelsSelectorComponent } from \"./scoped-models-selector.ts\";\nexport { SessionSelectorComponent } from \"./session-selector.ts\";\nexport { type SettingsCallbacks, type SettingsConfig, SettingsSelectorComponent } from \"./settings-selector.ts\";\nexport { ShowImagesSelectorComponent } from \"./show-images-selector.ts\";\nexport { SkillInvocationMessageComponent } from \"./skill-invocation-message.ts\";\nexport { ThemeSelectorComponent } from \"./theme-selector.ts\";\nexport { ThinkingSelectorComponent } from \"./thinking-selector.ts\";\nexport { ToolExecutionComponent, type ToolExecutionOptions } from \"./tool-execution.ts\";\nexport { TreeSelectorComponent } from \"./tree-selector.ts\";\nexport { TrustSelectorComponent } from \"./trust-selector.ts\";\nexport { UserMessageComponent } from \"./user-message.ts\";\nexport { UserMessageSelectorComponent } from \"./user-message-selector.ts\";\nexport { truncateToVisualLines, type VisualTruncateResult } from \"./visual-truncate.ts\";\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/keybinding-hints.d.ts b/dist/modes/interactive/components/keybinding-hints.d.ts new file mode 100644 index 0000000..3ba39c2 --- /dev/null +++ b/dist/modes/interactive/components/keybinding-hints.d.ts @@ -0,0 +1,13 @@ +/** + * Utilities for formatting keybinding hints in the UI. + */ +import { type Keybinding } from "@earendil-works/pi-tui"; +export interface KeyTextFormatOptions { + capitalize?: boolean; +} +export declare function formatKeyText(key: string, options?: KeyTextFormatOptions): string; +export declare function keyText(keybinding: Keybinding): string; +export declare function keyDisplayText(keybinding: Keybinding): string; +export declare function keyHint(keybinding: Keybinding, description: string): string; +export declare function rawKeyHint(key: string, description: string): string; +//# sourceMappingURL=keybinding-hints.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/keybinding-hints.d.ts.map b/dist/modes/interactive/components/keybinding-hints.d.ts.map new file mode 100644 index 0000000..34e44a8 --- /dev/null +++ b/dist/modes/interactive/components/keybinding-hints.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"keybinding-hints.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/keybinding-hints.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAkB,KAAK,UAAU,EAAc,MAAM,wBAAwB,CAAC;AAGrF,MAAM,WAAW,oBAAoB;IACpC,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAOD,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,oBAAyB,GAAG,MAAM,CAUrF;AAOD,wBAAgB,OAAO,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAEtD;AAED,wBAAgB,cAAc,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAE7D;AAED,wBAAgB,OAAO,CAAC,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAE3E;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAEnE","sourcesContent":["/**\n * Utilities for formatting keybinding hints in the UI.\n */\n\nimport { getKeybindings, type Keybinding, type KeyId } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\n\nexport interface KeyTextFormatOptions {\n\tcapitalize?: boolean;\n}\n\nfunction formatKeyPart(part: string, options: KeyTextFormatOptions): string {\n\tconst displayPart = process.platform === \"darwin\" && part.toLowerCase() === \"alt\" ? \"option\" : part;\n\treturn options.capitalize ? displayPart.charAt(0).toUpperCase() + displayPart.slice(1) : displayPart;\n}\n\nexport function formatKeyText(key: string, options: KeyTextFormatOptions = {}): string {\n\treturn key\n\t\t.split(\"/\")\n\t\t.map((k) =>\n\t\t\tk\n\t\t\t\t.split(\"+\")\n\t\t\t\t.map((part) => formatKeyPart(part, options))\n\t\t\t\t.join(\"+\"),\n\t\t)\n\t\t.join(\"/\");\n}\n\nfunction formatKeys(keys: KeyId[], options: KeyTextFormatOptions = {}): string {\n\tif (keys.length === 0) return \"\";\n\treturn formatKeyText(keys.join(\"/\"), options);\n}\n\nexport function keyText(keybinding: Keybinding): string {\n\treturn formatKeys(getKeybindings().getKeys(keybinding));\n}\n\nexport function keyDisplayText(keybinding: Keybinding): string {\n\treturn formatKeys(getKeybindings().getKeys(keybinding), { capitalize: true });\n}\n\nexport function keyHint(keybinding: Keybinding, description: string): string {\n\treturn theme.fg(\"dim\", keyText(keybinding)) + theme.fg(\"muted\", ` ${description}`);\n}\n\nexport function rawKeyHint(key: string, description: string): string {\n\treturn theme.fg(\"dim\", formatKeyText(key)) + theme.fg(\"muted\", ` ${description}`);\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/keybinding-hints.js b/dist/modes/interactive/components/keybinding-hints.js new file mode 100644 index 0000000..03a6c66 --- /dev/null +++ b/dist/modes/interactive/components/keybinding-hints.js @@ -0,0 +1,36 @@ +/** + * Utilities for formatting keybinding hints in the UI. + */ +import { getKeybindings } from "@earendil-works/pi-tui"; +import { theme } from "../theme/theme.js"; +function formatKeyPart(part, options) { + const displayPart = process.platform === "darwin" && part.toLowerCase() === "alt" ? "option" : part; + return options.capitalize ? displayPart.charAt(0).toUpperCase() + displayPart.slice(1) : displayPart; +} +export function formatKeyText(key, options = {}) { + return key + .split("/") + .map((k) => k + .split("+") + .map((part) => formatKeyPart(part, options)) + .join("+")) + .join("/"); +} +function formatKeys(keys, options = {}) { + if (keys.length === 0) + return ""; + return formatKeyText(keys.join("/"), options); +} +export function keyText(keybinding) { + return formatKeys(getKeybindings().getKeys(keybinding)); +} +export function keyDisplayText(keybinding) { + return formatKeys(getKeybindings().getKeys(keybinding), { capitalize: true }); +} +export function keyHint(keybinding, description) { + return theme.fg("dim", keyText(keybinding)) + theme.fg("muted", ` ${description}`); +} +export function rawKeyHint(key, description) { + return theme.fg("dim", formatKeyText(key)) + theme.fg("muted", ` ${description}`); +} +//# sourceMappingURL=keybinding-hints.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/keybinding-hints.js.map b/dist/modes/interactive/components/keybinding-hints.js.map new file mode 100644 index 0000000..71479ae --- /dev/null +++ b/dist/modes/interactive/components/keybinding-hints.js.map @@ -0,0 +1 @@ +{"version":3,"file":"keybinding-hints.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/keybinding-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C,CAAC;AAAA,CACxD;AAED,MAAM,UAAU,cAAc,CAAC,UAAsB,EAAU;IAC9D,OAAO,UAAU,CAAC,cAAc,EAAE,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;AAAA,CAC9E;AAED,MAAM,UAAU,OAAO,CAAC,UAAsB,EAAE,WAAmB,EAAU;IAC5E,OAAO,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,WAAW,EAAE,CAAC,CAAC;AAAA,CACnF;AAED,MAAM,UAAU,UAAU,CAAC,GAAW,EAAE,WAAmB,EAAU;IACpE,OAAO,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,WAAW,EAAE,CAAC,CAAC;AAAA,CAClF","sourcesContent":["/**\n * Utilities for formatting keybinding hints in the UI.\n */\n\nimport { getKeybindings, type Keybinding, type KeyId } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\n\nexport interface KeyTextFormatOptions {\n\tcapitalize?: boolean;\n}\n\nfunction formatKeyPart(part: string, options: KeyTextFormatOptions): string {\n\tconst displayPart = process.platform === \"darwin\" && part.toLowerCase() === \"alt\" ? \"option\" : part;\n\treturn options.capitalize ? displayPart.charAt(0).toUpperCase() + displayPart.slice(1) : displayPart;\n}\n\nexport function formatKeyText(key: string, options: KeyTextFormatOptions = {}): string {\n\treturn key\n\t\t.split(\"/\")\n\t\t.map((k) =>\n\t\t\tk\n\t\t\t\t.split(\"+\")\n\t\t\t\t.map((part) => formatKeyPart(part, options))\n\t\t\t\t.join(\"+\"),\n\t\t)\n\t\t.join(\"/\");\n}\n\nfunction formatKeys(keys: KeyId[], options: KeyTextFormatOptions = {}): string {\n\tif (keys.length === 0) return \"\";\n\treturn formatKeyText(keys.join(\"/\"), options);\n}\n\nexport function keyText(keybinding: Keybinding): string {\n\treturn formatKeys(getKeybindings().getKeys(keybinding));\n}\n\nexport function keyDisplayText(keybinding: Keybinding): string {\n\treturn formatKeys(getKeybindings().getKeys(keybinding), { capitalize: true });\n}\n\nexport function keyHint(keybinding: Keybinding, description: string): string {\n\treturn theme.fg(\"dim\", keyText(keybinding)) + theme.fg(\"muted\", ` ${description}`);\n}\n\nexport function rawKeyHint(key: string, description: string): string {\n\treturn theme.fg(\"dim\", formatKeyText(key)) + theme.fg(\"muted\", ` ${description}`);\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/login-dialog.d.ts b/dist/modes/interactive/components/login-dialog.d.ts new file mode 100644 index 0000000..b3c89a1 --- /dev/null +++ b/dist/modes/interactive/components/login-dialog.d.ts @@ -0,0 +1,52 @@ +import type { AuthInfoLink, OAuthDeviceCodeInfo } from "@earendil-works/pi-ai"; +import { Container, type Focusable, type TUI } from "@earendil-works/pi-tui"; +/** + * Login dialog component - replaces editor during OAuth login flow + */ +export declare class LoginDialogComponent extends Container implements Focusable { + private contentContainer; + private input; + private tui; + private abortController; + private inputResolver?; + private inputRejecter?; + private onComplete; + private _focused; + get focused(): boolean; + set focused(value: boolean); + constructor(tui: TUI, providerId: string, onComplete: (success: boolean, message?: string) => void, providerNameOverride?: string, titleOverride?: string); + get signal(): AbortSignal; + private replaceInputWithSubmittedText; + private cancel; + /** + * Called by onAuth callback - show URL and optional instructions + */ + showAuth(url: string, instructions?: string): void; + /** + * Called by onDeviceCode callback - show URL and user code. + */ + showDeviceCode(info: OAuthDeviceCodeInfo): void; + /** + * Show input for manual code/URL entry (for callback server providers) + */ + showManualInput(prompt: string): Promise; + /** + * Called by onPrompt callback - show prompt and wait for input + * Note: Does NOT clear content, appends to existing (preserves URL from showAuth) + */ + showPrompt(message: string, placeholder?: string): Promise; + /** Show informational text before another login step. */ + showDetails(lines: string[]): void; + /** Show provider-owned information and links without starting an auth callback flow. */ + showInfo(message: string, links?: readonly AuthInfoLink[], showCloseHint?: boolean): void; + /** + * Show waiting message (for polling flows like GitHub Copilot) + */ + showWaiting(message: string): void; + /** + * Called by onProgress callback + */ + showProgress(message: string): void; + handleInput(data: string): void; +} +//# sourceMappingURL=login-dialog.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/login-dialog.d.ts.map b/dist/modes/interactive/components/login-dialog.d.ts.map new file mode 100644 index 0000000..2bb826b --- /dev/null +++ b/dist/modes/interactive/components/login-dialog.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"login-dialog.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/login-dialog.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,SAAS,EAAE,KAAK,SAAS,EAAuC,KAAK,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAMlH;;GAEG;AACH,qBAAa,oBAAqB,SAAQ,SAAU,YAAW,SAAS;IACvE,OAAO,CAAC,gBAAgB,CAAY;IACpC,OAAO,CAAC,KAAK,CAAQ;IACrB,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,eAAe,CAAyB;IAChD,OAAO,CAAC,aAAa,CAAC,CAA0B;IAChD,OAAO,CAAC,aAAa,CAAC,CAAyB;IAC/C,OAAO,CAAC,UAAU,CAA+C;IAGjE,OAAO,CAAC,QAAQ,CAAS;IACzB,IAAI,OAAO,IAAI,OAAO,CAErB;IACD,IAAI,OAAO,CAAC,KAAK,EAAE,OAAO,EAGzB;IAED,YACC,GAAG,EAAE,GAAG,EACR,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,KAAK,IAAI,EACxD,oBAAoB,CAAC,EAAE,MAAM,EAC7B,aAAa,CAAC,EAAE,MAAM,EAoCtB;IAED,IAAI,MAAM,IAAI,WAAW,CAExB;IAED,OAAO,CAAC,6BAA6B;IAMrC,OAAO,CAAC,MAAM;IAUd;;OAEG;IACH,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAiBjD;IAED;;OAEG;IACH,cAAc,CAAC,IAAI,EAAE,mBAAmB,GAAG,IAAI,CAa9C;IAED;;OAEG;IACH,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAY/C;IAED;;;OAGG;IACH,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAsBjE;IAED,yDAAyD;IACzD,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAOjC;IAED,wFAAwF;IACxF,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,GAAE,SAAS,YAAY,EAAO,EAAE,aAAa,UAAQ,GAAG,IAAI,CAa1F;IAED;;OAEG;IACH,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAKjC;IAED;;OAEG;IACH,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAGlC;IAED,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAU9B;CACD","sourcesContent":["import type { AuthInfoLink, OAuthDeviceCodeInfo } from \"@earendil-works/pi-ai\";\nimport { Container, type Focusable, getKeybindings, Input, Spacer, Text, type TUI } from \"@earendil-works/pi-tui\";\nimport { openBrowser } from \"../../../utils/open-browser.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint } from \"./keybinding-hints.ts\";\n\n/**\n * Login dialog component - replaces editor during OAuth login flow\n */\nexport class LoginDialogComponent extends Container implements Focusable {\n\tprivate contentContainer: Container;\n\tprivate input: Input;\n\tprivate tui: TUI;\n\tprivate abortController = new AbortController();\n\tprivate inputResolver?: (value: string) => void;\n\tprivate inputRejecter?: (error: Error) => void;\n\tprivate onComplete: (success: boolean, message?: string) => void;\n\n\t// Focusable implementation - propagate to input for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.input.focused = value;\n\t}\n\n\tconstructor(\n\t\ttui: TUI,\n\t\tproviderId: string,\n\t\tonComplete: (success: boolean, message?: string) => void,\n\t\tproviderNameOverride?: string,\n\t\ttitleOverride?: string,\n\t) {\n\t\tsuper();\n\t\tthis.tui = tui;\n\t\tthis.onComplete = onComplete;\n\n\t\tconst providerName = providerNameOverride || providerId;\n\t\tconst title = titleOverride ?? `Login to ${providerName}`;\n\n\t\t// Top border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Title\n\t\tthis.addChild(new Text(theme.fg(\"accent\", theme.bold(title)), 1, 0));\n\n\t\t// Dynamic content area\n\t\tthis.contentContainer = new Container();\n\t\tthis.addChild(this.contentContainer);\n\n\t\t// Input (always present, used when needed)\n\t\tthis.input = new Input();\n\t\tthis.input.onSubmit = () => {\n\t\t\tif (this.inputResolver) {\n\t\t\t\tconst value = this.input.getValue();\n\t\t\t\tthis.replaceInputWithSubmittedText(value);\n\t\t\t\tthis.inputResolver(value);\n\t\t\t\tthis.inputResolver = undefined;\n\t\t\t\tthis.inputRejecter = undefined;\n\t\t\t}\n\t\t};\n\t\tthis.input.onEscape = () => {\n\t\t\tthis.cancel();\n\t\t};\n\n\t\t// Bottom border\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.abortController.signal;\n\t}\n\n\tprivate replaceInputWithSubmittedText(value: string): void {\n\t\tthis.contentContainer.children = this.contentContainer.children.map((child) =>\n\t\t\tchild === this.input ? new Text(`> ${value}`, 0, 0) : child,\n\t\t);\n\t}\n\n\tprivate cancel(): void {\n\t\tthis.abortController.abort();\n\t\tif (this.inputRejecter) {\n\t\t\tthis.inputRejecter(new Error(\"Login cancelled\"));\n\t\t\tthis.inputResolver = undefined;\n\t\t\tthis.inputRejecter = undefined;\n\t\t}\n\t\tthis.onComplete(false, \"Login cancelled\");\n\t}\n\n\t/**\n\t * Called by onAuth callback - show URL and optional instructions\n\t */\n\tshowAuth(url: string, instructions?: string): void {\n\t\tthis.contentContainer.clear();\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tconst linkedUrl = `\\x1b]8;;${url}\\x07${url}\\x1b]8;;\\x07`;\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"accent\", linkedUrl), 1, 0));\n\n\t\tconst clickHint = process.platform === \"darwin\" ? \"Cmd+click to open\" : \"Ctrl+click to open\";\n\t\tconst hyperlink = `\\x1b]8;;${url}\\x07${clickHint}\\x1b]8;;\\x07`;\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"dim\", hyperlink), 1, 0));\n\n\t\tif (instructions) {\n\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t\tthis.contentContainer.addChild(new Text(theme.fg(\"warning\", instructions), 1, 0));\n\t\t}\n\n\t\topenBrowser(url);\n\t\tthis.tui.requestRender();\n\t}\n\n\t/**\n\t * Called by onDeviceCode callback - show URL and user code.\n\t */\n\tshowDeviceCode(info: OAuthDeviceCodeInfo): void {\n\t\tthis.contentContainer.clear();\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tconst linkedUrl = `\\x1b]8;;${info.verificationUri}\\x07${info.verificationUri}\\x1b]8;;\\x07`;\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"accent\", linkedUrl), 1, 0));\n\n\t\tconst clickHint = process.platform === \"darwin\" ? \"Cmd+click to open\" : \"Ctrl+click to open\";\n\t\tconst hyperlink = `\\x1b]8;;${info.verificationUri}\\x07${clickHint}\\x1b]8;;\\x07`;\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"dim\", hyperlink), 1, 0));\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"warning\", `Enter code: ${info.userCode}`), 1, 0));\n\n\t\tthis.tui.requestRender();\n\t}\n\n\t/**\n\t * Show input for manual code/URL entry (for callback server providers)\n\t */\n\tshowManualInput(prompt: string): Promise {\n\t\tthis.input.setValue(\"\");\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"dim\", prompt), 1, 0));\n\t\tthis.contentContainer.addChild(this.input);\n\t\tthis.contentContainer.addChild(new Text(`(${keyHint(\"tui.select.cancel\", \"to cancel\")})`, 1, 0));\n\t\tthis.tui.requestRender();\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.inputResolver = resolve;\n\t\t\tthis.inputRejecter = reject;\n\t\t});\n\t}\n\n\t/**\n\t * Called by onPrompt callback - show prompt and wait for input\n\t * Note: Does NOT clear content, appends to existing (preserves URL from showAuth)\n\t */\n\tshowPrompt(message: string, placeholder?: string): Promise {\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"text\", message), 1, 0));\n\t\tif (placeholder) {\n\t\t\tthis.contentContainer.addChild(new Text(theme.fg(\"dim\", `e.g., ${placeholder}`), 1, 0));\n\t\t}\n\t\tthis.contentContainer.addChild(this.input);\n\t\tthis.contentContainer.addChild(\n\t\t\tnew Text(\n\t\t\t\t`(${keyHint(\"tui.select.cancel\", \"to cancel,\")} ${keyHint(\"tui.select.confirm\", \"to submit\")})`,\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\n\t\tthis.input.setValue(\"\");\n\t\tthis.tui.requestRender();\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.inputResolver = resolve;\n\t\t\tthis.inputRejecter = reject;\n\t\t});\n\t}\n\n\t/** Show informational text before another login step. */\n\tshowDetails(lines: string[]): void {\n\t\tthis.contentContainer.clear();\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tfor (const line of lines) {\n\t\t\tthis.contentContainer.addChild(new Text(line, 1, 0));\n\t\t}\n\t\tthis.tui.requestRender();\n\t}\n\n\t/** Show provider-owned information and links without starting an auth callback flow. */\n\tshowInfo(message: string, links: readonly AuthInfoLink[] = [], showCloseHint = false): void {\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"text\", message), 1, 0));\n\t\tfor (const link of links) {\n\t\t\tconst text = link.label ? `${link.label}: ${link.url}` : link.url;\n\t\t\tconst hyperlink = `\\x1b]8;;${link.url}\\x07${text}\\x1b]8;;\\x07`;\n\t\t\tthis.contentContainer.addChild(new Text(theme.fg(\"accent\", hyperlink), 1, 0));\n\t\t}\n\t\tif (showCloseHint) {\n\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t\tthis.contentContainer.addChild(new Text(`(${keyHint(\"tui.select.cancel\", \"to close\")})`, 1, 0));\n\t\t}\n\t\tthis.tui.requestRender();\n\t}\n\n\t/**\n\t * Show waiting message (for polling flows like GitHub Copilot)\n\t */\n\tshowWaiting(message: string): void {\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"dim\", message), 1, 0));\n\t\tthis.contentContainer.addChild(new Text(`(${keyHint(\"tui.select.cancel\", \"to cancel\")})`, 1, 0));\n\t\tthis.tui.requestRender();\n\t}\n\n\t/**\n\t * Called by onProgress callback\n\t */\n\tshowProgress(message: string): void {\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"dim\", message), 1, 0));\n\t\tthis.tui.requestRender();\n\t}\n\n\thandleInput(data: string): void {\n\t\tconst kb = getKeybindings();\n\n\t\tif (kb.matches(data, \"tui.select.cancel\")) {\n\t\t\tthis.cancel();\n\t\t\treturn;\n\t\t}\n\n\t\t// Pass to input\n\t\tthis.input.handleInput(data);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/login-dialog.js b/dist/modes/interactive/components/login-dialog.js new file mode 100644 index 0000000..5a07de2 --- /dev/null +++ b/dist/modes/interactive/components/login-dialog.js @@ -0,0 +1,188 @@ +import { Container, getKeybindings, Input, Spacer, Text } from "@earendil-works/pi-tui"; +import { openBrowser } from "../../../utils/open-browser.js"; +import { theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyHint } from "./keybinding-hints.js"; +/** + * Login dialog component - replaces editor during OAuth login flow + */ +export class LoginDialogComponent extends Container { + contentContainer; + input; + tui; + abortController = new AbortController(); + inputResolver; + inputRejecter; + onComplete; + // Focusable implementation - propagate to input for IME cursor positioning + _focused = false; + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + this.input.focused = value; + } + constructor(tui, providerId, onComplete, providerNameOverride, titleOverride) { + super(); + this.tui = tui; + this.onComplete = onComplete; + const providerName = providerNameOverride || providerId; + const title = titleOverride ?? `Login to ${providerName}`; + // Top border + this.addChild(new DynamicBorder()); + // Title + this.addChild(new Text(theme.fg("accent", theme.bold(title)), 1, 0)); + // Dynamic content area + this.contentContainer = new Container(); + this.addChild(this.contentContainer); + // Input (always present, used when needed) + this.input = new Input(); + this.input.onSubmit = () => { + if (this.inputResolver) { + const value = this.input.getValue(); + this.replaceInputWithSubmittedText(value); + this.inputResolver(value); + this.inputResolver = undefined; + this.inputRejecter = undefined; + } + }; + this.input.onEscape = () => { + this.cancel(); + }; + // Bottom border + this.addChild(new DynamicBorder()); + } + get signal() { + return this.abortController.signal; + } + replaceInputWithSubmittedText(value) { + this.contentContainer.children = this.contentContainer.children.map((child) => child === this.input ? new Text(`> ${value}`, 0, 0) : child); + } + cancel() { + this.abortController.abort(); + if (this.inputRejecter) { + this.inputRejecter(new Error("Login cancelled")); + this.inputResolver = undefined; + this.inputRejecter = undefined; + } + this.onComplete(false, "Login cancelled"); + } + /** + * Called by onAuth callback - show URL and optional instructions + */ + showAuth(url, instructions) { + this.contentContainer.clear(); + this.contentContainer.addChild(new Spacer(1)); + const linkedUrl = `\x1b]8;;${url}\x07${url}\x1b]8;;\x07`; + this.contentContainer.addChild(new Text(theme.fg("accent", linkedUrl), 1, 0)); + const clickHint = process.platform === "darwin" ? "Cmd+click to open" : "Ctrl+click to open"; + const hyperlink = `\x1b]8;;${url}\x07${clickHint}\x1b]8;;\x07`; + this.contentContainer.addChild(new Text(theme.fg("dim", hyperlink), 1, 0)); + if (instructions) { + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(theme.fg("warning", instructions), 1, 0)); + } + openBrowser(url); + this.tui.requestRender(); + } + /** + * Called by onDeviceCode callback - show URL and user code. + */ + showDeviceCode(info) { + this.contentContainer.clear(); + this.contentContainer.addChild(new Spacer(1)); + const linkedUrl = `\x1b]8;;${info.verificationUri}\x07${info.verificationUri}\x1b]8;;\x07`; + this.contentContainer.addChild(new Text(theme.fg("accent", linkedUrl), 1, 0)); + const clickHint = process.platform === "darwin" ? "Cmd+click to open" : "Ctrl+click to open"; + const hyperlink = `\x1b]8;;${info.verificationUri}\x07${clickHint}\x1b]8;;\x07`; + this.contentContainer.addChild(new Text(theme.fg("dim", hyperlink), 1, 0)); + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(theme.fg("warning", `Enter code: ${info.userCode}`), 1, 0)); + this.tui.requestRender(); + } + /** + * Show input for manual code/URL entry (for callback server providers) + */ + showManualInput(prompt) { + this.input.setValue(""); + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(theme.fg("dim", prompt), 1, 0)); + this.contentContainer.addChild(this.input); + this.contentContainer.addChild(new Text(`(${keyHint("tui.select.cancel", "to cancel")})`, 1, 0)); + this.tui.requestRender(); + return new Promise((resolve, reject) => { + this.inputResolver = resolve; + this.inputRejecter = reject; + }); + } + /** + * Called by onPrompt callback - show prompt and wait for input + * Note: Does NOT clear content, appends to existing (preserves URL from showAuth) + */ + showPrompt(message, placeholder) { + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(theme.fg("text", message), 1, 0)); + if (placeholder) { + this.contentContainer.addChild(new Text(theme.fg("dim", `e.g., ${placeholder}`), 1, 0)); + } + this.contentContainer.addChild(this.input); + this.contentContainer.addChild(new Text(`(${keyHint("tui.select.cancel", "to cancel,")} ${keyHint("tui.select.confirm", "to submit")})`, 1, 0)); + this.input.setValue(""); + this.tui.requestRender(); + return new Promise((resolve, reject) => { + this.inputResolver = resolve; + this.inputRejecter = reject; + }); + } + /** Show informational text before another login step. */ + showDetails(lines) { + this.contentContainer.clear(); + this.contentContainer.addChild(new Spacer(1)); + for (const line of lines) { + this.contentContainer.addChild(new Text(line, 1, 0)); + } + this.tui.requestRender(); + } + /** Show provider-owned information and links without starting an auth callback flow. */ + showInfo(message, links = [], showCloseHint = false) { + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(theme.fg("text", message), 1, 0)); + for (const link of links) { + const text = link.label ? `${link.label}: ${link.url}` : link.url; + const hyperlink = `\x1b]8;;${link.url}\x07${text}\x1b]8;;\x07`; + this.contentContainer.addChild(new Text(theme.fg("accent", hyperlink), 1, 0)); + } + if (showCloseHint) { + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(`(${keyHint("tui.select.cancel", "to close")})`, 1, 0)); + } + this.tui.requestRender(); + } + /** + * Show waiting message (for polling flows like GitHub Copilot) + */ + showWaiting(message) { + this.contentContainer.addChild(new Spacer(1)); + this.contentContainer.addChild(new Text(theme.fg("dim", message), 1, 0)); + this.contentContainer.addChild(new Text(`(${keyHint("tui.select.cancel", "to cancel")})`, 1, 0)); + this.tui.requestRender(); + } + /** + * Called by onProgress callback + */ + showProgress(message) { + this.contentContainer.addChild(new Text(theme.fg("dim", message), 1, 0)); + this.tui.requestRender(); + } + handleInput(data) { + const kb = getKeybindings(); + if (kb.matches(data, "tui.select.cancel")) { + this.cancel(); + return; + } + // Pass to input + this.input.handleInput(data); + } +} +//# sourceMappingURL=login-dialog.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/login-dialog.js.map b/dist/modes/interactive/components/login-dialog.js.map new file mode 100644 index 0000000..b68ecb8 --- /dev/null +++ b/dist/modes/interactive/components/login-dialog.js.map @@ -0,0 +1 @@ +{"version":3,"file":"login-dialog.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/login-dialog.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAkB,cAAc,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAY,MAAM,wBAAwB,CAAC;AAClH,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAC7D,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAEhD;;GAEG;AACH,MAAM,OAAO,oBAAqB,SAAQ,SAAS;IAC1C,gBAAgB,CAAY;IAC5B,KAAK,CAAQ;IACb,GAAG,CAAM;IACT,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;IACxC,aAAa,CAA2B;IACxC,aAAa,CAA0B;IACvC,UAAU,CAA+C;IAEjE,2EAA2E;IACnE,QAAQ,GAAG,KAAK,CAAC;IACzB,IAAI,OAAO,GAAY;QACtB,OAAO,IAAI,CAAC,QAAQ,CAAC;IAAA,CACrB;IACD,IAAI,OAAO,CAAC,KAAc,EAAE;QAC3B,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC;IAAA,CAC3B;IAED,YACC,GAAQ,EACR,UAAkB,EAClB,UAAwD,EACxD,oBAA6B,EAC7B,aAAsB,EACrB;QACD,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAE7B,MAAM,YAAY,GAAG,oBAAoB,IAAI,UAAU,CAAC;QACxD,MAAM,KAAK,GAAG,aA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oLink, OAuthDeviceCodeInfo } from \"@earendil-works/pi-ai\";\nimport { Container, type Focusable, getKeybindings, Input, Spacer, Text, type TUI } from \"@earendil-works/pi-tui\";\nimport { openBrowser } from \"../../../utils/open-browser.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint } from \"./keybinding-hints.ts\";\n\n/**\n * Login dialog component - replaces editor during OAuth login flow\n */\nexport class LoginDialogComponent extends Container implements Focusable {\n\tprivate contentContainer: Container;\n\tprivate input: Input;\n\tprivate tui: TUI;\n\tprivate abortController = new AbortController();\n\tprivate inputResolver?: (value: string) => void;\n\tprivate inputRejecter?: (error: Error) => void;\n\tprivate onComplete: (success: boolean, message?: string) => void;\n\n\t// Focusable implementation - propagate to input for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.input.focused = value;\n\t}\n\n\tconstructor(\n\t\ttui: TUI,\n\t\tproviderId: string,\n\t\tonComplete: (success: boolean, message?: string) => void,\n\t\tproviderNameOverride?: string,\n\t\ttitleOverride?: string,\n\t) {\n\t\tsuper();\n\t\tthis.tui = tui;\n\t\tthis.onComplete = onComplete;\n\n\t\tconst providerName = providerNameOverride || providerId;\n\t\tconst title = titleOverride ?? `Login to ${providerName}`;\n\n\t\t// Top border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Title\n\t\tthis.addChild(new Text(theme.fg(\"accent\", theme.bold(title)), 1, 0));\n\n\t\t// Dynamic content area\n\t\tthis.contentContainer = new Container();\n\t\tthis.addChild(this.contentContainer);\n\n\t\t// Input (always present, used when needed)\n\t\tthis.input = new Input();\n\t\tthis.input.onSubmit = () => {\n\t\t\tif (this.inputResolver) {\n\t\t\t\tconst value = this.input.getValue();\n\t\t\t\tthis.replaceInputWithSubmittedText(value);\n\t\t\t\tthis.inputResolver(value);\n\t\t\t\tthis.inputResolver = undefined;\n\t\t\t\tthis.inputRejecter = undefined;\n\t\t\t}\n\t\t};\n\t\tthis.input.onEscape = () => {\n\t\t\tthis.cancel();\n\t\t};\n\n\t\t// Bottom border\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tget signal(): AbortSignal {\n\t\treturn this.abortController.signal;\n\t}\n\n\tprivate replaceInputWithSubmittedText(value: string): void {\n\t\tthis.contentContainer.children = this.contentContainer.children.map((child) =>\n\t\t\tchild === this.input ? new Text(`> ${value}`, 0, 0) : child,\n\t\t);\n\t}\n\n\tprivate cancel(): void {\n\t\tthis.abortController.abort();\n\t\tif (this.inputRejecter) {\n\t\t\tthis.inputRejecter(new Error(\"Login cancelled\"));\n\t\t\tthis.inputResolver = undefined;\n\t\t\tthis.inputRejecter = undefined;\n\t\t}\n\t\tthis.onComplete(false, \"Login cancelled\");\n\t}\n\n\t/**\n\t * Called by onAuth callback - show URL and optional instructions\n\t */\n\tshowAuth(url: string, instructions?: string): void {\n\t\tthis.contentContainer.clear();\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tconst linkedUrl = `\\x1b]8;;${url}\\x07${url}\\x1b]8;;\\x07`;\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"accent\", linkedUrl), 1, 0));\n\n\t\tconst clickHint = process.platform === \"darwin\" ? \"Cmd+click to open\" : \"Ctrl+click to open\";\n\t\tconst hyperlink = `\\x1b]8;;${url}\\x07${clickHint}\\x1b]8;;\\x07`;\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"dim\", hyperlink), 1, 0));\n\n\t\tif (instructions) {\n\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t\tthis.contentContainer.addChild(new Text(theme.fg(\"warning\", instructions), 1, 0));\n\t\t}\n\n\t\topenBrowser(url);\n\t\tthis.tui.requestRender();\n\t}\n\n\t/**\n\t * Called by onDeviceCode callback - show URL and user code.\n\t */\n\tshowDeviceCode(info: OAuthDeviceCodeInfo): void {\n\t\tthis.contentContainer.clear();\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tconst linkedUrl = `\\x1b]8;;${info.verificationUri}\\x07${info.verificationUri}\\x1b]8;;\\x07`;\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"accent\", linkedUrl), 1, 0));\n\n\t\tconst clickHint = process.platform === \"darwin\" ? \"Cmd+click to open\" : \"Ctrl+click to open\";\n\t\tconst hyperlink = `\\x1b]8;;${info.verificationUri}\\x07${clickHint}\\x1b]8;;\\x07`;\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"dim\", hyperlink), 1, 0));\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"warning\", `Enter code: ${info.userCode}`), 1, 0));\n\n\t\tthis.tui.requestRender();\n\t}\n\n\t/**\n\t * Show input for manual code/URL entry (for callback server providers)\n\t */\n\tshowManualInput(prompt: string): Promise {\n\t\tthis.input.setValue(\"\");\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"dim\", prompt), 1, 0));\n\t\tthis.contentContainer.addChild(this.input);\n\t\tthis.contentContainer.addChild(new Text(`(${keyHint(\"tui.select.cancel\", \"to cancel\")})`, 1, 0));\n\t\tthis.tui.requestRender();\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.inputResolver = resolve;\n\t\t\tthis.inputRejecter = reject;\n\t\t});\n\t}\n\n\t/**\n\t * Called by onPrompt callback - show prompt and wait for input\n\t * Note: Does NOT clear content, appends to existing (preserves URL from showAuth)\n\t */\n\tshowPrompt(message: string, placeholder?: string): Promise {\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"text\", message), 1, 0));\n\t\tif (placeholder) {\n\t\t\tthis.contentContainer.addChild(new Text(theme.fg(\"dim\", `e.g., ${placeholder}`), 1, 0));\n\t\t}\n\t\tthis.contentContainer.addChild(this.input);\n\t\tthis.contentContainer.addChild(\n\t\t\tnew Text(\n\t\t\t\t`(${keyHint(\"tui.select.cancel\", \"to cancel,\")} ${keyHint(\"tui.select.confirm\", \"to submit\")})`,\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\n\t\tthis.input.setValue(\"\");\n\t\tthis.tui.requestRender();\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.inputResolver = resolve;\n\t\t\tthis.inputRejecter = reject;\n\t\t});\n\t}\n\n\t/** Show informational text before another login step. */\n\tshowDetails(lines: string[]): void {\n\t\tthis.contentContainer.clear();\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tfor (const line of lines) {\n\t\t\tthis.contentContainer.addChild(new Text(line, 1, 0));\n\t\t}\n\t\tthis.tui.requestRender();\n\t}\n\n\t/** Show provider-owned information and links without starting an auth callback flow. */\n\tshowInfo(message: string, links: readonly AuthInfoLink[] = [], showCloseHint = false): void {\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"text\", message), 1, 0));\n\t\tfor (const link of links) {\n\t\t\tconst text = link.label ? `${link.label}: ${link.url}` : link.url;\n\t\t\tconst hyperlink = `\\x1b]8;;${link.url}\\x07${text}\\x1b]8;;\\x07`;\n\t\t\tthis.contentContainer.addChild(new Text(theme.fg(\"accent\", hyperlink), 1, 0));\n\t\t}\n\t\tif (showCloseHint) {\n\t\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\t\tthis.contentContainer.addChild(new Text(`(${keyHint(\"tui.select.cancel\", \"to close\")})`, 1, 0));\n\t\t}\n\t\tthis.tui.requestRender();\n\t}\n\n\t/**\n\t * Show waiting message (for polling flows like GitHub Copilot)\n\t */\n\tshowWaiting(message: string): void {\n\t\tthis.contentContainer.addChild(new Spacer(1));\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"dim\", message), 1, 0));\n\t\tthis.contentContainer.addChild(new Text(`(${keyHint(\"tui.select.cancel\", \"to cancel\")})`, 1, 0));\n\t\tthis.tui.requestRender();\n\t}\n\n\t/**\n\t * Called by onProgress callback\n\t */\n\tshowProgress(message: string): void {\n\t\tthis.contentContainer.addChild(new Text(theme.fg(\"dim\", message), 1, 0));\n\t\tthis.tui.requestRender();\n\t}\n\n\thandleInput(data: string): void {\n\t\tconst kb = getKeybindings();\n\n\t\tif (kb.matches(data, \"tui.select.cancel\")) {\n\t\t\tthis.cancel();\n\t\t\treturn;\n\t\t}\n\n\t\t// Pass to input\n\t\tthis.input.handleInput(data);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/model-selector.d.ts b/dist/modes/interactive/components/model-selector.d.ts new file mode 100644 index 0000000..52138d4 --- /dev/null +++ b/dist/modes/interactive/components/model-selector.d.ts @@ -0,0 +1,54 @@ +import { type Model } from "@earendil-works/pi-ai"; +import { Container, type Focusable, Input, type TUI } from "@earendil-works/pi-tui"; +import type { ModelRuntime } from "../../../core/model-runtime.ts"; +import type { SettingsManager } from "../../../core/settings-manager.ts"; +interface ScopedModelItem { + model: Model; + thinkingLevel?: string; +} +/** + * Component that renders a model selector with search + */ +export declare class ModelSelectorComponent extends Container implements Focusable { + private searchInput; + private _focused; + get focused(): boolean; + set focused(value: boolean); + private listContainer; + private allModels; + private scopedModelItems; + private activeModels; + private filteredModels; + private selectedIndex; + private currentModel?; + private settingsManager; + private modelRuntime; + private onSelectCallback; + private onCancelCallback; + private errorMessage?; + private refreshStatusMessage; + private refreshStatusSuccess; + private tui; + private scopedModels; + private scope; + private scopeText?; + private scopeHintText?; + private readonly refreshAbortController; + private refreshTimeout?; + private closed; + constructor(tui: TUI, currentModel: Model | undefined, settingsManager: SettingsManager, modelRuntime: ModelRuntime, scopedModels: ReadonlyArray, onSelect: (model: Model) => void, onCancel: () => void, initialSearchInput?: string); + private loadModelsFromSnapshot; + private refreshModels; + private close; + private sortModels; + private getScopeText; + private getScopeHintText; + private setScope; + private filterModels; + private updateList; + handleInput(keyData: string): void; + private handleSelect; + getSearchInput(): Input; +} +export {}; +//# sourceMappingURL=model-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/model-selector.d.ts.map b/dist/modes/interactive/components/model-selector.d.ts.map new file mode 100644 index 0000000..53328fd --- /dev/null +++ b/dist/modes/interactive/components/model-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"model-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/model-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,KAAK,EAAkB,MAAM,uBAAuB,CAAC;AACnE,OAAO,EACN,SAAS,EACT,KAAK,SAAS,EAGd,KAAK,EAGL,KAAK,GAAG,EACR,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AAYzE,UAAU,eAAe;IACxB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAID;;GAEG;AACH,qBAAa,sBAAuB,SAAQ,SAAU,YAAW,SAAS;IACzE,OAAO,CAAC,WAAW,CAAQ;IAG3B,OAAO,CAAC,QAAQ,CAAS;IACzB,IAAI,OAAO,IAAI,OAAO,CAErB;IACD,IAAI,OAAO,CAAC,KAAK,EAAE,OAAO,EAGzB;IACD,OAAO,CAAC,aAAa,CAAY;IACjC,OAAO,CAAC,SAAS,CAAmB;IACpC,OAAO,CAAC,gBAAgB,CAAmB;IAC3C,OAAO,CAAC,YAAY,CAAmB;IACvC,OAAO,CAAC,cAAc,CAAmB;IACzC,OAAO,CAAC,aAAa,CAAa;IAClC,OAAO,CAAC,YAAY,CAAC,CAAa;IAClC,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,YAAY,CAAe;IACnC,OAAO,CAAC,gBAAgB,CAA8B;IACtD,OAAO,CAAC,gBAAgB,CAAa;IACrC,OAAO,CAAC,YAAY,CAAC,CAAS;IAC9B,OAAO,CAAC,oBAAoB,CAAgC;IAC5D,OAAO,CAAC,oBAAoB,CAAS;IACrC,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,YAAY,CAAiC;IACrD,OAAO,CAAC,KAAK,CAAqB;IAClC,OAAO,CAAC,SAAS,CAAC,CAAO;IACzB,OAAO,CAAC,aAAa,CAAC,CAAO;IAC7B,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAyB;IAChE,OAAO,CAAC,cAAc,CAAC,CAAgC;IACvD,OAAO,CAAC,MAAM,CAAS;IAEvB,YACC,GAAG,EAAE,GAAG,EACR,YAAY,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,EACpC,eAAe,EAAE,eAAe,EAChC,YAAY,EAAE,YAAY,EAC1B,YAAY,EAAE,aAAa,CAAC,eAAe,CAAC,EAC5C,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,EACrC,QAAQ,EAAE,MAAM,IAAI,EACpB,kBAAkB,CAAC,EAAE,MAAM,EA2D3B;IAED,OAAO,CAAC,sBAAsB;YAuBhB,aAAa;IAgC3B,OAAO,CAAC,KAAK;IAMb,OAAO,CAAC,UAAU;IAalB,OAAO,CAAC,YAAY;IAMpB,OAAO,CAAC,gBAAgB;IAIxB,OAAO,CAAC,QAAQ;IAYhB,OAAO,CAAC,YAAY;IAapB,OAAO,CAAC,UAAU;IA+DlB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAyCjC;IAED,OAAO,CAAC,YAAY;IAOpB,cAAc,IAAI,KAAK,CAEtB;CACD","sourcesContent":["import { type Model, modelsAreEqual } from \"@earendil-works/pi-ai\";\nimport {\n\tContainer,\n\ttype Focusable,\n\tfuzzyFilter,\n\tgetKeybindings,\n\tInput,\n\tSpacer,\n\tText,\n\ttype TUI,\n} from \"@earendil-works/pi-tui\";\nimport type { ModelRuntime } from \"../../../core/model-runtime.ts\";\nimport type { SettingsManager } from \"../../../core/settings-manager.ts\";\nimport { getModelSelectorSearchText } from \"../model-search.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint } from \"./keybinding-hints.ts\";\n\ninterface ModelItem {\n\tprovider: string;\n\tid: string;\n\tmodel: Model;\n}\n\ninterface ScopedModelItem {\n\tmodel: Model;\n\tthinkingLevel?: string;\n}\n\ntype ModelScope = \"all\" | \"scoped\";\n\n/**\n * Component that renders a model selector with search\n */\nexport class ModelSelectorComponent extends Container implements Focusable {\n\tprivate searchInput: Input;\n\n\t// Focusable implementation - propagate to searchInput for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.searchInput.focused = value;\n\t}\n\tprivate listContainer: Container;\n\tprivate allModels: ModelItem[] = [];\n\tprivate scopedModelItems: ModelItem[] = [];\n\tprivate activeModels: ModelItem[] = [];\n\tprivate filteredModels: ModelItem[] = [];\n\tprivate selectedIndex: number = 0;\n\tprivate currentModel?: Model;\n\tprivate settingsManager: SettingsManager;\n\tprivate modelRuntime: ModelRuntime;\n\tprivate onSelectCallback: (model: Model) => void;\n\tprivate onCancelCallback: () => void;\n\tprivate errorMessage?: string;\n\tprivate refreshStatusMessage = \"Refreshing model catalogs…\";\n\tprivate refreshStatusSuccess = false;\n\tprivate tui: TUI;\n\tprivate scopedModels: ReadonlyArray;\n\tprivate scope: ModelScope = \"all\";\n\tprivate scopeText?: Text;\n\tprivate scopeHintText?: Text;\n\tprivate readonly refreshAbortController = new AbortController();\n\tprivate refreshTimeout?: ReturnType;\n\tprivate closed = false;\n\n\tconstructor(\n\t\ttui: TUI,\n\t\tcurrentModel: Model | undefined,\n\t\tsettingsManager: SettingsManager,\n\t\tmodelRuntime: ModelRuntime,\n\t\tscopedModels: ReadonlyArray,\n\t\tonSelect: (model: Model) => void,\n\t\tonCancel: () => void,\n\t\tinitialSearchInput?: string,\n\t) {\n\t\tsuper();\n\n\t\tthis.tui = tui;\n\t\tthis.currentModel = currentModel;\n\t\tthis.settingsManager = settingsManager;\n\t\tthis.modelRuntime = modelRuntime;\n\t\tthis.scopedModels = scopedModels;\n\t\tthis.scope = scopedModels.length > 0 ? \"scoped\" : \"all\";\n\t\tthis.onSelectCallback = onSelect;\n\t\tthis.onCancelCallback = onCancel;\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add hint about model filtering\n\t\tif (scopedModels.length > 0) {\n\t\t\tthis.scopeText = new Text(this.getScopeText(), 0, 0);\n\t\t\tthis.addChild(this.scopeText);\n\t\t\tthis.scopeHintText = new Text(this.getScopeHintText(), 0, 0);\n\t\t\tthis.addChild(this.scopeHintText);\n\t\t} else {\n\t\t\tconst hintText = \"Only showing models from configured providers. Use /login to add providers.\";\n\t\t\tthis.addChild(new Text(theme.fg(\"warning\", hintText), 0, 0));\n\t\t}\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create search input\n\t\tthis.searchInput = new Input();\n\t\tif (initialSearchInput) {\n\t\t\tthis.searchInput.setValue(initialSearchInput);\n\t\t}\n\t\tthis.searchInput.onSubmit = () => {\n\t\t\t// Enter on search input selects the first filtered item\n\t\t\tif (this.filteredModels[this.selectedIndex]) {\n\t\t\t\tthis.handleSelect(this.filteredModels[this.selectedIndex].model);\n\t\t\t}\n\t\t};\n\t\tthis.addChild(this.searchInput);\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create list container\n\t\tthis.listContainer = new Container();\n\t\tthis.addChild(this.listContainer);\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Render the current snapshot immediately, then refresh in the background.\n\t\tthis.loadModelsFromSnapshot();\n\t\tif (initialSearchInput) this.filterModels(initialSearchInput);\n\t\telse this.updateList();\n\t\tthis.tui.requestRender();\n\t\tvoid this.refreshModels();\n\t}\n\n\tprivate loadModelsFromSnapshot(): void {\n\t\tconst models = this.modelRuntime.getAvailableSnapshot().map((model: Model) => ({\n\t\t\tprovider: model.provider,\n\t\t\tid: model.id,\n\t\t\tmodel,\n\t\t}));\n\t\tthis.allModels = this.sortModels(models);\n\t\tthis.scopedModels = this.scopedModels.map((scoped) => {\n\t\t\tconst refreshed = this.modelRuntime.getModel(scoped.model.provider, scoped.model.id);\n\t\t\treturn refreshed ? { ...scoped, model: refreshed } : scoped;\n\t\t});\n\t\tthis.scopedModelItems = this.scopedModels.map((scoped) => ({\n\t\t\tprovider: scoped.model.provider,\n\t\t\tid: scoped.model.id,\n\t\t\tmodel: scoped.model,\n\t\t}));\n\t\tthis.activeModels = this.scope === \"scoped\" ? this.scopedModelItems : this.allModels;\n\t\tthis.filteredModels = this.activeModels;\n\t\tconst currentIndex = this.filteredModels.findIndex((item) => modelsAreEqual(this.currentModel, item.model));\n\t\tthis.selectedIndex =\n\t\t\tcurrentIndex >= 0 ? currentIndex : Math.min(this.selectedIndex, Math.max(0, this.filteredModels.length - 1));\n\t}\n\n\tprivate async refreshModels(): Promise {\n\t\tconst timeoutMs = 15_000;\n\t\tlet timedOut = false;\n\t\tthis.refreshTimeout = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tthis.refreshAbortController.abort();\n\t\t}, timeoutMs);\n\t\ttry {\n\t\t\tconst result = await this.modelRuntime.refresh({ signal: this.refreshAbortController.signal });\n\t\t\tif (this.closed) return;\n\t\t\tthis.refreshStatusMessage = \"\";\n\t\t\tif (result.aborted && timedOut) {\n\t\t\t\tthis.errorMessage = \"Model refresh timed out; showing cached models.\";\n\t\t\t} else if (result.errors.size === 1) {\n\t\t\t\tthis.errorMessage = `Could not refresh ${result.errors.keys().next().value}; showing cached models.`;\n\t\t\t} else if (result.errors.size > 1) {\n\t\t\t\tthis.errorMessage = `Could not refresh ${result.errors.size} model catalogs; showing cached models.`;\n\t\t\t} else {\n\t\t\t\tthis.errorMessage = this.modelRuntime.getError();\n\t\t\t\tif (!this.errorMessage) {\n\t\t\t\t\tthis.refreshStatusMessage = \"Model catalogs refreshed.\";\n\t\t\t\t\tthis.refreshStatusSuccess = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.loadModelsFromSnapshot();\n\t\t\tthis.filterModels(this.searchInput.getValue());\n\t\t\tthis.tui.requestRender();\n\t\t} finally {\n\t\t\tif (this.refreshTimeout) clearTimeout(this.refreshTimeout);\n\t\t}\n\t}\n\n\tprivate close(): void {\n\t\tthis.closed = true;\n\t\tif (this.refreshTimeout) clearTimeout(this.refreshTimeout);\n\t\tthis.refreshAbortController.abort();\n\t}\n\n\tprivate sortModels(models: ModelItem[]): ModelItem[] {\n\t\tconst sorted = [...models];\n\t\t// Sort: current model first, then by provider\n\t\tsorted.sort((a, b) => {\n\t\t\tconst aIsCurrent = modelsAreEqual(this.currentModel, a.model);\n\t\t\tconst bIsCurrent = modelsAreEqual(this.currentModel, b.model);\n\t\t\tif (aIsCurrent && !bIsCurrent) return -1;\n\t\t\tif (!aIsCurrent && bIsCurrent) return 1;\n\t\t\treturn a.provider.localeCompare(b.provider);\n\t\t});\n\t\treturn sorted;\n\t}\n\n\tprivate getScopeText(): string {\n\t\tconst allText = this.scope === \"all\" ? theme.fg(\"accent\", \"all\") : theme.fg(\"muted\", \"all\");\n\t\tconst scopedText = this.scope === \"scoped\" ? theme.fg(\"accent\", \"scoped\") : theme.fg(\"muted\", \"scoped\");\n\t\treturn `${theme.fg(\"muted\", \"Scope: \")}${allText}${theme.fg(\"muted\", \" | \")}${scopedText}`;\n\t}\n\n\tprivate getScopeHintText(): string {\n\t\treturn keyHint(\"tui.input.tab\", \"scope\") + theme.fg(\"muted\", \" (all/scoped)\");\n\t}\n\n\tprivate setScope(scope: ModelScope): void {\n\t\tif (this.scope === scope) return;\n\t\tthis.scope = scope;\n\t\tthis.activeModels = this.scope === \"scoped\" ? this.scopedModelItems : this.allModels;\n\t\tconst currentIndex = this.activeModels.findIndex((item) => modelsAreEqual(this.currentModel, item.model));\n\t\tthis.selectedIndex = currentIndex >= 0 ? currentIndex : 0;\n\t\tthis.filterModels(this.searchInput.getValue());\n\t\tif (this.scopeText) {\n\t\t\tthis.scopeText.setText(this.getScopeText());\n\t\t}\n\t}\n\n\tprivate filterModels(query: string): void {\n\t\tthis.filteredModels = query\n\t\t\t? fuzzyFilter(this.activeModels, query, ({ id, provider, model }) =>\n\t\t\t\t\tgetModelSelectorSearchText({ id, provider, name: model.name }),\n\t\t\t\t)\n\t\t\t: this.activeModels;\n\t\t// When filtering by a query, move the selector to the top row so the best\n\t\t// match is highlighted. When the query is cleared, keep the current position\n\t\t// clamped to the (restored) list length.\n\t\tthis.selectedIndex = query ? 0 : Math.min(this.selectedIndex, Math.max(0, this.filteredModels.length - 1));\n\t\tthis.updateList();\n\t}\n\n\tprivate updateList(): void {\n\t\tthis.listContainer.clear();\n\n\t\tconst maxVisible = 10;\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(maxVisible / 2), this.filteredModels.length - maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + maxVisible, this.filteredModels.length);\n\n\t\t// Show visible slice of filtered models\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst item = this.filteredModels[i];\n\t\t\tif (!item) continue;\n\n\t\t\tconst isSelected = i === this.selectedIndex;\n\t\t\tconst isCurrent = modelsAreEqual(this.currentModel, item.model);\n\n\t\t\tlet line = \"\";\n\t\t\tif (isSelected) {\n\t\t\t\tconst prefix = theme.fg(\"accent\", \"→ \");\n\t\t\t\tconst modelText = `${item.id}`;\n\t\t\t\tconst providerBadge = theme.fg(\"muted\", `[${item.provider}]`);\n\t\t\t\tconst checkmark = isCurrent ? theme.fg(\"success\", \" ✓\") : \"\";\n\t\t\t\tline = `${prefix + theme.fg(\"accent\", modelText)} ${providerBadge}${checkmark}`;\n\t\t\t} else {\n\t\t\t\tconst modelText = ` ${item.id}`;\n\t\t\t\tconst providerBadge = theme.fg(\"muted\", `[${item.provider}]`);\n\t\t\t\tconst checkmark = isCurrent ? theme.fg(\"success\", \" ✓\") : \"\";\n\t\t\t\tline = `${modelText} ${providerBadge}${checkmark}`;\n\t\t\t}\n\n\t\t\tthis.listContainer.addChild(new Text(line, 0, 0));\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.filteredModels.length) {\n\t\t\tconst scrollInfo = theme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.filteredModels.length})`);\n\t\t\tthis.listContainer.addChild(new Text(scrollInfo, 0, 0));\n\t\t}\n\n\t\t// Show error message or \"no results\" if empty\n\t\tif (this.errorMessage) {\n\t\t\t// Show error in red\n\t\t\tconst errorLines = this.errorMessage.split(\"\\n\");\n\t\t\tfor (const line of errorLines) {\n\t\t\t\tthis.listContainer.addChild(new Text(theme.fg(\"error\", line), 0, 0));\n\t\t\t}\n\t\t} else if (this.filteredModels.length === 0) {\n\t\t\tthis.listContainer.addChild(new Text(theme.fg(\"muted\", \" No matching models\"), 0, 0));\n\t\t} else {\n\t\t\tconst selected = this.filteredModels[this.selectedIndex];\n\t\t\tthis.listContainer.addChild(new Spacer(1));\n\t\t\tthis.listContainer.addChild(new Text(theme.fg(\"muted\", ` Model Name: ${selected.model.name}`), 0, 0));\n\t\t}\n\t\tif (this.refreshStatusMessage) {\n\t\t\tthis.listContainer.addChild(new Spacer(1));\n\t\t\tthis.listContainer.addChild(\n\t\t\t\tnew Text(theme.fg(this.refreshStatusSuccess ? \"success\" : \"muted\", ` ${this.refreshStatusMessage}`), 0, 0),\n\t\t\t);\n\t\t}\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"tui.input.tab\")) {\n\t\t\tif (this.scopedModelItems.length > 0) {\n\t\t\t\tconst nextScope: ModelScope = this.scope === \"all\" ? \"scoped\" : \"all\";\n\t\t\t\tthis.setScope(nextScope);\n\t\t\t\tif (this.scopeHintText) {\n\t\t\t\t\tthis.scopeHintText.setText(this.getScopeHintText());\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t// Up arrow - wrap to bottom when at top\n\t\tif (kb.matches(keyData, \"tui.select.up\")) {\n\t\t\tif (this.filteredModels.length === 0) return;\n\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.filteredModels.length - 1 : this.selectedIndex - 1;\n\t\t\tthis.updateList();\n\t\t}\n\t\t// Down arrow - wrap to top when at bottom\n\t\telse if (kb.matches(keyData, \"tui.select.down\")) {\n\t\t\tif (this.filteredModels.length === 0) return;\n\t\t\tthis.selectedIndex = this.selectedIndex === this.filteredModels.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t\tthis.updateList();\n\t\t}\n\t\t// Enter\n\t\telse if (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\tconst selectedModel = this.filteredModels[this.selectedIndex];\n\t\t\tif (selectedModel) {\n\t\t\t\tthis.handleSelect(selectedModel.model);\n\t\t\t}\n\t\t}\n\t\t// Escape or Ctrl+C\n\t\telse if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.close();\n\t\t\tthis.onCancelCallback();\n\t\t}\n\t\t// Pass everything else to search input\n\t\telse {\n\t\t\tthis.searchInput.handleInput(keyData);\n\t\t\tthis.filterModels(this.searchInput.getValue());\n\t\t}\n\t}\n\n\tprivate handleSelect(model: Model): void {\n\t\tthis.close();\n\t\t// Save as new default\n\t\tthis.settingsManager.setDefaultModelAndProvider(model.provider, model.id);\n\t\tthis.onSelectCallback(model);\n\t}\n\n\tgetSearchInput(): Input {\n\t\treturn this.searchInput;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/model-selector.js b/dist/modes/interactive/components/model-selector.js new file mode 100644 index 0000000..b595a53 --- /dev/null +++ b/dist/modes/interactive/components/model-selector.js @@ -0,0 +1,313 @@ +import { modelsAreEqual } from "@earendil-works/pi-ai"; +import { Container, fuzzyFilter, getKeybindings, Input, Spacer, Text, } from "@earendil-works/pi-tui"; +import { getModelSelectorSearchText } from "../model-search.js"; +import { theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyHint } from "./keybinding-hints.js"; +/** + * Component that renders a model selector with search + */ +export class ModelSelectorComponent extends Container { + searchInput; + // Focusable implementation - propagate to searchInput for IME cursor positioning + _focused = false; + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + this.searchInput.focused = value; + } + listContainer; + allModels = []; + scopedModelItems = []; + activeModels = []; + filteredModels = []; + selectedIndex = 0; + currentModel; + settingsManager; + modelRuntime; + onSelectCallback; + onCancelCallback; + errorMessage; + refreshStatusMessage = "Refreshing model catalogs…"; + refreshStatusSuccess = false; + tui; + scopedModels; + scope = "all"; + scopeText; + scopeHintText; + refreshAbortController = new AbortController(); + refreshTimeout; + closed = false; + constructor(tui, currentModel, settingsManager, modelRuntime, scopedModels, onSelect, onCancel, initialSearchInput) { + super(); + this.tui = tui; + this.currentModel = currentModel; + this.settingsManager = settingsManager; + this.modelRuntime = modelRuntime; + this.scopedModels = scopedModels; + this.scope = scopedModels.length > 0 ? "scoped" : "all"; + this.onSelectCallback = onSelect; + this.onCancelCallback = onCancel; + // Add top border + this.addChild(new DynamicBorder()); + this.addChild(new Spacer(1)); + // Add hint about model filtering + if (scopedModels.length > 0) { + this.scopeText = new Text(this.getScopeText(), 0, 0); + this.addChild(this.scopeText); + this.scopeHintText = new Text(this.getScopeHintText(), 0, 0); + this.addChild(this.scopeHintText); + } + else { + const hintText = "Only showing models from configured providers. Use /login to add providers."; + this.addChild(new Text(theme.fg("warning", hintText), 0, 0)); + } + this.addChild(new Spacer(1)); + // Create search input + this.searchInput = new Input(); + if (initialSearchInput) { + this.searchInput.setValue(initialSearchInput); + } + this.searchInput.onSubmit = () => { + // Enter on search input selects the first filtered item + if (this.filteredModels[this.selectedIndex]) { + this.handleSelect(this.filteredModels[this.selectedIndex].model); + } + }; + this.addChild(this.searchInput); + this.addChild(new Spacer(1)); + // Create list container + this.listContainer = new Container(); + this.addChild(this.listContainer); + this.addChild(new Spacer(1)); + // Add bottom border + this.addChild(new DynamicBorder()); + // Render the current snapshot immediately, then refresh in the background. + this.loadModelsFromSnapshot(); + if (initialSearchInput) + this.filterModels(initialSearchInput); + else + this.updateList(); + this.tui.requestRender(); + void this.refreshModels(); + } + loadModelsFromSnapshot() { + const models = this.modelRuntime.getAvailableSnapshot().map((model) => ({ + provider: model.provider, + id: model.id, + model, + })); + this.allModels = this.sortModels(models); + this.scopedModels = this.scopedModels.map((scoped) => { + const refreshed = this.modelRuntime.getModel(scoped.model.provider, scoped.model.id); + return refreshed ? { ...scoped, model: refreshed } : scoped; + }); + this.scopedModelItems = this.scopedModels.map((scoped) => ({ + provider: scoped.model.provider, + id: scoped.model.id, + model: scoped.model, + })); + this.activeModels = this.scope === "scoped" ? this.scopedModelItems : this.allModels; + this.filteredModels = this.activeModels; + const currentIndex = this.filteredModels.findIndex((item) => modelsAreEqual(this.currentModel, item.model)); + this.selectedIndex = + currentIndex >= 0 ? currentIndex : Math.min(this.selectedIndex, Math.max(0, this.filteredModels.length - 1)); + } + async refreshModels() { + const timeoutMs = 15_000; + let timedOut = false; + this.refreshTimeout = setTimeout(() => { + timedOut = true; + this.refreshAbortController.abort(); + }, timeoutMs); + try { + const result = await this.modelRuntime.refresh({ signal: this.refreshAbortController.signal }); + if (this.closed) + return; + this.refreshStatusMessage = ""; + if (result.aborted && timedOut) { + this.errorMessage = "Model refresh timed out; showing cached models."; + } + else if (result.errors.size === 1) { + this.errorMessage = `Could not refresh ${result.errors.keys().next().value}; showing cached models.`; + } + else if (result.errors.size > 1) { + this.errorMessage = `Could not refresh ${result.errors.size} model catalogs; showing cached models.`; + } + else { + this.errorMessage = this.modelRuntime.getError(); + if (!this.errorMessage) { + this.refreshStatusMessage = "Model catalogs refreshed."; + this.refreshStatusSuccess = true; + } + } + this.loadModelsFromSnapshot(); + this.filterModels(this.searchInput.getValue()); + this.tui.requestRender(); + } + finally { + if (this.refreshTimeout) + clearTimeout(this.refreshTimeout); + } + } + close() { + this.closed = true; + if (this.refreshTimeout) + clearTimeout(this.refreshTimeout); + this.refreshAbortController.abort(); + } + sortModels(models) { + const sorted = [...models]; + // Sort: current model first, then by provider + sorted.sort((a, b) => { + const aIsCurrent = modelsAreEqual(this.currentModel, a.model); + const bIsCurrent = modelsAreEqual(this.currentModel, b.model); + if (aIsCurrent && !bIsCurrent) + return -1; + if (!aIsCurrent && bIsCurrent) + return 1; + return a.provider.localeCompare(b.provider); + }); + return sorted; + } + getScopeText() { + const allText = this.scope === "all" ? theme.fg("accent", "all") : theme.fg("muted", "all"); + const scopedText = this.scope === "scoped" ? theme.fg("accent", "scoped") : theme.fg("muted", "scoped"); + return `${theme.fg("muted", "Scope: ")}${allText}${theme.fg("muted", " | ")}${scopedText}`; + } + getScopeHintText() { + return keyHint("tui.input.tab", "scope") + theme.fg("muted", " (all/scoped)"); + } + setScope(scope) { + if (this.scope === scope) + return; + this.scope = scope; + this.activeModels = this.scope === "scoped" ? this.scopedModelItems : this.allModels; + const currentIndex = this.activeModels.findIndex((item) => modelsAreEqual(this.currentModel, item.model)); + this.selectedIndex = currentIndex >= 0 ? currentIndex : 0; + this.filterModels(this.searchInput.getValue()); + if (this.scopeText) { + this.scopeText.setText(this.getScopeText()); + } + } + filterModels(query) { + this.filteredModels = query + ? fuzzyFilter(this.activeModels, query, ({ id, provider, model }) => getModelSelectorSearchText({ id, provider, name: model.name })) + : this.activeModels; + // When filtering by a query, move the selector to the top row so the best + // match is highlighted. When the query is cleared, keep the current position + // clamped to the (restored) list length. + this.selectedIndex = query ? 0 : Math.min(this.selectedIndex, Math.max(0, this.filteredModels.length - 1)); + this.updateList(); + } + updateList() { + this.listContainer.clear(); + const maxVisible = 10; + const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(maxVisible / 2), this.filteredModels.length - maxVisible)); + const endIndex = Math.min(startIndex + maxVisible, this.filteredModels.length); + // Show visible slice of filtered models + for (let i = startIndex; i < endIndex; i++) { + const item = this.filteredModels[i]; + if (!item) + continue; + const isSelected = i === this.selectedIndex; + const isCurrent = modelsAreEqual(this.currentModel, item.model); + let line = ""; + if (isSelected) { + const prefix = theme.fg("accent", "→ "); + const modelText = `${item.id}`; + const providerBadge = theme.fg("muted", `[${item.provider}]`); + const checkmark = isCurrent ? theme.fg("success", " ✓") : ""; + line = `${prefix + theme.fg("accent", modelText)} ${providerBadge}${checkmark}`; + } + else { + const modelText = ` ${item.id}`; + const providerBadge = theme.fg("muted", `[${item.provider}]`); + const checkmark = isCurrent ? theme.fg("success", " ✓") : ""; + line = `${modelText} ${providerBadge}${checkmark}`; + } + this.listContainer.addChild(new Text(line, 0, 0)); + } + // Add scroll indicator if needed + if (startIndex > 0 || endIndex < this.filteredModels.length) { + const scrollInfo = theme.fg("muted", ` (${this.selectedIndex + 1}/${this.filteredModels.length})`); + this.listContainer.addChild(new Text(scrollInfo, 0, 0)); + } + // Show error message or "no results" if empty + if (this.errorMessage) { + // Show error in red + const errorLines = this.errorMessage.split("\n"); + for (const line of errorLines) { + this.listContainer.addChild(new Text(theme.fg("error", line), 0, 0)); + } + } + else if (this.filteredModels.length === 0) { + this.listContainer.addChild(new Text(theme.fg("muted", " No matching models"), 0, 0)); + } + else { + const selected = this.filteredModels[this.selectedIndex]; + this.listContainer.addChild(new Spacer(1)); + this.listContainer.addChild(new Text(theme.fg("muted", ` Model Name: ${selected.model.name}`), 0, 0)); + } + if (this.refreshStatusMessage) { + this.listContainer.addChild(new Spacer(1)); + this.listContainer.addChild(new Text(theme.fg(this.refreshStatusSuccess ? "success" : "muted", ` ${this.refreshStatusMessage}`), 0, 0)); + } + } + handleInput(keyData) { + const kb = getKeybindings(); + if (kb.matches(keyData, "tui.input.tab")) { + if (this.scopedModelItems.length > 0) { + const nextScope = this.scope === "all" ? "scoped" : "all"; + this.setScope(nextScope); + if (this.scopeHintText) { + this.scopeHintText.setText(this.getScopeHintText()); + } + } + return; + } + // Up arrow - wrap to bottom when at top + if (kb.matches(keyData, "tui.select.up")) { + if (this.filteredModels.length === 0) + return; + this.selectedIndex = this.selectedIndex === 0 ? this.filteredModels.length - 1 : this.selectedIndex - 1; + this.updateList(); + } + // Down arrow - wrap to top when at bottom + else if (kb.matches(keyData, "tui.select.down")) { + if (this.filteredModels.length === 0) + return; + this.selectedIndex = this.selectedIndex === this.filteredModels.length - 1 ? 0 : this.selectedIndex + 1; + this.updateList(); + } + // Enter + else if (kb.matches(keyData, "tui.select.confirm")) { + const selectedModel = this.filteredModels[this.selectedIndex]; + if (selectedModel) { + this.handleSelect(selectedModel.model); + } + } + // Escape or Ctrl+C + else if (kb.matches(keyData, "tui.select.cancel")) { + this.close(); + this.onCancelCallback(); + } + // Pass everything else to search input + else { + this.searchInput.handleInput(keyData); + this.filterModels(this.searchInput.getValue()); + } + } + handleSelect(model) { + this.close(); + // Save as new default + this.settingsManager.setDefaultModelAndProvider(model.provider, model.id); + this.onSelectCallback(model); + } + getSearchInput() { + return this.searchInput; + } +} +//# sourceMappingURL=model-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/model-selector.js.map b/dist/modes/interactive/components/model-selector.js.map new file mode 100644 index 0000000..29e148d --- /dev/null +++ b/dist/modes/interactive/components/model-selector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"model-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/model-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,EACN,SAAS,EAET,WAAW,EACX,cAAc,EACd,KAAK,EACL,MAAM,EACN,IAAI,GAEJ,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAA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,CAAC,YAAY,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;YACxC,CAAC;QACF,CAAC;QACD,mBAAmB;aACd,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,EAAE,CAAC;YACnD,IAAI,CAAC,KAAK,EAAE,CAAC;YACb,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACzB,CAAC;QACD,uCAAuC;aAClC,CAAC;YACL,IAAI,CAAC,WAAW,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;YACtC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC;QAChD,CAAC;IAAA,CACD;IAEO,YAAY,CAAC,KAAiB,EAAQ;QAC7C,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,sBAAsB;QACtB,IAAI,CAAC,eAAe,CAAC,0BAA0B,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;QAC1E,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC;IAAA,CAC7B;IAED,cAAc,GAAU;QACvB,OAAO,IAAI,CAAC,WAAW,CAAC;IAAA,CACxB;CACD","sourcesContent":["import { type Model, modelsAreEqual } from \"@earendil-works/pi-ai\";\nimport {\n\tContainer,\n\ttype Focusable,\n\tfuzzyFilter,\n\tgetKeybindings,\n\tInput,\n\tSpacer,\n\tText,\n\ttype TUI,\n} from \"@earendil-works/pi-tui\";\nimport type { ModelRuntime } from \"../../../core/model-runtime.ts\";\nimport type { SettingsManager } from \"../../../core/settings-manager.ts\";\nimport { getModelSelectorSearchText } from \"../model-search.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint } from \"./keybinding-hints.ts\";\n\ninterface ModelItem {\n\tprovider: string;\n\tid: string;\n\tmodel: Model;\n}\n\ninterface ScopedModelItem {\n\tmodel: Model;\n\tthinkingLevel?: string;\n}\n\ntype ModelScope = \"all\" | \"scoped\";\n\n/**\n * Component that renders a model selector with search\n */\nexport class ModelSelectorComponent extends Container implements Focusable {\n\tprivate searchInput: Input;\n\n\t// Focusable implementation - propagate to searchInput for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.searchInput.focused = value;\n\t}\n\tprivate listContainer: Container;\n\tprivate allModels: ModelItem[] = [];\n\tprivate scopedModelItems: ModelItem[] = [];\n\tprivate activeModels: ModelItem[] = [];\n\tprivate filteredModels: ModelItem[] = [];\n\tprivate selectedIndex: number = 0;\n\tprivate currentModel?: Model;\n\tprivate settingsManager: SettingsManager;\n\tprivate modelRuntime: ModelRuntime;\n\tprivate onSelectCallback: (model: Model) => void;\n\tprivate onCancelCallback: () => void;\n\tprivate errorMessage?: string;\n\tprivate refreshStatusMessage = \"Refreshing model catalogs…\";\n\tprivate refreshStatusSuccess = false;\n\tprivate tui: TUI;\n\tprivate scopedModels: ReadonlyArray;\n\tprivate scope: ModelScope = \"all\";\n\tprivate scopeText?: Text;\n\tprivate scopeHintText?: Text;\n\tprivate readonly refreshAbortController = new AbortController();\n\tprivate refreshTimeout?: ReturnType;\n\tprivate closed = false;\n\n\tconstructor(\n\t\ttui: TUI,\n\t\tcurrentModel: Model | undefined,\n\t\tsettingsManager: SettingsManager,\n\t\tmodelRuntime: ModelRuntime,\n\t\tscopedModels: ReadonlyArray,\n\t\tonSelect: (model: Model) => void,\n\t\tonCancel: () => void,\n\t\tinitialSearchInput?: string,\n\t) {\n\t\tsuper();\n\n\t\tthis.tui = tui;\n\t\tthis.currentModel = currentModel;\n\t\tthis.settingsManager = settingsManager;\n\t\tthis.modelRuntime = modelRuntime;\n\t\tthis.scopedModels = scopedModels;\n\t\tthis.scope = scopedModels.length > 0 ? \"scoped\" : \"all\";\n\t\tthis.onSelectCallback = onSelect;\n\t\tthis.onCancelCallback = onCancel;\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add hint about model filtering\n\t\tif (scopedModels.length > 0) {\n\t\t\tthis.scopeText = new Text(this.getScopeText(), 0, 0);\n\t\t\tthis.addChild(this.scopeText);\n\t\t\tthis.scopeHintText = new Text(this.getScopeHintText(), 0, 0);\n\t\t\tthis.addChild(this.scopeHintText);\n\t\t} else {\n\t\t\tconst hintText = \"Only showing models from configured providers. Use /login to add providers.\";\n\t\t\tthis.addChild(new Text(theme.fg(\"warning\", hintText), 0, 0));\n\t\t}\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create search input\n\t\tthis.searchInput = new Input();\n\t\tif (initialSearchInput) {\n\t\t\tthis.searchInput.setValue(initialSearchInput);\n\t\t}\n\t\tthis.searchInput.onSubmit = () => {\n\t\t\t// Enter on search input selects the first filtered item\n\t\t\tif (this.filteredModels[this.selectedIndex]) {\n\t\t\t\tthis.handleSelect(this.filteredModels[this.selectedIndex].model);\n\t\t\t}\n\t\t};\n\t\tthis.addChild(this.searchInput);\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create list container\n\t\tthis.listContainer = new Container();\n\t\tthis.addChild(this.listContainer);\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Render the current snapshot immediately, then refresh in the background.\n\t\tthis.loadModelsFromSnapshot();\n\t\tif (initialSearchInput) this.filterModels(initialSearchInput);\n\t\telse this.updateList();\n\t\tthis.tui.requestRender();\n\t\tvoid this.refreshModels();\n\t}\n\n\tprivate loadModelsFromSnapshot(): void {\n\t\tconst models = this.modelRuntime.getAvailableSnapshot().map((model: Model) => ({\n\t\t\tprovider: model.provider,\n\t\t\tid: model.id,\n\t\t\tmodel,\n\t\t}));\n\t\tthis.allModels = this.sortModels(models);\n\t\tthis.scopedModels = this.scopedModels.map((scoped) => {\n\t\t\tconst refreshed = this.modelRuntime.getModel(scoped.model.provider, scoped.model.id);\n\t\t\treturn refreshed ? { ...scoped, model: refreshed } : scoped;\n\t\t});\n\t\tthis.scopedModelItems = this.scopedModels.map((scoped) => ({\n\t\t\tprovider: scoped.model.provider,\n\t\t\tid: scoped.model.id,\n\t\t\tmodel: scoped.model,\n\t\t}));\n\t\tthis.activeModels = this.scope === \"scoped\" ? this.scopedModelItems : this.allModels;\n\t\tthis.filteredModels = this.activeModels;\n\t\tconst currentIndex = this.filteredModels.findIndex((item) => modelsAreEqual(this.currentModel, item.model));\n\t\tthis.selectedIndex =\n\t\t\tcurrentIndex >= 0 ? currentIndex : Math.min(this.selectedIndex, Math.max(0, this.filteredModels.length - 1));\n\t}\n\n\tprivate async refreshModels(): Promise {\n\t\tconst timeoutMs = 15_000;\n\t\tlet timedOut = false;\n\t\tthis.refreshTimeout = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tthis.refreshAbortController.abort();\n\t\t}, timeoutMs);\n\t\ttry {\n\t\t\tconst result = await this.modelRuntime.refresh({ signal: this.refreshAbortController.signal });\n\t\t\tif (this.closed) return;\n\t\t\tthis.refreshStatusMessage = \"\";\n\t\t\tif (result.aborted && timedOut) {\n\t\t\t\tthis.errorMessage = \"Model refresh timed out; showing cached models.\";\n\t\t\t} else if (result.errors.size === 1) {\n\t\t\t\tthis.errorMessage = `Could not refresh ${result.errors.keys().next().value}; showing cached models.`;\n\t\t\t} else if (result.errors.size > 1) {\n\t\t\t\tthis.errorMessage = `Could not refresh ${result.errors.size} model catalogs; showing cached models.`;\n\t\t\t} else {\n\t\t\t\tthis.errorMessage = this.modelRuntime.getError();\n\t\t\t\tif (!this.errorMessage) {\n\t\t\t\t\tthis.refreshStatusMessage = \"Model catalogs refreshed.\";\n\t\t\t\t\tthis.refreshStatusSuccess = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.loadModelsFromSnapshot();\n\t\t\tthis.filterModels(this.searchInput.getValue());\n\t\t\tthis.tui.requestRender();\n\t\t} finally {\n\t\t\tif (this.refreshTimeout) clearTimeout(this.refreshTimeout);\n\t\t}\n\t}\n\n\tprivate close(): void {\n\t\tthis.closed = true;\n\t\tif (this.refreshTimeout) clearTimeout(this.refreshTimeout);\n\t\tthis.refreshAbortController.abort();\n\t}\n\n\tprivate sortModels(models: ModelItem[]): ModelItem[] {\n\t\tconst sorted = [...models];\n\t\t// Sort: current model first, then by provider\n\t\tsorted.sort((a, b) => {\n\t\t\tconst aIsCurrent = modelsAreEqual(this.currentModel, a.model);\n\t\t\tconst bIsCurrent = modelsAreEqual(this.currentModel, b.model);\n\t\t\tif (aIsCurrent && !bIsCurrent) return -1;\n\t\t\tif (!aIsCurrent && bIsCurrent) return 1;\n\t\t\treturn a.provider.localeCompare(b.provider);\n\t\t});\n\t\treturn sorted;\n\t}\n\n\tprivate getScopeText(): string {\n\t\tconst allText = this.scope === \"all\" ? theme.fg(\"accent\", \"all\") : theme.fg(\"muted\", \"all\");\n\t\tconst scopedText = this.scope === \"scoped\" ? theme.fg(\"accent\", \"scoped\") : theme.fg(\"muted\", \"scoped\");\n\t\treturn `${theme.fg(\"muted\", \"Scope: \")}${allText}${theme.fg(\"muted\", \" | \")}${scopedText}`;\n\t}\n\n\tprivate getScopeHintText(): string {\n\t\treturn keyHint(\"tui.input.tab\", \"scope\") + theme.fg(\"muted\", \" (all/scoped)\");\n\t}\n\n\tprivate setScope(scope: ModelScope): void {\n\t\tif (this.scope === scope) return;\n\t\tthis.scope = scope;\n\t\tthis.activeModels = this.scope === \"scoped\" ? this.scopedModelItems : this.allModels;\n\t\tconst currentIndex = this.activeModels.findIndex((item) => modelsAreEqual(this.currentModel, item.model));\n\t\tthis.selectedIndex = currentIndex >= 0 ? currentIndex : 0;\n\t\tthis.filterModels(this.searchInput.getValue());\n\t\tif (this.scopeText) {\n\t\t\tthis.scopeText.setText(this.getScopeText());\n\t\t}\n\t}\n\n\tprivate filterModels(query: string): void {\n\t\tthis.filteredModels = query\n\t\t\t? fuzzyFilter(this.activeModels, query, ({ id, provider, model }) =>\n\t\t\t\t\tgetModelSelectorSearchText({ id, provider, name: model.name }),\n\t\t\t\t)\n\t\t\t: this.activeModels;\n\t\t// When filtering by a query, move the selector to the top row so the best\n\t\t// match is highlighted. When the query is cleared, keep the current position\n\t\t// clamped to the (restored) list length.\n\t\tthis.selectedIndex = query ? 0 : Math.min(this.selectedIndex, Math.max(0, this.filteredModels.length - 1));\n\t\tthis.updateList();\n\t}\n\n\tprivate updateList(): void {\n\t\tthis.listContainer.clear();\n\n\t\tconst maxVisible = 10;\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(maxVisible / 2), this.filteredModels.length - maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + maxVisible, this.filteredModels.length);\n\n\t\t// Show visible slice of filtered models\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst item = this.filteredModels[i];\n\t\t\tif (!item) continue;\n\n\t\t\tconst isSelected = i === this.selectedIndex;\n\t\t\tconst isCurrent = modelsAreEqual(this.currentModel, item.model);\n\n\t\t\tlet line = \"\";\n\t\t\tif (isSelected) {\n\t\t\t\tconst prefix = theme.fg(\"accent\", \"→ \");\n\t\t\t\tconst modelText = `${item.id}`;\n\t\t\t\tconst providerBadge = theme.fg(\"muted\", `[${item.provider}]`);\n\t\t\t\tconst checkmark = isCurrent ? theme.fg(\"success\", \" ✓\") : \"\";\n\t\t\t\tline = `${prefix + theme.fg(\"accent\", modelText)} ${providerBadge}${checkmark}`;\n\t\t\t} else {\n\t\t\t\tconst modelText = ` ${item.id}`;\n\t\t\t\tconst providerBadge = theme.fg(\"muted\", `[${item.provider}]`);\n\t\t\t\tconst checkmark = isCurrent ? theme.fg(\"success\", \" ✓\") : \"\";\n\t\t\t\tline = `${modelText} ${providerBadge}${checkmark}`;\n\t\t\t}\n\n\t\t\tthis.listContainer.addChild(new Text(line, 0, 0));\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.filteredModels.length) {\n\t\t\tconst scrollInfo = theme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.filteredModels.length})`);\n\t\t\tthis.listContainer.addChild(new Text(scrollInfo, 0, 0));\n\t\t}\n\n\t\t// Show error message or \"no results\" if empty\n\t\tif (this.errorMessage) {\n\t\t\t// Show error in red\n\t\t\tconst errorLines = this.errorMessage.split(\"\\n\");\n\t\t\tfor (const line of errorLines) {\n\t\t\t\tthis.listContainer.addChild(new Text(theme.fg(\"error\", line), 0, 0));\n\t\t\t}\n\t\t} else if (this.filteredModels.length === 0) {\n\t\t\tthis.listContainer.addChild(new Text(theme.fg(\"muted\", \" No matching models\"), 0, 0));\n\t\t} else {\n\t\t\tconst selected = this.filteredModels[this.selectedIndex];\n\t\t\tthis.listContainer.addChild(new Spacer(1));\n\t\t\tthis.listContainer.addChild(new Text(theme.fg(\"muted\", ` Model Name: ${selected.model.name}`), 0, 0));\n\t\t}\n\t\tif (this.refreshStatusMessage) {\n\t\t\tthis.listContainer.addChild(new Spacer(1));\n\t\t\tthis.listContainer.addChild(\n\t\t\t\tnew Text(theme.fg(this.refreshStatusSuccess ? \"success\" : \"muted\", ` ${this.refreshStatusMessage}`), 0, 0),\n\t\t\t);\n\t\t}\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"tui.input.tab\")) {\n\t\t\tif (this.scopedModelItems.length > 0) {\n\t\t\t\tconst nextScope: ModelScope = this.scope === \"all\" ? \"scoped\" : \"all\";\n\t\t\t\tthis.setScope(nextScope);\n\t\t\t\tif (this.scopeHintText) {\n\t\t\t\t\tthis.scopeHintText.setText(this.getScopeHintText());\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t// Up arrow - wrap to bottom when at top\n\t\tif (kb.matches(keyData, \"tui.select.up\")) {\n\t\t\tif (this.filteredModels.length === 0) return;\n\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.filteredModels.length - 1 : this.selectedIndex - 1;\n\t\t\tthis.updateList();\n\t\t}\n\t\t// Down arrow - wrap to top when at bottom\n\t\telse if (kb.matches(keyData, \"tui.select.down\")) {\n\t\t\tif (this.filteredModels.length === 0) return;\n\t\t\tthis.selectedIndex = this.selectedIndex === this.filteredModels.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t\tthis.updateList();\n\t\t}\n\t\t// Enter\n\t\telse if (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\tconst selectedModel = this.filteredModels[this.selectedIndex];\n\t\t\tif (selectedModel) {\n\t\t\t\tthis.handleSelect(selectedModel.model);\n\t\t\t}\n\t\t}\n\t\t// Escape or Ctrl+C\n\t\telse if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.close();\n\t\t\tthis.onCancelCallback();\n\t\t}\n\t\t// Pass everything else to search input\n\t\telse {\n\t\t\tthis.searchInput.handleInput(keyData);\n\t\t\tthis.filterModels(this.searchInput.getValue());\n\t\t}\n\t}\n\n\tprivate handleSelect(model: Model): void {\n\t\tthis.close();\n\t\t// Save as new default\n\t\tthis.settingsManager.setDefaultModelAndProvider(model.provider, model.id);\n\t\tthis.onSelectCallback(model);\n\t}\n\n\tgetSearchInput(): Input {\n\t\treturn this.searchInput;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/oauth-selector.d.ts b/dist/modes/interactive/components/oauth-selector.d.ts new file mode 100644 index 0000000..9209afb --- /dev/null +++ b/dist/modes/interactive/components/oauth-selector.d.ts @@ -0,0 +1,33 @@ +import type { ApiKeyAuth, AuthCheck, OAuthAuth } from "@earendil-works/pi-ai"; +import { Container, type Focusable } from "@earendil-works/pi-tui"; +export type AuthSelectorProvider = { + id: string; + name: string; + authType: "oauth" | "api_key"; + method?: ApiKeyAuth | OAuthAuth; + status?: AuthCheck; +}; +export declare function formatAuthSelectorProviderType(authType: AuthSelectorProvider["authType"]): string; +/** + * Component that renders an auth provider selector + */ +export declare class OAuthSelectorComponent extends Container implements Focusable { + private searchInput; + private _focused; + get focused(): boolean; + set focused(value: boolean); + private listContainer; + private allProviders; + private filteredProviders; + private selectedIndex; + private mode; + private onSelectCallback; + private onCancelCallback; + private showAuthTypeLabels; + constructor(mode: "login" | "logout", providers: AuthSelectorProvider[], onSelect: (providerId: string, authType: AuthSelectorProvider["authType"]) => void, onCancel: () => void, initialSearchInput?: string); + private filterProviders; + private updateList; + private formatStatusIndicator; + handleInput(keyData: string): void; +} +//# sourceMappingURL=oauth-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/oauth-selector.d.ts.map b/dist/modes/interactive/components/oauth-selector.d.ts.map new file mode 100644 index 0000000..959115d --- /dev/null +++ b/dist/modes/interactive/components/oauth-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"oauth-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/oauth-selector.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAC9E,OAAO,EACN,SAAS,EACT,KAAK,SAAS,EAMd,MAAM,wBAAwB,CAAC;AAIhC,MAAM,MAAM,oBAAoB,GAAG;IAClC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,GAAG,SAAS,CAAC;IAC9B,MAAM,CAAC,EAAE,UAAU,GAAG,SAAS,CAAC;IAChC,MAAM,CAAC,EAAE,SAAS,CAAC;CACnB,CAAC;AAEF,wBAAgB,8BAA8B,CAAC,QAAQ,EAAE,oBAAoB,CAAC,UAAU,CAAC,GAAG,MAAM,CAEjG;AAED;;GAEG;AACH,qBAAa,sBAAuB,SAAQ,SAAU,YAAW,SAAS;IACzE,OAAO,CAAC,WAAW,CAAQ;IAG3B,OAAO,CAAC,QAAQ,CAAS;IACzB,IAAI,OAAO,IAAI,OAAO,CAErB;IACD,IAAI,OAAO,CAAC,KAAK,EAAE,OAAO,EAGzB;IAED,OAAO,CAAC,aAAa,CAAY;IACjC,OAAO,CAAC,YAAY,CAAyB;IAC7C,OAAO,CAAC,iBAAiB,CAAyB;IAClD,OAAO,CAAC,aAAa,CAAa;IAClC,OAAO,CAAC,IAAI,CAAqB;IACjC,OAAO,CAAC,gBAAgB,CAA2E;IACnG,OAAO,CAAC,gBAAgB,CAAa;IACrC,OAAO,CAAC,kBAAkB,CAAU;IAEpC,YACC,IAAI,EAAE,OAAO,GAAG,QAAQ,EACxB,SAAS,EAAE,oBAAoB,EAAE,EACjC,QAAQ,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,oBAAoB,CAAC,UAAU,CAAC,KAAK,IAAI,EAClF,QAAQ,EAAE,MAAM,IAAI,EACpB,kBAAkB,CAAC,EAAE,MAAM,EA4C3B;IAED,OAAO,CAAC,eAAe;IAYvB,OAAO,CAAC,UAAU;IAkDlB,OAAO,CAAC,qBAAqB;IAmB7B,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CA8BjC;CACD","sourcesContent":["import type { ApiKeyAuth, AuthCheck, OAuthAuth } from \"@earendil-works/pi-ai\";\nimport {\n\tContainer,\n\ttype Focusable,\n\tfuzzyFilter,\n\tgetKeybindings,\n\tInput,\n\tSpacer,\n\tTruncatedText,\n} from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\n\nexport type AuthSelectorProvider = {\n\tid: string;\n\tname: string;\n\tauthType: \"oauth\" | \"api_key\";\n\tmethod?: ApiKeyAuth | OAuthAuth;\n\tstatus?: AuthCheck;\n};\n\nexport function formatAuthSelectorProviderType(authType: AuthSelectorProvider[\"authType\"]): string {\n\treturn authType === \"oauth\" ? \"subscription\" : \"API key\";\n}\n\n/**\n * Component that renders an auth provider selector\n */\nexport class OAuthSelectorComponent extends Container implements Focusable {\n\tprivate searchInput: Input;\n\n\t// Focusable implementation - propagate to search input for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.searchInput.focused = value;\n\t}\n\n\tprivate listContainer: Container;\n\tprivate allProviders: AuthSelectorProvider[];\n\tprivate filteredProviders: AuthSelectorProvider[];\n\tprivate selectedIndex: number = 0;\n\tprivate mode: \"login\" | \"logout\";\n\tprivate onSelectCallback: (providerId: string, authType: AuthSelectorProvider[\"authType\"]) => void;\n\tprivate onCancelCallback: () => void;\n\tprivate showAuthTypeLabels: boolean;\n\n\tconstructor(\n\t\tmode: \"login\" | \"logout\",\n\t\tproviders: AuthSelectorProvider[],\n\t\tonSelect: (providerId: string, authType: AuthSelectorProvider[\"authType\"]) => void,\n\t\tonCancel: () => void,\n\t\tinitialSearchInput?: string,\n\t) {\n\t\tsuper();\n\n\t\tthis.mode = mode;\n\t\tthis.allProviders = providers;\n\t\tthis.filteredProviders = providers;\n\t\tthis.showAuthTypeLabels = new Set(providers.map((provider) => provider.authType)).size > 1;\n\t\tthis.onSelectCallback = onSelect;\n\t\tthis.onCancelCallback = onCancel;\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add title\n\t\tconst title = mode === \"login\" ? \"Select provider to configure:\" : \"Select provider to logout:\";\n\t\tthis.addChild(new TruncatedText(theme.fg(\"accent\", theme.bold(title)), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\n\t\tthis.searchInput = new Input();\n\t\tif (initialSearchInput) {\n\t\t\tthis.searchInput.setValue(initialSearchInput);\n\t\t}\n\t\tthis.searchInput.onSubmit = () => {\n\t\t\tconst selectedProvider = this.filteredProviders[this.selectedIndex];\n\t\t\tif (selectedProvider) {\n\t\t\t\tthis.onSelectCallback(selectedProvider.id, selectedProvider.authType);\n\t\t\t}\n\t\t};\n\t\tthis.addChild(this.searchInput);\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create list container\n\t\tthis.listContainer = new Container();\n\t\tthis.addChild(this.listContainer);\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Initial render\n\t\tthis.filterProviders(initialSearchInput ?? \"\");\n\t}\n\n\tprivate filterProviders(query: string): void {\n\t\tthis.filteredProviders = query\n\t\t\t? fuzzyFilter(\n\t\t\t\t\tthis.allProviders,\n\t\t\t\t\tquery,\n\t\t\t\t\t(provider) => `${provider.name} ${provider.id} ${provider.authType} ${provider.method?.name ?? \"\"}`,\n\t\t\t\t)\n\t\t\t: this.allProviders;\n\t\tthis.selectedIndex = Math.max(0, Math.min(this.selectedIndex, Math.max(0, this.filteredProviders.length - 1)));\n\t\tthis.updateList();\n\t}\n\n\tprivate updateList(): void {\n\t\tthis.listContainer.clear();\n\n\t\tconst maxVisible = 8;\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(maxVisible / 2), this.filteredProviders.length - maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + maxVisible, this.filteredProviders.length);\n\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst provider = this.filteredProviders[i];\n\t\t\tif (!provider) continue;\n\n\t\t\tconst isSelected = i === this.selectedIndex;\n\n\t\t\tconst statusIndicator = this.formatStatusIndicator(provider);\n\t\t\tconst authTypeLabel = this.showAuthTypeLabels\n\t\t\t\t? theme.fg(\"muted\", ` [${formatAuthSelectorProviderType(provider.authType)}]`)\n\t\t\t\t: \"\";\n\t\t\tlet line = \"\";\n\t\t\tif (isSelected) {\n\t\t\t\tconst prefix = theme.fg(\"accent\", \"→ \");\n\t\t\t\tconst text = theme.fg(\"accent\", provider.name);\n\t\t\t\tline = prefix + text + authTypeLabel + statusIndicator;\n\t\t\t} else {\n\t\t\t\tconst text = ` ${theme.fg(\"text\", provider.name)}`;\n\t\t\t\tline = text + authTypeLabel + statusIndicator;\n\t\t\t}\n\n\t\t\tthis.listContainer.addChild(new TruncatedText(line, 1, 0));\n\t\t}\n\n\t\tif (startIndex > 0 || endIndex < this.filteredProviders.length) {\n\t\t\tconst scrollInfo = theme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.filteredProviders.length})`);\n\t\t\tthis.listContainer.addChild(new TruncatedText(scrollInfo, 1, 0));\n\t\t}\n\n\t\t// Show \"no providers\" if empty\n\t\tif (this.filteredProviders.length === 0) {\n\t\t\tconst message =\n\t\t\t\tthis.allProviders.length === 0\n\t\t\t\t\t? this.mode === \"login\"\n\t\t\t\t\t\t? \"No providers available\"\n\t\t\t\t\t\t: \"No providers logged in. Use /login first.\"\n\t\t\t\t\t: \"No matching providers\";\n\t\t\tthis.listContainer.addChild(new TruncatedText(theme.fg(\"muted\", ` ${message}`), 1, 0));\n\t\t}\n\t}\n\n\tprivate formatStatusIndicator(provider: AuthSelectorProvider): string {\n\t\tif (!provider.status) return theme.fg(\"muted\", \" • unconfigured\");\n\t\tif (provider.status.type !== provider.authType) {\n\t\t\tconst label = provider.status.type === \"oauth\" ? \"subscription configured\" : \"API key configured\";\n\t\t\treturn theme.fg(\"muted\", \" • \") + theme.fg(\"warning\", label);\n\t\t}\n\t\tif (\n\t\t\t!provider.status.source ||\n\t\t\tprovider.status.source === \"OAuth\" ||\n\t\t\tprovider.status.source === \"stored credential\"\n\t\t) {\n\t\t\treturn theme.fg(\"success\", \" ✓ configured\");\n\t\t}\n\t\tconst source = /^[A-Z][A-Z0-9_]*(?:, [A-Z][A-Z0-9_]*)*$/.test(provider.status.source)\n\t\t\t? `env: ${provider.status.source}`\n\t\t\t: provider.status.source;\n\t\treturn theme.fg(\"success\", ` ✓ ${source}`);\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\t// Up arrow\n\t\tif (kb.matches(keyData, \"tui.select.up\")) {\n\t\t\tif (this.filteredProviders.length === 0) return;\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - 1);\n\t\t\tthis.updateList();\n\t\t}\n\t\t// Down arrow\n\t\telse if (kb.matches(keyData, \"tui.select.down\")) {\n\t\t\tif (this.filteredProviders.length === 0) return;\n\t\t\tthis.selectedIndex = Math.min(this.filteredProviders.length - 1, this.selectedIndex + 1);\n\t\t\tthis.updateList();\n\t\t}\n\t\t// Enter\n\t\telse if (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\tconst selectedProvider = this.filteredProviders[this.selectedIndex];\n\t\t\tif (selectedProvider) {\n\t\t\t\tthis.onSelectCallback(selectedProvider.id, selectedProvider.authType);\n\t\t\t}\n\t\t}\n\t\t// Escape or Ctrl+C\n\t\telse if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.onCancelCallback();\n\t\t}\n\t\t// Pass everything else to search input\n\t\telse {\n\t\t\tthis.searchInput.handleInput(keyData);\n\t\t\tthis.filterProviders(this.searchInput.getValue());\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/oauth-selector.js b/dist/modes/interactive/components/oauth-selector.js new file mode 100644 index 0000000..a65a8cd --- /dev/null +++ b/dist/modes/interactive/components/oauth-selector.js @@ -0,0 +1,163 @@ +import { Container, fuzzyFilter, getKeybindings, Input, Spacer, TruncatedText, } from "@earendil-works/pi-tui"; +import { theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +export function formatAuthSelectorProviderType(authType) { + return authType === "oauth" ? "subscription" : "API key"; +} +/** + * Component that renders an auth provider selector + */ +export class OAuthSelectorComponent extends Container { + searchInput; + // Focusable implementation - propagate to search input for IME cursor positioning + _focused = false; + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + this.searchInput.focused = value; + } + listContainer; + allProviders; + filteredProviders; + selectedIndex = 0; + mode; + onSelectCallback; + onCancelCallback; + showAuthTypeLabels; + constructor(mode, providers, onSelect, onCancel, initialSearchInput) { + super(); + this.mode = mode; + this.allProviders = providers; + this.filteredProviders = providers; + this.showAuthTypeLabels = new Set(providers.map((provider) => provider.authType)).size > 1; + this.onSelectCallback = onSelect; + this.onCancelCallback = onCancel; + // Add top border + this.addChild(new DynamicBorder()); + this.addChild(new Spacer(1)); + // Add title + const title = mode === "login" ? "Select provider to configure:" : "Select provider to logout:"; + this.addChild(new TruncatedText(theme.fg("accent", theme.bold(title)), 1, 0)); + this.addChild(new Spacer(1)); + this.searchInput = new Input(); + if (initialSearchInput) { + this.searchInput.setValue(initialSearchInput); + } + this.searchInput.onSubmit = () => { + const selectedProvider = this.filteredProviders[this.selectedIndex]; + if (selectedProvider) { + this.onSelectCallback(selectedProvider.id, selectedProvider.authType); + } + }; + this.addChild(this.searchInput); + this.addChild(new Spacer(1)); + // Create list container + this.listContainer = new Container(); + this.addChild(this.listContainer); + this.addChild(new Spacer(1)); + // Add bottom border + this.addChild(new DynamicBorder()); + // Initial render + this.filterProviders(initialSearchInput ?? ""); + } + filterProviders(query) { + this.filteredProviders = query + ? fuzzyFilter(this.allProviders, query, (provider) => `${provider.name} ${provider.id} ${provider.authType} ${provider.method?.name ?? ""}`) + : this.allProviders; + this.selectedIndex = Math.max(0, Math.min(this.selectedIndex, Math.max(0, this.filteredProviders.length - 1))); + this.updateList(); + } + updateList() { + this.listContainer.clear(); + const maxVisible = 8; + const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(maxVisible / 2), this.filteredProviders.length - maxVisible)); + const endIndex = Math.min(startIndex + maxVisible, this.filteredProviders.length); + for (let i = startIndex; i < endIndex; i++) { + const provider = this.filteredProviders[i]; + if (!provider) + continue; + const isSelected = i === this.selectedIndex; + const statusIndicator = this.formatStatusIndicator(provider); + const authTypeLabel = this.showAuthTypeLabels + ? theme.fg("muted", ` [${formatAuthSelectorProviderType(provider.authType)}]`) + : ""; + let line = ""; + if (isSelected) { + const prefix = theme.fg("accent", "→ "); + const text = theme.fg("accent", provider.name); + line = prefix + text + authTypeLabel + statusIndicator; + } + else { + const text = ` ${theme.fg("text", provider.name)}`; + line = text + authTypeLabel + statusIndicator; + } + this.listContainer.addChild(new TruncatedText(line, 1, 0)); + } + if (startIndex > 0 || endIndex < this.filteredProviders.length) { + const scrollInfo = theme.fg("muted", ` (${this.selectedIndex + 1}/${this.filteredProviders.length})`); + this.listContainer.addChild(new TruncatedText(scrollInfo, 1, 0)); + } + // Show "no providers" if empty + if (this.filteredProviders.length === 0) { + const message = this.allProviders.length === 0 + ? this.mode === "login" + ? "No providers available" + : "No providers logged in. Use /login first." + : "No matching providers"; + this.listContainer.addChild(new TruncatedText(theme.fg("muted", ` ${message}`), 1, 0)); + } + } + formatStatusIndicator(provider) { + if (!provider.status) + return theme.fg("muted", " • unconfigured"); + if (provider.status.type !== provider.authType) { + const label = provider.status.type === "oauth" ? "subscription configured" : "API key configured"; + return theme.fg("muted", " • ") + theme.fg("warning", label); + } + if (!provider.status.source || + provider.status.source === "OAuth" || + provider.status.source === "stored credential") { + return theme.fg("success", " ✓ configured"); + } + const source = /^[A-Z][A-Z0-9_]*(?:, [A-Z][A-Z0-9_]*)*$/.test(provider.status.source) + ? `env: ${provider.status.source}` + : provider.status.source; + return theme.fg("success", ` ✓ ${source}`); + } + handleInput(keyData) { + const kb = getKeybindings(); + // Up arrow + if (kb.matches(keyData, "tui.select.up")) { + if (this.filteredProviders.length === 0) + return; + this.selectedIndex = Math.max(0, this.selectedIndex - 1); + this.updateList(); + } + // Down arrow + else if (kb.matches(keyData, "tui.select.down")) { + if (this.filteredProviders.length === 0) + return; + this.selectedIndex = Math.min(this.filteredProviders.length - 1, this.selectedIndex + 1); + this.updateList(); + } + // Enter + else if (kb.matches(keyData, "tui.select.confirm")) { + const selectedProvider = this.filteredProviders[this.selectedIndex]; + if (selectedProvider) { + this.onSelectCallback(selectedProvider.id, selectedProvider.authType); + } + } + // Escape or Ctrl+C + else if (kb.matches(keyData, "tui.select.cancel")) { + this.onCancelCallback(); + } + // Pass everything else to search input + else { + this.searchInput.handleInput(keyData); + this.filterProviders(this.searchInput.getValue()); + } + } +} +//# sourceMappingURL=oauth-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/oauth-selector.js.map b/dist/modes/interactive/components/oauth-selector.js.map new file mode 100644 index 0000000..5050316 --- /dev/null +++ b/dist/modes/interactive/components/oauth-selector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"oauth-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/oauth-selector.ts"],"names":[],"mappings":"AACA,OAAO,EACN,SAAS,EAET,WAAW,EACX,cAAc,EACd,KAAK,EACL,MAAM,EACN,aAAa,GACb,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAUpD,MAAM,UAAU,8BAA8B,CAAC,QAA0C,EAAU;IAClG,OAAO,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CACzD;AAED;;GAEG;AACH,MAAM,OAAO,sBAAuB,SAAQ,SAAS;IAC5C,WAAW,CAAQ;IAE3B,kFAAkF;IAC1E,QAAQ,GAAG,KAAK,CAAC;IACzB,IAAI,OAAO,GAAY;QACtB,OAAO,IAAI,CAAC,QAAQ,CAAC;IAAA,CACrB;IACD,IAAI,OAAO,CAAC,KAAc,EAAE;QAC3B,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;QACtB,IAAI,CAAC,WAAW,CAAC,OAAO,GAAG,KAAK,CAAC;IAAA,CACjC;IAEO,aAAa,CAAY;IACzB,YAAY,CAAyB;IACrC,iBAAiB,CAAyB;IAC1C,aAAa,GAAW,CAAC,CAAC;IAC1B,IAAI,CAAqB;IACzB,gBAAgB,CAA2E;IAC3F,gBAAgB,CAAa;IAC7B,kBAAkB,CAAU;IAEpC,YACC,IAAwB,EACxB,SAAiC,EACjC,QAAkF,EAClF,QAAoB,EACpB,kBAA2B,EAC1B;QACD,KAAK,EAAE,CAAC;QAER,IAAI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tContainer,\n\ttype Focusable,\n\tfuzzyFilter,\n\tgetKeybindings,\n\tInput,\n\tSpacer,\n\tTruncatedText,\n} from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\n\nexport type AuthSelectorProvider = {\n\tid: string;\n\tname: string;\n\tauthType: \"oauth\" | \"api_key\";\n\tmethod?: ApiKeyAuth | OAuthAuth;\n\tstatus?: AuthCheck;\n};\n\nexport function formatAuthSelectorProviderType(authType: AuthSelectorProvider[\"authType\"]): string {\n\treturn authType === \"oauth\" ? \"subscription\" : \"API key\";\n}\n\n/**\n * Component that renders an auth provider selector\n */\nexport class OAuthSelectorComponent extends Container implements Focusable {\n\tprivate searchInput: Input;\n\n\t// Focusable implementation - propagate to search input for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.searchInput.focused = value;\n\t}\n\n\tprivate listContainer: Container;\n\tprivate allProviders: AuthSelectorProvider[];\n\tprivate filteredProviders: AuthSelectorProvider[];\n\tprivate selectedIndex: number = 0;\n\tprivate mode: \"login\" | \"logout\";\n\tprivate onSelectCallback: (providerId: string, authType: AuthSelectorProvider[\"authType\"]) => void;\n\tprivate onCancelCallback: () => void;\n\tprivate showAuthTypeLabels: boolean;\n\n\tconstructor(\n\t\tmode: \"login\" | \"logout\",\n\t\tproviders: AuthSelectorProvider[],\n\t\tonSelect: (providerId: string, authType: AuthSelectorProvider[\"authType\"]) => void,\n\t\tonCancel: () => void,\n\t\tinitialSearchInput?: string,\n\t) {\n\t\tsuper();\n\n\t\tthis.mode = mode;\n\t\tthis.allProviders = providers;\n\t\tthis.filteredProviders = providers;\n\t\tthis.showAuthTypeLabels = new Set(providers.map((provider) => provider.authType)).size > 1;\n\t\tthis.onSelectCallback = onSelect;\n\t\tthis.onCancelCallback = onCancel;\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add title\n\t\tconst title = mode === \"login\" ? \"Select provider to configure:\" : \"Select provider to logout:\";\n\t\tthis.addChild(new TruncatedText(theme.fg(\"accent\", theme.bold(title)), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\n\t\tthis.searchInput = new Input();\n\t\tif (initialSearchInput) {\n\t\t\tthis.searchInput.setValue(initialSearchInput);\n\t\t}\n\t\tthis.searchInput.onSubmit = () => {\n\t\t\tconst selectedProvider = this.filteredProviders[this.selectedIndex];\n\t\t\tif (selectedProvider) {\n\t\t\t\tthis.onSelectCallback(selectedProvider.id, selectedProvider.authType);\n\t\t\t}\n\t\t};\n\t\tthis.addChild(this.searchInput);\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create list container\n\t\tthis.listContainer = new Container();\n\t\tthis.addChild(this.listContainer);\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Initial render\n\t\tthis.filterProviders(initialSearchInput ?? \"\");\n\t}\n\n\tprivate filterProviders(query: string): void {\n\t\tthis.filteredProviders = query\n\t\t\t? fuzzyFilter(\n\t\t\t\t\tthis.allProviders,\n\t\t\t\t\tquery,\n\t\t\t\t\t(provider) => `${provider.name} ${provider.id} ${provider.authType} ${provider.method?.name ?? \"\"}`,\n\t\t\t\t)\n\t\t\t: this.allProviders;\n\t\tthis.selectedIndex = Math.max(0, Math.min(this.selectedIndex, Math.max(0, this.filteredProviders.length - 1)));\n\t\tthis.updateList();\n\t}\n\n\tprivate updateList(): void {\n\t\tthis.listContainer.clear();\n\n\t\tconst maxVisible = 8;\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(maxVisible / 2), this.filteredProviders.length - maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + maxVisible, this.filteredProviders.length);\n\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst provider = this.filteredProviders[i];\n\t\t\tif (!provider) continue;\n\n\t\t\tconst isSelected = i === this.selectedIndex;\n\n\t\t\tconst statusIndicator = this.formatStatusIndicator(provider);\n\t\t\tconst authTypeLabel = this.showAuthTypeLabels\n\t\t\t\t? theme.fg(\"muted\", ` [${formatAuthSelectorProviderType(provider.authType)}]`)\n\t\t\t\t: \"\";\n\t\t\tlet line = \"\";\n\t\t\tif (isSelected) {\n\t\t\t\tconst prefix = theme.fg(\"accent\", \"→ \");\n\t\t\t\tconst text = theme.fg(\"accent\", provider.name);\n\t\t\t\tline = prefix + text + authTypeLabel + statusIndicator;\n\t\t\t} else {\n\t\t\t\tconst text = ` ${theme.fg(\"text\", provider.name)}`;\n\t\t\t\tline = text + authTypeLabel + statusIndicator;\n\t\t\t}\n\n\t\t\tthis.listContainer.addChild(new TruncatedText(line, 1, 0));\n\t\t}\n\n\t\tif (startIndex > 0 || endIndex < this.filteredProviders.length) {\n\t\t\tconst scrollInfo = theme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.filteredProviders.length})`);\n\t\t\tthis.listContainer.addChild(new TruncatedText(scrollInfo, 1, 0));\n\t\t}\n\n\t\t// Show \"no providers\" if empty\n\t\tif (this.filteredProviders.length === 0) {\n\t\t\tconst message =\n\t\t\t\tthis.allProviders.length === 0\n\t\t\t\t\t? this.mode === \"login\"\n\t\t\t\t\t\t? \"No providers available\"\n\t\t\t\t\t\t: \"No providers logged in. Use /login first.\"\n\t\t\t\t\t: \"No matching providers\";\n\t\t\tthis.listContainer.addChild(new TruncatedText(theme.fg(\"muted\", ` ${message}`), 1, 0));\n\t\t}\n\t}\n\n\tprivate formatStatusIndicator(provider: AuthSelectorProvider): string {\n\t\tif (!provider.status) return theme.fg(\"muted\", \" • unconfigured\");\n\t\tif (provider.status.type !== provider.authType) {\n\t\t\tconst label = provider.status.type === \"oauth\" ? \"subscription configured\" : \"API key configured\";\n\t\t\treturn theme.fg(\"muted\", \" • \") + theme.fg(\"warning\", label);\n\t\t}\n\t\tif (\n\t\t\t!provider.status.source ||\n\t\t\tprovider.status.source === \"OAuth\" ||\n\t\t\tprovider.status.source === \"stored credential\"\n\t\t) {\n\t\t\treturn theme.fg(\"success\", \" ✓ configured\");\n\t\t}\n\t\tconst source = /^[A-Z][A-Z0-9_]*(?:, [A-Z][A-Z0-9_]*)*$/.test(provider.status.source)\n\t\t\t? `env: ${provider.status.source}`\n\t\t\t: provider.status.source;\n\t\treturn theme.fg(\"success\", ` ✓ ${source}`);\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\t// Up arrow\n\t\tif (kb.matches(keyData, \"tui.select.up\")) {\n\t\t\tif (this.filteredProviders.length === 0) return;\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - 1);\n\t\t\tthis.updateList();\n\t\t}\n\t\t// Down arrow\n\t\telse if (kb.matches(keyData, \"tui.select.down\")) {\n\t\t\tif (this.filteredProviders.length === 0) return;\n\t\t\tthis.selectedIndex = Math.min(this.filteredProviders.length - 1, this.selectedIndex + 1);\n\t\t\tthis.updateList();\n\t\t}\n\t\t// Enter\n\t\telse if (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\tconst selectedProvider = this.filteredProviders[this.selectedIndex];\n\t\t\tif (selectedProvider) {\n\t\t\t\tthis.onSelectCallback(selectedProvider.id, selectedProvider.authType);\n\t\t\t}\n\t\t}\n\t\t// Escape or Ctrl+C\n\t\telse if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.onCancelCallback();\n\t\t}\n\t\t// Pass everything else to search input\n\t\telse {\n\t\t\tthis.searchInput.handleInput(keyData);\n\t\t\tthis.filterProviders(this.searchInput.getValue());\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/scoped-models-selector.d.ts b/dist/modes/interactive/components/scoped-models-selector.d.ts new file mode 100644 index 0000000..f86cc06 --- /dev/null +++ b/dist/modes/interactive/components/scoped-models-selector.d.ts @@ -0,0 +1,42 @@ +import type { Model } from "@earendil-works/pi-ai"; +import { Container, type Focusable, Input } from "@earendil-works/pi-tui"; +export interface ModelsConfig { + allModels: Model[]; + enabledModelIds: string[] | null; +} +export interface ModelsCallbacks { + /** Called whenever the enabled model set or order changes (session-only, no persist) */ + onChange: (enabledModelIds: string[] | null) => void | Promise; + /** Called when user wants to persist current selection to settings */ + onPersist: (enabledModelIds: string[] | null) => void | Promise; + onCancel: () => void; +} +/** + * Component for enabling/disabling models for Ctrl+P cycling. + * Changes are session-only until explicitly persisted with Ctrl+S. + */ +export declare class ScopedModelsSelectorComponent extends Container implements Focusable { + private modelsById; + private allIds; + private enabledIds; + private filteredItems; + private selectedIndex; + private searchInput; + private _focused; + get focused(): boolean; + set focused(value: boolean); + private listContainer; + private footerText; + private callbacks; + private maxVisible; + private isDirty; + constructor(config: ModelsConfig, callbacks: ModelsCallbacks); + private buildItems; + private getFooterText; + private refresh; + private notifyChange; + private updateList; + handleInput(data: string): void; + getSearchInput(): Input; +} +//# sourceMappingURL=scoped-models-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/scoped-models-selector.d.ts.map b/dist/modes/interactive/components/scoped-models-selector.d.ts.map new file mode 100644 index 0000000..78d8831 --- /dev/null +++ b/dist/modes/interactive/components/scoped-models-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"scoped-models-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/scoped-models-selector.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EACN,SAAS,EACT,KAAK,SAAS,EAGd,KAAK,EAKL,MAAM,wBAAwB,CAAC;AA8DhC,MAAM,WAAW,YAAY;IAC5B,SAAS,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;IACxB,eAAe,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;CACjC;AAED,MAAM,WAAW,eAAe;IAC/B,wFAAwF;IACxF,QAAQ,EAAE,CAAC,eAAe,EAAE,MAAM,EAAE,GAAG,IAAI,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACrE,sEAAsE;IACtE,SAAS,EAAE,CAAC,eAAe,EAAE,MAAM,EAAE,GAAG,IAAI,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACtE,QAAQ,EAAE,MAAM,IAAI,CAAC;CACrB;AAED;;;GAGG;AACH,qBAAa,6BAA8B,SAAQ,SAAU,YAAW,SAAS;IAChF,OAAO,CAAC,UAAU,CAAsC;IACxD,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,UAAU,CAAoB;IACtC,OAAO,CAAC,aAAa,CAAmB;IACxC,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,WAAW,CAAQ;IAG3B,OAAO,CAAC,QAAQ,CAAS;IACzB,IAAI,OAAO,IAAI,OAAO,CAErB;IACD,IAAI,OAAO,CAAC,KAAK,EAAE,OAAO,EAGzB;IACD,OAAO,CAAC,aAAa,CAAY;IACjC,OAAO,CAAC,UAAU,CAAO;IACzB,OAAO,CAAC,SAAS,CAAkB;IACnC,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,OAAO,CAAS;IAExB,YAAY,MAAM,EAAE,YAAY,EAAE,SAAS,EAAE,eAAe,EAsC3D;IAED,OAAO,CAAC,UAAU;IAQlB,OAAO,CAAC,aAAa;IAqBrB,OAAO,CAAC,OAAO;IAef,OAAO,CAAC,YAAY;IAIpB,OAAO,CAAC,UAAU;IAoDlB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAoH9B;IAED,cAAc,IAAI,KAAK,CAEtB;CACD","sourcesContent":["import type { Model } from \"@earendil-works/pi-ai\";\nimport {\n\tContainer,\n\ttype Focusable,\n\tfuzzyFilter,\n\tgetKeybindings,\n\tInput,\n\tKey,\n\tmatchesKey,\n\tSpacer,\n\tText,\n} from \"@earendil-works/pi-tui\";\nimport { getModelSearchText } from \"../model-search.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyText } from \"./keybinding-hints.ts\";\n\n// EnabledIds: null = all enabled (no filter), string[] = explicit ordered list\ntype EnabledIds = string[] | null;\n\nfunction isEnabled(enabledIds: EnabledIds, id: string): boolean {\n\treturn enabledIds === null || enabledIds.includes(id);\n}\n\nfunction toggle(enabledIds: EnabledIds, id: string): EnabledIds {\n\tif (enabledIds === null) return [id]; // First toggle: start with only this one\n\tconst index = enabledIds.indexOf(id);\n\tif (index >= 0) return [...enabledIds.slice(0, index), ...enabledIds.slice(index + 1)];\n\treturn [...enabledIds, id];\n}\n\nfunction enableAll(enabledIds: EnabledIds, allIds: string[], targetIds?: string[]): EnabledIds {\n\tif (enabledIds === null) return null; // Already all enabled\n\tconst targets = targetIds ?? allIds;\n\tconst result = [...enabledIds];\n\tfor (const id of targets) {\n\t\tif (!result.includes(id)) result.push(id);\n\t}\n\treturn result.length === allIds.length && result.every((id) => allIds.includes(id)) ? null : result;\n}\n\nfunction clearAll(enabledIds: EnabledIds, allIds: string[], targetIds?: string[]): EnabledIds {\n\tif (enabledIds === null) {\n\t\treturn targetIds ? allIds.filter((id) => !targetIds.includes(id)) : [];\n\t}\n\tconst targets = new Set(targetIds ?? enabledIds);\n\treturn enabledIds.filter((id) => !targets.has(id));\n}\n\nfunction move(enabledIds: EnabledIds, id: string, delta: number): EnabledIds {\n\tif (enabledIds === null) return null;\n\tconst list = [...enabledIds];\n\tconst index = list.indexOf(id);\n\tif (index < 0) return list;\n\tconst newIndex = index + delta;\n\tif (newIndex < 0 || newIndex >= list.length) return list;\n\tconst result = [...list];\n\t[result[index], result[newIndex]] = [result[newIndex], result[index]];\n\treturn result;\n}\n\nfunction getSortedIds(enabledIds: EnabledIds, allIds: string[]): string[] {\n\tif (enabledIds === null) return allIds;\n\tconst enabledSet = new Set(enabledIds);\n\treturn [...enabledIds, ...allIds.filter((id) => !enabledSet.has(id))];\n}\n\ninterface ModelItem {\n\tfullId: string;\n\tmodel: Model | undefined;\n\tenabled: boolean;\n}\n\nexport interface ModelsConfig {\n\tallModels: Model[];\n\tenabledModelIds: string[] | null;\n}\n\nexport interface ModelsCallbacks {\n\t/** Called whenever the enabled model set or order changes (session-only, no persist) */\n\tonChange: (enabledModelIds: string[] | null) => void | Promise;\n\t/** Called when user wants to persist current selection to settings */\n\tonPersist: (enabledModelIds: string[] | null) => void | Promise;\n\tonCancel: () => void;\n}\n\n/**\n * Component for enabling/disabling models for Ctrl+P cycling.\n * Changes are session-only until explicitly persisted with Ctrl+S.\n */\nexport class ScopedModelsSelectorComponent extends Container implements Focusable {\n\tprivate modelsById: Map> = new Map();\n\tprivate allIds: string[] = [];\n\tprivate enabledIds: EnabledIds = null;\n\tprivate filteredItems: ModelItem[] = [];\n\tprivate selectedIndex = 0;\n\tprivate searchInput: Input;\n\n\t// Focusable implementation - propagate to searchInput for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.searchInput.focused = value;\n\t}\n\tprivate listContainer: Container;\n\tprivate footerText: Text;\n\tprivate callbacks: ModelsCallbacks;\n\tprivate maxVisible = 8;\n\tprivate isDirty = false;\n\n\tconstructor(config: ModelsConfig, callbacks: ModelsCallbacks) {\n\t\tsuper();\n\t\tthis.callbacks = callbacks;\n\n\t\tfor (const model of config.allModels) {\n\t\t\tconst fullId = `${model.provider}/${model.id}`;\n\t\t\tthis.modelsById.set(fullId, model);\n\t\t\tthis.allIds.push(fullId);\n\t\t}\n\n\t\tthis.enabledIds = config.enabledModelIds === null ? null : [...config.enabledModelIds];\n\t\tthis.filteredItems = this.buildItems();\n\n\t\t// Header\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.fg(\"accent\", theme.bold(\"Model Configuration\")), 0, 0));\n\t\tthis.addChild(\n\t\t\tnew Text(theme.fg(\"muted\", `Session-only. ${keyText(\"app.models.save\")} to save to settings.`), 0, 0),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Search input\n\t\tthis.searchInput = new Input();\n\t\tthis.addChild(this.searchInput);\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// List container\n\t\tthis.listContainer = new Container();\n\t\tthis.addChild(this.listContainer);\n\n\t\t// Footer hint\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.footerText = new Text(this.getFooterText(), 0, 0);\n\t\tthis.addChild(this.footerText);\n\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.updateList();\n\t}\n\n\tprivate buildItems(): ModelItem[] {\n\t\treturn getSortedIds(this.enabledIds, this.allIds).map((id) => ({\n\t\t\tfullId: id,\n\t\t\tmodel: this.modelsById.get(id),\n\t\t\tenabled: isEnabled(this.enabledIds, id),\n\t\t}));\n\t}\n\n\tprivate getFooterText(): string {\n\t\tconst enabledCount = this.enabledIds?.filter((id) => this.modelsById.has(id)).length ?? this.allIds.length;\n\t\tconst unavailableCount = this.enabledIds?.filter((id) => !this.modelsById.has(id)).length ?? 0;\n\t\tconst allEnabled = this.enabledIds === null;\n\t\tconst countText = allEnabled\n\t\t\t? \"all enabled\"\n\t\t\t: `${enabledCount}/${this.allIds.length} enabled${unavailableCount ? ` · ${unavailableCount} unavailable` : \"\"}`;\n\t\tconst parts = [\n\t\t\t`${keyText(\"tui.select.confirm\")} toggle`,\n\t\t\t`${keyText(\"app.models.enableAll\")} all`,\n\t\t\t`${keyText(\"app.models.clearAll\")} clear`,\n\t\t\t`${keyText(\"app.models.toggleProvider\")} provider`,\n\t\t\t`${keyText(\"app.models.reorderUp\")}/${keyText(\"app.models.reorderDown\")} reorder`,\n\t\t\t`${keyText(\"app.models.save\")} save`,\n\t\t\tcountText,\n\t\t];\n\t\treturn this.isDirty\n\t\t\t? theme.fg(\"dim\", ` ${parts.join(\" · \")} `) + theme.fg(\"warning\", \"(unsaved)\")\n\t\t\t: theme.fg(\"dim\", ` ${parts.join(\" · \")}`);\n\t}\n\n\tprivate refresh(): void {\n\t\tconst query = this.searchInput.getValue();\n\t\tconst items = this.buildItems();\n\t\tthis.filteredItems = query\n\t\t\t? fuzzyFilter(items, query, (item) =>\n\t\t\t\t\titem.model\n\t\t\t\t\t\t? getModelSearchText({ id: item.model.id, provider: item.model.provider, name: item.model.name })\n\t\t\t\t\t\t: item.fullId,\n\t\t\t\t)\n\t\t\t: items;\n\t\tthis.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredItems.length - 1));\n\t\tthis.updateList();\n\t\tthis.footerText.setText(this.getFooterText());\n\t}\n\n\tprivate notifyChange(): void {\n\t\tthis.callbacks.onChange(this.enabledIds === null ? null : [...this.enabledIds]);\n\t}\n\n\tprivate updateList(): void {\n\t\tthis.listContainer.clear();\n\n\t\tif (this.filteredItems.length === 0) {\n\t\t\tthis.listContainer.addChild(new Text(theme.fg(\"muted\", \" No matching models\"), 0, 0));\n\t\t\treturn;\n\t\t}\n\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredItems.length - this.maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisible, this.filteredItems.length);\n\t\tconst allEnabled = this.enabledIds === null;\n\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst item = this.filteredItems[i]!;\n\t\t\tconst isSelected = i === this.selectedIndex;\n\t\t\tconst prefix = isSelected ? theme.fg(\"accent\", \"→ \") : \" \";\n\t\t\tconst id = item.model?.id ?? item.fullId;\n\t\t\tconst modelText = isSelected ? theme.fg(\"accent\", id) : id;\n\t\t\tconst providerBadge = theme.fg(\"muted\", item.model ? ` [${item.model.provider}]` : \" [unavailable]\");\n\t\t\tconst status = item.model\n\t\t\t\t? allEnabled\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: item.enabled\n\t\t\t\t\t\t? theme.fg(\"success\", \" ✓\")\n\t\t\t\t\t\t: theme.fg(\"dim\", \" ✗\")\n\t\t\t\t: theme.fg(\"dim\", \" ✗\");\n\t\t\tthis.listContainer.addChild(new Text(`${prefix}${modelText}${providerBadge}${status}`, 0, 0));\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.filteredItems.length) {\n\t\t\tthis.listContainer.addChild(\n\t\t\t\tnew Text(theme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.filteredItems.length})`), 0, 0),\n\t\t\t);\n\t\t}\n\n\t\tif (this.filteredItems.length > 0) {\n\t\t\tconst selected = this.filteredItems[this.selectedIndex];\n\t\t\tthis.listContainer.addChild(new Spacer(1));\n\t\t\tthis.listContainer.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\ttheme.fg(\"muted\", ` ${selected.model ? `Model Name: ${selected.model.name}` : \"Model unavailable\"}`),\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\thandleInput(data: string): void {\n\t\tconst kb = getKeybindings();\n\n\t\t// Navigation\n\t\tif (kb.matches(data, \"tui.select.up\")) {\n\t\t\tif (this.filteredItems.length === 0) return;\n\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.filteredItems.length - 1 : this.selectedIndex - 1;\n\t\t\tthis.updateList();\n\t\t\treturn;\n\t\t}\n\t\tif (kb.matches(data, \"tui.select.down\")) {\n\t\t\tif (this.filteredItems.length === 0) return;\n\t\t\tthis.selectedIndex = this.selectedIndex === this.filteredItems.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t\tthis.updateList();\n\t\t\treturn;\n\t\t}\n\n\t\t// Reorder enabled models\n\t\tconst reorderUp = kb.matches(data, \"app.models.reorderUp\");\n\t\tconst reorderDown = kb.matches(data, \"app.models.reorderDown\");\n\t\tif (reorderUp || reorderDown) {\n\t\t\tif (this.enabledIds === null) return;\n\t\t\tconst item = this.filteredItems[this.selectedIndex];\n\t\t\tif (item && isEnabled(this.enabledIds, item.fullId)) {\n\t\t\t\tconst delta = reorderUp ? -1 : 1;\n\t\t\t\tconst currentIndex = this.enabledIds.indexOf(item.fullId);\n\t\t\t\tconst newIndex = currentIndex + delta;\n\t\t\t\t// Only move if within bounds\n\t\t\t\tif (newIndex >= 0 && newIndex < this.enabledIds.length) {\n\t\t\t\t\tthis.enabledIds = move(this.enabledIds, item.fullId, delta);\n\t\t\t\t\tthis.isDirty = true;\n\t\t\t\t\tthis.selectedIndex += delta;\n\t\t\t\t\tthis.refresh();\n\t\t\t\t\tthis.notifyChange();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Toggle on Enter\n\t\tif (kb.matches(data, \"tui.select.confirm\")) {\n\t\t\tconst item = this.filteredItems[this.selectedIndex];\n\t\t\tif (item) {\n\t\t\t\tthis.enabledIds = toggle(this.enabledIds, item.fullId);\n\t\t\t\tthis.isDirty = true;\n\t\t\t\tthis.refresh();\n\t\t\t\tthis.notifyChange();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Enable all (filtered if search active, otherwise all)\n\t\tif (kb.matches(data, \"app.models.enableAll\")) {\n\t\t\tconst targetIds = this.searchInput.getValue() ? this.filteredItems.map((i) => i.fullId) : undefined;\n\t\t\tthis.enabledIds = enableAll(this.enabledIds, this.allIds, targetIds);\n\t\t\tthis.isDirty = true;\n\t\t\tthis.refresh();\n\t\t\tthis.notifyChange();\n\t\t\treturn;\n\t\t}\n\n\t\t// Clear all (filtered if search active, otherwise all)\n\t\tif (kb.matches(data, \"app.models.clearAll\")) {\n\t\t\tconst targetIds = this.searchInput.getValue() ? this.filteredItems.map((i) => i.fullId) : undefined;\n\t\t\tthis.enabledIds = clearAll(this.enabledIds, this.allIds, targetIds);\n\t\t\tthis.isDirty = true;\n\t\t\tthis.refresh();\n\t\t\tthis.notifyChange();\n\t\t\treturn;\n\t\t}\n\n\t\t// Toggle provider of current item\n\t\tif (kb.matches(data, \"app.models.toggleProvider\")) {\n\t\t\tconst item = this.filteredItems[this.selectedIndex];\n\t\t\tif (item?.model) {\n\t\t\t\tconst provider = item.model.provider;\n\t\t\t\tconst providerIds = this.allIds.filter((id) => this.modelsById.get(id)!.provider === provider);\n\t\t\t\tconst allEnabled = providerIds.every((id) => isEnabled(this.enabledIds, id));\n\t\t\t\tthis.enabledIds = allEnabled\n\t\t\t\t\t? clearAll(this.enabledIds, this.allIds, providerIds)\n\t\t\t\t\t: enableAll(this.enabledIds, this.allIds, providerIds);\n\t\t\t\tthis.isDirty = true;\n\t\t\t\tthis.refresh();\n\t\t\t\tthis.notifyChange();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Save/persist to settings\n\t\tif (kb.matches(data, \"app.models.save\")) {\n\t\t\tthis.callbacks.onPersist(this.enabledIds === null ? null : [...this.enabledIds]);\n\t\t\tthis.isDirty = false;\n\t\t\tthis.footerText.setText(this.getFooterText());\n\t\t\treturn;\n\t\t}\n\n\t\t// Ctrl+C - clear search or cancel if empty\n\t\tif (matchesKey(data, Key.ctrl(\"c\"))) {\n\t\t\tif (this.searchInput.getValue()) {\n\t\t\t\tthis.searchInput.setValue(\"\");\n\t\t\t\tthis.refresh();\n\t\t\t} else {\n\t\t\t\tthis.callbacks.onCancel();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Escape - cancel\n\t\tif (matchesKey(data, Key.escape)) {\n\t\t\tthis.callbacks.onCancel();\n\t\t\treturn;\n\t\t}\n\n\t\t// Pass everything else to search input\n\t\tthis.searchInput.handleInput(data);\n\t\tthis.refresh();\n\t}\n\n\tgetSearchInput(): Input {\n\t\treturn this.searchInput;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/scoped-models-selector.js b/dist/modes/interactive/components/scoped-models-selector.js new file mode 100644 index 0000000..078b9f8 --- /dev/null +++ b/dist/modes/interactive/components/scoped-models-selector.js @@ -0,0 +1,302 @@ +import { Container, fuzzyFilter, getKeybindings, Input, Key, matchesKey, Spacer, Text, } from "@earendil-works/pi-tui"; +import { getModelSearchText } from "../model-search.js"; +import { theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyText } from "./keybinding-hints.js"; +function isEnabled(enabledIds, id) { + return enabledIds === null || enabledIds.includes(id); +} +function toggle(enabledIds, id) { + if (enabledIds === null) + return [id]; // First toggle: start with only this one + const index = enabledIds.indexOf(id); + if (index >= 0) + return [...enabledIds.slice(0, index), ...enabledIds.slice(index + 1)]; + return [...enabledIds, id]; +} +function enableAll(enabledIds, allIds, targetIds) { + if (enabledIds === null) + return null; // Already all enabled + const targets = targetIds ?? allIds; + const result = [...enabledIds]; + for (const id of targets) { + if (!result.includes(id)) + result.push(id); + } + return result.length === allIds.length && result.every((id) => allIds.includes(id)) ? null : result; +} +function clearAll(enabledIds, allIds, targetIds) { + if (enabledIds === null) { + return targetIds ? allIds.filter((id) => !targetIds.includes(id)) : []; + } + const targets = new Set(targetIds ?? enabledIds); + return enabledIds.filter((id) => !targets.has(id)); +} +function move(enabledIds, id, delta) { + if (enabledIds === null) + return null; + const list = [...enabledIds]; + const index = list.indexOf(id); + if (index < 0) + return list; + const newIndex = index + delta; + if (newIndex < 0 || newIndex >= list.length) + return list; + const result = [...list]; + [result[index], result[newIndex]] = [result[newIndex], result[index]]; + return result; +} +function getSortedIds(enabledIds, allIds) { + if (enabledIds === null) + return allIds; + const enabledSet = new Set(enabledIds); + return [...enabledIds, ...allIds.filter((id) => !enabledSet.has(id))]; +} +/** + * Component for enabling/disabling models for Ctrl+P cycling. + * Changes are session-only until explicitly persisted with Ctrl+S. + */ +export class ScopedModelsSelectorComponent extends Container { + modelsById = new Map(); + allIds = []; + enabledIds = null; + filteredItems = []; + selectedIndex = 0; + searchInput; + // Focusable implementation - propagate to searchInput for IME cursor positioning + _focused = false; + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + this.searchInput.focused = value; + } + listContainer; + footerText; + callbacks; + maxVisible = 8; + isDirty = false; + constructor(config, callbacks) { + super(); + this.callbacks = callbacks; + for (const model of config.allModels) { + const fullId = `${model.provider}/${model.id}`; + this.modelsById.set(fullId, model); + this.allIds.push(fullId); + } + this.enabledIds = config.enabledModelIds === null ? null : [...config.enabledModelIds]; + this.filteredItems = this.buildItems(); + // Header + this.addChild(new DynamicBorder()); + this.addChild(new Spacer(1)); + this.addChild(new Text(theme.fg("accent", theme.bold("Model Configuration")), 0, 0)); + this.addChild(new Text(theme.fg("muted", `Session-only. ${keyText("app.models.save")} to save to settings.`), 0, 0)); + this.addChild(new Spacer(1)); + // Search input + this.searchInput = new Input(); + this.addChild(this.searchInput); + this.addChild(new Spacer(1)); + // List container + this.listContainer = new Container(); + this.addChild(this.listContainer); + // Footer hint + this.addChild(new Spacer(1)); + this.footerText = new Text(this.getFooterText(), 0, 0); + this.addChild(this.footerText); + this.addChild(new DynamicBorder()); + this.updateList(); + } + buildItems() { + return getSortedIds(this.enabledIds, this.allIds).map((id) => ({ + fullId: id, + model: this.modelsById.get(id), + enabled: isEnabled(this.enabledIds, id), + })); + } + getFooterText() { + const enabledCount = this.enabledIds?.filter((id) => this.modelsById.has(id)).length ?? this.allIds.length; + const unavailableCount = this.enabledIds?.filter((id) => !this.modelsById.has(id)).length ?? 0; + const allEnabled = this.enabledIds === null; + const countText = allEnabled + ? "all enabled" + : `${enabledCount}/${this.allIds.length} enabled${unavailableCount ? ` · ${unavailableCount} unavailable` : ""}`; + const parts = [ + `${keyText("tui.select.confirm")} toggle`, + `${keyText("app.models.enableAll")} all`, + `${keyText("app.models.clearAll")} clear`, + `${keyText("app.models.toggleProvider")} provider`, + `${keyText("app.models.reorderUp")}/${keyText("app.models.reorderDown")} reorder`, + `${keyText("app.models.save")} save`, + countText, + ]; + return this.isDirty + ? theme.fg("dim", ` ${parts.join(" · ")} `) + theme.fg("warning", "(unsaved)") + : theme.fg("dim", ` ${parts.join(" · ")}`); + } + refresh() { + const query = this.searchInput.getValue(); + const items = this.buildItems(); + this.filteredItems = query + ? fuzzyFilter(items, query, (item) => item.model + ? getModelSearchText({ id: item.model.id, provider: item.model.provider, name: item.model.name }) + : item.fullId) + : items; + this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredItems.length - 1)); + this.updateList(); + this.footerText.setText(this.getFooterText()); + } + notifyChange() { + this.callbacks.onChange(this.enabledIds === null ? null : [...this.enabledIds]); + } + updateList() { + this.listContainer.clear(); + if (this.filteredItems.length === 0) { + this.listContainer.addChild(new Text(theme.fg("muted", " No matching models"), 0, 0)); + return; + } + const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredItems.length - this.maxVisible)); + const endIndex = Math.min(startIndex + this.maxVisible, this.filteredItems.length); + const allEnabled = this.enabledIds === null; + for (let i = startIndex; i < endIndex; i++) { + const item = this.filteredItems[i]; + const isSelected = i === this.selectedIndex; + const prefix = isSelected ? theme.fg("accent", "→ ") : " "; + const id = item.model?.id ?? item.fullId; + const modelText = isSelected ? theme.fg("accent", id) : id; + const providerBadge = theme.fg("muted", item.model ? ` [${item.model.provider}]` : " [unavailable]"); + const status = item.model + ? allEnabled + ? "" + : item.enabled + ? theme.fg("success", " ✓") + : theme.fg("dim", " ✗") + : theme.fg("dim", " ✗"); + this.listContainer.addChild(new Text(`${prefix}${modelText}${providerBadge}${status}`, 0, 0)); + } + // Add scroll indicator if needed + if (startIndex > 0 || endIndex < this.filteredItems.length) { + this.listContainer.addChild(new Text(theme.fg("muted", ` (${this.selectedIndex + 1}/${this.filteredItems.length})`), 0, 0)); + } + if (this.filteredItems.length > 0) { + const selected = this.filteredItems[this.selectedIndex]; + this.listContainer.addChild(new Spacer(1)); + this.listContainer.addChild(new Text(theme.fg("muted", ` ${selected.model ? `Model Name: ${selected.model.name}` : "Model unavailable"}`), 0, 0)); + } + } + handleInput(data) { + const kb = getKeybindings(); + // Navigation + if (kb.matches(data, "tui.select.up")) { + if (this.filteredItems.length === 0) + return; + this.selectedIndex = this.selectedIndex === 0 ? this.filteredItems.length - 1 : this.selectedIndex - 1; + this.updateList(); + return; + } + if (kb.matches(data, "tui.select.down")) { + if (this.filteredItems.length === 0) + return; + this.selectedIndex = this.selectedIndex === this.filteredItems.length - 1 ? 0 : this.selectedIndex + 1; + this.updateList(); + return; + } + // Reorder enabled models + const reorderUp = kb.matches(data, "app.models.reorderUp"); + const reorderDown = kb.matches(data, "app.models.reorderDown"); + if (reorderUp || reorderDown) { + if (this.enabledIds === null) + return; + const item = this.filteredItems[this.selectedIndex]; + if (item && isEnabled(this.enabledIds, item.fullId)) { + const delta = reorderUp ? -1 : 1; + const currentIndex = this.enabledIds.indexOf(item.fullId); + const newIndex = currentIndex + delta; + // Only move if within bounds + if (newIndex >= 0 && newIndex < this.enabledIds.length) { + this.enabledIds = move(this.enabledIds, item.fullId, delta); + this.isDirty = true; + this.selectedIndex += delta; + this.refresh(); + this.notifyChange(); + } + } + return; + } + // Toggle on Enter + if (kb.matches(data, "tui.select.confirm")) { + const item = this.filteredItems[this.selectedIndex]; + if (item) { + this.enabledIds = toggle(this.enabledIds, item.fullId); + this.isDirty = true; + this.refresh(); + this.notifyChange(); + } + return; + } + // Enable all (filtered if search active, otherwise all) + if (kb.matches(data, "app.models.enableAll")) { + const targetIds = this.searchInput.getValue() ? this.filteredItems.map((i) => i.fullId) : undefined; + this.enabledIds = enableAll(this.enabledIds, this.allIds, targetIds); + this.isDirty = true; + this.refresh(); + this.notifyChange(); + return; + } + // Clear all (filtered if search active, otherwise all) + if (kb.matches(data, "app.models.clearAll")) { + const targetIds = this.searchInput.getValue() ? this.filteredItems.map((i) => i.fullId) : undefined; + this.enabledIds = clearAll(this.enabledIds, this.allIds, targetIds); + this.isDirty = true; + this.refresh(); + this.notifyChange(); + return; + } + // Toggle provider of current item + if (kb.matches(data, "app.models.toggleProvider")) { + const item = this.filteredItems[this.selectedIndex]; + if (item?.model) { + const provider = item.model.provider; + const providerIds = this.allIds.filter((id) => this.modelsById.get(id).provider === provider); + const allEnabled = providerIds.every((id) => isEnabled(this.enabledIds, id)); + this.enabledIds = allEnabled + ? clearAll(this.enabledIds, this.allIds, providerIds) + : enableAll(this.enabledIds, this.allIds, providerIds); + this.isDirty = true; + this.refresh(); + this.notifyChange(); + } + return; + } + // Save/persist to settings + if (kb.matches(data, "app.models.save")) { + this.callbacks.onPersist(this.enabledIds === null ? null : [...this.enabledIds]); + this.isDirty = false; + this.footerText.setText(this.getFooterText()); + return; + } + // Ctrl+C - clear search or cancel if empty + if (matchesKey(data, Key.ctrl("c"))) { + if (this.searchInput.getValue()) { + this.searchInput.setValue(""); + this.refresh(); + } + else { + this.callbacks.onCancel(); + } + return; + } + // Escape - cancel + if (matchesKey(data, Key.escape)) { + this.callbacks.onCancel(); + return; + } + // Pass everything else to search input + this.searchInput.handleInput(data); + this.refresh(); + } + getSearchInput() { + return this.searchInput; + } +} +//# sourceMappingURL=scoped-models-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/scoped-models-selector.js.map b/dist/modes/interactive/components/scoped-models-selector.js.map new file mode 100644 index 0000000..473db24 --- /dev/null +++ b/dist/modes/interactive/components/scoped-models-selector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scoped-models-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/scoped-models-selector.ts"],"names":[],"mappings":"AACA,OAAO,EACN,SAAS,EAET,WAAW,EACX,cAAc,EACd,KAAK,EACL,GAAG,EACH,UAAU,EACV,MAAM,EACN,IAAI,GACJ,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAKhD,SAAS,SAAS,CAAC,UAAsB,EAAE,EAAU,EAAW;IAC/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AC,SAAS,CAAC,QAAQ,EAAE,CAAC;YAC1B,OAAO;QACR,CAAC;QAED,uCAAuC;QACvC,IAAI,CAAC,WAAW,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QACnC,IAAI,CAAC,OAAO,EAAE,CAAC;IAAA,CACf;IAED,cAAc,GAAU;QACvB,OAAO,IAAI,CAAC,WAAW,CAAC;IAAA,CACxB;CACD","sourcesContent":["import type { Model } from \"@earendil-works/pi-ai\";\nimport {\n\tContainer,\n\ttype Focusable,\n\tfuzzyFilter,\n\tgetKeybindings,\n\tInput,\n\tKey,\n\tmatchesKey,\n\tSpacer,\n\tText,\n} from \"@earendil-works/pi-tui\";\nimport { getModelSearchText } from \"../model-search.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyText } from \"./keybinding-hints.ts\";\n\n// EnabledIds: null = all enabled (no filter), string[] = explicit ordered list\ntype EnabledIds = string[] | null;\n\nfunction isEnabled(enabledIds: EnabledIds, id: string): boolean {\n\treturn enabledIds === null || enabledIds.includes(id);\n}\n\nfunction toggle(enabledIds: EnabledIds, id: string): EnabledIds {\n\tif (enabledIds === null) return [id]; // First toggle: start with only this one\n\tconst index = enabledIds.indexOf(id);\n\tif (index >= 0) return [...enabledIds.slice(0, index), ...enabledIds.slice(index + 1)];\n\treturn [...enabledIds, id];\n}\n\nfunction enableAll(enabledIds: EnabledIds, allIds: string[], targetIds?: string[]): EnabledIds {\n\tif (enabledIds === null) return null; // Already all enabled\n\tconst targets = targetIds ?? allIds;\n\tconst result = [...enabledIds];\n\tfor (const id of targets) {\n\t\tif (!result.includes(id)) result.push(id);\n\t}\n\treturn result.length === allIds.length && result.every((id) => allIds.includes(id)) ? null : result;\n}\n\nfunction clearAll(enabledIds: EnabledIds, allIds: string[], targetIds?: string[]): EnabledIds {\n\tif (enabledIds === null) {\n\t\treturn targetIds ? allIds.filter((id) => !targetIds.includes(id)) : [];\n\t}\n\tconst targets = new Set(targetIds ?? enabledIds);\n\treturn enabledIds.filter((id) => !targets.has(id));\n}\n\nfunction move(enabledIds: EnabledIds, id: string, delta: number): EnabledIds {\n\tif (enabledIds === null) return null;\n\tconst list = [...enabledIds];\n\tconst index = list.indexOf(id);\n\tif (index < 0) return list;\n\tconst newIndex = index + delta;\n\tif (newIndex < 0 || newIndex >= list.length) return list;\n\tconst result = [...list];\n\t[result[index], result[newIndex]] = [result[newIndex], result[index]];\n\treturn result;\n}\n\nfunction getSortedIds(enabledIds: EnabledIds, allIds: string[]): string[] {\n\tif (enabledIds === null) return allIds;\n\tconst enabledSet = new Set(enabledIds);\n\treturn [...enabledIds, ...allIds.filter((id) => !enabledSet.has(id))];\n}\n\ninterface ModelItem {\n\tfullId: string;\n\tmodel: Model | undefined;\n\tenabled: boolean;\n}\n\nexport interface ModelsConfig {\n\tallModels: Model[];\n\tenabledModelIds: string[] | null;\n}\n\nexport interface ModelsCallbacks {\n\t/** Called whenever the enabled model set or order changes (session-only, no persist) */\n\tonChange: (enabledModelIds: string[] | null) => void | Promise;\n\t/** Called when user wants to persist current selection to settings */\n\tonPersist: (enabledModelIds: string[] | null) => void | Promise;\n\tonCancel: () => void;\n}\n\n/**\n * Component for enabling/disabling models for Ctrl+P cycling.\n * Changes are session-only until explicitly persisted with Ctrl+S.\n */\nexport class ScopedModelsSelectorComponent extends Container implements Focusable {\n\tprivate modelsById: Map> = new Map();\n\tprivate allIds: string[] = [];\n\tprivate enabledIds: EnabledIds = null;\n\tprivate filteredItems: ModelItem[] = [];\n\tprivate selectedIndex = 0;\n\tprivate searchInput: Input;\n\n\t// Focusable implementation - propagate to searchInput for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.searchInput.focused = value;\n\t}\n\tprivate listContainer: Container;\n\tprivate footerText: Text;\n\tprivate callbacks: ModelsCallbacks;\n\tprivate maxVisible = 8;\n\tprivate isDirty = false;\n\n\tconstructor(config: ModelsConfig, callbacks: ModelsCallbacks) {\n\t\tsuper();\n\t\tthis.callbacks = callbacks;\n\n\t\tfor (const model of config.allModels) {\n\t\t\tconst fullId = `${model.provider}/${model.id}`;\n\t\t\tthis.modelsById.set(fullId, model);\n\t\t\tthis.allIds.push(fullId);\n\t\t}\n\n\t\tthis.enabledIds = config.enabledModelIds === null ? null : [...config.enabledModelIds];\n\t\tthis.filteredItems = this.buildItems();\n\n\t\t// Header\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.fg(\"accent\", theme.bold(\"Model Configuration\")), 0, 0));\n\t\tthis.addChild(\n\t\t\tnew Text(theme.fg(\"muted\", `Session-only. ${keyText(\"app.models.save\")} to save to settings.`), 0, 0),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Search input\n\t\tthis.searchInput = new Input();\n\t\tthis.addChild(this.searchInput);\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// List container\n\t\tthis.listContainer = new Container();\n\t\tthis.addChild(this.listContainer);\n\n\t\t// Footer hint\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.footerText = new Text(this.getFooterText(), 0, 0);\n\t\tthis.addChild(this.footerText);\n\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.updateList();\n\t}\n\n\tprivate buildItems(): ModelItem[] {\n\t\treturn getSortedIds(this.enabledIds, this.allIds).map((id) => ({\n\t\t\tfullId: id,\n\t\t\tmodel: this.modelsById.get(id),\n\t\t\tenabled: isEnabled(this.enabledIds, id),\n\t\t}));\n\t}\n\n\tprivate getFooterText(): string {\n\t\tconst enabledCount = this.enabledIds?.filter((id) => this.modelsById.has(id)).length ?? this.allIds.length;\n\t\tconst unavailableCount = this.enabledIds?.filter((id) => !this.modelsById.has(id)).length ?? 0;\n\t\tconst allEnabled = this.enabledIds === null;\n\t\tconst countText = allEnabled\n\t\t\t? \"all enabled\"\n\t\t\t: `${enabledCount}/${this.allIds.length} enabled${unavailableCount ? ` · ${unavailableCount} unavailable` : \"\"}`;\n\t\tconst parts = [\n\t\t\t`${keyText(\"tui.select.confirm\")} toggle`,\n\t\t\t`${keyText(\"app.models.enableAll\")} all`,\n\t\t\t`${keyText(\"app.models.clearAll\")} clear`,\n\t\t\t`${keyText(\"app.models.toggleProvider\")} provider`,\n\t\t\t`${keyText(\"app.models.reorderUp\")}/${keyText(\"app.models.reorderDown\")} reorder`,\n\t\t\t`${keyText(\"app.models.save\")} save`,\n\t\t\tcountText,\n\t\t];\n\t\treturn this.isDirty\n\t\t\t? theme.fg(\"dim\", ` ${parts.join(\" · \")} `) + theme.fg(\"warning\", \"(unsaved)\")\n\t\t\t: theme.fg(\"dim\", ` ${parts.join(\" · \")}`);\n\t}\n\n\tprivate refresh(): void {\n\t\tconst query = this.searchInput.getValue();\n\t\tconst items = this.buildItems();\n\t\tthis.filteredItems = query\n\t\t\t? fuzzyFilter(items, query, (item) =>\n\t\t\t\t\titem.model\n\t\t\t\t\t\t? getModelSearchText({ id: item.model.id, provider: item.model.provider, name: item.model.name })\n\t\t\t\t\t\t: item.fullId,\n\t\t\t\t)\n\t\t\t: items;\n\t\tthis.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredItems.length - 1));\n\t\tthis.updateList();\n\t\tthis.footerText.setText(this.getFooterText());\n\t}\n\n\tprivate notifyChange(): void {\n\t\tthis.callbacks.onChange(this.enabledIds === null ? null : [...this.enabledIds]);\n\t}\n\n\tprivate updateList(): void {\n\t\tthis.listContainer.clear();\n\n\t\tif (this.filteredItems.length === 0) {\n\t\t\tthis.listContainer.addChild(new Text(theme.fg(\"muted\", \" No matching models\"), 0, 0));\n\t\t\treturn;\n\t\t}\n\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredItems.length - this.maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisible, this.filteredItems.length);\n\t\tconst allEnabled = this.enabledIds === null;\n\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst item = this.filteredItems[i]!;\n\t\t\tconst isSelected = i === this.selectedIndex;\n\t\t\tconst prefix = isSelected ? theme.fg(\"accent\", \"→ \") : \" \";\n\t\t\tconst id = item.model?.id ?? item.fullId;\n\t\t\tconst modelText = isSelected ? theme.fg(\"accent\", id) : id;\n\t\t\tconst providerBadge = theme.fg(\"muted\", item.model ? ` [${item.model.provider}]` : \" [unavailable]\");\n\t\t\tconst status = item.model\n\t\t\t\t? allEnabled\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: item.enabled\n\t\t\t\t\t\t? theme.fg(\"success\", \" ✓\")\n\t\t\t\t\t\t: theme.fg(\"dim\", \" ✗\")\n\t\t\t\t: theme.fg(\"dim\", \" ✗\");\n\t\t\tthis.listContainer.addChild(new Text(`${prefix}${modelText}${providerBadge}${status}`, 0, 0));\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.filteredItems.length) {\n\t\t\tthis.listContainer.addChild(\n\t\t\t\tnew Text(theme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.filteredItems.length})`), 0, 0),\n\t\t\t);\n\t\t}\n\n\t\tif (this.filteredItems.length > 0) {\n\t\t\tconst selected = this.filteredItems[this.selectedIndex];\n\t\t\tthis.listContainer.addChild(new Spacer(1));\n\t\t\tthis.listContainer.addChild(\n\t\t\t\tnew Text(\n\t\t\t\t\ttheme.fg(\"muted\", ` ${selected.model ? `Model Name: ${selected.model.name}` : \"Model unavailable\"}`),\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\thandleInput(data: string): void {\n\t\tconst kb = getKeybindings();\n\n\t\t// Navigation\n\t\tif (kb.matches(data, \"tui.select.up\")) {\n\t\t\tif (this.filteredItems.length === 0) return;\n\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.filteredItems.length - 1 : this.selectedIndex - 1;\n\t\t\tthis.updateList();\n\t\t\treturn;\n\t\t}\n\t\tif (kb.matches(data, \"tui.select.down\")) {\n\t\t\tif (this.filteredItems.length === 0) return;\n\t\t\tthis.selectedIndex = this.selectedIndex === this.filteredItems.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t\tthis.updateList();\n\t\t\treturn;\n\t\t}\n\n\t\t// Reorder enabled models\n\t\tconst reorderUp = kb.matches(data, \"app.models.reorderUp\");\n\t\tconst reorderDown = kb.matches(data, \"app.models.reorderDown\");\n\t\tif (reorderUp || reorderDown) {\n\t\t\tif (this.enabledIds === null) return;\n\t\t\tconst item = this.filteredItems[this.selectedIndex];\n\t\t\tif (item && isEnabled(this.enabledIds, item.fullId)) {\n\t\t\t\tconst delta = reorderUp ? -1 : 1;\n\t\t\t\tconst currentIndex = this.enabledIds.indexOf(item.fullId);\n\t\t\t\tconst newIndex = currentIndex + delta;\n\t\t\t\t// Only move if within bounds\n\t\t\t\tif (newIndex >= 0 && newIndex < this.enabledIds.length) {\n\t\t\t\t\tthis.enabledIds = move(this.enabledIds, item.fullId, delta);\n\t\t\t\t\tthis.isDirty = true;\n\t\t\t\t\tthis.selectedIndex += delta;\n\t\t\t\t\tthis.refresh();\n\t\t\t\t\tthis.notifyChange();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Toggle on Enter\n\t\tif (kb.matches(data, \"tui.select.confirm\")) {\n\t\t\tconst item = this.filteredItems[this.selectedIndex];\n\t\t\tif (item) {\n\t\t\t\tthis.enabledIds = toggle(this.enabledIds, item.fullId);\n\t\t\t\tthis.isDirty = true;\n\t\t\t\tthis.refresh();\n\t\t\t\tthis.notifyChange();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Enable all (filtered if search active, otherwise all)\n\t\tif (kb.matches(data, \"app.models.enableAll\")) {\n\t\t\tconst targetIds = this.searchInput.getValue() ? this.filteredItems.map((i) => i.fullId) : undefined;\n\t\t\tthis.enabledIds = enableAll(this.enabledIds, this.allIds, targetIds);\n\t\t\tthis.isDirty = true;\n\t\t\tthis.refresh();\n\t\t\tthis.notifyChange();\n\t\t\treturn;\n\t\t}\n\n\t\t// Clear all (filtered if search active, otherwise all)\n\t\tif (kb.matches(data, \"app.models.clearAll\")) {\n\t\t\tconst targetIds = this.searchInput.getValue() ? this.filteredItems.map((i) => i.fullId) : undefined;\n\t\t\tthis.enabledIds = clearAll(this.enabledIds, this.allIds, targetIds);\n\t\t\tthis.isDirty = true;\n\t\t\tthis.refresh();\n\t\t\tthis.notifyChange();\n\t\t\treturn;\n\t\t}\n\n\t\t// Toggle provider of current item\n\t\tif (kb.matches(data, \"app.models.toggleProvider\")) {\n\t\t\tconst item = this.filteredItems[this.selectedIndex];\n\t\t\tif (item?.model) {\n\t\t\t\tconst provider = item.model.provider;\n\t\t\t\tconst providerIds = this.allIds.filter((id) => this.modelsById.get(id)!.provider === provider);\n\t\t\t\tconst allEnabled = providerIds.every((id) => isEnabled(this.enabledIds, id));\n\t\t\t\tthis.enabledIds = allEnabled\n\t\t\t\t\t? clearAll(this.enabledIds, this.allIds, providerIds)\n\t\t\t\t\t: enableAll(this.enabledIds, this.allIds, providerIds);\n\t\t\t\tthis.isDirty = true;\n\t\t\t\tthis.refresh();\n\t\t\t\tthis.notifyChange();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Save/persist to settings\n\t\tif (kb.matches(data, \"app.models.save\")) {\n\t\t\tthis.callbacks.onPersist(this.enabledIds === null ? null : [...this.enabledIds]);\n\t\t\tthis.isDirty = false;\n\t\t\tthis.footerText.setText(this.getFooterText());\n\t\t\treturn;\n\t\t}\n\n\t\t// Ctrl+C - clear search or cancel if empty\n\t\tif (matchesKey(data, Key.ctrl(\"c\"))) {\n\t\t\tif (this.searchInput.getValue()) {\n\t\t\t\tthis.searchInput.setValue(\"\");\n\t\t\t\tthis.refresh();\n\t\t\t} else {\n\t\t\t\tthis.callbacks.onCancel();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Escape - cancel\n\t\tif (matchesKey(data, Key.escape)) {\n\t\t\tthis.callbacks.onCancel();\n\t\t\treturn;\n\t\t}\n\n\t\t// Pass everything else to search input\n\t\tthis.searchInput.handleInput(data);\n\t\tthis.refresh();\n\t}\n\n\tgetSearchInput(): Input {\n\t\treturn this.searchInput;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/session-selector-search.d.ts b/dist/modes/interactive/components/session-selector-search.d.ts new file mode 100644 index 0000000..5380359 --- /dev/null +++ b/dist/modes/interactive/components/session-selector-search.d.ts @@ -0,0 +1,23 @@ +import type { SessionInfo } from "../../../core/session-manager.ts"; +export type SortMode = "threaded" | "recent" | "relevance"; +export type NameFilter = "all" | "named"; +export interface ParsedSearchQuery { + mode: "tokens" | "regex"; + tokens: { + kind: "fuzzy" | "phrase"; + value: string; + }[]; + regex: RegExp | null; + /** If set, parsing failed and we should treat query as non-matching. */ + error?: string; +} +export interface MatchResult { + matches: boolean; + /** Lower is better; only meaningful when matches === true */ + score: number; +} +export declare function hasSessionName(session: SessionInfo): boolean; +export declare function parseSearchQuery(query: string): ParsedSearchQuery; +export declare function matchSession(session: SessionInfo, parsed: ParsedSearchQuery): MatchResult; +export declare function filterAndSortSessions(sessions: SessionInfo[], query: string, sortMode: SortMode, nameFilter?: NameFilter): SessionInfo[]; +//# sourceMappingURL=session-selector-search.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/session-selector-search.d.ts.map b/dist/modes/interactive/components/session-selector-search.d.ts.map new file mode 100644 index 0000000..eaaeab5 --- /dev/null +++ b/dist/modes/interactive/components/session-selector-search.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-selector-search.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/session-selector-search.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kCAAkC,CAAC;AAEpE,MAAM,MAAM,QAAQ,GAAG,UAAU,GAAG,QAAQ,GAAG,WAAW,CAAC;AAE3D,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,OAAO,CAAC;AAEzC,MAAM,WAAW,iBAAiB;IACjC,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;IACzB,MAAM,EAAE;QAAE,IAAI,EAAE,OAAO,GAAG,QAAQ,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACtD,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,wEAAwE;IACxE,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,WAAW;IAC3B,OAAO,EAAE,OAAO,CAAC;IACjB,6DAA6D;IAC7D,KAAK,EAAE,MAAM,CAAC;CACd;AAUD,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAE5D;AAOD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,iBAAiB,CA2EjE;AAED,wBAAgB,YAAY,CAAC,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,iBAAiB,GAAG,WAAW,CAsCzF;AAED,wBAAgB,qBAAqB,CACpC,QAAQ,EAAE,WAAW,EAAE,EACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,QAAQ,EAClB,UAAU,GAAE,UAAkB,GAC5B,WAAW,EAAE,CAiCf","sourcesContent":["import { fuzzyMatch } from \"@earendil-works/pi-tui\";\nimport type { SessionInfo } from \"../../../core/session-manager.ts\";\n\nexport type SortMode = \"threaded\" | \"recent\" | \"relevance\";\n\nexport type NameFilter = \"all\" | \"named\";\n\nexport interface ParsedSearchQuery {\n\tmode: \"tokens\" | \"regex\";\n\ttokens: { kind: \"fuzzy\" | \"phrase\"; value: string }[];\n\tregex: RegExp | null;\n\t/** If set, parsing failed and we should treat query as non-matching. */\n\terror?: string;\n}\n\nexport interface MatchResult {\n\tmatches: boolean;\n\t/** Lower is better; only meaningful when matches === true */\n\tscore: number;\n}\n\nfunction normalizeWhitespaceLower(text: string): string {\n\treturn text.toLowerCase().replace(/\\s+/g, \" \").trim();\n}\n\nfunction getSessionSearchText(session: SessionInfo): string {\n\treturn `${session.id} ${session.name ?? \"\"} ${session.allMessagesText} ${session.cwd}`;\n}\n\nexport function hasSessionName(session: SessionInfo): boolean {\n\treturn Boolean(session.name?.trim());\n}\n\nfunction matchesNameFilter(session: SessionInfo, filter: NameFilter): boolean {\n\tif (filter === \"all\") return true;\n\treturn hasSessionName(session);\n}\n\nexport function parseSearchQuery(query: string): ParsedSearchQuery {\n\tconst trimmed = query.trim();\n\tif (!trimmed) {\n\t\treturn { mode: \"tokens\", tokens: [], regex: null };\n\t}\n\n\t// Regex mode: re:\n\tif (trimmed.startsWith(\"re:\")) {\n\t\tconst pattern = trimmed.slice(3).trim();\n\t\tif (!pattern) {\n\t\t\treturn { mode: \"regex\", tokens: [], regex: null, error: \"Empty regex\" };\n\t\t}\n\t\ttry {\n\t\t\treturn { mode: \"regex\", tokens: [], regex: new RegExp(pattern, \"i\") };\n\t\t} catch (err) {\n\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\treturn { mode: \"regex\", tokens: [], regex: null, error: msg };\n\t\t}\n\t}\n\n\t// Token mode with quote support.\n\t// Example: foo \"node cve\" bar\n\tconst tokens: { kind: \"fuzzy\" | \"phrase\"; value: string }[] = [];\n\tlet buf = \"\";\n\tlet inQuote = false;\n\tlet hadUnclosedQuote = false;\n\n\tconst flush = (kind: \"fuzzy\" | \"phrase\"): void => {\n\t\tconst v = buf.trim();\n\t\tbuf = \"\";\n\t\tif (!v) return;\n\t\ttokens.push({ kind, value: v });\n\t};\n\n\tfor (let i = 0; i < trimmed.length; i++) {\n\t\tconst ch = trimmed[i]!;\n\t\tif (ch === '\"') {\n\t\t\tif (inQuote) {\n\t\t\t\tflush(\"phrase\");\n\t\t\t\tinQuote = false;\n\t\t\t} else {\n\t\t\t\tflush(\"fuzzy\");\n\t\t\t\tinQuote = true;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!inQuote && /\\s/.test(ch)) {\n\t\t\tflush(\"fuzzy\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tbuf += ch;\n\t}\n\n\tif (inQuote) {\n\t\thadUnclosedQuote = true;\n\t}\n\n\t// If quotes were unbalanced, fall back to plain whitespace tokenization.\n\tif (hadUnclosedQuote) {\n\t\treturn {\n\t\t\tmode: \"tokens\",\n\t\t\ttokens: trimmed\n\t\t\t\t.split(/\\s+/)\n\t\t\t\t.map((t) => t.trim())\n\t\t\t\t.filter((t) => t.length > 0)\n\t\t\t\t.map((t) => ({ kind: \"fuzzy\" as const, value: t })),\n\t\t\tregex: null,\n\t\t};\n\t}\n\n\tflush(inQuote ? \"phrase\" : \"fuzzy\");\n\n\treturn { mode: \"tokens\", tokens, regex: null };\n}\n\nexport function matchSession(session: SessionInfo, parsed: ParsedSearchQuery): MatchResult {\n\tconst text = getSessionSearchText(session);\n\n\tif (parsed.mode === \"regex\") {\n\t\tif (!parsed.regex) {\n\t\t\treturn { matches: false, score: 0 };\n\t\t}\n\t\tconst idx = text.search(parsed.regex);\n\t\tif (idx < 0) return { matches: false, score: 0 };\n\t\treturn { matches: true, score: idx * 0.1 };\n\t}\n\n\tif (parsed.tokens.length === 0) {\n\t\treturn { matches: true, score: 0 };\n\t}\n\n\tlet totalScore = 0;\n\tlet normalizedText: string | null = null;\n\n\tfor (const token of parsed.tokens) {\n\t\tif (token.kind === \"phrase\") {\n\t\t\tif (normalizedText === null) {\n\t\t\t\tnormalizedText = normalizeWhitespaceLower(text);\n\t\t\t}\n\t\t\tconst phrase = normalizeWhitespaceLower(token.value);\n\t\t\tif (!phrase) continue;\n\t\t\tconst idx = normalizedText.indexOf(phrase);\n\t\t\tif (idx < 0) return { matches: false, score: 0 };\n\t\t\ttotalScore += idx * 0.1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst m = fuzzyMatch(token.value, text);\n\t\tif (!m.matches) return { matches: false, score: 0 };\n\t\ttotalScore += m.score;\n\t}\n\n\treturn { matches: true, score: totalScore };\n}\n\nexport function filterAndSortSessions(\n\tsessions: SessionInfo[],\n\tquery: string,\n\tsortMode: SortMode,\n\tnameFilter: NameFilter = \"all\",\n): SessionInfo[] {\n\tconst nameFiltered =\n\t\tnameFilter === \"all\" ? sessions : sessions.filter((session) => matchesNameFilter(session, nameFilter));\n\tconst trimmed = query.trim();\n\tif (!trimmed) return nameFiltered;\n\n\tconst parsed = parseSearchQuery(query);\n\tif (parsed.error) return [];\n\n\t// Recent mode: filter only, keep incoming order.\n\tif (sortMode === \"recent\") {\n\t\tconst filtered: SessionInfo[] = [];\n\t\tfor (const s of nameFiltered) {\n\t\t\tconst res = matchSession(s, parsed);\n\t\t\tif (res.matches) filtered.push(s);\n\t\t}\n\t\treturn filtered;\n\t}\n\n\t// Relevance mode: sort by score, tie-break by modified desc.\n\tconst scored: { session: SessionInfo; score: number }[] = [];\n\tfor (const s of nameFiltered) {\n\t\tconst res = matchSession(s, parsed);\n\t\tif (!res.matches) continue;\n\t\tscored.push({ session: s, score: res.score });\n\t}\n\n\tscored.sort((a, b) => {\n\t\tif (a.score !== b.score) return a.score - b.score;\n\t\treturn b.session.modified.getTime() - a.session.modified.getTime();\n\t});\n\n\treturn scored.map((r) => r.session);\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/session-selector-search.js b/dist/modes/interactive/components/session-selector-search.js new file mode 100644 index 0000000..4f9c404 --- /dev/null +++ b/dist/modes/interactive/components/session-selector-search.js @@ -0,0 +1,155 @@ +import { fuzzyMatch } from "@earendil-works/pi-tui"; +function normalizeWhitespaceLower(text) { + return text.toLowerCase().replace(/\s+/g, " ").trim(); +} +function getSessionSearchText(session) { + return `${session.id} ${session.name ?? ""} ${session.allMessagesText} ${session.cwd}`; +} +export function hasSessionName(session) { + return Boolean(session.name?.trim()); +} +function matchesNameFilter(session, filter) { + if (filter === "all") + return true; + return hasSessionName(session); +} +export function parseSearchQuery(query) { + const trimmed = query.trim(); + if (!trimmed) { + return { mode: "tokens", tokens: [], regex: null }; + } + // Regex mode: re: + if (trimmed.startsWith("re:")) { + const pattern = trimmed.slice(3).trim(); + if (!pattern) { + return { mode: "regex", tokens: [], regex: null, error: "Empty regex" }; + } + try { + return { mode: "regex", tokens: [], regex: new RegExp(pattern, "i") }; + } + catch (err) { + const msg = err instanceof Error ? err.message : String(err); + return { mode: "regex", tokens: [], regex: null, error: msg }; + } + } + // Token mode with quote support. + // Example: foo "node cve" bar + const tokens = []; + let buf = ""; + let inQuote = false; + let hadUnclosedQuote = false; + const flush = (kind) => { + const v = buf.trim(); + buf = ""; + if (!v) + return; + tokens.push({ kind, value: v }); + }; + for (let i = 0; i < trimmed.length; i++) { + const ch = trimmed[i]; + if (ch === '"') { + if (inQuote) { + flush("phrase"); + inQuote = false; + } + else { + flush("fuzzy"); + inQuote = true; + } + continue; + } + if (!inQuote && /\s/.test(ch)) { + flush("fuzzy"); + continue; + } + buf += ch; + } + if (inQuote) { + hadUnclosedQuote = true; + } + // If quotes were unbalanced, fall back to plain whitespace tokenization. + if (hadUnclosedQuote) { + return { + mode: "tokens", + tokens: trimmed + .split(/\s+/) + .map((t) => t.trim()) + .filter((t) => t.length > 0) + .map((t) => ({ kind: "fuzzy", value: t })), + regex: null, + }; + } + flush(inQuote ? "phrase" : "fuzzy"); + return { mode: "tokens", tokens, regex: null }; +} +export function matchSession(session, parsed) { + const text = getSessionSearchText(session); + if (parsed.mode === "regex") { + if (!parsed.regex) { + return { matches: false, score: 0 }; + } + const idx = text.search(parsed.regex); + if (idx < 0) + return { matches: false, score: 0 }; + return { matches: true, score: idx * 0.1 }; + } + if (parsed.tokens.length === 0) { + return { matches: true, score: 0 }; + } + let totalScore = 0; + let normalizedText = null; + for (const token of parsed.tokens) { + if (token.kind === "phrase") { + if (normalizedText === null) { + normalizedText = normalizeWhitespaceLower(text); + } + const phrase = normalizeWhitespaceLower(token.value); + if (!phrase) + continue; + const idx = normalizedText.indexOf(phrase); + if (idx < 0) + return { matches: false, score: 0 }; + totalScore += idx * 0.1; + continue; + } + const m = fuzzyMatch(token.value, text); + if (!m.matches) + return { matches: false, score: 0 }; + totalScore += m.score; + } + return { matches: true, score: totalScore }; +} +export function filterAndSortSessions(sessions, query, sortMode, nameFilter = "all") { + const nameFiltered = nameFilter === "all" ? sessions : sessions.filter((session) => matchesNameFilter(session, nameFilter)); + const trimmed = query.trim(); + if (!trimmed) + return nameFiltered; + const parsed = parseSearchQuery(query); + if (parsed.error) + return []; + // Recent mode: filter only, keep incoming order. + if (sortMode === "recent") { + const filtered = []; + for (const s of nameFiltered) { + const res = matchSession(s, parsed); + if (res.matches) + filtered.push(s); + } + return filtered; + } + // Relevance mode: sort by score, tie-break by modified desc. + const scored = []; + for (const s of nameFiltered) { + const res = matchSession(s, parsed); + if (!res.matches) + continue; + scored.push({ session: s, score: res.score }); + } + scored.sort((a, b) => { + if (a.score !== b.score) + return a.score - b.score; + return b.session.modified.getTime() - a.session.modified.getTime(); + }); + return scored.map((r) => r.session); +} +//# sourceMappingURL=session-selector-search.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/session-selector-search.js.map b/dist/modes/interactive/components/session-selector-search.js.map new file mode 100644 index 0000000..3930aec --- /dev/null +++ b/dist/modes/interactive/components/session-selector-search.js.map @@ -0,0 +1 @@ +{"version":3,"file":"session-selector-search.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/session-selector-search.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAqBpD,SAAS,wBAAwB,CAAC,IAAY,EAAU;IACvD,OAAO,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;AAAA,CACtD;AAED,SAAS,oBAAoB,CAAC,OAAoB,EAAU;IAC3D,OAAO,GAAG,OAAO,CAAC,EAAE,IAAI,OAAO,CAAC,IAAI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K,CAAC,CAAC,KAAK;YAAE,OAAO,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC;QAClD,OAAO,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;IAAA,CACnE,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;AAAA,CACpC","sourcesContent":["import { fuzzyMatch } from \"@earendil-works/pi-tui\";\nimport type { SessionInfo } from \"../../../core/session-manager.ts\";\n\nexport type SortMode = \"threaded\" | \"recent\" | \"relevance\";\n\nexport type NameFilter = \"all\" | \"named\";\n\nexport interface ParsedSearchQuery {\n\tmode: \"tokens\" | \"regex\";\n\ttokens: { kind: \"fuzzy\" | \"phrase\"; value: string }[];\n\tregex: RegExp | null;\n\t/** If set, parsing failed and we should treat query as non-matching. */\n\terror?: string;\n}\n\nexport interface MatchResult {\n\tmatches: boolean;\n\t/** Lower is better; only meaningful when matches === true */\n\tscore: number;\n}\n\nfunction normalizeWhitespaceLower(text: string): string {\n\treturn text.toLowerCase().replace(/\\s+/g, \" \").trim();\n}\n\nfunction getSessionSearchText(session: SessionInfo): string {\n\treturn `${session.id} ${session.name ?? \"\"} ${session.allMessagesText} ${session.cwd}`;\n}\n\nexport function hasSessionName(session: SessionInfo): boolean {\n\treturn Boolean(session.name?.trim());\n}\n\nfunction matchesNameFilter(session: SessionInfo, filter: NameFilter): boolean {\n\tif (filter === \"all\") return true;\n\treturn hasSessionName(session);\n}\n\nexport function parseSearchQuery(query: string): ParsedSearchQuery {\n\tconst trimmed = query.trim();\n\tif (!trimmed) {\n\t\treturn { mode: \"tokens\", tokens: [], regex: null };\n\t}\n\n\t// Regex mode: re:\n\tif (trimmed.startsWith(\"re:\")) {\n\t\tconst pattern = trimmed.slice(3).trim();\n\t\tif (!pattern) {\n\t\t\treturn { mode: \"regex\", tokens: [], regex: null, error: \"Empty regex\" };\n\t\t}\n\t\ttry {\n\t\t\treturn { mode: \"regex\", tokens: [], regex: new RegExp(pattern, \"i\") };\n\t\t} catch (err) {\n\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\treturn { mode: \"regex\", tokens: [], regex: null, error: msg };\n\t\t}\n\t}\n\n\t// Token mode with quote support.\n\t// Example: foo \"node cve\" bar\n\tconst tokens: { kind: \"fuzzy\" | \"phrase\"; value: string }[] = [];\n\tlet buf = \"\";\n\tlet inQuote = false;\n\tlet hadUnclosedQuote = false;\n\n\tconst flush = (kind: \"fuzzy\" | \"phrase\"): void => {\n\t\tconst v = buf.trim();\n\t\tbuf = \"\";\n\t\tif (!v) return;\n\t\ttokens.push({ kind, value: v });\n\t};\n\n\tfor (let i = 0; i < trimmed.length; i++) {\n\t\tconst ch = trimmed[i]!;\n\t\tif (ch === '\"') {\n\t\t\tif (inQuote) {\n\t\t\t\tflush(\"phrase\");\n\t\t\t\tinQuote = false;\n\t\t\t} else {\n\t\t\t\tflush(\"fuzzy\");\n\t\t\t\tinQuote = true;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!inQuote && /\\s/.test(ch)) {\n\t\t\tflush(\"fuzzy\");\n\t\t\tcontinue;\n\t\t}\n\n\t\tbuf += ch;\n\t}\n\n\tif (inQuote) {\n\t\thadUnclosedQuote = true;\n\t}\n\n\t// If quotes were unbalanced, fall back to plain whitespace tokenization.\n\tif (hadUnclosedQuote) {\n\t\treturn {\n\t\t\tmode: \"tokens\",\n\t\t\ttokens: trimmed\n\t\t\t\t.split(/\\s+/)\n\t\t\t\t.map((t) => t.trim())\n\t\t\t\t.filter((t) => t.length > 0)\n\t\t\t\t.map((t) => ({ kind: \"fuzzy\" as const, value: t })),\n\t\t\tregex: null,\n\t\t};\n\t}\n\n\tflush(inQuote ? \"phrase\" : \"fuzzy\");\n\n\treturn { mode: \"tokens\", tokens, regex: null };\n}\n\nexport function matchSession(session: SessionInfo, parsed: ParsedSearchQuery): MatchResult {\n\tconst text = getSessionSearchText(session);\n\n\tif (parsed.mode === \"regex\") {\n\t\tif (!parsed.regex) {\n\t\t\treturn { matches: false, score: 0 };\n\t\t}\n\t\tconst idx = text.search(parsed.regex);\n\t\tif (idx < 0) return { matches: false, score: 0 };\n\t\treturn { matches: true, score: idx * 0.1 };\n\t}\n\n\tif (parsed.tokens.length === 0) {\n\t\treturn { matches: true, score: 0 };\n\t}\n\n\tlet totalScore = 0;\n\tlet normalizedText: string | null = null;\n\n\tfor (const token of parsed.tokens) {\n\t\tif (token.kind === \"phrase\") {\n\t\t\tif (normalizedText === null) {\n\t\t\t\tnormalizedText = normalizeWhitespaceLower(text);\n\t\t\t}\n\t\t\tconst phrase = normalizeWhitespaceLower(token.value);\n\t\t\tif (!phrase) continue;\n\t\t\tconst idx = normalizedText.indexOf(phrase);\n\t\t\tif (idx < 0) return { matches: false, score: 0 };\n\t\t\ttotalScore += idx * 0.1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst m = fuzzyMatch(token.value, text);\n\t\tif (!m.matches) return { matches: false, score: 0 };\n\t\ttotalScore += m.score;\n\t}\n\n\treturn { matches: true, score: totalScore };\n}\n\nexport function filterAndSortSessions(\n\tsessions: SessionInfo[],\n\tquery: string,\n\tsortMode: SortMode,\n\tnameFilter: NameFilter = \"all\",\n): SessionInfo[] {\n\tconst nameFiltered =\n\t\tnameFilter === \"all\" ? sessions : sessions.filter((session) => matchesNameFilter(session, nameFilter));\n\tconst trimmed = query.trim();\n\tif (!trimmed) return nameFiltered;\n\n\tconst parsed = parseSearchQuery(query);\n\tif (parsed.error) return [];\n\n\t// Recent mode: filter only, keep incoming order.\n\tif (sortMode === \"recent\") {\n\t\tconst filtered: SessionInfo[] = [];\n\t\tfor (const s of nameFiltered) {\n\t\t\tconst res = matchSession(s, parsed);\n\t\t\tif (res.matches) filtered.push(s);\n\t\t}\n\t\treturn filtered;\n\t}\n\n\t// Relevance mode: sort by score, tie-break by modified desc.\n\tconst scored: { session: SessionInfo; score: number }[] = [];\n\tfor (const s of nameFiltered) {\n\t\tconst res = matchSession(s, parsed);\n\t\tif (!res.matches) continue;\n\t\tscored.push({ session: s, score: res.score });\n\t}\n\n\tscored.sort((a, b) => {\n\t\tif (a.score !== b.score) return a.score - b.score;\n\t\treturn b.session.modified.getTime() - a.session.modified.getTime();\n\t});\n\n\treturn scored.map((r) => r.session);\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/session-selector.d.ts b/dist/modes/interactive/components/session-selector.d.ts new file mode 100644 index 0000000..2808ca5 --- /dev/null +++ b/dist/modes/interactive/components/session-selector.d.ts @@ -0,0 +1,95 @@ +import { type Component, Container, type Focusable } from "@earendil-works/pi-tui"; +import { KeybindingsManager } from "../../../core/keybindings.ts"; +import type { SessionInfo, SessionListProgress } from "../../../core/session-manager.ts"; +import { type NameFilter, type SortMode } from "./session-selector-search.ts"; +/** + * Custom session list component with multi-line items and search + */ +declare class SessionList implements Component, Focusable { + getSelectedSessionPath(): string | undefined; + private allSessions; + private filteredSessions; + private selectedIndex; + private searchInput; + private showCwd; + private sortMode; + private nameFilter; + private keybindings; + private showPath; + private confirmingDeletePath; + private currentSessionCanonicalPath?; + onSelect?: (sessionPath: string) => void; + onCancel?: () => void; + onExit: () => void; + onToggleScope?: () => void; + onToggleSort?: () => void; + onToggleNameFilter?: () => void; + onTogglePath?: (showPath: boolean) => void; + onDeleteConfirmationChange?: (path: string | null) => void; + onDeleteSession?: (sessionPath: string) => Promise; + onRenameSession?: (sessionPath: string) => void; + onError?: (message: string) => void; + private maxVisible; + private _focused; + get focused(): boolean; + set focused(value: boolean); + constructor(sessions: SessionInfo[], showCwd: boolean, sortMode: SortMode, nameFilter: NameFilter, keybindings: KeybindingsManager, currentSessionFilePath?: string); + setSortMode(sortMode: SortMode): void; + setNameFilter(nameFilter: NameFilter): void; + setSessions(sessions: SessionInfo[], showCwd: boolean): void; + private filterSessions; + private setConfirmingDeletePath; + private startDeleteConfirmationForSelectedSession; + private isCurrentSessionPath; + invalidate(): void; + render(width: number): string[]; + private buildTreePrefix; + handleInput(keyData: string): void; +} +type SessionsLoader = (onProgress?: SessionListProgress) => Promise; +/** + * Component that renders a session selector + */ +export declare class SessionSelectorComponent extends Container implements Focusable { + handleInput(data: string): void; + private canRename; + private sessionList; + private header; + private keybindings; + private scope; + private sortMode; + private nameFilter; + private currentSessions; + private allSessions; + private currentSessionsLoader; + private allSessionsLoader; + private requestRender; + private renameSession?; + private currentLoading; + private allLoading; + private allLoadSeq; + private mode; + private renameInput; + private renameTargetPath; + private _focused; + get focused(): boolean; + set focused(value: boolean); + private buildBaseLayout; + constructor(currentSessionsLoader: SessionsLoader, allSessionsLoader: SessionsLoader, onSelect: (sessionPath: string) => void, onCancel: () => void, onExit: () => void, requestRender: () => void, options?: { + renameSession?: (sessionPath: string, currentName: string | undefined) => Promise; + showRenameHint?: boolean; + keybindings?: KeybindingsManager; + }, currentSessionFilePath?: string); + private loadCurrentSessions; + private enterRenameMode; + private exitRenameMode; + private confirmRename; + private loadScope; + private toggleSortMode; + private toggleNameFilter; + private refreshSessionsAfterMutation; + private toggleScope; + getSessionList(): SessionList; +} +export {}; +//# sourceMappingURL=session-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/session-selector.d.ts.map b/dist/modes/interactive/components/session-selector.d.ts.map new file mode 100644 index 0000000..e30104f --- /dev/null +++ b/dist/modes/interactive/components/session-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"session-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/session-selector.ts"],"names":[],"mappings":"AAIA,OAAO,EACN,KAAK,SAAS,EACd,SAAS,EACT,KAAK,SAAS,EAOd,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,k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";\nimport { existsSync } from \"node:fs\";\nimport { unlink } from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport {\n\ttype Component,\n\tContainer,\n\ttype Focusable,\n\tgetKeybindings,\n\tInput,\n\tSpacer,\n\tText,\n\ttruncateToWidth,\n\tvisibleWidth,\n} from \"@earendil-works/pi-tui\";\nimport { KeybindingsManager } from \"../../../core/keybindings.ts\";\nimport type { SessionInfo, SessionListProgress } from \"../../../core/session-manager.ts\";\nimport { canonicalizePath as _canonicalizePath } from \"../../../utils/paths.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint, keyText } from \"./keybinding-hints.ts\";\nimport { filterAndSortSessions, hasSessionName, type NameFilter, type SortMode } from \"./session-selector-search.ts\";\n\ntype SessionScope = \"current\" | \"all\";\n\nfunction shortenPath(path: string): string {\n\tconst home = os.homedir();\n\tif (!path) return path;\n\tif (path.startsWith(home)) {\n\t\treturn `~${path.slice(home.length)}`;\n\t}\n\treturn path;\n}\n\nfunction formatSessionDate(date: Date): string {\n\tconst now = new Date();\n\tconst diffMs = now.getTime() - date.getTime();\n\tconst diffMins = Math.floor(diffMs / 60000);\n\tconst diffHours = Math.floor(diffMs / 3600000);\n\tconst diffDays = Math.floor(diffMs / 86400000);\n\n\tif (diffMins < 1) return \"now\";\n\tif (diffMins < 60) return `${diffMins}m`;\n\tif (diffHours < 24) return `${diffHours}h`;\n\tif (diffDays < 7) return `${diffDays}d`;\n\tif (diffDays < 30) return `${Math.floor(diffDays / 7)}w`;\n\tif (diffDays < 365) return `${Math.floor(diffDays / 30)}mo`;\n\treturn `${Math.floor(diffDays / 365)}y`;\n}\n\nfunction canonicalizePath(path: string | undefined): string | undefined {\n\tif (!path) return path;\n\treturn _canonicalizePath(path);\n}\n\nclass SessionSelectorHeader implements Component {\n\tprivate scope: SessionScope;\n\tprivate sortMode: SortMode;\n\tprivate nameFilter: NameFilter;\n\tprivate requestRender: () => void;\n\tprivate loading = false;\n\tprivate loadProgress: { loaded: number; total: number } | null = null;\n\tprivate showPath = false;\n\tprivate confirmingDeletePath: string | null = null;\n\tprivate statusMessage: { type: \"info\" | \"error\"; message: string } | null = null;\n\tprivate statusTimeout: ReturnType | null = null;\n\tprivate showRenameHint = false;\n\n\tconstructor(scope: SessionScope, sortMode: SortMode, nameFilter: NameFilter, requestRender: () => void) {\n\t\tthis.scope = scope;\n\t\tthis.sortMode = sortMode;\n\t\tthis.nameFilter = nameFilter;\n\t\tthis.requestRender = requestRender;\n\t}\n\n\tsetScope(scope: SessionScope): void {\n\t\tthis.scope = scope;\n\t}\n\n\tsetSortMode(sortMode: SortMode): void {\n\t\tthis.sortMode = sortMode;\n\t}\n\n\tsetNameFilter(nameFilter: NameFilter): void {\n\t\tthis.nameFilter = nameFilter;\n\t}\n\n\tsetLoading(loading: boolean): void {\n\t\tthis.loading = loading;\n\t\t// Progress is scoped to the current load; clear whenever the loading state is set\n\t\tthis.loadProgress = null;\n\t}\n\n\tsetProgress(loaded: number, total: number): void {\n\t\tthis.loadProgress = { loaded, total };\n\t}\n\n\tsetShowPath(showPath: boolean): void {\n\t\tthis.showPath = showPath;\n\t}\n\n\tsetShowRenameHint(show: boolean): void {\n\t\tthis.showRenameHint = show;\n\t}\n\n\tsetConfirmingDeletePath(path: string | null): void {\n\t\tthis.confirmingDeletePath = path;\n\t}\n\n\tprivate clearStatusTimeout(): void {\n\t\tif (!this.statusTimeout) return;\n\t\tclearTimeout(this.statusTimeout);\n\t\tthis.statusTimeout = null;\n\t}\n\n\tsetStatusMessage(msg: { type: \"info\" | \"error\"; message: string } | null, autoHideMs?: number): void {\n\t\tthis.clearStatusTimeout();\n\t\tthis.statusMessage = msg;\n\t\tif (!msg || !autoHideMs) return;\n\n\t\tthis.statusTimeout = setTimeout(() => {\n\t\t\tthis.statusMessage = null;\n\t\t\tthis.statusTimeout = null;\n\t\t\tthis.requestRender();\n\t\t}, autoHideMs);\n\t}\n\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst title = this.scope === \"current\" ? \"Resume Session (Current Folder)\" : \"Resume Session (All)\";\n\t\tconst leftText = theme.bold(title);\n\n\t\tconst sortLabel = this.sortMode === \"threaded\" ? \"Threaded\" : this.sortMode === \"recent\" ? \"Recent\" : \"Fuzzy\";\n\t\tconst sortText = theme.fg(\"muted\", \"Sort: \") + theme.fg(\"accent\", sortLabel);\n\n\t\tconst nameLabel = this.nameFilter === \"all\" ? \"All\" : \"Named\";\n\t\tconst nameText = theme.fg(\"muted\", \"Name: \") + theme.fg(\"accent\", nameLabel);\n\n\t\tlet scopeText: string;\n\t\tif (this.loading) {\n\t\t\tconst progressText = this.loadProgress ? `${this.loadProgress.loaded}/${this.loadProgress.total}` : \"...\";\n\t\t\tscopeText = `${theme.fg(\"muted\", \"○ Current Folder | \")}${theme.fg(\"accent\", `Loading ${progressText}`)}`;\n\t\t} else if (this.scope === \"current\") {\n\t\t\tscopeText = `${theme.fg(\"accent\", \"◉ Current Folder\")}${theme.fg(\"muted\", \" | ○ All\")}`;\n\t\t} else {\n\t\t\tscopeText = `${theme.fg(\"muted\", \"○ Current Folder | \")}${theme.fg(\"accent\", \"◉ All\")}`;\n\t\t}\n\n\t\tconst rightText = truncateToWidth(`${scopeText} ${nameText} ${sortText}`, width, \"\");\n\t\tconst availableLeft = Math.max(0, width - visibleWidth(rightText) - 1);\n\t\tconst left = truncateToWidth(leftText, availableLeft, \"\");\n\t\tconst spacing = Math.max(0, width - visibleWidth(left) - visibleWidth(rightText));\n\n\t\t// Build hint lines - changes based on state (all branches truncate to width)\n\t\tlet hintLine1: string;\n\t\tlet hintLine2: string;\n\t\tif (this.confirmingDeletePath !== null) {\n\t\t\tconst confirmHint = `Delete session? ${keyHint(\"tui.select.confirm\", \"confirm\")} · ${keyHint(\"tui.select.cancel\", \"cancel\")}`;\n\t\t\thintLine1 = theme.fg(\"error\", truncateToWidth(confirmHint, width, \"…\"));\n\t\t\thintLine2 = \"\";\n\t\t} else if (this.statusMessage) {\n\t\t\tconst color = this.statusMessage.type === \"error\" ? \"error\" : \"accent\";\n\t\t\thintLine1 = theme.fg(color, truncateToWidth(this.statusMessage.message, width, \"…\"));\n\t\t\thintLine2 = \"\";\n\t\t} else {\n\t\t\tconst pathState = this.showPath ? \"(on)\" : \"(off)\";\n\t\t\tconst sep = theme.fg(\"muted\", \" · \");\n\t\t\tconst hint1 =\n\t\t\t\tkeyHint(\"tui.input.tab\", \"scope\") + sep + theme.fg(\"muted\", 're: regex · \"phrase\" exact');\n\t\t\tconst hint2Parts = [\n\t\t\t\tkeyHint(\"app.session.toggleSort\", \"sort\"),\n\t\t\t\tkeyHint(\"app.session.toggleNamedFilter\", \"named\"),\n\t\t\t\tkeyHint(\"app.session.delete\", \"delete\"),\n\t\t\t\tkeyHint(\"app.session.togglePath\", `path ${pathState}`),\n\t\t\t];\n\t\t\tif (this.showRenameHint) {\n\t\t\t\thint2Parts.push(keyHint(\"app.session.rename\", \"rename\"));\n\t\t\t}\n\t\t\tconst hint2 = hint2Parts.join(sep);\n\t\t\thintLine1 = truncateToWidth(hint1, width, \"…\");\n\t\t\thintLine2 = truncateToWidth(hint2, width, \"…\");\n\t\t}\n\n\t\treturn [`${left}${\" \".repeat(spacing)}${rightText}`, hintLine1, hintLine2];\n\t}\n}\n\n/** A session tree node for hierarchical display */\ninterface SessionTreeNode {\n\tsession: SessionInfo;\n\tchildren: SessionTreeNode[];\n\tlatestActivity: number;\n}\n\n/** Flattened node for display with tree structure info */\ninterface FlatSessionNode {\n\tsession: SessionInfo;\n\tdepth: number;\n\tisLast: boolean;\n\t/** For each ancestor level, whether there are more siblings after it */\n\tancestorContinues: boolean[];\n}\n\n/**\n * Build a tree structure from sessions based on parentSessionPath.\n * Returns root nodes sorted by modified date (descending).\n */\nfunction buildSessionTree(sessions: SessionInfo[]): SessionTreeNode[] {\n\tconst byPath = new Map();\n\n\tfor (const session of sessions) {\n\t\tconst sessionPath = canonicalizePath(session.path) ?? session.path;\n\t\tbyPath.set(sessionPath, { session, children: [], latestActivity: session.modified.getTime() });\n\t}\n\n\tconst roots: SessionTreeNode[] = [];\n\n\tfor (const session of sessions) {\n\t\tconst sessionPath = canonicalizePath(session.path) ?? session.path;\n\t\tconst node = byPath.get(sessionPath)!;\n\t\tconst parentPath = canonicalizePath(session.parentSessionPath);\n\n\t\tif (parentPath && byPath.has(parentPath)) {\n\t\t\tbyPath.get(parentPath)!.children.push(node);\n\t\t} else {\n\t\t\troots.push(node);\n\t\t}\n\t}\n\n\tconst updateLatestActivity = (node: SessionTreeNode): number => {\n\t\tlet latestActivity = node.session.modified.getTime();\n\t\tfor (const child of node.children) {\n\t\t\tlatestActivity = Math.max(latestActivity, updateLatestActivity(child));\n\t\t}\n\t\tnode.latestActivity = latestActivity;\n\t\treturn latestActivity;\n\t};\n\n\tfor (const root of roots) {\n\t\tupdateLatestActivity(root);\n\t}\n\n\t// Sort children and roots by latest activity in each subtree (descending)\n\tconst sortNodes = (nodes: SessionTreeNode[]): void => {\n\t\tnodes.sort((a, b) => b.latestActivity - a.latestActivity);\n\t\tfor (const node of nodes) {\n\t\t\tsortNodes(node.children);\n\t\t}\n\t};\n\tsortNodes(roots);\n\n\treturn roots;\n}\n\n/**\n * Flatten tree into display list with tree structure metadata.\n */\nfunction flattenSessionTree(roots: SessionTreeNode[]): FlatSessionNode[] {\n\tconst result: FlatSessionNode[] = [];\n\n\tconst walk = (node: SessionTreeNode, depth: number, ancestorContinues: boolean[], isLast: boolean): void => {\n\t\tresult.push({ session: node.session, depth, isLast, ancestorContinues });\n\n\t\tfor (let i = 0; i < node.children.length; i++) {\n\t\t\tconst childIsLast = i === node.children.length - 1;\n\t\t\t// Only show continuation line for non-root ancestors\n\t\t\tconst continues = depth > 0 ? !isLast : false;\n\t\t\twalk(node.children[i]!, depth + 1, [...ancestorContinues, continues], childIsLast);\n\t\t}\n\t};\n\n\tfor (let i = 0; i < roots.length; i++) {\n\t\twalk(roots[i]!, 0, [], i === roots.length - 1);\n\t}\n\n\treturn result;\n}\n\n/**\n * Custom session list component with multi-line items and search\n */\nclass SessionList implements Component, Focusable {\n\tpublic getSelectedSessionPath(): string | undefined {\n\t\tconst selected = this.filteredSessions[this.selectedIndex];\n\t\treturn selected?.session.path;\n\t}\n\tprivate allSessions: SessionInfo[] = [];\n\tprivate filteredSessions: FlatSessionNode[] = [];\n\tprivate selectedIndex: number = 0;\n\tprivate searchInput: Input;\n\tprivate showCwd = false;\n\tprivate sortMode: SortMode = \"threaded\";\n\tprivate nameFilter: NameFilter = \"all\";\n\tprivate keybindings: KeybindingsManager;\n\tprivate showPath = false;\n\tprivate confirmingDeletePath: string | null = null;\n\tprivate currentSessionCanonicalPath?: string;\n\tpublic onSelect?: (sessionPath: string) => void;\n\tpublic onCancel?: () => void;\n\tpublic onExit: () => void = () => {};\n\tpublic onToggleScope?: () => void;\n\tpublic onToggleSort?: () => void;\n\tpublic onToggleNameFilter?: () => void;\n\tpublic onTogglePath?: (showPath: boolean) => void;\n\tpublic onDeleteConfirmationChange?: (path: string | null) => void;\n\tpublic onDeleteSession?: (sessionPath: string) => Promise;\n\tpublic onRenameSession?: (sessionPath: string) => void;\n\tpublic onError?: (message: string) => void;\n\tprivate maxVisible: number = 10; // Max sessions visible (one line each)\n\n\t// Focusable implementation - propagate to searchInput for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.searchInput.focused = value;\n\t}\n\n\tconstructor(\n\t\tsessions: SessionInfo[],\n\t\tshowCwd: boolean,\n\t\tsortMode: SortMode,\n\t\tnameFilter: NameFilter,\n\t\tkeybindings: KeybindingsManager,\n\t\tcurrentSessionFilePath?: string,\n\t) {\n\t\tthis.allSessions = sessions;\n\t\tthis.filteredSessions = [];\n\t\tthis.searchInput = new Input();\n\t\tthis.showCwd = showCwd;\n\t\tthis.sortMode = sortMode;\n\t\tthis.nameFilter = nameFilter;\n\t\tthis.keybindings = keybindings;\n\t\tthis.currentSessionCanonicalPath = canonicalizePath(currentSessionFilePath);\n\t\tthis.filterSessions(\"\");\n\n\t\t// Handle Enter in search input - select current item\n\t\tthis.searchInput.onSubmit = () => {\n\t\t\tif (this.filteredSessions[this.selectedIndex]) {\n\t\t\t\tconst selected = this.filteredSessions[this.selectedIndex];\n\t\t\t\tif (this.onSelect) {\n\t\t\t\t\tthis.onSelect(selected.session.path);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\n\tsetSortMode(sortMode: SortMode): void {\n\t\tthis.sortMode = sortMode;\n\t\tthis.filterSessions(this.searchInput.getValue());\n\t}\n\n\tsetNameFilter(nameFilter: NameFilter): void {\n\t\tthis.nameFilter = nameFilter;\n\t\tthis.filterSessions(this.searchInput.getValue());\n\t}\n\n\tsetSessions(sessions: SessionInfo[], showCwd: boolean): void {\n\t\tthis.allSessions = sessions;\n\t\tthis.showCwd = showCwd;\n\t\tthis.filterSessions(this.searchInput.getValue());\n\t}\n\n\tprivate filterSessions(query: string): void {\n\t\tconst trimmed = query.trim();\n\t\tconst nameFiltered =\n\t\t\tthis.nameFilter === \"all\" ? this.allSessions : this.allSessions.filter((session) => hasSessionName(session));\n\n\t\tif (this.sortMode === \"threaded\" && !trimmed) {\n\t\t\t// Threaded mode without search: show tree structure\n\t\t\tconst roots = buildSessionTree(nameFiltered);\n\t\t\tthis.filteredSessions = flattenSessionTree(roots);\n\t\t} else {\n\t\t\t// Other modes or with search: flat list\n\t\t\tconst filtered = filterAndSortSessions(nameFiltered, query, this.sortMode, \"all\");\n\t\t\tthis.filteredSessions = filtered.map((session) => ({\n\t\t\t\tsession,\n\t\t\t\tdepth: 0,\n\t\t\t\tisLast: true,\n\t\t\t\tancestorContinues: [],\n\t\t\t}));\n\t\t}\n\t\tthis.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredSessions.length - 1));\n\t}\n\n\tprivate setConfirmingDeletePath(path: string | null): void {\n\t\tthis.confirmingDeletePath = path;\n\t\tthis.onDeleteConfirmationChange?.(path);\n\t}\n\n\tprivate startDeleteConfirmationForSelectedSession(): void {\n\t\tconst selected = this.filteredSessions[this.selectedIndex];\n\t\tif (!selected) return;\n\n\t\t// Prevent deleting current session\n\t\tif (this.isCurrentSessionPath(selected.session.path)) {\n\t\t\tthis.onError?.(\"Cannot delete the currently active session\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.setConfirmingDeletePath(selected.session.path);\n\t}\n\n\tprivate isCurrentSessionPath(path: string): boolean {\n\t\tif (!this.currentSessionCanonicalPath) return false;\n\t\treturn (canonicalizePath(path) ?? path) === this.currentSessionCanonicalPath;\n\t}\n\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\n\t\t// Render search input\n\t\tlines.push(...this.searchInput.render(width));\n\t\tlines.push(\"\"); // Blank line after search\n\n\t\tif (this.filteredSessions.length === 0) {\n\t\t\tlet emptyMessage: string;\n\t\t\tif (this.nameFilter === \"named\") {\n\t\t\t\tconst toggleKey = keyText(\"app.session.toggleNamedFilter\");\n\t\t\t\tif (this.showCwd) {\n\t\t\t\t\temptyMessage = ` No named sessions found. Press ${toggleKey} to show all.`;\n\t\t\t\t} else {\n\t\t\t\t\temptyMessage = ` No named sessions in current folder. Press ${toggleKey} to show all, or Tab to view all.`;\n\t\t\t\t}\n\t\t\t} else if (this.showCwd) {\n\t\t\t\t// \"All\" scope - no sessions anywhere that match filter\n\t\t\t\temptyMessage = \" No sessions found\";\n\t\t\t} else {\n\t\t\t\t// \"Current folder\" scope - hint to try \"all\"\n\t\t\t\temptyMessage = \" No sessions in current folder. Press Tab to view all.\";\n\t\t\t}\n\t\t\tlines.push(theme.fg(\"muted\", truncateToWidth(emptyMessage, width, \"…\")));\n\t\t\treturn lines;\n\t\t}\n\n\t\t// Calculate visible range with scrolling\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredSessions.length - this.maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisible, this.filteredSessions.length);\n\n\t\t// Render visible sessions (one line each with tree structure)\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst node = this.filteredSessions[i]!;\n\t\t\tconst session = node.session;\n\t\t\tconst isSelected = i === this.selectedIndex;\n\t\t\tconst isConfirmingDelete = session.path === this.confirmingDeletePath;\n\t\t\tconst isCurrent = this.isCurrentSessionPath(session.path);\n\n\t\t\t// Build tree prefix\n\t\t\tconst prefix = this.buildTreePrefix(node);\n\n\t\t\t// Session display text (name or first message)\n\t\t\tconst hasName = !!session.name;\n\t\t\tconst displayText = session.name ?? session.firstMessage;\n\t\t\tconst normalizedMessage = displayText.replace(/[\\x00-\\x1f\\x7f]/g, \" \").trim();\n\n\t\t\t// Right side: message count and age\n\t\t\tconst age = formatSessionDate(session.modified);\n\t\t\tconst msgCount = String(session.messageCount);\n\t\t\tlet rightPart = `${msgCount} ${age}`;\n\t\t\tif (this.showCwd && session.cwd) {\n\t\t\t\trightPart = `${shortenPath(session.cwd)} ${rightPart}`;\n\t\t\t}\n\t\t\tif (this.showPath) {\n\t\t\t\trightPart = `${shortenPath(session.path)} ${rightPart}`;\n\t\t\t}\n\n\t\t\t// Cursor\n\t\t\tconst cursor = isSelected ? theme.fg(\"accent\", \"› \") : \" \";\n\n\t\t\t// Calculate available width for message\n\t\t\tconst prefixWidth = visibleWidth(prefix);\n\t\t\tconst rightWidth = visibleWidth(rightPart) + 2; // +2 for spacing\n\t\t\tconst availableForMsg = width - 2 - prefixWidth - rightWidth; // -2 for cursor\n\n\t\t\tconst truncatedMsg = truncateToWidth(normalizedMessage, Math.max(10, availableForMsg), \"…\");\n\n\t\t\t// Style message\n\t\t\tlet messageColor: \"error\" | \"warning\" | \"accent\" | null = null;\n\t\t\tif (isConfirmingDelete) {\n\t\t\t\tmessageColor = \"error\";\n\t\t\t} else if (isCurrent) {\n\t\t\t\tmessageColor = \"accent\";\n\t\t\t} else if (hasName) {\n\t\t\t\tmessageColor = \"warning\";\n\t\t\t}\n\t\t\tlet styledMsg = messageColor ? theme.fg(messageColor, truncatedMsg) : truncatedMsg;\n\t\t\tif (isSelected) {\n\t\t\t\tstyledMsg = theme.bold(styledMsg);\n\t\t\t}\n\n\t\t\t// Build line\n\t\t\tconst leftPart = cursor + theme.fg(\"dim\", prefix) + styledMsg;\n\t\t\tconst leftWidth = visibleWidth(leftPart);\n\t\t\tconst spacing = Math.max(1, width - leftWidth - visibleWidth(rightPart));\n\t\t\tconst styledRight = theme.fg(isConfirmingDelete ? \"error\" : \"dim\", rightPart);\n\n\t\t\tlet line = leftPart + \" \".repeat(spacing) + styledRight;\n\t\t\tif (isSelected) {\n\t\t\t\tline = theme.bg(\"selectedBg\", line);\n\t\t\t}\n\t\t\tlines.push(truncateToWidth(line, width));\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.filteredSessions.length) {\n\t\t\tconst scrollText = ` (${this.selectedIndex + 1}/${this.filteredSessions.length})`;\n\t\t\tconst scrollInfo = theme.fg(\"muted\", truncateToWidth(scrollText, width, \"\"));\n\t\t\tlines.push(scrollInfo);\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\tprivate buildTreePrefix(node: FlatSessionNode): string {\n\t\tif (node.depth === 0) {\n\t\t\treturn \"\";\n\t\t}\n\n\t\tconst parts = node.ancestorContinues.map((continues) => (continues ? \"│ \" : \" \"));\n\t\tconst branch = node.isLast ? \"└─ \" : \"├─ \";\n\t\treturn parts.join(\"\") + branch;\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\n\t\t// Handle delete confirmation state first - intercept all keys\n\t\tif (this.confirmingDeletePath !== null) {\n\t\t\tif (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\t\tconst pathToDelete = this.confirmingDeletePath;\n\t\t\t\tthis.setConfirmingDeletePath(null);\n\t\t\t\tvoid this.onDeleteSession?.(pathToDelete);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\t\tthis.setConfirmingDeletePath(null);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Ignore all other keys while confirming\n\t\t\treturn;\n\t\t}\n\n\t\tif (kb.matches(keyData, \"tui.input.tab\")) {\n\t\t\tif (this.onToggleScope) {\n\t\t\t\tthis.onToggleScope();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (kb.matches(keyData, \"app.session.toggleSort\")) {\n\t\t\tthis.onToggleSort?.();\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.keybindings.matches(keyData, \"app.session.toggleNamedFilter\")) {\n\t\t\tthis.onToggleNameFilter?.();\n\t\t\treturn;\n\t\t}\n\n\t\t// Ctrl+P: toggle path display\n\t\tif (kb.matches(keyData, \"app.session.togglePath\")) {\n\t\t\tthis.showPath = !this.showPath;\n\t\t\tthis.onTogglePath?.(this.showPath);\n\t\t\treturn;\n\t\t}\n\n\t\t// Ctrl+D: initiate delete confirmation (useful on terminals that don't distinguish Ctrl+Backspace from Backspace)\n\t\tif (kb.matches(keyData, \"app.session.delete\")) {\n\t\t\tthis.startDeleteConfirmationForSelectedSession();\n\t\t\treturn;\n\t\t}\n\n\t\t// Rename selected session\n\t\tif (kb.matches(keyData, \"app.session.rename\")) {\n\t\t\tconst selected = this.filteredSessions[this.selectedIndex];\n\t\t\tif (selected) {\n\t\t\t\tthis.onRenameSession?.(selected.session.path);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Ctrl+Backspace: non-invasive convenience alias for delete\n\t\t// Only triggers deletion when the query is empty; otherwise it is forwarded to the input\n\t\tif (kb.matches(keyData, \"app.session.deleteNoninvasive\")) {\n\t\t\tif (this.searchInput.getValue().length > 0) {\n\t\t\t\tthis.searchInput.handleInput(keyData);\n\t\t\t\tthis.filterSessions(this.searchInput.getValue());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.startDeleteConfirmationForSelectedSession();\n\t\t\treturn;\n\t\t}\n\n\t\t// Up arrow\n\t\tif (kb.matches(keyData, \"tui.select.up\")) {\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - 1);\n\t\t}\n\t\t// Down arrow\n\t\telse if (kb.matches(keyData, \"tui.select.down\")) {\n\t\t\tthis.selectedIndex = Math.min(this.filteredSessions.length - 1, this.selectedIndex + 1);\n\t\t}\n\t\t// Page up - jump up by maxVisible items\n\t\telse if (kb.matches(keyData, \"tui.select.pageUp\")) {\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - this.maxVisible);\n\t\t}\n\t\t// Page down - jump down by maxVisible items\n\t\telse if (kb.matches(keyData, \"tui.select.pageDown\")) {\n\t\t\tthis.selectedIndex = Math.min(this.filteredSessions.length - 1, this.selectedIndex + this.maxVisible);\n\t\t}\n\t\t// Enter\n\t\telse if (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\tconst selected = this.filteredSessions[this.selectedIndex];\n\t\t\tif (selected && this.onSelect) {\n\t\t\t\tthis.onSelect(selected.session.path);\n\t\t\t}\n\t\t}\n\t\t// Escape - cancel\n\t\telse if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tif (this.onCancel) {\n\t\t\t\tthis.onCancel();\n\t\t\t}\n\t\t}\n\t\t// Pass everything else to search input\n\t\telse {\n\t\t\tthis.searchInput.handleInput(keyData);\n\t\t\tthis.filterSessions(this.searchInput.getValue());\n\t\t}\n\t}\n}\n\ntype SessionsLoader = (onProgress?: SessionListProgress) => Promise;\n\n/**\n * Delete a session file, trying the `trash` CLI first, then falling back to unlink\n */\nasync function deleteSessionFile(\n\tsessionPath: string,\n): Promise<{ ok: boolean; method: \"trash\" | \"unlink\"; error?: string }> {\n\t// Try `trash` first (if installed)\n\tconst trashArgs = sessionPath.startsWith(\"-\") ? [\"--\", sessionPath] : [sessionPath];\n\tconst trashResult = spawnSync(\"trash\", trashArgs, { encoding: \"utf-8\" });\n\n\tconst getTrashErrorHint = (): string | null => {\n\t\tconst parts: string[] = [];\n\t\tif (trashResult.error) {\n\t\t\tparts.push(trashResult.error.message);\n\t\t}\n\t\tconst stderr = trashResult.stderr?.trim();\n\t\tif (stderr) {\n\t\t\tparts.push(stderr.split(\"\\n\")[0] ?? stderr);\n\t\t}\n\t\tif (parts.length === 0) return null;\n\t\treturn `trash: ${parts.join(\" · \").slice(0, 200)}`;\n\t};\n\n\t// If trash reports success, or the file is gone afterwards, treat it as successful\n\tif (trashResult.status === 0 || !existsSync(sessionPath)) {\n\t\treturn { ok: true, method: \"trash\" };\n\t}\n\n\t// Fallback to permanent deletion\n\ttry {\n\t\tawait unlink(sessionPath);\n\t\treturn { ok: true, method: \"unlink\" };\n\t} catch (err) {\n\t\tconst unlinkError = err instanceof Error ? err.message : String(err);\n\t\tconst trashErrorHint = getTrashErrorHint();\n\t\tconst error = trashErrorHint ? `${unlinkError} (${trashErrorHint})` : unlinkError;\n\t\treturn { ok: false, method: \"unlink\", error };\n\t}\n}\n\n/**\n * Component that renders a session selector\n */\nexport class SessionSelectorComponent extends Container implements Focusable {\n\thandleInput(data: string): void {\n\t\tif (this.mode === \"rename\") {\n\t\t\tconst kb = getKeybindings();\n\t\t\tif (kb.matches(data, \"tui.select.cancel\")) {\n\t\t\t\tthis.exitRenameMode();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.renameInput.handleInput(data);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.sessionList.handleInput(data);\n\t}\n\n\tprivate canRename = true;\n\tprivate sessionList: SessionList;\n\tprivate header: SessionSelectorHeader;\n\tprivate keybindings: KeybindingsManager;\n\tprivate scope: SessionScope = \"current\";\n\tprivate sortMode: SortMode = \"threaded\";\n\tprivate nameFilter: NameFilter = \"all\";\n\tprivate currentSessions: SessionInfo[] | null = null;\n\tprivate allSessions: SessionInfo[] | null = null;\n\tprivate currentSessionsLoader: SessionsLoader;\n\tprivate allSessionsLoader: SessionsLoader;\n\tprivate requestRender: () => void;\n\tprivate renameSession?: (sessionPath: string, currentName: string | undefined) => Promise;\n\tprivate currentLoading = false;\n\tprivate allLoading = false;\n\tprivate allLoadSeq = 0;\n\n\tprivate mode: \"list\" | \"rename\" = \"list\";\n\tprivate renameInput = new Input();\n\tprivate renameTargetPath: string | null = null;\n\n\t// Focusable implementation - propagate to sessionList for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.sessionList.focused = value;\n\t\tthis.renameInput.focused = value;\n\t\tif (value && this.mode === \"rename\") {\n\t\t\tthis.renameInput.focused = true;\n\t\t}\n\t}\n\n\tprivate buildBaseLayout(content: Component, options?: { showHeader?: boolean }): void {\n\t\tthis.clear();\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder((s) => theme.fg(\"accent\", s)));\n\t\tthis.addChild(new Spacer(1));\n\t\tif (options?.showHeader ?? true) {\n\t\t\tthis.addChild(this.header);\n\t\t\tthis.addChild(new Spacer(1));\n\t\t}\n\t\tthis.addChild(content);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder((s) => theme.fg(\"accent\", s)));\n\t}\n\n\tconstructor(\n\t\tcurrentSessionsLoader: SessionsLoader,\n\t\tallSessionsLoader: SessionsLoader,\n\t\tonSelect: (sessionPath: string) => void,\n\t\tonCancel: () => void,\n\t\tonExit: () => void,\n\t\trequestRender: () => void,\n\t\toptions?: {\n\t\t\trenameSession?: (sessionPath: string, currentName: string | undefined) => Promise;\n\t\t\tshowRenameHint?: boolean;\n\t\t\tkeybindings?: KeybindingsManager;\n\t\t},\n\t\tcurrentSessionFilePath?: string,\n\t) {\n\t\tsuper();\n\t\tthis.keybindings = options?.keybindings ?? KeybindingsManager.create();\n\t\tthis.currentSessionsLoader = currentSessionsLoader;\n\t\tthis.allSessionsLoader = allSessionsLoader;\n\t\tthis.requestRender = requestRender;\n\t\tthis.header = new SessionSelectorHeader(this.scope, this.sortMode, this.nameFilter, this.requestRender);\n\t\tconst renameSession = options?.renameSession;\n\t\tthis.renameSession = renameSession;\n\t\tthis.canRename = !!renameSession;\n\t\tthis.header.setShowRenameHint(options?.showRenameHint ?? this.canRename);\n\n\t\t// Create session list (starts empty, will be populated after load)\n\t\tthis.sessionList = new SessionList(\n\t\t\t[],\n\t\t\tfalse,\n\t\t\tthis.sortMode,\n\t\t\tthis.nameFilter,\n\t\t\tthis.keybindings,\n\t\t\tcurrentSessionFilePath,\n\t\t);\n\n\t\tthis.buildBaseLayout(this.sessionList);\n\n\t\tthis.renameInput.onSubmit = (value) => {\n\t\t\tvoid this.confirmRename(value);\n\t\t};\n\n\t\t// Ensure header status timeouts are cleared when leaving the selector\n\t\tconst clearStatusMessage = () => this.header.setStatusMessage(null);\n\t\tthis.sessionList.onSelect = (sessionPath) => {\n\t\t\tclearStatusMessage();\n\t\t\tonSelect(sessionPath);\n\t\t};\n\t\tthis.sessionList.onCancel = () => {\n\t\t\tclearStatusMessage();\n\t\t\tonCancel();\n\t\t};\n\t\tthis.sessionList.onExit = () => {\n\t\t\tclearStatusMessage();\n\t\t\tonExit();\n\t\t};\n\t\tthis.sessionList.onToggleScope = () => this.toggleScope();\n\t\tthis.sessionList.onToggleSort = () => this.toggleSortMode();\n\t\tthis.sessionList.onToggleNameFilter = () => this.toggleNameFilter();\n\t\tthis.sessionList.onRenameSession = (sessionPath) => {\n\t\t\tif (!renameSession) return;\n\t\t\tif (this.scope === \"current\" && this.currentLoading) return;\n\t\t\tif (this.scope === \"all\" && this.allLoading) return;\n\n\t\t\tconst sessions = this.scope === \"all\" ? (this.allSessions ?? []) : (this.currentSessions ?? []);\n\t\t\tconst session = sessions.find((s) => s.path === sessionPath);\n\t\t\tthis.enterRenameMode(sessionPath, session?.name);\n\t\t};\n\n\t\t// Sync list events to header\n\t\tthis.sessionList.onTogglePath = (showPath) => {\n\t\t\tthis.header.setShowPath(showPath);\n\t\t\tthis.requestRender();\n\t\t};\n\t\tthis.sessionList.onDeleteConfirmationChange = (path) => {\n\t\t\tthis.header.setConfirmingDeletePath(path);\n\t\t\tthis.requestRender();\n\t\t};\n\t\tthis.sessionList.onError = (msg) => {\n\t\t\tthis.header.setStatusMessage({ type: \"error\", message: msg }, 3000);\n\t\t\tthis.requestRender();\n\t\t};\n\n\t\t// Handle session deletion\n\t\tthis.sessionList.onDeleteSession = async (sessionPath: string) => {\n\t\t\tconst result = await deleteSessionFile(sessionPath);\n\n\t\t\tif (result.ok) {\n\t\t\t\tif (this.currentSessions) {\n\t\t\t\t\tthis.currentSessions = this.currentSessions.filter((s) => s.path !== sessionPath);\n\t\t\t\t}\n\t\t\t\tif (this.allSessions) {\n\t\t\t\t\tthis.allSessions = this.allSessions.filter((s) => s.path !== sessionPath);\n\t\t\t\t}\n\n\t\t\t\tconst sessions = this.scope === \"all\" ? (this.allSessions ?? []) : (this.currentSessions ?? []);\n\t\t\t\tconst showCwd = this.scope === \"all\";\n\t\t\t\tthis.sessionList.setSessions(sessions, showCwd);\n\n\t\t\t\tconst msg = result.method === \"trash\" ? \"Session moved to trash\" : \"Session deleted\";\n\t\t\t\tthis.header.setStatusMessage({ type: \"info\", message: msg }, 2000);\n\t\t\t\tawait this.refreshSessionsAfterMutation();\n\t\t\t} else {\n\t\t\t\tconst errorMessage = result.error ?? \"Unknown error\";\n\t\t\t\tthis.header.setStatusMessage({ type: \"error\", message: `Failed to delete: ${errorMessage}` }, 3000);\n\t\t\t}\n\n\t\t\tthis.requestRender();\n\t\t};\n\n\t\t// Start loading current sessions immediately\n\t\tthis.loadCurrentSessions();\n\t}\n\n\tprivate loadCurrentSessions(): void {\n\t\tvoid this.loadScope(\"current\", \"initial\");\n\t}\n\n\tprivate enterRenameMode(sessionPath: string, currentName: string | undefined): void {\n\t\tthis.mode = \"rename\";\n\t\tthis.renameTargetPath = sessionPath;\n\t\tthis.renameInput.setValue(currentName ?? \"\");\n\t\tthis.renameInput.focused = true;\n\n\t\tconst panel = new Container();\n\t\tpanel.addChild(new Text(theme.bold(\"Rename Session\"), 1, 0));\n\t\tpanel.addChild(new Spacer(1));\n\t\tpanel.addChild(this.renameInput);\n\t\tpanel.addChild(new Spacer(1));\n\t\tpanel.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.fg(\"muted\", `${keyText(\"tui.select.confirm\")} to save · ${keyText(\"tui.select.cancel\")} to cancel`),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\n\t\tthis.buildBaseLayout(panel, { showHeader: false });\n\t\tthis.requestRender();\n\t}\n\n\tprivate exitRenameMode(): void {\n\t\tthis.mode = \"list\";\n\t\tthis.renameTargetPath = null;\n\n\t\tthis.buildBaseLayout(this.sessionList);\n\n\t\tthis.requestRender();\n\t}\n\n\tprivate async confirmRename(value: string): Promise {\n\t\tconst next = value.trim();\n\t\tif (!next) return;\n\t\tconst target = this.renameTargetPath;\n\t\tif (!target) {\n\t\t\tthis.exitRenameMode();\n\t\t\treturn;\n\t\t}\n\n\t\t// Find current name for callback\n\t\tconst renameSession = this.renameSession;\n\t\tif (!renameSession) {\n\t\t\tthis.exitRenameMode();\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tawait renameSession(target, next);\n\t\t\tawait this.refreshSessionsAfterMutation();\n\t\t} finally {\n\t\t\tthis.exitRenameMode();\n\t\t}\n\t}\n\n\tprivate async loadScope(scope: SessionScope, reason: \"initial\" | \"refresh\" | \"toggle\"): Promise {\n\t\tconst showCwd = scope === \"all\";\n\n\t\t// Mark loading\n\t\tif (scope === \"current\") {\n\t\t\tthis.currentLoading = true;\n\t\t} else {\n\t\t\tthis.allLoading = true;\n\t\t}\n\n\t\tconst seq = scope === \"all\" ? ++this.allLoadSeq : undefined;\n\t\tthis.header.setScope(scope);\n\t\tthis.header.setLoading(true);\n\t\tthis.requestRender();\n\n\t\tconst onProgress = (loaded: number, total: number) => {\n\t\t\tif (scope !== this.scope) return;\n\t\t\tif (seq !== undefined && seq !== this.allLoadSeq) return;\n\t\t\tthis.header.setProgress(loaded, total);\n\t\t\tthis.requestRender();\n\t\t};\n\n\t\ttry {\n\t\t\tconst sessions = await (scope === \"current\"\n\t\t\t\t? this.currentSessionsLoader(onProgress)\n\t\t\t\t: this.allSessionsLoader(onProgress));\n\n\t\t\tif (scope === \"current\") {\n\t\t\t\tthis.currentSessions = sessions;\n\t\t\t\tthis.currentLoading = false;\n\t\t\t} else {\n\t\t\t\tthis.allSessions = sessions;\n\t\t\t\tthis.allLoading = false;\n\t\t\t}\n\n\t\t\tif (scope !== this.scope) return;\n\t\t\tif (seq !== undefined && seq !== this.allLoadSeq) return;\n\n\t\t\tthis.header.setLoading(false);\n\t\t\tthis.sessionList.setSessions(sessions, showCwd);\n\t\t\tthis.requestRender();\n\t\t} catch (err) {\n\t\t\tif (scope === \"current\") {\n\t\t\t\tthis.currentLoading = false;\n\t\t\t} else {\n\t\t\t\tthis.allLoading = false;\n\t\t\t}\n\n\t\t\tif (scope !== this.scope) return;\n\t\t\tif (seq !== undefined && seq !== this.allLoadSeq) return;\n\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthis.header.setLoading(false);\n\t\t\tthis.header.setStatusMessage({ type: \"error\", message: `Failed to load sessions: ${message}` }, 4000);\n\n\t\t\tif (reason === \"initial\") {\n\t\t\t\tthis.sessionList.setSessions([], showCwd);\n\t\t\t}\n\t\t\tthis.requestRender();\n\t\t}\n\t}\n\n\tprivate toggleSortMode(): void {\n\t\t// Cycle: threaded -> recent -> relevance -> threaded\n\t\tthis.sortMode = this.sortMode === \"threaded\" ? \"recent\" : this.sortMode === \"recent\" ? \"relevance\" : \"threaded\";\n\t\tthis.header.setSortMode(this.sortMode);\n\t\tthis.sessionList.setSortMode(this.sortMode);\n\t\tthis.requestRender();\n\t}\n\n\tprivate toggleNameFilter(): void {\n\t\tthis.nameFilter = this.nameFilter === \"all\" ? \"named\" : \"all\";\n\t\tthis.header.setNameFilter(this.nameFilter);\n\t\tthis.sessionList.setNameFilter(this.nameFilter);\n\t\tthis.requestRender();\n\t}\n\n\tprivate async refreshSessionsAfterMutation(): Promise {\n\t\tawait this.loadScope(this.scope, \"refresh\");\n\t}\n\n\tprivate toggleScope(): void {\n\t\tif (this.scope === \"current\") {\n\t\t\tthis.scope = \"all\";\n\t\t\tthis.header.setScope(this.scope);\n\n\t\t\tif (this.allSessions !== null) {\n\t\t\t\tthis.header.setLoading(false);\n\t\t\t\tthis.sessionList.setSessions(this.allSessions, true);\n\t\t\t\tthis.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!this.allLoading) {\n\t\t\t\tvoid this.loadScope(\"all\", \"toggle\");\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tthis.scope = \"current\";\n\t\tthis.header.setScope(this.scope);\n\t\tthis.header.setLoading(this.currentLoading);\n\t\tthis.sessionList.setSessions(this.currentSessions ?? [], false);\n\t\tthis.requestRender();\n\t}\n\n\tgetSessionList(): SessionList {\n\t\treturn this.sessionList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/session-selector.js b/dist/modes/interactive/components/session-selector.js new file mode 100644 index 0000000..59886ee --- /dev/null +++ b/dist/modes/interactive/components/session-selector.js @@ -0,0 +1,867 @@ +import { spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { unlink } from "node:fs/promises"; +import * as os from "node:os"; +import { Container, getKeybindings, Input, Spacer, Text, truncateToWidth, visibleWidth, } from "@earendil-works/pi-tui"; +import { KeybindingsManager } from "../../../core/keybindings.js"; +import { canonicalizePath as _canonicalizePath } from "../../../utils/paths.js"; +import { theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyHint, keyText } from "./keybinding-hints.js"; +import { filterAndSortSessions, hasSessionName } from "./session-selector-search.js"; +function shortenPath(path) { + const home = os.homedir(); + if (!path) + return path; + if (path.startsWith(home)) { + return `~${path.slice(home.length)}`; + } + return path; +} +function formatSessionDate(date) { + const now = new Date(); + const diffMs = now.getTime() - date.getTime(); + const diffMins = Math.floor(diffMs / 60000); + const diffHours = Math.floor(diffMs / 3600000); + const diffDays = Math.floor(diffMs / 86400000); + if (diffMins < 1) + return "now"; + if (diffMins < 60) + return `${diffMins}m`; + if (diffHours < 24) + return `${diffHours}h`; + if (diffDays < 7) + return `${diffDays}d`; + if (diffDays < 30) + return `${Math.floor(diffDays / 7)}w`; + if (diffDays < 365) + return `${Math.floor(diffDays / 30)}mo`; + return `${Math.floor(diffDays / 365)}y`; +} +function canonicalizePath(path) { + if (!path) + return path; + return _canonicalizePath(path); +} +class SessionSelectorHeader { + scope; + sortMode; + nameFilter; + requestRender; + loading = false; + loadProgress = null; + showPath = false; + confirmingDeletePath = null; + statusMessage = null; + statusTimeout = null; + showRenameHint = false; + constructor(scope, sortMode, nameFilter, requestRender) { + this.scope = scope; + this.sortMode = sortMode; + this.nameFilter = nameFilter; + this.requestRender = requestRender; + } + setScope(scope) { + this.scope = scope; + } + setSortMode(sortMode) { + this.sortMode = sortMode; + } + setNameFilter(nameFilter) { + this.nameFilter = nameFilter; + } + setLoading(loading) { + this.loading = loading; + // Progress is scoped to the current load; clear whenever the loading state is set + this.loadProgress = null; + } + setProgress(loaded, total) { + this.loadProgress = { loaded, total }; + } + setShowPath(showPath) { + this.showPath = showPath; + } + setShowRenameHint(show) { + this.showRenameHint = show; + } + setConfirmingDeletePath(path) { + this.confirmingDeletePath = path; + } + clearStatusTimeout() { + if (!this.statusTimeout) + return; + clearTimeout(this.statusTimeout); + this.statusTimeout = null; + } + setStatusMessage(msg, autoHideMs) { + this.clearStatusTimeout(); + this.statusMessage = msg; + if (!msg || !autoHideMs) + return; + this.statusTimeout = setTimeout(() => { + this.statusMessage = null; + this.statusTimeout = null; + this.requestRender(); + }, autoHideMs); + } + invalidate() { } + render(width) { + const title = this.scope === "current" ? "Resume Session (Current Folder)" : "Resume Session (All)"; + const leftText = theme.bold(title); + const sortLabel = this.sortMode === "threaded" ? "Threaded" : this.sortMode === "recent" ? "Recent" : "Fuzzy"; + const sortText = theme.fg("muted", "Sort: ") + theme.fg("accent", sortLabel); + const nameLabel = this.nameFilter === "all" ? "All" : "Named"; + const nameText = theme.fg("muted", "Name: ") + theme.fg("accent", nameLabel); + let scopeText; + if (this.loading) { + const progressText = this.loadProgress ? `${this.loadProgress.loaded}/${this.loadProgress.total}` : "..."; + scopeText = `${theme.fg("muted", "○ Current Folder | ")}${theme.fg("accent", `Loading ${progressText}`)}`; + } + else if (this.scope === "current") { + scopeText = `${theme.fg("accent", "◉ Current Folder")}${theme.fg("muted", " | ○ All")}`; + } + else { + scopeText = `${theme.fg("muted", "○ Current Folder | ")}${theme.fg("accent", "◉ All")}`; + } + const rightText = truncateToWidth(`${scopeText} ${nameText} ${sortText}`, width, ""); + const availableLeft = Math.max(0, width - visibleWidth(rightText) - 1); + const left = truncateToWidth(leftText, availableLeft, ""); + const spacing = Math.max(0, width - visibleWidth(left) - visibleWidth(rightText)); + // Build hint lines - changes based on state (all branches truncate to width) + let hintLine1; + let hintLine2; + if (this.confirmingDeletePath !== null) { + const confirmHint = `Delete session? ${keyHint("tui.select.confirm", "confirm")} · ${keyHint("tui.select.cancel", "cancel")}`; + hintLine1 = theme.fg("error", truncateToWidth(confirmHint, width, "…")); + hintLine2 = ""; + } + else if (this.statusMessage) { + const color = this.statusMessage.type === "error" ? "error" : "accent"; + hintLine1 = theme.fg(color, truncateToWidth(this.statusMessage.message, width, "…")); + hintLine2 = ""; + } + else { + const pathState = this.showPath ? "(on)" : "(off)"; + const sep = theme.fg("muted", " · "); + const hint1 = keyHint("tui.input.tab", "scope") + sep + theme.fg("muted", 're: regex · "phrase" exact'); + const hint2Parts = [ + keyHint("app.session.toggleSort", "sort"), + keyHint("app.session.toggleNamedFilter", "named"), + keyHint("app.session.delete", "delete"), + keyHint("app.session.togglePath", `path ${pathState}`), + ]; + if (this.showRenameHint) { + hint2Parts.push(keyHint("app.session.rename", "rename")); + } + const hint2 = hint2Parts.join(sep); + hintLine1 = truncateToWidth(hint1, width, "…"); + hintLine2 = truncateToWidth(hint2, width, "…"); + } + return [`${left}${" ".repeat(spacing)}${rightText}`, hintLine1, hintLine2]; + } +} +/** + * Build a tree structure from sessions based on parentSessionPath. + * Returns root nodes sorted by modified date (descending). + */ +function buildSessionTree(sessions) { + const byPath = new Map(); + for (const session of sessions) { + const sessionPath = canonicalizePath(session.path) ?? session.path; + byPath.set(sessionPath, { session, children: [], latestActivity: session.modified.getTime() }); + } + const roots = []; + for (const session of sessions) { + const sessionPath = canonicalizePath(session.path) ?? session.path; + const node = byPath.get(sessionPath); + const parentPath = canonicalizePath(session.parentSessionPath); + if (parentPath && byPath.has(parentPath)) { + byPath.get(parentPath).children.push(node); + } + else { + roots.push(node); + } + } + const updateLatestActivity = (node) => { + let latestActivity = node.session.modified.getTime(); + for (const child of node.children) { + latestActivity = Math.max(latestActivity, updateLatestActivity(child)); + } + node.latestActivity = latestActivity; + return latestActivity; + }; + for (const root of roots) { + updateLatestActivity(root); + } + // Sort children and roots by latest activity in each subtree (descending) + const sortNodes = (nodes) => { + nodes.sort((a, b) => b.latestActivity - a.latestActivity); + for (const node of nodes) { + sortNodes(node.children); + } + }; + sortNodes(roots); + return roots; +} +/** + * Flatten tree into display list with tree structure metadata. + */ +function flattenSessionTree(roots) { + const result = []; + const walk = (node, depth, ancestorContinues, isLast) => { + result.push({ session: node.session, depth, isLast, ancestorContinues }); + for (let i = 0; i < node.children.length; i++) { + const childIsLast = i === node.children.length - 1; + // Only show continuation line for non-root ancestors + const continues = depth > 0 ? !isLast : false; + walk(node.children[i], depth + 1, [...ancestorContinues, continues], childIsLast); + } + }; + for (let i = 0; i < roots.length; i++) { + walk(roots[i], 0, [], i === roots.length - 1); + } + return result; +} +/** + * Custom session list component with multi-line items and search + */ +class SessionList { + getSelectedSessionPath() { + const selected = this.filteredSessions[this.selectedIndex]; + return selected?.session.path; + } + allSessions = []; + filteredSessions = []; + selectedIndex = 0; + searchInput; + showCwd = false; + sortMode = "threaded"; + nameFilter = "all"; + keybindings; + showPath = false; + confirmingDeletePath = null; + currentSessionCanonicalPath; + onSelect; + onCancel; + onExit = () => { }; + onToggleScope; + onToggleSort; + onToggleNameFilter; + onTogglePath; + onDeleteConfirmationChange; + onDeleteSession; + onRenameSession; + onError; + maxVisible = 10; // Max sessions visible (one line each) + // Focusable implementation - propagate to searchInput for IME cursor positioning + _focused = false; + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + this.searchInput.focused = value; + } + constructor(sessions, showCwd, sortMode, nameFilter, keybindings, currentSessionFilePath) { + this.allSessions = sessions; + this.filteredSessions = []; + this.searchInput = new Input(); + this.showCwd = showCwd; + this.sortMode = sortMode; + this.nameFilter = nameFilter; + this.keybindings = keybindings; + this.currentSessionCanonicalPath = canonicalizePath(currentSessionFilePath); + this.filterSessions(""); + // Handle Enter in search input - select current item + this.searchInput.onSubmit = () => { + if (this.filteredSessions[this.selectedIndex]) { + const selected = this.filteredSessions[this.selectedIndex]; + if (this.onSelect) { + this.onSelect(selected.session.path); + } + } + }; + } + setSortMode(sortMode) { + this.sortMode = sortMode; + this.filterSessions(this.searchInput.getValue()); + } + setNameFilter(nameFilter) { + this.nameFilter = nameFilter; + this.filterSessions(this.searchInput.getValue()); + } + setSessions(sessions, showCwd) { + this.allSessions = sessions; + this.showCwd = showCwd; + this.filterSessions(this.searchInput.getValue()); + } + filterSessions(query) { + const trimmed = query.trim(); + const nameFiltered = this.nameFilter === "all" ? this.allSessions : this.allSessions.filter((session) => hasSessionName(session)); + if (this.sortMode === "threaded" && !trimmed) { + // Threaded mode without search: show tree structure + const roots = buildSessionTree(nameFiltered); + this.filteredSessions = flattenSessionTree(roots); + } + else { + // Other modes or with search: flat list + const filtered = filterAndSortSessions(nameFiltered, query, this.sortMode, "all"); + this.filteredSessions = filtered.map((session) => ({ + session, + depth: 0, + isLast: true, + ancestorContinues: [], + })); + } + this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredSessions.length - 1)); + } + setConfirmingDeletePath(path) { + this.confirmingDeletePath = path; + this.onDeleteConfirmationChange?.(path); + } + startDeleteConfirmationForSelectedSession() { + const selected = this.filteredSessions[this.selectedIndex]; + if (!selected) + return; + // Prevent deleting current session + if (this.isCurrentSessionPath(selected.session.path)) { + this.onError?.("Cannot delete the currently active session"); + return; + } + this.setConfirmingDeletePath(selected.session.path); + } + isCurrentSessionPath(path) { + if (!this.currentSessionCanonicalPath) + return false; + return (canonicalizePath(path) ?? path) === this.currentSessionCanonicalPath; + } + invalidate() { } + render(width) { + const lines = []; + // Render search input + lines.push(...this.searchInput.render(width)); + lines.push(""); // Blank line after search + if (this.filteredSessions.length === 0) { + let emptyMessage; + if (this.nameFilter === "named") { + const toggleKey = keyText("app.session.toggleNamedFilter"); + if (this.showCwd) { + emptyMessage = ` No named sessions found. Press ${toggleKey} to show all.`; + } + else { + emptyMessage = ` No named sessions in current folder. Press ${toggleKey} to show all, or Tab to view all.`; + } + } + else if (this.showCwd) { + // "All" scope - no sessions anywhere that match filter + emptyMessage = " No sessions found"; + } + else { + // "Current folder" scope - hint to try "all" + emptyMessage = " No sessions in current folder. Press Tab to view all."; + } + lines.push(theme.fg("muted", truncateToWidth(emptyMessage, width, "…"))); + return lines; + } + // Calculate visible range with scrolling + const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredSessions.length - this.maxVisible)); + const endIndex = Math.min(startIndex + this.maxVisible, this.filteredSessions.length); + // Render visible sessions (one line each with tree structure) + for (let i = startIndex; i < endIndex; i++) { + const node = this.filteredSessions[i]; + const session = node.session; + const isSelected = i === this.selectedIndex; + const isConfirmingDelete = session.path === this.confirmingDeletePath; + const isCurrent = this.isCurrentSessionPath(session.path); + // Build tree prefix + const prefix = this.buildTreePrefix(node); + // Session display text (name or first message) + const hasName = !!session.name; + const displayText = session.name ?? session.firstMessage; + const normalizedMessage = displayText.replace(/[\x00-\x1f\x7f]/g, " ").trim(); + // Right side: message count and age + const age = formatSessionDate(session.modified); + const msgCount = String(session.messageCount); + let rightPart = `${msgCount} ${age}`; + if (this.showCwd && session.cwd) { + rightPart = `${shortenPath(session.cwd)} ${rightPart}`; + } + if (this.showPath) { + rightPart = `${shortenPath(session.path)} ${rightPart}`; + } + // Cursor + const cursor = isSelected ? theme.fg("accent", "› ") : " "; + // Calculate available width for message + const prefixWidth = visibleWidth(prefix); + const rightWidth = visibleWidth(rightPart) + 2; // +2 for spacing + const availableForMsg = width - 2 - prefixWidth - rightWidth; // -2 for cursor + const truncatedMsg = truncateToWidth(normalizedMessage, Math.max(10, availableForMsg), "…"); + // Style message + let messageColor = null; + if (isConfirmingDelete) { + messageColor = "error"; + } + else if (isCurrent) { + messageColor = "accent"; + } + else if (hasName) { + messageColor = "warning"; + } + let styledMsg = messageColor ? theme.fg(messageColor, truncatedMsg) : truncatedMsg; + if (isSelected) { + styledMsg = theme.bold(styledMsg); + } + // Build line + const leftPart = cursor + theme.fg("dim", prefix) + styledMsg; + const leftWidth = visibleWidth(leftPart); + const spacing = Math.max(1, width - leftWidth - visibleWidth(rightPart)); + const styledRight = theme.fg(isConfirmingDelete ? "error" : "dim", rightPart); + let line = leftPart + " ".repeat(spacing) + styledRight; + if (isSelected) { + line = theme.bg("selectedBg", line); + } + lines.push(truncateToWidth(line, width)); + } + // Add scroll indicator if needed + if (startIndex > 0 || endIndex < this.filteredSessions.length) { + const scrollText = ` (${this.selectedIndex + 1}/${this.filteredSessions.length})`; + const scrollInfo = theme.fg("muted", truncateToWidth(scrollText, width, "")); + lines.push(scrollInfo); + } + return lines; + } + buildTreePrefix(node) { + if (node.depth === 0) { + return ""; + } + const parts = node.ancestorContinues.map((continues) => (continues ? "│ " : " ")); + const branch = node.isLast ? "└─ " : "├─ "; + return parts.join("") + branch; + } + handleInput(keyData) { + const kb = getKeybindings(); + // Handle delete confirmation state first - intercept all keys + if (this.confirmingDeletePath !== null) { + if (kb.matches(keyData, "tui.select.confirm")) { + const pathToDelete = this.confirmingDeletePath; + this.setConfirmingDeletePath(null); + void this.onDeleteSession?.(pathToDelete); + return; + } + if (kb.matches(keyData, "tui.select.cancel")) { + this.setConfirmingDeletePath(null); + return; + } + // Ignore all other keys while confirming + return; + } + if (kb.matches(keyData, "tui.input.tab")) { + if (this.onToggleScope) { + this.onToggleScope(); + } + return; + } + if (kb.matches(keyData, "app.session.toggleSort")) { + this.onToggleSort?.(); + return; + } + if (this.keybindings.matches(keyData, "app.session.toggleNamedFilter")) { + this.onToggleNameFilter?.(); + return; + } + // Ctrl+P: toggle path display + if (kb.matches(keyData, "app.session.togglePath")) { + this.showPath = !this.showPath; + this.onTogglePath?.(this.showPath); + return; + } + // Ctrl+D: initiate delete confirmation (useful on terminals that don't distinguish Ctrl+Backspace from Backspace) + if (kb.matches(keyData, "app.session.delete")) { + this.startDeleteConfirmationForSelectedSession(); + return; + } + // Rename selected session + if (kb.matches(keyData, "app.session.rename")) { + const selected = this.filteredSessions[this.selectedIndex]; + if (selected) { + this.onRenameSession?.(selected.session.path); + } + return; + } + // Ctrl+Backspace: non-invasive convenience alias for delete + // Only triggers deletion when the query is empty; otherwise it is forwarded to the input + if (kb.matches(keyData, "app.session.deleteNoninvasive")) { + if (this.searchInput.getValue().length > 0) { + this.searchInput.handleInput(keyData); + this.filterSessions(this.searchInput.getValue()); + return; + } + this.startDeleteConfirmationForSelectedSession(); + return; + } + // Up arrow + if (kb.matches(keyData, "tui.select.up")) { + this.selectedIndex = Math.max(0, this.selectedIndex - 1); + } + // Down arrow + else if (kb.matches(keyData, "tui.select.down")) { + this.selectedIndex = Math.min(this.filteredSessions.length - 1, this.selectedIndex + 1); + } + // Page up - jump up by maxVisible items + else if (kb.matches(keyData, "tui.select.pageUp")) { + this.selectedIndex = Math.max(0, this.selectedIndex - this.maxVisible); + } + // Page down - jump down by maxVisible items + else if (kb.matches(keyData, "tui.select.pageDown")) { + this.selectedIndex = Math.min(this.filteredSessions.length - 1, this.selectedIndex + this.maxVisible); + } + // Enter + else if (kb.matches(keyData, "tui.select.confirm")) { + const selected = this.filteredSessions[this.selectedIndex]; + if (selected && this.onSelect) { + this.onSelect(selected.session.path); + } + } + // Escape - cancel + else if (kb.matches(keyData, "tui.select.cancel")) { + if (this.onCancel) { + this.onCancel(); + } + } + // Pass everything else to search input + else { + this.searchInput.handleInput(keyData); + this.filterSessions(this.searchInput.getValue()); + } + } +} +/** + * Delete a session file, trying the `trash` CLI first, then falling back to unlink + */ +async function deleteSessionFile(sessionPath) { + // Try `trash` first (if installed) + const trashArgs = sessionPath.startsWith("-") ? ["--", sessionPath] : [sessionPath]; + const trashResult = spawnSync("trash", trashArgs, { encoding: "utf-8" }); + const getTrashErrorHint = () => { + const parts = []; + if (trashResult.error) { + parts.push(trashResult.error.message); + } + const stderr = trashResult.stderr?.trim(); + if (stderr) { + parts.push(stderr.split("\n")[0] ?? stderr); + } + if (parts.length === 0) + return null; + return `trash: ${parts.join(" · ").slice(0, 200)}`; + }; + // If trash reports success, or the file is gone afterwards, treat it as successful + if (trashResult.status === 0 || !existsSync(sessionPath)) { + return { ok: true, method: "trash" }; + } + // Fallback to permanent deletion + try { + await unlink(sessionPath); + return { ok: true, method: "unlink" }; + } + catch (err) { + const unlinkError = err instanceof Error ? err.message : String(err); + const trashErrorHint = getTrashErrorHint(); + const error = trashErrorHint ? `${unlinkError} (${trashErrorHint})` : unlinkError; + return { ok: false, method: "unlink", error }; + } +} +/** + * Component that renders a session selector + */ +export class SessionSelectorComponent extends Container { + handleInput(data) { + if (this.mode === "rename") { + const kb = getKeybindings(); + if (kb.matches(data, "tui.select.cancel")) { + this.exitRenameMode(); + return; + } + this.renameInput.handleInput(data); + return; + } + this.sessionList.handleInput(data); + } + canRename = true; + sessionList; + header; + keybindings; + scope = "current"; + sortMode = "threaded"; + nameFilter = "all"; + currentSessions = null; + allSessions = null; + currentSessionsLoader; + allSessionsLoader; + requestRender; + renameSession; + currentLoading = false; + allLoading = false; + allLoadSeq = 0; + mode = "list"; + renameInput = new Input(); + renameTargetPath = null; + // Focusable implementation - propagate to sessionList for IME cursor positioning + _focused = false; + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + this.sessionList.focused = value; + this.renameInput.focused = value; + if (value && this.mode === "rename") { + this.renameInput.focused = true; + } + } + buildBaseLayout(content, options) { + this.clear(); + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder((s) => theme.fg("accent", s))); + this.addChild(new Spacer(1)); + if (options?.showHeader ?? true) { + this.addChild(this.header); + this.addChild(new Spacer(1)); + } + this.addChild(content); + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder((s) => theme.fg("accent", s))); + } + constructor(currentSessionsLoader, allSessionsLoader, onSelect, onCancel, onExit, requestRender, options, currentSessionFilePath) { + super(); + this.keybindings = options?.keybindings ?? KeybindingsManager.create(); + this.currentSessionsLoader = currentSessionsLoader; + this.allSessionsLoader = allSessionsLoader; + this.requestRender = requestRender; + this.header = new SessionSelectorHeader(this.scope, this.sortMode, this.nameFilter, this.requestRender); + const renameSession = options?.renameSession; + this.renameSession = renameSession; + this.canRename = !!renameSession; + this.header.setShowRenameHint(options?.showRenameHint ?? this.canRename); + // Create session list (starts empty, will be populated after load) + this.sessionList = new SessionList([], false, this.sortMode, this.nameFilter, this.keybindings, currentSessionFilePath); + this.buildBaseLayout(this.sessionList); + this.renameInput.onSubmit = (value) => { + void this.confirmRename(value); + }; + // Ensure header status timeouts are cleared when leaving the selector + const clearStatusMessage = () => this.header.setStatusMessage(null); + this.sessionList.onSelect = (sessionPath) => { + clearStatusMessage(); + onSelect(sessionPath); + }; + this.sessionList.onCancel = () => { + clearStatusMessage(); + onCancel(); + }; + this.sessionList.onExit = () => { + clearStatusMessage(); + onExit(); + }; + this.sessionList.onToggleScope = () => this.toggleScope(); + this.sessionList.onToggleSort = () => this.toggleSortMode(); + this.sessionList.onToggleNameFilter = () => this.toggleNameFilter(); + this.sessionList.onRenameSession = (sessionPath) => { + if (!renameSession) + return; + if (this.scope === "current" && this.currentLoading) + return; + if (this.scope === "all" && this.allLoading) + return; + const sessions = this.scope === "all" ? (this.allSessions ?? []) : (this.currentSessions ?? []); + const session = sessions.find((s) => s.path === sessionPath); + this.enterRenameMode(sessionPath, session?.name); + }; + // Sync list events to header + this.sessionList.onTogglePath = (showPath) => { + this.header.setShowPath(showPath); + this.requestRender(); + }; + this.sessionList.onDeleteConfirmationChange = (path) => { + this.header.setConfirmingDeletePath(path); + this.requestRender(); + }; + this.sessionList.onError = (msg) => { + this.header.setStatusMessage({ type: "error", message: msg }, 3000); + this.requestRender(); + }; + // Handle session deletion + this.sessionList.onDeleteSession = async (sessionPath) => { + const result = await deleteSessionFile(sessionPath); + if (result.ok) { + if (this.currentSessions) { + this.currentSessions = this.currentSessions.filter((s) => s.path !== sessionPath); + } + if (this.allSessions) { + this.allSessions = this.allSessions.filter((s) => s.path !== sessionPath); + } + const sessions = this.scope === "all" ? (this.allSessions ?? []) : (this.currentSessions ?? []); + const showCwd = this.scope === "all"; + this.sessionList.setSessions(sessions, showCwd); + const msg = result.method === "trash" ? "Session moved to trash" : "Session deleted"; + this.header.setStatusMessage({ type: "info", message: msg }, 2000); + await this.refreshSessionsAfterMutation(); + } + else { + const errorMessage = result.error ?? "Unknown error"; + this.header.setStatusMessage({ type: "error", message: `Failed to delete: ${errorMessage}` }, 3000); + } + this.requestRender(); + }; + // Start loading current sessions immediately + this.loadCurrentSessions(); + } + loadCurrentSessions() { + void this.loadScope("current", "initial"); + } + enterRenameMode(sessionPath, currentName) { + this.mode = "rename"; + this.renameTargetPath = sessionPath; + this.renameInput.setValue(currentName ?? ""); + this.renameInput.focused = true; + const panel = new Container(); + panel.addChild(new Text(theme.bold("Rename Session"), 1, 0)); + panel.addChild(new Spacer(1)); + panel.addChild(this.renameInput); + panel.addChild(new Spacer(1)); + panel.addChild(new Text(theme.fg("muted", `${keyText("tui.select.confirm")} to save · ${keyText("tui.select.cancel")} to cancel`), 1, 0)); + this.buildBaseLayout(panel, { showHeader: false }); + this.requestRender(); + } + exitRenameMode() { + this.mode = "list"; + this.renameTargetPath = null; + this.buildBaseLayout(this.sessionList); + this.requestRender(); + } + async confirmRename(value) { + const next = value.trim(); + if (!next) + return; + const target = this.renameTargetPath; + if (!target) { + this.exitRenameMode(); + return; + } + // Find current name for callback + const renameSession = this.renameSession; + if (!renameSession) { + this.exitRenameMode(); + return; + } + try { + await renameSession(target, next); + await this.refreshSessionsAfterMutation(); + } + finally { + this.exitRenameMode(); + } + } + async loadScope(scope, reason) { + const showCwd = scope === "all"; + // Mark loading + if (scope === "current") { + this.currentLoading = true; + } + else { + this.allLoading = true; + } + const seq = scope === "all" ? ++this.allLoadSeq : undefined; + this.header.setScope(scope); + this.header.setLoading(true); + this.requestRender(); + const onProgress = (loaded, total) => { + if (scope !== this.scope) + return; + if (seq !== undefined && seq !== this.allLoadSeq) + return; + this.header.setProgress(loaded, total); + this.requestRender(); + }; + try { + const sessions = await (scope === "current" + ? this.currentSessionsLoader(onProgress) + : this.allSessionsLoader(onProgress)); + if (scope === "current") { + this.currentSessions = sessions; + this.currentLoading = false; + } + else { + this.allSessions = sessions; + this.allLoading = false; + } + if (scope !== this.scope) + return; + if (seq !== undefined && seq !== this.allLoadSeq) + return; + this.header.setLoading(false); + this.sessionList.setSessions(sessions, showCwd); + this.requestRender(); + } + catch (err) { + if (scope === "current") { + this.currentLoading = false; + } + else { + this.allLoading = false; + } + if (scope !== this.scope) + return; + if (seq !== undefined && seq !== this.allLoadSeq) + return; + const message = err instanceof Error ? err.message : String(err); + this.header.setLoading(false); + this.header.setStatusMessage({ type: "error", message: `Failed to load sessions: ${message}` }, 4000); + if (reason === "initial") { + this.sessionList.setSessions([], showCwd); + } + this.requestRender(); + } + } + toggleSortMode() { + // Cycle: threaded -> recent -> relevance -> threaded + this.sortMode = this.sortMode === "threaded" ? "recent" : this.sortMode === "recent" ? "relevance" : "threaded"; + this.header.setSortMode(this.sortMode); + this.sessionList.setSortMode(this.sortMode); + this.requestRender(); + } + toggleNameFilter() { + this.nameFilter = this.nameFilter === "all" ? "named" : "all"; + this.header.setNameFilter(this.nameFilter); + this.sessionList.setNameFilter(this.nameFilter); + this.requestRender(); + } + async refreshSessionsAfterMutation() { + await this.loadScope(this.scope, "refresh"); + } + toggleScope() { + if (this.scope === "current") { + this.scope = "all"; + this.header.setScope(this.scope); + if (this.allSessions !== null) { + this.header.setLoading(false); + this.sessionList.setSessions(this.allSessions, true); + this.requestRender(); + return; + } + if (!this.allLoading) { + void this.loadScope("all", "toggle"); + } + return; + } + this.scope = "current"; + this.header.setScope(this.scope); + this.header.setLoading(this.currentLoading); + this.sessionList.setSessions(this.currentSessions ?? [], false); + this.requestRender(); + } + getSessionList() { + return this.sessionList; + } +} +//# sourceMappingURL=session-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/session-selector.js.map b/dist/modes/interactive/components/session-selector.js.map new file mode 100644 index 0000000..5f1c33a --- /dev/null +++ b/dist/modes/interactive/components/session-selector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"session-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/session-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAEN,SAAS,EAET,cAAc,EACd,KAAK,EACL,MAAM,EACN,IAAI,EACJ,eAAe,EACf,YAAY,GACZ,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,OAAO,EAAE,gBAAgB,IAAI,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAChF,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC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IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YAEjC,IAAI,IAAI,CAAC,WAAW,KAAK,IAAI,EAAE,CAAC;gBAC/B,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;gBAC9B,IAAI,CAAC,WAAW,CAAC,WAAW,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC;gBACrD,IAAI,CAAC,aAAa,EAAE,CAAC;gBACrB,OAAO;YACR,CAAC;YAED,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;gBACtB,KAAK,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;YACtC,CAAC;YACD,OAAO;QACR,CAAC;QAED,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;QACvB,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACjC,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAC5C,IAAI,CAAC,WAAW,CAAC,WAAW,CAAC,IAAI,CAAC,eAAe,IAAI,EAAE,EAAE,KAAK,CAAC,CAAC;QAChE,IAAI,CAAC,aAAa,EAAE,CAAC;IAAA,CACrB;IAED,cAAc,GAAgB;QAC7B,OAAO,IAAI,CAAC,WAAW,CAAC;IAAA,CACxB;CACD","sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { unlink } from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport {\n\ttype Component,\n\tContainer,\n\ttype Focusable,\n\tgetKeybindings,\n\tInput,\n\tSpacer,\n\tText,\n\ttruncateToWidth,\n\tvisibleWidth,\n} from \"@earendil-works/pi-tui\";\nimport { KeybindingsManager } from \"../../../core/keybindings.ts\";\nimport type { SessionInfo, SessionListProgress } from \"../../../core/session-manager.ts\";\nimport { canonicalizePath as _canonicalizePath } from \"../../../utils/paths.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint, keyText } from \"./keybinding-hints.ts\";\nimport { filterAndSortSessions, hasSessionName, type NameFilter, type SortMode } from \"./session-selector-search.ts\";\n\ntype SessionScope = \"current\" | \"all\";\n\nfunction shortenPath(path: string): string {\n\tconst home = os.homedir();\n\tif (!path) return path;\n\tif (path.startsWith(home)) {\n\t\treturn `~${path.slice(home.length)}`;\n\t}\n\treturn path;\n}\n\nfunction formatSessionDate(date: Date): string {\n\tconst now = new Date();\n\tconst diffMs = now.getTime() - date.getTime();\n\tconst diffMins = Math.floor(diffMs / 60000);\n\tconst diffHours = Math.floor(diffMs / 3600000);\n\tconst diffDays = Math.floor(diffMs / 86400000);\n\n\tif (diffMins < 1) return \"now\";\n\tif (diffMins < 60) return `${diffMins}m`;\n\tif (diffHours < 24) return `${diffHours}h`;\n\tif (diffDays < 7) return `${diffDays}d`;\n\tif (diffDays < 30) return `${Math.floor(diffDays / 7)}w`;\n\tif (diffDays < 365) return `${Math.floor(diffDays / 30)}mo`;\n\treturn `${Math.floor(diffDays / 365)}y`;\n}\n\nfunction canonicalizePath(path: string | undefined): string | undefined {\n\tif (!path) return path;\n\treturn _canonicalizePath(path);\n}\n\nclass SessionSelectorHeader implements Component {\n\tprivate scope: SessionScope;\n\tprivate sortMode: SortMode;\n\tprivate nameFilter: NameFilter;\n\tprivate requestRender: () => void;\n\tprivate loading = false;\n\tprivate loadProgress: { loaded: number; total: number } | null = null;\n\tprivate showPath = false;\n\tprivate confirmingDeletePath: string | null = null;\n\tprivate statusMessage: { type: \"info\" | \"error\"; message: string } | null = null;\n\tprivate statusTimeout: ReturnType | null = null;\n\tprivate showRenameHint = false;\n\n\tconstructor(scope: SessionScope, sortMode: SortMode, nameFilter: NameFilter, requestRender: () => void) {\n\t\tthis.scope = scope;\n\t\tthis.sortMode = sortMode;\n\t\tthis.nameFilter = nameFilter;\n\t\tthis.requestRender = requestRender;\n\t}\n\n\tsetScope(scope: SessionScope): void {\n\t\tthis.scope = scope;\n\t}\n\n\tsetSortMode(sortMode: SortMode): void {\n\t\tthis.sortMode = sortMode;\n\t}\n\n\tsetNameFilter(nameFilter: NameFilter): void {\n\t\tthis.nameFilter = nameFilter;\n\t}\n\n\tsetLoading(loading: boolean): void {\n\t\tthis.loading = loading;\n\t\t// Progress is scoped to the current load; clear whenever the loading state is set\n\t\tthis.loadProgress = null;\n\t}\n\n\tsetProgress(loaded: number, total: number): void {\n\t\tthis.loadProgress = { loaded, total };\n\t}\n\n\tsetShowPath(showPath: boolean): void {\n\t\tthis.showPath = showPath;\n\t}\n\n\tsetShowRenameHint(show: boolean): void {\n\t\tthis.showRenameHint = show;\n\t}\n\n\tsetConfirmingDeletePath(path: string | null): void {\n\t\tthis.confirmingDeletePath = path;\n\t}\n\n\tprivate clearStatusTimeout(): void {\n\t\tif (!this.statusTimeout) return;\n\t\tclearTimeout(this.statusTimeout);\n\t\tthis.statusTimeout = null;\n\t}\n\n\tsetStatusMessage(msg: { type: \"info\" | \"error\"; message: string } | null, autoHideMs?: number): void {\n\t\tthis.clearStatusTimeout();\n\t\tthis.statusMessage = msg;\n\t\tif (!msg || !autoHideMs) return;\n\n\t\tthis.statusTimeout = setTimeout(() => {\n\t\t\tthis.statusMessage = null;\n\t\t\tthis.statusTimeout = null;\n\t\t\tthis.requestRender();\n\t\t}, autoHideMs);\n\t}\n\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst title = this.scope === \"current\" ? \"Resume Session (Current Folder)\" : \"Resume Session (All)\";\n\t\tconst leftText = theme.bold(title);\n\n\t\tconst sortLabel = this.sortMode === \"threaded\" ? \"Threaded\" : this.sortMode === \"recent\" ? \"Recent\" : \"Fuzzy\";\n\t\tconst sortText = theme.fg(\"muted\", \"Sort: \") + theme.fg(\"accent\", sortLabel);\n\n\t\tconst nameLabel = this.nameFilter === \"all\" ? \"All\" : \"Named\";\n\t\tconst nameText = theme.fg(\"muted\", \"Name: \") + theme.fg(\"accent\", nameLabel);\n\n\t\tlet scopeText: string;\n\t\tif (this.loading) {\n\t\t\tconst progressText = this.loadProgress ? `${this.loadProgress.loaded}/${this.loadProgress.total}` : \"...\";\n\t\t\tscopeText = `${theme.fg(\"muted\", \"○ Current Folder | \")}${theme.fg(\"accent\", `Loading ${progressText}`)}`;\n\t\t} else if (this.scope === \"current\") {\n\t\t\tscopeText = `${theme.fg(\"accent\", \"◉ Current Folder\")}${theme.fg(\"muted\", \" | ○ All\")}`;\n\t\t} else {\n\t\t\tscopeText = `${theme.fg(\"muted\", \"○ Current Folder | \")}${theme.fg(\"accent\", \"◉ All\")}`;\n\t\t}\n\n\t\tconst rightText = truncateToWidth(`${scopeText} ${nameText} ${sortText}`, width, \"\");\n\t\tconst availableLeft = Math.max(0, width - visibleWidth(rightText) - 1);\n\t\tconst left = truncateToWidth(leftText, availableLeft, \"\");\n\t\tconst spacing = Math.max(0, width - visibleWidth(left) - visibleWidth(rightText));\n\n\t\t// Build hint lines - changes based on state (all branches truncate to width)\n\t\tlet hintLine1: string;\n\t\tlet hintLine2: string;\n\t\tif (this.confirmingDeletePath !== null) {\n\t\t\tconst confirmHint = `Delete session? ${keyHint(\"tui.select.confirm\", \"confirm\")} · ${keyHint(\"tui.select.cancel\", \"cancel\")}`;\n\t\t\thintLine1 = theme.fg(\"error\", truncateToWidth(confirmHint, width, \"…\"));\n\t\t\thintLine2 = \"\";\n\t\t} else if (this.statusMessage) {\n\t\t\tconst color = this.statusMessage.type === \"error\" ? \"error\" : \"accent\";\n\t\t\thintLine1 = theme.fg(color, truncateToWidth(this.statusMessage.message, width, \"…\"));\n\t\t\thintLine2 = \"\";\n\t\t} else {\n\t\t\tconst pathState = this.showPath ? \"(on)\" : \"(off)\";\n\t\t\tconst sep = theme.fg(\"muted\", \" · \");\n\t\t\tconst hint1 =\n\t\t\t\tkeyHint(\"tui.input.tab\", \"scope\") + sep + theme.fg(\"muted\", 're: regex · \"phrase\" exact');\n\t\t\tconst hint2Parts = [\n\t\t\t\tkeyHint(\"app.session.toggleSort\", \"sort\"),\n\t\t\t\tkeyHint(\"app.session.toggleNamedFilter\", \"named\"),\n\t\t\t\tkeyHint(\"app.session.delete\", \"delete\"),\n\t\t\t\tkeyHint(\"app.session.togglePath\", `path ${pathState}`),\n\t\t\t];\n\t\t\tif (this.showRenameHint) {\n\t\t\t\thint2Parts.push(keyHint(\"app.session.rename\", \"rename\"));\n\t\t\t}\n\t\t\tconst hint2 = hint2Parts.join(sep);\n\t\t\thintLine1 = truncateToWidth(hint1, width, \"…\");\n\t\t\thintLine2 = truncateToWidth(hint2, width, \"…\");\n\t\t}\n\n\t\treturn [`${left}${\" \".repeat(spacing)}${rightText}`, hintLine1, hintLine2];\n\t}\n}\n\n/** A session tree node for hierarchical display */\ninterface SessionTreeNode {\n\tsession: SessionInfo;\n\tchildren: SessionTreeNode[];\n\tlatestActivity: number;\n}\n\n/** Flattened node for display with tree structure info */\ninterface FlatSessionNode {\n\tsession: SessionInfo;\n\tdepth: number;\n\tisLast: boolean;\n\t/** For each ancestor level, whether there are more siblings after it */\n\tancestorContinues: boolean[];\n}\n\n/**\n * Build a tree structure from sessions based on parentSessionPath.\n * Returns root nodes sorted by modified date (descending).\n */\nfunction buildSessionTree(sessions: SessionInfo[]): SessionTreeNode[] {\n\tconst byPath = new Map();\n\n\tfor (const session of sessions) {\n\t\tconst sessionPath = canonicalizePath(session.path) ?? session.path;\n\t\tbyPath.set(sessionPath, { session, children: [], latestActivity: session.modified.getTime() });\n\t}\n\n\tconst roots: SessionTreeNode[] = [];\n\n\tfor (const session of sessions) {\n\t\tconst sessionPath = canonicalizePath(session.path) ?? session.path;\n\t\tconst node = byPath.get(sessionPath)!;\n\t\tconst parentPath = canonicalizePath(session.parentSessionPath);\n\n\t\tif (parentPath && byPath.has(parentPath)) {\n\t\t\tbyPath.get(parentPath)!.children.push(node);\n\t\t} else {\n\t\t\troots.push(node);\n\t\t}\n\t}\n\n\tconst updateLatestActivity = (node: SessionTreeNode): number => {\n\t\tlet latestActivity = node.session.modified.getTime();\n\t\tfor (const child of node.children) {\n\t\t\tlatestActivity = Math.max(latestActivity, updateLatestActivity(child));\n\t\t}\n\t\tnode.latestActivity = latestActivity;\n\t\treturn latestActivity;\n\t};\n\n\tfor (const root of roots) {\n\t\tupdateLatestActivity(root);\n\t}\n\n\t// Sort children and roots by latest activity in each subtree (descending)\n\tconst sortNodes = (nodes: SessionTreeNode[]): void => {\n\t\tnodes.sort((a, b) => b.latestActivity - a.latestActivity);\n\t\tfor (const node of nodes) {\n\t\t\tsortNodes(node.children);\n\t\t}\n\t};\n\tsortNodes(roots);\n\n\treturn roots;\n}\n\n/**\n * Flatten tree into display list with tree structure metadata.\n */\nfunction flattenSessionTree(roots: SessionTreeNode[]): FlatSessionNode[] {\n\tconst result: FlatSessionNode[] = [];\n\n\tconst walk = (node: SessionTreeNode, depth: number, ancestorContinues: boolean[], isLast: boolean): void => {\n\t\tresult.push({ session: node.session, depth, isLast, ancestorContinues });\n\n\t\tfor (let i = 0; i < node.children.length; i++) {\n\t\t\tconst childIsLast = i === node.children.length - 1;\n\t\t\t// Only show continuation line for non-root ancestors\n\t\t\tconst continues = depth > 0 ? !isLast : false;\n\t\t\twalk(node.children[i]!, depth + 1, [...ancestorContinues, continues], childIsLast);\n\t\t}\n\t};\n\n\tfor (let i = 0; i < roots.length; i++) {\n\t\twalk(roots[i]!, 0, [], i === roots.length - 1);\n\t}\n\n\treturn result;\n}\n\n/**\n * Custom session list component with multi-line items and search\n */\nclass SessionList implements Component, Focusable {\n\tpublic getSelectedSessionPath(): string | undefined {\n\t\tconst selected = this.filteredSessions[this.selectedIndex];\n\t\treturn selected?.session.path;\n\t}\n\tprivate allSessions: SessionInfo[] = [];\n\tprivate filteredSessions: FlatSessionNode[] = [];\n\tprivate selectedIndex: number = 0;\n\tprivate searchInput: Input;\n\tprivate showCwd = false;\n\tprivate sortMode: SortMode = \"threaded\";\n\tprivate nameFilter: NameFilter = \"all\";\n\tprivate keybindings: KeybindingsManager;\n\tprivate showPath = false;\n\tprivate confirmingDeletePath: string | null = null;\n\tprivate currentSessionCanonicalPath?: string;\n\tpublic onSelect?: (sessionPath: string) => void;\n\tpublic onCancel?: () => void;\n\tpublic onExit: () => void = () => {};\n\tpublic onToggleScope?: () => void;\n\tpublic onToggleSort?: () => void;\n\tpublic onToggleNameFilter?: () => void;\n\tpublic onTogglePath?: (showPath: boolean) => void;\n\tpublic onDeleteConfirmationChange?: (path: string | null) => void;\n\tpublic onDeleteSession?: (sessionPath: string) => Promise;\n\tpublic onRenameSession?: (sessionPath: string) => void;\n\tpublic onError?: (message: string) => void;\n\tprivate maxVisible: number = 10; // Max sessions visible (one line each)\n\n\t// Focusable implementation - propagate to searchInput for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.searchInput.focused = value;\n\t}\n\n\tconstructor(\n\t\tsessions: SessionInfo[],\n\t\tshowCwd: boolean,\n\t\tsortMode: SortMode,\n\t\tnameFilter: NameFilter,\n\t\tkeybindings: KeybindingsManager,\n\t\tcurrentSessionFilePath?: string,\n\t) {\n\t\tthis.allSessions = sessions;\n\t\tthis.filteredSessions = [];\n\t\tthis.searchInput = new Input();\n\t\tthis.showCwd = showCwd;\n\t\tthis.sortMode = sortMode;\n\t\tthis.nameFilter = nameFilter;\n\t\tthis.keybindings = keybindings;\n\t\tthis.currentSessionCanonicalPath = canonicalizePath(currentSessionFilePath);\n\t\tthis.filterSessions(\"\");\n\n\t\t// Handle Enter in search input - select current item\n\t\tthis.searchInput.onSubmit = () => {\n\t\t\tif (this.filteredSessions[this.selectedIndex]) {\n\t\t\t\tconst selected = this.filteredSessions[this.selectedIndex];\n\t\t\t\tif (this.onSelect) {\n\t\t\t\t\tthis.onSelect(selected.session.path);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\n\tsetSortMode(sortMode: SortMode): void {\n\t\tthis.sortMode = sortMode;\n\t\tthis.filterSessions(this.searchInput.getValue());\n\t}\n\n\tsetNameFilter(nameFilter: NameFilter): void {\n\t\tthis.nameFilter = nameFilter;\n\t\tthis.filterSessions(this.searchInput.getValue());\n\t}\n\n\tsetSessions(sessions: SessionInfo[], showCwd: boolean): void {\n\t\tthis.allSessions = sessions;\n\t\tthis.showCwd = showCwd;\n\t\tthis.filterSessions(this.searchInput.getValue());\n\t}\n\n\tprivate filterSessions(query: string): void {\n\t\tconst trimmed = query.trim();\n\t\tconst nameFiltered =\n\t\t\tthis.nameFilter === \"all\" ? this.allSessions : this.allSessions.filter((session) => hasSessionName(session));\n\n\t\tif (this.sortMode === \"threaded\" && !trimmed) {\n\t\t\t// Threaded mode without search: show tree structure\n\t\t\tconst roots = buildSessionTree(nameFiltered);\n\t\t\tthis.filteredSessions = flattenSessionTree(roots);\n\t\t} else {\n\t\t\t// Other modes or with search: flat list\n\t\t\tconst filtered = filterAndSortSessions(nameFiltered, query, this.sortMode, \"all\");\n\t\t\tthis.filteredSessions = filtered.map((session) => ({\n\t\t\t\tsession,\n\t\t\t\tdepth: 0,\n\t\t\t\tisLast: true,\n\t\t\t\tancestorContinues: [],\n\t\t\t}));\n\t\t}\n\t\tthis.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredSessions.length - 1));\n\t}\n\n\tprivate setConfirmingDeletePath(path: string | null): void {\n\t\tthis.confirmingDeletePath = path;\n\t\tthis.onDeleteConfirmationChange?.(path);\n\t}\n\n\tprivate startDeleteConfirmationForSelectedSession(): void {\n\t\tconst selected = this.filteredSessions[this.selectedIndex];\n\t\tif (!selected) return;\n\n\t\t// Prevent deleting current session\n\t\tif (this.isCurrentSessionPath(selected.session.path)) {\n\t\t\tthis.onError?.(\"Cannot delete the currently active session\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.setConfirmingDeletePath(selected.session.path);\n\t}\n\n\tprivate isCurrentSessionPath(path: string): boolean {\n\t\tif (!this.currentSessionCanonicalPath) return false;\n\t\treturn (canonicalizePath(path) ?? path) === this.currentSessionCanonicalPath;\n\t}\n\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\n\t\t// Render search input\n\t\tlines.push(...this.searchInput.render(width));\n\t\tlines.push(\"\"); // Blank line after search\n\n\t\tif (this.filteredSessions.length === 0) {\n\t\t\tlet emptyMessage: string;\n\t\t\tif (this.nameFilter === \"named\") {\n\t\t\t\tconst toggleKey = keyText(\"app.session.toggleNamedFilter\");\n\t\t\t\tif (this.showCwd) {\n\t\t\t\t\temptyMessage = ` No named sessions found. Press ${toggleKey} to show all.`;\n\t\t\t\t} else {\n\t\t\t\t\temptyMessage = ` No named sessions in current folder. Press ${toggleKey} to show all, or Tab to view all.`;\n\t\t\t\t}\n\t\t\t} else if (this.showCwd) {\n\t\t\t\t// \"All\" scope - no sessions anywhere that match filter\n\t\t\t\temptyMessage = \" No sessions found\";\n\t\t\t} else {\n\t\t\t\t// \"Current folder\" scope - hint to try \"all\"\n\t\t\t\temptyMessage = \" No sessions in current folder. Press Tab to view all.\";\n\t\t\t}\n\t\t\tlines.push(theme.fg(\"muted\", truncateToWidth(emptyMessage, width, \"…\")));\n\t\t\treturn lines;\n\t\t}\n\n\t\t// Calculate visible range with scrolling\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredSessions.length - this.maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisible, this.filteredSessions.length);\n\n\t\t// Render visible sessions (one line each with tree structure)\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst node = this.filteredSessions[i]!;\n\t\t\tconst session = node.session;\n\t\t\tconst isSelected = i === this.selectedIndex;\n\t\t\tconst isConfirmingDelete = session.path === this.confirmingDeletePath;\n\t\t\tconst isCurrent = this.isCurrentSessionPath(session.path);\n\n\t\t\t// Build tree prefix\n\t\t\tconst prefix = this.buildTreePrefix(node);\n\n\t\t\t// Session display text (name or first message)\n\t\t\tconst hasName = !!session.name;\n\t\t\tconst displayText = session.name ?? session.firstMessage;\n\t\t\tconst normalizedMessage = displayText.replace(/[\\x00-\\x1f\\x7f]/g, \" \").trim();\n\n\t\t\t// Right side: message count and age\n\t\t\tconst age = formatSessionDate(session.modified);\n\t\t\tconst msgCount = String(session.messageCount);\n\t\t\tlet rightPart = `${msgCount} ${age}`;\n\t\t\tif (this.showCwd && session.cwd) {\n\t\t\t\trightPart = `${shortenPath(session.cwd)} ${rightPart}`;\n\t\t\t}\n\t\t\tif (this.showPath) {\n\t\t\t\trightPart = `${shortenPath(session.path)} ${rightPart}`;\n\t\t\t}\n\n\t\t\t// Cursor\n\t\t\tconst cursor = isSelected ? theme.fg(\"accent\", \"› \") : \" \";\n\n\t\t\t// Calculate available width for message\n\t\t\tconst prefixWidth = visibleWidth(prefix);\n\t\t\tconst rightWidth = visibleWidth(rightPart) + 2; // +2 for spacing\n\t\t\tconst availableForMsg = width - 2 - prefixWidth - rightWidth; // -2 for cursor\n\n\t\t\tconst truncatedMsg = truncateToWidth(normalizedMessage, Math.max(10, availableForMsg), \"…\");\n\n\t\t\t// Style message\n\t\t\tlet messageColor: \"error\" | \"warning\" | \"accent\" | null = null;\n\t\t\tif (isConfirmingDelete) {\n\t\t\t\tmessageColor = \"error\";\n\t\t\t} else if (isCurrent) {\n\t\t\t\tmessageColor = \"accent\";\n\t\t\t} else if (hasName) {\n\t\t\t\tmessageColor = \"warning\";\n\t\t\t}\n\t\t\tlet styledMsg = messageColor ? theme.fg(messageColor, truncatedMsg) : truncatedMsg;\n\t\t\tif (isSelected) {\n\t\t\t\tstyledMsg = theme.bold(styledMsg);\n\t\t\t}\n\n\t\t\t// Build line\n\t\t\tconst leftPart = cursor + theme.fg(\"dim\", prefix) + styledMsg;\n\t\t\tconst leftWidth = visibleWidth(leftPart);\n\t\t\tconst spacing = Math.max(1, width - leftWidth - visibleWidth(rightPart));\n\t\t\tconst styledRight = theme.fg(isConfirmingDelete ? \"error\" : \"dim\", rightPart);\n\n\t\t\tlet line = leftPart + \" \".repeat(spacing) + styledRight;\n\t\t\tif (isSelected) {\n\t\t\t\tline = theme.bg(\"selectedBg\", line);\n\t\t\t}\n\t\t\tlines.push(truncateToWidth(line, width));\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.filteredSessions.length) {\n\t\t\tconst scrollText = ` (${this.selectedIndex + 1}/${this.filteredSessions.length})`;\n\t\t\tconst scrollInfo = theme.fg(\"muted\", truncateToWidth(scrollText, width, \"\"));\n\t\t\tlines.push(scrollInfo);\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\tprivate buildTreePrefix(node: FlatSessionNode): string {\n\t\tif (node.depth === 0) {\n\t\t\treturn \"\";\n\t\t}\n\n\t\tconst parts = node.ancestorContinues.map((continues) => (continues ? \"│ \" : \" \"));\n\t\tconst branch = node.isLast ? \"└─ \" : \"├─ \";\n\t\treturn parts.join(\"\") + branch;\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\n\t\t// Handle delete confirmation state first - intercept all keys\n\t\tif (this.confirmingDeletePath !== null) {\n\t\t\tif (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\t\tconst pathToDelete = this.confirmingDeletePath;\n\t\t\t\tthis.setConfirmingDeletePath(null);\n\t\t\t\tvoid this.onDeleteSession?.(pathToDelete);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\t\tthis.setConfirmingDeletePath(null);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Ignore all other keys while confirming\n\t\t\treturn;\n\t\t}\n\n\t\tif (kb.matches(keyData, \"tui.input.tab\")) {\n\t\t\tif (this.onToggleScope) {\n\t\t\t\tthis.onToggleScope();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (kb.matches(keyData, \"app.session.toggleSort\")) {\n\t\t\tthis.onToggleSort?.();\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.keybindings.matches(keyData, \"app.session.toggleNamedFilter\")) {\n\t\t\tthis.onToggleNameFilter?.();\n\t\t\treturn;\n\t\t}\n\n\t\t// Ctrl+P: toggle path display\n\t\tif (kb.matches(keyData, \"app.session.togglePath\")) {\n\t\t\tthis.showPath = !this.showPath;\n\t\t\tthis.onTogglePath?.(this.showPath);\n\t\t\treturn;\n\t\t}\n\n\t\t// Ctrl+D: initiate delete confirmation (useful on terminals that don't distinguish Ctrl+Backspace from Backspace)\n\t\tif (kb.matches(keyData, \"app.session.delete\")) {\n\t\t\tthis.startDeleteConfirmationForSelectedSession();\n\t\t\treturn;\n\t\t}\n\n\t\t// Rename selected session\n\t\tif (kb.matches(keyData, \"app.session.rename\")) {\n\t\t\tconst selected = this.filteredSessions[this.selectedIndex];\n\t\t\tif (selected) {\n\t\t\t\tthis.onRenameSession?.(selected.session.path);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Ctrl+Backspace: non-invasive convenience alias for delete\n\t\t// Only triggers deletion when the query is empty; otherwise it is forwarded to the input\n\t\tif (kb.matches(keyData, \"app.session.deleteNoninvasive\")) {\n\t\t\tif (this.searchInput.getValue().length > 0) {\n\t\t\t\tthis.searchInput.handleInput(keyData);\n\t\t\t\tthis.filterSessions(this.searchInput.getValue());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.startDeleteConfirmationForSelectedSession();\n\t\t\treturn;\n\t\t}\n\n\t\t// Up arrow\n\t\tif (kb.matches(keyData, \"tui.select.up\")) {\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - 1);\n\t\t}\n\t\t// Down arrow\n\t\telse if (kb.matches(keyData, \"tui.select.down\")) {\n\t\t\tthis.selectedIndex = Math.min(this.filteredSessions.length - 1, this.selectedIndex + 1);\n\t\t}\n\t\t// Page up - jump up by maxVisible items\n\t\telse if (kb.matches(keyData, \"tui.select.pageUp\")) {\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - this.maxVisible);\n\t\t}\n\t\t// Page down - jump down by maxVisible items\n\t\telse if (kb.matches(keyData, \"tui.select.pageDown\")) {\n\t\t\tthis.selectedIndex = Math.min(this.filteredSessions.length - 1, this.selectedIndex + this.maxVisible);\n\t\t}\n\t\t// Enter\n\t\telse if (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\tconst selected = this.filteredSessions[this.selectedIndex];\n\t\t\tif (selected && this.onSelect) {\n\t\t\t\tthis.onSelect(selected.session.path);\n\t\t\t}\n\t\t}\n\t\t// Escape - cancel\n\t\telse if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tif (this.onCancel) {\n\t\t\t\tthis.onCancel();\n\t\t\t}\n\t\t}\n\t\t// Pass everything else to search input\n\t\telse {\n\t\t\tthis.searchInput.handleInput(keyData);\n\t\t\tthis.filterSessions(this.searchInput.getValue());\n\t\t}\n\t}\n}\n\ntype SessionsLoader = (onProgress?: SessionListProgress) => Promise;\n\n/**\n * Delete a session file, trying the `trash` CLI first, then falling back to unlink\n */\nasync function deleteSessionFile(\n\tsessionPath: string,\n): Promise<{ ok: boolean; method: \"trash\" | \"unlink\"; error?: string }> {\n\t// Try `trash` first (if installed)\n\tconst trashArgs = sessionPath.startsWith(\"-\") ? [\"--\", sessionPath] : [sessionPath];\n\tconst trashResult = spawnSync(\"trash\", trashArgs, { encoding: \"utf-8\" });\n\n\tconst getTrashErrorHint = (): string | null => {\n\t\tconst parts: string[] = [];\n\t\tif (trashResult.error) {\n\t\t\tparts.push(trashResult.error.message);\n\t\t}\n\t\tconst stderr = trashResult.stderr?.trim();\n\t\tif (stderr) {\n\t\t\tparts.push(stderr.split(\"\\n\")[0] ?? stderr);\n\t\t}\n\t\tif (parts.length === 0) return null;\n\t\treturn `trash: ${parts.join(\" · \").slice(0, 200)}`;\n\t};\n\n\t// If trash reports success, or the file is gone afterwards, treat it as successful\n\tif (trashResult.status === 0 || !existsSync(sessionPath)) {\n\t\treturn { ok: true, method: \"trash\" };\n\t}\n\n\t// Fallback to permanent deletion\n\ttry {\n\t\tawait unlink(sessionPath);\n\t\treturn { ok: true, method: \"unlink\" };\n\t} catch (err) {\n\t\tconst unlinkError = err instanceof Error ? err.message : String(err);\n\t\tconst trashErrorHint = getTrashErrorHint();\n\t\tconst error = trashErrorHint ? `${unlinkError} (${trashErrorHint})` : unlinkError;\n\t\treturn { ok: false, method: \"unlink\", error };\n\t}\n}\n\n/**\n * Component that renders a session selector\n */\nexport class SessionSelectorComponent extends Container implements Focusable {\n\thandleInput(data: string): void {\n\t\tif (this.mode === \"rename\") {\n\t\t\tconst kb = getKeybindings();\n\t\t\tif (kb.matches(data, \"tui.select.cancel\")) {\n\t\t\t\tthis.exitRenameMode();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.renameInput.handleInput(data);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.sessionList.handleInput(data);\n\t}\n\n\tprivate canRename = true;\n\tprivate sessionList: SessionList;\n\tprivate header: SessionSelectorHeader;\n\tprivate keybindings: KeybindingsManager;\n\tprivate scope: SessionScope = \"current\";\n\tprivate sortMode: SortMode = \"threaded\";\n\tprivate nameFilter: NameFilter = \"all\";\n\tprivate currentSessions: SessionInfo[] | null = null;\n\tprivate allSessions: SessionInfo[] | null = null;\n\tprivate currentSessionsLoader: SessionsLoader;\n\tprivate allSessionsLoader: SessionsLoader;\n\tprivate requestRender: () => void;\n\tprivate renameSession?: (sessionPath: string, currentName: string | undefined) => Promise;\n\tprivate currentLoading = false;\n\tprivate allLoading = false;\n\tprivate allLoadSeq = 0;\n\n\tprivate mode: \"list\" | \"rename\" = \"list\";\n\tprivate renameInput = new Input();\n\tprivate renameTargetPath: string | null = null;\n\n\t// Focusable implementation - propagate to sessionList for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.sessionList.focused = value;\n\t\tthis.renameInput.focused = value;\n\t\tif (value && this.mode === \"rename\") {\n\t\t\tthis.renameInput.focused = true;\n\t\t}\n\t}\n\n\tprivate buildBaseLayout(content: Component, options?: { showHeader?: boolean }): void {\n\t\tthis.clear();\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder((s) => theme.fg(\"accent\", s)));\n\t\tthis.addChild(new Spacer(1));\n\t\tif (options?.showHeader ?? true) {\n\t\t\tthis.addChild(this.header);\n\t\t\tthis.addChild(new Spacer(1));\n\t\t}\n\t\tthis.addChild(content);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder((s) => theme.fg(\"accent\", s)));\n\t}\n\n\tconstructor(\n\t\tcurrentSessionsLoader: SessionsLoader,\n\t\tallSessionsLoader: SessionsLoader,\n\t\tonSelect: (sessionPath: string) => void,\n\t\tonCancel: () => void,\n\t\tonExit: () => void,\n\t\trequestRender: () => void,\n\t\toptions?: {\n\t\t\trenameSession?: (sessionPath: string, currentName: string | undefined) => Promise;\n\t\t\tshowRenameHint?: boolean;\n\t\t\tkeybindings?: KeybindingsManager;\n\t\t},\n\t\tcurrentSessionFilePath?: string,\n\t) {\n\t\tsuper();\n\t\tthis.keybindings = options?.keybindings ?? KeybindingsManager.create();\n\t\tthis.currentSessionsLoader = currentSessionsLoader;\n\t\tthis.allSessionsLoader = allSessionsLoader;\n\t\tthis.requestRender = requestRender;\n\t\tthis.header = new SessionSelectorHeader(this.scope, this.sortMode, this.nameFilter, this.requestRender);\n\t\tconst renameSession = options?.renameSession;\n\t\tthis.renameSession = renameSession;\n\t\tthis.canRename = !!renameSession;\n\t\tthis.header.setShowRenameHint(options?.showRenameHint ?? this.canRename);\n\n\t\t// Create session list (starts empty, will be populated after load)\n\t\tthis.sessionList = new SessionList(\n\t\t\t[],\n\t\t\tfalse,\n\t\t\tthis.sortMode,\n\t\t\tthis.nameFilter,\n\t\t\tthis.keybindings,\n\t\t\tcurrentSessionFilePath,\n\t\t);\n\n\t\tthis.buildBaseLayout(this.sessionList);\n\n\t\tthis.renameInput.onSubmit = (value) => {\n\t\t\tvoid this.confirmRename(value);\n\t\t};\n\n\t\t// Ensure header status timeouts are cleared when leaving the selector\n\t\tconst clearStatusMessage = () => this.header.setStatusMessage(null);\n\t\tthis.sessionList.onSelect = (sessionPath) => {\n\t\t\tclearStatusMessage();\n\t\t\tonSelect(sessionPath);\n\t\t};\n\t\tthis.sessionList.onCancel = () => {\n\t\t\tclearStatusMessage();\n\t\t\tonCancel();\n\t\t};\n\t\tthis.sessionList.onExit = () => {\n\t\t\tclearStatusMessage();\n\t\t\tonExit();\n\t\t};\n\t\tthis.sessionList.onToggleScope = () => this.toggleScope();\n\t\tthis.sessionList.onToggleSort = () => this.toggleSortMode();\n\t\tthis.sessionList.onToggleNameFilter = () => this.toggleNameFilter();\n\t\tthis.sessionList.onRenameSession = (sessionPath) => {\n\t\t\tif (!renameSession) return;\n\t\t\tif (this.scope === \"current\" && this.currentLoading) return;\n\t\t\tif (this.scope === \"all\" && this.allLoading) return;\n\n\t\t\tconst sessions = this.scope === \"all\" ? (this.allSessions ?? []) : (this.currentSessions ?? []);\n\t\t\tconst session = sessions.find((s) => s.path === sessionPath);\n\t\t\tthis.enterRenameMode(sessionPath, session?.name);\n\t\t};\n\n\t\t// Sync list events to header\n\t\tthis.sessionList.onTogglePath = (showPath) => {\n\t\t\tthis.header.setShowPath(showPath);\n\t\t\tthis.requestRender();\n\t\t};\n\t\tthis.sessionList.onDeleteConfirmationChange = (path) => {\n\t\t\tthis.header.setConfirmingDeletePath(path);\n\t\t\tthis.requestRender();\n\t\t};\n\t\tthis.sessionList.onError = (msg) => {\n\t\t\tthis.header.setStatusMessage({ type: \"error\", message: msg }, 3000);\n\t\t\tthis.requestRender();\n\t\t};\n\n\t\t// Handle session deletion\n\t\tthis.sessionList.onDeleteSession = async (sessionPath: string) => {\n\t\t\tconst result = await deleteSessionFile(sessionPath);\n\n\t\t\tif (result.ok) {\n\t\t\t\tif (this.currentSessions) {\n\t\t\t\t\tthis.currentSessions = this.currentSessions.filter((s) => s.path !== sessionPath);\n\t\t\t\t}\n\t\t\t\tif (this.allSessions) {\n\t\t\t\t\tthis.allSessions = this.allSessions.filter((s) => s.path !== sessionPath);\n\t\t\t\t}\n\n\t\t\t\tconst sessions = this.scope === \"all\" ? (this.allSessions ?? []) : (this.currentSessions ?? []);\n\t\t\t\tconst showCwd = this.scope === \"all\";\n\t\t\t\tthis.sessionList.setSessions(sessions, showCwd);\n\n\t\t\t\tconst msg = result.method === \"trash\" ? \"Session moved to trash\" : \"Session deleted\";\n\t\t\t\tthis.header.setStatusMessage({ type: \"info\", message: msg }, 2000);\n\t\t\t\tawait this.refreshSessionsAfterMutation();\n\t\t\t} else {\n\t\t\t\tconst errorMessage = result.error ?? \"Unknown error\";\n\t\t\t\tthis.header.setStatusMessage({ type: \"error\", message: `Failed to delete: ${errorMessage}` }, 3000);\n\t\t\t}\n\n\t\t\tthis.requestRender();\n\t\t};\n\n\t\t// Start loading current sessions immediately\n\t\tthis.loadCurrentSessions();\n\t}\n\n\tprivate loadCurrentSessions(): void {\n\t\tvoid this.loadScope(\"current\", \"initial\");\n\t}\n\n\tprivate enterRenameMode(sessionPath: string, currentName: string | undefined): void {\n\t\tthis.mode = \"rename\";\n\t\tthis.renameTargetPath = sessionPath;\n\t\tthis.renameInput.setValue(currentName ?? \"\");\n\t\tthis.renameInput.focused = true;\n\n\t\tconst panel = new Container();\n\t\tpanel.addChild(new Text(theme.bold(\"Rename Session\"), 1, 0));\n\t\tpanel.addChild(new Spacer(1));\n\t\tpanel.addChild(this.renameInput);\n\t\tpanel.addChild(new Spacer(1));\n\t\tpanel.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.fg(\"muted\", `${keyText(\"tui.select.confirm\")} to save · ${keyText(\"tui.select.cancel\")} to cancel`),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\n\t\tthis.buildBaseLayout(panel, { showHeader: false });\n\t\tthis.requestRender();\n\t}\n\n\tprivate exitRenameMode(): void {\n\t\tthis.mode = \"list\";\n\t\tthis.renameTargetPath = null;\n\n\t\tthis.buildBaseLayout(this.sessionList);\n\n\t\tthis.requestRender();\n\t}\n\n\tprivate async confirmRename(value: string): Promise {\n\t\tconst next = value.trim();\n\t\tif (!next) return;\n\t\tconst target = this.renameTargetPath;\n\t\tif (!target) {\n\t\t\tthis.exitRenameMode();\n\t\t\treturn;\n\t\t}\n\n\t\t// Find current name for callback\n\t\tconst renameSession = this.renameSession;\n\t\tif (!renameSession) {\n\t\t\tthis.exitRenameMode();\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tawait renameSession(target, next);\n\t\t\tawait this.refreshSessionsAfterMutation();\n\t\t} finally {\n\t\t\tthis.exitRenameMode();\n\t\t}\n\t}\n\n\tprivate async loadScope(scope: SessionScope, reason: \"initial\" | \"refresh\" | \"toggle\"): Promise {\n\t\tconst showCwd = scope === \"all\";\n\n\t\t// Mark loading\n\t\tif (scope === \"current\") {\n\t\t\tthis.currentLoading = true;\n\t\t} else {\n\t\t\tthis.allLoading = true;\n\t\t}\n\n\t\tconst seq = scope === \"all\" ? ++this.allLoadSeq : undefined;\n\t\tthis.header.setScope(scope);\n\t\tthis.header.setLoading(true);\n\t\tthis.requestRender();\n\n\t\tconst onProgress = (loaded: number, total: number) => {\n\t\t\tif (scope !== this.scope) return;\n\t\t\tif (seq !== undefined && seq !== this.allLoadSeq) return;\n\t\t\tthis.header.setProgress(loaded, total);\n\t\t\tthis.requestRender();\n\t\t};\n\n\t\ttry {\n\t\t\tconst sessions = await (scope === \"current\"\n\t\t\t\t? this.currentSessionsLoader(onProgress)\n\t\t\t\t: this.allSessionsLoader(onProgress));\n\n\t\t\tif (scope === \"current\") {\n\t\t\t\tthis.currentSessions = sessions;\n\t\t\t\tthis.currentLoading = false;\n\t\t\t} else {\n\t\t\t\tthis.allSessions = sessions;\n\t\t\t\tthis.allLoading = false;\n\t\t\t}\n\n\t\t\tif (scope !== this.scope) return;\n\t\t\tif (seq !== undefined && seq !== this.allLoadSeq) return;\n\n\t\t\tthis.header.setLoading(false);\n\t\t\tthis.sessionList.setSessions(sessions, showCwd);\n\t\t\tthis.requestRender();\n\t\t} catch (err) {\n\t\t\tif (scope === \"current\") {\n\t\t\t\tthis.currentLoading = false;\n\t\t\t} else {\n\t\t\t\tthis.allLoading = false;\n\t\t\t}\n\n\t\t\tif (scope !== this.scope) return;\n\t\t\tif (seq !== undefined && seq !== this.allLoadSeq) return;\n\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthis.header.setLoading(false);\n\t\t\tthis.header.setStatusMessage({ type: \"error\", message: `Failed to load sessions: ${message}` }, 4000);\n\n\t\t\tif (reason === \"initial\") {\n\t\t\t\tthis.sessionList.setSessions([], showCwd);\n\t\t\t}\n\t\t\tthis.requestRender();\n\t\t}\n\t}\n\n\tprivate toggleSortMode(): void {\n\t\t// Cycle: threaded -> recent -> relevance -> threaded\n\t\tthis.sortMode = this.sortMode === \"threaded\" ? \"recent\" : this.sortMode === \"recent\" ? \"relevance\" : \"threaded\";\n\t\tthis.header.setSortMode(this.sortMode);\n\t\tthis.sessionList.setSortMode(this.sortMode);\n\t\tthis.requestRender();\n\t}\n\n\tprivate toggleNameFilter(): void {\n\t\tthis.nameFilter = this.nameFilter === \"all\" ? \"named\" : \"all\";\n\t\tthis.header.setNameFilter(this.nameFilter);\n\t\tthis.sessionList.setNameFilter(this.nameFilter);\n\t\tthis.requestRender();\n\t}\n\n\tprivate async refreshSessionsAfterMutation(): Promise {\n\t\tawait this.loadScope(this.scope, \"refresh\");\n\t}\n\n\tprivate toggleScope(): void {\n\t\tif (this.scope === \"current\") {\n\t\t\tthis.scope = \"all\";\n\t\t\tthis.header.setScope(this.scope);\n\n\t\t\tif (this.allSessions !== null) {\n\t\t\t\tthis.header.setLoading(false);\n\t\t\t\tthis.sessionList.setSessions(this.allSessions, true);\n\t\t\t\tthis.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!this.allLoading) {\n\t\t\t\tvoid this.loadScope(\"all\", \"toggle\");\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tthis.scope = \"current\";\n\t\tthis.header.setScope(this.scope);\n\t\tthis.header.setLoading(this.currentLoading);\n\t\tthis.sessionList.setSessions(this.currentSessions ?? [], false);\n\t\tthis.requestRender();\n\t}\n\n\tgetSessionList(): SessionList {\n\t\treturn this.sessionList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/settings-selector.d.ts b/dist/modes/interactive/components/settings-selector.d.ts new file mode 100644 index 0000000..5efe6ce --- /dev/null +++ b/dist/modes/interactive/components/settings-selector.d.ts @@ -0,0 +1,77 @@ +import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; +import type { Transport } from "@earendil-works/pi-ai"; +import { Container, SettingsList } from "@earendil-works/pi-tui"; +import type { DefaultProjectTrust, WarningSettings } from "../../../core/settings-manager.ts"; +import { type TerminalTheme } from "../theme/theme.ts"; +export interface SettingsConfig { + autoCompact: boolean; + showImages: boolean; + imageWidthCells: number; + autoResizeImages: boolean; + blockImages: boolean; + enableSkillCommands: boolean; + steeringMode: "all" | "one-at-a-time"; + followUpMode: "all" | "one-at-a-time"; + transport: Transport; + httpIdleTimeoutMs: number; + thinkingLevel: ThinkingLevel; + availableThinkingLevels: ThinkingLevel[]; + currentTheme: string; + terminalTheme: TerminalTheme; + availableThemes: string[]; + hideThinkingBlock: boolean; + showCacheMissNotices: boolean; + collapseChangelog: boolean; + enableInstallTelemetry: boolean; + doubleEscapeAction: "fork" | "tree" | "none"; + treeFilterMode: "default" | "no-tools" | "user-only" | "labeled-only" | "all"; + showHardwareCursor: boolean; + editorPaddingX: number; + outputPad: 0 | 1; + autocompleteMaxVisible: number; + quietStartup: boolean; + defaultProjectTrust: DefaultProjectTrust; + clearOnShrink: boolean; + showTerminalProgress: boolean; + warnings: WarningSettings; +} +export interface SettingsCallbacks { + onAutoCompactChange: (enabled: boolean) => void; + onShowImagesChange: (enabled: boolean) => void; + onImageWidthCellsChange: (width: number) => void; + onAutoResizeImagesChange: (enabled: boolean) => void; + onBlockImagesChange: (blocked: boolean) => void; + onEnableSkillCommandsChange: (enabled: boolean) => void; + onSteeringModeChange: (mode: "all" | "one-at-a-time") => void; + onFollowUpModeChange: (mode: "all" | "one-at-a-time") => void; + onTransportChange: (transport: Transport) => void; + onHttpIdleTimeoutMsChange: (timeoutMs: number) => void; + onThinkingLevelChange: (level: ThinkingLevel) => void; + onThemeChange: (theme: string) => void; + onThemePreview?: (theme: string) => void; + onHideThinkingBlockChange: (hidden: boolean) => void; + onShowCacheMissNoticesChange: (shown: boolean) => void; + onCollapseChangelogChange: (collapsed: boolean) => void; + onEnableInstallTelemetryChange: (enabled: boolean) => void; + onDoubleEscapeActionChange: (action: "fork" | "tree" | "none") => void; + onTreeFilterModeChange: (mode: "default" | "no-tools" | "user-only" | "labeled-only" | "all") => void; + onShowHardwareCursorChange: (enabled: boolean) => void; + onEditorPaddingXChange: (padding: number) => void; + onOutputPadChange: (padding: 0 | 1) => void; + onAutocompleteMaxVisibleChange: (maxVisible: number) => void; + onQuietStartupChange: (enabled: boolean) => void; + onDefaultProjectTrustChange: (defaultProjectTrust: DefaultProjectTrust) => void; + onClearOnShrinkChange: (enabled: boolean) => void; + onShowTerminalProgressChange: (enabled: boolean) => void; + onWarningsChange: (warnings: WarningSettings) => void; + onCancel: () => void; +} +/** + * Main settings selector component. + */ +export declare class SettingsSelectorComponent extends Container { + private settingsList; + constructor(config: SettingsConfig, callbacks: SettingsCallbacks); + getSettingsList(): SettingsList; +} +//# sourceMappingURL=settings-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/settings-selector.d.ts.map b/dist/modes/interactive/components/settings-selector.d.ts.map new file mode 100644 index 0000000..fda9648 --- /dev/null +++ b/dist/modes/interactive/components/settings-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"settings-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/settings-selector.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAEN,SAAS,EAMT,YAAY,EAGZ,MAAM,wBAAwB,CAAC;AAEhC,OAAO,KAAK,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AAC9F,OAAO,EAIN,KAAK,aAAa,EAElB,MAAM,mBAAmB,CAAC;AA6B3B,MAAM,WAAW,cAAc;IAC9B,WAAW,EAAE,OAAO,CAAC;IACrB,UAAU,EAAE,OAAO,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;IACxB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,WAAW,EAAE,OAAO,CAAC;IACrB,mBAAmB,EAAE,OAAO,CAAC;IAC7B,YAAY,EAAE,KAAK,GAAG,eAAe,CAAC;IACtC,YAAY,EAAE,KAAK,GAAG,eAAe,CAAC;IACtC,SAAS,EAAE,SAAS,CAAC;IACrB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,aAAa,EAAE,aAAa,CAAC;IAC7B,uBAAuB,EAAE,aAAa,EAAE,CAAC;IACzC,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,aAAa,CAAC;IAC7B,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B,iBAAiB,EAAE,OAAO,CAAC;IAC3B,oBAAoB,EAAE,OAAO,CAAC;IAC9B,iBAAiB,EAAE,OAAO,CAAC;IAC3B,sBAAsB,EAAE,OAAO,CAAC;IAChC,kBAAkB,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IAC7C,cAAc,EAAE,SAAS,GAAG,UAAU,GAAG,WAAW,GAAG,cAAc,GAAG,KAAK,CAAC;IAC9E,kBAAkB,EAAE,OA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} from \"@earendil-works/pi-ai\";\nimport {\n\ttype Component,\n\tContainer,\n\tgetCapabilities,\n\ttype SelectItem,\n\tSelectList,\n\ttype SelectListLayoutOptions,\n\ttype SettingItem,\n\tSettingsList,\n\tSpacer,\n\tText,\n} from \"@earendil-works/pi-tui\";\nimport { formatHttpIdleTimeoutMs, HTTP_IDLE_TIMEOUT_CHOICES } from \"../../../core/http-dispatcher.ts\";\nimport type { DefaultProjectTrust, WarningSettings } from \"../../../core/settings-manager.ts\";\nimport {\n\tgetSelectListTheme,\n\tgetSettingsListTheme,\n\tparseAutoThemeSetting,\n\ttype TerminalTheme,\n\ttheme,\n} from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyDisplayText } from \"./keybinding-hints.ts\";\n\nconst SETTINGS_SUBMENU_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {\n\tminPrimaryColumnWidth: 12,\n\tmaxPrimaryColumnWidth: 32,\n};\n\nconst THINKING_DESCRIPTIONS: Record = {\n\toff: \"No reasoning\",\n\tminimal: \"Very brief reasoning (~1k tokens)\",\n\tlow: \"Light reasoning (~2k tokens)\",\n\tmedium: \"Moderate reasoning (~8k tokens)\",\n\thigh: \"Deep reasoning (~16k tokens)\",\n\txhigh: \"Extra-high reasoning (~32k tokens)\",\n\tmax: \"Maximum reasoning\",\n};\n\nconst DEFAULT_PROJECT_TRUST_LABELS: Record = {\n\task: \"Ask\",\n\talways: \"Always trust\",\n\tnever: \"Never trust\",\n};\n\nconst DEFAULT_PROJECT_TRUST_BY_LABEL = new Map(\n\tObject.entries(DEFAULT_PROJECT_TRUST_LABELS).map(([value, label]) => [label, value as DefaultProjectTrust]),\n);\n\nexport interface SettingsConfig {\n\tautoCompact: boolean;\n\tshowImages: boolean;\n\timageWidthCells: number;\n\tautoResizeImages: boolean;\n\tblockImages: boolean;\n\tenableSkillCommands: boolean;\n\tsteeringMode: \"all\" | \"one-at-a-time\";\n\tfollowUpMode: \"all\" | \"one-at-a-time\";\n\ttransport: Transport;\n\thttpIdleTimeoutMs: number;\n\tthinkingLevel: ThinkingLevel;\n\tavailableThinkingLevels: ThinkingLevel[];\n\tcurrentTheme: string;\n\tterminalTheme: TerminalTheme;\n\tavailableThemes: string[];\n\thideThinkingBlock: boolean;\n\tshowCacheMissNotices: boolean;\n\tcollapseChangelog: boolean;\n\tenableInstallTelemetry: boolean;\n\tdoubleEscapeAction: \"fork\" | \"tree\" | \"none\";\n\ttreeFilterMode: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\";\n\tshowHardwareCursor: boolean;\n\teditorPaddingX: number;\n\toutputPad: 0 | 1;\n\tautocompleteMaxVisible: number;\n\tquietStartup: boolean;\n\tdefaultProjectTrust: DefaultProjectTrust;\n\tclearOnShrink: boolean;\n\tshowTerminalProgress: boolean;\n\twarnings: WarningSettings;\n}\n\nexport interface SettingsCallbacks {\n\tonAutoCompactChange: (enabled: boolean) => void;\n\tonShowImagesChange: (enabled: boolean) => void;\n\tonImageWidthCellsChange: (width: number) => void;\n\tonAutoResizeImagesChange: (enabled: boolean) => void;\n\tonBlockImagesChange: (blocked: boolean) => void;\n\tonEnableSkillCommandsChange: (enabled: boolean) => void;\n\tonSteeringModeChange: (mode: \"all\" | \"one-at-a-time\") => void;\n\tonFollowUpModeChange: (mode: \"all\" | \"one-at-a-time\") => void;\n\tonTransportChange: (transport: Transport) => void;\n\tonHttpIdleTimeoutMsChange: (timeoutMs: number) => void;\n\tonThinkingLevelChange: (level: ThinkingLevel) => void;\n\tonThemeChange: (theme: string) => void;\n\tonThemePreview?: (theme: string) => void;\n\tonHideThinkingBlockChange: (hidden: boolean) => void;\n\tonShowCacheMissNoticesChange: (shown: boolean) => void;\n\tonCollapseChangelogChange: (collapsed: boolean) => void;\n\tonEnableInstallTelemetryChange: (enabled: boolean) => void;\n\tonDoubleEscapeActionChange: (action: \"fork\" | \"tree\" | \"none\") => void;\n\tonTreeFilterModeChange: (mode: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\") => void;\n\tonShowHardwareCursorChange: (enabled: boolean) => void;\n\tonEditorPaddingXChange: (padding: number) => void;\n\tonOutputPadChange: (padding: 0 | 1) => void;\n\tonAutocompleteMaxVisibleChange: (maxVisible: number) => void;\n\tonQuietStartupChange: (enabled: boolean) => void;\n\tonDefaultProjectTrustChange: (defaultProjectTrust: DefaultProjectTrust) => void;\n\tonClearOnShrinkChange: (enabled: boolean) => void;\n\tonShowTerminalProgressChange: (enabled: boolean) => void;\n\tonWarningsChange: (warnings: WarningSettings) => void;\n\tonCancel: () => void;\n}\n\n/**\n * A submenu component for selecting from a list of options.\n */\nclass WarningSettingsSubmenu extends Container {\n\tprivate settingsList: SettingsList;\n\tprivate state: WarningSettings;\n\n\tconstructor(warnings: WarningSettings, onChange: (warnings: WarningSettings) => void, onCancel: () => void) {\n\t\tsuper();\n\n\t\tthis.state = { ...warnings };\n\n\t\tconst items: SettingItem[] = [\n\t\t\t{\n\t\t\t\tid: \"anthropic-extra-usage\",\n\t\t\t\tlabel: \"Anthropic extra usage\",\n\t\t\t\tdescription: \"Warn when Anthropic subscription auth may use paid extra usage\",\n\t\t\t\tcurrentValue: (this.state.anthropicExtraUsage ?? true) ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t];\n\n\t\tthis.settingsList = new SettingsList(\n\t\t\titems,\n\t\t\tMath.min(items.length, 10),\n\t\t\tgetSettingsListTheme(),\n\t\t\t(id, newValue) => {\n\t\t\t\tswitch (id) {\n\t\t\t\t\tcase \"anthropic-extra-usage\":\n\t\t\t\t\t\tthis.state = { ...this.state, anthropicExtraUsage: newValue === \"true\" };\n\t\t\t\t\t\tonChange({ ...this.state });\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t},\n\t\t\tonCancel,\n\t\t);\n\n\t\tthis.addChild(this.settingsList);\n\t}\n\n\thandleInput(data: string): void {\n\t\tthis.settingsList.handleInput(data);\n\t}\n}\n\nclass SelectSubmenu extends Container {\n\tprivate selectList: SelectList;\n\n\tconstructor(\n\t\ttitle: string,\n\t\tdescription: string,\n\t\toptions: SelectItem[],\n\t\tcurrentValue: string,\n\t\tonSelect: (value: string) => void,\n\t\tonCancel: () => void,\n\t\tonSelectionChange?: (value: string) => void,\n\t) {\n\t\tsuper();\n\n\t\t// Title\n\t\tthis.addChild(new Text(theme.bold(theme.fg(\"accent\", title)), 0, 0));\n\n\t\t// Description\n\t\tif (description) {\n\t\t\tthis.addChild(new Spacer(1));\n\t\t\tthis.addChild(new Text(theme.fg(\"muted\", description), 0, 0));\n\t\t}\n\n\t\t// Spacer\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Select list\n\t\tthis.selectList = new SelectList(\n\t\t\toptions,\n\t\t\tMath.min(options.length, 10),\n\t\t\tgetSelectListTheme(),\n\t\t\tSETTINGS_SUBMENU_SELECT_LIST_LAYOUT,\n\t\t);\n\n\t\t// Pre-select current value\n\t\tconst currentIndex = options.findIndex((o) => o.value === currentValue);\n\t\tif (currentIndex !== -1) {\n\t\t\tthis.selectList.setSelectedIndex(currentIndex);\n\t\t}\n\n\t\tthis.selectList.onSelect = (item) => {\n\t\t\tonSelect(item.value);\n\t\t};\n\n\t\tthis.selectList.onCancel = onCancel;\n\n\t\tif (onSelectionChange) {\n\t\t\tthis.selectList.onSelectionChange = (item) => {\n\t\t\t\tonSelectionChange(item.value);\n\t\t\t};\n\t\t}\n\n\t\tthis.addChild(this.selectList);\n\n\t\t// Hint\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.fg(\"dim\", \" Enter to select · Esc to go back\"), 0, 0));\n\t}\n\n\thandleInput(data: string): void {\n\t\tthis.selectList.handleInput(data);\n\t}\n}\n\nfunction themeItems(availableThemes: string[]): SelectItem[] {\n\treturn availableThemes.map((name) => ({ value: name, label: name }));\n}\n\nconst AUTOMATIC_THEME_VALUE = \"/\";\n\nfunction singleModeThemeItems(availableThemes: string[]): SelectItem[] {\n\treturn [\n\t\t{\n\t\t\tvalue: AUTOMATIC_THEME_VALUE,\n\t\t\tlabel: \"Automatic\",\n\t\t\tdescription: \"Use separate themes for light and dark terminal appearance\",\n\t\t},\n\t\t...themeItems(availableThemes),\n\t];\n}\n\nfunction preferredTheme(availableThemes: string[], preferred: string | undefined, fallback: string): string {\n\tif (preferred && availableThemes.includes(preferred)) return preferred;\n\tif (availableThemes.includes(fallback)) return fallback;\n\treturn availableThemes[0] ?? fallback;\n}\n\nfunction defaultAutomaticThemes(\n\tcurrentThemeSetting: string,\n\tavailableThemes: string[],\n): { lightTheme: string; darkTheme: string } {\n\tconst autoTheme = parseAutoThemeSetting(currentThemeSetting);\n\tif (autoTheme) return autoTheme;\n\n\tconst currentFixedTheme = currentThemeSetting.includes(\"/\") ? undefined : currentThemeSetting;\n\tconst themeName = preferredTheme(availableThemes, currentFixedTheme, \"dark\");\n\treturn { lightTheme: themeName, darkTheme: themeName };\n}\n\nclass ThemeSubmenu extends Container {\n\tprivate inputComponent: Component | undefined;\n\tprivate readonly callbacks: SettingsCallbacks;\n\tprivate readonly availableThemes: string[];\n\tprivate readonly terminalTheme: TerminalTheme;\n\tprivate readonly onDone: (selectedValue?: string) => void;\n\tprivate readonly originalThemeSetting: string;\n\tprivate mode: \"single\" | \"automatic\";\n\tprivate singleTheme: string;\n\tprivate lightTheme: string;\n\tprivate darkTheme: string;\n\n\tconstructor(\n\t\tcurrentThemeSetting: string,\n\t\tterminalTheme: TerminalTheme,\n\t\tavailableThemes: string[],\n\t\tcallbacks: SettingsCallbacks,\n\t\tonDone: (selectedValue?: string) => void,\n\t) {\n\t\tsuper();\n\t\tthis.callbacks = callbacks;\n\t\tthis.availableThemes = availableThemes;\n\t\tthis.terminalTheme = terminalTheme;\n\t\tthis.onDone = onDone;\n\t\tthis.originalThemeSetting = currentThemeSetting;\n\t\tconst autoTheme = parseAutoThemeSetting(currentThemeSetting);\n\t\tconst automaticThemes = defaultAutomaticThemes(currentThemeSetting, availableThemes);\n\t\tconst fixedTheme = autoTheme || currentThemeSetting.includes(\"/\") ? undefined : currentThemeSetting;\n\t\tthis.mode = autoTheme ? \"automatic\" : \"single\";\n\t\tthis.lightTheme = automaticThemes.lightTheme;\n\t\tthis.darkTheme = automaticThemes.darkTheme;\n\t\tthis.singleTheme = preferredTheme(\n\t\t\tavailableThemes,\n\t\t\tfixedTheme ?? (autoTheme ? this.getActiveAutomaticTheme() : undefined),\n\t\t\t\"dark\",\n\t\t);\n\n\t\tif (this.mode === \"automatic\") {\n\t\t\tthis.showAutomaticMenu();\n\t\t} else {\n\t\t\tthis.showSingleMenu();\n\t\t}\n\t}\n\n\thandleInput(data: string): void {\n\t\tthis.inputComponent?.handleInput?.(data);\n\t}\n\n\tprivate setContent(renderComponent: Component, inputComponent: Component = renderComponent): void {\n\t\tthis.clear();\n\t\tthis.addChild(renderComponent);\n\t\tthis.inputComponent = inputComponent;\n\t}\n\n\tprivate showSingleMenu(): void {\n\t\tthis.mode = \"single\";\n\t\tconst menu = new SelectSubmenu(\n\t\t\t\"Theme\",\n\t\t\t\"Select a theme, or choose Automatic to follow terminal appearance.\",\n\t\t\tsingleModeThemeItems(this.availableThemes),\n\t\t\tthis.singleTheme,\n\t\t\t(value) => {\n\t\t\t\tif (value === AUTOMATIC_THEME_VALUE) {\n\t\t\t\t\tthis.mode = \"automatic\";\n\t\t\t\t\tthis.callbacks.onThemePreview?.(this.getThemeSetting());\n\t\t\t\t\tthis.showAutomaticMenu();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tthis.singleTheme = value;\n\t\t\t\tthis.apply(value);\n\t\t\t},\n\t\t\t() => this.cancel(),\n\t\t\t(value) => {\n\t\t\t\tthis.callbacks.onThemePreview?.(value === AUTOMATIC_THEME_VALUE ? this.getAutomaticThemeSetting() : value);\n\t\t\t},\n\t\t);\n\t\tthis.setContent(menu);\n\t}\n\n\tprivate showAutomaticMenu(): void {\n\t\tthis.mode = \"automatic\";\n\t\tconst content = new Container();\n\t\tcontent.addChild(new Text(theme.bold(theme.fg(\"accent\", \"Automatic Theme\")), 0, 0));\n\t\tcontent.addChild(new Spacer(1));\n\t\tcontent.addChild(new Text(theme.fg(\"muted\", \"Choose themes for terminal light and dark appearance.\"), 0, 0));\n\t\tcontent.addChild(new Text(theme.fg(\"muted\", \"Light/dark detection requires terminal support.\"), 0, 0));\n\t\tcontent.addChild(new Spacer(1));\n\n\t\tconst items: SettingItem[] = [\n\t\t\t{\n\t\t\t\tid: \"light-theme\",\n\t\t\t\tlabel: \"Light theme\",\n\t\t\t\tdescription: \"Theme to use in automatic mode when the terminal is light\",\n\t\t\t\tcurrentValue: this.lightTheme,\n\t\t\t\tsubmenu: (currentValue, done) =>\n\t\t\t\t\tthis.createThemeSelect(\n\t\t\t\t\t\t\"Light Theme\",\n\t\t\t\t\t\t\"Select the theme to use for light terminal appearance\",\n\t\t\t\t\t\tcurrentValue,\n\t\t\t\t\t\tdone,\n\t\t\t\t\t\t(value) => {\n\t\t\t\t\t\t\tthis.lightTheme = value;\n\t\t\t\t\t\t\tthis.callbacks.onThemePreview?.(this.getThemeSetting());\n\t\t\t\t\t\t\tdone(value);\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"dark-theme\",\n\t\t\t\tlabel: \"Dark theme\",\n\t\t\t\tdescription: \"Theme to use in automatic mode when the terminal is dark\",\n\t\t\t\tcurrentValue: this.darkTheme,\n\t\t\t\tsubmenu: (currentValue, done) =>\n\t\t\t\t\tthis.createThemeSelect(\n\t\t\t\t\t\t\"Dark Theme\",\n\t\t\t\t\t\t\"Select the theme to use for dark terminal appearance\",\n\t\t\t\t\t\tcurrentValue,\n\t\t\t\t\t\tdone,\n\t\t\t\t\t\t(value) => {\n\t\t\t\t\t\t\tthis.darkTheme = value;\n\t\t\t\t\t\t\tthis.callbacks.onThemePreview?.(this.getThemeSetting());\n\t\t\t\t\t\t\tdone(value);\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"apply\",\n\t\t\t\tlabel: \"Apply\",\n\t\t\t\tdescription: \"Save and go back\",\n\t\t\t\tcurrentValue: \"save and go back\",\n\t\t\t\tvalues: [\"save and go back\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"single-mode\",\n\t\t\t\tlabel: \"Change mode\",\n\t\t\t\tdescription: \"Switch to one theme for light and dark\",\n\t\t\t\tcurrentValue: \"switch to single theme\",\n\t\t\t\tvalues: [\"switch to single theme\"],\n\t\t\t},\n\t\t];\n\n\t\tconst settingsList = new SettingsList(\n\t\t\titems,\n\t\t\tMath.min(items.length, 10),\n\t\t\tgetSettingsListTheme(),\n\t\t\t(id) => {\n\t\t\t\tswitch (id) {\n\t\t\t\t\tcase \"single-mode\":\n\t\t\t\t\t\tthis.mode = \"single\";\n\t\t\t\t\t\tthis.singleTheme = this.getActiveAutomaticTheme();\n\t\t\t\t\t\tthis.callbacks.onThemePreview?.(this.singleTheme);\n\t\t\t\t\t\tthis.showSingleMenu();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"apply\":\n\t\t\t\t\t\tthis.apply(this.getAutomaticThemeSetting());\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => this.cancel(),\n\t\t);\n\t\tcontent.addChild(settingsList);\n\t\tthis.setContent(content, settingsList);\n\t}\n\n\tprivate createThemeSelect(\n\t\ttitle: string,\n\t\tdescription: string,\n\t\tcurrentValue: string,\n\t\tdone: (selectedValue?: string) => void,\n\t\tonSelect: (value: string) => void,\n\t): SelectSubmenu {\n\t\treturn new SelectSubmenu(\n\t\t\ttitle,\n\t\t\tdescription,\n\t\t\tthemeItems(this.availableThemes),\n\t\t\tcurrentValue,\n\t\t\tonSelect,\n\t\t\t() => {\n\t\t\t\tthis.callbacks.onThemePreview?.(this.getThemeSetting());\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t(value) => this.callbacks.onThemePreview?.(value),\n\t\t);\n\t}\n\n\tprivate getThemeSetting(): string {\n\t\treturn this.mode === \"automatic\" ? this.getAutomaticThemeSetting() : this.singleTheme;\n\t}\n\n\tprivate getActiveAutomaticTheme(): string {\n\t\treturn this.terminalTheme === \"light\" ? this.lightTheme : this.darkTheme;\n\t}\n\n\tprivate getAutomaticThemeSetting(): string {\n\t\treturn `${this.lightTheme}/${this.darkTheme}`;\n\t}\n\n\tprivate apply(themeSetting: string): void {\n\t\tthis.onDone(themeSetting);\n\t}\n\n\tprivate cancel(): void {\n\t\tthis.callbacks.onThemePreview?.(this.originalThemeSetting);\n\t\tthis.onDone();\n\t}\n}\n\n/**\n * Main settings selector component.\n */\nexport class SettingsSelectorComponent extends Container {\n\tprivate settingsList: SettingsList;\n\n\tconstructor(config: SettingsConfig, callbacks: SettingsCallbacks) {\n\t\tsuper();\n\n\t\tconst supportsImages = getCapabilities().images;\n\t\tconst followUpKey = keyDisplayText(\"app.message.followUp\");\n\t\tlet currentWarnings = { ...config.warnings };\n\n\t\tconst items: SettingItem[] = [\n\t\t\t{\n\t\t\t\tid: \"autocompact\",\n\t\t\t\tlabel: \"Auto-compact\",\n\t\t\t\tdescription: \"Automatically compact context when it gets too large\",\n\t\t\t\tcurrentValue: config.autoCompact ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"steering-mode\",\n\t\t\t\tlabel: \"Steering mode\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Enter while streaming queues steering messages. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.\",\n\t\t\t\tcurrentValue: config.steeringMode,\n\t\t\t\tvalues: [\"one-at-a-time\", \"all\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"follow-up-mode\",\n\t\t\t\tlabel: \"Follow-up mode\",\n\t\t\t\tdescription: `${followUpKey} queues follow-up messages until agent stops. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.`,\n\t\t\t\tcurrentValue: config.followUpMode,\n\t\t\t\tvalues: [\"one-at-a-time\", \"all\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"transport\",\n\t\t\t\tlabel: \"Transport\",\n\t\t\t\tdescription: \"Preferred transport for providers that support multiple transports\",\n\t\t\t\tcurrentValue: config.transport,\n\t\t\t\tvalues: [\"sse\", \"websocket\", \"websocket-cached\", \"auto\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"http-idle-timeout\",\n\t\t\t\tlabel: \"HTTP idle timeout\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Maximum idle gap while waiting for HTTP headers or body chunks. Disable for local models that pause longer than five minutes.\",\n\t\t\t\tcurrentValue: formatHttpIdleTimeoutMs(config.httpIdleTimeoutMs),\n\t\t\t\tvalues: HTTP_IDLE_TIMEOUT_CHOICES.map((choice) => choice.label),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"hide-thinking\",\n\t\t\t\tlabel: \"Hide thinking\",\n\t\t\t\tdescription: \"Hide thinking blocks in assistant responses\",\n\t\t\t\tcurrentValue: config.hideThinkingBlock ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"cache-miss-notices\",\n\t\t\t\tlabel: \"Cache miss notices\",\n\t\t\t\tdescription: \"Show transcript notices for significant prompt-cache misses\",\n\t\t\t\tcurrentValue: config.showCacheMissNotices ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"collapse-changelog\",\n\t\t\t\tlabel: \"Collapse changelog\",\n\t\t\t\tdescription: \"Show condensed changelog after updates\",\n\t\t\t\tcurrentValue: config.collapseChangelog ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"quiet-startup\",\n\t\t\t\tlabel: \"Quiet startup\",\n\t\t\t\tdescription: \"Disable verbose printing at startup\",\n\t\t\t\tcurrentValue: config.quietStartup ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"install-telemetry\",\n\t\t\t\tlabel: \"Install telemetry\",\n\t\t\t\tdescription: \"Send an anonymous version/update ping after changelog-detected updates\",\n\t\t\t\tcurrentValue: config.enableInstallTelemetry ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"default-project-trust\",\n\t\t\t\tlabel: \"Default project trust\",\n\t\t\t\tdescription: \"Fallback behavior when no extension or saved trust decision decides project trust\",\n\t\t\t\tcurrentValue: DEFAULT_PROJECT_TRUST_LABELS[config.defaultProjectTrust],\n\t\t\t\tvalues: Object.values(DEFAULT_PROJECT_TRUST_LABELS),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"double-escape-action\",\n\t\t\t\tlabel: \"Double-escape action\",\n\t\t\t\tdescription: \"Action when pressing Escape twice with empty editor\",\n\t\t\t\tcurrentValue: config.doubleEscapeAction,\n\t\t\t\tvalues: [\"tree\", \"fork\", \"none\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"tree-filter-mode\",\n\t\t\t\tlabel: \"Tree filter mode\",\n\t\t\t\tdescription: \"Default filter when opening /tree\",\n\t\t\t\tcurrentValue: config.treeFilterMode,\n\t\t\t\tvalues: [\"default\", \"no-tools\", \"user-only\", \"labeled-only\", \"all\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"warnings\",\n\t\t\t\tlabel: \"Warnings\",\n\t\t\t\tdescription: \"Enable or disable individual warnings\",\n\t\t\t\tcurrentValue: \"configure\",\n\t\t\t\tsubmenu: (_currentValue, done) =>\n\t\t\t\t\tnew WarningSettingsSubmenu(\n\t\t\t\t\t\tcurrentWarnings,\n\t\t\t\t\t\t(warnings) => {\n\t\t\t\t\t\t\tcurrentWarnings = warnings;\n\t\t\t\t\t\t\tcallbacks.onWarningsChange(warnings);\n\t\t\t\t\t\t},\n\t\t\t\t\t\t() => done(),\n\t\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"thinking\",\n\t\t\t\tlabel: \"Thinking level\",\n\t\t\t\tdescription: \"Reasoning depth for thinking-capable models\",\n\t\t\t\tcurrentValue: config.thinkingLevel,\n\t\t\t\tsubmenu: (currentValue, done) =>\n\t\t\t\t\tnew SelectSubmenu(\n\t\t\t\t\t\t\"Thinking Level\",\n\t\t\t\t\t\t\"Select reasoning depth for thinking-capable models\",\n\t\t\t\t\t\tconfig.availableThinkingLevels.map((level) => ({\n\t\t\t\t\t\t\tvalue: level,\n\t\t\t\t\t\t\tlabel: level,\n\t\t\t\t\t\t\tdescription: THINKING_DESCRIPTIONS[level],\n\t\t\t\t\t\t})),\n\t\t\t\t\t\tcurrentValue,\n\t\t\t\t\t\t(value) => {\n\t\t\t\t\t\t\tcallbacks.onThinkingLevelChange(value as ThinkingLevel);\n\t\t\t\t\t\t\tdone(value);\n\t\t\t\t\t\t},\n\t\t\t\t\t\t() => done(),\n\t\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"theme\",\n\t\t\t\tlabel: \"Theme\",\n\t\t\t\tdescription: \"Color theme for the interface\",\n\t\t\t\tcurrentValue: config.currentTheme,\n\t\t\t\tsubmenu: (currentValue, done) =>\n\t\t\t\t\tnew ThemeSubmenu(currentValue, config.terminalTheme, config.availableThemes, callbacks, done),\n\t\t\t},\n\t\t];\n\n\t\t// Only show image toggle if terminal supports it\n\t\tif (supportsImages) {\n\t\t\t// Insert after autocompact\n\t\t\titems.splice(1, 0, {\n\t\t\t\tid: \"show-images\",\n\t\t\t\tlabel: \"Show images\",\n\t\t\t\tdescription: \"Render images inline in terminal\",\n\t\t\t\tcurrentValue: config.showImages ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t});\n\t\t\titems.splice(2, 0, {\n\t\t\t\tid: \"image-width-cells\",\n\t\t\t\tlabel: \"Image width\",\n\t\t\t\tdescription: \"Preferred inline image width in terminal cells\",\n\t\t\t\tcurrentValue: String(config.imageWidthCells),\n\t\t\t\tvalues: [\"60\", \"80\", \"120\"],\n\t\t\t});\n\t\t}\n\n\t\t// Image auto-resize toggle (always available, affects both attached and read images)\n\t\titems.splice(supportsImages ? 3 : 1, 0, {\n\t\t\tid: \"auto-resize-images\",\n\t\t\tlabel: \"Auto-resize images\",\n\t\t\tdescription: \"Resize large images to 2000x2000 max for better model compatibility\",\n\t\t\tcurrentValue: config.autoResizeImages ? \"true\" : \"false\",\n\t\t\tvalues: [\"true\", \"false\"],\n\t\t});\n\n\t\t// Block images toggle (always available, insert after auto-resize-images)\n\t\tconst autoResizeIndex = items.findIndex((item) => item.id === \"auto-resize-images\");\n\t\titems.splice(autoResizeIndex + 1, 0, {\n\t\t\tid: \"block-images\",\n\t\t\tlabel: \"Block images\",\n\t\t\tdescription: \"Prevent images from being sent to LLM providers\",\n\t\t\tcurrentValue: config.blockImages ? \"true\" : \"false\",\n\t\t\tvalues: [\"true\", \"false\"],\n\t\t});\n\n\t\t// Skill commands toggle (insert after block-images)\n\t\tconst blockImagesIndex = items.findIndex((item) => item.id === \"block-images\");\n\t\titems.splice(blockImagesIndex + 1, 0, {\n\t\t\tid: \"skill-commands\",\n\t\t\tlabel: \"Skill commands\",\n\t\t\tdescription: \"Register skills as /skill:name commands\",\n\t\t\tcurrentValue: config.enableSkillCommands ? \"true\" : \"false\",\n\t\t\tvalues: [\"true\", \"false\"],\n\t\t});\n\n\t\t// Hardware cursor toggle (insert after skill-commands)\n\t\tconst skillCommandsIndex = items.findIndex((item) => item.id === \"skill-commands\");\n\t\titems.splice(skillCommandsIndex + 1, 0, {\n\t\t\tid: \"show-hardware-cursor\",\n\t\t\tlabel: \"Show hardware cursor\",\n\t\t\tdescription: \"Show the terminal cursor while still positioning it for IME support\",\n\t\t\tcurrentValue: config.showHardwareCursor ? \"true\" : \"false\",\n\t\t\tvalues: [\"true\", \"false\"],\n\t\t});\n\n\t\t// Editor padding toggle (insert after show-hardware-cursor)\n\t\tconst hardwareCursorIndex = items.findIndex((item) => item.id === \"show-hardware-cursor\");\n\t\titems.splice(hardwareCursorIndex + 1, 0, {\n\t\t\tid: \"editor-padding\",\n\t\t\tlabel: \"Editor padding\",\n\t\t\tdescription: \"Horizontal padding for input editor (0-3)\",\n\t\t\tcurrentValue: String(config.editorPaddingX),\n\t\t\tvalues: [\"0\", \"1\", \"2\", \"3\"],\n\t\t});\n\n\t\t// Output padding toggle (insert after editor-padding)\n\t\tconst editorPaddingIndex = items.findIndex((item) => item.id === \"editor-padding\");\n\t\titems.splice(editorPaddingIndex + 1, 0, {\n\t\t\tid: \"output-padding\",\n\t\t\tlabel: \"Output padding\",\n\t\t\tdescription: \"Horizontal padding for user messages, assistant messages, and thinking\",\n\t\t\tcurrentValue: String(config.outputPad),\n\t\t\tvalues: [\"0\", \"1\"],\n\t\t});\n\n\t\t// Autocomplete max visible toggle (insert after output-padding)\n\t\tconst outputPaddingIndex = items.findIndex((item) => item.id === \"output-padding\");\n\t\titems.splice(outputPaddingIndex + 1, 0, {\n\t\t\tid: \"autocomplete-max-visible\",\n\t\t\tlabel: \"Autocomplete max items\",\n\t\t\tdescription: \"Max visible items in autocomplete dropdown (3-20)\",\n\t\t\tcurrentValue: String(config.autocompleteMaxVisible),\n\t\t\tvalues: [\"3\", \"5\", \"7\", \"10\", \"15\", \"20\"],\n\t\t});\n\n\t\t// Clear on shrink toggle (insert after autocomplete-max-visible)\n\t\tconst autocompleteIndex = items.findIndex((item) => item.id === \"autocomplete-max-visible\");\n\t\titems.splice(autocompleteIndex + 1, 0, {\n\t\t\tid: \"clear-on-shrink\",\n\t\t\tlabel: \"Clear on shrink\",\n\t\t\tdescription: \"Clear empty rows when content shrinks (may cause flicker)\",\n\t\t\tcurrentValue: config.clearOnShrink ? \"true\" : \"false\",\n\t\t\tvalues: [\"true\", \"false\"],\n\t\t});\n\n\t\t// Terminal progress toggle (insert after clear-on-shrink)\n\t\tconst clearOnShrinkIndex = items.findIndex((item) => item.id === \"clear-on-shrink\");\n\t\titems.splice(clearOnShrinkIndex + 1, 0, {\n\t\t\tid: \"terminal-progress\",\n\t\t\tlabel: \"Terminal progress\",\n\t\t\tdescription: \"Show OSC 9;4 progress indicators in the terminal tab bar\",\n\t\t\tcurrentValue: config.showTerminalProgress ? \"true\" : \"false\",\n\t\t\tvalues: [\"true\", \"false\"],\n\t\t});\n\n\t\t// Add borders\n\t\tthis.addChild(new DynamicBorder());\n\n\t\tthis.settingsList = new SettingsList(\n\t\t\titems,\n\t\t\t10,\n\t\t\tgetSettingsListTheme(),\n\t\t\t(id, newValue) => {\n\t\t\t\tswitch (id) {\n\t\t\t\t\tcase \"autocompact\":\n\t\t\t\t\t\tcallbacks.onAutoCompactChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"show-images\":\n\t\t\t\t\t\tcallbacks.onShowImagesChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"image-width-cells\":\n\t\t\t\t\t\tcallbacks.onImageWidthCellsChange(parseInt(newValue, 10));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"auto-resize-images\":\n\t\t\t\t\t\tcallbacks.onAutoResizeImagesChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"block-images\":\n\t\t\t\t\t\tcallbacks.onBlockImagesChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"skill-commands\":\n\t\t\t\t\t\tcallbacks.onEnableSkillCommandsChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"steering-mode\":\n\t\t\t\t\t\tcallbacks.onSteeringModeChange(newValue as \"all\" | \"one-at-a-time\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"follow-up-mode\":\n\t\t\t\t\t\tcallbacks.onFollowUpModeChange(newValue as \"all\" | \"one-at-a-time\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"transport\":\n\t\t\t\t\t\tcallbacks.onTransportChange(newValue as Transport);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"http-idle-timeout\": {\n\t\t\t\t\t\tconst choice = HTTP_IDLE_TIMEOUT_CHOICES.find((item) => item.label === newValue);\n\t\t\t\t\t\tif (choice) {\n\t\t\t\t\t\t\tcallbacks.onHttpIdleTimeoutMsChange(choice.timeoutMs);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"hide-thinking\":\n\t\t\t\t\t\tcallbacks.onHideThinkingBlockChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"cache-miss-notices\":\n\t\t\t\t\t\tcallbacks.onShowCacheMissNoticesChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"collapse-changelog\":\n\t\t\t\t\t\tcallbacks.onCollapseChangelogChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"quiet-startup\":\n\t\t\t\t\t\tcallbacks.onQuietStartupChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"install-telemetry\":\n\t\t\t\t\t\tcallbacks.onEnableInstallTelemetryChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"default-project-trust\": {\n\t\t\t\t\t\tconst defaultProjectTrust = DEFAULT_PROJECT_TRUST_BY_LABEL.get(newValue);\n\t\t\t\t\t\tif (defaultProjectTrust) {\n\t\t\t\t\t\t\tcallbacks.onDefaultProjectTrustChange(defaultProjectTrust);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"double-escape-action\":\n\t\t\t\t\t\tcallbacks.onDoubleEscapeActionChange(newValue as \"fork\" | \"tree\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tree-filter-mode\":\n\t\t\t\t\t\tcallbacks.onTreeFilterModeChange(\n\t\t\t\t\t\t\tnewValue as \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"show-hardware-cursor\":\n\t\t\t\t\t\tcallbacks.onShowHardwareCursorChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"editor-padding\":\n\t\t\t\t\t\tcallbacks.onEditorPaddingXChange(parseInt(newValue, 10));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"output-padding\":\n\t\t\t\t\t\tcallbacks.onOutputPadChange(newValue === \"0\" ? 0 : 1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"autocomplete-max-visible\":\n\t\t\t\t\t\tcallbacks.onAutocompleteMaxVisibleChange(parseInt(newValue, 10));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"clear-on-shrink\":\n\t\t\t\t\t\tcallbacks.onClearOnShrinkChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"terminal-progress\":\n\t\t\t\t\t\tcallbacks.onShowTerminalProgressChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"theme\":\n\t\t\t\t\t\tcallbacks.onThemeChange(newValue);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t},\n\t\t\tcallbacks.onCancel,\n\t\t\t{ enableSearch: true },\n\t\t);\n\n\t\tthis.addChild(this.settingsList);\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tgetSettingsList(): SettingsList {\n\t\treturn this.settingsList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/settings-selector.js b/dist/modes/interactive/components/settings-selector.js new file mode 100644 index 0000000..2f93e9d --- /dev/null +++ b/dist/modes/interactive/components/settings-selector.js @@ -0,0 +1,593 @@ +import { Container, getCapabilities, SelectList, SettingsList, Spacer, Text, } from "@earendil-works/pi-tui"; +import { formatHttpIdleTimeoutMs, HTTP_IDLE_TIMEOUT_CHOICES } from "../../../core/http-dispatcher.js"; +import { getSelectListTheme, getSettingsListTheme, parseAutoThemeSetting, theme, } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyDisplayText } from "./keybinding-hints.js"; +const SETTINGS_SUBMENU_SELECT_LIST_LAYOUT = { + minPrimaryColumnWidth: 12, + maxPrimaryColumnWidth: 32, +}; +const THINKING_DESCRIPTIONS = { + off: "No reasoning", + minimal: "Very brief reasoning (~1k tokens)", + low: "Light reasoning (~2k tokens)", + medium: "Moderate reasoning (~8k tokens)", + high: "Deep reasoning (~16k tokens)", + xhigh: "Extra-high reasoning (~32k tokens)", + max: "Maximum reasoning", +}; +const DEFAULT_PROJECT_TRUST_LABELS = { + ask: "Ask", + always: "Always trust", + never: "Never trust", +}; +const DEFAULT_PROJECT_TRUST_BY_LABEL = new Map(Object.entries(DEFAULT_PROJECT_TRUST_LABELS).map(([value, label]) => [label, value])); +/** + * A submenu component for selecting from a list of options. + */ +class WarningSettingsSubmenu extends Container { + settingsList; + state; + constructor(warnings, onChange, onCancel) { + super(); + this.state = { ...warnings }; + const items = [ + { + id: "anthropic-extra-usage", + label: "Anthropic extra usage", + description: "Warn when Anthropic subscription auth may use paid extra usage", + currentValue: (this.state.anthropicExtraUsage ?? true) ? "true" : "false", + values: ["true", "false"], + }, + ]; + this.settingsList = new SettingsList(items, Math.min(items.length, 10), getSettingsListTheme(), (id, newValue) => { + switch (id) { + case "anthropic-extra-usage": + this.state = { ...this.state, anthropicExtraUsage: newValue === "true" }; + onChange({ ...this.state }); + break; + } + }, onCancel); + this.addChild(this.settingsList); + } + handleInput(data) { + this.settingsList.handleInput(data); + } +} +class SelectSubmenu extends Container { + selectList; + constructor(title, description, options, currentValue, onSelect, onCancel, onSelectionChange) { + super(); + // Title + this.addChild(new Text(theme.bold(theme.fg("accent", title)), 0, 0)); + // Description + if (description) { + this.addChild(new Spacer(1)); + this.addChild(new Text(theme.fg("muted", description), 0, 0)); + } + // Spacer + this.addChild(new Spacer(1)); + // Select list + this.selectList = new SelectList(options, Math.min(options.length, 10), getSelectListTheme(), SETTINGS_SUBMENU_SELECT_LIST_LAYOUT); + // Pre-select current value + const currentIndex = options.findIndex((o) => o.value === currentValue); + if (currentIndex !== -1) { + this.selectList.setSelectedIndex(currentIndex); + } + this.selectList.onSelect = (item) => { + onSelect(item.value); + }; + this.selectList.onCancel = onCancel; + if (onSelectionChange) { + this.selectList.onSelectionChange = (item) => { + onSelectionChange(item.value); + }; + } + this.addChild(this.selectList); + // Hint + this.addChild(new Spacer(1)); + this.addChild(new Text(theme.fg("dim", " Enter to select · Esc to go back"), 0, 0)); + } + handleInput(data) { + this.selectList.handleInput(data); + } +} +function themeItems(availableThemes) { + return availableThemes.map((name) => ({ value: name, label: name })); +} +const AUTOMATIC_THEME_VALUE = "/"; +function singleModeThemeItems(availableThemes) { + return [ + { + value: AUTOMATIC_THEME_VALUE, + label: "Automatic", + description: "Use separate themes for light and dark terminal appearance", + }, + ...themeItems(availableThemes), + ]; +} +function preferredTheme(availableThemes, preferred, fallback) { + if (preferred && availableThemes.includes(preferred)) + return preferred; + if (availableThemes.includes(fallback)) + return fallback; + return availableThemes[0] ?? fallback; +} +function defaultAutomaticThemes(currentThemeSetting, availableThemes) { + const autoTheme = parseAutoThemeSetting(currentThemeSetting); + if (autoTheme) + return autoTheme; + const currentFixedTheme = currentThemeSetting.includes("/") ? undefined : currentThemeSetting; + const themeName = preferredTheme(availableThemes, currentFixedTheme, "dark"); + return { lightTheme: themeName, darkTheme: themeName }; +} +class ThemeSubmenu extends Container { + inputComponent; + callbacks; + availableThemes; + terminalTheme; + onDone; + originalThemeSetting; + mode; + singleTheme; + lightTheme; + darkTheme; + constructor(currentThemeSetting, terminalTheme, availableThemes, callbacks, onDone) { + super(); + this.callbacks = callbacks; + this.availableThemes = availableThemes; + this.terminalTheme = terminalTheme; + this.onDone = onDone; + this.originalThemeSetting = currentThemeSetting; + const autoTheme = parseAutoThemeSetting(currentThemeSetting); + const automaticThemes = defaultAutomaticThemes(currentThemeSetting, availableThemes); + const fixedTheme = autoTheme || currentThemeSetting.includes("/") ? undefined : currentThemeSetting; + this.mode = autoTheme ? "automatic" : "single"; + this.lightTheme = automaticThemes.lightTheme; + this.darkTheme = automaticThemes.darkTheme; + this.singleTheme = preferredTheme(availableThemes, fixedTheme ?? (autoTheme ? this.getActiveAutomaticTheme() : undefined), "dark"); + if (this.mode === "automatic") { + this.showAutomaticMenu(); + } + else { + this.showSingleMenu(); + } + } + handleInput(data) { + this.inputComponent?.handleInput?.(data); + } + setContent(renderComponent, inputComponent = renderComponent) { + this.clear(); + this.addChild(renderComponent); + this.inputComponent = inputComponent; + } + showSingleMenu() { + this.mode = "single"; + const menu = new SelectSubmenu("Theme", "Select a theme, or choose Automatic to follow terminal appearance.", singleModeThemeItems(this.availableThemes), this.singleTheme, (value) => { + if (value === AUTOMATIC_THEME_VALUE) { + this.mode = "automatic"; + this.callbacks.onThemePreview?.(this.getThemeSetting()); + this.showAutomaticMenu(); + return; + } + this.singleTheme = value; + this.apply(value); + }, () => this.cancel(), (value) => { + this.callbacks.onThemePreview?.(value === AUTOMATIC_THEME_VALUE ? this.getAutomaticThemeSetting() : value); + }); + this.setContent(menu); + } + showAutomaticMenu() { + this.mode = "automatic"; + const content = new Container(); + content.addChild(new Text(theme.bold(theme.fg("accent", "Automatic Theme")), 0, 0)); + content.addChild(new Spacer(1)); + content.addChild(new Text(theme.fg("muted", "Choose themes for terminal light and dark appearance."), 0, 0)); + content.addChild(new Text(theme.fg("muted", "Light/dark detection requires terminal support."), 0, 0)); + content.addChild(new Spacer(1)); + const items = [ + { + id: "light-theme", + label: "Light theme", + description: "Theme to use in automatic mode when the terminal is light", + currentValue: this.lightTheme, + submenu: (currentValue, done) => this.createThemeSelect("Light Theme", "Select the theme to use for light terminal appearance", currentValue, done, (value) => { + this.lightTheme = value; + this.callbacks.onThemePreview?.(this.getThemeSetting()); + done(value); + }), + }, + { + id: "dark-theme", + label: "Dark theme", + description: "Theme to use in automatic mode when the terminal is dark", + currentValue: this.darkTheme, + submenu: (currentValue, done) => this.createThemeSelect("Dark Theme", "Select the theme to use for dark terminal appearance", currentValue, done, (value) => { + this.darkTheme = value; + this.callbacks.onThemePreview?.(this.getThemeSetting()); + done(value); + }), + }, + { + id: "apply", + label: "Apply", + description: "Save and go back", + currentValue: "save and go back", + values: ["save and go back"], + }, + { + id: "single-mode", + label: "Change mode", + description: "Switch to one theme for light and dark", + currentValue: "switch to single theme", + values: ["switch to single theme"], + }, + ]; + const settingsList = new SettingsList(items, Math.min(items.length, 10), getSettingsListTheme(), (id) => { + switch (id) { + case "single-mode": + this.mode = "single"; + this.singleTheme = this.getActiveAutomaticTheme(); + this.callbacks.onThemePreview?.(this.singleTheme); + this.showSingleMenu(); + break; + case "apply": + this.apply(this.getAutomaticThemeSetting()); + break; + } + }, () => this.cancel()); + content.addChild(settingsList); + this.setContent(content, settingsList); + } + createThemeSelect(title, description, currentValue, done, onSelect) { + return new SelectSubmenu(title, description, themeItems(this.availableThemes), currentValue, onSelect, () => { + this.callbacks.onThemePreview?.(this.getThemeSetting()); + done(); + }, (value) => this.callbacks.onThemePreview?.(value)); + } + getThemeSetting() { + return this.mode === "automatic" ? this.getAutomaticThemeSetting() : this.singleTheme; + } + getActiveAutomaticTheme() { + return this.terminalTheme === "light" ? this.lightTheme : this.darkTheme; + } + getAutomaticThemeSetting() { + return `${this.lightTheme}/${this.darkTheme}`; + } + apply(themeSetting) { + this.onDone(themeSetting); + } + cancel() { + this.callbacks.onThemePreview?.(this.originalThemeSetting); + this.onDone(); + } +} +/** + * Main settings selector component. + */ +export class SettingsSelectorComponent extends Container { + settingsList; + constructor(config, callbacks) { + super(); + const supportsImages = getCapabilities().images; + const followUpKey = keyDisplayText("app.message.followUp"); + let currentWarnings = { ...config.warnings }; + const items = [ + { + id: "autocompact", + label: "Auto-compact", + description: "Automatically compact context when it gets too large", + currentValue: config.autoCompact ? "true" : "false", + values: ["true", "false"], + }, + { + id: "steering-mode", + label: "Steering mode", + description: "Enter while streaming queues steering messages. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.", + currentValue: config.steeringMode, + values: ["one-at-a-time", "all"], + }, + { + id: "follow-up-mode", + label: "Follow-up mode", + description: `${followUpKey} queues follow-up messages until agent stops. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.`, + currentValue: config.followUpMode, + values: ["one-at-a-time", "all"], + }, + { + id: "transport", + label: "Transport", + description: "Preferred transport for providers that support multiple transports", + currentValue: config.transport, + values: ["sse", "websocket", "websocket-cached", "auto"], + }, + { + id: "http-idle-timeout", + label: "HTTP idle timeout", + description: "Maximum idle gap while waiting for HTTP headers or body chunks. Disable for local models that pause longer than five minutes.", + currentValue: formatHttpIdleTimeoutMs(config.httpIdleTimeoutMs), + values: HTTP_IDLE_TIMEOUT_CHOICES.map((choice) => choice.label), + }, + { + id: "hide-thinking", + label: "Hide thinking", + description: "Hide thinking blocks in assistant responses", + currentValue: config.hideThinkingBlock ? "true" : "false", + values: ["true", "false"], + }, + { + id: "cache-miss-notices", + label: "Cache miss notices", + description: "Show transcript notices for significant prompt-cache misses", + currentValue: config.showCacheMissNotices ? "true" : "false", + values: ["true", "false"], + }, + { + id: "collapse-changelog", + label: "Collapse changelog", + description: "Show condensed changelog after updates", + currentValue: config.collapseChangelog ? "true" : "false", + values: ["true", "false"], + }, + { + id: "quiet-startup", + label: "Quiet startup", + description: "Disable verbose printing at startup", + currentValue: config.quietStartup ? "true" : "false", + values: ["true", "false"], + }, + { + id: "install-telemetry", + label: "Install telemetry", + description: "Send an anonymous version/update ping after changelog-detected updates", + currentValue: config.enableInstallTelemetry ? "true" : "false", + values: ["true", "false"], + }, + { + id: "default-project-trust", + label: "Default project trust", + description: "Fallback behavior when no extension or saved trust decision decides project trust", + currentValue: DEFAULT_PROJECT_TRUST_LABELS[config.defaultProjectTrust], + values: Object.values(DEFAULT_PROJECT_TRUST_LABELS), + }, + { + id: "double-escape-action", + label: "Double-escape action", + description: "Action when pressing Escape twice with empty editor", + currentValue: config.doubleEscapeAction, + values: ["tree", "fork", "none"], + }, + { + id: "tree-filter-mode", + label: "Tree filter mode", + description: "Default filter when opening /tree", + currentValue: config.treeFilterMode, + values: ["default", "no-tools", "user-only", "labeled-only", "all"], + }, + { + id: "warnings", + label: "Warnings", + description: "Enable or disable individual warnings", + currentValue: "configure", + submenu: (_currentValue, done) => new WarningSettingsSubmenu(currentWarnings, (warnings) => { + currentWarnings = warnings; + callbacks.onWarningsChange(warnings); + }, () => done()), + }, + { + id: "thinking", + label: "Thinking level", + description: "Reasoning depth for thinking-capable models", + currentValue: config.thinkingLevel, + submenu: (currentValue, done) => new SelectSubmenu("Thinking Level", "Select reasoning depth for thinking-capable models", config.availableThinkingLevels.map((level) => ({ + value: level, + label: level, + description: THINKING_DESCRIPTIONS[level], + })), currentValue, (value) => { + callbacks.onThinkingLevelChange(value); + done(value); + }, () => done()), + }, + { + id: "theme", + label: "Theme", + description: "Color theme for the interface", + currentValue: config.currentTheme, + submenu: (currentValue, done) => new ThemeSubmenu(currentValue, config.terminalTheme, config.availableThemes, callbacks, done), + }, + ]; + // Only show image toggle if terminal supports it + if (supportsImages) { + // Insert after autocompact + items.splice(1, 0, { + id: "show-images", + label: "Show images", + description: "Render images inline in terminal", + currentValue: config.showImages ? "true" : "false", + values: ["true", "false"], + }); + items.splice(2, 0, { + id: "image-width-cells", + label: "Image width", + description: "Preferred inline image width in terminal cells", + currentValue: String(config.imageWidthCells), + values: ["60", "80", "120"], + }); + } + // Image auto-resize toggle (always available, affects both attached and read images) + items.splice(supportsImages ? 3 : 1, 0, { + id: "auto-resize-images", + label: "Auto-resize images", + description: "Resize large images to 2000x2000 max for better model compatibility", + currentValue: config.autoResizeImages ? "true" : "false", + values: ["true", "false"], + }); + // Block images toggle (always available, insert after auto-resize-images) + const autoResizeIndex = items.findIndex((item) => item.id === "auto-resize-images"); + items.splice(autoResizeIndex + 1, 0, { + id: "block-images", + label: "Block images", + description: "Prevent images from being sent to LLM providers", + currentValue: config.blockImages ? "true" : "false", + values: ["true", "false"], + }); + // Skill commands toggle (insert after block-images) + const blockImagesIndex = items.findIndex((item) => item.id === "block-images"); + items.splice(blockImagesIndex + 1, 0, { + id: "skill-commands", + label: "Skill commands", + description: "Register skills as /skill:name commands", + currentValue: config.enableSkillCommands ? "true" : "false", + values: ["true", "false"], + }); + // Hardware cursor toggle (insert after skill-commands) + const skillCommandsIndex = items.findIndex((item) => item.id === "skill-commands"); + items.splice(skillCommandsIndex + 1, 0, { + id: "show-hardware-cursor", + label: "Show hardware cursor", + description: "Show the terminal cursor while still positioning it for IME support", + currentValue: config.showHardwareCursor ? "true" : "false", + values: ["true", "false"], + }); + // Editor padding toggle (insert after show-hardware-cursor) + const hardwareCursorIndex = items.findIndex((item) => item.id === "show-hardware-cursor"); + items.splice(hardwareCursorIndex + 1, 0, { + id: "editor-padding", + label: "Editor padding", + description: "Horizontal padding for input editor (0-3)", + currentValue: String(config.editorPaddingX), + values: ["0", "1", "2", "3"], + }); + // Output padding toggle (insert after editor-padding) + const editorPaddingIndex = items.findIndex((item) => item.id === "editor-padding"); + items.splice(editorPaddingIndex + 1, 0, { + id: "output-padding", + label: "Output padding", + description: "Horizontal padding for user messages, assistant messages, and thinking", + currentValue: String(config.outputPad), + values: ["0", "1"], + }); + // Autocomplete max visible toggle (insert after output-padding) + const outputPaddingIndex = items.findIndex((item) => item.id === "output-padding"); + items.splice(outputPaddingIndex + 1, 0, { + id: "autocomplete-max-visible", + label: "Autocomplete max items", + description: "Max visible items in autocomplete dropdown (3-20)", + currentValue: String(config.autocompleteMaxVisible), + values: ["3", "5", "7", "10", "15", "20"], + }); + // Clear on shrink toggle (insert after autocomplete-max-visible) + const autocompleteIndex = items.findIndex((item) => item.id === "autocomplete-max-visible"); + items.splice(autocompleteIndex + 1, 0, { + id: "clear-on-shrink", + label: "Clear on shrink", + description: "Clear empty rows when content shrinks (may cause flicker)", + currentValue: config.clearOnShrink ? "true" : "false", + values: ["true", "false"], + }); + // Terminal progress toggle (insert after clear-on-shrink) + const clearOnShrinkIndex = items.findIndex((item) => item.id === "clear-on-shrink"); + items.splice(clearOnShrinkIndex + 1, 0, { + id: "terminal-progress", + label: "Terminal progress", + description: "Show OSC 9;4 progress indicators in the terminal tab bar", + currentValue: config.showTerminalProgress ? "true" : "false", + values: ["true", "false"], + }); + // Add borders + this.addChild(new DynamicBorder()); + this.settingsList = new SettingsList(items, 10, getSettingsListTheme(), (id, newValue) => { + switch (id) { + case "autocompact": + callbacks.onAutoCompactChange(newValue === "true"); + break; + case "show-images": + callbacks.onShowImagesChange(newValue === "true"); + break; + case "image-width-cells": + callbacks.onImageWidthCellsChange(parseInt(newValue, 10)); + break; + case "auto-resize-images": + callbacks.onAutoResizeImagesChange(newValue === "true"); + break; + case "block-images": + callbacks.onBlockImagesChange(newValue === "true"); + break; + case "skill-commands": + callbacks.onEnableSkillCommandsChange(newValue === "true"); + break; + case "steering-mode": + callbacks.onSteeringModeChange(newValue); + break; + case "follow-up-mode": + callbacks.onFollowUpModeChange(newValue); + break; + case "transport": + callbacks.onTransportChange(newValue); + break; + case "http-idle-timeout": { + const choice = HTTP_IDLE_TIMEOUT_CHOICES.find((item) => item.label === newValue); + if (choice) { + callbacks.onHttpIdleTimeoutMsChange(choice.timeoutMs); + } + break; + } + case "hide-thinking": + callbacks.onHideThinkingBlockChange(newValue === "true"); + break; + case "cache-miss-notices": + callbacks.onShowCacheMissNoticesChange(newValue === "true"); + break; + case "collapse-changelog": + callbacks.onCollapseChangelogChange(newValue === "true"); + break; + case "quiet-startup": + callbacks.onQuietStartupChange(newValue === "true"); + break; + case "install-telemetry": + callbacks.onEnableInstallTelemetryChange(newValue === "true"); + break; + case "default-project-trust": { + const defaultProjectTrust = DEFAULT_PROJECT_TRUST_BY_LABEL.get(newValue); + if (defaultProjectTrust) { + callbacks.onDefaultProjectTrustChange(defaultProjectTrust); + } + break; + } + case "double-escape-action": + callbacks.onDoubleEscapeActionChange(newValue); + break; + case "tree-filter-mode": + callbacks.onTreeFilterModeChange(newValue); + break; + case "show-hardware-cursor": + callbacks.onShowHardwareCursorChange(newValue === "true"); + break; + case "editor-padding": + callbacks.onEditorPaddingXChange(parseInt(newValue, 10)); + break; + case "output-padding": + callbacks.onOutputPadChange(newValue === "0" ? 0 : 1); + break; + case "autocomplete-max-visible": + callbacks.onAutocompleteMaxVisibleChange(parseInt(newValue, 10)); + break; + case "clear-on-shrink": + callbacks.onClearOnShrinkChange(newValue === "true"); + break; + case "terminal-progress": + callbacks.onShowTerminalProgressChange(newValue === "true"); + break; + case "theme": + callbacks.onThemeChange(newValue); + break; + } + }, callbacks.onCancel, { enableSearch: true }); + this.addChild(this.settingsList); + this.addChild(new DynamicBorder()); + } + getSettingsList() { + return this.settingsList; + } +} +//# sourceMappingURL=settings-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/settings-selector.js.map b/dist/modes/interactive/components/settings-selector.js.map new file mode 100644 index 0000000..51fb3b4 --- /dev/null +++ b/dist/modes/interactive/components/settings-selector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"settings-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/settings-selector.ts"],"names":[],"mappings":"AAEA,OAAO,EAEN,SAAS,EACT,eAAe,EAEf,UAAU,EAGV,YAAY,EACZ,MAAM,EACN,IAAI,GACJ,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,uBAAuB,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAEtG,OAAO,EACN,kBAAkB,EAClB,oBAAoB,EACpB,qBAAqB,EAErB,KAAK,GACL,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,u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CAAC;QAAA,CACD,EACD,SAAS,CAAC,QAAQ,EAClB,EAAE,YAAY,EAAE,IAAI,EAAE,CACtB,CAAC;QAEF,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QACjC,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;IAAA,CACnC;IAED,eAAe,GAAiB;QAC/B,OAAO,IAAI,CAAC,YAAY,CAAC;IAAA,CACzB;CACD","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Transport } from \"@earendil-works/pi-ai\";\nimport {\n\ttype Component,\n\tContainer,\n\tgetCapabilities,\n\ttype SelectItem,\n\tSelectList,\n\ttype SelectListLayoutOptions,\n\ttype SettingItem,\n\tSettingsList,\n\tSpacer,\n\tText,\n} from \"@earendil-works/pi-tui\";\nimport { formatHttpIdleTimeoutMs, HTTP_IDLE_TIMEOUT_CHOICES } from \"../../../core/http-dispatcher.ts\";\nimport type { DefaultProjectTrust, WarningSettings } from \"../../../core/settings-manager.ts\";\nimport {\n\tgetSelectListTheme,\n\tgetSettingsListTheme,\n\tparseAutoThemeSetting,\n\ttype TerminalTheme,\n\ttheme,\n} from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyDisplayText } from \"./keybinding-hints.ts\";\n\nconst SETTINGS_SUBMENU_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {\n\tminPrimaryColumnWidth: 12,\n\tmaxPrimaryColumnWidth: 32,\n};\n\nconst THINKING_DESCRIPTIONS: Record = {\n\toff: \"No reasoning\",\n\tminimal: \"Very brief reasoning (~1k tokens)\",\n\tlow: \"Light reasoning (~2k tokens)\",\n\tmedium: \"Moderate reasoning (~8k tokens)\",\n\thigh: \"Deep reasoning (~16k tokens)\",\n\txhigh: \"Extra-high reasoning (~32k tokens)\",\n\tmax: \"Maximum reasoning\",\n};\n\nconst DEFAULT_PROJECT_TRUST_LABELS: Record = {\n\task: \"Ask\",\n\talways: \"Always trust\",\n\tnever: \"Never trust\",\n};\n\nconst DEFAULT_PROJECT_TRUST_BY_LABEL = new Map(\n\tObject.entries(DEFAULT_PROJECT_TRUST_LABELS).map(([value, label]) => [label, value as DefaultProjectTrust]),\n);\n\nexport interface SettingsConfig {\n\tautoCompact: boolean;\n\tshowImages: boolean;\n\timageWidthCells: number;\n\tautoResizeImages: boolean;\n\tblockImages: boolean;\n\tenableSkillCommands: boolean;\n\tsteeringMode: \"all\" | \"one-at-a-time\";\n\tfollowUpMode: \"all\" | \"one-at-a-time\";\n\ttransport: Transport;\n\thttpIdleTimeoutMs: number;\n\tthinkingLevel: ThinkingLevel;\n\tavailableThinkingLevels: ThinkingLevel[];\n\tcurrentTheme: string;\n\tterminalTheme: TerminalTheme;\n\tavailableThemes: string[];\n\thideThinkingBlock: boolean;\n\tshowCacheMissNotices: boolean;\n\tcollapseChangelog: boolean;\n\tenableInstallTelemetry: boolean;\n\tdoubleEscapeAction: \"fork\" | \"tree\" | \"none\";\n\ttreeFilterMode: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\";\n\tshowHardwareCursor: boolean;\n\teditorPaddingX: number;\n\toutputPad: 0 | 1;\n\tautocompleteMaxVisible: number;\n\tquietStartup: boolean;\n\tdefaultProjectTrust: DefaultProjectTrust;\n\tclearOnShrink: boolean;\n\tshowTerminalProgress: boolean;\n\twarnings: WarningSettings;\n}\n\nexport interface SettingsCallbacks {\n\tonAutoCompactChange: (enabled: boolean) => void;\n\tonShowImagesChange: (enabled: boolean) => void;\n\tonImageWidthCellsChange: (width: number) => void;\n\tonAutoResizeImagesChange: (enabled: boolean) => void;\n\tonBlockImagesChange: (blocked: boolean) => void;\n\tonEnableSkillCommandsChange: (enabled: boolean) => void;\n\tonSteeringModeChange: (mode: \"all\" | \"one-at-a-time\") => void;\n\tonFollowUpModeChange: (mode: \"all\" | \"one-at-a-time\") => void;\n\tonTransportChange: (transport: Transport) => void;\n\tonHttpIdleTimeoutMsChange: (timeoutMs: number) => void;\n\tonThinkingLevelChange: (level: ThinkingLevel) => void;\n\tonThemeChange: (theme: string) => void;\n\tonThemePreview?: (theme: string) => void;\n\tonHideThinkingBlockChange: (hidden: boolean) => void;\n\tonShowCacheMissNoticesChange: (shown: boolean) => void;\n\tonCollapseChangelogChange: (collapsed: boolean) => void;\n\tonEnableInstallTelemetryChange: (enabled: boolean) => void;\n\tonDoubleEscapeActionChange: (action: \"fork\" | \"tree\" | \"none\") => void;\n\tonTreeFilterModeChange: (mode: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\") => void;\n\tonShowHardwareCursorChange: (enabled: boolean) => void;\n\tonEditorPaddingXChange: (padding: number) => void;\n\tonOutputPadChange: (padding: 0 | 1) => void;\n\tonAutocompleteMaxVisibleChange: (maxVisible: number) => void;\n\tonQuietStartupChange: (enabled: boolean) => void;\n\tonDefaultProjectTrustChange: (defaultProjectTrust: DefaultProjectTrust) => void;\n\tonClearOnShrinkChange: (enabled: boolean) => void;\n\tonShowTerminalProgressChange: (enabled: boolean) => void;\n\tonWarningsChange: (warnings: WarningSettings) => void;\n\tonCancel: () => void;\n}\n\n/**\n * A submenu component for selecting from a list of options.\n */\nclass WarningSettingsSubmenu extends Container {\n\tprivate settingsList: SettingsList;\n\tprivate state: WarningSettings;\n\n\tconstructor(warnings: WarningSettings, onChange: (warnings: WarningSettings) => void, onCancel: () => void) {\n\t\tsuper();\n\n\t\tthis.state = { ...warnings };\n\n\t\tconst items: SettingItem[] = [\n\t\t\t{\n\t\t\t\tid: \"anthropic-extra-usage\",\n\t\t\t\tlabel: \"Anthropic extra usage\",\n\t\t\t\tdescription: \"Warn when Anthropic subscription auth may use paid extra usage\",\n\t\t\t\tcurrentValue: (this.state.anthropicExtraUsage ?? true) ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t];\n\n\t\tthis.settingsList = new SettingsList(\n\t\t\titems,\n\t\t\tMath.min(items.length, 10),\n\t\t\tgetSettingsListTheme(),\n\t\t\t(id, newValue) => {\n\t\t\t\tswitch (id) {\n\t\t\t\t\tcase \"anthropic-extra-usage\":\n\t\t\t\t\t\tthis.state = { ...this.state, anthropicExtraUsage: newValue === \"true\" };\n\t\t\t\t\t\tonChange({ ...this.state });\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t},\n\t\t\tonCancel,\n\t\t);\n\n\t\tthis.addChild(this.settingsList);\n\t}\n\n\thandleInput(data: string): void {\n\t\tthis.settingsList.handleInput(data);\n\t}\n}\n\nclass SelectSubmenu extends Container {\n\tprivate selectList: SelectList;\n\n\tconstructor(\n\t\ttitle: string,\n\t\tdescription: string,\n\t\toptions: SelectItem[],\n\t\tcurrentValue: string,\n\t\tonSelect: (value: string) => void,\n\t\tonCancel: () => void,\n\t\tonSelectionChange?: (value: string) => void,\n\t) {\n\t\tsuper();\n\n\t\t// Title\n\t\tthis.addChild(new Text(theme.bold(theme.fg(\"accent\", title)), 0, 0));\n\n\t\t// Description\n\t\tif (description) {\n\t\t\tthis.addChild(new Spacer(1));\n\t\t\tthis.addChild(new Text(theme.fg(\"muted\", description), 0, 0));\n\t\t}\n\n\t\t// Spacer\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Select list\n\t\tthis.selectList = new SelectList(\n\t\t\toptions,\n\t\t\tMath.min(options.length, 10),\n\t\t\tgetSelectListTheme(),\n\t\t\tSETTINGS_SUBMENU_SELECT_LIST_LAYOUT,\n\t\t);\n\n\t\t// Pre-select current value\n\t\tconst currentIndex = options.findIndex((o) => o.value === currentValue);\n\t\tif (currentIndex !== -1) {\n\t\t\tthis.selectList.setSelectedIndex(currentIndex);\n\t\t}\n\n\t\tthis.selectList.onSelect = (item) => {\n\t\t\tonSelect(item.value);\n\t\t};\n\n\t\tthis.selectList.onCancel = onCancel;\n\n\t\tif (onSelectionChange) {\n\t\t\tthis.selectList.onSelectionChange = (item) => {\n\t\t\t\tonSelectionChange(item.value);\n\t\t\t};\n\t\t}\n\n\t\tthis.addChild(this.selectList);\n\n\t\t// Hint\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.fg(\"dim\", \" Enter to select · Esc to go back\"), 0, 0));\n\t}\n\n\thandleInput(data: string): void {\n\t\tthis.selectList.handleInput(data);\n\t}\n}\n\nfunction themeItems(availableThemes: string[]): SelectItem[] {\n\treturn availableThemes.map((name) => ({ value: name, label: name }));\n}\n\nconst AUTOMATIC_THEME_VALUE = \"/\";\n\nfunction singleModeThemeItems(availableThemes: string[]): SelectItem[] {\n\treturn [\n\t\t{\n\t\t\tvalue: AUTOMATIC_THEME_VALUE,\n\t\t\tlabel: \"Automatic\",\n\t\t\tdescription: \"Use separate themes for light and dark terminal appearance\",\n\t\t},\n\t\t...themeItems(availableThemes),\n\t];\n}\n\nfunction preferredTheme(availableThemes: string[], preferred: string | undefined, fallback: string): string {\n\tif (preferred && availableThemes.includes(preferred)) return preferred;\n\tif (availableThemes.includes(fallback)) return fallback;\n\treturn availableThemes[0] ?? fallback;\n}\n\nfunction defaultAutomaticThemes(\n\tcurrentThemeSetting: string,\n\tavailableThemes: string[],\n): { lightTheme: string; darkTheme: string } {\n\tconst autoTheme = parseAutoThemeSetting(currentThemeSetting);\n\tif (autoTheme) return autoTheme;\n\n\tconst currentFixedTheme = currentThemeSetting.includes(\"/\") ? undefined : currentThemeSetting;\n\tconst themeName = preferredTheme(availableThemes, currentFixedTheme, \"dark\");\n\treturn { lightTheme: themeName, darkTheme: themeName };\n}\n\nclass ThemeSubmenu extends Container {\n\tprivate inputComponent: Component | undefined;\n\tprivate readonly callbacks: SettingsCallbacks;\n\tprivate readonly availableThemes: string[];\n\tprivate readonly terminalTheme: TerminalTheme;\n\tprivate readonly onDone: (selectedValue?: string) => void;\n\tprivate readonly originalThemeSetting: string;\n\tprivate mode: \"single\" | \"automatic\";\n\tprivate singleTheme: string;\n\tprivate lightTheme: string;\n\tprivate darkTheme: string;\n\n\tconstructor(\n\t\tcurrentThemeSetting: string,\n\t\tterminalTheme: TerminalTheme,\n\t\tavailableThemes: string[],\n\t\tcallbacks: SettingsCallbacks,\n\t\tonDone: (selectedValue?: string) => void,\n\t) {\n\t\tsuper();\n\t\tthis.callbacks = callbacks;\n\t\tthis.availableThemes = availableThemes;\n\t\tthis.terminalTheme = terminalTheme;\n\t\tthis.onDone = onDone;\n\t\tthis.originalThemeSetting = currentThemeSetting;\n\t\tconst autoTheme = parseAutoThemeSetting(currentThemeSetting);\n\t\tconst automaticThemes = defaultAutomaticThemes(currentThemeSetting, availableThemes);\n\t\tconst fixedTheme = autoTheme || currentThemeSetting.includes(\"/\") ? undefined : currentThemeSetting;\n\t\tthis.mode = autoTheme ? \"automatic\" : \"single\";\n\t\tthis.lightTheme = automaticThemes.lightTheme;\n\t\tthis.darkTheme = automaticThemes.darkTheme;\n\t\tthis.singleTheme = preferredTheme(\n\t\t\tavailableThemes,\n\t\t\tfixedTheme ?? (autoTheme ? this.getActiveAutomaticTheme() : undefined),\n\t\t\t\"dark\",\n\t\t);\n\n\t\tif (this.mode === \"automatic\") {\n\t\t\tthis.showAutomaticMenu();\n\t\t} else {\n\t\t\tthis.showSingleMenu();\n\t\t}\n\t}\n\n\thandleInput(data: string): void {\n\t\tthis.inputComponent?.handleInput?.(data);\n\t}\n\n\tprivate setContent(renderComponent: Component, inputComponent: Component = renderComponent): void {\n\t\tthis.clear();\n\t\tthis.addChild(renderComponent);\n\t\tthis.inputComponent = inputComponent;\n\t}\n\n\tprivate showSingleMenu(): void {\n\t\tthis.mode = \"single\";\n\t\tconst menu = new SelectSubmenu(\n\t\t\t\"Theme\",\n\t\t\t\"Select a theme, or choose Automatic to follow terminal appearance.\",\n\t\t\tsingleModeThemeItems(this.availableThemes),\n\t\t\tthis.singleTheme,\n\t\t\t(value) => {\n\t\t\t\tif (value === AUTOMATIC_THEME_VALUE) {\n\t\t\t\t\tthis.mode = \"automatic\";\n\t\t\t\t\tthis.callbacks.onThemePreview?.(this.getThemeSetting());\n\t\t\t\t\tthis.showAutomaticMenu();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tthis.singleTheme = value;\n\t\t\t\tthis.apply(value);\n\t\t\t},\n\t\t\t() => this.cancel(),\n\t\t\t(value) => {\n\t\t\t\tthis.callbacks.onThemePreview?.(value === AUTOMATIC_THEME_VALUE ? this.getAutomaticThemeSetting() : value);\n\t\t\t},\n\t\t);\n\t\tthis.setContent(menu);\n\t}\n\n\tprivate showAutomaticMenu(): void {\n\t\tthis.mode = \"automatic\";\n\t\tconst content = new Container();\n\t\tcontent.addChild(new Text(theme.bold(theme.fg(\"accent\", \"Automatic Theme\")), 0, 0));\n\t\tcontent.addChild(new Spacer(1));\n\t\tcontent.addChild(new Text(theme.fg(\"muted\", \"Choose themes for terminal light and dark appearance.\"), 0, 0));\n\t\tcontent.addChild(new Text(theme.fg(\"muted\", \"Light/dark detection requires terminal support.\"), 0, 0));\n\t\tcontent.addChild(new Spacer(1));\n\n\t\tconst items: SettingItem[] = [\n\t\t\t{\n\t\t\t\tid: \"light-theme\",\n\t\t\t\tlabel: \"Light theme\",\n\t\t\t\tdescription: \"Theme to use in automatic mode when the terminal is light\",\n\t\t\t\tcurrentValue: this.lightTheme,\n\t\t\t\tsubmenu: (currentValue, done) =>\n\t\t\t\t\tthis.createThemeSelect(\n\t\t\t\t\t\t\"Light Theme\",\n\t\t\t\t\t\t\"Select the theme to use for light terminal appearance\",\n\t\t\t\t\t\tcurrentValue,\n\t\t\t\t\t\tdone,\n\t\t\t\t\t\t(value) => {\n\t\t\t\t\t\t\tthis.lightTheme = value;\n\t\t\t\t\t\t\tthis.callbacks.onThemePreview?.(this.getThemeSetting());\n\t\t\t\t\t\t\tdone(value);\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"dark-theme\",\n\t\t\t\tlabel: \"Dark theme\",\n\t\t\t\tdescription: \"Theme to use in automatic mode when the terminal is dark\",\n\t\t\t\tcurrentValue: this.darkTheme,\n\t\t\t\tsubmenu: (currentValue, done) =>\n\t\t\t\t\tthis.createThemeSelect(\n\t\t\t\t\t\t\"Dark Theme\",\n\t\t\t\t\t\t\"Select the theme to use for dark terminal appearance\",\n\t\t\t\t\t\tcurrentValue,\n\t\t\t\t\t\tdone,\n\t\t\t\t\t\t(value) => {\n\t\t\t\t\t\t\tthis.darkTheme = value;\n\t\t\t\t\t\t\tthis.callbacks.onThemePreview?.(this.getThemeSetting());\n\t\t\t\t\t\t\tdone(value);\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"apply\",\n\t\t\t\tlabel: \"Apply\",\n\t\t\t\tdescription: \"Save and go back\",\n\t\t\t\tcurrentValue: \"save and go back\",\n\t\t\t\tvalues: [\"save and go back\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"single-mode\",\n\t\t\t\tlabel: \"Change mode\",\n\t\t\t\tdescription: \"Switch to one theme for light and dark\",\n\t\t\t\tcurrentValue: \"switch to single theme\",\n\t\t\t\tvalues: [\"switch to single theme\"],\n\t\t\t},\n\t\t];\n\n\t\tconst settingsList = new SettingsList(\n\t\t\titems,\n\t\t\tMath.min(items.length, 10),\n\t\t\tgetSettingsListTheme(),\n\t\t\t(id) => {\n\t\t\t\tswitch (id) {\n\t\t\t\t\tcase \"single-mode\":\n\t\t\t\t\t\tthis.mode = \"single\";\n\t\t\t\t\t\tthis.singleTheme = this.getActiveAutomaticTheme();\n\t\t\t\t\t\tthis.callbacks.onThemePreview?.(this.singleTheme);\n\t\t\t\t\t\tthis.showSingleMenu();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"apply\":\n\t\t\t\t\t\tthis.apply(this.getAutomaticThemeSetting());\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => this.cancel(),\n\t\t);\n\t\tcontent.addChild(settingsList);\n\t\tthis.setContent(content, settingsList);\n\t}\n\n\tprivate createThemeSelect(\n\t\ttitle: string,\n\t\tdescription: string,\n\t\tcurrentValue: string,\n\t\tdone: (selectedValue?: string) => void,\n\t\tonSelect: (value: string) => void,\n\t): SelectSubmenu {\n\t\treturn new SelectSubmenu(\n\t\t\ttitle,\n\t\t\tdescription,\n\t\t\tthemeItems(this.availableThemes),\n\t\t\tcurrentValue,\n\t\t\tonSelect,\n\t\t\t() => {\n\t\t\t\tthis.callbacks.onThemePreview?.(this.getThemeSetting());\n\t\t\t\tdone();\n\t\t\t},\n\t\t\t(value) => this.callbacks.onThemePreview?.(value),\n\t\t);\n\t}\n\n\tprivate getThemeSetting(): string {\n\t\treturn this.mode === \"automatic\" ? this.getAutomaticThemeSetting() : this.singleTheme;\n\t}\n\n\tprivate getActiveAutomaticTheme(): string {\n\t\treturn this.terminalTheme === \"light\" ? this.lightTheme : this.darkTheme;\n\t}\n\n\tprivate getAutomaticThemeSetting(): string {\n\t\treturn `${this.lightTheme}/${this.darkTheme}`;\n\t}\n\n\tprivate apply(themeSetting: string): void {\n\t\tthis.onDone(themeSetting);\n\t}\n\n\tprivate cancel(): void {\n\t\tthis.callbacks.onThemePreview?.(this.originalThemeSetting);\n\t\tthis.onDone();\n\t}\n}\n\n/**\n * Main settings selector component.\n */\nexport class SettingsSelectorComponent extends Container {\n\tprivate settingsList: SettingsList;\n\n\tconstructor(config: SettingsConfig, callbacks: SettingsCallbacks) {\n\t\tsuper();\n\n\t\tconst supportsImages = getCapabilities().images;\n\t\tconst followUpKey = keyDisplayText(\"app.message.followUp\");\n\t\tlet currentWarnings = { ...config.warnings };\n\n\t\tconst items: SettingItem[] = [\n\t\t\t{\n\t\t\t\tid: \"autocompact\",\n\t\t\t\tlabel: \"Auto-compact\",\n\t\t\t\tdescription: \"Automatically compact context when it gets too large\",\n\t\t\t\tcurrentValue: config.autoCompact ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"steering-mode\",\n\t\t\t\tlabel: \"Steering mode\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Enter while streaming queues steering messages. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.\",\n\t\t\t\tcurrentValue: config.steeringMode,\n\t\t\t\tvalues: [\"one-at-a-time\", \"all\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"follow-up-mode\",\n\t\t\t\tlabel: \"Follow-up mode\",\n\t\t\t\tdescription: `${followUpKey} queues follow-up messages until agent stops. 'one-at-a-time': deliver one, wait for response. 'all': deliver all at once.`,\n\t\t\t\tcurrentValue: config.followUpMode,\n\t\t\t\tvalues: [\"one-at-a-time\", \"all\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"transport\",\n\t\t\t\tlabel: \"Transport\",\n\t\t\t\tdescription: \"Preferred transport for providers that support multiple transports\",\n\t\t\t\tcurrentValue: config.transport,\n\t\t\t\tvalues: [\"sse\", \"websocket\", \"websocket-cached\", \"auto\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"http-idle-timeout\",\n\t\t\t\tlabel: \"HTTP idle timeout\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Maximum idle gap while waiting for HTTP headers or body chunks. Disable for local models that pause longer than five minutes.\",\n\t\t\t\tcurrentValue: formatHttpIdleTimeoutMs(config.httpIdleTimeoutMs),\n\t\t\t\tvalues: HTTP_IDLE_TIMEOUT_CHOICES.map((choice) => choice.label),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"hide-thinking\",\n\t\t\t\tlabel: \"Hide thinking\",\n\t\t\t\tdescription: \"Hide thinking blocks in assistant responses\",\n\t\t\t\tcurrentValue: config.hideThinkingBlock ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"cache-miss-notices\",\n\t\t\t\tlabel: \"Cache miss notices\",\n\t\t\t\tdescription: \"Show transcript notices for significant prompt-cache misses\",\n\t\t\t\tcurrentValue: config.showCacheMissNotices ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"collapse-changelog\",\n\t\t\t\tlabel: \"Collapse changelog\",\n\t\t\t\tdescription: \"Show condensed changelog after updates\",\n\t\t\t\tcurrentValue: config.collapseChangelog ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"quiet-startup\",\n\t\t\t\tlabel: \"Quiet startup\",\n\t\t\t\tdescription: \"Disable verbose printing at startup\",\n\t\t\t\tcurrentValue: config.quietStartup ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"install-telemetry\",\n\t\t\t\tlabel: \"Install telemetry\",\n\t\t\t\tdescription: \"Send an anonymous version/update ping after changelog-detected updates\",\n\t\t\t\tcurrentValue: config.enableInstallTelemetry ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"default-project-trust\",\n\t\t\t\tlabel: \"Default project trust\",\n\t\t\t\tdescription: \"Fallback behavior when no extension or saved trust decision decides project trust\",\n\t\t\t\tcurrentValue: DEFAULT_PROJECT_TRUST_LABELS[config.defaultProjectTrust],\n\t\t\t\tvalues: Object.values(DEFAULT_PROJECT_TRUST_LABELS),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"double-escape-action\",\n\t\t\t\tlabel: \"Double-escape action\",\n\t\t\t\tdescription: \"Action when pressing Escape twice with empty editor\",\n\t\t\t\tcurrentValue: config.doubleEscapeAction,\n\t\t\t\tvalues: [\"tree\", \"fork\", \"none\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"tree-filter-mode\",\n\t\t\t\tlabel: \"Tree filter mode\",\n\t\t\t\tdescription: \"Default filter when opening /tree\",\n\t\t\t\tcurrentValue: config.treeFilterMode,\n\t\t\t\tvalues: [\"default\", \"no-tools\", \"user-only\", \"labeled-only\", \"all\"],\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"warnings\",\n\t\t\t\tlabel: \"Warnings\",\n\t\t\t\tdescription: \"Enable or disable individual warnings\",\n\t\t\t\tcurrentValue: \"configure\",\n\t\t\t\tsubmenu: (_currentValue, done) =>\n\t\t\t\t\tnew WarningSettingsSubmenu(\n\t\t\t\t\t\tcurrentWarnings,\n\t\t\t\t\t\t(warnings) => {\n\t\t\t\t\t\t\tcurrentWarnings = warnings;\n\t\t\t\t\t\t\tcallbacks.onWarningsChange(warnings);\n\t\t\t\t\t\t},\n\t\t\t\t\t\t() => done(),\n\t\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"thinking\",\n\t\t\t\tlabel: \"Thinking level\",\n\t\t\t\tdescription: \"Reasoning depth for thinking-capable models\",\n\t\t\t\tcurrentValue: config.thinkingLevel,\n\t\t\t\tsubmenu: (currentValue, done) =>\n\t\t\t\t\tnew SelectSubmenu(\n\t\t\t\t\t\t\"Thinking Level\",\n\t\t\t\t\t\t\"Select reasoning depth for thinking-capable models\",\n\t\t\t\t\t\tconfig.availableThinkingLevels.map((level) => ({\n\t\t\t\t\t\t\tvalue: level,\n\t\t\t\t\t\t\tlabel: level,\n\t\t\t\t\t\t\tdescription: THINKING_DESCRIPTIONS[level],\n\t\t\t\t\t\t})),\n\t\t\t\t\t\tcurrentValue,\n\t\t\t\t\t\t(value) => {\n\t\t\t\t\t\t\tcallbacks.onThinkingLevelChange(value as ThinkingLevel);\n\t\t\t\t\t\t\tdone(value);\n\t\t\t\t\t\t},\n\t\t\t\t\t\t() => done(),\n\t\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"theme\",\n\t\t\t\tlabel: \"Theme\",\n\t\t\t\tdescription: \"Color theme for the interface\",\n\t\t\t\tcurrentValue: config.currentTheme,\n\t\t\t\tsubmenu: (currentValue, done) =>\n\t\t\t\t\tnew ThemeSubmenu(currentValue, config.terminalTheme, config.availableThemes, callbacks, done),\n\t\t\t},\n\t\t];\n\n\t\t// Only show image toggle if terminal supports it\n\t\tif (supportsImages) {\n\t\t\t// Insert after autocompact\n\t\t\titems.splice(1, 0, {\n\t\t\t\tid: \"show-images\",\n\t\t\t\tlabel: \"Show images\",\n\t\t\t\tdescription: \"Render images inline in terminal\",\n\t\t\t\tcurrentValue: config.showImages ? \"true\" : \"false\",\n\t\t\t\tvalues: [\"true\", \"false\"],\n\t\t\t});\n\t\t\titems.splice(2, 0, {\n\t\t\t\tid: \"image-width-cells\",\n\t\t\t\tlabel: \"Image width\",\n\t\t\t\tdescription: \"Preferred inline image width in terminal cells\",\n\t\t\t\tcurrentValue: String(config.imageWidthCells),\n\t\t\t\tvalues: [\"60\", \"80\", \"120\"],\n\t\t\t});\n\t\t}\n\n\t\t// Image auto-resize toggle (always available, affects both attached and read images)\n\t\titems.splice(supportsImages ? 3 : 1, 0, {\n\t\t\tid: \"auto-resize-images\",\n\t\t\tlabel: \"Auto-resize images\",\n\t\t\tdescription: \"Resize large images to 2000x2000 max for better model compatibility\",\n\t\t\tcurrentValue: config.autoResizeImages ? \"true\" : \"false\",\n\t\t\tvalues: [\"true\", \"false\"],\n\t\t});\n\n\t\t// Block images toggle (always available, insert after auto-resize-images)\n\t\tconst autoResizeIndex = items.findIndex((item) => item.id === \"auto-resize-images\");\n\t\titems.splice(autoResizeIndex + 1, 0, {\n\t\t\tid: \"block-images\",\n\t\t\tlabel: \"Block images\",\n\t\t\tdescription: \"Prevent images from being sent to LLM providers\",\n\t\t\tcurrentValue: config.blockImages ? \"true\" : \"false\",\n\t\t\tvalues: [\"true\", \"false\"],\n\t\t});\n\n\t\t// Skill commands toggle (insert after block-images)\n\t\tconst blockImagesIndex = items.findIndex((item) => item.id === \"block-images\");\n\t\titems.splice(blockImagesIndex + 1, 0, {\n\t\t\tid: \"skill-commands\",\n\t\t\tlabel: \"Skill commands\",\n\t\t\tdescription: \"Register skills as /skill:name commands\",\n\t\t\tcurrentValue: config.enableSkillCommands ? \"true\" : \"false\",\n\t\t\tvalues: [\"true\", \"false\"],\n\t\t});\n\n\t\t// Hardware cursor toggle (insert after skill-commands)\n\t\tconst skillCommandsIndex = items.findIndex((item) => item.id === \"skill-commands\");\n\t\titems.splice(skillCommandsIndex + 1, 0, {\n\t\t\tid: \"show-hardware-cursor\",\n\t\t\tlabel: \"Show hardware cursor\",\n\t\t\tdescription: \"Show the terminal cursor while still positioning it for IME support\",\n\t\t\tcurrentValue: config.showHardwareCursor ? \"true\" : \"false\",\n\t\t\tvalues: [\"true\", \"false\"],\n\t\t});\n\n\t\t// Editor padding toggle (insert after show-hardware-cursor)\n\t\tconst hardwareCursorIndex = items.findIndex((item) => item.id === \"show-hardware-cursor\");\n\t\titems.splice(hardwareCursorIndex + 1, 0, {\n\t\t\tid: \"editor-padding\",\n\t\t\tlabel: \"Editor padding\",\n\t\t\tdescription: \"Horizontal padding for input editor (0-3)\",\n\t\t\tcurrentValue: String(config.editorPaddingX),\n\t\t\tvalues: [\"0\", \"1\", \"2\", \"3\"],\n\t\t});\n\n\t\t// Output padding toggle (insert after editor-padding)\n\t\tconst editorPaddingIndex = items.findIndex((item) => item.id === \"editor-padding\");\n\t\titems.splice(editorPaddingIndex + 1, 0, {\n\t\t\tid: \"output-padding\",\n\t\t\tlabel: \"Output padding\",\n\t\t\tdescription: \"Horizontal padding for user messages, assistant messages, and thinking\",\n\t\t\tcurrentValue: String(config.outputPad),\n\t\t\tvalues: [\"0\", \"1\"],\n\t\t});\n\n\t\t// Autocomplete max visible toggle (insert after output-padding)\n\t\tconst outputPaddingIndex = items.findIndex((item) => item.id === \"output-padding\");\n\t\titems.splice(outputPaddingIndex + 1, 0, {\n\t\t\tid: \"autocomplete-max-visible\",\n\t\t\tlabel: \"Autocomplete max items\",\n\t\t\tdescription: \"Max visible items in autocomplete dropdown (3-20)\",\n\t\t\tcurrentValue: String(config.autocompleteMaxVisible),\n\t\t\tvalues: [\"3\", \"5\", \"7\", \"10\", \"15\", \"20\"],\n\t\t});\n\n\t\t// Clear on shrink toggle (insert after autocomplete-max-visible)\n\t\tconst autocompleteIndex = items.findIndex((item) => item.id === \"autocomplete-max-visible\");\n\t\titems.splice(autocompleteIndex + 1, 0, {\n\t\t\tid: \"clear-on-shrink\",\n\t\t\tlabel: \"Clear on shrink\",\n\t\t\tdescription: \"Clear empty rows when content shrinks (may cause flicker)\",\n\t\t\tcurrentValue: config.clearOnShrink ? \"true\" : \"false\",\n\t\t\tvalues: [\"true\", \"false\"],\n\t\t});\n\n\t\t// Terminal progress toggle (insert after clear-on-shrink)\n\t\tconst clearOnShrinkIndex = items.findIndex((item) => item.id === \"clear-on-shrink\");\n\t\titems.splice(clearOnShrinkIndex + 1, 0, {\n\t\t\tid: \"terminal-progress\",\n\t\t\tlabel: \"Terminal progress\",\n\t\t\tdescription: \"Show OSC 9;4 progress indicators in the terminal tab bar\",\n\t\t\tcurrentValue: config.showTerminalProgress ? \"true\" : \"false\",\n\t\t\tvalues: [\"true\", \"false\"],\n\t\t});\n\n\t\t// Add borders\n\t\tthis.addChild(new DynamicBorder());\n\n\t\tthis.settingsList = new SettingsList(\n\t\t\titems,\n\t\t\t10,\n\t\t\tgetSettingsListTheme(),\n\t\t\t(id, newValue) => {\n\t\t\t\tswitch (id) {\n\t\t\t\t\tcase \"autocompact\":\n\t\t\t\t\t\tcallbacks.onAutoCompactChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"show-images\":\n\t\t\t\t\t\tcallbacks.onShowImagesChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"image-width-cells\":\n\t\t\t\t\t\tcallbacks.onImageWidthCellsChange(parseInt(newValue, 10));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"auto-resize-images\":\n\t\t\t\t\t\tcallbacks.onAutoResizeImagesChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"block-images\":\n\t\t\t\t\t\tcallbacks.onBlockImagesChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"skill-commands\":\n\t\t\t\t\t\tcallbacks.onEnableSkillCommandsChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"steering-mode\":\n\t\t\t\t\t\tcallbacks.onSteeringModeChange(newValue as \"all\" | \"one-at-a-time\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"follow-up-mode\":\n\t\t\t\t\t\tcallbacks.onFollowUpModeChange(newValue as \"all\" | \"one-at-a-time\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"transport\":\n\t\t\t\t\t\tcallbacks.onTransportChange(newValue as Transport);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"http-idle-timeout\": {\n\t\t\t\t\t\tconst choice = HTTP_IDLE_TIMEOUT_CHOICES.find((item) => item.label === newValue);\n\t\t\t\t\t\tif (choice) {\n\t\t\t\t\t\t\tcallbacks.onHttpIdleTimeoutMsChange(choice.timeoutMs);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"hide-thinking\":\n\t\t\t\t\t\tcallbacks.onHideThinkingBlockChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"cache-miss-notices\":\n\t\t\t\t\t\tcallbacks.onShowCacheMissNoticesChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"collapse-changelog\":\n\t\t\t\t\t\tcallbacks.onCollapseChangelogChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"quiet-startup\":\n\t\t\t\t\t\tcallbacks.onQuietStartupChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"install-telemetry\":\n\t\t\t\t\t\tcallbacks.onEnableInstallTelemetryChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"default-project-trust\": {\n\t\t\t\t\t\tconst defaultProjectTrust = DEFAULT_PROJECT_TRUST_BY_LABEL.get(newValue);\n\t\t\t\t\t\tif (defaultProjectTrust) {\n\t\t\t\t\t\t\tcallbacks.onDefaultProjectTrustChange(defaultProjectTrust);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"double-escape-action\":\n\t\t\t\t\t\tcallbacks.onDoubleEscapeActionChange(newValue as \"fork\" | \"tree\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tree-filter-mode\":\n\t\t\t\t\t\tcallbacks.onTreeFilterModeChange(\n\t\t\t\t\t\t\tnewValue as \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"show-hardware-cursor\":\n\t\t\t\t\t\tcallbacks.onShowHardwareCursorChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"editor-padding\":\n\t\t\t\t\t\tcallbacks.onEditorPaddingXChange(parseInt(newValue, 10));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"output-padding\":\n\t\t\t\t\t\tcallbacks.onOutputPadChange(newValue === \"0\" ? 0 : 1);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"autocomplete-max-visible\":\n\t\t\t\t\t\tcallbacks.onAutocompleteMaxVisibleChange(parseInt(newValue, 10));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"clear-on-shrink\":\n\t\t\t\t\t\tcallbacks.onClearOnShrinkChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"terminal-progress\":\n\t\t\t\t\t\tcallbacks.onShowTerminalProgressChange(newValue === \"true\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"theme\":\n\t\t\t\t\t\tcallbacks.onThemeChange(newValue);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t},\n\t\t\tcallbacks.onCancel,\n\t\t\t{ enableSearch: true },\n\t\t);\n\n\t\tthis.addChild(this.settingsList);\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tgetSettingsList(): SettingsList {\n\t\treturn this.settingsList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/show-images-selector.d.ts b/dist/modes/interactive/components/show-images-selector.d.ts new file mode 100644 index 0000000..b9e14f2 --- /dev/null +++ b/dist/modes/interactive/components/show-images-selector.d.ts @@ -0,0 +1,10 @@ +import { Container, SelectList } from "@earendil-works/pi-tui"; +/** + * Component that renders a show images selector with borders + */ +export declare class ShowImagesSelectorComponent extends Container { + private selectList; + constructor(currentValue: boolean, onSelect: (show: boolean) => void, onCancel: () => void); + getSelectList(): SelectList; +} +//# sourceMappingURL=show-images-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/show-images-selector.d.ts.map b/dist/modes/interactive/components/show-images-selector.d.ts.map new file mode 100644 index 0000000..b533899 --- /dev/null +++ b/dist/modes/interactive/components/show-images-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"show-images-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/show-images-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAmB,UAAU,EAAgC,MAAM,wBAAwB,CAAC;AAS9G;;GAEG;AACH,qBAAa,2BAA4B,SAAQ,SAAS;IACzD,OAAO,CAAC,UAAU,CAAa;IAE/B,YAAY,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,EA6BzF;IAED,aAAa,IAAI,UAAU,CAE1B;CACD","sourcesContent":["import { Container, type SelectItem, SelectList, type SelectListLayoutOptions } from \"@earendil-works/pi-tui\";\nimport { getSelectListTheme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\n\nconst SHOW_IMAGES_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {\n\tminPrimaryColumnWidth: 12,\n\tmaxPrimaryColumnWidth: 32,\n};\n\n/**\n * Component that renders a show images selector with borders\n */\nexport class ShowImagesSelectorComponent extends Container {\n\tprivate selectList: SelectList;\n\n\tconstructor(currentValue: boolean, onSelect: (show: boolean) => void, onCancel: () => void) {\n\t\tsuper();\n\n\t\tconst items: SelectItem[] = [\n\t\t\t{ value: \"yes\", label: \"Yes\", description: \"Show images inline in terminal\" },\n\t\t\t{ value: \"no\", label: \"No\", description: \"Show text placeholder instead\" },\n\t\t];\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Create selector\n\t\tthis.selectList = new SelectList(items, 5, getSelectListTheme(), SHOW_IMAGES_SELECT_LIST_LAYOUT);\n\n\t\t// Preselect current value\n\t\tthis.selectList.setSelectedIndex(currentValue ? 0 : 1);\n\n\t\tthis.selectList.onSelect = (item) => {\n\t\t\tonSelect(item.value === \"yes\");\n\t\t};\n\n\t\tthis.selectList.onCancel = () => {\n\t\t\tonCancel();\n\t\t};\n\n\t\tthis.addChild(this.selectList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tgetSelectList(): SelectList {\n\t\treturn this.selectList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/show-images-selector.js b/dist/modes/interactive/components/show-images-selector.js new file mode 100644 index 0000000..5da465b --- /dev/null +++ b/dist/modes/interactive/components/show-images-selector.js @@ -0,0 +1,39 @@ +import { Container, SelectList } from "@earendil-works/pi-tui"; +import { getSelectListTheme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +const SHOW_IMAGES_SELECT_LIST_LAYOUT = { + minPrimaryColumnWidth: 12, + maxPrimaryColumnWidth: 32, +}; +/** + * Component that renders a show images selector with borders + */ +export class ShowImagesSelectorComponent extends Container { + selectList; + constructor(currentValue, onSelect, onCancel) { + super(); + const items = [ + { value: "yes", label: "Yes", description: "Show images inline in terminal" }, + { value: "no", label: "No", description: "Show text placeholder instead" }, + ]; + // Add top border + this.addChild(new DynamicBorder()); + // Create selector + this.selectList = new SelectList(items, 5, getSelectListTheme(), SHOW_IMAGES_SELECT_LIST_LAYOUT); + // Preselect current value + this.selectList.setSelectedIndex(currentValue ? 0 : 1); + this.selectList.onSelect = (item) => { + onSelect(item.value === "yes"); + }; + this.selectList.onCancel = () => { + onCancel(); + }; + this.addChild(this.selectList); + // Add bottom border + this.addChild(new DynamicBorder()); + } + getSelectList() { + return this.selectList; + } +} +//# sourceMappingURL=show-images-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/show-images-selector.js.map b/dist/modes/interactive/components/show-images-selector.js.map new file mode 100644 index 0000000..6d4efd1 --- /dev/null +++ b/dist/modes/interactive/components/show-images-selector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"show-images-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/show-images-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAmB,UAAU,EAAgC,MAAM,wBAAwB,CAAC;AAC9G,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,MAAM,8BAA8B,GAA4B;IAC/D,qBAAqB,EAAE,EAAE;IACzB,qBAAqB,EAAE,EAAE;CACzB,CAAC;AAEF;;GAEG;AACH,MAAM,OAAO,2BAA4B,SAAQ,SAAS;IACjD,UAAU,CAAa;IAE/B,YAAY,YAAqB,EAAE,QAAiC,EAAE,QAAoB,EAAE;QAC3F,KAAK,EAAE,CAAC;QAER,MAAM,KAAK,GAAiB;YAC3B,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,gCAAgC,EAAE;YAC7E,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,+BAA+B,EAAE;SAC1E,CAAC;QAEF,iBAAiB;QACjB,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;QAEnC,kBAAkB;QAClB,IAAI,CAAC,UAAU,GAAG,IAAI,UAAU,CAAC,KAAK,EAAE,CAAC,EAAE,kBAAkB,EAAE,EAAE,8BAA8B,CAAC,CAAC;QAEjG,0BAA0B;QAC1B,IAAI,CAAC,UAAU,CAAC,gBAAgB,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAEvD,IAAI,CAAC,UAAU,CAAC,QAAQ,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC;YACpC,QAAQ,CAAC,IAAI,CAAC,KAAK,KAAK,KAAK,CAAC,CAAC;QAAA,CAC/B,CAAC;QAEF,IAAI,CAAC,UAAU,CAAC,QAAQ,GAAG,GAAG,EAAE,CAAC;YAChC,QAAQ,EAAE,CAAC;QAAA,CACX,CAAC;QAEF,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAE/B,oBAAoB;QACpB,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;IAAA,CACnC;IAED,aAAa,GAAe;QAC3B,OAAO,IAAI,CAAC,UAAU,CAAC;IAAA,CACvB;CACD","sourcesContent":["import { Container, type SelectItem, SelectList, type SelectListLayoutOptions } from \"@earendil-works/pi-tui\";\nimport { getSelectListTheme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\n\nconst SHOW_IMAGES_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {\n\tminPrimaryColumnWidth: 12,\n\tmaxPrimaryColumnWidth: 32,\n};\n\n/**\n * Component that renders a show images selector with borders\n */\nexport class ShowImagesSelectorComponent extends Container {\n\tprivate selectList: SelectList;\n\n\tconstructor(currentValue: boolean, onSelect: (show: boolean) => void, onCancel: () => void) {\n\t\tsuper();\n\n\t\tconst items: SelectItem[] = [\n\t\t\t{ value: \"yes\", label: \"Yes\", description: \"Show images inline in terminal\" },\n\t\t\t{ value: \"no\", label: \"No\", description: \"Show text placeholder instead\" },\n\t\t];\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Create selector\n\t\tthis.selectList = new SelectList(items, 5, getSelectListTheme(), SHOW_IMAGES_SELECT_LIST_LAYOUT);\n\n\t\t// Preselect current value\n\t\tthis.selectList.setSelectedIndex(currentValue ? 0 : 1);\n\n\t\tthis.selectList.onSelect = (item) => {\n\t\t\tonSelect(item.value === \"yes\");\n\t\t};\n\n\t\tthis.selectList.onCancel = () => {\n\t\t\tonCancel();\n\t\t};\n\n\t\tthis.addChild(this.selectList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tgetSelectList(): SelectList {\n\t\treturn this.selectList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/skill-invocation-message.d.ts b/dist/modes/interactive/components/skill-invocation-message.d.ts new file mode 100644 index 0000000..8841515 --- /dev/null +++ b/dist/modes/interactive/components/skill-invocation-message.d.ts @@ -0,0 +1,17 @@ +import { Box, type MarkdownTheme } from "@earendil-works/pi-tui"; +import type { ParsedSkillBlock } from "../../../core/agent-session.ts"; +/** + * Component that renders a skill invocation message with collapsed/expanded state. + * Uses same background color as custom messages for visual consistency. + * Only renders the skill block itself - user message is rendered separately. + */ +export declare class SkillInvocationMessageComponent extends Box { + private expanded; + private skillBlock; + private markdownTheme; + constructor(skillBlock: ParsedSkillBlock, markdownTheme?: MarkdownTheme); + setExpanded(expanded: boolean): void; + invalidate(): void; + private updateDisplay; +} +//# sourceMappingURL=skill-invocation-message.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/skill-invocation-message.d.ts.map b/dist/modes/interactive/components/skill-invocation-message.d.ts.map new file mode 100644 index 0000000..3ea603c --- /dev/null +++ b/dist/modes/interactive/components/skill-invocation-message.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"skill-invocation-message.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/skill-invocation-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAY,KAAK,aAAa,EAAQ,MAAM,wBAAwB,CAAC;AACjF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAIvE;;;;GAIG;AACH,qBAAa,+BAAgC,SAAQ,GAAG;IACvD,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,UAAU,CAAmB;IACrC,OAAO,CAAC,aAAa,CAAgB;IAErC,YAAY,UAAU,EAAE,gBAAgB,EAAE,aAAa,GAAE,aAAkC,EAK1F;IAED,WAAW,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI,CAGnC;IAEQ,UAAU,IAAI,IAAI,CAG1B;IAED,OAAO,CAAC,aAAa;CAsBrB","sourcesContent":["import { Box, Markdown, type MarkdownTheme, Text } from \"@earendil-works/pi-tui\";\nimport type { ParsedSkillBlock } from \"../../../core/agent-session.ts\";\nimport { getMarkdownTheme, theme } from \"../theme/theme.ts\";\nimport { keyText } from \"./keybinding-hints.ts\";\n\n/**\n * Component that renders a skill invocation message with collapsed/expanded state.\n * Uses same background color as custom messages for visual consistency.\n * Only renders the skill block itself - user message is rendered separately.\n */\nexport class SkillInvocationMessageComponent extends Box {\n\tprivate expanded = false;\n\tprivate skillBlock: ParsedSkillBlock;\n\tprivate markdownTheme: MarkdownTheme;\n\n\tconstructor(skillBlock: ParsedSkillBlock, markdownTheme: MarkdownTheme = getMarkdownTheme()) {\n\t\tsuper(1, 1, (t) => theme.bg(\"customMessageBg\", t));\n\t\tthis.skillBlock = skillBlock;\n\t\tthis.markdownTheme = markdownTheme;\n\t\tthis.updateDisplay();\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.expanded = expanded;\n\t\tthis.updateDisplay();\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.updateDisplay();\n\t}\n\n\tprivate updateDisplay(): void {\n\t\tthis.clear();\n\n\t\tif (this.expanded) {\n\t\t\t// Expanded: label + skill name header + full content\n\t\t\tconst label = theme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m`);\n\t\t\tthis.addChild(new Text(label, 0, 0));\n\t\t\tconst header = `**${this.skillBlock.name}**\\n\\n`;\n\t\t\tthis.addChild(\n\t\t\t\tnew Markdown(header + this.skillBlock.content, 0, 0, this.markdownTheme, {\n\t\t\t\t\tcolor: (text: string) => theme.fg(\"customMessageText\", text),\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\t// Collapsed: single line - [skill] name (hint to expand)\n\t\t\tconst line =\n\t\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m `) +\n\t\t\t\ttheme.fg(\"customMessageText\", this.skillBlock.name) +\n\t\t\t\ttheme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} to expand)`);\n\t\t\tthis.addChild(new Text(line, 0, 0));\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/skill-invocation-message.js b/dist/modes/interactive/components/skill-invocation-message.js new file mode 100644 index 0000000..561f3d2 --- /dev/null +++ b/dist/modes/interactive/components/skill-invocation-message.js @@ -0,0 +1,47 @@ +import { Box, Markdown, Text } from "@earendil-works/pi-tui"; +import { getMarkdownTheme, theme } from "../theme/theme.js"; +import { keyText } from "./keybinding-hints.js"; +/** + * Component that renders a skill invocation message with collapsed/expanded state. + * Uses same background color as custom messages for visual consistency. + * Only renders the skill block itself - user message is rendered separately. + */ +export class SkillInvocationMessageComponent extends Box { + expanded = false; + skillBlock; + markdownTheme; + constructor(skillBlock, markdownTheme = getMarkdownTheme()) { + super(1, 1, (t) => theme.bg("customMessageBg", t)); + this.skillBlock = skillBlock; + this.markdownTheme = markdownTheme; + this.updateDisplay(); + } + setExpanded(expanded) { + this.expanded = expanded; + this.updateDisplay(); + } + invalidate() { + super.invalidate(); + this.updateDisplay(); + } + updateDisplay() { + this.clear(); + if (this.expanded) { + // Expanded: label + skill name header + full content + const label = theme.fg("customMessageLabel", `\x1b[1m[skill]\x1b[22m`); + this.addChild(new Text(label, 0, 0)); + const header = `**${this.skillBlock.name}**\n\n`; + this.addChild(new Markdown(header + this.skillBlock.content, 0, 0, this.markdownTheme, { + color: (text) => theme.fg("customMessageText", text), + })); + } + else { + // Collapsed: single line - [skill] name (hint to expand) + const line = theme.fg("customMessageLabel", `\x1b[1m[skill]\x1b[22m `) + + theme.fg("customMessageText", this.skillBlock.name) + + theme.fg("dim", ` (${keyText("app.tools.expand")} to expand)`); + this.addChild(new Text(line, 0, 0)); + } + } +} +//# sourceMappingURL=skill-invocation-message.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/skill-invocation-message.js.map b/dist/modes/interactive/components/skill-invocation-message.js.map new file mode 100644 index 0000000..f01a749 --- /dev/null +++ b/dist/modes/interactive/components/skill-invocation-message.js.map @@ -0,0 +1 @@ +{"version":3,"file":"skill-invocation-message.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/skill-invocation-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAsB,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAEjF,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAEhD;;;;GAIG;AACH,MAAM,OAAO,+BAAgC,SAAQ,GAAG;IAC/C,QAAQ,GAAG,KAAK,CAAC;IACjB,UAAU,CAAmB;IAC7B,aAAa,CAAgB;IAErC,YAAY,UAA4B,EAAE,aAAa,GAAkB,gBAAgB,EAAE,EAAE;QAC5F,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,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CAAC;gBACnD,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,OAAO,CAAC,kBAAkB,CAAC,aAAa,CAAC,CAAC;YAChE,IAAI,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QACrC,CAAC;IAAA,CACD;CACD","sourcesContent":["import { Box, Markdown, type MarkdownTheme, Text } from \"@earendil-works/pi-tui\";\nimport type { ParsedSkillBlock } from \"../../../core/agent-session.ts\";\nimport { getMarkdownTheme, theme } from \"../theme/theme.ts\";\nimport { keyText } from \"./keybinding-hints.ts\";\n\n/**\n * Component that renders a skill invocation message with collapsed/expanded state.\n * Uses same background color as custom messages for visual consistency.\n * Only renders the skill block itself - user message is rendered separately.\n */\nexport class SkillInvocationMessageComponent extends Box {\n\tprivate expanded = false;\n\tprivate skillBlock: ParsedSkillBlock;\n\tprivate markdownTheme: MarkdownTheme;\n\n\tconstructor(skillBlock: ParsedSkillBlock, markdownTheme: MarkdownTheme = getMarkdownTheme()) {\n\t\tsuper(1, 1, (t) => theme.bg(\"customMessageBg\", t));\n\t\tthis.skillBlock = skillBlock;\n\t\tthis.markdownTheme = markdownTheme;\n\t\tthis.updateDisplay();\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.expanded = expanded;\n\t\tthis.updateDisplay();\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.updateDisplay();\n\t}\n\n\tprivate updateDisplay(): void {\n\t\tthis.clear();\n\n\t\tif (this.expanded) {\n\t\t\t// Expanded: label + skill name header + full content\n\t\t\tconst label = theme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m`);\n\t\t\tthis.addChild(new Text(label, 0, 0));\n\t\t\tconst header = `**${this.skillBlock.name}**\\n\\n`;\n\t\t\tthis.addChild(\n\t\t\t\tnew Markdown(header + this.skillBlock.content, 0, 0, this.markdownTheme, {\n\t\t\t\t\tcolor: (text: string) => theme.fg(\"customMessageText\", text),\n\t\t\t\t}),\n\t\t\t);\n\t\t} else {\n\t\t\t// Collapsed: single line - [skill] name (hint to expand)\n\t\t\tconst line =\n\t\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m `) +\n\t\t\t\ttheme.fg(\"customMessageText\", this.skillBlock.name) +\n\t\t\t\ttheme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} to expand)`);\n\t\t\tthis.addChild(new Text(line, 0, 0));\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/status-indicator.d.ts b/dist/modes/interactive/components/status-indicator.d.ts new file mode 100644 index 0000000..76205f7 --- /dev/null +++ b/dist/modes/interactive/components/status-indicator.d.ts @@ -0,0 +1,28 @@ +import { type Component, Loader, type TUI } from "@earendil-works/pi-tui"; +import type { WorkingIndicatorOptions } from "../../../core/extensions/index.ts"; +export type StatusIndicatorKind = "working" | "retry" | "compaction" | "branchSummary"; +export declare class StatusIndicator extends Loader { + readonly kind: StatusIndicatorKind; + constructor(kind: StatusIndicatorKind, ui: TUI, spinnerColorFn: (str: string) => string, messageColorFn: (str: string) => string, message: string, indicator?: WorkingIndicatorOptions); + dispose(): void; +} +export declare class WorkingStatusIndicator extends StatusIndicator { + constructor(ui: TUI, message: string, indicator?: WorkingIndicatorOptions); +} +export declare class RetryStatusIndicator extends StatusIndicator { + private countdown; + constructor(ui: TUI, attempt: number, maxAttempts: number, delayMs: number); + dispose(): void; +} +export type CompactionStatusReason = "manual" | "threshold" | "overflow"; +export declare class CompactionStatusIndicator extends StatusIndicator { + constructor(ui: TUI, reason: CompactionStatusReason); +} +export declare class BranchSummaryStatusIndicator extends StatusIndicator { + constructor(ui: TUI); +} +export declare class IdleStatus implements Component { + invalidate(): void; + render(width: number): string[]; +} +//# sourceMappingURL=status-indicator.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/status-indicator.d.ts.map b/dist/modes/interactive/components/status-indicator.d.ts.map new file mode 100644 index 0000000..1dc2c17 --- /dev/null +++ b/dist/modes/interactive/components/status-indicator.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"status-indicator.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/status-indicator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,EAAE,KAAK,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,mCAAmC,CAAC;AAKjF,MAAM,MAAM,mBAAmB,GAAG,SAAS,GAAG,OAAO,GAAG,YAAY,GAAG,eAAe,CAAC;AAEvF,qBAAa,eAAgB,SAAQ,MAAM;IAC1C,QAAQ,CAAC,IAAI,EAAE,mBAAmB,CAAC;IAEnC,YACC,IAAI,EAAE,mBAAmB,EACzB,EAAE,EAAE,GAAG,EACP,cAAc,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,EACvC,cAAc,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,EACvC,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,uBAAuB,EAInC;IAED,OAAO,IAAI,IAAI,CAEd;CACD;AAED,qBAAa,sBAAuB,SAAQ,eAAe;IAC1D,YAAY,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,uBAAuB,EASxE;CACD;AAED,qBAAa,oBAAqB,SAAQ,eAAe;IACxD,OAAO,CAAC,SAAS,CAA6B;IAE9C,YAAY,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAoBzE;IAEQ,OAAO,IAAI,IAAI,CAIvB;CACD;AAED,MAAM,MAAM,sBAAsB,GAAG,QAAQ,GAAG,WAAW,GAAG,UAAU,CAAC;AAEzE,qBAAa,yBAA0B,SAAQ,eAAe;IAC7D,YAAY,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,sBAAsB,EAalD;CACD;AAED,qBAAa,4BAA6B,SAAQ,eAAe;IAChE,YAAY,EAAE,EAAE,GAAG,EAQlB;CACD;AAED,qBAAa,UAAW,YAAW,SAAS;IAC3C,UAAU,IAAI,IAAI,CAEjB;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAG9B;CACD","sourcesContent":["import { type Component, Loader, type TUI } from \"@earendil-works/pi-tui\";\nimport type { WorkingIndicatorOptions } from \"../../../core/extensions/index.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { CountdownTimer } from \"./countdown-timer.ts\";\nimport { keyText } from \"./keybinding-hints.ts\";\n\nexport type StatusIndicatorKind = \"working\" | \"retry\" | \"compaction\" | \"branchSummary\";\n\nexport class StatusIndicator extends Loader {\n\treadonly kind: StatusIndicatorKind;\n\n\tconstructor(\n\t\tkind: StatusIndicatorKind,\n\t\tui: TUI,\n\t\tspinnerColorFn: (str: string) => string,\n\t\tmessageColorFn: (str: string) => string,\n\t\tmessage: string,\n\t\tindicator?: WorkingIndicatorOptions,\n\t) {\n\t\tsuper(ui, spinnerColorFn, messageColorFn, message, indicator);\n\t\tthis.kind = kind;\n\t}\n\n\tdispose(): void {\n\t\tthis.stop();\n\t}\n}\n\nexport class WorkingStatusIndicator extends StatusIndicator {\n\tconstructor(ui: TUI, message: string, indicator?: WorkingIndicatorOptions) {\n\t\tsuper(\n\t\t\t\"working\",\n\t\t\tui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tmessage,\n\t\t\tindicator,\n\t\t);\n\t}\n}\n\nexport class RetryStatusIndicator extends StatusIndicator {\n\tprivate countdown: CountdownTimer | undefined;\n\n\tconstructor(ui: TUI, attempt: number, maxAttempts: number, delayMs: number) {\n\t\tconst retryMessage = (seconds: number) =>\n\t\t\t`Retrying (${attempt}/${maxAttempts}) in ${seconds}s... (${keyText(\"app.interrupt\")} to cancel)`;\n\t\tsuper(\n\t\t\t\"retry\",\n\t\t\tui,\n\t\t\t(spinner) => theme.fg(\"warning\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tretryMessage(Math.ceil(delayMs / 1000)),\n\t\t);\n\t\tthis.countdown = new CountdownTimer(\n\t\t\tdelayMs,\n\t\t\tui,\n\t\t\t(seconds) => {\n\t\t\t\tthis.setMessage(retryMessage(seconds));\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tthis.countdown = undefined;\n\t\t\t},\n\t\t);\n\t}\n\n\toverride dispose(): void {\n\t\tthis.countdown?.dispose();\n\t\tthis.countdown = undefined;\n\t\tsuper.dispose();\n\t}\n}\n\nexport type CompactionStatusReason = \"manual\" | \"threshold\" | \"overflow\";\n\nexport class CompactionStatusIndicator extends StatusIndicator {\n\tconstructor(ui: TUI, reason: CompactionStatusReason) {\n\t\tconst cancelHint = `(${keyText(\"app.interrupt\")} to cancel)`;\n\t\tconst label =\n\t\t\treason === \"manual\"\n\t\t\t\t? `Compacting context... ${cancelHint}`\n\t\t\t\t: `${reason === \"overflow\" ? \"Context overflow detected, \" : \"\"}Auto-compacting... ${cancelHint}`;\n\t\tsuper(\n\t\t\t\"compaction\",\n\t\t\tui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tlabel,\n\t\t);\n\t}\n}\n\nexport class BranchSummaryStatusIndicator extends StatusIndicator {\n\tconstructor(ui: TUI) {\n\t\tsuper(\n\t\t\t\"branchSummary\",\n\t\t\tui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t`Summarizing branch... (${keyText(\"app.interrupt\")} to cancel)`,\n\t\t);\n\t}\n}\n\nexport class IdleStatus implements Component {\n\tinvalidate(): void {\n\t\t// No cached state to invalidate.\n\t}\n\n\trender(width: number): string[] {\n\t\tconst emptyLine = \" \".repeat(width);\n\t\treturn [emptyLine, emptyLine];\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/status-indicator.js b/dist/modes/interactive/components/status-indicator.js new file mode 100644 index 0000000..e7a7590 --- /dev/null +++ b/dist/modes/interactive/components/status-indicator.js @@ -0,0 +1,60 @@ +import { Loader } from "@earendil-works/pi-tui"; +import { theme } from "../theme/theme.js"; +import { CountdownTimer } from "./countdown-timer.js"; +import { keyText } from "./keybinding-hints.js"; +export class StatusIndicator extends Loader { + kind; + constructor(kind, ui, spinnerColorFn, messageColorFn, message, indicator) { + super(ui, spinnerColorFn, messageColorFn, message, indicator); + this.kind = kind; + } + dispose() { + this.stop(); + } +} +export class WorkingStatusIndicator extends StatusIndicator { + constructor(ui, message, indicator) { + super("working", ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), message, indicator); + } +} +export class RetryStatusIndicator extends StatusIndicator { + countdown; + constructor(ui, attempt, maxAttempts, delayMs) { + const retryMessage = (seconds) => `Retrying (${attempt}/${maxAttempts}) in ${seconds}s... (${keyText("app.interrupt")} to cancel)`; + super("retry", ui, (spinner) => theme.fg("warning", spinner), (text) => theme.fg("muted", text), retryMessage(Math.ceil(delayMs / 1000))); + this.countdown = new CountdownTimer(delayMs, ui, (seconds) => { + this.setMessage(retryMessage(seconds)); + }, () => { + this.countdown = undefined; + }); + } + dispose() { + this.countdown?.dispose(); + this.countdown = undefined; + super.dispose(); + } +} +export class CompactionStatusIndicator extends StatusIndicator { + constructor(ui, reason) { + const cancelHint = `(${keyText("app.interrupt")} to cancel)`; + const label = reason === "manual" + ? `Compacting context... ${cancelHint}` + : `${reason === "overflow" ? "Context overflow detected, " : ""}Auto-compacting... ${cancelHint}`; + super("compaction", ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), label); + } +} +export class BranchSummaryStatusIndicator extends StatusIndicator { + constructor(ui) { + super("branchSummary", ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), `Summarizing branch... (${keyText("app.interrupt")} to cancel)`); + } +} +export class IdleStatus { + invalidate() { + // No cached state to invalidate. + } + render(width) { + const emptyLine = " ".repeat(width); + return [emptyLine, emptyLine]; + } +} +//# sourceMappingURL=status-indicator.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/status-indicator.js.map b/dist/modes/interactive/components/status-indicator.js.map new file mode 100644 index 0000000..f3367df --- /dev/null +++ b/dist/modes/interactive/components/status-indicator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"status-indicator.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/status-indicator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,MAAM,EAAY,MAAM,wBAAwB,CAAC;AAE1E,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAIhD,MAAM,OAAO,eAAgB,SAAQ,MAAM;IACjC,IAAI,CAAsB;IAEnC,YACC,IAAyB,EACzB,EAAO,EACP,cAAuC,EACvC,cAAuC,EACvC,OAAe,EACf,SAAmC,EAClC;QACD,KAAK,CAAC,EAAE,EAAE,cAAc,EAAE,cAAc,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;QAC9D,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;IAED,OAAO,GAAS;QACf,IAAI,CAAC,IAAI,EAAE,CAAC;IAAA,CACZ;CACD;AAED,MAAM,OAAO,sBAAuB,SAAQ,eAAe;IAC1D,YAAY,EAAO,EAAE,OAAe,EAAE,SAAmC,EAAE;QAC1E,KAAK,CACJ,SAAS,EACT,EAAE,EACF,CAAC,OAAO,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,EACxC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,EACjC,OAAO,EACP,SAAS,CAC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ACvC,CAAC,CAAC,GAAG,MAAM,KAAK,UAAU,CAAC,CAAC,CAAC,6BAA6B,CAAC,CAAC,CAAC,EAAE,sBAAsB,UAAU,EAAE,CAAC;QACpG,KAAK,CACJ,YAAY,EACZ,EAAE,EACF,CAAC,OAAO,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,EACxC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,EACjC,KAAK,CACL,CAAC;IAAA,CACF;CACD;AAED,MAAM,OAAO,4BAA6B,SAAQ,eAAe;IAChE,YAAY,EAAO,EAAE;QACpB,KAAK,CACJ,eAAe,EACf,EAAE,EACF,CAAC,OAAO,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,EACxC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,EACjC,0BAA0B,OAAO,CAAC,eAAe,CAAC,aAAa,CAC/D,CAAC;IAAA,CACF;CACD;AAED,MAAM,OAAO,UAAU;IACtB,UAAU,GAAS;QAClB,iCAAiC;IADd,CAEnB;IAED,MAAM,CAAC,KAAa,EAAY;QAC/B,MAAM,SAAS,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACpC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;IAAA,CAC9B;CACD","sourcesContent":["import { type Component, Loader, type TUI } from \"@earendil-works/pi-tui\";\nimport type { WorkingIndicatorOptions } from \"../../../core/extensions/index.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { CountdownTimer } from \"./countdown-timer.ts\";\nimport { keyText } from \"./keybinding-hints.ts\";\n\nexport type StatusIndicatorKind = \"working\" | \"retry\" | \"compaction\" | \"branchSummary\";\n\nexport class StatusIndicator extends Loader {\n\treadonly kind: StatusIndicatorKind;\n\n\tconstructor(\n\t\tkind: StatusIndicatorKind,\n\t\tui: TUI,\n\t\tspinnerColorFn: (str: string) => string,\n\t\tmessageColorFn: (str: string) => string,\n\t\tmessage: string,\n\t\tindicator?: WorkingIndicatorOptions,\n\t) {\n\t\tsuper(ui, spinnerColorFn, messageColorFn, message, indicator);\n\t\tthis.kind = kind;\n\t}\n\n\tdispose(): void {\n\t\tthis.stop();\n\t}\n}\n\nexport class WorkingStatusIndicator extends StatusIndicator {\n\tconstructor(ui: TUI, message: string, indicator?: WorkingIndicatorOptions) {\n\t\tsuper(\n\t\t\t\"working\",\n\t\t\tui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tmessage,\n\t\t\tindicator,\n\t\t);\n\t}\n}\n\nexport class RetryStatusIndicator extends StatusIndicator {\n\tprivate countdown: CountdownTimer | undefined;\n\n\tconstructor(ui: TUI, attempt: number, maxAttempts: number, delayMs: number) {\n\t\tconst retryMessage = (seconds: number) =>\n\t\t\t`Retrying (${attempt}/${maxAttempts}) in ${seconds}s... (${keyText(\"app.interrupt\")} to cancel)`;\n\t\tsuper(\n\t\t\t\"retry\",\n\t\t\tui,\n\t\t\t(spinner) => theme.fg(\"warning\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tretryMessage(Math.ceil(delayMs / 1000)),\n\t\t);\n\t\tthis.countdown = new CountdownTimer(\n\t\t\tdelayMs,\n\t\t\tui,\n\t\t\t(seconds) => {\n\t\t\t\tthis.setMessage(retryMessage(seconds));\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tthis.countdown = undefined;\n\t\t\t},\n\t\t);\n\t}\n\n\toverride dispose(): void {\n\t\tthis.countdown?.dispose();\n\t\tthis.countdown = undefined;\n\t\tsuper.dispose();\n\t}\n}\n\nexport type CompactionStatusReason = \"manual\" | \"threshold\" | \"overflow\";\n\nexport class CompactionStatusIndicator extends StatusIndicator {\n\tconstructor(ui: TUI, reason: CompactionStatusReason) {\n\t\tconst cancelHint = `(${keyText(\"app.interrupt\")} to cancel)`;\n\t\tconst label =\n\t\t\treason === \"manual\"\n\t\t\t\t? `Compacting context... ${cancelHint}`\n\t\t\t\t: `${reason === \"overflow\" ? \"Context overflow detected, \" : \"\"}Auto-compacting... ${cancelHint}`;\n\t\tsuper(\n\t\t\t\"compaction\",\n\t\t\tui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tlabel,\n\t\t);\n\t}\n}\n\nexport class BranchSummaryStatusIndicator extends StatusIndicator {\n\tconstructor(ui: TUI) {\n\t\tsuper(\n\t\t\t\"branchSummary\",\n\t\t\tui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t`Summarizing branch... (${keyText(\"app.interrupt\")} to cancel)`,\n\t\t);\n\t}\n}\n\nexport class IdleStatus implements Component {\n\tinvalidate(): void {\n\t\t// No cached state to invalidate.\n\t}\n\n\trender(width: number): string[] {\n\t\tconst emptyLine = \" \".repeat(width);\n\t\treturn [emptyLine, emptyLine];\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/theme-selector.d.ts b/dist/modes/interactive/components/theme-selector.d.ts new file mode 100644 index 0000000..af2d3bc --- /dev/null +++ b/dist/modes/interactive/components/theme-selector.d.ts @@ -0,0 +1,11 @@ +import { Container, SelectList } from "@earendil-works/pi-tui"; +/** + * Component that renders a theme selector + */ +export declare class ThemeSelectorComponent extends Container { + private selectList; + private onPreview; + constructor(currentTheme: string, onSelect: (themeName: string) => void, onCancel: () => void, onPreview: (themeName: string) => void); + getSelectList(): SelectList; +} +//# sourceMappingURL=theme-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/theme-selector.d.ts.map b/dist/modes/interactive/components/theme-selector.d.ts.map new file mode 100644 index 0000000..6f9f341 --- /dev/null +++ b/dist/modes/interactive/components/theme-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"theme-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/theme-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAmB,UAAU,EAAgC,MAAM,wBAAwB,CAAC;AAS9G;;GAEG;AACH,qBAAa,sBAAuB,SAAQ,SAAS;IACpD,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,SAAS,CAA8B;IAE/C,YACC,YAAY,EAAE,MAAM,EACpB,QAAQ,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,EACrC,QAAQ,EAAE,MAAM,IAAI,EACpB,SAAS,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,EAyCtC;IAED,aAAa,IAAI,UAAU,CAE1B;CACD","sourcesContent":["import { Container, type SelectItem, SelectList, type SelectListLayoutOptions } from \"@earendil-works/pi-tui\";\nimport { getAvailableThemes, getSelectListTheme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\n\nconst THEME_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {\n\tminPrimaryColumnWidth: 12,\n\tmaxPrimaryColumnWidth: 32,\n};\n\n/**\n * Component that renders a theme selector\n */\nexport class ThemeSelectorComponent extends Container {\n\tprivate selectList: SelectList;\n\tprivate onPreview: (themeName: string) => void;\n\n\tconstructor(\n\t\tcurrentTheme: string,\n\t\tonSelect: (themeName: string) => void,\n\t\tonCancel: () => void,\n\t\tonPreview: (themeName: string) => void,\n\t) {\n\t\tsuper();\n\t\tthis.onPreview = onPreview;\n\n\t\t// Get available themes and create select items\n\t\tconst themes = getAvailableThemes();\n\t\tconst themeItems: SelectItem[] = themes.map((name) => ({\n\t\t\tvalue: name,\n\t\t\tlabel: name,\n\t\t\tdescription: name === currentTheme ? \"(current)\" : undefined,\n\t\t}));\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Create selector\n\t\tthis.selectList = new SelectList(themeItems, 10, getSelectListTheme(), THEME_SELECT_LIST_LAYOUT);\n\n\t\t// Preselect current theme\n\t\tconst currentIndex = themes.indexOf(currentTheme);\n\t\tif (currentIndex !== -1) {\n\t\t\tthis.selectList.setSelectedIndex(currentIndex);\n\t\t}\n\n\t\tthis.selectList.onSelect = (item) => {\n\t\t\tonSelect(item.value);\n\t\t};\n\n\t\tthis.selectList.onCancel = () => {\n\t\t\tonCancel();\n\t\t};\n\n\t\tthis.selectList.onSelectionChange = (item) => {\n\t\t\tthis.onPreview(item.value);\n\t\t};\n\n\t\tthis.addChild(this.selectList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tgetSelectList(): SelectList {\n\t\treturn this.selectList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/theme-selector.js b/dist/modes/interactive/components/theme-selector.js new file mode 100644 index 0000000..c23156a --- /dev/null +++ b/dist/modes/interactive/components/theme-selector.js @@ -0,0 +1,50 @@ +import { Container, SelectList } from "@earendil-works/pi-tui"; +import { getAvailableThemes, getSelectListTheme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +const THEME_SELECT_LIST_LAYOUT = { + minPrimaryColumnWidth: 12, + maxPrimaryColumnWidth: 32, +}; +/** + * Component that renders a theme selector + */ +export class ThemeSelectorComponent extends Container { + selectList; + onPreview; + constructor(currentTheme, onSelect, onCancel, onPreview) { + super(); + this.onPreview = onPreview; + // Get available themes and create select items + const themes = getAvailableThemes(); + const themeItems = themes.map((name) => ({ + value: name, + label: name, + description: name === currentTheme ? "(current)" : undefined, + })); + // Add top border + this.addChild(new DynamicBorder()); + // Create selector + this.selectList = new SelectList(themeItems, 10, getSelectListTheme(), THEME_SELECT_LIST_LAYOUT); + // Preselect current theme + const currentIndex = themes.indexOf(currentTheme); + if (currentIndex !== -1) { + this.selectList.setSelectedIndex(currentIndex); + } + this.selectList.onSelect = (item) => { + onSelect(item.value); + }; + this.selectList.onCancel = () => { + onCancel(); + }; + this.selectList.onSelectionChange = (item) => { + this.onPreview(item.value); + }; + this.addChild(this.selectList); + // Add bottom border + this.addChild(new DynamicBorder()); + } + getSelectList() { + return this.selectList; + } +} +//# sourceMappingURL=theme-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/theme-selector.js.map b/dist/modes/interactive/components/theme-selector.js.map new file mode 100644 index 0000000..9f7cba8 --- /dev/null +++ b/dist/modes/interactive/components/theme-selector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"theme-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/theme-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAmB,UAAU,EAAgC,MAAM,wBAAwB,CAAC;AAC9G,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,MAAM,wBAAwB,GAA4B;IACzD,qBAAqB,EAAE,EAAE;IACzB,qBAAqB,EAAE,EAAE;CACzB,CAAC;AAEF;;GAEG;AACH,MAAM,OAAO,sBAAuB,SAAQ,SAAS;IAC5C,UAAU,CAAa;IACvB,SAAS,CAA8B;IAE/C,YACC,YAAoB,EACpB,QAAqC,EACrC,QAAoB,EACpB,SAAsC,EACrC;QACD,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAE3B,+CAA+C;QAC/C,MAAM,MAAM,GAAG,kBAAkB,EAAE,CAAC;QACpC,MAAM,UAAU,GAAiB,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;YACtD,KAAK,EAAE,IAAI;YACX,KAAK,EAAE,IAAI;YACX,WAAW,EAAE,IAAI,KAAK,YAAY,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS;SAC5D,CAAC,CAAC,CAAC;QAEJ,iBAAiB;QACjB,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;QAEnC,kBAAkB;QAClB,IAAI,CAAC,UAAU,GAAG,IAAI,UAAU,CAAC,UAAU,EAAE,EAAE,EAAE,kBAAkB,EAAE,EAAE,wBAAwB,CAAC,CAAC;QAEjG,0BAA0B;QAC1B,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAClD,IAAI,YAAY,KAAK,CAAC,CAAC,EAAE,CAAC;YACzB,IAAI,CAAC,UAAU,CAAC,gBAAgB,CAAC,YAAY,CAAC,CAAC;QAChD,CAAC;QAED,IAAI,CAAC,UAAU,CAAC,QAAQ,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC;YACpC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAAA,CACrB,CAAC;QAEF,IAAI,CAAC,UAAU,CAAC,QAAQ,GAAG,GAAG,EAAE,CAAC;YAChC,QAAQ,EAAE,CAAC;QAAA,CACX,CAAC;QAEF,IAAI,CAAC,UAAU,CAAC,iBAAiB,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC;YAC7C,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAAA,CAC3B,CAAC;QAEF,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAE/B,oBAAoB;QACpB,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;IAAA,CACnC;IAED,aAAa,GAAe;QAC3B,OAAO,IAAI,CAAC,UAAU,CAAC;IAAA,CACvB;CACD","sourcesContent":["import { Container, type SelectItem, SelectList, type SelectListLayoutOptions } from \"@earendil-works/pi-tui\";\nimport { getAvailableThemes, getSelectListTheme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\n\nconst THEME_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {\n\tminPrimaryColumnWidth: 12,\n\tmaxPrimaryColumnWidth: 32,\n};\n\n/**\n * Component that renders a theme selector\n */\nexport class ThemeSelectorComponent extends Container {\n\tprivate selectList: SelectList;\n\tprivate onPreview: (themeName: string) => void;\n\n\tconstructor(\n\t\tcurrentTheme: string,\n\t\tonSelect: (themeName: string) => void,\n\t\tonCancel: () => void,\n\t\tonPreview: (themeName: string) => void,\n\t) {\n\t\tsuper();\n\t\tthis.onPreview = onPreview;\n\n\t\t// Get available themes and create select items\n\t\tconst themes = getAvailableThemes();\n\t\tconst themeItems: SelectItem[] = themes.map((name) => ({\n\t\t\tvalue: name,\n\t\t\tlabel: name,\n\t\t\tdescription: name === currentTheme ? \"(current)\" : undefined,\n\t\t}));\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Create selector\n\t\tthis.selectList = new SelectList(themeItems, 10, getSelectListTheme(), THEME_SELECT_LIST_LAYOUT);\n\n\t\t// Preselect current theme\n\t\tconst currentIndex = themes.indexOf(currentTheme);\n\t\tif (currentIndex !== -1) {\n\t\t\tthis.selectList.setSelectedIndex(currentIndex);\n\t\t}\n\n\t\tthis.selectList.onSelect = (item) => {\n\t\t\tonSelect(item.value);\n\t\t};\n\n\t\tthis.selectList.onCancel = () => {\n\t\t\tonCancel();\n\t\t};\n\n\t\tthis.selectList.onSelectionChange = (item) => {\n\t\t\tthis.onPreview(item.value);\n\t\t};\n\n\t\tthis.addChild(this.selectList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tgetSelectList(): SelectList {\n\t\treturn this.selectList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/thinking-selector.d.ts b/dist/modes/interactive/components/thinking-selector.d.ts new file mode 100644 index 0000000..f56b2b0 --- /dev/null +++ b/dist/modes/interactive/components/thinking-selector.d.ts @@ -0,0 +1,11 @@ +import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; +import { Container, SelectList } from "@earendil-works/pi-tui"; +/** + * Component that renders a thinking level selector with borders + */ +export declare class ThinkingSelectorComponent extends Container { + private selectList; + constructor(currentLevel: ThinkingLevel, availableLevels: ThinkingLevel[], onSelect: (level: ThinkingLevel) => void, onCancel: () => void); + getSelectList(): SelectList; +} +//# sourceMappingURL=thinking-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/thinking-selector.d.ts.map b/dist/modes/interactive/components/thinking-selector.d.ts.map new file mode 100644 index 0000000..ca797eb --- /dev/null +++ b/dist/modes/interactive/components/thinking-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"thinking-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/thinking-selector.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,SAAS,EAAmB,UAAU,EAAgC,MAAM,wBAAwB,CAAC;AAmB9G;;GAEG;AACH,qBAAa,yBAA0B,SAAQ,SAAS;IACvD,OAAO,CAAC,UAAU,CAAa;IAE/B,YACC,YAAY,EAAE,aAAa,EAC3B,eAAe,EAAE,aAAa,EAAE,EAChC,QAAQ,EAAE,CAAC,KAAK,EAAE,aAAa,KAAK,IAAI,EACxC,QAAQ,EAAE,MAAM,IAAI,EAuCpB;IAED,aAAa,IAAI,UAAU,CAE1B;CACD","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { Container, type SelectItem, SelectList, type SelectListLayoutOptions } from \"@earendil-works/pi-tui\";\nimport { getSelectListTheme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\n\nconst THINKING_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {\n\tminPrimaryColumnWidth: 12,\n\tmaxPrimaryColumnWidth: 32,\n};\n\nconst LEVEL_DESCRIPTIONS: Record = {\n\toff: \"No reasoning\",\n\tminimal: \"Very brief reasoning (~1k tokens)\",\n\tlow: \"Light reasoning (~2k tokens)\",\n\tmedium: \"Moderate reasoning (~8k tokens)\",\n\thigh: \"Deep reasoning (~16k tokens)\",\n\txhigh: \"Extra-high reasoning (~32k tokens)\",\n\tmax: \"Maximum reasoning\",\n};\n\n/**\n * Component that renders a thinking level selector with borders\n */\nexport class ThinkingSelectorComponent extends Container {\n\tprivate selectList: SelectList;\n\n\tconstructor(\n\t\tcurrentLevel: ThinkingLevel,\n\t\tavailableLevels: ThinkingLevel[],\n\t\tonSelect: (level: ThinkingLevel) => void,\n\t\tonCancel: () => void,\n\t) {\n\t\tsuper();\n\n\t\tconst thinkingLevels: SelectItem[] = availableLevels.map((level) => ({\n\t\t\tvalue: level,\n\t\t\tlabel: level,\n\t\t\tdescription: LEVEL_DESCRIPTIONS[level],\n\t\t}));\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Create selector\n\t\tthis.selectList = new SelectList(\n\t\t\tthinkingLevels,\n\t\t\tthinkingLevels.length,\n\t\t\tgetSelectListTheme(),\n\t\t\tTHINKING_SELECT_LIST_LAYOUT,\n\t\t);\n\n\t\t// Preselect current level\n\t\tconst currentIndex = thinkingLevels.findIndex((item) => item.value === currentLevel);\n\t\tif (currentIndex !== -1) {\n\t\t\tthis.selectList.setSelectedIndex(currentIndex);\n\t\t}\n\n\t\tthis.selectList.onSelect = (item) => {\n\t\t\tonSelect(item.value as ThinkingLevel);\n\t\t};\n\n\t\tthis.selectList.onCancel = () => {\n\t\t\tonCancel();\n\t\t};\n\n\t\tthis.addChild(this.selectList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tgetSelectList(): SelectList {\n\t\treturn this.selectList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/thinking-selector.js b/dist/modes/interactive/components/thinking-selector.js new file mode 100644 index 0000000..55c03c8 --- /dev/null +++ b/dist/modes/interactive/components/thinking-selector.js @@ -0,0 +1,52 @@ +import { Container, SelectList } from "@earendil-works/pi-tui"; +import { getSelectListTheme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +const THINKING_SELECT_LIST_LAYOUT = { + minPrimaryColumnWidth: 12, + maxPrimaryColumnWidth: 32, +}; +const LEVEL_DESCRIPTIONS = { + off: "No reasoning", + minimal: "Very brief reasoning (~1k tokens)", + low: "Light reasoning (~2k tokens)", + medium: "Moderate reasoning (~8k tokens)", + high: "Deep reasoning (~16k tokens)", + xhigh: "Extra-high reasoning (~32k tokens)", + max: "Maximum reasoning", +}; +/** + * Component that renders a thinking level selector with borders + */ +export class ThinkingSelectorComponent extends Container { + selectList; + constructor(currentLevel, availableLevels, onSelect, onCancel) { + super(); + const thinkingLevels = availableLevels.map((level) => ({ + value: level, + label: level, + description: LEVEL_DESCRIPTIONS[level], + })); + // Add top border + this.addChild(new DynamicBorder()); + // Create selector + this.selectList = new SelectList(thinkingLevels, thinkingLevels.length, getSelectListTheme(), THINKING_SELECT_LIST_LAYOUT); + // Preselect current level + const currentIndex = thinkingLevels.findIndex((item) => item.value === currentLevel); + if (currentIndex !== -1) { + this.selectList.setSelectedIndex(currentIndex); + } + this.selectList.onSelect = (item) => { + onSelect(item.value); + }; + this.selectList.onCancel = () => { + onCancel(); + }; + this.addChild(this.selectList); + // Add bottom border + this.addChild(new DynamicBorder()); + } + getSelectList() { + return this.selectList; + } +} +//# sourceMappingURL=thinking-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/thinking-selector.js.map b/dist/modes/interactive/components/thinking-selector.js.map new file mode 100644 index 0000000..9f18004 --- /dev/null +++ b/dist/modes/interactive/components/thinking-selector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"thinking-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/thinking-selector.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAmB,UAAU,EAAgC,MAAM,wBAAwB,CAAC;AAC9G,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,MAAM,2BAA2B,GAA4B;IAC5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sB,CAAC,CAAC;QAAA,CACtC,CAAC;QAEF,IAAI,CAAC,UAAU,CAAC,QAAQ,GAAG,GAAG,EAAE,CAAC;YAChC,QAAQ,EAAE,CAAC;QAAA,CACX,CAAC;QAEF,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAE/B,oBAAoB;QACpB,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;IAAA,CACnC;IAED,aAAa,GAAe;QAC3B,OAAO,IAAI,CAAC,UAAU,CAAC;IAAA,CACvB;CACD","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { Container, type SelectItem, SelectList, type SelectListLayoutOptions } from \"@earendil-works/pi-tui\";\nimport { getSelectListTheme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\n\nconst THINKING_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {\n\tminPrimaryColumnWidth: 12,\n\tmaxPrimaryColumnWidth: 32,\n};\n\nconst LEVEL_DESCRIPTIONS: Record = {\n\toff: \"No reasoning\",\n\tminimal: \"Very brief reasoning (~1k tokens)\",\n\tlow: \"Light reasoning (~2k tokens)\",\n\tmedium: \"Moderate reasoning (~8k tokens)\",\n\thigh: \"Deep reasoning (~16k tokens)\",\n\txhigh: \"Extra-high reasoning (~32k tokens)\",\n\tmax: \"Maximum reasoning\",\n};\n\n/**\n * Component that renders a thinking level selector with borders\n */\nexport class ThinkingSelectorComponent extends Container {\n\tprivate selectList: SelectList;\n\n\tconstructor(\n\t\tcurrentLevel: ThinkingLevel,\n\t\tavailableLevels: ThinkingLevel[],\n\t\tonSelect: (level: ThinkingLevel) => void,\n\t\tonCancel: () => void,\n\t) {\n\t\tsuper();\n\n\t\tconst thinkingLevels: SelectItem[] = availableLevels.map((level) => ({\n\t\t\tvalue: level,\n\t\t\tlabel: level,\n\t\t\tdescription: LEVEL_DESCRIPTIONS[level],\n\t\t}));\n\n\t\t// Add top border\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Create selector\n\t\tthis.selectList = new SelectList(\n\t\t\tthinkingLevels,\n\t\t\tthinkingLevels.length,\n\t\t\tgetSelectListTheme(),\n\t\t\tTHINKING_SELECT_LIST_LAYOUT,\n\t\t);\n\n\t\t// Preselect current level\n\t\tconst currentIndex = thinkingLevels.findIndex((item) => item.value === currentLevel);\n\t\tif (currentIndex !== -1) {\n\t\t\tthis.selectList.setSelectedIndex(currentIndex);\n\t\t}\n\n\t\tthis.selectList.onSelect = (item) => {\n\t\t\tonSelect(item.value as ThinkingLevel);\n\t\t};\n\n\t\tthis.selectList.onCancel = () => {\n\t\t\tonCancel();\n\t\t};\n\n\t\tthis.addChild(this.selectList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new DynamicBorder());\n\t}\n\n\tgetSelectList(): SelectList {\n\t\treturn this.selectList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/tool-execution.d.ts b/dist/modes/interactive/components/tool-execution.d.ts new file mode 100644 index 0000000..4a22d5c --- /dev/null +++ b/dist/modes/interactive/components/tool-execution.d.ts @@ -0,0 +1,63 @@ +import { Container, type TUI } from "@earendil-works/pi-tui"; +import type { ToolDefinition } from "../../../core/extensions/types.ts"; +export interface ToolExecutionOptions { + showImages?: boolean; + imageWidthCells?: number; +} +export declare class ToolExecutionComponent extends Container { + private contentBox; + private contentText; + private selfRenderContainer; + private callRendererComponent?; + private resultRendererComponent?; + private rendererState; + private imageComponents; + private imageSpacers; + private toolName; + private toolCallId; + private args; + private expanded; + private showImages; + private imageWidthCells; + private isPartial; + private toolDefinition?; + private builtInToolDefinition?; + private ui; + private cwd; + private executionStarted; + private argsComplete; + private result?; + private convertedImages; + private hideComponent; + constructor(toolName: string, toolCallId: string, args: any, options: ToolExecutionOptions | undefined, toolDefinition: ToolDefinition | undefined, ui: TUI, cwd: string); + private getCallRenderer; + private getResultRenderer; + private hasRendererDefinition; + private getRenderShell; + private getRenderContext; + private createCallFallback; + private createResultFallback; + updateArgs(args: any): void; + markExecutionStarted(): void; + setArgsComplete(): void; + updateResult(result: { + content: Array<{ + type: string; + text?: string; + data?: string; + mimeType?: string; + }>; + details?: any; + isError: boolean; + }, isPartial?: boolean): void; + private maybeConvertImagesForKitty; + setExpanded(expanded: boolean): void; + setShowImages(show: boolean): void; + setImageWidthCells(width: number): void; + invalidate(): void; + render(width: number): string[]; + private updateDisplay; + private getTextOutput; + private formatToolExecution; +} +//# sourceMappingURL=tool-execution.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/tool-execution.d.ts.map b/dist/modes/interactive/components/tool-execution.d.ts.map new file mode 100644 index 0000000..5b471c2 --- /dev/null +++ b/dist/modes/interactive/components/tool-execution.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tool-execution.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/tool-execution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,SAAS,EAAwC,KAAK,GAAG,EAAE,MAAM,wBAAwB,CAAC;AACxH,OAAO,KAAK,EAAE,cAAc,EAAqB,MAAM,mCAAmC,CAAC;AAM3F,MAAM,WAAW,oBAAoB;IACpC,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,eAAe,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,qBAAa,sBAAuB,SAAQ,SAAS;IACpD,OAAO,CAAC,UAAU,CAAM;IACxB,OAAO,CAAC,WAAW,CAAO;IAC1B,OAAO,CAAC,mBAAmB,CAAY;IACvC,OAAO,CAAC,qBAAqB,CAAC,CAAY;IAC1C,OAAO,CAAC,uBAAuB,CAAC,CAAY;IAC5C,OAAO,CAAC,aAAa,CAAW;IAChC,OAAO,CAAC,eAAe,CAAe;IACtC,OAAO,CAAC,YAAY,CAAgB;IACpC,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,IAAI,CAAM;IAClB,OAAO,CAAC,QAAQ,CAAS;IAC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;IAED,OAAO,CAAC,0BAA0B;IAuBlC,WAAW,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI,CAGnC;IAED,aAAa,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAGjC;IAED,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAGtC;IAEQ,UAAU,IAAI,IAAI,CAG1B;IAEQ,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CA8BvC;IAED,OAAO,CAAC,aAAa;IA4GrB,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,mBAAmB;CAY3B","sourcesContent":["import { Box, type Component, Container, getCapabilities, Image, Spacer, Text, type TUI } from \"@earendil-works/pi-tui\";\nimport type { ToolDefinition, ToolRenderContext } from \"../../../core/extensions/types.ts\";\nimport { createAllToolDefinitions, type ToolName } from \"../../../core/tools/index.ts\";\nimport { getTextOutput as getRenderedTextOutput } from \"../../../core/tools/render-utils.ts\";\nimport { convertToPng } from \"../../../utils/image-convert.ts\";\nimport { theme } from \"../theme/theme.ts\";\n\nexport interface ToolExecutionOptions {\n\tshowImages?: boolean;\n\timageWidthCells?: number;\n}\n\nexport class ToolExecutionComponent extends Container {\n\tprivate contentBox: Box;\n\tprivate contentText: Text;\n\tprivate selfRenderContainer: Container;\n\tprivate callRendererComponent?: Component;\n\tprivate resultRendererComponent?: Component;\n\tprivate rendererState: any = {};\n\tprivate imageComponents: Image[] = [];\n\tprivate imageSpacers: Spacer[] = [];\n\tprivate toolName: string;\n\tprivate toolCallId: string;\n\tprivate args: any;\n\tprivate expanded = false;\n\tprivate showImages: boolean;\n\tprivate imageWidthCells: number;\n\tprivate isPartial = true;\n\tprivate toolDefinition?: ToolDefinition;\n\tprivate builtInToolDefinition?: ToolDefinition;\n\tprivate ui: TUI;\n\tprivate cwd: string;\n\tprivate executionStarted = false;\n\tprivate argsComplete = false;\n\tprivate result?: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tisError: boolean;\n\t\tdetails?: any;\n\t};\n\tprivate convertedImages: Map = new Map();\n\tprivate hideComponent = false;\n\n\tconstructor(\n\t\ttoolName: string,\n\t\ttoolCallId: string,\n\t\targs: any,\n\t\toptions: ToolExecutionOptions = {},\n\t\ttoolDefinition: ToolDefinition | undefined,\n\t\tui: TUI,\n\t\tcwd: string,\n\t) {\n\t\tsuper();\n\t\tthis.toolName = toolName;\n\t\tthis.toolCallId = toolCallId;\n\t\tthis.args = args;\n\t\tthis.toolDefinition = toolDefinition;\n\t\tthis.builtInToolDefinition = createAllToolDefinitions(cwd)[toolName as ToolName];\n\t\tthis.showImages = options.showImages ?? true;\n\t\tthis.imageWidthCells = options.imageWidthCells ?? 60;\n\t\tthis.ui = ui;\n\t\tthis.cwd = cwd;\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Always create all shell variants. contentBox is used for default renderer-based composition.\n\t\t// selfRenderContainer is used when the tool renders its own framing.\n\t\t// contentText is reserved for generic fallback rendering when no tool definition exists.\n\t\tthis.contentBox = new Box(1, 1, (text: string) => theme.bg(\"toolPendingBg\", text));\n\t\tthis.contentText = new Text(\"\", 1, 1, (text: string) => theme.bg(\"toolPendingBg\", text));\n\t\tthis.selfRenderContainer = new Container();\n\n\t\tif (this.hasRendererDefinition()) {\n\t\t\tthis.addChild(this.getRenderShell() === \"self\" ? this.selfRenderContainer : this.contentBox);\n\t\t} else {\n\t\t\tthis.addChild(this.contentText);\n\t\t}\n\n\t\tthis.updateDisplay();\n\t}\n\n\tprivate getCallRenderer(): ToolDefinition[\"renderCall\"] | undefined {\n\t\tif (!this.builtInToolDefinition) {\n\t\t\treturn this.toolDefinition?.renderCall;\n\t\t}\n\t\tif (!this.toolDefinition) {\n\t\t\treturn this.builtInToolDefinition.renderCall;\n\t\t}\n\t\treturn this.toolDefinition.renderCall ?? this.builtInToolDefinition.renderCall;\n\t}\n\n\tprivate getResultRenderer(): ToolDefinition[\"renderResult\"] | undefined {\n\t\tif (!this.builtInToolDefinition) {\n\t\t\treturn this.toolDefinition?.renderResult;\n\t\t}\n\t\tif (!this.toolDefinition) {\n\t\t\treturn this.builtInToolDefinition.renderResult;\n\t\t}\n\t\treturn this.toolDefinition.renderResult ?? this.builtInToolDefinition.renderResult;\n\t}\n\n\tprivate hasRendererDefinition(): boolean {\n\t\treturn this.builtInToolDefinition !== undefined || this.toolDefinition !== undefined;\n\t}\n\n\tprivate getRenderShell(): \"default\" | \"self\" {\n\t\tif (!this.builtInToolDefinition) {\n\t\t\treturn this.toolDefinition?.renderShell ?? \"default\";\n\t\t}\n\t\tif (!this.toolDefinition) {\n\t\t\treturn this.builtInToolDefinition.renderShell ?? \"default\";\n\t\t}\n\t\treturn this.toolDefinition.renderShell ?? this.builtInToolDefinition.renderShell ?? \"default\";\n\t}\n\n\tprivate getRenderContext(lastComponent: Component | undefined): ToolRenderContext {\n\t\treturn {\n\t\t\targs: this.args,\n\t\t\ttoolCallId: this.toolCallId,\n\t\t\tinvalidate: () => {\n\t\t\t\tthis.invalidate();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t\tlastComponent,\n\t\t\tstate: this.rendererState,\n\t\t\tcwd: this.cwd,\n\t\t\texecutionStarted: this.executionStarted,\n\t\t\targsComplete: this.argsComplete,\n\t\t\tisPartial: this.isPartial,\n\t\t\texpanded: this.expanded,\n\t\t\tshowImages: this.showImages,\n\t\t\tisError: this.result?.isError ?? false,\n\t\t};\n\t}\n\n\tprivate createCallFallback(): Component {\n\t\treturn new Text(theme.fg(\"toolTitle\", theme.bold(this.toolName)), 0, 0);\n\t}\n\n\tprivate createResultFallback(): Component | undefined {\n\t\tconst output = this.getTextOutput();\n\t\tif (!output) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn new Text(theme.fg(\"toolOutput\", output), 0, 0);\n\t}\n\n\tupdateArgs(args: any): void {\n\t\tthis.args = args;\n\t\tthis.updateDisplay();\n\t}\n\n\tmarkExecutionStarted(): void {\n\t\tthis.executionStarted = true;\n\t\tthis.updateDisplay();\n\t\tthis.ui.requestRender();\n\t}\n\n\tsetArgsComplete(): void {\n\t\tthis.argsComplete = true;\n\t\tthis.updateDisplay();\n\t\tthis.ui.requestRender();\n\t}\n\n\tupdateResult(\n\t\tresult: {\n\t\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\t\tdetails?: any;\n\t\t\tisError: boolean;\n\t\t},\n\t\tisPartial = false,\n\t): void {\n\t\tthis.result = result;\n\t\tthis.isPartial = isPartial;\n\t\tthis.updateDisplay();\n\t\tthis.maybeConvertImagesForKitty();\n\t}\n\n\tprivate maybeConvertImagesForKitty(): void {\n\t\tconst caps = getCapabilities();\n\t\tif (caps.images !== \"kitty\") return;\n\t\tif (!this.result) return;\n\n\t\tconst imageBlocks = this.result.content.filter((c) => c.type === \"image\");\n\t\tfor (let i = 0; i < imageBlocks.length; i++) {\n\t\t\tconst img = imageBlocks[i];\n\t\t\tif (!img.data || !img.mimeType) continue;\n\t\t\tif (img.mimeType === \"image/png\") continue;\n\t\t\tif (this.convertedImages.has(i)) continue;\n\n\t\t\tconst index = i;\n\t\t\tconvertToPng(img.data, img.mimeType).then((converted) => {\n\t\t\t\tif (converted) {\n\t\t\t\t\tthis.convertedImages.set(index, converted);\n\t\t\t\t\tthis.updateDisplay();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.expanded = expanded;\n\t\tthis.updateDisplay();\n\t}\n\n\tsetShowImages(show: boolean): void {\n\t\tthis.showImages = show;\n\t\tthis.updateDisplay();\n\t}\n\n\tsetImageWidthCells(width: number): void {\n\t\tthis.imageWidthCells = Math.max(1, Math.floor(width));\n\t\tthis.updateDisplay();\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.updateDisplay();\n\t}\n\n\toverride render(width: number): string[] {\n\t\tif (this.hideComponent) {\n\t\t\treturn [];\n\t\t}\n\n\t\tif (this.hasRendererDefinition() && this.getRenderShell() === \"self\") {\n\t\t\tconst contentLines = this.selfRenderContainer.render(width);\n\t\t\tif (contentLines.length === 0 && this.imageComponents.length === 0) {\n\t\t\t\treturn [];\n\t\t\t}\n\n\t\t\tconst lines: string[] = [];\n\t\t\tif (contentLines.length > 0) {\n\t\t\t\tlines.push(\"\");\n\t\t\t\tlines.push(...contentLines);\n\t\t\t}\n\t\t\tfor (let i = 0; i < this.imageComponents.length; i++) {\n\t\t\t\tconst spacer = this.imageSpacers[i];\n\t\t\t\tif (spacer) {\n\t\t\t\t\tlines.push(...spacer.render(width));\n\t\t\t\t}\n\t\t\t\tconst imageComponent = this.imageComponents[i];\n\t\t\t\tif (imageComponent) {\n\t\t\t\t\tlines.push(...imageComponent.render(width));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn lines;\n\t\t}\n\n\t\treturn super.render(width);\n\t}\n\n\tprivate updateDisplay(): void {\n\t\tconst bgFn = this.isPartial\n\t\t\t? (text: string) => theme.bg(\"toolPendingBg\", text)\n\t\t\t: this.result?.isError\n\t\t\t\t? (text: string) => theme.bg(\"toolErrorBg\", text)\n\t\t\t\t: (text: string) => theme.bg(\"toolSuccessBg\", text);\n\n\t\tlet hasContent = false;\n\t\tthis.hideComponent = false;\n\t\tif (this.hasRendererDefinition()) {\n\t\t\tconst renderContainer = this.getRenderShell() === \"self\" ? this.selfRenderContainer : this.contentBox;\n\t\t\tif (renderContainer instanceof Box) {\n\t\t\t\trenderContainer.setBgFn(bgFn);\n\t\t\t}\n\t\t\trenderContainer.clear();\n\n\t\t\tconst callRenderer = this.getCallRenderer();\n\t\t\tif (!callRenderer) {\n\t\t\t\trenderContainer.addChild(this.createCallFallback());\n\t\t\t\thasContent = true;\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tconst component = callRenderer(this.args, theme, this.getRenderContext(this.callRendererComponent));\n\t\t\t\t\tthis.callRendererComponent = component;\n\t\t\t\t\trenderContainer.addChild(component);\n\t\t\t\t\thasContent = true;\n\t\t\t\t} catch {\n\t\t\t\t\tthis.callRendererComponent = undefined;\n\t\t\t\t\trenderContainer.addChild(this.createCallFallback());\n\t\t\t\t\thasContent = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.result) {\n\t\t\t\tconst resultRenderer = this.getResultRenderer();\n\t\t\t\tif (!resultRenderer) {\n\t\t\t\t\tconst component = this.createResultFallback();\n\t\t\t\t\tif (component) {\n\t\t\t\t\t\trenderContainer.addChild(component);\n\t\t\t\t\t\thasContent = true;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst component = resultRenderer(\n\t\t\t\t\t\t\t{ content: this.result.content as any, details: this.result.details },\n\t\t\t\t\t\t\t{ expanded: this.expanded, isPartial: this.isPartial },\n\t\t\t\t\t\t\ttheme,\n\t\t\t\t\t\t\tthis.getRenderContext(this.resultRendererComponent),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.resultRendererComponent = component;\n\t\t\t\t\t\trenderContainer.addChild(component);\n\t\t\t\t\t\thasContent = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthis.resultRendererComponent = undefined;\n\t\t\t\t\t\tconst component = this.createResultFallback();\n\t\t\t\t\t\tif (component) {\n\t\t\t\t\t\t\trenderContainer.addChild(component);\n\t\t\t\t\t\t\thasContent = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthis.contentText.setCustomBgFn(bgFn);\n\t\t\tthis.contentText.setText(this.formatToolExecution());\n\t\t\thasContent = true;\n\t\t}\n\n\t\tfor (const img of this.imageComponents) {\n\t\t\tthis.removeChild(img);\n\t\t}\n\t\tthis.imageComponents = [];\n\t\tfor (const spacer of this.imageSpacers) {\n\t\t\tthis.removeChild(spacer);\n\t\t}\n\t\tthis.imageSpacers = [];\n\n\t\tif (this.result) {\n\t\t\tconst imageBlocks = this.result.content.filter((c) => c.type === \"image\");\n\t\t\tconst caps = getCapabilities();\n\t\t\tfor (let i = 0; i < imageBlocks.length; i++) {\n\t\t\t\tconst img = imageBlocks[i];\n\t\t\t\tif (caps.images && this.showImages && img.data && img.mimeType) {\n\t\t\t\t\tconst converted = this.convertedImages.get(i);\n\t\t\t\t\tconst imageData = converted?.data ?? img.data;\n\t\t\t\t\tconst imageMimeType = converted?.mimeType ?? img.mimeType;\n\t\t\t\t\tif (caps.images === \"kitty\" && imageMimeType !== \"image/png\") continue;\n\n\t\t\t\t\tconst spacer = new Spacer(1);\n\t\t\t\t\tthis.addChild(spacer);\n\t\t\t\t\tthis.imageSpacers.push(spacer);\n\t\t\t\t\tconst imageComponent = new Image(\n\t\t\t\t\t\timageData,\n\t\t\t\t\t\timageMimeType,\n\t\t\t\t\t\t{ fallbackColor: (s: string) => theme.fg(\"toolOutput\", s) },\n\t\t\t\t\t\t{ maxWidthCells: this.imageWidthCells },\n\t\t\t\t\t);\n\t\t\t\t\tthis.imageComponents.push(imageComponent);\n\t\t\t\t\tthis.addChild(imageComponent);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (this.hasRendererDefinition() && !hasContent && this.imageComponents.length === 0) {\n\t\t\tthis.hideComponent = true;\n\t\t}\n\t}\n\n\tprivate getTextOutput(): string {\n\t\treturn getRenderedTextOutput(this.result, this.showImages);\n\t}\n\n\tprivate formatToolExecution(): string {\n\t\tlet text = theme.fg(\"toolTitle\", theme.bold(this.toolName));\n\t\tconst content = JSON.stringify(this.args, null, 2);\n\t\tif (content) {\n\t\t\ttext += `\\n\\n${content}`;\n\t\t}\n\t\tconst output = this.getTextOutput();\n\t\tif (output) {\n\t\t\ttext += `\\n${output}`;\n\t\t}\n\t\treturn text;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/tool-execution.js b/dist/modes/interactive/components/tool-execution.js new file mode 100644 index 0000000..3f93cc6 --- /dev/null +++ b/dist/modes/interactive/components/tool-execution.js @@ -0,0 +1,317 @@ +import { Box, Container, getCapabilities, Image, Spacer, Text } from "@earendil-works/pi-tui"; +import { createAllToolDefinitions } from "../../../core/tools/index.js"; +import { getTextOutput as getRenderedTextOutput } from "../../../core/tools/render-utils.js"; +import { convertToPng } from "../../../utils/image-convert.js"; +import { theme } from "../theme/theme.js"; +export class ToolExecutionComponent extends Container { + contentBox; + contentText; + selfRenderContainer; + callRendererComponent; + resultRendererComponent; + rendererState = {}; + imageComponents = []; + imageSpacers = []; + toolName; + toolCallId; + args; + expanded = false; + showImages; + imageWidthCells; + isPartial = true; + toolDefinition; + builtInToolDefinition; + ui; + cwd; + executionStarted = false; + argsComplete = false; + result; + convertedImages = new Map(); + hideComponent = false; + constructor(toolName, toolCallId, args, options = {}, toolDefinition, ui, cwd) { + super(); + this.toolName = toolName; + this.toolCallId = toolCallId; + this.args = args; + this.toolDefinition = toolDefinition; + this.builtInToolDefinition = createAllToolDefinitions(cwd)[toolName]; + this.showImages = options.showImages ?? true; + this.imageWidthCells = options.imageWidthCells ?? 60; + this.ui = ui; + this.cwd = cwd; + this.addChild(new Spacer(1)); + // Always create all shell variants. contentBox is used for default renderer-based composition. + // selfRenderContainer is used when the tool renders its own framing. + // contentText is reserved for generic fallback rendering when no tool definition exists. + this.contentBox = new Box(1, 1, (text) => theme.bg("toolPendingBg", text)); + this.contentText = new Text("", 1, 1, (text) => theme.bg("toolPendingBg", text)); + this.selfRenderContainer = new Container(); + if (this.hasRendererDefinition()) { + this.addChild(this.getRenderShell() === "self" ? this.selfRenderContainer : this.contentBox); + } + else { + this.addChild(this.contentText); + } + this.updateDisplay(); + } + getCallRenderer() { + if (!this.builtInToolDefinition) { + return this.toolDefinition?.renderCall; + } + if (!this.toolDefinition) { + return this.builtInToolDefinition.renderCall; + } + return this.toolDefinition.renderCall ?? this.builtInToolDefinition.renderCall; + } + getResultRenderer() { + if (!this.builtInToolDefinition) { + return this.toolDefinition?.renderResult; + } + if (!this.toolDefinition) { + return this.builtInToolDefinition.renderResult; + } + return this.toolDefinition.renderResult ?? this.builtInToolDefinition.renderResult; + } + hasRendererDefinition() { + return this.builtInToolDefinition !== undefined || this.toolDefinition !== undefined; + } + getRenderShell() { + if (!this.builtInToolDefinition) { + return this.toolDefinition?.renderShell ?? "default"; + } + if (!this.toolDefinition) { + return this.builtInToolDefinition.renderShell ?? "default"; + } + return this.toolDefinition.renderShell ?? this.builtInToolDefinition.renderShell ?? "default"; + } + getRenderContext(lastComponent) { + return { + args: this.args, + toolCallId: this.toolCallId, + invalidate: () => { + this.invalidate(); + this.ui.requestRender(); + }, + lastComponent, + state: this.rendererState, + cwd: this.cwd, + executionStarted: this.executionStarted, + argsComplete: this.argsComplete, + isPartial: this.isPartial, + expanded: this.expanded, + showImages: this.showImages, + isError: this.result?.isError ?? false, + }; + } + createCallFallback() { + return new Text(theme.fg("toolTitle", theme.bold(this.toolName)), 0, 0); + } + createResultFallback() { + const output = this.getTextOutput(); + if (!output) { + return undefined; + } + return new Text(theme.fg("toolOutput", output), 0, 0); + } + updateArgs(args) { + this.args = args; + this.updateDisplay(); + } + markExecutionStarted() { + this.executionStarted = true; + this.updateDisplay(); + this.ui.requestRender(); + } + setArgsComplete() { + this.argsComplete = true; + this.updateDisplay(); + this.ui.requestRender(); + } + updateResult(result, isPartial = false) { + this.result = result; + this.isPartial = isPartial; + this.updateDisplay(); + this.maybeConvertImagesForKitty(); + } + maybeConvertImagesForKitty() { + const caps = getCapabilities(); + if (caps.images !== "kitty") + return; + if (!this.result) + return; + const imageBlocks = this.result.content.filter((c) => c.type === "image"); + for (let i = 0; i < imageBlocks.length; i++) { + const img = imageBlocks[i]; + if (!img.data || !img.mimeType) + continue; + if (img.mimeType === "image/png") + continue; + if (this.convertedImages.has(i)) + continue; + const index = i; + convertToPng(img.data, img.mimeType).then((converted) => { + if (converted) { + this.convertedImages.set(index, converted); + this.updateDisplay(); + this.ui.requestRender(); + } + }); + } + } + setExpanded(expanded) { + this.expanded = expanded; + this.updateDisplay(); + } + setShowImages(show) { + this.showImages = show; + this.updateDisplay(); + } + setImageWidthCells(width) { + this.imageWidthCells = Math.max(1, Math.floor(width)); + this.updateDisplay(); + } + invalidate() { + super.invalidate(); + this.updateDisplay(); + } + render(width) { + if (this.hideComponent) { + return []; + } + if (this.hasRendererDefinition() && this.getRenderShell() === "self") { + const contentLines = this.selfRenderContainer.render(width); + if (contentLines.length === 0 && this.imageComponents.length === 0) { + return []; + } + const lines = []; + if (contentLines.length > 0) { + lines.push(""); + lines.push(...contentLines); + } + for (let i = 0; i < this.imageComponents.length; i++) { + const spacer = this.imageSpacers[i]; + if (spacer) { + lines.push(...spacer.render(width)); + } + const imageComponent = this.imageComponents[i]; + if (imageComponent) { + lines.push(...imageComponent.render(width)); + } + } + return lines; + } + return super.render(width); + } + updateDisplay() { + const bgFn = this.isPartial + ? (text) => theme.bg("toolPendingBg", text) + : this.result?.isError + ? (text) => theme.bg("toolErrorBg", text) + : (text) => theme.bg("toolSuccessBg", text); + let hasContent = false; + this.hideComponent = false; + if (this.hasRendererDefinition()) { + const renderContainer = this.getRenderShell() === "self" ? this.selfRenderContainer : this.contentBox; + if (renderContainer instanceof Box) { + renderContainer.setBgFn(bgFn); + } + renderContainer.clear(); + const callRenderer = this.getCallRenderer(); + if (!callRenderer) { + renderContainer.addChild(this.createCallFallback()); + hasContent = true; + } + else { + try { + const component = callRenderer(this.args, theme, this.getRenderContext(this.callRendererComponent)); + this.callRendererComponent = component; + renderContainer.addChild(component); + hasContent = true; + } + catch { + this.callRendererComponent = undefined; + renderContainer.addChild(this.createCallFallback()); + hasContent = true; + } + } + if (this.result) { + const resultRenderer = this.getResultRenderer(); + if (!resultRenderer) { + const component = this.createResultFallback(); + if (component) { + renderContainer.addChild(component); + hasContent = true; + } + } + else { + try { + const component = resultRenderer({ content: this.result.content, details: this.result.details }, { expanded: this.expanded, isPartial: this.isPartial }, theme, this.getRenderContext(this.resultRendererComponent)); + this.resultRendererComponent = component; + renderContainer.addChild(component); + hasContent = true; + } + catch { + this.resultRendererComponent = undefined; + const component = this.createResultFallback(); + if (component) { + renderContainer.addChild(component); + hasContent = true; + } + } + } + } + } + else { + this.contentText.setCustomBgFn(bgFn); + this.contentText.setText(this.formatToolExecution()); + hasContent = true; + } + for (const img of this.imageComponents) { + this.removeChild(img); + } + this.imageComponents = []; + for (const spacer of this.imageSpacers) { + this.removeChild(spacer); + } + this.imageSpacers = []; + if (this.result) { + const imageBlocks = this.result.content.filter((c) => c.type === "image"); + const caps = getCapabilities(); + for (let i = 0; i < imageBlocks.length; i++) { + const img = imageBlocks[i]; + if (caps.images && this.showImages && img.data && img.mimeType) { + const converted = this.convertedImages.get(i); + const imageData = converted?.data ?? img.data; + const imageMimeType = converted?.mimeType ?? img.mimeType; + if (caps.images === "kitty" && imageMimeType !== "image/png") + continue; + const spacer = new Spacer(1); + this.addChild(spacer); + this.imageSpacers.push(spacer); + const imageComponent = new Image(imageData, imageMimeType, { fallbackColor: (s) => theme.fg("toolOutput", s) }, { maxWidthCells: this.imageWidthCells }); + this.imageComponents.push(imageComponent); + this.addChild(imageComponent); + } + } + } + if (this.hasRendererDefinition() && !hasContent && this.imageComponents.length === 0) { + this.hideComponent = true; + } + } + getTextOutput() { + return getRenderedTextOutput(this.result, this.showImages); + } + formatToolExecution() { + let text = theme.fg("toolTitle", theme.bold(this.toolName)); + const content = JSON.stringify(this.args, null, 2); + if (content) { + text += `\n\n${content}`; + } + const output = this.getTextOutput(); + if (output) { + text += `\n${output}`; + } + return text; + } +} +//# sourceMappingURL=tool-execution.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/tool-execution.js.map b/dist/modes/interactive/components/tool-execution.js.map new file mode 100644 index 0000000..0f9a8cd --- /dev/null +++ b/dist/modes/interactive/components/tool-execution.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tool-execution.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/tool-execution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAkB,SAAS,EAAE,eAAe,E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\";\nimport type { ToolDefinition, ToolRenderContext } from \"../../../core/extensions/types.ts\";\nimport { createAllToolDefinitions, type ToolName } from \"../../../core/tools/index.ts\";\nimport { getTextOutput as getRenderedTextOutput } from \"../../../core/tools/render-utils.ts\";\nimport { convertToPng } from \"../../../utils/image-convert.ts\";\nimport { theme } from \"../theme/theme.ts\";\n\nexport interface ToolExecutionOptions {\n\tshowImages?: boolean;\n\timageWidthCells?: number;\n}\n\nexport class ToolExecutionComponent extends Container {\n\tprivate contentBox: Box;\n\tprivate contentText: Text;\n\tprivate selfRenderContainer: Container;\n\tprivate callRendererComponent?: Component;\n\tprivate resultRendererComponent?: Component;\n\tprivate rendererState: any = {};\n\tprivate imageComponents: Image[] = [];\n\tprivate imageSpacers: Spacer[] = [];\n\tprivate toolName: string;\n\tprivate toolCallId: string;\n\tprivate args: any;\n\tprivate expanded = false;\n\tprivate showImages: boolean;\n\tprivate imageWidthCells: number;\n\tprivate isPartial = true;\n\tprivate toolDefinition?: ToolDefinition;\n\tprivate builtInToolDefinition?: ToolDefinition;\n\tprivate ui: TUI;\n\tprivate cwd: string;\n\tprivate executionStarted = false;\n\tprivate argsComplete = false;\n\tprivate result?: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tisError: boolean;\n\t\tdetails?: any;\n\t};\n\tprivate convertedImages: Map = new Map();\n\tprivate hideComponent = false;\n\n\tconstructor(\n\t\ttoolName: string,\n\t\ttoolCallId: string,\n\t\targs: any,\n\t\toptions: ToolExecutionOptions = {},\n\t\ttoolDefinition: ToolDefinition | undefined,\n\t\tui: TUI,\n\t\tcwd: string,\n\t) {\n\t\tsuper();\n\t\tthis.toolName = toolName;\n\t\tthis.toolCallId = toolCallId;\n\t\tthis.args = args;\n\t\tthis.toolDefinition = toolDefinition;\n\t\tthis.builtInToolDefinition = createAllToolDefinitions(cwd)[toolName as ToolName];\n\t\tthis.showImages = options.showImages ?? true;\n\t\tthis.imageWidthCells = options.imageWidthCells ?? 60;\n\t\tthis.ui = ui;\n\t\tthis.cwd = cwd;\n\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Always create all shell variants. contentBox is used for default renderer-based composition.\n\t\t// selfRenderContainer is used when the tool renders its own framing.\n\t\t// contentText is reserved for generic fallback rendering when no tool definition exists.\n\t\tthis.contentBox = new Box(1, 1, (text: string) => theme.bg(\"toolPendingBg\", text));\n\t\tthis.contentText = new Text(\"\", 1, 1, (text: string) => theme.bg(\"toolPendingBg\", text));\n\t\tthis.selfRenderContainer = new Container();\n\n\t\tif (this.hasRendererDefinition()) {\n\t\t\tthis.addChild(this.getRenderShell() === \"self\" ? this.selfRenderContainer : this.contentBox);\n\t\t} else {\n\t\t\tthis.addChild(this.contentText);\n\t\t}\n\n\t\tthis.updateDisplay();\n\t}\n\n\tprivate getCallRenderer(): ToolDefinition[\"renderCall\"] | undefined {\n\t\tif (!this.builtInToolDefinition) {\n\t\t\treturn this.toolDefinition?.renderCall;\n\t\t}\n\t\tif (!this.toolDefinition) {\n\t\t\treturn this.builtInToolDefinition.renderCall;\n\t\t}\n\t\treturn this.toolDefinition.renderCall ?? this.builtInToolDefinition.renderCall;\n\t}\n\n\tprivate getResultRenderer(): ToolDefinition[\"renderResult\"] | undefined {\n\t\tif (!this.builtInToolDefinition) {\n\t\t\treturn this.toolDefinition?.renderResult;\n\t\t}\n\t\tif (!this.toolDefinition) {\n\t\t\treturn this.builtInToolDefinition.renderResult;\n\t\t}\n\t\treturn this.toolDefinition.renderResult ?? this.builtInToolDefinition.renderResult;\n\t}\n\n\tprivate hasRendererDefinition(): boolean {\n\t\treturn this.builtInToolDefinition !== undefined || this.toolDefinition !== undefined;\n\t}\n\n\tprivate getRenderShell(): \"default\" | \"self\" {\n\t\tif (!this.builtInToolDefinition) {\n\t\t\treturn this.toolDefinition?.renderShell ?? \"default\";\n\t\t}\n\t\tif (!this.toolDefinition) {\n\t\t\treturn this.builtInToolDefinition.renderShell ?? \"default\";\n\t\t}\n\t\treturn this.toolDefinition.renderShell ?? this.builtInToolDefinition.renderShell ?? \"default\";\n\t}\n\n\tprivate getRenderContext(lastComponent: Component | undefined): ToolRenderContext {\n\t\treturn {\n\t\t\targs: this.args,\n\t\t\ttoolCallId: this.toolCallId,\n\t\t\tinvalidate: () => {\n\t\t\t\tthis.invalidate();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t},\n\t\t\tlastComponent,\n\t\t\tstate: this.rendererState,\n\t\t\tcwd: this.cwd,\n\t\t\texecutionStarted: this.executionStarted,\n\t\t\targsComplete: this.argsComplete,\n\t\t\tisPartial: this.isPartial,\n\t\t\texpanded: this.expanded,\n\t\t\tshowImages: this.showImages,\n\t\t\tisError: this.result?.isError ?? false,\n\t\t};\n\t}\n\n\tprivate createCallFallback(): Component {\n\t\treturn new Text(theme.fg(\"toolTitle\", theme.bold(this.toolName)), 0, 0);\n\t}\n\n\tprivate createResultFallback(): Component | undefined {\n\t\tconst output = this.getTextOutput();\n\t\tif (!output) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn new Text(theme.fg(\"toolOutput\", output), 0, 0);\n\t}\n\n\tupdateArgs(args: any): void {\n\t\tthis.args = args;\n\t\tthis.updateDisplay();\n\t}\n\n\tmarkExecutionStarted(): void {\n\t\tthis.executionStarted = true;\n\t\tthis.updateDisplay();\n\t\tthis.ui.requestRender();\n\t}\n\n\tsetArgsComplete(): void {\n\t\tthis.argsComplete = true;\n\t\tthis.updateDisplay();\n\t\tthis.ui.requestRender();\n\t}\n\n\tupdateResult(\n\t\tresult: {\n\t\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\t\tdetails?: any;\n\t\t\tisError: boolean;\n\t\t},\n\t\tisPartial = false,\n\t): void {\n\t\tthis.result = result;\n\t\tthis.isPartial = isPartial;\n\t\tthis.updateDisplay();\n\t\tthis.maybeConvertImagesForKitty();\n\t}\n\n\tprivate maybeConvertImagesForKitty(): void {\n\t\tconst caps = getCapabilities();\n\t\tif (caps.images !== \"kitty\") return;\n\t\tif (!this.result) return;\n\n\t\tconst imageBlocks = this.result.content.filter((c) => c.type === \"image\");\n\t\tfor (let i = 0; i < imageBlocks.length; i++) {\n\t\t\tconst img = imageBlocks[i];\n\t\t\tif (!img.data || !img.mimeType) continue;\n\t\t\tif (img.mimeType === \"image/png\") continue;\n\t\t\tif (this.convertedImages.has(i)) continue;\n\n\t\t\tconst index = i;\n\t\t\tconvertToPng(img.data, img.mimeType).then((converted) => {\n\t\t\t\tif (converted) {\n\t\t\t\t\tthis.convertedImages.set(index, converted);\n\t\t\t\t\tthis.updateDisplay();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.expanded = expanded;\n\t\tthis.updateDisplay();\n\t}\n\n\tsetShowImages(show: boolean): void {\n\t\tthis.showImages = show;\n\t\tthis.updateDisplay();\n\t}\n\n\tsetImageWidthCells(width: number): void {\n\t\tthis.imageWidthCells = Math.max(1, Math.floor(width));\n\t\tthis.updateDisplay();\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.updateDisplay();\n\t}\n\n\toverride render(width: number): string[] {\n\t\tif (this.hideComponent) {\n\t\t\treturn [];\n\t\t}\n\n\t\tif (this.hasRendererDefinition() && this.getRenderShell() === \"self\") {\n\t\t\tconst contentLines = this.selfRenderContainer.render(width);\n\t\t\tif (contentLines.length === 0 && this.imageComponents.length === 0) {\n\t\t\t\treturn [];\n\t\t\t}\n\n\t\t\tconst lines: string[] = [];\n\t\t\tif (contentLines.length > 0) {\n\t\t\t\tlines.push(\"\");\n\t\t\t\tlines.push(...contentLines);\n\t\t\t}\n\t\t\tfor (let i = 0; i < this.imageComponents.length; i++) {\n\t\t\t\tconst spacer = this.imageSpacers[i];\n\t\t\t\tif (spacer) {\n\t\t\t\t\tlines.push(...spacer.render(width));\n\t\t\t\t}\n\t\t\t\tconst imageComponent = this.imageComponents[i];\n\t\t\t\tif (imageComponent) {\n\t\t\t\t\tlines.push(...imageComponent.render(width));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn lines;\n\t\t}\n\n\t\treturn super.render(width);\n\t}\n\n\tprivate updateDisplay(): void {\n\t\tconst bgFn = this.isPartial\n\t\t\t? (text: string) => theme.bg(\"toolPendingBg\", text)\n\t\t\t: this.result?.isError\n\t\t\t\t? (text: string) => theme.bg(\"toolErrorBg\", text)\n\t\t\t\t: (text: string) => theme.bg(\"toolSuccessBg\", text);\n\n\t\tlet hasContent = false;\n\t\tthis.hideComponent = false;\n\t\tif (this.hasRendererDefinition()) {\n\t\t\tconst renderContainer = this.getRenderShell() === \"self\" ? this.selfRenderContainer : this.contentBox;\n\t\t\tif (renderContainer instanceof Box) {\n\t\t\t\trenderContainer.setBgFn(bgFn);\n\t\t\t}\n\t\t\trenderContainer.clear();\n\n\t\t\tconst callRenderer = this.getCallRenderer();\n\t\t\tif (!callRenderer) {\n\t\t\t\trenderContainer.addChild(this.createCallFallback());\n\t\t\t\thasContent = true;\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tconst component = callRenderer(this.args, theme, this.getRenderContext(this.callRendererComponent));\n\t\t\t\t\tthis.callRendererComponent = component;\n\t\t\t\t\trenderContainer.addChild(component);\n\t\t\t\t\thasContent = true;\n\t\t\t\t} catch {\n\t\t\t\t\tthis.callRendererComponent = undefined;\n\t\t\t\t\trenderContainer.addChild(this.createCallFallback());\n\t\t\t\t\thasContent = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.result) {\n\t\t\t\tconst resultRenderer = this.getResultRenderer();\n\t\t\t\tif (!resultRenderer) {\n\t\t\t\t\tconst component = this.createResultFallback();\n\t\t\t\t\tif (component) {\n\t\t\t\t\t\trenderContainer.addChild(component);\n\t\t\t\t\t\thasContent = true;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst component = resultRenderer(\n\t\t\t\t\t\t\t{ content: this.result.content as any, details: this.result.details },\n\t\t\t\t\t\t\t{ expanded: this.expanded, isPartial: this.isPartial },\n\t\t\t\t\t\t\ttheme,\n\t\t\t\t\t\t\tthis.getRenderContext(this.resultRendererComponent),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.resultRendererComponent = component;\n\t\t\t\t\t\trenderContainer.addChild(component);\n\t\t\t\t\t\thasContent = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthis.resultRendererComponent = undefined;\n\t\t\t\t\t\tconst component = this.createResultFallback();\n\t\t\t\t\t\tif (component) {\n\t\t\t\t\t\t\trenderContainer.addChild(component);\n\t\t\t\t\t\t\thasContent = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthis.contentText.setCustomBgFn(bgFn);\n\t\t\tthis.contentText.setText(this.formatToolExecution());\n\t\t\thasContent = true;\n\t\t}\n\n\t\tfor (const img of this.imageComponents) {\n\t\t\tthis.removeChild(img);\n\t\t}\n\t\tthis.imageComponents = [];\n\t\tfor (const spacer of this.imageSpacers) {\n\t\t\tthis.removeChild(spacer);\n\t\t}\n\t\tthis.imageSpacers = [];\n\n\t\tif (this.result) {\n\t\t\tconst imageBlocks = this.result.content.filter((c) => c.type === \"image\");\n\t\t\tconst caps = getCapabilities();\n\t\t\tfor (let i = 0; i < imageBlocks.length; i++) {\n\t\t\t\tconst img = imageBlocks[i];\n\t\t\t\tif (caps.images && this.showImages && img.data && img.mimeType) {\n\t\t\t\t\tconst converted = this.convertedImages.get(i);\n\t\t\t\t\tconst imageData = converted?.data ?? img.data;\n\t\t\t\t\tconst imageMimeType = converted?.mimeType ?? img.mimeType;\n\t\t\t\t\tif (caps.images === \"kitty\" && imageMimeType !== \"image/png\") continue;\n\n\t\t\t\t\tconst spacer = new Spacer(1);\n\t\t\t\t\tthis.addChild(spacer);\n\t\t\t\t\tthis.imageSpacers.push(spacer);\n\t\t\t\t\tconst imageComponent = new Image(\n\t\t\t\t\t\timageData,\n\t\t\t\t\t\timageMimeType,\n\t\t\t\t\t\t{ fallbackColor: (s: string) => theme.fg(\"toolOutput\", s) },\n\t\t\t\t\t\t{ maxWidthCells: this.imageWidthCells },\n\t\t\t\t\t);\n\t\t\t\t\tthis.imageComponents.push(imageComponent);\n\t\t\t\t\tthis.addChild(imageComponent);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (this.hasRendererDefinition() && !hasContent && this.imageComponents.length === 0) {\n\t\t\tthis.hideComponent = true;\n\t\t}\n\t}\n\n\tprivate getTextOutput(): string {\n\t\treturn getRenderedTextOutput(this.result, this.showImages);\n\t}\n\n\tprivate formatToolExecution(): string {\n\t\tlet text = theme.fg(\"toolTitle\", theme.bold(this.toolName));\n\t\tconst content = JSON.stringify(this.args, null, 2);\n\t\tif (content) {\n\t\t\ttext += `\\n\\n${content}`;\n\t\t}\n\t\tconst output = this.getTextOutput();\n\t\tif (output) {\n\t\t\ttext += `\\n${output}`;\n\t\t}\n\t\treturn text;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/tree-selector.d.ts b/dist/modes/interactive/components/tree-selector.d.ts new file mode 100644 index 0000000..407ad51 --- /dev/null +++ b/dist/modes/interactive/components/tree-selector.d.ts @@ -0,0 +1,94 @@ +import { type Component, Container, type Focusable } from "@earendil-works/pi-tui"; +import type { SessionTreeNode } from "../../../core/session-manager.ts"; +/** Filter mode for tree display */ +export type FilterMode = "default" | "no-tools" | "user-only" | "labeled-only" | "all"; +declare class TreeList implements Component { + private flatNodes; + private filteredNodes; + private selectedIndex; + private currentLeafId; + private maxVisibleLines; + private filterMode; + private searchQuery; + private toolCallMap; + private multipleRoots; + private showLabelTimestamps; + private activePathIds; + private visibleParentMap; + private visibleChildrenMap; + private lastSelectedId; + private foldedNodes; + onSelect?: (entryId: string) => void; + onCancel?: () => void; + onCopy?: (text: string | undefined) => void; + onLabelEdit?: (entryId: string, currentLabel: string | undefined) => void; + constructor(tree: SessionTreeNode[], currentLeafId: string | null, maxVisibleLines: number, initialSelectedId?: string, initialFilterMode?: FilterMode); + /** + * Find the index of the nearest visible entry, walking up the parent chain if needed. + * Returns the index in filteredNodes, or the last index as fallback. + */ + private findNearestVisibleIndex; + /** Build the set of entry IDs on the path from root to current leaf */ + private buildActivePath; + private flattenTree; + private applyFilter; + /** + * Recompute indentation/connectors for the filtered view + * + * Filtering can hide intermediate entries; descendants attach to the nearest visible ancestor. + * Keep indentation semantics aligned with flattenTree() so single-child chains don't drift right. + */ + private recalculateVisualStructure; + /** Get searchable text content from a node */ + private getSearchableText; + invalidate(): void; + getSearchQuery(): string; + getSelectedNode(): SessionTreeNode | undefined; + copySelected(): void; + updateNodeLabel(entryId: string, label: string | undefined, labelTimestamp?: string): void; + private getStatusLabels; + render(width: number): string[]; + private getEntryDisplayText; + private formatLabelTimestamp; + private extractContent; + private extractFullContent; + private getEntryCopyText; + private hasTextContent; + private formatToolCall; + handleInput(keyData: string): void; + /** + * Whether a node can be folded. A node is foldable if it has visible children + * and is either a root (no visible parent) or a segment start (visible parent + * has multiple visible children). + */ + private isFoldable; + /** + * Find the index of the next branch segment start in the given direction. + * A segment start is the first child of a branch point. + * + * "up" walks the visible parent chain; "down" walks visible children + * (always following the first child). + */ + private findBranchSegmentStart; +} +/** + * Component that renders a session tree selector for navigation + */ +export declare class TreeSelectorComponent extends Container implements Focusable { + private treeList; + private labelInput; + private labelInputContainer; + private treeContainer; + private onLabelChangeCallback?; + onCopy?: (text: string | undefined) => void; + private _focused; + get focused(): boolean; + set focused(value: boolean); + constructor(tree: SessionTreeNode[], currentLeafId: string | null, terminalHeight: number, onSelect: (entryId: string) => void, onCancel: () => void, onLabelChange?: (entryId: string, label: string | undefined) => void, initialSelectedId?: string, initialFilterMode?: FilterMode); + private showLabelInput; + private hideLabelInput; + handleInput(keyData: string): void; + getTreeList(): TreeList; +} +export {}; +//# sourceMappingURL=tree-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/tree-selector.d.ts.map b/dist/modes/interactive/components/tree-selector.d.ts.map new file mode 100644 index 0000000..23a36b2 --- /dev/null +++ b/dist/modes/interactive/components/tree-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tree-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/tree-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,SAAS,EACd,SAAS,EACT,KAAK,SAAS,EAUd,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AA+ExE,mCAAmC;AACnC,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,UAAU,GAAG,WAAW,GAAG,cAAc,GAAG,KAAK,CAAC;AAWvF,cAAM,QAAS,YAAW,SAAS;IAClC,OAAO,CAAC,SAAS,CAAkB;IACnC,OAAO,CAAC,aAAa,CAAkB;IACvC,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,UAAU,CAAyB;IAC3C,OAAO,CAAC,WAAW,CAAM;IACzB,OAAO,CAAC,WAAW,CAAwC;IAC3D,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,mBAAmB,CAAS;IACpC,OAAO,CAAC,aAAa,CAA0B;IAC/C,OAAO,CAAC,gBAAgB,CAAyC;IACjE,OAAO,CAAC,kBAAkB,CAA2C;IACrE,OAAO,CAAC,cAAc,CAAuB;IAC7C,OAAO,CAAC,WAAW,CAA0B;IAEtC,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACrC,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;IACtB,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,CAAC;IAC5C,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAA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OAAO,CAAC,mBAAmB,CAAY;IACvC,OAAO,CAAC,aAAa,CAAY;IACjC,OAAO,CAAC,qBAAqB,CAAC,CAAuD;IAC9E,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,CAAC;IAGnD,OAAO,CAAC,QAAQ,CAAS;IACzB,IAAI,OAAO,IAAI,OAAO,CAErB;IACD,IAAI,OAAO,CAAC,KAAK,EAAE,OAAO,EAMzB;IAED,YACC,IAAI,EAAE,eAAe,EAAE,EACvB,aAAa,EAAE,MAAM,GAAG,IAAI,EAC5B,cAAc,EAAE,MAAM,EACtB,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,EACnC,QAAQ,EAAE,MAAM,IAAI,EACpB,aAAa,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,EACpE,iBAAiB,CAAC,EAAE,MAAM,EAC1B,iBAAiB,CAAC,EAAE,UAAU,EAiC9B;IAED,OAAO,CAAC,cAAc;IAiBtB,OAAO,CAAC,cAAc;IAOtB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAMjC;IAED,WAAW,IAAI,QAAQ,CAEtB;CACD","sourcesContent":["import {\n\ttype Component,\n\tContainer,\n\ttype Focusable,\n\tgetKeybindings,\n\tInput,\n\ttype Keybinding,\n\tSpacer,\n\tsliceByColumn,\n\tText,\n\ttruncateToWidth,\n\tvisibleWidth,\n\twrapTextWithAnsi,\n} from \"@earendil-works/pi-tui\";\nimport type { SessionTreeNode } from \"../../../core/session-manager.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { formatKeyText, keyHint } from \"./keybinding-hints.ts\";\n\n/** Gutter info: position (displayIndent where connector was) and whether to show │ */\ninterface GutterInfo {\n\tposition: number; // displayIndent level where the connector was shown\n\tshow: boolean; // true = show │, false = show spaces\n}\n\n/** Flattened tree node for navigation */\ninterface FlatNode {\n\tnode: SessionTreeNode;\n\t/** Indentation level (each level = 3 chars) */\n\tindent: number;\n\t/** Whether to show connector (├─ or └─) - true if parent has multiple children */\n\tshowConnector: boolean;\n\t/** If showConnector, true = last sibling (└─), false = not last (├─) */\n\tisLast: boolean;\n\t/** Gutter info for each ancestor branch point */\n\tgutters: GutterInfo[];\n\t/** True if this node is a root under a virtual branching root (multiple roots) */\n\tisVirtualRootChild: boolean;\n}\n\ninterface HorizontalViewportRow {\n\tgutter: string;\n\tbody: string;\n\tanchorCol: number;\n\tbodyWidth: number;\n\tisSelected: boolean;\n}\n\nconst TREE_GUTTER_WIDTH = 2;\nconst MIN_VISIBLE_ANCHOR_CONTENT_WIDTH = 4;\nconst MAX_VISIBLE_ANCHOR_CONTENT_WIDTH = 20;\nconst MIN_ANCHOR_CONTEXT_WIDTH = 2;\nconst MAX_ANCHOR_CONTEXT_WIDTH = 12;\n\n/**\n * Render tree rows into a horizontally clipped viewport.\n *\n * The tree gutter is always kept visible. The row bodies are shifted left only\n * when the selected row's anchor (the start of its entry text after tree\n * indentation/markers) would otherwise be too far right to see useful content.\n */\nfunction renderHorizontalViewport(rows: HorizontalViewportRow[], width: number): string[] {\n\tconst viewportWidth = Math.max(0, width - TREE_GUTTER_WIDTH);\n\tconst maxBodyWidth = rows.reduce((max, row) => Math.max(max, row.bodyWidth), 0);\n\tconst maxHorizontalScroll = Math.max(0, maxBodyWidth - viewportWidth);\n\tconst selectedRow = rows.find((row) => row.isSelected);\n\n\t// Only pan horizontally when needed to keep enough selected-row content visible after its anchor.\n\tlet horizontalScroll = 0;\n\tif (selectedRow && maxHorizontalScroll > 0) {\n\t\tconst minVisibleAnchorContentWidth = Math.min(\n\t\t\tMAX_VISIBLE_ANCHOR_CONTENT_WIDTH,\n\t\t\tMath.max(MIN_VISIBLE_ANCHOR_CONTENT_WIDTH, Math.floor(viewportWidth / 3)),\n\t\t);\n\t\tif (selectedRow.anchorCol > viewportWidth - minVisibleAnchorContentWidth) {\n\t\t\tconst anchorContextWidth = Math.min(\n\t\t\t\tMAX_ANCHOR_CONTEXT_WIDTH,\n\t\t\t\tMath.max(MIN_ANCHOR_CONTEXT_WIDTH, Math.floor(viewportWidth / 4)),\n\t\t\t);\n\t\t\thorizontalScroll = Math.min(maxHorizontalScroll, selectedRow.anchorCol - anchorContextWidth);\n\t\t}\n\t}\n\n\t// Clip only the body; the fixed-width gutter remains visible as navigation context.\n\treturn rows.map((row) => {\n\t\tconst line =\n\t\t\thorizontalScroll > 0\n\t\t\t\t? `${row.gutter}${sliceByColumn(row.body, horizontalScroll, viewportWidth, true)}\\x1b[0m`\n\t\t\t\t: row.gutter + row.body;\n\t\treturn truncateToWidth(line, width, \"\");\n\t});\n}\n\n/** Filter mode for tree display */\nexport type FilterMode = \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\";\n\n/**\n * Tree list component with selection and ASCII art visualization\n */\n/** Tool call info for lookup */\ninterface ToolCallInfo {\n\tname: string;\n\targuments: Record;\n}\n\nclass TreeList implements Component {\n\tprivate flatNodes: FlatNode[] = [];\n\tprivate filteredNodes: FlatNode[] = [];\n\tprivate selectedIndex = 0;\n\tprivate currentLeafId: string | null;\n\tprivate maxVisibleLines: number;\n\tprivate filterMode: FilterMode = \"default\";\n\tprivate searchQuery = \"\";\n\tprivate toolCallMap: Map = new Map();\n\tprivate multipleRoots = false;\n\tprivate showLabelTimestamps = false;\n\tprivate activePathIds: Set = new Set();\n\tprivate visibleParentMap: Map = new Map();\n\tprivate visibleChildrenMap: Map = new Map();\n\tprivate lastSelectedId: string | null = null;\n\tprivate foldedNodes: Set = new Set();\n\n\tpublic onSelect?: (entryId: string) => void;\n\tpublic onCancel?: () => void;\n\tpublic onCopy?: (text: string | undefined) => void;\n\tpublic onLabelEdit?: (entryId: string, currentLabel: string | undefined) => void;\n\n\tconstructor(\n\t\ttree: SessionTreeNode[],\n\t\tcurrentLeafId: string | null,\n\t\tmaxVisibleLines: number,\n\t\tinitialSelectedId?: string,\n\t\tinitialFilterMode?: FilterMode,\n\t) {\n\t\tthis.currentLeafId = currentLeafId;\n\t\tthis.maxVisibleLines = maxVisibleLines;\n\t\tthis.filterMode = initialFilterMode ?? \"default\";\n\t\tthis.multipleRoots = tree.length > 1;\n\t\tthis.flatNodes = this.flattenTree(tree);\n\t\tthis.buildActivePath();\n\t\tthis.applyFilter();\n\n\t\t// Start with initialSelectedId if provided, otherwise current leaf\n\t\tconst targetId = initialSelectedId ?? currentLeafId;\n\t\tthis.selectedIndex = this.findNearestVisibleIndex(targetId);\n\t\tthis.lastSelectedId = this.filteredNodes[this.selectedIndex]?.node.entry.id ?? null;\n\t}\n\n\t/**\n\t * Find the index of the nearest visible entry, walking up the parent chain if needed.\n\t * Returns the index in filteredNodes, or the last index as fallback.\n\t */\n\tprivate findNearestVisibleIndex(entryId: string | null): number {\n\t\tif (this.filteredNodes.length === 0) return 0;\n\n\t\t// Build a map for parent lookup\n\t\tconst entryMap = new Map();\n\t\tfor (const flatNode of this.flatNodes) {\n\t\t\tentryMap.set(flatNode.node.entry.id, flatNode);\n\t\t}\n\n\t\t// Build a map of visible entry IDs to their indices in filteredNodes\n\t\tconst visibleIdToIndex = new Map(this.filteredNodes.map((node, i) => [node.node.entry.id, i]));\n\n\t\t// Walk from entryId up to root, looking for a visible entry\n\t\tlet currentId = entryId;\n\t\twhile (currentId !== null) {\n\t\t\tconst index = visibleIdToIndex.get(currentId);\n\t\t\tif (index !== undefined) return index;\n\t\t\tconst node = entryMap.get(currentId);\n\t\t\tif (!node) break;\n\t\t\tcurrentId = node.node.entry.parentId ?? null;\n\t\t}\n\n\t\t// Fallback: last visible entry\n\t\treturn this.filteredNodes.length - 1;\n\t}\n\n\t/** Build the set of entry IDs on the path from root to current leaf */\n\tprivate buildActivePath(): void {\n\t\tthis.activePathIds.clear();\n\t\tif (!this.currentLeafId) return;\n\n\t\t// Build a map of id -> entry for parent lookup\n\t\tconst entryMap = new Map();\n\t\tfor (const flatNode of this.flatNodes) {\n\t\t\tentryMap.set(flatNode.node.entry.id, flatNode);\n\t\t}\n\n\t\t// Walk from leaf to root\n\t\tlet currentId: string | null = this.currentLeafId;\n\t\twhile (currentId) {\n\t\t\tthis.activePathIds.add(currentId);\n\t\t\tconst node = entryMap.get(currentId);\n\t\t\tif (!node) break;\n\t\t\tcurrentId = node.node.entry.parentId ?? null;\n\t\t}\n\t}\n\n\tprivate flattenTree(roots: SessionTreeNode[]): FlatNode[] {\n\t\tconst result: FlatNode[] = [];\n\t\tthis.toolCallMap.clear();\n\n\t\t// Indentation rules:\n\t\t// - At indent 0: stay at 0 unless parent has >1 children (then +1)\n\t\t// - At indent 1: children always go to indent 2 (visual grouping of subtree)\n\t\t// - At indent 2+: stay flat for single-child chains, +1 only if parent branches\n\n\t\t// Stack items: [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild]\n\t\ttype StackItem = [SessionTreeNode, number, boolean, boolean, boolean, GutterInfo[], boolean];\n\t\tconst stack: StackItem[] = [];\n\n\t\t// Determine which subtrees contain the active leaf (to sort current branch first)\n\t\t// Use iterative post-order traversal to avoid stack overflow\n\t\tconst containsActive = new Map();\n\t\tconst leafId = this.currentLeafId;\n\t\t{\n\t\t\t// Build list in pre-order, then process in reverse for post-order effect\n\t\t\tconst allNodes: SessionTreeNode[] = [];\n\t\t\tconst preOrderStack: SessionTreeNode[] = [...roots];\n\t\t\twhile (preOrderStack.length > 0) {\n\t\t\t\tconst node = preOrderStack.pop()!;\n\t\t\t\tallNodes.push(node);\n\t\t\t\t// Push children in reverse so they're processed left-to-right\n\t\t\t\tfor (let i = node.children.length - 1; i >= 0; i--) {\n\t\t\t\t\tpreOrderStack.push(node.children[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Process in reverse (post-order): children before parents\n\t\t\tfor (let i = allNodes.length - 1; i >= 0; i--) {\n\t\t\t\tconst node = allNodes[i];\n\t\t\t\tlet has = leafId !== null && node.entry.id === leafId;\n\t\t\t\tfor (const child of node.children) {\n\t\t\t\t\tif (containsActive.get(child)) {\n\t\t\t\t\t\thas = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontainsActive.set(node, has);\n\t\t\t}\n\t\t}\n\n\t\t// Add roots in reverse order, prioritizing the one containing the active leaf\n\t\t// If multiple roots, treat them as children of a virtual root that branches\n\t\tconst multipleRoots = roots.length > 1;\n\t\tconst orderedRoots = [...roots].sort((a, b) => Number(containsActive.get(b)) - Number(containsActive.get(a)));\n\t\tfor (let i = orderedRoots.length - 1; i >= 0; i--) {\n\t\t\tconst isLast = i === orderedRoots.length - 1;\n\t\t\tstack.push([orderedRoots[i], multipleRoots ? 1 : 0, multipleRoots, multipleRoots, isLast, [], multipleRoots]);\n\t\t}\n\n\t\twhile (stack.length > 0) {\n\t\t\tconst [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] = stack.pop()!;\n\n\t\t\t// Extract tool calls from assistant messages for later lookup\n\t\t\tconst entry = node.entry;\n\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\tconst content = (entry.message as { content?: unknown }).content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tfor (const block of content) {\n\t\t\t\t\t\tif (typeof block === \"object\" && block !== null && \"type\" in block && block.type === \"toolCall\") {\n\t\t\t\t\t\t\tconst tc = block as { id: string; name: string; arguments: Record };\n\t\t\t\t\t\t\tthis.toolCallMap.set(tc.id, { name: tc.name, arguments: tc.arguments });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresult.push({ node, indent, showConnector, isLast, gutters, isVirtualRootChild });\n\n\t\t\tconst children = node.children;\n\t\t\tconst multipleChildren = children.length > 1;\n\n\t\t\t// Order children so the branch containing the active leaf comes first\n\t\t\tconst orderedChildren = (() => {\n\t\t\t\tconst prioritized: SessionTreeNode[] = [];\n\t\t\t\tconst rest: SessionTreeNode[] = [];\n\t\t\t\tfor (const child of children) {\n\t\t\t\t\tif (containsActive.get(child)) {\n\t\t\t\t\t\tprioritized.push(child);\n\t\t\t\t\t} else {\n\t\t\t\t\t\trest.push(child);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn [...prioritized, ...rest];\n\t\t\t})();\n\n\t\t\t// Calculate child indent\n\t\t\tlet childIndent: number;\n\t\t\tif (multipleChildren) {\n\t\t\t\t// Parent branches: children get +1\n\t\t\t\tchildIndent = indent + 1;\n\t\t\t} else if (justBranched && indent > 0) {\n\t\t\t\t// First generation after a branch: +1 for visual grouping\n\t\t\t\tchildIndent = indent + 1;\n\t\t\t} else {\n\t\t\t\t// Single-child chain: stay flat\n\t\t\t\tchildIndent = indent;\n\t\t\t}\n\n\t\t\t// Build gutters for children\n\t\t\t// If this node showed a connector, add a gutter entry for descendants\n\t\t\t// Only add gutter if connector is actually displayed (not suppressed for virtual root children)\n\t\t\tconst connectorDisplayed = showConnector && !isVirtualRootChild;\n\t\t\t// When connector is displayed, add a gutter entry at the connector's position\n\t\t\t// Connector is at position (displayIndent - 1), so gutter should be there too\n\t\t\tconst currentDisplayIndent = this.multipleRoots ? Math.max(0, indent - 1) : indent;\n\t\t\tconst connectorPosition = Math.max(0, currentDisplayIndent - 1);\n\t\t\tconst childGutters: GutterInfo[] = connectorDisplayed\n\t\t\t\t? [...gutters, { position: connectorPosition, show: !isLast }]\n\t\t\t\t: gutters;\n\n\t\t\t// Add children in reverse order\n\t\t\tfor (let i = orderedChildren.length - 1; i >= 0; i--) {\n\t\t\t\tconst childIsLast = i === orderedChildren.length - 1;\n\t\t\t\tstack.push([\n\t\t\t\t\torderedChildren[i],\n\t\t\t\t\tchildIndent,\n\t\t\t\t\tmultipleChildren,\n\t\t\t\t\tmultipleChildren,\n\t\t\t\t\tchildIsLast,\n\t\t\t\t\tchildGutters,\n\t\t\t\t\tfalse,\n\t\t\t\t]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate applyFilter(): void {\n\t\t// Update lastSelectedId only when we have a valid selection (non-empty list)\n\t\t// This preserves the selection when switching through empty filter results\n\t\tif (this.filteredNodes.length > 0) {\n\t\t\tthis.lastSelectedId = this.filteredNodes[this.selectedIndex]?.node.entry.id ?? this.lastSelectedId;\n\t\t}\n\n\t\tconst searchTokens = this.searchQuery.toLowerCase().split(/\\s+/).filter(Boolean);\n\n\t\tthis.filteredNodes = this.flatNodes.filter((flatNode) => {\n\t\t\tconst entry = flatNode.node.entry;\n\t\t\tconst isCurrentLeaf = entry.id === this.currentLeafId;\n\n\t\t\t// Skip assistant messages with only tool calls (no text) unless error/aborted\n\t\t\t// Always show current leaf so active position is visible\n\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\" && !isCurrentLeaf) {\n\t\t\t\tconst msg = entry.message as { stopReason?: string; content?: unknown };\n\t\t\t\tconst hasText = this.hasTextContent(msg.content);\n\t\t\t\tconst isErrorOrAborted = msg.stopReason && msg.stopReason !== \"stop\" && msg.stopReason !== \"toolUse\";\n\t\t\t\t// Only hide if no text AND not an error/aborted message\n\t\t\t\tif (!hasText && !isErrorOrAborted) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Apply filter mode\n\t\t\tlet passesFilter = true;\n\t\t\t// Entry types hidden in default view (settings/bookkeeping)\n\t\t\tconst isSettingsEntry =\n\t\t\t\tentry.type === \"label\" ||\n\t\t\t\tentry.type === \"custom\" ||\n\t\t\t\tentry.type === \"model_change\" ||\n\t\t\t\tentry.type === \"thinking_level_change\" ||\n\t\t\t\tentry.type === \"session_info\";\n\n\t\t\tswitch (this.filterMode) {\n\t\t\t\tcase \"user-only\":\n\t\t\t\t\t// Just user messages\n\t\t\t\t\tpassesFilter = entry.type === \"message\" && entry.message.role === \"user\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"no-tools\":\n\t\t\t\t\t// Default minus tool results\n\t\t\t\t\tpassesFilter = !isSettingsEntry && !(entry.type === \"message\" && entry.message.role === \"toolResult\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"labeled-only\":\n\t\t\t\t\t// Just labeled entries\n\t\t\t\t\tpassesFilter = flatNode.node.label !== undefined;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"all\":\n\t\t\t\t\t// Show everything\n\t\t\t\t\tpassesFilter = true;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t// Default mode: hide settings/bookkeeping entries\n\t\t\t\t\tpassesFilter = !isSettingsEntry;\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!passesFilter) return false;\n\n\t\t\t// Apply search filter\n\t\t\tif (searchTokens.length > 0) {\n\t\t\t\tconst nodeText = this.getSearchableText(flatNode.node).toLowerCase();\n\t\t\t\treturn searchTokens.every((token) => nodeText.includes(token));\n\t\t\t}\n\n\t\t\treturn true;\n\t\t});\n\n\t\t// Filter out descendants of folded nodes.\n\t\tif (this.foldedNodes.size > 0) {\n\t\t\tconst skipSet = new Set();\n\t\t\tfor (const flatNode of this.flatNodes) {\n\t\t\t\tconst { id, parentId } = flatNode.node.entry;\n\t\t\t\tif (parentId != null && (this.foldedNodes.has(parentId) || skipSet.has(parentId))) {\n\t\t\t\t\tskipSet.add(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.filteredNodes = this.filteredNodes.filter((flatNode) => !skipSet.has(flatNode.node.entry.id));\n\t\t}\n\n\t\t// Recalculate visual structure (indent, connectors, gutters) based on visible tree\n\t\tthis.recalculateVisualStructure();\n\n\t\t// Try to preserve cursor on the same node, or find nearest visible ancestor\n\t\tif (this.lastSelectedId) {\n\t\t\tthis.selectedIndex = this.findNearestVisibleIndex(this.lastSelectedId);\n\t\t} else if (this.selectedIndex >= this.filteredNodes.length) {\n\t\t\t// Clamp index if out of bounds\n\t\t\tthis.selectedIndex = Math.max(0, this.filteredNodes.length - 1);\n\t\t}\n\n\t\t// Update lastSelectedId to the actual selection (may have changed due to parent walk)\n\t\tif (this.filteredNodes.length > 0) {\n\t\t\tthis.lastSelectedId = this.filteredNodes[this.selectedIndex]?.node.entry.id ?? this.lastSelectedId;\n\t\t}\n\t}\n\n\t/**\n\t * Recompute indentation/connectors for the filtered view\n\t *\n\t * Filtering can hide intermediate entries; descendants attach to the nearest visible ancestor.\n\t * Keep indentation semantics aligned with flattenTree() so single-child chains don't drift right.\n\t */\n\tprivate recalculateVisualStructure(): void {\n\t\tif (this.filteredNodes.length === 0) return;\n\n\t\tconst visibleIds = new Set(this.filteredNodes.map((n) => n.node.entry.id));\n\n\t\t// Build entry map for efficient parent lookup (using full tree)\n\t\tconst entryMap = new Map();\n\t\tfor (const flatNode of this.flatNodes) {\n\t\t\tentryMap.set(flatNode.node.entry.id, flatNode);\n\t\t}\n\n\t\t// Find nearest visible ancestor for a node\n\t\tconst findVisibleAncestor = (nodeId: string): string | null => {\n\t\t\tlet currentId = entryMap.get(nodeId)?.node.entry.parentId ?? null;\n\t\t\twhile (currentId !== null) {\n\t\t\t\tif (visibleIds.has(currentId)) {\n\t\t\t\t\treturn currentId;\n\t\t\t\t}\n\t\t\t\tcurrentId = entryMap.get(currentId)?.node.entry.parentId ?? null;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\n\t\t// Build visible tree structure:\n\t\t// - visibleParent: nodeId → nearest visible ancestor (or null for roots)\n\t\t// - visibleChildren: parentId → list of visible children (in filteredNodes order)\n\t\tconst visibleParent = new Map();\n\t\tconst visibleChildren = new Map();\n\t\tvisibleChildren.set(null, []); // root-level nodes\n\n\t\tfor (const flatNode of this.filteredNodes) {\n\t\t\tconst nodeId = flatNode.node.entry.id;\n\t\t\tconst ancestorId = findVisibleAncestor(nodeId);\n\t\t\tvisibleParent.set(nodeId, ancestorId);\n\n\t\t\tif (!visibleChildren.has(ancestorId)) {\n\t\t\t\tvisibleChildren.set(ancestorId, []);\n\t\t\t}\n\t\t\tvisibleChildren.get(ancestorId)!.push(nodeId);\n\t\t}\n\n\t\t// Update multipleRoots based on visible roots\n\t\tconst visibleRootIds = visibleChildren.get(null)!;\n\t\tthis.multipleRoots = visibleRootIds.length > 1;\n\n\t\t// Build a map for quick lookup: nodeId → FlatNode\n\t\tconst filteredNodeMap = new Map();\n\t\tfor (const flatNode of this.filteredNodes) {\n\t\t\tfilteredNodeMap.set(flatNode.node.entry.id, flatNode);\n\t\t}\n\n\t\t// DFS over the visible tree using flattenTree() indentation semantics\n\t\t// Stack items: [nodeId, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild]\n\t\ttype StackItem = [string, number, boolean, boolean, boolean, GutterInfo[], boolean];\n\t\tconst stack: StackItem[] = [];\n\n\t\t// Add visible roots in reverse order (to process in forward order via stack)\n\t\tfor (let i = visibleRootIds.length - 1; i >= 0; i--) {\n\t\t\tconst isLast = i === visibleRootIds.length - 1;\n\t\t\tstack.push([\n\t\t\t\tvisibleRootIds[i],\n\t\t\t\tthis.multipleRoots ? 1 : 0,\n\t\t\t\tthis.multipleRoots,\n\t\t\t\tthis.multipleRoots,\n\t\t\t\tisLast,\n\t\t\t\t[],\n\t\t\t\tthis.multipleRoots,\n\t\t\t]);\n\t\t}\n\n\t\twhile (stack.length > 0) {\n\t\t\tconst [nodeId, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] = stack.pop()!;\n\n\t\t\tconst flatNode = filteredNodeMap.get(nodeId);\n\t\t\tif (!flatNode) continue;\n\n\t\t\t// Update this node's visual properties\n\t\t\tflatNode.indent = indent;\n\t\t\tflatNode.showConnector = showConnector;\n\t\t\tflatNode.isLast = isLast;\n\t\t\tflatNode.gutters = gutters;\n\t\t\tflatNode.isVirtualRootChild = isVirtualRootChild;\n\n\t\t\t// Get visible children of this node\n\t\t\tconst children = visibleChildren.get(nodeId) || [];\n\t\t\tconst multipleChildren = children.length > 1;\n\n\t\t\t// Child indent follows flattenTree(): branch points (and first generation after a branch) shift +1\n\t\t\tlet childIndent: number;\n\t\t\tif (multipleChildren) {\n\t\t\t\tchildIndent = indent + 1;\n\t\t\t} else if (justBranched && indent > 0) {\n\t\t\t\tchildIndent = indent + 1;\n\t\t\t} else {\n\t\t\t\tchildIndent = indent;\n\t\t\t}\n\n\t\t\t// Child gutters follow flattenTree() connector/gutter rules\n\t\t\tconst connectorDisplayed = showConnector && !isVirtualRootChild;\n\t\t\tconst currentDisplayIndent = this.multipleRoots ? Math.max(0, indent - 1) : indent;\n\t\t\tconst connectorPosition = Math.max(0, currentDisplayIndent - 1);\n\t\t\tconst childGutters: GutterInfo[] = connectorDisplayed\n\t\t\t\t? [...gutters, { position: connectorPosition, show: !isLast }]\n\t\t\t\t: gutters;\n\n\t\t\t// Add children in reverse order (to process in forward order via stack)\n\t\t\tfor (let i = children.length - 1; i >= 0; i--) {\n\t\t\t\tconst childIsLast = i === children.length - 1;\n\t\t\t\tstack.push([\n\t\t\t\t\tchildren[i],\n\t\t\t\t\tchildIndent,\n\t\t\t\t\tmultipleChildren,\n\t\t\t\t\tmultipleChildren,\n\t\t\t\t\tchildIsLast,\n\t\t\t\t\tchildGutters,\n\t\t\t\t\tfalse,\n\t\t\t\t]);\n\t\t\t}\n\t\t}\n\n\t\t// Store visible tree maps for ancestor/descendant lookups in navigation\n\t\tthis.visibleParentMap = visibleParent;\n\t\tthis.visibleChildrenMap = visibleChildren;\n\t}\n\n\t/** Get searchable text content from a node */\n\tprivate getSearchableText(node: SessionTreeNode): string {\n\t\tconst entry = node.entry;\n\t\tconst parts: string[] = [];\n\n\t\tif (node.label) {\n\t\t\tparts.push(node.label);\n\t\t}\n\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst msg = entry.message;\n\t\t\t\tparts.push(msg.role);\n\t\t\t\tif (\"content\" in msg && msg.content) {\n\t\t\t\t\tparts.push(this.extractContent(msg.content));\n\t\t\t\t}\n\t\t\t\tif (msg.role === \"bashExecution\") {\n\t\t\t\t\tconst bashMsg = msg as { command?: string };\n\t\t\t\t\tif (bashMsg.command) parts.push(bashMsg.command);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"custom_message\": {\n\t\t\t\tparts.push(entry.customType);\n\t\t\t\tif (typeof entry.content === \"string\") {\n\t\t\t\t\tparts.push(entry.content);\n\t\t\t\t} else {\n\t\t\t\t\tparts.push(this.extractContent(entry.content));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"compaction\":\n\t\t\t\tparts.push(\"compaction\");\n\t\t\t\tbreak;\n\t\t\tcase \"branch_summary\":\n\t\t\t\tparts.push(\"branch summary\", entry.summary);\n\t\t\t\tbreak;\n\t\t\tcase \"session_info\":\n\t\t\t\tparts.push(\"title\");\n\t\t\t\tif (entry.name) parts.push(entry.name);\n\t\t\t\tbreak;\n\t\t\tcase \"model_change\":\n\t\t\t\tparts.push(\"model\", entry.modelId);\n\t\t\t\tbreak;\n\t\t\tcase \"thinking_level_change\":\n\t\t\t\tparts.push(\"thinking\", entry.thinkingLevel);\n\t\t\t\tbreak;\n\t\t\tcase \"custom\":\n\t\t\t\tparts.push(\"custom\", entry.customType);\n\t\t\t\tbreak;\n\t\t\tcase \"label\":\n\t\t\t\tparts.push(\"label\", entry.label ?? \"\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn parts.join(\" \");\n\t}\n\n\tinvalidate(): void {}\n\n\tgetSearchQuery(): string {\n\t\treturn this.searchQuery;\n\t}\n\n\tgetSelectedNode(): SessionTreeNode | undefined {\n\t\treturn this.filteredNodes[this.selectedIndex]?.node;\n\t}\n\n\tcopySelected(): void {\n\t\tconst node = this.getSelectedNode();\n\t\tthis.onCopy?.(node ? this.getEntryCopyText(node) : undefined);\n\t}\n\n\tupdateNodeLabel(entryId: string, label: string | undefined, labelTimestamp?: string): void {\n\t\tfor (const flatNode of this.flatNodes) {\n\t\t\tif (flatNode.node.entry.id === entryId) {\n\t\t\t\tflatNode.node.label = label;\n\t\t\t\tflatNode.node.labelTimestamp = label ? (labelTimestamp ?? new Date().toISOString()) : undefined;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate getStatusLabels(): string {\n\t\tlet labels = \"\";\n\t\tswitch (this.filterMode) {\n\t\t\tcase \"no-tools\":\n\t\t\t\tlabels += \" [no-tools]\";\n\t\t\t\tbreak;\n\t\t\tcase \"user-only\":\n\t\t\t\tlabels += \" [user]\";\n\t\t\t\tbreak;\n\t\t\tcase \"labeled-only\":\n\t\t\t\tlabels += \" [labeled]\";\n\t\t\t\tbreak;\n\t\t\tcase \"all\":\n\t\t\t\tlabels += \" [all]\";\n\t\t\t\tbreak;\n\t\t}\n\t\tif (this.showLabelTimestamps) {\n\t\t\tlabels += \" [+label time]\";\n\t\t}\n\t\treturn labels;\n\t}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\n\t\tif (this.filteredNodes.length === 0) {\n\t\t\tlines.push(truncateToWidth(theme.fg(\"muted\", \" No entries found\"), width));\n\t\t\tlines.push(truncateToWidth(theme.fg(\"muted\", ` (0/0)${this.getStatusLabels()}`), width));\n\t\t\treturn lines;\n\t\t}\n\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(\n\t\t\t\tthis.selectedIndex - Math.floor(this.maxVisibleLines / 2),\n\t\t\t\tthis.filteredNodes.length - this.maxVisibleLines,\n\t\t\t),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisibleLines, this.filteredNodes.length);\n\n\t\tconst renderedRows: HorizontalViewportRow[] = [];\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst flatNode = this.filteredNodes[i];\n\t\t\tconst entry = flatNode.node.entry;\n\t\t\tconst isSelected = i === this.selectedIndex;\n\n\t\t\t// Build line: cursor + prefix + path marker + label + content\n\t\t\tconst cursor = isSelected ? theme.fg(\"accent\", \"› \") : \" \";\n\n\t\t\t// If multiple roots, shift display (roots at 0, not 1)\n\t\t\tconst displayIndent = this.multipleRoots ? Math.max(0, flatNode.indent - 1) : flatNode.indent;\n\n\t\t\t// Build prefix with gutters at their correct positions\n\t\t\t// Each gutter has a position (displayIndent where its connector was shown)\n\t\t\tconst connector =\n\t\t\t\tflatNode.showConnector && !flatNode.isVirtualRootChild ? (flatNode.isLast ? \"└─ \" : \"├─ \") : \"\";\n\t\t\tconst connectorPosition = connector ? displayIndent - 1 : -1;\n\n\t\t\t// Build prefix char by char, placing gutters and connector at their positions\n\t\t\tconst totalChars = displayIndent * 3;\n\t\t\tconst prefixChars: string[] = [];\n\t\t\tconst isFolded = this.foldedNodes.has(entry.id);\n\t\t\tfor (let i = 0; i < totalChars; i++) {\n\t\t\t\tconst level = Math.floor(i / 3);\n\t\t\t\tconst posInLevel = i % 3;\n\n\t\t\t\t// Check if there's a gutter at this level\n\t\t\t\tconst gutter = flatNode.gutters.find((g) => g.position === level);\n\t\t\t\tif (gutter) {\n\t\t\t\t\tif (posInLevel === 0) {\n\t\t\t\t\t\tprefixChars.push(gutter.show ? \"│\" : \" \");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprefixChars.push(\" \");\n\t\t\t\t\t}\n\t\t\t\t} else if (connector && level === connectorPosition) {\n\t\t\t\t\t// Connector at this level, with fold indicator\n\t\t\t\t\tif (posInLevel === 0) {\n\t\t\t\t\t\tprefixChars.push(flatNode.isLast ? \"└\" : \"├\");\n\t\t\t\t\t} else if (posInLevel === 1) {\n\t\t\t\t\t\tconst foldable = this.isFoldable(entry.id);\n\t\t\t\t\t\tprefixChars.push(isFolded ? \"⊞\" : foldable ? \"⊟\" : \"─\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprefixChars.push(\" \");\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tprefixChars.push(\" \");\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst prefix = prefixChars.join(\"\");\n\n\t\t\t// Fold marker for nodes without connectors (roots)\n\t\t\tconst showsFoldInConnector = flatNode.showConnector && !flatNode.isVirtualRootChild;\n\t\t\tconst foldMarker = isFolded && !showsFoldInConnector ? theme.fg(\"accent\", \"⊞ \") : \"\";\n\n\t\t\t// Active path marker - shown right before the entry text\n\t\t\tconst isOnActivePath = this.activePathIds.has(entry.id);\n\t\t\tconst pathMarker = isOnActivePath ? theme.fg(\"accent\", \"• \") : \"\";\n\n\t\t\tconst label = flatNode.node.label ? theme.fg(\"warning\", `[${flatNode.node.label}] `) : \"\";\n\t\t\tconst labelTimestamp =\n\t\t\t\tthis.showLabelTimestamps && flatNode.node.label && flatNode.node.labelTimestamp\n\t\t\t\t\t? theme.fg(\"muted\", `${this.formatLabelTimestamp(flatNode.node.labelTimestamp)} `)\n\t\t\t\t\t: \"\";\n\t\t\tconst content = this.getEntryDisplayText(flatNode.node, isSelected);\n\t\t\tconst prefixPart = theme.fg(\"dim\", prefix) + foldMarker + pathMarker;\n\t\t\tconst anchorCol = visibleWidth(prefixPart);\n\t\t\tlet gutter = cursor;\n\t\t\tlet body = prefixPart + label + labelTimestamp + content;\n\t\t\tif (isSelected) {\n\t\t\t\tgutter = theme.bg(\"selectedBg\", gutter);\n\t\t\t\tbody = theme.bg(\"selectedBg\", body);\n\t\t\t}\n\t\t\trenderedRows.push({ gutter, body, anchorCol, bodyWidth: visibleWidth(body), isSelected });\n\t\t}\n\n\t\tlines.push(...renderHorizontalViewport(renderedRows, width));\n\t\tlines.push(\n\t\t\ttruncateToWidth(\n\t\t\t\ttheme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.filteredNodes.length})${this.getStatusLabels()}`),\n\t\t\t\twidth,\n\t\t\t),\n\t\t);\n\n\t\treturn lines;\n\t}\n\n\tprivate getEntryDisplayText(node: SessionTreeNode, isSelected: boolean): string {\n\t\tconst entry = node.entry;\n\t\tlet result: string;\n\n\t\tconst normalize = (s: string) => s.replace(/[\\n\\t]/g, \" \").trim();\n\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst msg = entry.message;\n\t\t\t\tconst role = msg.role;\n\t\t\t\tif (role === \"user\") {\n\t\t\t\t\tconst msgWithContent = msg as { content?: unknown };\n\t\t\t\t\tconst content = normalize(this.extractContent(msgWithContent.content));\n\t\t\t\t\tresult = theme.fg(\"accent\", \"user: \") + content;\n\t\t\t\t} else if (role === \"assistant\") {\n\t\t\t\t\tconst msgWithContent = msg as { content?: unknown; stopReason?: string; errorMessage?: string };\n\t\t\t\t\tconst textContent = normalize(this.extractContent(msgWithContent.content));\n\t\t\t\t\tif (textContent) {\n\t\t\t\t\t\tresult = theme.fg(\"success\", \"assistant: \") + textContent;\n\t\t\t\t\t} else if (msgWithContent.stopReason === \"aborted\") {\n\t\t\t\t\t\tresult = theme.fg(\"success\", \"assistant: \") + theme.fg(\"muted\", \"(aborted)\");\n\t\t\t\t\t} else if (msgWithContent.errorMessage) {\n\t\t\t\t\t\tconst errMsg = normalize(msgWithContent.errorMessage).slice(0, 80);\n\t\t\t\t\t\tresult = theme.fg(\"success\", \"assistant: \") + theme.fg(\"error\", errMsg);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresult = theme.fg(\"success\", \"assistant: \") + theme.fg(\"muted\", \"(no content)\");\n\t\t\t\t\t}\n\t\t\t\t} else if (role === \"toolResult\") {\n\t\t\t\t\tconst toolMsg = msg as { toolCallId?: string; toolName?: string };\n\t\t\t\t\tconst toolCall = toolMsg.toolCallId ? this.toolCallMap.get(toolMsg.toolCallId) : undefined;\n\t\t\t\t\tif (toolCall) {\n\t\t\t\t\t\tresult = theme.fg(\"muted\", this.formatToolCall(toolCall.name, toolCall.arguments));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresult = theme.fg(\"muted\", `[${toolMsg.toolName ?? \"tool\"}]`);\n\t\t\t\t\t}\n\t\t\t\t} else if (role === \"bashExecution\") {\n\t\t\t\t\tconst bashMsg = msg as { command?: string };\n\t\t\t\t\tresult = theme.fg(\"dim\", `[bash]: ${normalize(bashMsg.command ?? \"\")}`);\n\t\t\t\t} else {\n\t\t\t\t\tresult = theme.fg(\"dim\", `[${role}]`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"custom_message\": {\n\t\t\t\tconst content =\n\t\t\t\t\ttypeof entry.content === \"string\"\n\t\t\t\t\t\t? entry.content\n\t\t\t\t\t\t: entry.content\n\t\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t\t.join(\"\");\n\t\t\t\tresult = theme.fg(\"customMessageLabel\", `[${entry.customType}]: `) + normalize(content);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"compaction\": {\n\t\t\t\tconst tokens = Math.round(entry.tokensBefore / 1000);\n\t\t\t\tresult = theme.fg(\"borderAccent\", `[compaction: ${tokens}k tokens]`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"branch_summary\":\n\t\t\t\tresult = theme.fg(\"warning\", `[branch summary]: `) + normalize(entry.summary);\n\t\t\t\tbreak;\n\t\t\tcase \"model_change\":\n\t\t\t\tresult = theme.fg(\"dim\", `[model: ${entry.modelId}]`);\n\t\t\t\tbreak;\n\t\t\tcase \"thinking_level_change\":\n\t\t\t\tresult = theme.fg(\"dim\", `[thinking: ${entry.thinkingLevel}]`);\n\t\t\t\tbreak;\n\t\t\tcase \"custom\":\n\t\t\t\tresult = theme.fg(\"dim\", `[custom: ${entry.customType}]`);\n\t\t\t\tbreak;\n\t\t\tcase \"label\":\n\t\t\t\tresult = theme.fg(\"dim\", `[label: ${entry.label ?? \"(cleared)\"}]`);\n\t\t\t\tbreak;\n\t\t\tcase \"session_info\":\n\t\t\t\tresult = entry.name\n\t\t\t\t\t? [theme.fg(\"dim\", \"[title: \"), theme.fg(\"dim\", entry.name), theme.fg(\"dim\", \"]\")].join(\"\")\n\t\t\t\t\t: [theme.fg(\"dim\", \"[title: \"), theme.italic(theme.fg(\"dim\", \"empty\")), theme.fg(\"dim\", \"]\")].join(\"\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tresult = \"\";\n\t\t}\n\n\t\treturn isSelected ? theme.bold(result) : result;\n\t}\n\n\tprivate formatLabelTimestamp(timestamp: string): string {\n\t\tconst date = new Date(timestamp);\n\t\tconst now = new Date();\n\t\tconst hours = date.getHours().toString().padStart(2, \"0\");\n\t\tconst minutes = date.getMinutes().toString().padStart(2, \"0\");\n\t\tconst time = `${hours}:${minutes}`;\n\n\t\tif (\n\t\t\tdate.getFullYear() === now.getFullYear() &&\n\t\t\tdate.getMonth() === now.getMonth() &&\n\t\t\tdate.getDate() === now.getDate()\n\t\t) {\n\t\t\treturn time;\n\t\t}\n\n\t\tconst month = date.getMonth() + 1;\n\t\tconst day = date.getDate();\n\t\tif (date.getFullYear() === now.getFullYear()) {\n\t\t\treturn `${month}/${day} ${time}`;\n\t\t}\n\n\t\tconst year = date.getFullYear().toString().slice(-2);\n\t\treturn `${year}/${month}/${day} ${time}`;\n\t}\n\n\tprivate extractContent(content: unknown): string {\n\t\treturn this.extractFullContent(content).slice(0, 200);\n\t}\n\n\tprivate extractFullContent(content: unknown): string {\n\t\tif (typeof content === \"string\") return content;\n\t\tif (!Array.isArray(content)) return \"\";\n\n\t\tlet result = \"\";\n\t\tfor (const block of content) {\n\t\t\tif (typeof block === \"object\" && block !== null && \"type\" in block && block.type === \"text\") {\n\t\t\t\tresult += (block as { text: string }).text;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate getEntryCopyText(node: SessionTreeNode): string | undefined {\n\t\tconst entry = node.entry;\n\t\tlet text: string | undefined;\n\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\":\n\t\t\t\tif (entry.message.role === \"bashExecution\") {\n\t\t\t\t\ttext = entry.message.command;\n\t\t\t\t} else if (\"content\" in entry.message) {\n\t\t\t\t\ttext = this.extractFullContent(entry.message.content);\n\t\t\t\t\tif (!text && entry.message.role === \"assistant\") {\n\t\t\t\t\t\ttext = entry.message.errorMessage;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"custom_message\":\n\t\t\t\ttext = this.extractFullContent(entry.content);\n\t\t\t\tbreak;\n\t\t\tcase \"compaction\":\n\t\t\t\ttext = entry.summary;\n\t\t\t\tbreak;\n\t\t\tcase \"branch_summary\":\n\t\t\t\ttext = entry.summary;\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn text?.trim() ? text : undefined;\n\t}\n\n\tprivate hasTextContent(content: unknown): boolean {\n\t\tif (typeof content === \"string\") return content.trim().length > 0;\n\t\tif (Array.isArray(content)) {\n\t\t\tfor (const c of content) {\n\t\t\t\tif (typeof c === \"object\" && c !== null && \"type\" in c && c.type === \"text\") {\n\t\t\t\t\tconst text = (c as { text?: string }).text;\n\t\t\t\t\tif (text && text.trim().length > 0) return true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate formatToolCall(name: string, args: Record): string {\n\t\tconst shortenPath = (p: string): string => {\n\t\t\tconst home = process.env.HOME || process.env.USERPROFILE || \"\";\n\t\t\tif (home && p.startsWith(home)) return `~${p.slice(home.length)}`;\n\t\t\treturn p;\n\t\t};\n\n\t\tswitch (name) {\n\t\t\tcase \"read\": {\n\t\t\t\tconst path = shortenPath(String(args.path || args.file_path || \"\"));\n\t\t\t\tconst offset = args.offset as number | undefined;\n\t\t\t\tconst limit = args.limit as number | undefined;\n\t\t\t\tlet display = path;\n\t\t\t\tif (offset !== undefined || limit !== undefined) {\n\t\t\t\t\tconst start = offset ?? 1;\n\t\t\t\t\tconst end = limit !== undefined ? start + limit - 1 : \"\";\n\t\t\t\t\tdisplay += `:${start}${end ? `-${end}` : \"\"}`;\n\t\t\t\t}\n\t\t\t\treturn `[read: ${display}]`;\n\t\t\t}\n\t\t\tcase \"write\": {\n\t\t\t\tconst path = shortenPath(String(args.path || args.file_path || \"\"));\n\t\t\t\treturn `[write: ${path}]`;\n\t\t\t}\n\t\t\tcase \"edit\": {\n\t\t\t\tconst path = shortenPath(String(args.path || args.file_path || \"\"));\n\t\t\t\treturn `[edit: ${path}]`;\n\t\t\t}\n\t\t\tcase \"bash\": {\n\t\t\t\tconst rawCmd = String(args.command || \"\");\n\t\t\t\tconst cmd = rawCmd\n\t\t\t\t\t.replace(/[\\n\\t]/g, \" \")\n\t\t\t\t\t.trim()\n\t\t\t\t\t.slice(0, 50);\n\t\t\t\treturn `[bash: ${cmd}${rawCmd.length > 50 ? \"...\" : \"\"}]`;\n\t\t\t}\n\t\t\tcase \"grep\": {\n\t\t\t\tconst pattern = String(args.pattern || \"\");\n\t\t\t\tconst path = shortenPath(String(args.path || \".\"));\n\t\t\t\treturn `[grep: /${pattern}/ in ${path}]`;\n\t\t\t}\n\t\t\tcase \"find\": {\n\t\t\t\tconst pattern = String(args.pattern || \"\");\n\t\t\t\tconst path = shortenPath(String(args.path || \".\"));\n\t\t\t\treturn `[find: ${pattern} in ${path}]`;\n\t\t\t}\n\t\t\tcase \"ls\": {\n\t\t\t\tconst path = shortenPath(String(args.path || \".\"));\n\t\t\t\treturn `[ls: ${path}]`;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\t// Custom tool - show name and truncated JSON args\n\t\t\t\tconst argsStr = JSON.stringify(args).slice(0, 40);\n\t\t\t\treturn `[${name}: ${argsStr}${JSON.stringify(args).length > 40 ? \"...\" : \"\"}]`;\n\t\t\t}\n\t\t}\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"tui.select.up\")) {\n\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.filteredNodes.length - 1 : this.selectedIndex - 1;\n\t\t} else if (kb.matches(keyData, \"tui.select.down\")) {\n\t\t\tthis.selectedIndex = this.selectedIndex === this.filteredNodes.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t} else if (kb.matches(keyData, \"app.tree.foldOrUp\")) {\n\t\t\tconst currentId = this.filteredNodes[this.selectedIndex]?.node.entry.id;\n\t\t\tif (currentId && this.isFoldable(currentId) && !this.foldedNodes.has(currentId)) {\n\t\t\t\tthis.foldedNodes.add(currentId);\n\t\t\t\tthis.applyFilter();\n\t\t\t} else {\n\t\t\t\tthis.selectedIndex = this.findBranchSegmentStart(\"up\");\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"app.tree.unfoldOrDown\")) {\n\t\t\tconst currentId = this.filteredNodes[this.selectedIndex]?.node.entry.id;\n\t\t\tif (currentId && this.foldedNodes.has(currentId)) {\n\t\t\t\tthis.foldedNodes.delete(currentId);\n\t\t\t\tthis.applyFilter();\n\t\t\t} else {\n\t\t\t\tthis.selectedIndex = this.findBranchSegmentStart(\"down\");\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"tui.editor.cursorLeft\") || kb.matches(keyData, \"tui.select.pageUp\")) {\n\t\t\t// Page up\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - this.maxVisibleLines);\n\t\t} else if (kb.matches(keyData, \"tui.editor.cursorRight\") || kb.matches(keyData, \"tui.select.pageDown\")) {\n\t\t\t// Page down\n\t\t\tthis.selectedIndex = Math.min(this.filteredNodes.length - 1, this.selectedIndex + this.maxVisibleLines);\n\t\t} else if (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\tconst selected = this.filteredNodes[this.selectedIndex];\n\t\t\tif (selected && this.onSelect) {\n\t\t\t\tthis.onSelect(selected.node.entry.id);\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"app.message.copy\")) {\n\t\t\tthis.copySelected();\n\t\t} else if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tif (this.searchQuery) {\n\t\t\t\tthis.searchQuery = \"\";\n\t\t\t\tthis.foldedNodes.clear();\n\t\t\t\tthis.applyFilter();\n\t\t\t} else {\n\t\t\t\tthis.onCancel?.();\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.default\")) {\n\t\t\t// Direct filter: default\n\t\t\tthis.filterMode = \"default\";\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.noTools\")) {\n\t\t\t// Toggle filter: no-tools ↔ default\n\t\t\tthis.filterMode = this.filterMode === \"no-tools\" ? \"default\" : \"no-tools\";\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.userOnly\")) {\n\t\t\t// Toggle filter: user-only ↔ default\n\t\t\tthis.filterMode = this.filterMode === \"user-only\" ? \"default\" : \"user-only\";\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.labeledOnly\")) {\n\t\t\t// Toggle filter: labeled-only ↔ default\n\t\t\tthis.filterMode = this.filterMode === \"labeled-only\" ? \"default\" : \"labeled-only\";\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.all\")) {\n\t\t\t// Toggle filter: all ↔ default\n\t\t\tthis.filterMode = this.filterMode === \"all\" ? \"default\" : \"all\";\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.cycleBackward\")) {\n\t\t\t// Cycle filter backwards\n\t\t\tconst modes: FilterMode[] = [\"default\", \"no-tools\", \"user-only\", \"labeled-only\", \"all\"];\n\t\t\tconst currentIndex = modes.indexOf(this.filterMode);\n\t\t\tthis.filterMode = modes[(currentIndex - 1 + modes.length) % modes.length];\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.cycleForward\")) {\n\t\t\t// Cycle filter forwards: default → no-tools → user-only → labeled-only → all → default\n\t\t\tconst modes: FilterMode[] = [\"default\", \"no-tools\", \"user-only\", \"labeled-only\", \"all\"];\n\t\t\tconst currentIndex = modes.indexOf(this.filterMode);\n\t\t\tthis.filterMode = modes[(currentIndex + 1) % modes.length];\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"tui.editor.deleteCharBackward\")) {\n\t\t\tif (this.searchQuery.length > 0) {\n\t\t\t\tthis.searchQuery = this.searchQuery.slice(0, -1);\n\t\t\t\tthis.foldedNodes.clear();\n\t\t\t\tthis.applyFilter();\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"app.tree.editLabel\")) {\n\t\t\tconst selected = this.filteredNodes[this.selectedIndex];\n\t\t\tif (selected && this.onLabelEdit) {\n\t\t\t\tthis.onLabelEdit(selected.node.entry.id, selected.node.label);\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"app.tree.toggleLabelTimestamp\")) {\n\t\t\tthis.showLabelTimestamps = !this.showLabelTimestamps;\n\t\t} else {\n\t\t\tconst hasControlChars = [...keyData].some((ch) => {\n\t\t\t\tconst code = ch.charCodeAt(0);\n\t\t\t\treturn code < 32 || code === 0x7f || (code >= 0x80 && code <= 0x9f);\n\t\t\t});\n\t\t\tif (!hasControlChars && keyData.length > 0) {\n\t\t\t\tthis.searchQuery += keyData;\n\t\t\t\tthis.foldedNodes.clear();\n\t\t\t\tthis.applyFilter();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Whether a node can be folded. A node is foldable if it has visible children\n\t * and is either a root (no visible parent) or a segment start (visible parent\n\t * has multiple visible children).\n\t */\n\tprivate isFoldable(entryId: string): boolean {\n\t\tconst children = this.visibleChildrenMap.get(entryId);\n\t\tif (!children || children.length === 0) return false;\n\t\tconst parentId = this.visibleParentMap.get(entryId);\n\t\tif (parentId === null || parentId === undefined) return true;\n\t\tconst siblings = this.visibleChildrenMap.get(parentId);\n\t\treturn siblings !== undefined && siblings.length > 1;\n\t}\n\n\t/**\n\t * Find the index of the next branch segment start in the given direction.\n\t * A segment start is the first child of a branch point.\n\t *\n\t * \"up\" walks the visible parent chain; \"down\" walks visible children\n\t * (always following the first child).\n\t */\n\tprivate findBranchSegmentStart(direction: \"up\" | \"down\"): number {\n\t\tconst selectedId = this.filteredNodes[this.selectedIndex]?.node.entry.id;\n\t\tif (!selectedId) return this.selectedIndex;\n\n\t\tconst indexByEntryId = new Map(this.filteredNodes.map((node, i) => [node.node.entry.id, i]));\n\t\tlet currentId: string = selectedId;\n\t\tif (direction === \"down\") {\n\t\t\twhile (true) {\n\t\t\t\tconst children: string[] = this.visibleChildrenMap.get(currentId) ?? [];\n\t\t\t\tif (children.length === 0) return indexByEntryId.get(currentId)!;\n\t\t\t\tif (children.length > 1) return indexByEntryId.get(children[0])!;\n\t\t\t\tcurrentId = children[0];\n\t\t\t}\n\t\t}\n\n\t\t// direction === \"up\"\n\t\twhile (true) {\n\t\t\tconst parentId: string | null = this.visibleParentMap.get(currentId) ?? null;\n\t\t\tif (parentId === null) return indexByEntryId.get(currentId)!;\n\t\t\tconst children = this.visibleChildrenMap.get(parentId) ?? [];\n\t\t\tif (children.length > 1) {\n\t\t\t\tconst segmentStart = indexByEntryId.get(currentId)!;\n\t\t\t\tif (segmentStart < this.selectedIndex) {\n\t\t\t\t\treturn segmentStart;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurrentId = parentId;\n\t\t}\n\t}\n}\n\n/** Component that displays the current search query */\nclass SearchLine implements Component {\n\tprivate treeList: TreeList;\n\n\tconstructor(treeList: TreeList) {\n\t\tthis.treeList = treeList;\n\t}\n\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst query = this.treeList.getSearchQuery();\n\t\tif (query) {\n\t\t\treturn [truncateToWidth(` ${theme.fg(\"muted\", \"Type to search:\")} ${theme.fg(\"accent\", query)}`, width)];\n\t\t}\n\t\treturn [truncateToWidth(` ${theme.fg(\"muted\", \"Type to search:\")}`, width)];\n\t}\n\n\thandleInput(_keyData: string): void {}\n}\n\n/** Component that renders tree help as semantic rows with chunk-aware wrapping */\nclass TreeHelp implements Component {\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst items = TREE_HELP_ITEMS.map(({ keys, label, labelFirst }) => {\n\t\t\tconst text = formatHelpKeys(keys);\n\t\t\tif (!text) return label;\n\t\t\treturn labelFirst ? `${label} ${text}` : `${text} ${label}`;\n\t\t});\n\n\t\tconst availableWidth = Math.max(1, width);\n\t\tconst indent = \" \";\n\t\tconst separator = \" · \";\n\t\tconst lines: string[] = [];\n\t\tlet currentLine = \"\";\n\n\t\tfor (const item of items) {\n\t\t\tconst candidate = currentLine\n\t\t\t\t? `${currentLine}${separator}${item}`\n\t\t\t\t: visibleWidth(`${indent}${item}`) <= availableWidth\n\t\t\t\t\t? `${indent}${item}`\n\t\t\t\t\t: item;\n\t\t\tif (!currentLine || visibleWidth(candidate) <= availableWidth) {\n\t\t\t\tcurrentLine = candidate;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tlines.push(...wrapTextWithAnsi(currentLine.trimEnd(), availableWidth));\n\t\t\tcurrentLine = visibleWidth(`${indent}${item}`) <= availableWidth ? `${indent}${item}` : item;\n\t\t}\n\n\t\tif (currentLine) {\n\t\t\tlines.push(...wrapTextWithAnsi(currentLine.trimEnd(), availableWidth));\n\t\t}\n\n\t\treturn lines.map((line) => theme.fg(\"muted\", line));\n\t}\n}\n\nconst TREE_HELP_ITEMS: Array<{ keys: Keybinding[]; label: string; labelFirst?: boolean }> = [\n\t{ keys: [\"tui.select.up\", \"tui.select.down\"], label: \"move\" },\n\t{ keys: [\"tui.editor.cursorLeft\", \"tui.editor.cursorRight\"], label: \"page\" },\n\t{ keys: [\"app.tree.foldOrUp\", \"app.tree.unfoldOrDown\"], label: \"branch\" },\n\t{ keys: [\"app.message.copy\"], label: \"copy\" },\n\t{ keys: [\"app.tree.editLabel\"], label: \"label\" },\n\t{ keys: [\"app.tree.toggleLabelTimestamp\"], label: \"label time\" },\n\t{\n\t\tkeys: [\n\t\t\t\"app.tree.filter.default\",\n\t\t\t\"app.tree.filter.noTools\",\n\t\t\t\"app.tree.filter.userOnly\",\n\t\t\t\"app.tree.filter.labeledOnly\",\n\t\t\t\"app.tree.filter.all\",\n\t\t],\n\t\tlabel: \"filters\",\n\t\tlabelFirst: true,\n\t},\n\t{ keys: [\"app.tree.filter.cycleForward\", \"app.tree.filter.cycleBackward\"], label: \"cycle\", labelFirst: true },\n];\n\nfunction formatHelpKeys(keybindings: Keybinding[]): string {\n\tconst keys: string[] = [];\n\tfor (const keybinding of keybindings) {\n\t\tconst key = getKeybindings().getKeys(keybinding)[0];\n\t\tif (key !== undefined) keys.push(key);\n\t}\n\tif (keys.length === 0) return \"\";\n\n\treturn formatKeyText(compactRawKeys(keys))\n\t\t.replace(/\\bpageUp\\b/g, \"pgup\")\n\t\t.replace(/\\bpageDown\\b/g, \"pgdn\")\n\t\t.replace(/\\bup\\b/g, \"↑\")\n\t\t.replace(/\\bdown\\b/g, \"↓\")\n\t\t.replace(/\\bleft\\b/g, \"←\")\n\t\t.replace(/\\bright\\b/g, \"→\");\n}\n\nfunction compactRawKeys(keys: string[]): string {\n\tif (keys.length === 1) return keys[0]!;\n\n\tconst parts = keys.map((key) => {\n\t\tconst separatorIndex = key.lastIndexOf(\"+\");\n\t\treturn separatorIndex === -1\n\t\t\t? { prefix: \"\", suffix: key }\n\t\t\t: { prefix: key.slice(0, separatorIndex + 1), suffix: key.slice(separatorIndex + 1) };\n\t});\n\tconst prefix = parts[0]!.prefix;\n\treturn prefix && parts.every((part) => part.prefix === prefix)\n\t\t? `${prefix}${parts.map((part) => part.suffix).join(\"/\")}`\n\t\t: keys.join(\"/\");\n}\n\n/** Label input component shown when editing a label */\nclass LabelInput implements Component, Focusable {\n\tprivate input: Input;\n\tprivate entryId: string;\n\tpublic onSubmit?: (entryId: string, label: string | undefined) => void;\n\tpublic onCancel?: () => void;\n\n\t// Focusable implementation - propagate to input for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.input.focused = value;\n\t}\n\n\tconstructor(entryId: string, currentLabel: string | undefined) {\n\t\tthis.entryId = entryId;\n\t\tthis.input = new Input();\n\t\tif (currentLabel) {\n\t\t\tthis.input.setValue(currentLabel);\n\t\t}\n\t}\n\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\t\tconst indent = \" \";\n\t\tconst availableWidth = width - indent.length;\n\t\tlines.push(truncateToWidth(`${indent}${theme.fg(\"muted\", \"Label (empty to remove):\")}`, width));\n\t\tlines.push(...this.input.render(availableWidth).map((line) => truncateToWidth(`${indent}${line}`, width)));\n\t\tlines.push(\n\t\t\ttruncateToWidth(\n\t\t\t\t`${indent}${keyHint(\"tui.select.confirm\", \"save\")} ${keyHint(\"tui.select.cancel\", \"cancel\")}`,\n\t\t\t\twidth,\n\t\t\t),\n\t\t);\n\t\treturn lines;\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\tconst value = this.input.getValue().trim();\n\t\t\tthis.onSubmit?.(this.entryId, value || undefined);\n\t\t} else if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.onCancel?.();\n\t\t} else {\n\t\t\tthis.input.handleInput(keyData);\n\t\t}\n\t}\n}\n\n/**\n * Component that renders a session tree selector for navigation\n */\nexport class TreeSelectorComponent extends Container implements Focusable {\n\tprivate treeList: TreeList;\n\tprivate labelInput: LabelInput | null = null;\n\tprivate labelInputContainer: Container;\n\tprivate treeContainer: Container;\n\tprivate onLabelChangeCallback?: (entryId: string, label: string | undefined) => void;\n\tpublic onCopy?: (text: string | undefined) => void;\n\n\t// Focusable implementation - propagate to labelInput when active for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\t// Propagate to labelInput when it's active\n\t\tif (this.labelInput) {\n\t\t\tthis.labelInput.focused = value;\n\t\t}\n\t}\n\n\tconstructor(\n\t\ttree: SessionTreeNode[],\n\t\tcurrentLeafId: string | null,\n\t\tterminalHeight: number,\n\t\tonSelect: (entryId: string) => void,\n\t\tonCancel: () => void,\n\t\tonLabelChange?: (entryId: string, label: string | undefined) => void,\n\t\tinitialSelectedId?: string,\n\t\tinitialFilterMode?: FilterMode,\n\t) {\n\t\tsuper();\n\n\t\tthis.onLabelChangeCallback = onLabelChange;\n\t\tconst maxVisibleLines = Math.max(5, Math.floor(terminalHeight / 2));\n\n\t\tthis.treeList = new TreeList(tree, currentLeafId, maxVisibleLines, initialSelectedId, initialFilterMode);\n\t\tthis.treeList.onSelect = onSelect;\n\t\tthis.treeList.onCancel = onCancel;\n\t\tthis.treeList.onCopy = (text) => this.onCopy?.(text);\n\t\tthis.treeList.onLabelEdit = (entryId, currentLabel) => this.showLabelInput(entryId, currentLabel);\n\n\t\tthis.treeContainer = new Container();\n\t\tthis.treeContainer.addChild(this.treeList);\n\n\t\tthis.labelInputContainer = new Container();\n\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Text(theme.bold(\" Session Tree\"), 1, 0));\n\t\tthis.addChild(new TreeHelp());\n\t\tthis.addChild(new SearchLine(this.treeList));\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(this.treeContainer);\n\t\tthis.addChild(this.labelInputContainer);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\tif (tree.length === 0) {\n\t\t\tsetTimeout(() => onCancel(), 100);\n\t\t}\n\t}\n\n\tprivate showLabelInput(entryId: string, currentLabel: string | undefined): void {\n\t\tthis.labelInput = new LabelInput(entryId, currentLabel);\n\t\tthis.labelInput.onSubmit = (id, label) => {\n\t\t\tthis.treeList.updateNodeLabel(id, label);\n\t\t\tthis.onLabelChangeCallback?.(id, label);\n\t\t\tthis.hideLabelInput();\n\t\t};\n\t\tthis.labelInput.onCancel = () => this.hideLabelInput();\n\n\t\t// Propagate current focused state to the new labelInput\n\t\tthis.labelInput.focused = this._focused;\n\n\t\tthis.treeContainer.clear();\n\t\tthis.labelInputContainer.clear();\n\t\tthis.labelInputContainer.addChild(this.labelInput);\n\t}\n\n\tprivate hideLabelInput(): void {\n\t\tthis.labelInput = null;\n\t\tthis.labelInputContainer.clear();\n\t\tthis.treeContainer.clear();\n\t\tthis.treeContainer.addChild(this.treeList);\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tif (this.labelInput) {\n\t\t\tthis.labelInput.handleInput(keyData);\n\t\t} else {\n\t\t\tthis.treeList.handleInput(keyData);\n\t\t}\n\t}\n\n\tgetTreeList(): TreeList {\n\t\treturn this.treeList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/tree-selector.js b/dist/modes/interactive/components/tree-selector.js new file mode 100644 index 0000000..96ec667 --- /dev/null +++ b/dist/modes/interactive/components/tree-selector.js @@ -0,0 +1,1245 @@ +import { Container, getKeybindings, Input, Spacer, sliceByColumn, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui"; +import { theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { formatKeyText, keyHint } from "./keybinding-hints.js"; +const TREE_GUTTER_WIDTH = 2; +const MIN_VISIBLE_ANCHOR_CONTENT_WIDTH = 4; +const MAX_VISIBLE_ANCHOR_CONTENT_WIDTH = 20; +const MIN_ANCHOR_CONTEXT_WIDTH = 2; +const MAX_ANCHOR_CONTEXT_WIDTH = 12; +/** + * Render tree rows into a horizontally clipped viewport. + * + * The tree gutter is always kept visible. The row bodies are shifted left only + * when the selected row's anchor (the start of its entry text after tree + * indentation/markers) would otherwise be too far right to see useful content. + */ +function renderHorizontalViewport(rows, width) { + const viewportWidth = Math.max(0, width - TREE_GUTTER_WIDTH); + const maxBodyWidth = rows.reduce((max, row) => Math.max(max, row.bodyWidth), 0); + const maxHorizontalScroll = Math.max(0, maxBodyWidth - viewportWidth); + const selectedRow = rows.find((row) => row.isSelected); + // Only pan horizontally when needed to keep enough selected-row content visible after its anchor. + let horizontalScroll = 0; + if (selectedRow && maxHorizontalScroll > 0) { + const minVisibleAnchorContentWidth = Math.min(MAX_VISIBLE_ANCHOR_CONTENT_WIDTH, Math.max(MIN_VISIBLE_ANCHOR_CONTENT_WIDTH, Math.floor(viewportWidth / 3))); + if (selectedRow.anchorCol > viewportWidth - minVisibleAnchorContentWidth) { + const anchorContextWidth = Math.min(MAX_ANCHOR_CONTEXT_WIDTH, Math.max(MIN_ANCHOR_CONTEXT_WIDTH, Math.floor(viewportWidth / 4))); + horizontalScroll = Math.min(maxHorizontalScroll, selectedRow.anchorCol - anchorContextWidth); + } + } + // Clip only the body; the fixed-width gutter remains visible as navigation context. + return rows.map((row) => { + const line = horizontalScroll > 0 + ? `${row.gutter}${sliceByColumn(row.body, horizontalScroll, viewportWidth, true)}\x1b[0m` + : row.gutter + row.body; + return truncateToWidth(line, width, ""); + }); +} +class TreeList { + flatNodes = []; + filteredNodes = []; + selectedIndex = 0; + currentLeafId; + maxVisibleLines; + filterMode = "default"; + searchQuery = ""; + toolCallMap = new Map(); + multipleRoots = false; + showLabelTimestamps = false; + activePathIds = new Set(); + visibleParentMap = new Map(); + visibleChildrenMap = new Map(); + lastSelectedId = null; + foldedNodes = new Set(); + onSelect; + onCancel; + onCopy; + onLabelEdit; + constructor(tree, currentLeafId, maxVisibleLines, initialSelectedId, initialFilterMode) { + this.currentLeafId = currentLeafId; + this.maxVisibleLines = maxVisibleLines; + this.filterMode = initialFilterMode ?? "default"; + this.multipleRoots = tree.length > 1; + this.flatNodes = this.flattenTree(tree); + this.buildActivePath(); + this.applyFilter(); + // Start with initialSelectedId if provided, otherwise current leaf + const targetId = initialSelectedId ?? currentLeafId; + this.selectedIndex = this.findNearestVisibleIndex(targetId); + this.lastSelectedId = this.filteredNodes[this.selectedIndex]?.node.entry.id ?? null; + } + /** + * Find the index of the nearest visible entry, walking up the parent chain if needed. + * Returns the index in filteredNodes, or the last index as fallback. + */ + findNearestVisibleIndex(entryId) { + if (this.filteredNodes.length === 0) + return 0; + // Build a map for parent lookup + const entryMap = new Map(); + for (const flatNode of this.flatNodes) { + entryMap.set(flatNode.node.entry.id, flatNode); + } + // Build a map of visible entry IDs to their indices in filteredNodes + const visibleIdToIndex = new Map(this.filteredNodes.map((node, i) => [node.node.entry.id, i])); + // Walk from entryId up to root, looking for a visible entry + let currentId = entryId; + while (currentId !== null) { + const index = visibleIdToIndex.get(currentId); + if (index !== undefined) + return index; + const node = entryMap.get(currentId); + if (!node) + break; + currentId = node.node.entry.parentId ?? null; + } + // Fallback: last visible entry + return this.filteredNodes.length - 1; + } + /** Build the set of entry IDs on the path from root to current leaf */ + buildActivePath() { + this.activePathIds.clear(); + if (!this.currentLeafId) + return; + // Build a map of id -> entry for parent lookup + const entryMap = new Map(); + for (const flatNode of this.flatNodes) { + entryMap.set(flatNode.node.entry.id, flatNode); + } + // Walk from leaf to root + let currentId = this.currentLeafId; + while (currentId) { + this.activePathIds.add(currentId); + const node = entryMap.get(currentId); + if (!node) + break; + currentId = node.node.entry.parentId ?? null; + } + } + flattenTree(roots) { + const result = []; + this.toolCallMap.clear(); + const stack = []; + // Determine which subtrees contain the active leaf (to sort current branch first) + // Use iterative post-order traversal to avoid stack overflow + const containsActive = new Map(); + const leafId = this.currentLeafId; + { + // Build list in pre-order, then process in reverse for post-order effect + const allNodes = []; + const preOrderStack = [...roots]; + while (preOrderStack.length > 0) { + const node = preOrderStack.pop(); + allNodes.push(node); + // Push children in reverse so they're processed left-to-right + for (let i = node.children.length - 1; i >= 0; i--) { + preOrderStack.push(node.children[i]); + } + } + // Process in reverse (post-order): children before parents + for (let i = allNodes.length - 1; i >= 0; i--) { + const node = allNodes[i]; + let has = leafId !== null && node.entry.id === leafId; + for (const child of node.children) { + if (containsActive.get(child)) { + has = true; + } + } + containsActive.set(node, has); + } + } + // Add roots in reverse order, prioritizing the one containing the active leaf + // If multiple roots, treat them as children of a virtual root that branches + const multipleRoots = roots.length > 1; + const orderedRoots = [...roots].sort((a, b) => Number(containsActive.get(b)) - Number(containsActive.get(a))); + for (let i = orderedRoots.length - 1; i >= 0; i--) { + const isLast = i === orderedRoots.length - 1; + stack.push([orderedRoots[i], multipleRoots ? 1 : 0, multipleRoots, multipleRoots, isLast, [], multipleRoots]); + } + while (stack.length > 0) { + const [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] = stack.pop(); + // Extract tool calls from assistant messages for later lookup + const entry = node.entry; + if (entry.type === "message" && entry.message.role === "assistant") { + const content = entry.message.content; + if (Array.isArray(content)) { + for (const block of content) { + if (typeof block === "object" && block !== null && "type" in block && block.type === "toolCall") { + const tc = block; + this.toolCallMap.set(tc.id, { name: tc.name, arguments: tc.arguments }); + } + } + } + } + result.push({ node, indent, showConnector, isLast, gutters, isVirtualRootChild }); + const children = node.children; + const multipleChildren = children.length > 1; + // Order children so the branch containing the active leaf comes first + const orderedChildren = (() => { + const prioritized = []; + const rest = []; + for (const child of children) { + if (containsActive.get(child)) { + prioritized.push(child); + } + else { + rest.push(child); + } + } + return [...prioritized, ...rest]; + })(); + // Calculate child indent + let childIndent; + if (multipleChildren) { + // Parent branches: children get +1 + childIndent = indent + 1; + } + else if (justBranched && indent > 0) { + // First generation after a branch: +1 for visual grouping + childIndent = indent + 1; + } + else { + // Single-child chain: stay flat + childIndent = indent; + } + // Build gutters for children + // If this node showed a connector, add a gutter entry for descendants + // Only add gutter if connector is actually displayed (not suppressed for virtual root children) + const connectorDisplayed = showConnector && !isVirtualRootChild; + // When connector is displayed, add a gutter entry at the connector's position + // Connector is at position (displayIndent - 1), so gutter should be there too + const currentDisplayIndent = this.multipleRoots ? Math.max(0, indent - 1) : indent; + const connectorPosition = Math.max(0, currentDisplayIndent - 1); + const childGutters = connectorDisplayed + ? [...gutters, { position: connectorPosition, show: !isLast }] + : gutters; + // Add children in reverse order + for (let i = orderedChildren.length - 1; i >= 0; i--) { + const childIsLast = i === orderedChildren.length - 1; + stack.push([ + orderedChildren[i], + childIndent, + multipleChildren, + multipleChildren, + childIsLast, + childGutters, + false, + ]); + } + } + return result; + } + applyFilter() { + // Update lastSelectedId only when we have a valid selection (non-empty list) + // This preserves the selection when switching through empty filter results + if (this.filteredNodes.length > 0) { + this.lastSelectedId = this.filteredNodes[this.selectedIndex]?.node.entry.id ?? this.lastSelectedId; + } + const searchTokens = this.searchQuery.toLowerCase().split(/\s+/).filter(Boolean); + this.filteredNodes = this.flatNodes.filter((flatNode) => { + const entry = flatNode.node.entry; + const isCurrentLeaf = entry.id === this.currentLeafId; + // Skip assistant messages with only tool calls (no text) unless error/aborted + // Always show current leaf so active position is visible + if (entry.type === "message" && entry.message.role === "assistant" && !isCurrentLeaf) { + const msg = entry.message; + const hasText = this.hasTextContent(msg.content); + const isErrorOrAborted = msg.stopReason && msg.stopReason !== "stop" && msg.stopReason !== "toolUse"; + // Only hide if no text AND not an error/aborted message + if (!hasText && !isErrorOrAborted) { + return false; + } + } + // Apply filter mode + let passesFilter = true; + // Entry types hidden in default view (settings/bookkeeping) + const isSettingsEntry = entry.type === "label" || + entry.type === "custom" || + entry.type === "model_change" || + entry.type === "thinking_level_change" || + entry.type === "session_info"; + switch (this.filterMode) { + case "user-only": + // Just user messages + passesFilter = entry.type === "message" && entry.message.role === "user"; + break; + case "no-tools": + // Default minus tool results + passesFilter = !isSettingsEntry && !(entry.type === "message" && entry.message.role === "toolResult"); + break; + case "labeled-only": + // Just labeled entries + passesFilter = flatNode.node.label !== undefined; + break; + case "all": + // Show everything + passesFilter = true; + break; + default: + // Default mode: hide settings/bookkeeping entries + passesFilter = !isSettingsEntry; + break; + } + if (!passesFilter) + return false; + // Apply search filter + if (searchTokens.length > 0) { + const nodeText = this.getSearchableText(flatNode.node).toLowerCase(); + return searchTokens.every((token) => nodeText.includes(token)); + } + return true; + }); + // Filter out descendants of folded nodes. + if (this.foldedNodes.size > 0) { + const skipSet = new Set(); + for (const flatNode of this.flatNodes) { + const { id, parentId } = flatNode.node.entry; + if (parentId != null && (this.foldedNodes.has(parentId) || skipSet.has(parentId))) { + skipSet.add(id); + } + } + this.filteredNodes = this.filteredNodes.filter((flatNode) => !skipSet.has(flatNode.node.entry.id)); + } + // Recalculate visual structure (indent, connectors, gutters) based on visible tree + this.recalculateVisualStructure(); + // Try to preserve cursor on the same node, or find nearest visible ancestor + if (this.lastSelectedId) { + this.selectedIndex = this.findNearestVisibleIndex(this.lastSelectedId); + } + else if (this.selectedIndex >= this.filteredNodes.length) { + // Clamp index if out of bounds + this.selectedIndex = Math.max(0, this.filteredNodes.length - 1); + } + // Update lastSelectedId to the actual selection (may have changed due to parent walk) + if (this.filteredNodes.length > 0) { + this.lastSelectedId = this.filteredNodes[this.selectedIndex]?.node.entry.id ?? this.lastSelectedId; + } + } + /** + * Recompute indentation/connectors for the filtered view + * + * Filtering can hide intermediate entries; descendants attach to the nearest visible ancestor. + * Keep indentation semantics aligned with flattenTree() so single-child chains don't drift right. + */ + recalculateVisualStructure() { + if (this.filteredNodes.length === 0) + return; + const visibleIds = new Set(this.filteredNodes.map((n) => n.node.entry.id)); + // Build entry map for efficient parent lookup (using full tree) + const entryMap = new Map(); + for (const flatNode of this.flatNodes) { + entryMap.set(flatNode.node.entry.id, flatNode); + } + // Find nearest visible ancestor for a node + const findVisibleAncestor = (nodeId) => { + let currentId = entryMap.get(nodeId)?.node.entry.parentId ?? null; + while (currentId !== null) { + if (visibleIds.has(currentId)) { + return currentId; + } + currentId = entryMap.get(currentId)?.node.entry.parentId ?? null; + } + return null; + }; + // Build visible tree structure: + // - visibleParent: nodeId → nearest visible ancestor (or null for roots) + // - visibleChildren: parentId → list of visible children (in filteredNodes order) + const visibleParent = new Map(); + const visibleChildren = new Map(); + visibleChildren.set(null, []); // root-level nodes + for (const flatNode of this.filteredNodes) { + const nodeId = flatNode.node.entry.id; + const ancestorId = findVisibleAncestor(nodeId); + visibleParent.set(nodeId, ancestorId); + if (!visibleChildren.has(ancestorId)) { + visibleChildren.set(ancestorId, []); + } + visibleChildren.get(ancestorId).push(nodeId); + } + // Update multipleRoots based on visible roots + const visibleRootIds = visibleChildren.get(null); + this.multipleRoots = visibleRootIds.length > 1; + // Build a map for quick lookup: nodeId → FlatNode + const filteredNodeMap = new Map(); + for (const flatNode of this.filteredNodes) { + filteredNodeMap.set(flatNode.node.entry.id, flatNode); + } + const stack = []; + // Add visible roots in reverse order (to process in forward order via stack) + for (let i = visibleRootIds.length - 1; i >= 0; i--) { + const isLast = i === visibleRootIds.length - 1; + stack.push([ + visibleRootIds[i], + this.multipleRoots ? 1 : 0, + this.multipleRoots, + this.multipleRoots, + isLast, + [], + this.multipleRoots, + ]); + } + while (stack.length > 0) { + const [nodeId, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] = stack.pop(); + const flatNode = filteredNodeMap.get(nodeId); + if (!flatNode) + continue; + // Update this node's visual properties + flatNode.indent = indent; + flatNode.showConnector = showConnector; + flatNode.isLast = isLast; + flatNode.gutters = gutters; + flatNode.isVirtualRootChild = isVirtualRootChild; + // Get visible children of this node + const children = visibleChildren.get(nodeId) || []; + const multipleChildren = children.length > 1; + // Child indent follows flattenTree(): branch points (and first generation after a branch) shift +1 + let childIndent; + if (multipleChildren) { + childIndent = indent + 1; + } + else if (justBranched && indent > 0) { + childIndent = indent + 1; + } + else { + childIndent = indent; + } + // Child gutters follow flattenTree() connector/gutter rules + const connectorDisplayed = showConnector && !isVirtualRootChild; + const currentDisplayIndent = this.multipleRoots ? Math.max(0, indent - 1) : indent; + const connectorPosition = Math.max(0, currentDisplayIndent - 1); + const childGutters = connectorDisplayed + ? [...gutters, { position: connectorPosition, show: !isLast }] + : gutters; + // Add children in reverse order (to process in forward order via stack) + for (let i = children.length - 1; i >= 0; i--) { + const childIsLast = i === children.length - 1; + stack.push([ + children[i], + childIndent, + multipleChildren, + multipleChildren, + childIsLast, + childGutters, + false, + ]); + } + } + // Store visible tree maps for ancestor/descendant lookups in navigation + this.visibleParentMap = visibleParent; + this.visibleChildrenMap = visibleChildren; + } + /** Get searchable text content from a node */ + getSearchableText(node) { + const entry = node.entry; + const parts = []; + if (node.label) { + parts.push(node.label); + } + switch (entry.type) { + case "message": { + const msg = entry.message; + parts.push(msg.role); + if ("content" in msg && msg.content) { + parts.push(this.extractContent(msg.content)); + } + if (msg.role === "bashExecution") { + const bashMsg = msg; + if (bashMsg.command) + parts.push(bashMsg.command); + } + break; + } + case "custom_message": { + parts.push(entry.customType); + if (typeof entry.content === "string") { + parts.push(entry.content); + } + else { + parts.push(this.extractContent(entry.content)); + } + break; + } + case "compaction": + parts.push("compaction"); + break; + case "branch_summary": + parts.push("branch summary", entry.summary); + break; + case "session_info": + parts.push("title"); + if (entry.name) + parts.push(entry.name); + break; + case "model_change": + parts.push("model", entry.modelId); + break; + case "thinking_level_change": + parts.push("thinking", entry.thinkingLevel); + break; + case "custom": + parts.push("custom", entry.customType); + break; + case "label": + parts.push("label", entry.label ?? ""); + break; + } + return parts.join(" "); + } + invalidate() { } + getSearchQuery() { + return this.searchQuery; + } + getSelectedNode() { + return this.filteredNodes[this.selectedIndex]?.node; + } + copySelected() { + const node = this.getSelectedNode(); + this.onCopy?.(node ? this.getEntryCopyText(node) : undefined); + } + updateNodeLabel(entryId, label, labelTimestamp) { + for (const flatNode of this.flatNodes) { + if (flatNode.node.entry.id === entryId) { + flatNode.node.label = label; + flatNode.node.labelTimestamp = label ? (labelTimestamp ?? new Date().toISOString()) : undefined; + break; + } + } + } + getStatusLabels() { + let labels = ""; + switch (this.filterMode) { + case "no-tools": + labels += " [no-tools]"; + break; + case "user-only": + labels += " [user]"; + break; + case "labeled-only": + labels += " [labeled]"; + break; + case "all": + labels += " [all]"; + break; + } + if (this.showLabelTimestamps) { + labels += " [+label time]"; + } + return labels; + } + render(width) { + const lines = []; + if (this.filteredNodes.length === 0) { + lines.push(truncateToWidth(theme.fg("muted", " No entries found"), width)); + lines.push(truncateToWidth(theme.fg("muted", ` (0/0)${this.getStatusLabels()}`), width)); + return lines; + } + const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(this.maxVisibleLines / 2), this.filteredNodes.length - this.maxVisibleLines)); + const endIndex = Math.min(startIndex + this.maxVisibleLines, this.filteredNodes.length); + const renderedRows = []; + for (let i = startIndex; i < endIndex; i++) { + const flatNode = this.filteredNodes[i]; + const entry = flatNode.node.entry; + const isSelected = i === this.selectedIndex; + // Build line: cursor + prefix + path marker + label + content + const cursor = isSelected ? theme.fg("accent", "› ") : " "; + // If multiple roots, shift display (roots at 0, not 1) + const displayIndent = this.multipleRoots ? Math.max(0, flatNode.indent - 1) : flatNode.indent; + // Build prefix with gutters at their correct positions + // Each gutter has a position (displayIndent where its connector was shown) + const connector = flatNode.showConnector && !flatNode.isVirtualRootChild ? (flatNode.isLast ? "└─ " : "├─ ") : ""; + const connectorPosition = connector ? displayIndent - 1 : -1; + // Build prefix char by char, placing gutters and connector at their positions + const totalChars = displayIndent * 3; + const prefixChars = []; + const isFolded = this.foldedNodes.has(entry.id); + for (let i = 0; i < totalChars; i++) { + const level = Math.floor(i / 3); + const posInLevel = i % 3; + // Check if there's a gutter at this level + const gutter = flatNode.gutters.find((g) => g.position === level); + if (gutter) { + if (posInLevel === 0) { + prefixChars.push(gutter.show ? "│" : " "); + } + else { + prefixChars.push(" "); + } + } + else if (connector && level === connectorPosition) { + // Connector at this level, with fold indicator + if (posInLevel === 0) { + prefixChars.push(flatNode.isLast ? "└" : "├"); + } + else if (posInLevel === 1) { + const foldable = this.isFoldable(entry.id); + prefixChars.push(isFolded ? "⊞" : foldable ? "⊟" : "─"); + } + else { + prefixChars.push(" "); + } + } + else { + prefixChars.push(" "); + } + } + const prefix = prefixChars.join(""); + // Fold marker for nodes without connectors (roots) + const showsFoldInConnector = flatNode.showConnector && !flatNode.isVirtualRootChild; + const foldMarker = isFolded && !showsFoldInConnector ? theme.fg("accent", "⊞ ") : ""; + // Active path marker - shown right before the entry text + const isOnActivePath = this.activePathIds.has(entry.id); + const pathMarker = isOnActivePath ? theme.fg("accent", "• ") : ""; + const label = flatNode.node.label ? theme.fg("warning", `[${flatNode.node.label}] `) : ""; + const labelTimestamp = this.showLabelTimestamps && flatNode.node.label && flatNode.node.labelTimestamp + ? theme.fg("muted", `${this.formatLabelTimestamp(flatNode.node.labelTimestamp)} `) + : ""; + const content = this.getEntryDisplayText(flatNode.node, isSelected); + const prefixPart = theme.fg("dim", prefix) + foldMarker + pathMarker; + const anchorCol = visibleWidth(prefixPart); + let gutter = cursor; + let body = prefixPart + label + labelTimestamp + content; + if (isSelected) { + gutter = theme.bg("selectedBg", gutter); + body = theme.bg("selectedBg", body); + } + renderedRows.push({ gutter, body, anchorCol, bodyWidth: visibleWidth(body), isSelected }); + } + lines.push(...renderHorizontalViewport(renderedRows, width)); + lines.push(truncateToWidth(theme.fg("muted", ` (${this.selectedIndex + 1}/${this.filteredNodes.length})${this.getStatusLabels()}`), width)); + return lines; + } + getEntryDisplayText(node, isSelected) { + const entry = node.entry; + let result; + const normalize = (s) => s.replace(/[\n\t]/g, " ").trim(); + switch (entry.type) { + case "message": { + const msg = entry.message; + const role = msg.role; + if (role === "user") { + const msgWithContent = msg; + const content = normalize(this.extractContent(msgWithContent.content)); + result = theme.fg("accent", "user: ") + content; + } + else if (role === "assistant") { + const msgWithContent = msg; + const textContent = normalize(this.extractContent(msgWithContent.content)); + if (textContent) { + result = theme.fg("success", "assistant: ") + textContent; + } + else if (msgWithContent.stopReason === "aborted") { + result = theme.fg("success", "assistant: ") + theme.fg("muted", "(aborted)"); + } + else if (msgWithContent.errorMessage) { + const errMsg = normalize(msgWithContent.errorMessage).slice(0, 80); + result = theme.fg("success", "assistant: ") + theme.fg("error", errMsg); + } + else { + result = theme.fg("success", "assistant: ") + theme.fg("muted", "(no content)"); + } + } + else if (role === "toolResult") { + const toolMsg = msg; + const toolCall = toolMsg.toolCallId ? this.toolCallMap.get(toolMsg.toolCallId) : undefined; + if (toolCall) { + result = theme.fg("muted", this.formatToolCall(toolCall.name, toolCall.arguments)); + } + else { + result = theme.fg("muted", `[${toolMsg.toolName ?? "tool"}]`); + } + } + else if (role === "bashExecution") { + const bashMsg = msg; + result = theme.fg("dim", `[bash]: ${normalize(bashMsg.command ?? "")}`); + } + else { + result = theme.fg("dim", `[${role}]`); + } + break; + } + case "custom_message": { + const content = typeof entry.content === "string" + ? entry.content + : entry.content + .filter((c) => c.type === "text") + .map((c) => c.text) + .join(""); + result = theme.fg("customMessageLabel", `[${entry.customType}]: `) + normalize(content); + break; + } + case "compaction": { + const tokens = Math.round(entry.tokensBefore / 1000); + result = theme.fg("borderAccent", `[compaction: ${tokens}k tokens]`); + break; + } + case "branch_summary": + result = theme.fg("warning", `[branch summary]: `) + normalize(entry.summary); + break; + case "model_change": + result = theme.fg("dim", `[model: ${entry.modelId}]`); + break; + case "thinking_level_change": + result = theme.fg("dim", `[thinking: ${entry.thinkingLevel}]`); + break; + case "custom": + result = theme.fg("dim", `[custom: ${entry.customType}]`); + break; + case "label": + result = theme.fg("dim", `[label: ${entry.label ?? "(cleared)"}]`); + break; + case "session_info": + result = entry.name + ? [theme.fg("dim", "[title: "), theme.fg("dim", entry.name), theme.fg("dim", "]")].join("") + : [theme.fg("dim", "[title: "), theme.italic(theme.fg("dim", "empty")), theme.fg("dim", "]")].join(""); + break; + default: + result = ""; + } + return isSelected ? theme.bold(result) : result; + } + formatLabelTimestamp(timestamp) { + const date = new Date(timestamp); + const now = new Date(); + const hours = date.getHours().toString().padStart(2, "0"); + const minutes = date.getMinutes().toString().padStart(2, "0"); + const time = `${hours}:${minutes}`; + if (date.getFullYear() === now.getFullYear() && + date.getMonth() === now.getMonth() && + date.getDate() === now.getDate()) { + return time; + } + const month = date.getMonth() + 1; + const day = date.getDate(); + if (date.getFullYear() === now.getFullYear()) { + return `${month}/${day} ${time}`; + } + const year = date.getFullYear().toString().slice(-2); + return `${year}/${month}/${day} ${time}`; + } + extractContent(content) { + return this.extractFullContent(content).slice(0, 200); + } + extractFullContent(content) { + if (typeof content === "string") + return content; + if (!Array.isArray(content)) + return ""; + let result = ""; + for (const block of content) { + if (typeof block === "object" && block !== null && "type" in block && block.type === "text") { + result += block.text; + } + } + return result; + } + getEntryCopyText(node) { + const entry = node.entry; + let text; + switch (entry.type) { + case "message": + if (entry.message.role === "bashExecution") { + text = entry.message.command; + } + else if ("content" in entry.message) { + text = this.extractFullContent(entry.message.content); + if (!text && entry.message.role === "assistant") { + text = entry.message.errorMessage; + } + } + break; + case "custom_message": + text = this.extractFullContent(entry.content); + break; + case "compaction": + text = entry.summary; + break; + case "branch_summary": + text = entry.summary; + break; + } + return text?.trim() ? text : undefined; + } + hasTextContent(content) { + if (typeof content === "string") + return content.trim().length > 0; + if (Array.isArray(content)) { + for (const c of content) { + if (typeof c === "object" && c !== null && "type" in c && c.type === "text") { + const text = c.text; + if (text && text.trim().length > 0) + return true; + } + } + } + return false; + } + formatToolCall(name, args) { + const shortenPath = (p) => { + const home = process.env.HOME || process.env.USERPROFILE || ""; + if (home && p.startsWith(home)) + return `~${p.slice(home.length)}`; + return p; + }; + switch (name) { + case "read": { + const path = shortenPath(String(args.path || args.file_path || "")); + const offset = args.offset; + const limit = args.limit; + let display = path; + if (offset !== undefined || limit !== undefined) { + const start = offset ?? 1; + const end = limit !== undefined ? start + limit - 1 : ""; + display += `:${start}${end ? `-${end}` : ""}`; + } + return `[read: ${display}]`; + } + case "write": { + const path = shortenPath(String(args.path || args.file_path || "")); + return `[write: ${path}]`; + } + case "edit": { + const path = shortenPath(String(args.path || args.file_path || "")); + return `[edit: ${path}]`; + } + case "bash": { + const rawCmd = String(args.command || ""); + const cmd = rawCmd + .replace(/[\n\t]/g, " ") + .trim() + .slice(0, 50); + return `[bash: ${cmd}${rawCmd.length > 50 ? "..." : ""}]`; + } + case "grep": { + const pattern = String(args.pattern || ""); + const path = shortenPath(String(args.path || ".")); + return `[grep: /${pattern}/ in ${path}]`; + } + case "find": { + const pattern = String(args.pattern || ""); + const path = shortenPath(String(args.path || ".")); + return `[find: ${pattern} in ${path}]`; + } + case "ls": { + const path = shortenPath(String(args.path || ".")); + return `[ls: ${path}]`; + } + default: { + // Custom tool - show name and truncated JSON args + const argsStr = JSON.stringify(args).slice(0, 40); + return `[${name}: ${argsStr}${JSON.stringify(args).length > 40 ? "..." : ""}]`; + } + } + } + handleInput(keyData) { + const kb = getKeybindings(); + if (kb.matches(keyData, "tui.select.up")) { + this.selectedIndex = this.selectedIndex === 0 ? this.filteredNodes.length - 1 : this.selectedIndex - 1; + } + else if (kb.matches(keyData, "tui.select.down")) { + this.selectedIndex = this.selectedIndex === this.filteredNodes.length - 1 ? 0 : this.selectedIndex + 1; + } + else if (kb.matches(keyData, "app.tree.foldOrUp")) { + const currentId = this.filteredNodes[this.selectedIndex]?.node.entry.id; + if (currentId && this.isFoldable(currentId) && !this.foldedNodes.has(currentId)) { + this.foldedNodes.add(currentId); + this.applyFilter(); + } + else { + this.selectedIndex = this.findBranchSegmentStart("up"); + } + } + else if (kb.matches(keyData, "app.tree.unfoldOrDown")) { + const currentId = this.filteredNodes[this.selectedIndex]?.node.entry.id; + if (currentId && this.foldedNodes.has(currentId)) { + this.foldedNodes.delete(currentId); + this.applyFilter(); + } + else { + this.selectedIndex = this.findBranchSegmentStart("down"); + } + } + else if (kb.matches(keyData, "tui.editor.cursorLeft") || kb.matches(keyData, "tui.select.pageUp")) { + // Page up + this.selectedIndex = Math.max(0, this.selectedIndex - this.maxVisibleLines); + } + else if (kb.matches(keyData, "tui.editor.cursorRight") || kb.matches(keyData, "tui.select.pageDown")) { + // Page down + this.selectedIndex = Math.min(this.filteredNodes.length - 1, this.selectedIndex + this.maxVisibleLines); + } + else if (kb.matches(keyData, "tui.select.confirm")) { + const selected = this.filteredNodes[this.selectedIndex]; + if (selected && this.onSelect) { + this.onSelect(selected.node.entry.id); + } + } + else if (kb.matches(keyData, "app.message.copy")) { + this.copySelected(); + } + else if (kb.matches(keyData, "tui.select.cancel")) { + if (this.searchQuery) { + this.searchQuery = ""; + this.foldedNodes.clear(); + this.applyFilter(); + } + else { + this.onCancel?.(); + } + } + else if (kb.matches(keyData, "app.tree.filter.default")) { + // Direct filter: default + this.filterMode = "default"; + this.foldedNodes.clear(); + this.applyFilter(); + } + else if (kb.matches(keyData, "app.tree.filter.noTools")) { + // Toggle filter: no-tools ↔ default + this.filterMode = this.filterMode === "no-tools" ? "default" : "no-tools"; + this.foldedNodes.clear(); + this.applyFilter(); + } + else if (kb.matches(keyData, "app.tree.filter.userOnly")) { + // Toggle filter: user-only ↔ default + this.filterMode = this.filterMode === "user-only" ? "default" : "user-only"; + this.foldedNodes.clear(); + this.applyFilter(); + } + else if (kb.matches(keyData, "app.tree.filter.labeledOnly")) { + // Toggle filter: labeled-only ↔ default + this.filterMode = this.filterMode === "labeled-only" ? "default" : "labeled-only"; + this.foldedNodes.clear(); + this.applyFilter(); + } + else if (kb.matches(keyData, "app.tree.filter.all")) { + // Toggle filter: all ↔ default + this.filterMode = this.filterMode === "all" ? "default" : "all"; + this.foldedNodes.clear(); + this.applyFilter(); + } + else if (kb.matches(keyData, "app.tree.filter.cycleBackward")) { + // Cycle filter backwards + const modes = ["default", "no-tools", "user-only", "labeled-only", "all"]; + const currentIndex = modes.indexOf(this.filterMode); + this.filterMode = modes[(currentIndex - 1 + modes.length) % modes.length]; + this.foldedNodes.clear(); + this.applyFilter(); + } + else if (kb.matches(keyData, "app.tree.filter.cycleForward")) { + // Cycle filter forwards: default → no-tools → user-only → labeled-only → all → default + const modes = ["default", "no-tools", "user-only", "labeled-only", "all"]; + const currentIndex = modes.indexOf(this.filterMode); + this.filterMode = modes[(currentIndex + 1) % modes.length]; + this.foldedNodes.clear(); + this.applyFilter(); + } + else if (kb.matches(keyData, "tui.editor.deleteCharBackward")) { + if (this.searchQuery.length > 0) { + this.searchQuery = this.searchQuery.slice(0, -1); + this.foldedNodes.clear(); + this.applyFilter(); + } + } + else if (kb.matches(keyData, "app.tree.editLabel")) { + const selected = this.filteredNodes[this.selectedIndex]; + if (selected && this.onLabelEdit) { + this.onLabelEdit(selected.node.entry.id, selected.node.label); + } + } + else if (kb.matches(keyData, "app.tree.toggleLabelTimestamp")) { + this.showLabelTimestamps = !this.showLabelTimestamps; + } + else { + const hasControlChars = [...keyData].some((ch) => { + const code = ch.charCodeAt(0); + return code < 32 || code === 0x7f || (code >= 0x80 && code <= 0x9f); + }); + if (!hasControlChars && keyData.length > 0) { + this.searchQuery += keyData; + this.foldedNodes.clear(); + this.applyFilter(); + } + } + } + /** + * Whether a node can be folded. A node is foldable if it has visible children + * and is either a root (no visible parent) or a segment start (visible parent + * has multiple visible children). + */ + isFoldable(entryId) { + const children = this.visibleChildrenMap.get(entryId); + if (!children || children.length === 0) + return false; + const parentId = this.visibleParentMap.get(entryId); + if (parentId === null || parentId === undefined) + return true; + const siblings = this.visibleChildrenMap.get(parentId); + return siblings !== undefined && siblings.length > 1; + } + /** + * Find the index of the next branch segment start in the given direction. + * A segment start is the first child of a branch point. + * + * "up" walks the visible parent chain; "down" walks visible children + * (always following the first child). + */ + findBranchSegmentStart(direction) { + const selectedId = this.filteredNodes[this.selectedIndex]?.node.entry.id; + if (!selectedId) + return this.selectedIndex; + const indexByEntryId = new Map(this.filteredNodes.map((node, i) => [node.node.entry.id, i])); + let currentId = selectedId; + if (direction === "down") { + while (true) { + const children = this.visibleChildrenMap.get(currentId) ?? []; + if (children.length === 0) + return indexByEntryId.get(currentId); + if (children.length > 1) + return indexByEntryId.get(children[0]); + currentId = children[0]; + } + } + // direction === "up" + while (true) { + const parentId = this.visibleParentMap.get(currentId) ?? null; + if (parentId === null) + return indexByEntryId.get(currentId); + const children = this.visibleChildrenMap.get(parentId) ?? []; + if (children.length > 1) { + const segmentStart = indexByEntryId.get(currentId); + if (segmentStart < this.selectedIndex) { + return segmentStart; + } + } + currentId = parentId; + } + } +} +/** Component that displays the current search query */ +class SearchLine { + treeList; + constructor(treeList) { + this.treeList = treeList; + } + invalidate() { } + render(width) { + const query = this.treeList.getSearchQuery(); + if (query) { + return [truncateToWidth(` ${theme.fg("muted", "Type to search:")} ${theme.fg("accent", query)}`, width)]; + } + return [truncateToWidth(` ${theme.fg("muted", "Type to search:")}`, width)]; + } + handleInput(_keyData) { } +} +/** Component that renders tree help as semantic rows with chunk-aware wrapping */ +class TreeHelp { + invalidate() { } + render(width) { + const items = TREE_HELP_ITEMS.map(({ keys, label, labelFirst }) => { + const text = formatHelpKeys(keys); + if (!text) + return label; + return labelFirst ? `${label} ${text}` : `${text} ${label}`; + }); + const availableWidth = Math.max(1, width); + const indent = " "; + const separator = " · "; + const lines = []; + let currentLine = ""; + for (const item of items) { + const candidate = currentLine + ? `${currentLine}${separator}${item}` + : visibleWidth(`${indent}${item}`) <= availableWidth + ? `${indent}${item}` + : item; + if (!currentLine || visibleWidth(candidate) <= availableWidth) { + currentLine = candidate; + continue; + } + lines.push(...wrapTextWithAnsi(currentLine.trimEnd(), availableWidth)); + currentLine = visibleWidth(`${indent}${item}`) <= availableWidth ? `${indent}${item}` : item; + } + if (currentLine) { + lines.push(...wrapTextWithAnsi(currentLine.trimEnd(), availableWidth)); + } + return lines.map((line) => theme.fg("muted", line)); + } +} +const TREE_HELP_ITEMS = [ + { keys: ["tui.select.up", "tui.select.down"], label: "move" }, + { keys: ["tui.editor.cursorLeft", "tui.editor.cursorRight"], label: "page" }, + { keys: ["app.tree.foldOrUp", "app.tree.unfoldOrDown"], label: "branch" }, + { keys: ["app.message.copy"], label: "copy" }, + { keys: ["app.tree.editLabel"], label: "label" }, + { keys: ["app.tree.toggleLabelTimestamp"], label: "label time" }, + { + keys: [ + "app.tree.filter.default", + "app.tree.filter.noTools", + "app.tree.filter.userOnly", + "app.tree.filter.labeledOnly", + "app.tree.filter.all", + ], + label: "filters", + labelFirst: true, + }, + { keys: ["app.tree.filter.cycleForward", "app.tree.filter.cycleBackward"], label: "cycle", labelFirst: true }, +]; +function formatHelpKeys(keybindings) { + const keys = []; + for (const keybinding of keybindings) { + const key = getKeybindings().getKeys(keybinding)[0]; + if (key !== undefined) + keys.push(key); + } + if (keys.length === 0) + return ""; + return formatKeyText(compactRawKeys(keys)) + .replace(/\bpageUp\b/g, "pgup") + .replace(/\bpageDown\b/g, "pgdn") + .replace(/\bup\b/g, "↑") + .replace(/\bdown\b/g, "↓") + .replace(/\bleft\b/g, "←") + .replace(/\bright\b/g, "→"); +} +function compactRawKeys(keys) { + if (keys.length === 1) + return keys[0]; + const parts = keys.map((key) => { + const separatorIndex = key.lastIndexOf("+"); + return separatorIndex === -1 + ? { prefix: "", suffix: key } + : { prefix: key.slice(0, separatorIndex + 1), suffix: key.slice(separatorIndex + 1) }; + }); + const prefix = parts[0].prefix; + return prefix && parts.every((part) => part.prefix === prefix) + ? `${prefix}${parts.map((part) => part.suffix).join("/")}` + : keys.join("/"); +} +/** Label input component shown when editing a label */ +class LabelInput { + input; + entryId; + onSubmit; + onCancel; + // Focusable implementation - propagate to input for IME cursor positioning + _focused = false; + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + this.input.focused = value; + } + constructor(entryId, currentLabel) { + this.entryId = entryId; + this.input = new Input(); + if (currentLabel) { + this.input.setValue(currentLabel); + } + } + invalidate() { } + render(width) { + const lines = []; + const indent = " "; + const availableWidth = width - indent.length; + lines.push(truncateToWidth(`${indent}${theme.fg("muted", "Label (empty to remove):")}`, width)); + lines.push(...this.input.render(availableWidth).map((line) => truncateToWidth(`${indent}${line}`, width))); + lines.push(truncateToWidth(`${indent}${keyHint("tui.select.confirm", "save")} ${keyHint("tui.select.cancel", "cancel")}`, width)); + return lines; + } + handleInput(keyData) { + const kb = getKeybindings(); + if (kb.matches(keyData, "tui.select.confirm")) { + const value = this.input.getValue().trim(); + this.onSubmit?.(this.entryId, value || undefined); + } + else if (kb.matches(keyData, "tui.select.cancel")) { + this.onCancel?.(); + } + else { + this.input.handleInput(keyData); + } + } +} +/** + * Component that renders a session tree selector for navigation + */ +export class TreeSelectorComponent extends Container { + treeList; + labelInput = null; + labelInputContainer; + treeContainer; + onLabelChangeCallback; + onCopy; + // Focusable implementation - propagate to labelInput when active for IME cursor positioning + _focused = false; + get focused() { + return this._focused; + } + set focused(value) { + this._focused = value; + // Propagate to labelInput when it's active + if (this.labelInput) { + this.labelInput.focused = value; + } + } + constructor(tree, currentLeafId, terminalHeight, onSelect, onCancel, onLabelChange, initialSelectedId, initialFilterMode) { + super(); + this.onLabelChangeCallback = onLabelChange; + const maxVisibleLines = Math.max(5, Math.floor(terminalHeight / 2)); + this.treeList = new TreeList(tree, currentLeafId, maxVisibleLines, initialSelectedId, initialFilterMode); + this.treeList.onSelect = onSelect; + this.treeList.onCancel = onCancel; + this.treeList.onCopy = (text) => this.onCopy?.(text); + this.treeList.onLabelEdit = (entryId, currentLabel) => this.showLabelInput(entryId, currentLabel); + this.treeContainer = new Container(); + this.treeContainer.addChild(this.treeList); + this.labelInputContainer = new Container(); + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder()); + this.addChild(new Text(theme.bold(" Session Tree"), 1, 0)); + this.addChild(new TreeHelp()); + this.addChild(new SearchLine(this.treeList)); + this.addChild(new DynamicBorder()); + this.addChild(new Spacer(1)); + this.addChild(this.treeContainer); + this.addChild(this.labelInputContainer); + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder()); + if (tree.length === 0) { + setTimeout(() => onCancel(), 100); + } + } + showLabelInput(entryId, currentLabel) { + this.labelInput = new LabelInput(entryId, currentLabel); + this.labelInput.onSubmit = (id, label) => { + this.treeList.updateNodeLabel(id, label); + this.onLabelChangeCallback?.(id, label); + this.hideLabelInput(); + }; + this.labelInput.onCancel = () => this.hideLabelInput(); + // Propagate current focused state to the new labelInput + this.labelInput.focused = this._focused; + this.treeContainer.clear(); + this.labelInputContainer.clear(); + this.labelInputContainer.addChild(this.labelInput); + } + hideLabelInput() { + this.labelInput = null; + this.labelInputContainer.clear(); + this.treeContainer.clear(); + this.treeContainer.addChild(this.treeList); + } + handleInput(keyData) { + if (this.labelInput) { + this.labelInput.handleInput(keyData); + } + else { + this.treeList.handleInput(keyData); + } + } + getTreeList() { + return this.treeList; + } +} +//# sourceMappingURL=tree-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/tree-selector.js.map b/dist/modes/interactive/components/tree-selector.js.map new file mode 100644 index 0000000..c268098 --- /dev/null +++ b/dist/modes/interactive/components/tree-selector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tree-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/tree-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,SAAS,EAET,cAAc,EACd,KAAK,EAEL,MAAM,EACN,aAAa,EACb,IAAI,EACJ,eAAe,EACf,YAAY,EACZ,gBAAgB,GAChB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AA+B/D,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAC5B,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAC3C,MAAM,gCAAgC,GAAG,EAAE,CAAC;AAC5C,MAAM,wBAAwB,GAAG,CAAC,CAAC;AACnC,MAAM,wBAAwB,GAAG,EAAE,CAAC;AAEpC;;;;;;GAMG;AACH,SAAS,wBAAwB,CAAC,IAA6B,EAAE,KAAa,EAAY;IACzF,MAAM,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,GAAG,iBAAiB,CAAC,CAAC;IAC7D,MAAM,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;IAChF,MAAM,mBAAmB,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,YAAY,GAAG,aAAa,CAAC,CAAC;IACtE,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EA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D;IAEO,cAAc,GAAS;QAC9B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;QACvB,IAAI,CAAC,mBAAmB,CAAC,KAAK,EAAE,CAAC;QACjC,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC;QAC3B,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAAA,CAC3C;IAED,WAAW,CAAC,OAAe,EAAQ;QAClC,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACrB,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACtC,CAAC;aAAM,CAAC;YACP,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACpC,CAAC;IAAA,CACD;IAED,WAAW,GAAa;QACvB,OAAO,IAAI,CAAC,QAAQ,CAAC;IAAA,CACrB;CACD","sourcesContent":["import {\n\ttype Component,\n\tContainer,\n\ttype Focusable,\n\tgetKeybindings,\n\tInput,\n\ttype Keybinding,\n\tSpacer,\n\tsliceByColumn,\n\tText,\n\ttruncateToWidth,\n\tvisibleWidth,\n\twrapTextWithAnsi,\n} from \"@earendil-works/pi-tui\";\nimport type { SessionTreeNode } from \"../../../core/session-manager.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { formatKeyText, keyHint } from \"./keybinding-hints.ts\";\n\n/** Gutter info: position (displayIndent where connector was) and whether to show │ */\ninterface GutterInfo {\n\tposition: number; // displayIndent level where the connector was shown\n\tshow: boolean; // true = show │, false = show spaces\n}\n\n/** Flattened tree node for navigation */\ninterface FlatNode {\n\tnode: SessionTreeNode;\n\t/** Indentation level (each level = 3 chars) */\n\tindent: number;\n\t/** Whether to show connector (├─ or └─) - true if parent has multiple children */\n\tshowConnector: boolean;\n\t/** If showConnector, true = last sibling (└─), false = not last (├─) */\n\tisLast: boolean;\n\t/** Gutter info for each ancestor branch point */\n\tgutters: GutterInfo[];\n\t/** True if this node is a root under a virtual branching root (multiple roots) */\n\tisVirtualRootChild: boolean;\n}\n\ninterface HorizontalViewportRow {\n\tgutter: string;\n\tbody: string;\n\tanchorCol: number;\n\tbodyWidth: number;\n\tisSelected: boolean;\n}\n\nconst TREE_GUTTER_WIDTH = 2;\nconst MIN_VISIBLE_ANCHOR_CONTENT_WIDTH = 4;\nconst MAX_VISIBLE_ANCHOR_CONTENT_WIDTH = 20;\nconst MIN_ANCHOR_CONTEXT_WIDTH = 2;\nconst MAX_ANCHOR_CONTEXT_WIDTH = 12;\n\n/**\n * Render tree rows into a horizontally clipped viewport.\n *\n * The tree gutter is always kept visible. The row bodies are shifted left only\n * when the selected row's anchor (the start of its entry text after tree\n * indentation/markers) would otherwise be too far right to see useful content.\n */\nfunction renderHorizontalViewport(rows: HorizontalViewportRow[], width: number): string[] {\n\tconst viewportWidth = Math.max(0, width - TREE_GUTTER_WIDTH);\n\tconst maxBodyWidth = rows.reduce((max, row) => Math.max(max, row.bodyWidth), 0);\n\tconst maxHorizontalScroll = Math.max(0, maxBodyWidth - viewportWidth);\n\tconst selectedRow = rows.find((row) => row.isSelected);\n\n\t// Only pan horizontally when needed to keep enough selected-row content visible after its anchor.\n\tlet horizontalScroll = 0;\n\tif (selectedRow && maxHorizontalScroll > 0) {\n\t\tconst minVisibleAnchorContentWidth = Math.min(\n\t\t\tMAX_VISIBLE_ANCHOR_CONTENT_WIDTH,\n\t\t\tMath.max(MIN_VISIBLE_ANCHOR_CONTENT_WIDTH, Math.floor(viewportWidth / 3)),\n\t\t);\n\t\tif (selectedRow.anchorCol > viewportWidth - minVisibleAnchorContentWidth) {\n\t\t\tconst anchorContextWidth = Math.min(\n\t\t\t\tMAX_ANCHOR_CONTEXT_WIDTH,\n\t\t\t\tMath.max(MIN_ANCHOR_CONTEXT_WIDTH, Math.floor(viewportWidth / 4)),\n\t\t\t);\n\t\t\thorizontalScroll = Math.min(maxHorizontalScroll, selectedRow.anchorCol - anchorContextWidth);\n\t\t}\n\t}\n\n\t// Clip only the body; the fixed-width gutter remains visible as navigation context.\n\treturn rows.map((row) => {\n\t\tconst line =\n\t\t\thorizontalScroll > 0\n\t\t\t\t? `${row.gutter}${sliceByColumn(row.body, horizontalScroll, viewportWidth, true)}\\x1b[0m`\n\t\t\t\t: row.gutter + row.body;\n\t\treturn truncateToWidth(line, width, \"\");\n\t});\n}\n\n/** Filter mode for tree display */\nexport type FilterMode = \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\";\n\n/**\n * Tree list component with selection and ASCII art visualization\n */\n/** Tool call info for lookup */\ninterface ToolCallInfo {\n\tname: string;\n\targuments: Record;\n}\n\nclass TreeList implements Component {\n\tprivate flatNodes: FlatNode[] = [];\n\tprivate filteredNodes: FlatNode[] = [];\n\tprivate selectedIndex = 0;\n\tprivate currentLeafId: string | null;\n\tprivate maxVisibleLines: number;\n\tprivate filterMode: FilterMode = \"default\";\n\tprivate searchQuery = \"\";\n\tprivate toolCallMap: Map = new Map();\n\tprivate multipleRoots = false;\n\tprivate showLabelTimestamps = false;\n\tprivate activePathIds: Set = new Set();\n\tprivate visibleParentMap: Map = new Map();\n\tprivate visibleChildrenMap: Map = new Map();\n\tprivate lastSelectedId: string | null = null;\n\tprivate foldedNodes: Set = new Set();\n\n\tpublic onSelect?: (entryId: string) => void;\n\tpublic onCancel?: () => void;\n\tpublic onCopy?: (text: string | undefined) => void;\n\tpublic onLabelEdit?: (entryId: string, currentLabel: string | undefined) => void;\n\n\tconstructor(\n\t\ttree: SessionTreeNode[],\n\t\tcurrentLeafId: string | null,\n\t\tmaxVisibleLines: number,\n\t\tinitialSelectedId?: string,\n\t\tinitialFilterMode?: FilterMode,\n\t) {\n\t\tthis.currentLeafId = currentLeafId;\n\t\tthis.maxVisibleLines = maxVisibleLines;\n\t\tthis.filterMode = initialFilterMode ?? \"default\";\n\t\tthis.multipleRoots = tree.length > 1;\n\t\tthis.flatNodes = this.flattenTree(tree);\n\t\tthis.buildActivePath();\n\t\tthis.applyFilter();\n\n\t\t// Start with initialSelectedId if provided, otherwise current leaf\n\t\tconst targetId = initialSelectedId ?? currentLeafId;\n\t\tthis.selectedIndex = this.findNearestVisibleIndex(targetId);\n\t\tthis.lastSelectedId = this.filteredNodes[this.selectedIndex]?.node.entry.id ?? null;\n\t}\n\n\t/**\n\t * Find the index of the nearest visible entry, walking up the parent chain if needed.\n\t * Returns the index in filteredNodes, or the last index as fallback.\n\t */\n\tprivate findNearestVisibleIndex(entryId: string | null): number {\n\t\tif (this.filteredNodes.length === 0) return 0;\n\n\t\t// Build a map for parent lookup\n\t\tconst entryMap = new Map();\n\t\tfor (const flatNode of this.flatNodes) {\n\t\t\tentryMap.set(flatNode.node.entry.id, flatNode);\n\t\t}\n\n\t\t// Build a map of visible entry IDs to their indices in filteredNodes\n\t\tconst visibleIdToIndex = new Map(this.filteredNodes.map((node, i) => [node.node.entry.id, i]));\n\n\t\t// Walk from entryId up to root, looking for a visible entry\n\t\tlet currentId = entryId;\n\t\twhile (currentId !== null) {\n\t\t\tconst index = visibleIdToIndex.get(currentId);\n\t\t\tif (index !== undefined) return index;\n\t\t\tconst node = entryMap.get(currentId);\n\t\t\tif (!node) break;\n\t\t\tcurrentId = node.node.entry.parentId ?? null;\n\t\t}\n\n\t\t// Fallback: last visible entry\n\t\treturn this.filteredNodes.length - 1;\n\t}\n\n\t/** Build the set of entry IDs on the path from root to current leaf */\n\tprivate buildActivePath(): void {\n\t\tthis.activePathIds.clear();\n\t\tif (!this.currentLeafId) return;\n\n\t\t// Build a map of id -> entry for parent lookup\n\t\tconst entryMap = new Map();\n\t\tfor (const flatNode of this.flatNodes) {\n\t\t\tentryMap.set(flatNode.node.entry.id, flatNode);\n\t\t}\n\n\t\t// Walk from leaf to root\n\t\tlet currentId: string | null = this.currentLeafId;\n\t\twhile (currentId) {\n\t\t\tthis.activePathIds.add(currentId);\n\t\t\tconst node = entryMap.get(currentId);\n\t\t\tif (!node) break;\n\t\t\tcurrentId = node.node.entry.parentId ?? null;\n\t\t}\n\t}\n\n\tprivate flattenTree(roots: SessionTreeNode[]): FlatNode[] {\n\t\tconst result: FlatNode[] = [];\n\t\tthis.toolCallMap.clear();\n\n\t\t// Indentation rules:\n\t\t// - At indent 0: stay at 0 unless parent has >1 children (then +1)\n\t\t// - At indent 1: children always go to indent 2 (visual grouping of subtree)\n\t\t// - At indent 2+: stay flat for single-child chains, +1 only if parent branches\n\n\t\t// Stack items: [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild]\n\t\ttype StackItem = [SessionTreeNode, number, boolean, boolean, boolean, GutterInfo[], boolean];\n\t\tconst stack: StackItem[] = [];\n\n\t\t// Determine which subtrees contain the active leaf (to sort current branch first)\n\t\t// Use iterative post-order traversal to avoid stack overflow\n\t\tconst containsActive = new Map();\n\t\tconst leafId = this.currentLeafId;\n\t\t{\n\t\t\t// Build list in pre-order, then process in reverse for post-order effect\n\t\t\tconst allNodes: SessionTreeNode[] = [];\n\t\t\tconst preOrderStack: SessionTreeNode[] = [...roots];\n\t\t\twhile (preOrderStack.length > 0) {\n\t\t\t\tconst node = preOrderStack.pop()!;\n\t\t\t\tallNodes.push(node);\n\t\t\t\t// Push children in reverse so they're processed left-to-right\n\t\t\t\tfor (let i = node.children.length - 1; i >= 0; i--) {\n\t\t\t\t\tpreOrderStack.push(node.children[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Process in reverse (post-order): children before parents\n\t\t\tfor (let i = allNodes.length - 1; i >= 0; i--) {\n\t\t\t\tconst node = allNodes[i];\n\t\t\t\tlet has = leafId !== null && node.entry.id === leafId;\n\t\t\t\tfor (const child of node.children) {\n\t\t\t\t\tif (containsActive.get(child)) {\n\t\t\t\t\t\thas = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontainsActive.set(node, has);\n\t\t\t}\n\t\t}\n\n\t\t// Add roots in reverse order, prioritizing the one containing the active leaf\n\t\t// If multiple roots, treat them as children of a virtual root that branches\n\t\tconst multipleRoots = roots.length > 1;\n\t\tconst orderedRoots = [...roots].sort((a, b) => Number(containsActive.get(b)) - Number(containsActive.get(a)));\n\t\tfor (let i = orderedRoots.length - 1; i >= 0; i--) {\n\t\t\tconst isLast = i === orderedRoots.length - 1;\n\t\t\tstack.push([orderedRoots[i], multipleRoots ? 1 : 0, multipleRoots, multipleRoots, isLast, [], multipleRoots]);\n\t\t}\n\n\t\twhile (stack.length > 0) {\n\t\t\tconst [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] = stack.pop()!;\n\n\t\t\t// Extract tool calls from assistant messages for later lookup\n\t\t\tconst entry = node.entry;\n\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\tconst content = (entry.message as { content?: unknown }).content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tfor (const block of content) {\n\t\t\t\t\t\tif (typeof block === \"object\" && block !== null && \"type\" in block && block.type === \"toolCall\") {\n\t\t\t\t\t\t\tconst tc = block as { id: string; name: string; arguments: Record };\n\t\t\t\t\t\t\tthis.toolCallMap.set(tc.id, { name: tc.name, arguments: tc.arguments });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresult.push({ node, indent, showConnector, isLast, gutters, isVirtualRootChild });\n\n\t\t\tconst children = node.children;\n\t\t\tconst multipleChildren = children.length > 1;\n\n\t\t\t// Order children so the branch containing the active leaf comes first\n\t\t\tconst orderedChildren = (() => {\n\t\t\t\tconst prioritized: SessionTreeNode[] = [];\n\t\t\t\tconst rest: SessionTreeNode[] = [];\n\t\t\t\tfor (const child of children) {\n\t\t\t\t\tif (containsActive.get(child)) {\n\t\t\t\t\t\tprioritized.push(child);\n\t\t\t\t\t} else {\n\t\t\t\t\t\trest.push(child);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn [...prioritized, ...rest];\n\t\t\t})();\n\n\t\t\t// Calculate child indent\n\t\t\tlet childIndent: number;\n\t\t\tif (multipleChildren) {\n\t\t\t\t// Parent branches: children get +1\n\t\t\t\tchildIndent = indent + 1;\n\t\t\t} else if (justBranched && indent > 0) {\n\t\t\t\t// First generation after a branch: +1 for visual grouping\n\t\t\t\tchildIndent = indent + 1;\n\t\t\t} else {\n\t\t\t\t// Single-child chain: stay flat\n\t\t\t\tchildIndent = indent;\n\t\t\t}\n\n\t\t\t// Build gutters for children\n\t\t\t// If this node showed a connector, add a gutter entry for descendants\n\t\t\t// Only add gutter if connector is actually displayed (not suppressed for virtual root children)\n\t\t\tconst connectorDisplayed = showConnector && !isVirtualRootChild;\n\t\t\t// When connector is displayed, add a gutter entry at the connector's position\n\t\t\t// Connector is at position (displayIndent - 1), so gutter should be there too\n\t\t\tconst currentDisplayIndent = this.multipleRoots ? Math.max(0, indent - 1) : indent;\n\t\t\tconst connectorPosition = Math.max(0, currentDisplayIndent - 1);\n\t\t\tconst childGutters: GutterInfo[] = connectorDisplayed\n\t\t\t\t? [...gutters, { position: connectorPosition, show: !isLast }]\n\t\t\t\t: gutters;\n\n\t\t\t// Add children in reverse order\n\t\t\tfor (let i = orderedChildren.length - 1; i >= 0; i--) {\n\t\t\t\tconst childIsLast = i === orderedChildren.length - 1;\n\t\t\t\tstack.push([\n\t\t\t\t\torderedChildren[i],\n\t\t\t\t\tchildIndent,\n\t\t\t\t\tmultipleChildren,\n\t\t\t\t\tmultipleChildren,\n\t\t\t\t\tchildIsLast,\n\t\t\t\t\tchildGutters,\n\t\t\t\t\tfalse,\n\t\t\t\t]);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate applyFilter(): void {\n\t\t// Update lastSelectedId only when we have a valid selection (non-empty list)\n\t\t// This preserves the selection when switching through empty filter results\n\t\tif (this.filteredNodes.length > 0) {\n\t\t\tthis.lastSelectedId = this.filteredNodes[this.selectedIndex]?.node.entry.id ?? this.lastSelectedId;\n\t\t}\n\n\t\tconst searchTokens = this.searchQuery.toLowerCase().split(/\\s+/).filter(Boolean);\n\n\t\tthis.filteredNodes = this.flatNodes.filter((flatNode) => {\n\t\t\tconst entry = flatNode.node.entry;\n\t\t\tconst isCurrentLeaf = entry.id === this.currentLeafId;\n\n\t\t\t// Skip assistant messages with only tool calls (no text) unless error/aborted\n\t\t\t// Always show current leaf so active position is visible\n\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\" && !isCurrentLeaf) {\n\t\t\t\tconst msg = entry.message as { stopReason?: string; content?: unknown };\n\t\t\t\tconst hasText = this.hasTextContent(msg.content);\n\t\t\t\tconst isErrorOrAborted = msg.stopReason && msg.stopReason !== \"stop\" && msg.stopReason !== \"toolUse\";\n\t\t\t\t// Only hide if no text AND not an error/aborted message\n\t\t\t\tif (!hasText && !isErrorOrAborted) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Apply filter mode\n\t\t\tlet passesFilter = true;\n\t\t\t// Entry types hidden in default view (settings/bookkeeping)\n\t\t\tconst isSettingsEntry =\n\t\t\t\tentry.type === \"label\" ||\n\t\t\t\tentry.type === \"custom\" ||\n\t\t\t\tentry.type === \"model_change\" ||\n\t\t\t\tentry.type === \"thinking_level_change\" ||\n\t\t\t\tentry.type === \"session_info\";\n\n\t\t\tswitch (this.filterMode) {\n\t\t\t\tcase \"user-only\":\n\t\t\t\t\t// Just user messages\n\t\t\t\t\tpassesFilter = entry.type === \"message\" && entry.message.role === \"user\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"no-tools\":\n\t\t\t\t\t// Default minus tool results\n\t\t\t\t\tpassesFilter = !isSettingsEntry && !(entry.type === \"message\" && entry.message.role === \"toolResult\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"labeled-only\":\n\t\t\t\t\t// Just labeled entries\n\t\t\t\t\tpassesFilter = flatNode.node.label !== undefined;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"all\":\n\t\t\t\t\t// Show everything\n\t\t\t\t\tpassesFilter = true;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t// Default mode: hide settings/bookkeeping entries\n\t\t\t\t\tpassesFilter = !isSettingsEntry;\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!passesFilter) return false;\n\n\t\t\t// Apply search filter\n\t\t\tif (searchTokens.length > 0) {\n\t\t\t\tconst nodeText = this.getSearchableText(flatNode.node).toLowerCase();\n\t\t\t\treturn searchTokens.every((token) => nodeText.includes(token));\n\t\t\t}\n\n\t\t\treturn true;\n\t\t});\n\n\t\t// Filter out descendants of folded nodes.\n\t\tif (this.foldedNodes.size > 0) {\n\t\t\tconst skipSet = new Set();\n\t\t\tfor (const flatNode of this.flatNodes) {\n\t\t\t\tconst { id, parentId } = flatNode.node.entry;\n\t\t\t\tif (parentId != null && (this.foldedNodes.has(parentId) || skipSet.has(parentId))) {\n\t\t\t\t\tskipSet.add(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.filteredNodes = this.filteredNodes.filter((flatNode) => !skipSet.has(flatNode.node.entry.id));\n\t\t}\n\n\t\t// Recalculate visual structure (indent, connectors, gutters) based on visible tree\n\t\tthis.recalculateVisualStructure();\n\n\t\t// Try to preserve cursor on the same node, or find nearest visible ancestor\n\t\tif (this.lastSelectedId) {\n\t\t\tthis.selectedIndex = this.findNearestVisibleIndex(this.lastSelectedId);\n\t\t} else if (this.selectedIndex >= this.filteredNodes.length) {\n\t\t\t// Clamp index if out of bounds\n\t\t\tthis.selectedIndex = Math.max(0, this.filteredNodes.length - 1);\n\t\t}\n\n\t\t// Update lastSelectedId to the actual selection (may have changed due to parent walk)\n\t\tif (this.filteredNodes.length > 0) {\n\t\t\tthis.lastSelectedId = this.filteredNodes[this.selectedIndex]?.node.entry.id ?? this.lastSelectedId;\n\t\t}\n\t}\n\n\t/**\n\t * Recompute indentation/connectors for the filtered view\n\t *\n\t * Filtering can hide intermediate entries; descendants attach to the nearest visible ancestor.\n\t * Keep indentation semantics aligned with flattenTree() so single-child chains don't drift right.\n\t */\n\tprivate recalculateVisualStructure(): void {\n\t\tif (this.filteredNodes.length === 0) return;\n\n\t\tconst visibleIds = new Set(this.filteredNodes.map((n) => n.node.entry.id));\n\n\t\t// Build entry map for efficient parent lookup (using full tree)\n\t\tconst entryMap = new Map();\n\t\tfor (const flatNode of this.flatNodes) {\n\t\t\tentryMap.set(flatNode.node.entry.id, flatNode);\n\t\t}\n\n\t\t// Find nearest visible ancestor for a node\n\t\tconst findVisibleAncestor = (nodeId: string): string | null => {\n\t\t\tlet currentId = entryMap.get(nodeId)?.node.entry.parentId ?? null;\n\t\t\twhile (currentId !== null) {\n\t\t\t\tif (visibleIds.has(currentId)) {\n\t\t\t\t\treturn currentId;\n\t\t\t\t}\n\t\t\t\tcurrentId = entryMap.get(currentId)?.node.entry.parentId ?? null;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\n\t\t// Build visible tree structure:\n\t\t// - visibleParent: nodeId → nearest visible ancestor (or null for roots)\n\t\t// - visibleChildren: parentId → list of visible children (in filteredNodes order)\n\t\tconst visibleParent = new Map();\n\t\tconst visibleChildren = new Map();\n\t\tvisibleChildren.set(null, []); // root-level nodes\n\n\t\tfor (const flatNode of this.filteredNodes) {\n\t\t\tconst nodeId = flatNode.node.entry.id;\n\t\t\tconst ancestorId = findVisibleAncestor(nodeId);\n\t\t\tvisibleParent.set(nodeId, ancestorId);\n\n\t\t\tif (!visibleChildren.has(ancestorId)) {\n\t\t\t\tvisibleChildren.set(ancestorId, []);\n\t\t\t}\n\t\t\tvisibleChildren.get(ancestorId)!.push(nodeId);\n\t\t}\n\n\t\t// Update multipleRoots based on visible roots\n\t\tconst visibleRootIds = visibleChildren.get(null)!;\n\t\tthis.multipleRoots = visibleRootIds.length > 1;\n\n\t\t// Build a map for quick lookup: nodeId → FlatNode\n\t\tconst filteredNodeMap = new Map();\n\t\tfor (const flatNode of this.filteredNodes) {\n\t\t\tfilteredNodeMap.set(flatNode.node.entry.id, flatNode);\n\t\t}\n\n\t\t// DFS over the visible tree using flattenTree() indentation semantics\n\t\t// Stack items: [nodeId, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild]\n\t\ttype StackItem = [string, number, boolean, boolean, boolean, GutterInfo[], boolean];\n\t\tconst stack: StackItem[] = [];\n\n\t\t// Add visible roots in reverse order (to process in forward order via stack)\n\t\tfor (let i = visibleRootIds.length - 1; i >= 0; i--) {\n\t\t\tconst isLast = i === visibleRootIds.length - 1;\n\t\t\tstack.push([\n\t\t\t\tvisibleRootIds[i],\n\t\t\t\tthis.multipleRoots ? 1 : 0,\n\t\t\t\tthis.multipleRoots,\n\t\t\t\tthis.multipleRoots,\n\t\t\t\tisLast,\n\t\t\t\t[],\n\t\t\t\tthis.multipleRoots,\n\t\t\t]);\n\t\t}\n\n\t\twhile (stack.length > 0) {\n\t\t\tconst [nodeId, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] = stack.pop()!;\n\n\t\t\tconst flatNode = filteredNodeMap.get(nodeId);\n\t\t\tif (!flatNode) continue;\n\n\t\t\t// Update this node's visual properties\n\t\t\tflatNode.indent = indent;\n\t\t\tflatNode.showConnector = showConnector;\n\t\t\tflatNode.isLast = isLast;\n\t\t\tflatNode.gutters = gutters;\n\t\t\tflatNode.isVirtualRootChild = isVirtualRootChild;\n\n\t\t\t// Get visible children of this node\n\t\t\tconst children = visibleChildren.get(nodeId) || [];\n\t\t\tconst multipleChildren = children.length > 1;\n\n\t\t\t// Child indent follows flattenTree(): branch points (and first generation after a branch) shift +1\n\t\t\tlet childIndent: number;\n\t\t\tif (multipleChildren) {\n\t\t\t\tchildIndent = indent + 1;\n\t\t\t} else if (justBranched && indent > 0) {\n\t\t\t\tchildIndent = indent + 1;\n\t\t\t} else {\n\t\t\t\tchildIndent = indent;\n\t\t\t}\n\n\t\t\t// Child gutters follow flattenTree() connector/gutter rules\n\t\t\tconst connectorDisplayed = showConnector && !isVirtualRootChild;\n\t\t\tconst currentDisplayIndent = this.multipleRoots ? Math.max(0, indent - 1) : indent;\n\t\t\tconst connectorPosition = Math.max(0, currentDisplayIndent - 1);\n\t\t\tconst childGutters: GutterInfo[] = connectorDisplayed\n\t\t\t\t? [...gutters, { position: connectorPosition, show: !isLast }]\n\t\t\t\t: gutters;\n\n\t\t\t// Add children in reverse order (to process in forward order via stack)\n\t\t\tfor (let i = children.length - 1; i >= 0; i--) {\n\t\t\t\tconst childIsLast = i === children.length - 1;\n\t\t\t\tstack.push([\n\t\t\t\t\tchildren[i],\n\t\t\t\t\tchildIndent,\n\t\t\t\t\tmultipleChildren,\n\t\t\t\t\tmultipleChildren,\n\t\t\t\t\tchildIsLast,\n\t\t\t\t\tchildGutters,\n\t\t\t\t\tfalse,\n\t\t\t\t]);\n\t\t\t}\n\t\t}\n\n\t\t// Store visible tree maps for ancestor/descendant lookups in navigation\n\t\tthis.visibleParentMap = visibleParent;\n\t\tthis.visibleChildrenMap = visibleChildren;\n\t}\n\n\t/** Get searchable text content from a node */\n\tprivate getSearchableText(node: SessionTreeNode): string {\n\t\tconst entry = node.entry;\n\t\tconst parts: string[] = [];\n\n\t\tif (node.label) {\n\t\t\tparts.push(node.label);\n\t\t}\n\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst msg = entry.message;\n\t\t\t\tparts.push(msg.role);\n\t\t\t\tif (\"content\" in msg && msg.content) {\n\t\t\t\t\tparts.push(this.extractContent(msg.content));\n\t\t\t\t}\n\t\t\t\tif (msg.role === \"bashExecution\") {\n\t\t\t\t\tconst bashMsg = msg as { command?: string };\n\t\t\t\t\tif (bashMsg.command) parts.push(bashMsg.command);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"custom_message\": {\n\t\t\t\tparts.push(entry.customType);\n\t\t\t\tif (typeof entry.content === \"string\") {\n\t\t\t\t\tparts.push(entry.content);\n\t\t\t\t} else {\n\t\t\t\t\tparts.push(this.extractContent(entry.content));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"compaction\":\n\t\t\t\tparts.push(\"compaction\");\n\t\t\t\tbreak;\n\t\t\tcase \"branch_summary\":\n\t\t\t\tparts.push(\"branch summary\", entry.summary);\n\t\t\t\tbreak;\n\t\t\tcase \"session_info\":\n\t\t\t\tparts.push(\"title\");\n\t\t\t\tif (entry.name) parts.push(entry.name);\n\t\t\t\tbreak;\n\t\t\tcase \"model_change\":\n\t\t\t\tparts.push(\"model\", entry.modelId);\n\t\t\t\tbreak;\n\t\t\tcase \"thinking_level_change\":\n\t\t\t\tparts.push(\"thinking\", entry.thinkingLevel);\n\t\t\t\tbreak;\n\t\t\tcase \"custom\":\n\t\t\t\tparts.push(\"custom\", entry.customType);\n\t\t\t\tbreak;\n\t\t\tcase \"label\":\n\t\t\t\tparts.push(\"label\", entry.label ?? \"\");\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn parts.join(\" \");\n\t}\n\n\tinvalidate(): void {}\n\n\tgetSearchQuery(): string {\n\t\treturn this.searchQuery;\n\t}\n\n\tgetSelectedNode(): SessionTreeNode | undefined {\n\t\treturn this.filteredNodes[this.selectedIndex]?.node;\n\t}\n\n\tcopySelected(): void {\n\t\tconst node = this.getSelectedNode();\n\t\tthis.onCopy?.(node ? this.getEntryCopyText(node) : undefined);\n\t}\n\n\tupdateNodeLabel(entryId: string, label: string | undefined, labelTimestamp?: string): void {\n\t\tfor (const flatNode of this.flatNodes) {\n\t\t\tif (flatNode.node.entry.id === entryId) {\n\t\t\t\tflatNode.node.label = label;\n\t\t\t\tflatNode.node.labelTimestamp = label ? (labelTimestamp ?? new Date().toISOString()) : undefined;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate getStatusLabels(): string {\n\t\tlet labels = \"\";\n\t\tswitch (this.filterMode) {\n\t\t\tcase \"no-tools\":\n\t\t\t\tlabels += \" [no-tools]\";\n\t\t\t\tbreak;\n\t\t\tcase \"user-only\":\n\t\t\t\tlabels += \" [user]\";\n\t\t\t\tbreak;\n\t\t\tcase \"labeled-only\":\n\t\t\t\tlabels += \" [labeled]\";\n\t\t\t\tbreak;\n\t\t\tcase \"all\":\n\t\t\t\tlabels += \" [all]\";\n\t\t\t\tbreak;\n\t\t}\n\t\tif (this.showLabelTimestamps) {\n\t\t\tlabels += \" [+label time]\";\n\t\t}\n\t\treturn labels;\n\t}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\n\t\tif (this.filteredNodes.length === 0) {\n\t\t\tlines.push(truncateToWidth(theme.fg(\"muted\", \" No entries found\"), width));\n\t\t\tlines.push(truncateToWidth(theme.fg(\"muted\", ` (0/0)${this.getStatusLabels()}`), width));\n\t\t\treturn lines;\n\t\t}\n\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(\n\t\t\t\tthis.selectedIndex - Math.floor(this.maxVisibleLines / 2),\n\t\t\t\tthis.filteredNodes.length - this.maxVisibleLines,\n\t\t\t),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisibleLines, this.filteredNodes.length);\n\n\t\tconst renderedRows: HorizontalViewportRow[] = [];\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst flatNode = this.filteredNodes[i];\n\t\t\tconst entry = flatNode.node.entry;\n\t\t\tconst isSelected = i === this.selectedIndex;\n\n\t\t\t// Build line: cursor + prefix + path marker + label + content\n\t\t\tconst cursor = isSelected ? theme.fg(\"accent\", \"› \") : \" \";\n\n\t\t\t// If multiple roots, shift display (roots at 0, not 1)\n\t\t\tconst displayIndent = this.multipleRoots ? Math.max(0, flatNode.indent - 1) : flatNode.indent;\n\n\t\t\t// Build prefix with gutters at their correct positions\n\t\t\t// Each gutter has a position (displayIndent where its connector was shown)\n\t\t\tconst connector =\n\t\t\t\tflatNode.showConnector && !flatNode.isVirtualRootChild ? (flatNode.isLast ? \"└─ \" : \"├─ \") : \"\";\n\t\t\tconst connectorPosition = connector ? displayIndent - 1 : -1;\n\n\t\t\t// Build prefix char by char, placing gutters and connector at their positions\n\t\t\tconst totalChars = displayIndent * 3;\n\t\t\tconst prefixChars: string[] = [];\n\t\t\tconst isFolded = this.foldedNodes.has(entry.id);\n\t\t\tfor (let i = 0; i < totalChars; i++) {\n\t\t\t\tconst level = Math.floor(i / 3);\n\t\t\t\tconst posInLevel = i % 3;\n\n\t\t\t\t// Check if there's a gutter at this level\n\t\t\t\tconst gutter = flatNode.gutters.find((g) => g.position === level);\n\t\t\t\tif (gutter) {\n\t\t\t\t\tif (posInLevel === 0) {\n\t\t\t\t\t\tprefixChars.push(gutter.show ? \"│\" : \" \");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprefixChars.push(\" \");\n\t\t\t\t\t}\n\t\t\t\t} else if (connector && level === connectorPosition) {\n\t\t\t\t\t// Connector at this level, with fold indicator\n\t\t\t\t\tif (posInLevel === 0) {\n\t\t\t\t\t\tprefixChars.push(flatNode.isLast ? \"└\" : \"├\");\n\t\t\t\t\t} else if (posInLevel === 1) {\n\t\t\t\t\t\tconst foldable = this.isFoldable(entry.id);\n\t\t\t\t\t\tprefixChars.push(isFolded ? \"⊞\" : foldable ? \"⊟\" : \"─\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprefixChars.push(\" \");\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tprefixChars.push(\" \");\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst prefix = prefixChars.join(\"\");\n\n\t\t\t// Fold marker for nodes without connectors (roots)\n\t\t\tconst showsFoldInConnector = flatNode.showConnector && !flatNode.isVirtualRootChild;\n\t\t\tconst foldMarker = isFolded && !showsFoldInConnector ? theme.fg(\"accent\", \"⊞ \") : \"\";\n\n\t\t\t// Active path marker - shown right before the entry text\n\t\t\tconst isOnActivePath = this.activePathIds.has(entry.id);\n\t\t\tconst pathMarker = isOnActivePath ? theme.fg(\"accent\", \"• \") : \"\";\n\n\t\t\tconst label = flatNode.node.label ? theme.fg(\"warning\", `[${flatNode.node.label}] `) : \"\";\n\t\t\tconst labelTimestamp =\n\t\t\t\tthis.showLabelTimestamps && flatNode.node.label && flatNode.node.labelTimestamp\n\t\t\t\t\t? theme.fg(\"muted\", `${this.formatLabelTimestamp(flatNode.node.labelTimestamp)} `)\n\t\t\t\t\t: \"\";\n\t\t\tconst content = this.getEntryDisplayText(flatNode.node, isSelected);\n\t\t\tconst prefixPart = theme.fg(\"dim\", prefix) + foldMarker + pathMarker;\n\t\t\tconst anchorCol = visibleWidth(prefixPart);\n\t\t\tlet gutter = cursor;\n\t\t\tlet body = prefixPart + label + labelTimestamp + content;\n\t\t\tif (isSelected) {\n\t\t\t\tgutter = theme.bg(\"selectedBg\", gutter);\n\t\t\t\tbody = theme.bg(\"selectedBg\", body);\n\t\t\t}\n\t\t\trenderedRows.push({ gutter, body, anchorCol, bodyWidth: visibleWidth(body), isSelected });\n\t\t}\n\n\t\tlines.push(...renderHorizontalViewport(renderedRows, width));\n\t\tlines.push(\n\t\t\ttruncateToWidth(\n\t\t\t\ttheme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.filteredNodes.length})${this.getStatusLabels()}`),\n\t\t\t\twidth,\n\t\t\t),\n\t\t);\n\n\t\treturn lines;\n\t}\n\n\tprivate getEntryDisplayText(node: SessionTreeNode, isSelected: boolean): string {\n\t\tconst entry = node.entry;\n\t\tlet result: string;\n\n\t\tconst normalize = (s: string) => s.replace(/[\\n\\t]/g, \" \").trim();\n\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\": {\n\t\t\t\tconst msg = entry.message;\n\t\t\t\tconst role = msg.role;\n\t\t\t\tif (role === \"user\") {\n\t\t\t\t\tconst msgWithContent = msg as { content?: unknown };\n\t\t\t\t\tconst content = normalize(this.extractContent(msgWithContent.content));\n\t\t\t\t\tresult = theme.fg(\"accent\", \"user: \") + content;\n\t\t\t\t} else if (role === \"assistant\") {\n\t\t\t\t\tconst msgWithContent = msg as { content?: unknown; stopReason?: string; errorMessage?: string };\n\t\t\t\t\tconst textContent = normalize(this.extractContent(msgWithContent.content));\n\t\t\t\t\tif (textContent) {\n\t\t\t\t\t\tresult = theme.fg(\"success\", \"assistant: \") + textContent;\n\t\t\t\t\t} else if (msgWithContent.stopReason === \"aborted\") {\n\t\t\t\t\t\tresult = theme.fg(\"success\", \"assistant: \") + theme.fg(\"muted\", \"(aborted)\");\n\t\t\t\t\t} else if (msgWithContent.errorMessage) {\n\t\t\t\t\t\tconst errMsg = normalize(msgWithContent.errorMessage).slice(0, 80);\n\t\t\t\t\t\tresult = theme.fg(\"success\", \"assistant: \") + theme.fg(\"error\", errMsg);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresult = theme.fg(\"success\", \"assistant: \") + theme.fg(\"muted\", \"(no content)\");\n\t\t\t\t\t}\n\t\t\t\t} else if (role === \"toolResult\") {\n\t\t\t\t\tconst toolMsg = msg as { toolCallId?: string; toolName?: string };\n\t\t\t\t\tconst toolCall = toolMsg.toolCallId ? this.toolCallMap.get(toolMsg.toolCallId) : undefined;\n\t\t\t\t\tif (toolCall) {\n\t\t\t\t\t\tresult = theme.fg(\"muted\", this.formatToolCall(toolCall.name, toolCall.arguments));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresult = theme.fg(\"muted\", `[${toolMsg.toolName ?? \"tool\"}]`);\n\t\t\t\t\t}\n\t\t\t\t} else if (role === \"bashExecution\") {\n\t\t\t\t\tconst bashMsg = msg as { command?: string };\n\t\t\t\t\tresult = theme.fg(\"dim\", `[bash]: ${normalize(bashMsg.command ?? \"\")}`);\n\t\t\t\t} else {\n\t\t\t\t\tresult = theme.fg(\"dim\", `[${role}]`);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"custom_message\": {\n\t\t\t\tconst content =\n\t\t\t\t\ttypeof entry.content === \"string\"\n\t\t\t\t\t\t? entry.content\n\t\t\t\t\t\t: entry.content\n\t\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t\t.join(\"\");\n\t\t\t\tresult = theme.fg(\"customMessageLabel\", `[${entry.customType}]: `) + normalize(content);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"compaction\": {\n\t\t\t\tconst tokens = Math.round(entry.tokensBefore / 1000);\n\t\t\t\tresult = theme.fg(\"borderAccent\", `[compaction: ${tokens}k tokens]`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"branch_summary\":\n\t\t\t\tresult = theme.fg(\"warning\", `[branch summary]: `) + normalize(entry.summary);\n\t\t\t\tbreak;\n\t\t\tcase \"model_change\":\n\t\t\t\tresult = theme.fg(\"dim\", `[model: ${entry.modelId}]`);\n\t\t\t\tbreak;\n\t\t\tcase \"thinking_level_change\":\n\t\t\t\tresult = theme.fg(\"dim\", `[thinking: ${entry.thinkingLevel}]`);\n\t\t\t\tbreak;\n\t\t\tcase \"custom\":\n\t\t\t\tresult = theme.fg(\"dim\", `[custom: ${entry.customType}]`);\n\t\t\t\tbreak;\n\t\t\tcase \"label\":\n\t\t\t\tresult = theme.fg(\"dim\", `[label: ${entry.label ?? \"(cleared)\"}]`);\n\t\t\t\tbreak;\n\t\t\tcase \"session_info\":\n\t\t\t\tresult = entry.name\n\t\t\t\t\t? [theme.fg(\"dim\", \"[title: \"), theme.fg(\"dim\", entry.name), theme.fg(\"dim\", \"]\")].join(\"\")\n\t\t\t\t\t: [theme.fg(\"dim\", \"[title: \"), theme.italic(theme.fg(\"dim\", \"empty\")), theme.fg(\"dim\", \"]\")].join(\"\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tresult = \"\";\n\t\t}\n\n\t\treturn isSelected ? theme.bold(result) : result;\n\t}\n\n\tprivate formatLabelTimestamp(timestamp: string): string {\n\t\tconst date = new Date(timestamp);\n\t\tconst now = new Date();\n\t\tconst hours = date.getHours().toString().padStart(2, \"0\");\n\t\tconst minutes = date.getMinutes().toString().padStart(2, \"0\");\n\t\tconst time = `${hours}:${minutes}`;\n\n\t\tif (\n\t\t\tdate.getFullYear() === now.getFullYear() &&\n\t\t\tdate.getMonth() === now.getMonth() &&\n\t\t\tdate.getDate() === now.getDate()\n\t\t) {\n\t\t\treturn time;\n\t\t}\n\n\t\tconst month = date.getMonth() + 1;\n\t\tconst day = date.getDate();\n\t\tif (date.getFullYear() === now.getFullYear()) {\n\t\t\treturn `${month}/${day} ${time}`;\n\t\t}\n\n\t\tconst year = date.getFullYear().toString().slice(-2);\n\t\treturn `${year}/${month}/${day} ${time}`;\n\t}\n\n\tprivate extractContent(content: unknown): string {\n\t\treturn this.extractFullContent(content).slice(0, 200);\n\t}\n\n\tprivate extractFullContent(content: unknown): string {\n\t\tif (typeof content === \"string\") return content;\n\t\tif (!Array.isArray(content)) return \"\";\n\n\t\tlet result = \"\";\n\t\tfor (const block of content) {\n\t\t\tif (typeof block === \"object\" && block !== null && \"type\" in block && block.type === \"text\") {\n\t\t\t\tresult += (block as { text: string }).text;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate getEntryCopyText(node: SessionTreeNode): string | undefined {\n\t\tconst entry = node.entry;\n\t\tlet text: string | undefined;\n\n\t\tswitch (entry.type) {\n\t\t\tcase \"message\":\n\t\t\t\tif (entry.message.role === \"bashExecution\") {\n\t\t\t\t\ttext = entry.message.command;\n\t\t\t\t} else if (\"content\" in entry.message) {\n\t\t\t\t\ttext = this.extractFullContent(entry.message.content);\n\t\t\t\t\tif (!text && entry.message.role === \"assistant\") {\n\t\t\t\t\t\ttext = entry.message.errorMessage;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"custom_message\":\n\t\t\t\ttext = this.extractFullContent(entry.content);\n\t\t\t\tbreak;\n\t\t\tcase \"compaction\":\n\t\t\t\ttext = entry.summary;\n\t\t\t\tbreak;\n\t\t\tcase \"branch_summary\":\n\t\t\t\ttext = entry.summary;\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn text?.trim() ? text : undefined;\n\t}\n\n\tprivate hasTextContent(content: unknown): boolean {\n\t\tif (typeof content === \"string\") return content.trim().length > 0;\n\t\tif (Array.isArray(content)) {\n\t\t\tfor (const c of content) {\n\t\t\t\tif (typeof c === \"object\" && c !== null && \"type\" in c && c.type === \"text\") {\n\t\t\t\t\tconst text = (c as { text?: string }).text;\n\t\t\t\t\tif (text && text.trim().length > 0) return true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate formatToolCall(name: string, args: Record): string {\n\t\tconst shortenPath = (p: string): string => {\n\t\t\tconst home = process.env.HOME || process.env.USERPROFILE || \"\";\n\t\t\tif (home && p.startsWith(home)) return `~${p.slice(home.length)}`;\n\t\t\treturn p;\n\t\t};\n\n\t\tswitch (name) {\n\t\t\tcase \"read\": {\n\t\t\t\tconst path = shortenPath(String(args.path || args.file_path || \"\"));\n\t\t\t\tconst offset = args.offset as number | undefined;\n\t\t\t\tconst limit = args.limit as number | undefined;\n\t\t\t\tlet display = path;\n\t\t\t\tif (offset !== undefined || limit !== undefined) {\n\t\t\t\t\tconst start = offset ?? 1;\n\t\t\t\t\tconst end = limit !== undefined ? start + limit - 1 : \"\";\n\t\t\t\t\tdisplay += `:${start}${end ? `-${end}` : \"\"}`;\n\t\t\t\t}\n\t\t\t\treturn `[read: ${display}]`;\n\t\t\t}\n\t\t\tcase \"write\": {\n\t\t\t\tconst path = shortenPath(String(args.path || args.file_path || \"\"));\n\t\t\t\treturn `[write: ${path}]`;\n\t\t\t}\n\t\t\tcase \"edit\": {\n\t\t\t\tconst path = shortenPath(String(args.path || args.file_path || \"\"));\n\t\t\t\treturn `[edit: ${path}]`;\n\t\t\t}\n\t\t\tcase \"bash\": {\n\t\t\t\tconst rawCmd = String(args.command || \"\");\n\t\t\t\tconst cmd = rawCmd\n\t\t\t\t\t.replace(/[\\n\\t]/g, \" \")\n\t\t\t\t\t.trim()\n\t\t\t\t\t.slice(0, 50);\n\t\t\t\treturn `[bash: ${cmd}${rawCmd.length > 50 ? \"...\" : \"\"}]`;\n\t\t\t}\n\t\t\tcase \"grep\": {\n\t\t\t\tconst pattern = String(args.pattern || \"\");\n\t\t\t\tconst path = shortenPath(String(args.path || \".\"));\n\t\t\t\treturn `[grep: /${pattern}/ in ${path}]`;\n\t\t\t}\n\t\t\tcase \"find\": {\n\t\t\t\tconst pattern = String(args.pattern || \"\");\n\t\t\t\tconst path = shortenPath(String(args.path || \".\"));\n\t\t\t\treturn `[find: ${pattern} in ${path}]`;\n\t\t\t}\n\t\t\tcase \"ls\": {\n\t\t\t\tconst path = shortenPath(String(args.path || \".\"));\n\t\t\t\treturn `[ls: ${path}]`;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\t// Custom tool - show name and truncated JSON args\n\t\t\t\tconst argsStr = JSON.stringify(args).slice(0, 40);\n\t\t\t\treturn `[${name}: ${argsStr}${JSON.stringify(args).length > 40 ? \"...\" : \"\"}]`;\n\t\t\t}\n\t\t}\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"tui.select.up\")) {\n\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.filteredNodes.length - 1 : this.selectedIndex - 1;\n\t\t} else if (kb.matches(keyData, \"tui.select.down\")) {\n\t\t\tthis.selectedIndex = this.selectedIndex === this.filteredNodes.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t} else if (kb.matches(keyData, \"app.tree.foldOrUp\")) {\n\t\t\tconst currentId = this.filteredNodes[this.selectedIndex]?.node.entry.id;\n\t\t\tif (currentId && this.isFoldable(currentId) && !this.foldedNodes.has(currentId)) {\n\t\t\t\tthis.foldedNodes.add(currentId);\n\t\t\t\tthis.applyFilter();\n\t\t\t} else {\n\t\t\t\tthis.selectedIndex = this.findBranchSegmentStart(\"up\");\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"app.tree.unfoldOrDown\")) {\n\t\t\tconst currentId = this.filteredNodes[this.selectedIndex]?.node.entry.id;\n\t\t\tif (currentId && this.foldedNodes.has(currentId)) {\n\t\t\t\tthis.foldedNodes.delete(currentId);\n\t\t\t\tthis.applyFilter();\n\t\t\t} else {\n\t\t\t\tthis.selectedIndex = this.findBranchSegmentStart(\"down\");\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"tui.editor.cursorLeft\") || kb.matches(keyData, \"tui.select.pageUp\")) {\n\t\t\t// Page up\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - this.maxVisibleLines);\n\t\t} else if (kb.matches(keyData, \"tui.editor.cursorRight\") || kb.matches(keyData, \"tui.select.pageDown\")) {\n\t\t\t// Page down\n\t\t\tthis.selectedIndex = Math.min(this.filteredNodes.length - 1, this.selectedIndex + this.maxVisibleLines);\n\t\t} else if (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\tconst selected = this.filteredNodes[this.selectedIndex];\n\t\t\tif (selected && this.onSelect) {\n\t\t\t\tthis.onSelect(selected.node.entry.id);\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"app.message.copy\")) {\n\t\t\tthis.copySelected();\n\t\t} else if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tif (this.searchQuery) {\n\t\t\t\tthis.searchQuery = \"\";\n\t\t\t\tthis.foldedNodes.clear();\n\t\t\t\tthis.applyFilter();\n\t\t\t} else {\n\t\t\t\tthis.onCancel?.();\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.default\")) {\n\t\t\t// Direct filter: default\n\t\t\tthis.filterMode = \"default\";\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.noTools\")) {\n\t\t\t// Toggle filter: no-tools ↔ default\n\t\t\tthis.filterMode = this.filterMode === \"no-tools\" ? \"default\" : \"no-tools\";\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.userOnly\")) {\n\t\t\t// Toggle filter: user-only ↔ default\n\t\t\tthis.filterMode = this.filterMode === \"user-only\" ? \"default\" : \"user-only\";\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.labeledOnly\")) {\n\t\t\t// Toggle filter: labeled-only ↔ default\n\t\t\tthis.filterMode = this.filterMode === \"labeled-only\" ? \"default\" : \"labeled-only\";\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.all\")) {\n\t\t\t// Toggle filter: all ↔ default\n\t\t\tthis.filterMode = this.filterMode === \"all\" ? \"default\" : \"all\";\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.cycleBackward\")) {\n\t\t\t// Cycle filter backwards\n\t\t\tconst modes: FilterMode[] = [\"default\", \"no-tools\", \"user-only\", \"labeled-only\", \"all\"];\n\t\t\tconst currentIndex = modes.indexOf(this.filterMode);\n\t\t\tthis.filterMode = modes[(currentIndex - 1 + modes.length) % modes.length];\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"app.tree.filter.cycleForward\")) {\n\t\t\t// Cycle filter forwards: default → no-tools → user-only → labeled-only → all → default\n\t\t\tconst modes: FilterMode[] = [\"default\", \"no-tools\", \"user-only\", \"labeled-only\", \"all\"];\n\t\t\tconst currentIndex = modes.indexOf(this.filterMode);\n\t\t\tthis.filterMode = modes[(currentIndex + 1) % modes.length];\n\t\t\tthis.foldedNodes.clear();\n\t\t\tthis.applyFilter();\n\t\t} else if (kb.matches(keyData, \"tui.editor.deleteCharBackward\")) {\n\t\t\tif (this.searchQuery.length > 0) {\n\t\t\t\tthis.searchQuery = this.searchQuery.slice(0, -1);\n\t\t\t\tthis.foldedNodes.clear();\n\t\t\t\tthis.applyFilter();\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"app.tree.editLabel\")) {\n\t\t\tconst selected = this.filteredNodes[this.selectedIndex];\n\t\t\tif (selected && this.onLabelEdit) {\n\t\t\t\tthis.onLabelEdit(selected.node.entry.id, selected.node.label);\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"app.tree.toggleLabelTimestamp\")) {\n\t\t\tthis.showLabelTimestamps = !this.showLabelTimestamps;\n\t\t} else {\n\t\t\tconst hasControlChars = [...keyData].some((ch) => {\n\t\t\t\tconst code = ch.charCodeAt(0);\n\t\t\t\treturn code < 32 || code === 0x7f || (code >= 0x80 && code <= 0x9f);\n\t\t\t});\n\t\t\tif (!hasControlChars && keyData.length > 0) {\n\t\t\t\tthis.searchQuery += keyData;\n\t\t\t\tthis.foldedNodes.clear();\n\t\t\t\tthis.applyFilter();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Whether a node can be folded. A node is foldable if it has visible children\n\t * and is either a root (no visible parent) or a segment start (visible parent\n\t * has multiple visible children).\n\t */\n\tprivate isFoldable(entryId: string): boolean {\n\t\tconst children = this.visibleChildrenMap.get(entryId);\n\t\tif (!children || children.length === 0) return false;\n\t\tconst parentId = this.visibleParentMap.get(entryId);\n\t\tif (parentId === null || parentId === undefined) return true;\n\t\tconst siblings = this.visibleChildrenMap.get(parentId);\n\t\treturn siblings !== undefined && siblings.length > 1;\n\t}\n\n\t/**\n\t * Find the index of the next branch segment start in the given direction.\n\t * A segment start is the first child of a branch point.\n\t *\n\t * \"up\" walks the visible parent chain; \"down\" walks visible children\n\t * (always following the first child).\n\t */\n\tprivate findBranchSegmentStart(direction: \"up\" | \"down\"): number {\n\t\tconst selectedId = this.filteredNodes[this.selectedIndex]?.node.entry.id;\n\t\tif (!selectedId) return this.selectedIndex;\n\n\t\tconst indexByEntryId = new Map(this.filteredNodes.map((node, i) => [node.node.entry.id, i]));\n\t\tlet currentId: string = selectedId;\n\t\tif (direction === \"down\") {\n\t\t\twhile (true) {\n\t\t\t\tconst children: string[] = this.visibleChildrenMap.get(currentId) ?? [];\n\t\t\t\tif (children.length === 0) return indexByEntryId.get(currentId)!;\n\t\t\t\tif (children.length > 1) return indexByEntryId.get(children[0])!;\n\t\t\t\tcurrentId = children[0];\n\t\t\t}\n\t\t}\n\n\t\t// direction === \"up\"\n\t\twhile (true) {\n\t\t\tconst parentId: string | null = this.visibleParentMap.get(currentId) ?? null;\n\t\t\tif (parentId === null) return indexByEntryId.get(currentId)!;\n\t\t\tconst children = this.visibleChildrenMap.get(parentId) ?? [];\n\t\t\tif (children.length > 1) {\n\t\t\t\tconst segmentStart = indexByEntryId.get(currentId)!;\n\t\t\t\tif (segmentStart < this.selectedIndex) {\n\t\t\t\t\treturn segmentStart;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurrentId = parentId;\n\t\t}\n\t}\n}\n\n/** Component that displays the current search query */\nclass SearchLine implements Component {\n\tprivate treeList: TreeList;\n\n\tconstructor(treeList: TreeList) {\n\t\tthis.treeList = treeList;\n\t}\n\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst query = this.treeList.getSearchQuery();\n\t\tif (query) {\n\t\t\treturn [truncateToWidth(` ${theme.fg(\"muted\", \"Type to search:\")} ${theme.fg(\"accent\", query)}`, width)];\n\t\t}\n\t\treturn [truncateToWidth(` ${theme.fg(\"muted\", \"Type to search:\")}`, width)];\n\t}\n\n\thandleInput(_keyData: string): void {}\n}\n\n/** Component that renders tree help as semantic rows with chunk-aware wrapping */\nclass TreeHelp implements Component {\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst items = TREE_HELP_ITEMS.map(({ keys, label, labelFirst }) => {\n\t\t\tconst text = formatHelpKeys(keys);\n\t\t\tif (!text) return label;\n\t\t\treturn labelFirst ? `${label} ${text}` : `${text} ${label}`;\n\t\t});\n\n\t\tconst availableWidth = Math.max(1, width);\n\t\tconst indent = \" \";\n\t\tconst separator = \" · \";\n\t\tconst lines: string[] = [];\n\t\tlet currentLine = \"\";\n\n\t\tfor (const item of items) {\n\t\t\tconst candidate = currentLine\n\t\t\t\t? `${currentLine}${separator}${item}`\n\t\t\t\t: visibleWidth(`${indent}${item}`) <= availableWidth\n\t\t\t\t\t? `${indent}${item}`\n\t\t\t\t\t: item;\n\t\t\tif (!currentLine || visibleWidth(candidate) <= availableWidth) {\n\t\t\t\tcurrentLine = candidate;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tlines.push(...wrapTextWithAnsi(currentLine.trimEnd(), availableWidth));\n\t\t\tcurrentLine = visibleWidth(`${indent}${item}`) <= availableWidth ? `${indent}${item}` : item;\n\t\t}\n\n\t\tif (currentLine) {\n\t\t\tlines.push(...wrapTextWithAnsi(currentLine.trimEnd(), availableWidth));\n\t\t}\n\n\t\treturn lines.map((line) => theme.fg(\"muted\", line));\n\t}\n}\n\nconst TREE_HELP_ITEMS: Array<{ keys: Keybinding[]; label: string; labelFirst?: boolean }> = [\n\t{ keys: [\"tui.select.up\", \"tui.select.down\"], label: \"move\" },\n\t{ keys: [\"tui.editor.cursorLeft\", \"tui.editor.cursorRight\"], label: \"page\" },\n\t{ keys: [\"app.tree.foldOrUp\", \"app.tree.unfoldOrDown\"], label: \"branch\" },\n\t{ keys: [\"app.message.copy\"], label: \"copy\" },\n\t{ keys: [\"app.tree.editLabel\"], label: \"label\" },\n\t{ keys: [\"app.tree.toggleLabelTimestamp\"], label: \"label time\" },\n\t{\n\t\tkeys: [\n\t\t\t\"app.tree.filter.default\",\n\t\t\t\"app.tree.filter.noTools\",\n\t\t\t\"app.tree.filter.userOnly\",\n\t\t\t\"app.tree.filter.labeledOnly\",\n\t\t\t\"app.tree.filter.all\",\n\t\t],\n\t\tlabel: \"filters\",\n\t\tlabelFirst: true,\n\t},\n\t{ keys: [\"app.tree.filter.cycleForward\", \"app.tree.filter.cycleBackward\"], label: \"cycle\", labelFirst: true },\n];\n\nfunction formatHelpKeys(keybindings: Keybinding[]): string {\n\tconst keys: string[] = [];\n\tfor (const keybinding of keybindings) {\n\t\tconst key = getKeybindings().getKeys(keybinding)[0];\n\t\tif (key !== undefined) keys.push(key);\n\t}\n\tif (keys.length === 0) return \"\";\n\n\treturn formatKeyText(compactRawKeys(keys))\n\t\t.replace(/\\bpageUp\\b/g, \"pgup\")\n\t\t.replace(/\\bpageDown\\b/g, \"pgdn\")\n\t\t.replace(/\\bup\\b/g, \"↑\")\n\t\t.replace(/\\bdown\\b/g, \"↓\")\n\t\t.replace(/\\bleft\\b/g, \"←\")\n\t\t.replace(/\\bright\\b/g, \"→\");\n}\n\nfunction compactRawKeys(keys: string[]): string {\n\tif (keys.length === 1) return keys[0]!;\n\n\tconst parts = keys.map((key) => {\n\t\tconst separatorIndex = key.lastIndexOf(\"+\");\n\t\treturn separatorIndex === -1\n\t\t\t? { prefix: \"\", suffix: key }\n\t\t\t: { prefix: key.slice(0, separatorIndex + 1), suffix: key.slice(separatorIndex + 1) };\n\t});\n\tconst prefix = parts[0]!.prefix;\n\treturn prefix && parts.every((part) => part.prefix === prefix)\n\t\t? `${prefix}${parts.map((part) => part.suffix).join(\"/\")}`\n\t\t: keys.join(\"/\");\n}\n\n/** Label input component shown when editing a label */\nclass LabelInput implements Component, Focusable {\n\tprivate input: Input;\n\tprivate entryId: string;\n\tpublic onSubmit?: (entryId: string, label: string | undefined) => void;\n\tpublic onCancel?: () => void;\n\n\t// Focusable implementation - propagate to input for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\tthis.input.focused = value;\n\t}\n\n\tconstructor(entryId: string, currentLabel: string | undefined) {\n\t\tthis.entryId = entryId;\n\t\tthis.input = new Input();\n\t\tif (currentLabel) {\n\t\t\tthis.input.setValue(currentLabel);\n\t\t}\n\t}\n\n\tinvalidate(): void {}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\t\tconst indent = \" \";\n\t\tconst availableWidth = width - indent.length;\n\t\tlines.push(truncateToWidth(`${indent}${theme.fg(\"muted\", \"Label (empty to remove):\")}`, width));\n\t\tlines.push(...this.input.render(availableWidth).map((line) => truncateToWidth(`${indent}${line}`, width)));\n\t\tlines.push(\n\t\t\ttruncateToWidth(\n\t\t\t\t`${indent}${keyHint(\"tui.select.confirm\", \"save\")} ${keyHint(\"tui.select.cancel\", \"cancel\")}`,\n\t\t\t\twidth,\n\t\t\t),\n\t\t);\n\t\treturn lines;\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\tconst value = this.input.getValue().trim();\n\t\t\tthis.onSubmit?.(this.entryId, value || undefined);\n\t\t} else if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.onCancel?.();\n\t\t} else {\n\t\t\tthis.input.handleInput(keyData);\n\t\t}\n\t}\n}\n\n/**\n * Component that renders a session tree selector for navigation\n */\nexport class TreeSelectorComponent extends Container implements Focusable {\n\tprivate treeList: TreeList;\n\tprivate labelInput: LabelInput | null = null;\n\tprivate labelInputContainer: Container;\n\tprivate treeContainer: Container;\n\tprivate onLabelChangeCallback?: (entryId: string, label: string | undefined) => void;\n\tpublic onCopy?: (text: string | undefined) => void;\n\n\t// Focusable implementation - propagate to labelInput when active for IME cursor positioning\n\tprivate _focused = false;\n\tget focused(): boolean {\n\t\treturn this._focused;\n\t}\n\tset focused(value: boolean) {\n\t\tthis._focused = value;\n\t\t// Propagate to labelInput when it's active\n\t\tif (this.labelInput) {\n\t\t\tthis.labelInput.focused = value;\n\t\t}\n\t}\n\n\tconstructor(\n\t\ttree: SessionTreeNode[],\n\t\tcurrentLeafId: string | null,\n\t\tterminalHeight: number,\n\t\tonSelect: (entryId: string) => void,\n\t\tonCancel: () => void,\n\t\tonLabelChange?: (entryId: string, label: string | undefined) => void,\n\t\tinitialSelectedId?: string,\n\t\tinitialFilterMode?: FilterMode,\n\t) {\n\t\tsuper();\n\n\t\tthis.onLabelChangeCallback = onLabelChange;\n\t\tconst maxVisibleLines = Math.max(5, Math.floor(terminalHeight / 2));\n\n\t\tthis.treeList = new TreeList(tree, currentLeafId, maxVisibleLines, initialSelectedId, initialFilterMode);\n\t\tthis.treeList.onSelect = onSelect;\n\t\tthis.treeList.onCancel = onCancel;\n\t\tthis.treeList.onCopy = (text) => this.onCopy?.(text);\n\t\tthis.treeList.onLabelEdit = (entryId, currentLabel) => this.showLabelInput(entryId, currentLabel);\n\n\t\tthis.treeContainer = new Container();\n\t\tthis.treeContainer.addChild(this.treeList);\n\n\t\tthis.labelInputContainer = new Container();\n\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Text(theme.bold(\" Session Tree\"), 1, 0));\n\t\tthis.addChild(new TreeHelp());\n\t\tthis.addChild(new SearchLine(this.treeList));\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(this.treeContainer);\n\t\tthis.addChild(this.labelInputContainer);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\tif (tree.length === 0) {\n\t\t\tsetTimeout(() => onCancel(), 100);\n\t\t}\n\t}\n\n\tprivate showLabelInput(entryId: string, currentLabel: string | undefined): void {\n\t\tthis.labelInput = new LabelInput(entryId, currentLabel);\n\t\tthis.labelInput.onSubmit = (id, label) => {\n\t\t\tthis.treeList.updateNodeLabel(id, label);\n\t\t\tthis.onLabelChangeCallback?.(id, label);\n\t\t\tthis.hideLabelInput();\n\t\t};\n\t\tthis.labelInput.onCancel = () => this.hideLabelInput();\n\n\t\t// Propagate current focused state to the new labelInput\n\t\tthis.labelInput.focused = this._focused;\n\n\t\tthis.treeContainer.clear();\n\t\tthis.labelInputContainer.clear();\n\t\tthis.labelInputContainer.addChild(this.labelInput);\n\t}\n\n\tprivate hideLabelInput(): void {\n\t\tthis.labelInput = null;\n\t\tthis.labelInputContainer.clear();\n\t\tthis.treeContainer.clear();\n\t\tthis.treeContainer.addChild(this.treeList);\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tif (this.labelInput) {\n\t\t\tthis.labelInput.handleInput(keyData);\n\t\t} else {\n\t\t\tthis.treeList.handleInput(keyData);\n\t\t}\n\t}\n\n\tgetTreeList(): TreeList {\n\t\treturn this.treeList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/trust-selector.d.ts b/dist/modes/interactive/components/trust-selector.d.ts new file mode 100644 index 0000000..a807b9f --- /dev/null +++ b/dist/modes/interactive/components/trust-selector.d.ts @@ -0,0 +1,23 @@ +import { Container } from "@earendil-works/pi-tui"; +import { type ProjectTrustOption, type ProjectTrustStoreEntry } from "../../../core/trust-manager.ts"; +export type TrustSelection = Pick; +export interface TrustSelectorOptions { + cwd: string; + savedDecision: ProjectTrustStoreEntry | null; + projectTrusted: boolean; + onSelect: (selection: TrustSelection) => void; + onCancel: () => void; +} +export declare class TrustSelectorComponent extends Container { + private selectedIndex; + private readonly listContainer; + private readonly trustOptions; + private readonly savedDecision; + private readonly onSelectCallback; + private readonly onCancelCallback; + constructor(options: TrustSelectorOptions); + private isSavedOption; + private updateList; + handleInput(keyData: string): void; +} +//# sourceMappingURL=trust-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/trust-selector.d.ts.map b/dist/modes/interactive/components/trust-selector.d.ts.map new file mode 100644 index 0000000..9be2b1e --- /dev/null +++ b/dist/modes/interactive/components/trust-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"trust-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/trust-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAgC,MAAM,wBAAwB,CAAC;AACjF,OAAO,EAEN,KAAK,kBAAkB,EACvB,KAAK,sBAAsB,EAC3B,MAAM,gCAAgC,CAAC;AAKxC,MAAM,MAAM,cAAc,GAAG,IAAI,CAAC,kBAAkB,EAAE,SAAS,GAAG,SAAS,CAAC,CAAC;AAE7E,MAAM,WAAW,oBAAoB;IACpC,GAAG,EAAE,MAAM,CAAC;IACZ,aAAa,EAAE,sBAAsB,GAAG,IAAI,CAAC;IAC7C,cAAc,EAAE,OAAO,CAAC;IACxB,QAAQ,EAAE,CAAC,SAAS,EAAE,cAAc,KAAK,IAAI,CAAC;IAC9C,QAAQ,EAAE,MAAM,IAAI,CAAC;CACrB;AAaD,qBAAa,sBAAuB,SAAQ,SAAS;IACpD,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAY;IAC1C,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAuB;IACpD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAgC;IAC9D,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAsC;IACvE,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAa;IAE9C,YAAY,OAAO,EAAE,oBAAoB,EAkDxC;IAED,OAAO,CAAC,aAAa;IAQrB,OAAO,CAAC,UAAU;IAiBlB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAgBjC;CACD","sourcesContent":["import { Container, getKeybindings, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport {\n\tgetProjectTrustOptions,\n\ttype ProjectTrustOption,\n\ttype ProjectTrustStoreEntry,\n} from \"../../../core/trust-manager.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint, rawKeyHint } from \"./keybinding-hints.ts\";\n\nexport type TrustSelection = Pick;\n\nexport interface TrustSelectorOptions {\n\tcwd: string;\n\tsavedDecision: ProjectTrustStoreEntry | null;\n\tprojectTrusted: boolean;\n\tonSelect: (selection: TrustSelection) => void;\n\tonCancel: () => void;\n}\n\nfunction formatDecision(trustPath: string | undefined, decision: ProjectTrustStoreEntry | null): string {\n\tif (decision === null) {\n\t\treturn \"none\";\n\t}\n\tconst label = decision.decision ? \"trusted\" : \"untrusted\";\n\tif (trustPath !== undefined && decision.path !== trustPath) {\n\t\treturn `${label} (inherited from ${decision.path})`;\n\t}\n\treturn `${label} (${decision.path})`;\n}\n\nexport class TrustSelectorComponent extends Container {\n\tprivate selectedIndex: number;\n\tprivate readonly listContainer: Container;\n\tprivate readonly trustOptions: ProjectTrustOption[];\n\tprivate readonly savedDecision: ProjectTrustStoreEntry | null;\n\tprivate readonly onSelectCallback: (selection: TrustSelection) => void;\n\tprivate readonly onCancelCallback: () => void;\n\n\tconstructor(options: TrustSelectorOptions) {\n\t\tsuper();\n\n\t\tthis.savedDecision = options.savedDecision;\n\t\tthis.trustOptions = getProjectTrustOptions(options.cwd);\n\t\tthis.selectedIndex = Math.max(\n\t\t\t0,\n\t\t\tthis.trustOptions.findIndex((option) => this.isSavedOption(option)),\n\t\t);\n\t\tthis.onSelectCallback = options.onSelect;\n\t\tthis.onCancelCallback = options.onCancel;\n\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.fg(\"accent\", theme.bold(\"Project trust\")), 1, 0));\n\t\tthis.addChild(new Text(theme.fg(\"muted\", options.cwd), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.fg(\n\t\t\t\t\t\"muted\",\n\t\t\t\t\t`Saved decision: ${formatDecision(this.trustOptions[0]?.savedPath, options.savedDecision)}`,\n\t\t\t\t),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.addChild(\n\t\t\tnew Text(theme.fg(\"muted\", `Current session: ${options.projectTrusted ? \"trusted\" : \"untrusted\"}`), 1, 0),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\n\t\tthis.listContainer = new Container();\n\t\tthis.addChild(this.listContainer);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(\n\t\t\tnew Text(\n\t\t\t\trawKeyHint(\"↑↓\", \"navigate\") +\n\t\t\t\t\t\" \" +\n\t\t\t\t\tkeyHint(\"tui.select.confirm\", \"save\") +\n\t\t\t\t\t\" \" +\n\t\t\t\t\tkeyHint(\"tui.select.cancel\", \"cancel\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\tthis.updateList();\n\t}\n\n\tprivate isSavedOption(option: ProjectTrustOption): boolean {\n\t\treturn (\n\t\t\toption.savedPath !== undefined &&\n\t\t\tthis.savedDecision?.decision === option.trusted &&\n\t\t\tthis.savedDecision.path === option.savedPath\n\t\t);\n\t}\n\n\tprivate updateList(): void {\n\t\tthis.listContainer.clear();\n\t\tfor (let i = 0; i < this.trustOptions.length; i++) {\n\t\t\tconst option = this.trustOptions[i];\n\t\t\tif (!option) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst isSelected = i === this.selectedIndex;\n\t\t\tconst isCurrent = this.isSavedOption(option);\n\t\t\tconst checkmark = isCurrent ? theme.fg(\"success\", \" ✓\") : \"\";\n\t\t\tconst prefix = isSelected ? theme.fg(\"accent\", \"→ \") : \" \";\n\t\t\tconst label = isSelected ? theme.fg(\"accent\", option.label) : theme.fg(\"text\", option.label);\n\t\t\tthis.listContainer.addChild(new Text(`${prefix}${label}${checkmark}`, 1, 0));\n\t\t}\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"tui.select.up\") || keyData === \"k\") {\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - 1);\n\t\t\tthis.updateList();\n\t\t} else if (kb.matches(keyData, \"tui.select.down\") || keyData === \"j\") {\n\t\t\tthis.selectedIndex = Math.min(this.trustOptions.length - 1, this.selectedIndex + 1);\n\t\t\tthis.updateList();\n\t\t} else if (kb.matches(keyData, \"tui.select.confirm\") || keyData === \"\\n\") {\n\t\t\tconst selected = this.trustOptions[this.selectedIndex];\n\t\t\tif (selected) {\n\t\t\t\tthis.onSelectCallback({ trusted: selected.trusted, updates: selected.updates });\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.onCancelCallback();\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/trust-selector.js b/dist/modes/interactive/components/trust-selector.js new file mode 100644 index 0000000..48cca1d --- /dev/null +++ b/dist/modes/interactive/components/trust-selector.js @@ -0,0 +1,91 @@ +import { Container, getKeybindings, Spacer, Text } from "@earendil-works/pi-tui"; +import { getProjectTrustOptions, } from "../../../core/trust-manager.js"; +import { theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +import { keyHint, rawKeyHint } from "./keybinding-hints.js"; +function formatDecision(trustPath, decision) { + if (decision === null) { + return "none"; + } + const label = decision.decision ? "trusted" : "untrusted"; + if (trustPath !== undefined && decision.path !== trustPath) { + return `${label} (inherited from ${decision.path})`; + } + return `${label} (${decision.path})`; +} +export class TrustSelectorComponent extends Container { + selectedIndex; + listContainer; + trustOptions; + savedDecision; + onSelectCallback; + onCancelCallback; + constructor(options) { + super(); + this.savedDecision = options.savedDecision; + this.trustOptions = getProjectTrustOptions(options.cwd); + this.selectedIndex = Math.max(0, this.trustOptions.findIndex((option) => this.isSavedOption(option))); + this.onSelectCallback = options.onSelect; + this.onCancelCallback = options.onCancel; + this.addChild(new DynamicBorder()); + this.addChild(new Spacer(1)); + this.addChild(new Text(theme.fg("accent", theme.bold("Project trust")), 1, 0)); + this.addChild(new Text(theme.fg("muted", options.cwd), 1, 0)); + this.addChild(new Spacer(1)); + this.addChild(new Text(theme.fg("muted", `Saved decision: ${formatDecision(this.trustOptions[0]?.savedPath, options.savedDecision)}`), 1, 0)); + this.addChild(new Text(theme.fg("muted", `Current session: ${options.projectTrusted ? "trusted" : "untrusted"}`), 1, 0)); + this.addChild(new Spacer(1)); + this.listContainer = new Container(); + this.addChild(this.listContainer); + this.addChild(new Spacer(1)); + this.addChild(new Text(rawKeyHint("↑↓", "navigate") + + " " + + keyHint("tui.select.confirm", "save") + + " " + + keyHint("tui.select.cancel", "cancel"), 1, 0)); + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder()); + this.updateList(); + } + isSavedOption(option) { + return (option.savedPath !== undefined && + this.savedDecision?.decision === option.trusted && + this.savedDecision.path === option.savedPath); + } + updateList() { + this.listContainer.clear(); + for (let i = 0; i < this.trustOptions.length; i++) { + const option = this.trustOptions[i]; + if (!option) { + continue; + } + const isSelected = i === this.selectedIndex; + const isCurrent = this.isSavedOption(option); + const checkmark = isCurrent ? theme.fg("success", " ✓") : ""; + const prefix = isSelected ? theme.fg("accent", "→ ") : " "; + const label = isSelected ? theme.fg("accent", option.label) : theme.fg("text", option.label); + this.listContainer.addChild(new Text(`${prefix}${label}${checkmark}`, 1, 0)); + } + } + handleInput(keyData) { + const kb = getKeybindings(); + if (kb.matches(keyData, "tui.select.up") || keyData === "k") { + this.selectedIndex = Math.max(0, this.selectedIndex - 1); + this.updateList(); + } + else if (kb.matches(keyData, "tui.select.down") || keyData === "j") { + this.selectedIndex = Math.min(this.trustOptions.length - 1, this.selectedIndex + 1); + this.updateList(); + } + else if (kb.matches(keyData, "tui.select.confirm") || keyData === "\n") { + const selected = this.trustOptions[this.selectedIndex]; + if (selected) { + this.onSelectCallback({ trusted: selected.trusted, updates: selected.updates }); + } + } + else if (kb.matches(keyData, "tui.select.cancel")) { + this.onCancelCallback(); + } + } +} +//# sourceMappingURL=trust-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/trust-selector.js.map b/dist/modes/interactive/components/trust-selector.js.map new file mode 100644 index 0000000..abc260d --- /dev/null +++ b/dist/modes/interactive/components/trust-selector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trust-selector.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/trust-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AACjF,OAAO,EACN,sBAAsB,GAGtB,MAAM,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,EAAE,CAAC;YAC1E,MAAM,QAAQ,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;YACvD,IAAI,QAAQ,EAAE,CAAC;gBACd,IAAI,CAAC,gBAAgB,CAAC,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;YACjF,CAAC;QACF,CAAC;aAAM,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,CAAC,EAAE,CAAC;YACrD,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACzB,CAAC;IAAA,CACD;CACD","sourcesContent":["import { Container, getKeybindings, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport {\n\tgetProjectTrustOptions,\n\ttype ProjectTrustOption,\n\ttype ProjectTrustStoreEntry,\n} from \"../../../core/trust-manager.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\nimport { keyHint, rawKeyHint } from \"./keybinding-hints.ts\";\n\nexport type TrustSelection = Pick;\n\nexport interface TrustSelectorOptions {\n\tcwd: string;\n\tsavedDecision: ProjectTrustStoreEntry | null;\n\tprojectTrusted: boolean;\n\tonSelect: (selection: TrustSelection) => void;\n\tonCancel: () => void;\n}\n\nfunction formatDecision(trustPath: string | undefined, decision: ProjectTrustStoreEntry | null): string {\n\tif (decision === null) {\n\t\treturn \"none\";\n\t}\n\tconst label = decision.decision ? \"trusted\" : \"untrusted\";\n\tif (trustPath !== undefined && decision.path !== trustPath) {\n\t\treturn `${label} (inherited from ${decision.path})`;\n\t}\n\treturn `${label} (${decision.path})`;\n}\n\nexport class TrustSelectorComponent extends Container {\n\tprivate selectedIndex: number;\n\tprivate readonly listContainer: Container;\n\tprivate readonly trustOptions: ProjectTrustOption[];\n\tprivate readonly savedDecision: ProjectTrustStoreEntry | null;\n\tprivate readonly onSelectCallback: (selection: TrustSelection) => void;\n\tprivate readonly onCancelCallback: () => void;\n\n\tconstructor(options: TrustSelectorOptions) {\n\t\tsuper();\n\n\t\tthis.savedDecision = options.savedDecision;\n\t\tthis.trustOptions = getProjectTrustOptions(options.cwd);\n\t\tthis.selectedIndex = Math.max(\n\t\t\t0,\n\t\t\tthis.trustOptions.findIndex((option) => this.isSavedOption(option)),\n\t\t);\n\t\tthis.onSelectCallback = options.onSelect;\n\t\tthis.onCancelCallback = options.onCancel;\n\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.fg(\"accent\", theme.bold(\"Project trust\")), 1, 0));\n\t\tthis.addChild(new Text(theme.fg(\"muted\", options.cwd), 1, 0));\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.fg(\n\t\t\t\t\t\"muted\",\n\t\t\t\t\t`Saved decision: ${formatDecision(this.trustOptions[0]?.savedPath, options.savedDecision)}`,\n\t\t\t\t),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.addChild(\n\t\t\tnew Text(theme.fg(\"muted\", `Current session: ${options.projectTrusted ? \"trusted\" : \"untrusted\"}`), 1, 0),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\n\t\tthis.listContainer = new Container();\n\t\tthis.addChild(this.listContainer);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(\n\t\t\tnew Text(\n\t\t\t\trawKeyHint(\"↑↓\", \"navigate\") +\n\t\t\t\t\t\" \" +\n\t\t\t\t\tkeyHint(\"tui.select.confirm\", \"save\") +\n\t\t\t\t\t\" \" +\n\t\t\t\t\tkeyHint(\"tui.select.cancel\", \"cancel\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\tthis.updateList();\n\t}\n\n\tprivate isSavedOption(option: ProjectTrustOption): boolean {\n\t\treturn (\n\t\t\toption.savedPath !== undefined &&\n\t\t\tthis.savedDecision?.decision === option.trusted &&\n\t\t\tthis.savedDecision.path === option.savedPath\n\t\t);\n\t}\n\n\tprivate updateList(): void {\n\t\tthis.listContainer.clear();\n\t\tfor (let i = 0; i < this.trustOptions.length; i++) {\n\t\t\tconst option = this.trustOptions[i];\n\t\t\tif (!option) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst isSelected = i === this.selectedIndex;\n\t\t\tconst isCurrent = this.isSavedOption(option);\n\t\t\tconst checkmark = isCurrent ? theme.fg(\"success\", \" ✓\") : \"\";\n\t\t\tconst prefix = isSelected ? theme.fg(\"accent\", \"→ \") : \" \";\n\t\t\tconst label = isSelected ? theme.fg(\"accent\", option.label) : theme.fg(\"text\", option.label);\n\t\t\tthis.listContainer.addChild(new Text(`${prefix}${label}${checkmark}`, 1, 0));\n\t\t}\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\tif (kb.matches(keyData, \"tui.select.up\") || keyData === \"k\") {\n\t\t\tthis.selectedIndex = Math.max(0, this.selectedIndex - 1);\n\t\t\tthis.updateList();\n\t\t} else if (kb.matches(keyData, \"tui.select.down\") || keyData === \"j\") {\n\t\t\tthis.selectedIndex = Math.min(this.trustOptions.length - 1, this.selectedIndex + 1);\n\t\t\tthis.updateList();\n\t\t} else if (kb.matches(keyData, \"tui.select.confirm\") || keyData === \"\\n\") {\n\t\t\tconst selected = this.trustOptions[this.selectedIndex];\n\t\t\tif (selected) {\n\t\t\t\tthis.onSelectCallback({ trusted: selected.trusted, updates: selected.updates });\n\t\t\t}\n\t\t} else if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tthis.onCancelCallback();\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/user-message-selector.d.ts b/dist/modes/interactive/components/user-message-selector.d.ts new file mode 100644 index 0000000..8e92f6a --- /dev/null +++ b/dist/modes/interactive/components/user-message-selector.d.ts @@ -0,0 +1,30 @@ +import { type Component, Container } from "@earendil-works/pi-tui"; +interface UserMessageItem { + id: string; + text: string; + timestamp?: string; +} +/** + * Custom user message list component with selection + */ +declare class UserMessageList implements Component { + private messages; + private selectedIndex; + onSelect?: (entryId: string) => void; + onCancel?: () => void; + private maxVisible; + constructor(messages: UserMessageItem[], initialSelectedId?: string); + invalidate(): void; + render(width: number): string[]; + handleInput(keyData: string): void; +} +/** + * Component that renders a user message selector for branching + */ +export declare class UserMessageSelectorComponent extends Container { + private messageList; + constructor(messages: UserMessageItem[], onSelect: (entryId: string) => void, onCancel: () => void, initialSelectedId?: string); + getMessageList(): UserMessageList; +} +export {}; +//# sourceMappingURL=user-message-selector.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/user-message-selector.d.ts.map b/dist/modes/interactive/components/user-message-selector.d.ts.map new file mode 100644 index 0000000..4ff2935 --- /dev/null +++ b/dist/modes/interactive/components/user-message-selector.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"user-message-selector.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/user-message-selector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAE,SAAS,EAAiD,MAAM,wBAAwB,CAAC;AAIlH,UAAU,eAAe;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,cAAM,eAAgB,YAAW,SAAS;IACzC,OAAO,CAAC,QAAQ,CAAyB;IACzC,OAAO,CAAC,aAAa,CAAa;IAC3B,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACrC,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;IAC7B,OAAO,CAAC,UAAU,CAAc;IAEhC,YAAY,QAAQ,EAAE,eAAe,EAAE,EAAE,iBAAiB,CAAC,EAAE,MAAM,EAMlE;IAED,UAAU,IAAI,IAAI,CAEjB;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CA8C9B;IAED,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAuBjC;CACD;AAED;;GAEG;AACH,qBAAa,4BAA6B,SAAQ,SAAS;IAC1D,OAAO,CAAC,WAAW,CAAkB;IAErC,YACC,QAAQ,EAAE,eAAe,EAAE,EAC3B,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,EACnC,QAAQ,EAAE,MAAM,IAAI,EACpB,iBAAiB,CAAC,EAAE,MAAM,EAiC1B;IAED,cAAc,IAAI,eAAe,CAEhC;CACD","sourcesContent":["import { type Component, Container, getKeybindings, Spacer, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\n\ninterface UserMessageItem {\n\tid: string; // Entry ID in the session\n\ttext: string; // The message text\n\ttimestamp?: string; // Optional timestamp if available\n}\n\n/**\n * Custom user message list component with selection\n */\nclass UserMessageList implements Component {\n\tprivate messages: UserMessageItem[] = [];\n\tprivate selectedIndex: number = 0;\n\tpublic onSelect?: (entryId: string) => void;\n\tpublic onCancel?: () => void;\n\tprivate maxVisible: number = 10; // Max messages visible\n\n\tconstructor(messages: UserMessageItem[], initialSelectedId?: string) {\n\t\t// Store messages in chronological order (oldest to newest)\n\t\tthis.messages = messages;\n\t\tconst initialIndex = initialSelectedId ? messages.findIndex((message) => message.id === initialSelectedId) : -1;\n\t\t// Start with selected message if provided, else default to the most recent\n\t\tthis.selectedIndex = initialIndex >= 0 ? initialIndex : Math.max(0, messages.length - 1);\n\t}\n\n\tinvalidate(): void {\n\t\t// No cached state to invalidate currently\n\t}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\n\t\tif (this.messages.length === 0) {\n\t\t\tlines.push(theme.fg(\"muted\", \" No user messages found\"));\n\t\t\treturn lines;\n\t\t}\n\n\t\t// Calculate visible range with scrolling\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.messages.length - this.maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisible, this.messages.length);\n\n\t\t// Render visible messages (2 lines per message + blank line)\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst message = this.messages[i];\n\t\t\tconst isSelected = i === this.selectedIndex;\n\n\t\t\t// Normalize message to single line\n\t\t\tconst normalizedMessage = message.text.replace(/\\n/g, \" \").trim();\n\n\t\t\t// First line: cursor + message\n\t\t\tconst cursor = isSelected ? theme.fg(\"accent\", \"› \") : \" \";\n\t\t\tconst maxMsgWidth = width - 2; // Account for cursor (2 chars)\n\t\t\tconst truncatedMsg = truncateToWidth(normalizedMessage, maxMsgWidth);\n\t\t\tconst messageLine = cursor + (isSelected ? theme.bold(truncatedMsg) : truncatedMsg);\n\n\t\t\tlines.push(messageLine);\n\n\t\t\t// Second line: metadata (position in history)\n\t\t\tconst position = i + 1;\n\t\t\tconst metadata = ` Message ${position} of ${this.messages.length}`;\n\t\t\tconst metadataLine = theme.fg(\"muted\", metadata);\n\t\t\tlines.push(metadataLine);\n\t\t\tlines.push(\"\"); // Blank line between messages\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.messages.length) {\n\t\t\tconst scrollInfo = theme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.messages.length})`);\n\t\t\tlines.push(scrollInfo);\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\t// Up arrow - go to previous (older) message, wrap to bottom when at top\n\t\tif (kb.matches(keyData, \"tui.select.up\")) {\n\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.messages.length - 1 : this.selectedIndex - 1;\n\t\t}\n\t\t// Down arrow - go to next (newer) message, wrap to top when at bottom\n\t\telse if (kb.matches(keyData, \"tui.select.down\")) {\n\t\t\tthis.selectedIndex = this.selectedIndex === this.messages.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t}\n\t\t// Enter - select message and branch\n\t\telse if (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\tconst selected = this.messages[this.selectedIndex];\n\t\t\tif (selected && this.onSelect) {\n\t\t\t\tthis.onSelect(selected.id);\n\t\t\t}\n\t\t}\n\t\t// Escape - cancel\n\t\telse if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tif (this.onCancel) {\n\t\t\t\tthis.onCancel();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Component that renders a user message selector for branching\n */\nexport class UserMessageSelectorComponent extends Container {\n\tprivate messageList: UserMessageList;\n\n\tconstructor(\n\t\tmessages: UserMessageItem[],\n\t\tonSelect: (entryId: string) => void,\n\t\tonCancel: () => void,\n\t\tinitialSelectedId?: string,\n\t) {\n\t\tsuper();\n\n\t\t// Add header\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.bold(\"Fork from Message\"), 1, 0));\n\t\tthis.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.fg(\"muted\", \"Select a user message to copy the active path up to that point into a new session\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create message list\n\t\tthis.messageList = new UserMessageList(messages, initialSelectedId);\n\t\tthis.messageList.onSelect = onSelect;\n\t\tthis.messageList.onCancel = onCancel;\n\n\t\tthis.addChild(this.messageList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Auto-cancel if no messages\n\t\tif (messages.length === 0) {\n\t\t\tsetTimeout(() => onCancel(), 100);\n\t\t}\n\t}\n\n\tgetMessageList(): UserMessageList {\n\t\treturn this.messageList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/user-message-selector.js b/dist/modes/interactive/components/user-message-selector.js new file mode 100644 index 0000000..7f26882 --- /dev/null +++ b/dist/modes/interactive/components/user-message-selector.js @@ -0,0 +1,114 @@ +import { Container, getKeybindings, Spacer, Text, truncateToWidth } from "@earendil-works/pi-tui"; +import { theme } from "../theme/theme.js"; +import { DynamicBorder } from "./dynamic-border.js"; +/** + * Custom user message list component with selection + */ +class UserMessageList { + messages = []; + selectedIndex = 0; + onSelect; + onCancel; + maxVisible = 10; // Max messages visible + constructor(messages, initialSelectedId) { + // Store messages in chronological order (oldest to newest) + this.messages = messages; + const initialIndex = initialSelectedId ? messages.findIndex((message) => message.id === initialSelectedId) : -1; + // Start with selected message if provided, else default to the most recent + this.selectedIndex = initialIndex >= 0 ? initialIndex : Math.max(0, messages.length - 1); + } + invalidate() { + // No cached state to invalidate currently + } + render(width) { + const lines = []; + if (this.messages.length === 0) { + lines.push(theme.fg("muted", " No user messages found")); + return lines; + } + // Calculate visible range with scrolling + const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.messages.length - this.maxVisible)); + const endIndex = Math.min(startIndex + this.maxVisible, this.messages.length); + // Render visible messages (2 lines per message + blank line) + for (let i = startIndex; i < endIndex; i++) { + const message = this.messages[i]; + const isSelected = i === this.selectedIndex; + // Normalize message to single line + const normalizedMessage = message.text.replace(/\n/g, " ").trim(); + // First line: cursor + message + const cursor = isSelected ? theme.fg("accent", "› ") : " "; + const maxMsgWidth = width - 2; // Account for cursor (2 chars) + const truncatedMsg = truncateToWidth(normalizedMessage, maxMsgWidth); + const messageLine = cursor + (isSelected ? theme.bold(truncatedMsg) : truncatedMsg); + lines.push(messageLine); + // Second line: metadata (position in history) + const position = i + 1; + const metadata = ` Message ${position} of ${this.messages.length}`; + const metadataLine = theme.fg("muted", metadata); + lines.push(metadataLine); + lines.push(""); // Blank line between messages + } + // Add scroll indicator if needed + if (startIndex > 0 || endIndex < this.messages.length) { + const scrollInfo = theme.fg("muted", ` (${this.selectedIndex + 1}/${this.messages.length})`); + lines.push(scrollInfo); + } + return lines; + } + handleInput(keyData) { + const kb = getKeybindings(); + // Up arrow - go to previous (older) message, wrap to bottom when at top + if (kb.matches(keyData, "tui.select.up")) { + this.selectedIndex = this.selectedIndex === 0 ? this.messages.length - 1 : this.selectedIndex - 1; + } + // Down arrow - go to next (newer) message, wrap to top when at bottom + else if (kb.matches(keyData, "tui.select.down")) { + this.selectedIndex = this.selectedIndex === this.messages.length - 1 ? 0 : this.selectedIndex + 1; + } + // Enter - select message and branch + else if (kb.matches(keyData, "tui.select.confirm")) { + const selected = this.messages[this.selectedIndex]; + if (selected && this.onSelect) { + this.onSelect(selected.id); + } + } + // Escape - cancel + else if (kb.matches(keyData, "tui.select.cancel")) { + if (this.onCancel) { + this.onCancel(); + } + } + } +} +/** + * Component that renders a user message selector for branching + */ +export class UserMessageSelectorComponent extends Container { + messageList; + constructor(messages, onSelect, onCancel, initialSelectedId) { + super(); + // Add header + this.addChild(new Spacer(1)); + this.addChild(new Text(theme.bold("Fork from Message"), 1, 0)); + this.addChild(new Text(theme.fg("muted", "Select a user message to copy the active path up to that point into a new session"), 1, 0)); + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder()); + this.addChild(new Spacer(1)); + // Create message list + this.messageList = new UserMessageList(messages, initialSelectedId); + this.messageList.onSelect = onSelect; + this.messageList.onCancel = onCancel; + this.addChild(this.messageList); + // Add bottom border + this.addChild(new Spacer(1)); + this.addChild(new DynamicBorder()); + // Auto-cancel if no messages + if (messages.length === 0) { + setTimeout(() => onCancel(), 100); + } + } + getMessageList() { + return this.messageList; + } +} +//# sourceMappingURL=user-message-selector.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/user-message-selector.js.map b/dist/modes/interactive/components/user-message-selector.js.map new file mode 100644 index 0000000..9fae51e --- /dev/null +++ b/dist/modes/interactive/components/user-message-selector.js.map @@ -0,0 +1 @@ +{"version":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AAC,IAAI,aAAa,EAAE,CAAC,CAAC;QACnC,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAE7B,sBAAsB;QACtB,IAAI,CAAC,WAAW,GAAG,IAAI,eAAe,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAAC;QACpE,IAAI,CAAC,WAAW,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACrC,IAAI,CAAC,WAAW,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAErC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAEhC,oBAAoB;QACpB,IAAI,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,IAAI,CAAC,QAAQ,CAAC,IAAI,aAAa,EAAE,CAAC,CAAC;QAEnC,6BAA6B;QAC7B,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC3B,UAAU,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,EAAE,GAAG,CAAC,CAAC;QACnC,CAAC;IAAA,CACD;IAED,cAAc,GAAoB;QACjC,OAAO,IAAI,CAAC,WAAW,CAAC;IAAA,CACxB;CACD","sourcesContent":["import { type Component, Container, getKeybindings, Spacer, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { theme } from \"../theme/theme.ts\";\nimport { DynamicBorder } from \"./dynamic-border.ts\";\n\ninterface UserMessageItem {\n\tid: string; // Entry ID in the session\n\ttext: string; // The message text\n\ttimestamp?: string; // Optional timestamp if available\n}\n\n/**\n * Custom user message list component with selection\n */\nclass UserMessageList implements Component {\n\tprivate messages: UserMessageItem[] = [];\n\tprivate selectedIndex: number = 0;\n\tpublic onSelect?: (entryId: string) => void;\n\tpublic onCancel?: () => void;\n\tprivate maxVisible: number = 10; // Max messages visible\n\n\tconstructor(messages: UserMessageItem[], initialSelectedId?: string) {\n\t\t// Store messages in chronological order (oldest to newest)\n\t\tthis.messages = messages;\n\t\tconst initialIndex = initialSelectedId ? messages.findIndex((message) => message.id === initialSelectedId) : -1;\n\t\t// Start with selected message if provided, else default to the most recent\n\t\tthis.selectedIndex = initialIndex >= 0 ? initialIndex : Math.max(0, messages.length - 1);\n\t}\n\n\tinvalidate(): void {\n\t\t// No cached state to invalidate currently\n\t}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\n\t\tif (this.messages.length === 0) {\n\t\t\tlines.push(theme.fg(\"muted\", \" No user messages found\"));\n\t\t\treturn lines;\n\t\t}\n\n\t\t// Calculate visible range with scrolling\n\t\tconst startIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.messages.length - this.maxVisible),\n\t\t);\n\t\tconst endIndex = Math.min(startIndex + this.maxVisible, this.messages.length);\n\n\t\t// Render visible messages (2 lines per message + blank line)\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tconst message = this.messages[i];\n\t\t\tconst isSelected = i === this.selectedIndex;\n\n\t\t\t// Normalize message to single line\n\t\t\tconst normalizedMessage = message.text.replace(/\\n/g, \" \").trim();\n\n\t\t\t// First line: cursor + message\n\t\t\tconst cursor = isSelected ? theme.fg(\"accent\", \"› \") : \" \";\n\t\t\tconst maxMsgWidth = width - 2; // Account for cursor (2 chars)\n\t\t\tconst truncatedMsg = truncateToWidth(normalizedMessage, maxMsgWidth);\n\t\t\tconst messageLine = cursor + (isSelected ? theme.bold(truncatedMsg) : truncatedMsg);\n\n\t\t\tlines.push(messageLine);\n\n\t\t\t// Second line: metadata (position in history)\n\t\t\tconst position = i + 1;\n\t\t\tconst metadata = ` Message ${position} of ${this.messages.length}`;\n\t\t\tconst metadataLine = theme.fg(\"muted\", metadata);\n\t\t\tlines.push(metadataLine);\n\t\t\tlines.push(\"\"); // Blank line between messages\n\t\t}\n\n\t\t// Add scroll indicator if needed\n\t\tif (startIndex > 0 || endIndex < this.messages.length) {\n\t\t\tconst scrollInfo = theme.fg(\"muted\", ` (${this.selectedIndex + 1}/${this.messages.length})`);\n\t\t\tlines.push(scrollInfo);\n\t\t}\n\n\t\treturn lines;\n\t}\n\n\thandleInput(keyData: string): void {\n\t\tconst kb = getKeybindings();\n\t\t// Up arrow - go to previous (older) message, wrap to bottom when at top\n\t\tif (kb.matches(keyData, \"tui.select.up\")) {\n\t\t\tthis.selectedIndex = this.selectedIndex === 0 ? this.messages.length - 1 : this.selectedIndex - 1;\n\t\t}\n\t\t// Down arrow - go to next (newer) message, wrap to top when at bottom\n\t\telse if (kb.matches(keyData, \"tui.select.down\")) {\n\t\t\tthis.selectedIndex = this.selectedIndex === this.messages.length - 1 ? 0 : this.selectedIndex + 1;\n\t\t}\n\t\t// Enter - select message and branch\n\t\telse if (kb.matches(keyData, \"tui.select.confirm\")) {\n\t\t\tconst selected = this.messages[this.selectedIndex];\n\t\t\tif (selected && this.onSelect) {\n\t\t\t\tthis.onSelect(selected.id);\n\t\t\t}\n\t\t}\n\t\t// Escape - cancel\n\t\telse if (kb.matches(keyData, \"tui.select.cancel\")) {\n\t\t\tif (this.onCancel) {\n\t\t\t\tthis.onCancel();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Component that renders a user message selector for branching\n */\nexport class UserMessageSelectorComponent extends Container {\n\tprivate messageList: UserMessageList;\n\n\tconstructor(\n\t\tmessages: UserMessageItem[],\n\t\tonSelect: (entryId: string) => void,\n\t\tonCancel: () => void,\n\t\tinitialSelectedId?: string,\n\t) {\n\t\tsuper();\n\n\t\t// Add header\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new Text(theme.bold(\"Fork from Message\"), 1, 0));\n\t\tthis.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.fg(\"muted\", \"Select a user message to copy the active path up to that point into a new session\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\t\tthis.addChild(new Spacer(1));\n\n\t\t// Create message list\n\t\tthis.messageList = new UserMessageList(messages, initialSelectedId);\n\t\tthis.messageList.onSelect = onSelect;\n\t\tthis.messageList.onCancel = onCancel;\n\n\t\tthis.addChild(this.messageList);\n\n\t\t// Add bottom border\n\t\tthis.addChild(new Spacer(1));\n\t\tthis.addChild(new DynamicBorder());\n\n\t\t// Auto-cancel if no messages\n\t\tif (messages.length === 0) {\n\t\t\tsetTimeout(() => onCancel(), 100);\n\t\t}\n\t}\n\n\tgetMessageList(): UserMessageList {\n\t\treturn this.messageList;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/user-message.d.ts b/dist/modes/interactive/components/user-message.d.ts new file mode 100644 index 0000000..63ad551 --- /dev/null +++ b/dist/modes/interactive/components/user-message.d.ts @@ -0,0 +1,14 @@ +import { Container, type MarkdownTheme } from "@earendil-works/pi-tui"; +/** + * Component that renders a user message + */ +export declare class UserMessageComponent extends Container { + private text; + private markdownTheme; + private outputPad; + constructor(text: string, markdownTheme?: MarkdownTheme, outputPad?: number); + setOutputPad(padding: number): void; + private rebuild; + render(width: number): string[]; +} +//# sourceMappingURL=user-message.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/user-message.d.ts.map b/dist/modes/interactive/components/user-message.d.ts.map new file mode 100644 index 0000000..8a3245b --- /dev/null +++ b/dist/modes/interactive/components/user-message.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"user-message.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/user-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAO,SAAS,EAAY,KAAK,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAOtF;;GAEG;AACH,qBAAa,oBAAqB,SAAQ,SAAS;IAClD,OAAO,CAAC,IAAI,CAAS;IACrB,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,SAAS,CAAS;IAE1B,YAAY,IAAI,EAAE,MAAM,EAAE,aAAa,GAAE,aAAkC,EAAE,SAAS,SAAI,EAMzF;IAED,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAGlC;IAED,OAAO,CAAC,OAAO;IAkBN,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CASvC;CACD","sourcesContent":["import { Box, Container, Markdown, type MarkdownTheme } from \"@earendil-works/pi-tui\";\nimport { getMarkdownTheme, theme } from \"../theme/theme.ts\";\n\nconst OSC133_ZONE_START = \"\\x1b]133;A\\x07\";\nconst OSC133_ZONE_END = \"\\x1b]133;B\\x07\";\nconst OSC133_ZONE_FINAL = \"\\x1b]133;C\\x07\";\n\n/**\n * Component that renders a user message\n */\nexport class UserMessageComponent extends Container {\n\tprivate text: string;\n\tprivate markdownTheme: MarkdownTheme;\n\tprivate outputPad: number;\n\n\tconstructor(text: string, markdownTheme: MarkdownTheme = getMarkdownTheme(), outputPad = 1) {\n\t\tsuper();\n\t\tthis.text = text;\n\t\tthis.markdownTheme = markdownTheme;\n\t\tthis.outputPad = outputPad;\n\t\tthis.rebuild();\n\t}\n\n\tsetOutputPad(padding: number): void {\n\t\tthis.outputPad = padding;\n\t\tthis.rebuild();\n\t}\n\n\tprivate rebuild(): void {\n\t\tthis.clear();\n\t\tconst contentBox = new Box(this.outputPad, 1, (content: string) => theme.bg(\"userMessageBg\", content));\n\t\tcontentBox.addChild(\n\t\t\tnew Markdown(\n\t\t\t\tthis.text,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\tthis.markdownTheme,\n\t\t\t\t{\n\t\t\t\t\tcolor: (content: string) => theme.fg(\"userMessageText\", content),\n\t\t\t\t},\n\t\t\t\t{ preserveOrderedListMarkers: true, preserveBackslashEscapes: true },\n\t\t\t),\n\t\t);\n\t\tthis.addChild(contentBox);\n\t}\n\n\toverride render(width: number): string[] {\n\t\tconst lines = super.render(width);\n\t\tif (lines.length === 0) {\n\t\t\treturn lines;\n\t\t}\n\n\t\tlines[0] = OSC133_ZONE_START + lines[0];\n\t\tlines[lines.length - 1] = OSC133_ZONE_END + OSC133_ZONE_FINAL + lines[lines.length - 1];\n\t\treturn lines;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/user-message.js b/dist/modes/interactive/components/user-message.js new file mode 100644 index 0000000..7ad309f --- /dev/null +++ b/dist/modes/interactive/components/user-message.js @@ -0,0 +1,42 @@ +import { Box, Container, Markdown } from "@earendil-works/pi-tui"; +import { getMarkdownTheme, theme } from "../theme/theme.js"; +const OSC133_ZONE_START = "\x1b]133;A\x07"; +const OSC133_ZONE_END = "\x1b]133;B\x07"; +const OSC133_ZONE_FINAL = "\x1b]133;C\x07"; +/** + * Component that renders a user message + */ +export class UserMessageComponent extends Container { + text; + markdownTheme; + outputPad; + constructor(text, markdownTheme = getMarkdownTheme(), outputPad = 1) { + super(); + this.text = text; + this.markdownTheme = markdownTheme; + this.outputPad = outputPad; + this.rebuild(); + } + setOutputPad(padding) { + this.outputPad = padding; + this.rebuild(); + } + rebuild() { + this.clear(); + const contentBox = new Box(this.outputPad, 1, (content) => theme.bg("userMessageBg", content)); + contentBox.addChild(new Markdown(this.text, 0, 0, this.markdownTheme, { + color: (content) => theme.fg("userMessageText", content), + }, { preserveOrderedListMarkers: true, preserveBackslashEscapes: true })); + this.addChild(contentBox); + } + render(width) { + const lines = super.render(width); + if (lines.length === 0) { + return lines; + } + lines[0] = OSC133_ZONE_START + lines[0]; + lines[lines.length - 1] = OSC133_ZONE_END + OSC133_ZONE_FINAL + lines[lines.length - 1]; + return lines; + } +} +//# sourceMappingURL=user-message.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/user-message.js.map b/dist/modes/interactive/components/user-message.js.map new file mode 100644 index 0000000..8837cce --- /dev/null +++ b/dist/modes/interactive/components/user-message.js.map @@ -0,0 +1 @@ +{"version":3,"file":"user-message.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/user-message.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,QAAQ,EAAsB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CACD,CAAC;QACF,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;IAAA,CAC1B;IAEQ,MAAM,CAAC,KAAa,EAAY;QACxC,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAClC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACxB,OAAO,KAAK,CAAC;QACd,CAAC;QAED,KAAK,CAAC,CAAC,CAAC,GAAG,iBAAiB,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACxC,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,eAAe,GAAG,iBAAiB,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QACxF,OAAO,KAAK,CAAC;IAAA,CACb;CACD","sourcesContent":["import { Box, Container, Markdown, type MarkdownTheme } from \"@earendil-works/pi-tui\";\nimport { getMarkdownTheme, theme } from \"../theme/theme.ts\";\n\nconst OSC133_ZONE_START = \"\\x1b]133;A\\x07\";\nconst OSC133_ZONE_END = \"\\x1b]133;B\\x07\";\nconst OSC133_ZONE_FINAL = \"\\x1b]133;C\\x07\";\n\n/**\n * Component that renders a user message\n */\nexport class UserMessageComponent extends Container {\n\tprivate text: string;\n\tprivate markdownTheme: MarkdownTheme;\n\tprivate outputPad: number;\n\n\tconstructor(text: string, markdownTheme: MarkdownTheme = getMarkdownTheme(), outputPad = 1) {\n\t\tsuper();\n\t\tthis.text = text;\n\t\tthis.markdownTheme = markdownTheme;\n\t\tthis.outputPad = outputPad;\n\t\tthis.rebuild();\n\t}\n\n\tsetOutputPad(padding: number): void {\n\t\tthis.outputPad = padding;\n\t\tthis.rebuild();\n\t}\n\n\tprivate rebuild(): void {\n\t\tthis.clear();\n\t\tconst contentBox = new Box(this.outputPad, 1, (content: string) => theme.bg(\"userMessageBg\", content));\n\t\tcontentBox.addChild(\n\t\t\tnew Markdown(\n\t\t\t\tthis.text,\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t\tthis.markdownTheme,\n\t\t\t\t{\n\t\t\t\t\tcolor: (content: string) => theme.fg(\"userMessageText\", content),\n\t\t\t\t},\n\t\t\t\t{ preserveOrderedListMarkers: true, preserveBackslashEscapes: true },\n\t\t\t),\n\t\t);\n\t\tthis.addChild(contentBox);\n\t}\n\n\toverride render(width: number): string[] {\n\t\tconst lines = super.render(width);\n\t\tif (lines.length === 0) {\n\t\t\treturn lines;\n\t\t}\n\n\t\tlines[0] = OSC133_ZONE_START + lines[0];\n\t\tlines[lines.length - 1] = OSC133_ZONE_END + OSC133_ZONE_FINAL + lines[lines.length - 1];\n\t\treturn lines;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/visual-truncate.d.ts b/dist/modes/interactive/components/visual-truncate.d.ts new file mode 100644 index 0000000..4ffb639 --- /dev/null +++ b/dist/modes/interactive/components/visual-truncate.d.ts @@ -0,0 +1,24 @@ +/** + * Shared utility for truncating text to visual lines (accounting for line wrapping). + * Used by both tool-execution.ts and bash-execution.ts for consistent behavior. + */ +export interface VisualTruncateResult { + /** The visual lines to display */ + visualLines: string[]; + /** Number of visual lines that were skipped (hidden) */ + skippedCount: number; +} +/** + * Truncate text to a maximum number of visual lines (from the end). + * This accounts for line wrapping based on terminal width. + * + * @param text - The text content (may contain newlines) + * @param maxVisualLines - Maximum number of visual lines to show + * @param width - Terminal/render width + * @param paddingX - Horizontal padding for Text component (default 0). + * Use 0 when result will be placed in a Box (Box adds its own padding). + * Use 1 when result will be placed in a plain Container. + * @returns The truncated visual lines and count of skipped lines + */ +export declare function truncateToVisualLines(text: string, maxVisualLines: number, width: number, paddingX?: number): VisualTruncateResult; +//# sourceMappingURL=visual-truncate.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/components/visual-truncate.d.ts.map b/dist/modes/interactive/components/visual-truncate.d.ts.map new file mode 100644 index 0000000..6510911 --- /dev/null +++ b/dist/modes/interactive/components/visual-truncate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"visual-truncate.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/visual-truncate.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,MAAM,WAAW,oBAAoB;IACpC,kCAAkC;IAClC,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,wDAAwD;IACxD,YAAY,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CACpC,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,MAAM,EACb,QAAQ,GAAE,MAAU,GAClB,oBAAoB,CAkBtB","sourcesContent":["/**\n * Shared utility for truncating text to visual lines (accounting for line wrapping).\n * Used by both tool-execution.ts and bash-execution.ts for consistent behavior.\n */\n\nimport { Text } from \"@earendil-works/pi-tui\";\n\nexport interface VisualTruncateResult {\n\t/** The visual lines to display */\n\tvisualLines: string[];\n\t/** Number of visual lines that were skipped (hidden) */\n\tskippedCount: number;\n}\n\n/**\n * Truncate text to a maximum number of visual lines (from the end).\n * This accounts for line wrapping based on terminal width.\n *\n * @param text - The text content (may contain newlines)\n * @param maxVisualLines - Maximum number of visual lines to show\n * @param width - Terminal/render width\n * @param paddingX - Horizontal padding for Text component (default 0).\n * Use 0 when result will be placed in a Box (Box adds its own padding).\n * Use 1 when result will be placed in a plain Container.\n * @returns The truncated visual lines and count of skipped lines\n */\nexport function truncateToVisualLines(\n\ttext: string,\n\tmaxVisualLines: number,\n\twidth: number,\n\tpaddingX: number = 0,\n): VisualTruncateResult {\n\tif (!text) {\n\t\treturn { visualLines: [], skippedCount: 0 };\n\t}\n\n\t// Create a temporary Text component to render and get visual lines\n\tconst tempText = new Text(text, paddingX, 0);\n\tconst allVisualLines = tempText.render(width);\n\n\tif (allVisualLines.length <= maxVisualLines) {\n\t\treturn { visualLines: allVisualLines, skippedCount: 0 };\n\t}\n\n\t// Take the last N visual lines\n\tconst truncatedLines = allVisualLines.slice(-maxVisualLines);\n\tconst skippedCount = allVisualLines.length - maxVisualLines;\n\n\treturn { visualLines: truncatedLines, skippedCount };\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/components/visual-truncate.js b/dist/modes/interactive/components/visual-truncate.js new file mode 100644 index 0000000..492636b --- /dev/null +++ b/dist/modes/interactive/components/visual-truncate.js @@ -0,0 +1,33 @@ +/** + * Shared utility for truncating text to visual lines (accounting for line wrapping). + * Used by both tool-execution.ts and bash-execution.ts for consistent behavior. + */ +import { Text } from "@earendil-works/pi-tui"; +/** + * Truncate text to a maximum number of visual lines (from the end). + * This accounts for line wrapping based on terminal width. + * + * @param text - The text content (may contain newlines) + * @param maxVisualLines - Maximum number of visual lines to show + * @param width - Terminal/render width + * @param paddingX - Horizontal padding for Text component (default 0). + * Use 0 when result will be placed in a Box (Box adds its own padding). + * Use 1 when result will be placed in a plain Container. + * @returns The truncated visual lines and count of skipped lines + */ +export function truncateToVisualLines(text, maxVisualLines, width, paddingX = 0) { + if (!text) { + return { visualLines: [], skippedCount: 0 }; + } + // Create a temporary Text component to render and get visual lines + const tempText = new Text(text, paddingX, 0); + const allVisualLines = tempText.render(width); + if (allVisualLines.length <= maxVisualLines) { + return { visualLines: allVisualLines, skippedCount: 0 }; + } + // Take the last N visual lines + const truncatedLines = allVisualLines.slice(-maxVisualLines); + const skippedCount = allVisualLines.length - maxVisualLines; + return { visualLines: truncatedLines, skippedCount }; +} +//# sourceMappingURL=visual-truncate.js.map \ No newline at end of file diff --git a/dist/modes/interactive/components/visual-truncate.js.map b/dist/modes/interactive/components/visual-truncate.js.map new file mode 100644 index 0000000..0a41308 --- /dev/null +++ b/dist/modes/interactive/components/visual-truncate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"visual-truncate.js","sourceRoot":"","sources":["../../../../src/modes/interactive/components/visual-truncate.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAS9C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,qBAAqB,CACpC,IAAY,EACZ,cAAsB,EACtB,KAAa,EACb,QAAQ,GAAW,CAAC,EACG;IACvB,IAAI,CAAC,IAAI,EAAE,CAAC;QACX,OAAO,EAAE,WAAW,EAAE,EAAE,EAAE,YAAY,EAAE,CAAC,EAAE,CAAC;IAC7C,CAAC;IAED,mEAAmE;IACnE,MAAM,QAAQ,GAAG,IAAI,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC;IAC7C,MAAM,cAAc,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAE9C,IAAI,cAAc,CAAC,MAAM,IAAI,cAAc,EAAE,CAAC;QAC7C,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,YAAY,EAAE,CAAC,EAAE,CAAC;IACzD,CAAC;IAED,+BAA+B;IAC/B,MAAM,cAAc,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC,cAAc,CAAC,CAAC;IAC7D,MAAM,YAAY,GAAG,cAAc,CAAC,MAAM,GAAG,cAAc,CAAC;IAE5D,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,YAAY,EAAE,CAAC;AAAA,CACrD","sourcesContent":["/**\n * Shared utility for truncating text to visual lines (accounting for line wrapping).\n * Used by both tool-execution.ts and bash-execution.ts for consistent behavior.\n */\n\nimport { Text } from \"@earendil-works/pi-tui\";\n\nexport interface VisualTruncateResult {\n\t/** The visual lines to display */\n\tvisualLines: string[];\n\t/** Number of visual lines that were skipped (hidden) */\n\tskippedCount: number;\n}\n\n/**\n * Truncate text to a maximum number of visual lines (from the end).\n * This accounts for line wrapping based on terminal width.\n *\n * @param text - The text content (may contain newlines)\n * @param maxVisualLines - Maximum number of visual lines to show\n * @param width - Terminal/render width\n * @param paddingX - Horizontal padding for Text component (default 0).\n * Use 0 when result will be placed in a Box (Box adds its own padding).\n * Use 1 when result will be placed in a plain Container.\n * @returns The truncated visual lines and count of skipped lines\n */\nexport function truncateToVisualLines(\n\ttext: string,\n\tmaxVisualLines: number,\n\twidth: number,\n\tpaddingX: number = 0,\n): VisualTruncateResult {\n\tif (!text) {\n\t\treturn { visualLines: [], skippedCount: 0 };\n\t}\n\n\t// Create a temporary Text component to render and get visual lines\n\tconst tempText = new Text(text, paddingX, 0);\n\tconst allVisualLines = tempText.render(width);\n\n\tif (allVisualLines.length <= maxVisualLines) {\n\t\treturn { visualLines: allVisualLines, skippedCount: 0 };\n\t}\n\n\t// Take the last N visual lines\n\tconst truncatedLines = allVisualLines.slice(-maxVisualLines);\n\tconst skippedCount = allVisualLines.length - maxVisualLines;\n\n\treturn { visualLines: truncatedLines, skippedCount };\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/external-editor.d.ts b/dist/modes/interactive/external-editor.d.ts new file mode 100644 index 0000000..dd76972 --- /dev/null +++ b/dist/modes/interactive/external-editor.d.ts @@ -0,0 +1,12 @@ +export interface ExternalEditorOptions { + command: string; + content: string; +} +export type ExternalEditorResult = { + status: "complete"; + content: string; +} | { + status: "failed"; +}; +export declare function editInExternalEditor(options: ExternalEditorOptions): Promise; +//# sourceMappingURL=external-editor.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/external-editor.d.ts.map b/dist/modes/interactive/external-editor.d.ts.map new file mode 100644 index 0000000..6c5a615 --- /dev/null +++ b/dist/modes/interactive/external-editor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"external-editor.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/external-editor.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,qBAAqB;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,MAAM,oBAAoB,GAAG;IAAE,MAAM,EAAE,UAAU,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,MAAM,EAAE,QAAQ,CAAA;CAAE,CAAC;AAElG,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAgCxG","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { mkdtempSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport interface ExternalEditorOptions {\n\tcommand: string;\n\tcontent: string;\n}\n\nexport type ExternalEditorResult = { status: \"complete\"; content: string } | { status: \"failed\" };\n\nexport async function editInExternalEditor(options: ExternalEditorOptions): Promise {\n\tconst directory = mkdtempSync(join(tmpdir(), \"pi-editor-\"));\n\tconst filePath = join(directory, \"prompt.md\");\n\ttry {\n\t\twriteFileSync(filePath, options.content, \"utf-8\");\n\t\tconst [editor, ...editorArgs] = options.command.split(\" \");\n\t\tprocess.stdout.write(`Launching external editor: ${options.command}\\nPi will resume when the editor exits.\\n`);\n\n\t\t// Do not use spawnSync here. On Windows, synchronous child_process calls can keep\n\t\t// Node/libuv's console input read active after the parent pauses stdin, racing\n\t\t// vim/nvim for the console input buffer until Ctrl+C cancels the pending read.\n\t\tconst exitCode = await new Promise((resolve) => {\n\t\t\tconst child = spawn(editor, [...editorArgs, filePath], {\n\t\t\t\tstdio: \"inherit\",\n\t\t\t\tshell: process.platform === \"win32\",\n\t\t\t});\n\t\t\tchild.on(\"error\", () => resolve(null));\n\t\t\tchild.on(\"close\", (code) => resolve(code));\n\t\t});\n\n\t\tif (exitCode !== 0) {\n\t\t\treturn { status: \"failed\" };\n\t\t}\n\n\t\treturn { status: \"complete\", content: readFileSync(filePath, \"utf-8\").replace(/\\n$/, \"\") };\n\t} finally {\n\t\ttry {\n\t\t\trmSync(directory, { recursive: true, force: true });\n\t\t} catch {\n\t\t\t// Cleanup is best effort.\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/external-editor.js b/dist/modes/interactive/external-editor.js new file mode 100644 index 0000000..740bf56 --- /dev/null +++ b/dist/modes/interactive/external-editor.js @@ -0,0 +1,37 @@ +import { spawn } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +export async function editInExternalEditor(options) { + const directory = mkdtempSync(join(tmpdir(), "pi-editor-")); + const filePath = join(directory, "prompt.md"); + try { + writeFileSync(filePath, options.content, "utf-8"); + const [editor, ...editorArgs] = options.command.split(" "); + process.stdout.write(`Launching external editor: ${options.command}\nPi will resume when the editor exits.\n`); + // Do not use spawnSync here. On Windows, synchronous child_process calls can keep + // Node/libuv's console input read active after the parent pauses stdin, racing + // vim/nvim for the console input buffer until Ctrl+C cancels the pending read. + const exitCode = await new Promise((resolve) => { + const child = spawn(editor, [...editorArgs, filePath], { + stdio: "inherit", + shell: process.platform === "win32", + }); + child.on("error", () => resolve(null)); + child.on("close", (code) => resolve(code)); + }); + if (exitCode !== 0) { + return { status: "failed" }; + } + return { status: "complete", content: readFileSync(filePath, "utf-8").replace(/\n$/, "") }; + } + finally { + try { + rmSync(directory, { recursive: true, force: true }); + } + catch { + // Cleanup is best effort. + } + } +} +//# sourceMappingURL=external-editor.js.map \ No newline at end of file diff --git a/dist/modes/interactive/external-editor.js.map b/dist/modes/interactive/external-editor.js.map new file mode 100644 index 0000000..98d3ad9 --- /dev/null +++ b/dist/modes/interactive/external-editor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"external-editor.js","sourceRoot":"","sources":["../../../src/modes/interactive/external-editor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC3E,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AASjC,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,OAA8B,EAAiC;IACzG,MAAM,SAAS,GAAG,WAAW,CAAC,IAA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,IAAI,CAAC;YACJ,MAAM,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QACrD,CAAC;QAAC,MAAM,CAAC;YACR,0BAA0B;QAC3B,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { mkdtempSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport interface ExternalEditorOptions {\n\tcommand: string;\n\tcontent: string;\n}\n\nexport type ExternalEditorResult = { status: \"complete\"; content: string } | { status: \"failed\" };\n\nexport async function editInExternalEditor(options: ExternalEditorOptions): Promise {\n\tconst directory = mkdtempSync(join(tmpdir(), \"pi-editor-\"));\n\tconst filePath = join(directory, \"prompt.md\");\n\ttry {\n\t\twriteFileSync(filePath, options.content, \"utf-8\");\n\t\tconst [editor, ...editorArgs] = options.command.split(\" \");\n\t\tprocess.stdout.write(`Launching external editor: ${options.command}\\nPi will resume when the editor exits.\\n`);\n\n\t\t// Do not use spawnSync here. On Windows, synchronous child_process calls can keep\n\t\t// Node/libuv's console input read active after the parent pauses stdin, racing\n\t\t// vim/nvim for the console input buffer until Ctrl+C cancels the pending read.\n\t\tconst exitCode = await new Promise((resolve) => {\n\t\t\tconst child = spawn(editor, [...editorArgs, filePath], {\n\t\t\t\tstdio: \"inherit\",\n\t\t\t\tshell: process.platform === \"win32\",\n\t\t\t});\n\t\t\tchild.on(\"error\", () => resolve(null));\n\t\t\tchild.on(\"close\", (code) => resolve(code));\n\t\t});\n\n\t\tif (exitCode !== 0) {\n\t\t\treturn { status: \"failed\" };\n\t\t}\n\n\t\treturn { status: \"complete\", content: readFileSync(filePath, \"utf-8\").replace(/\\n$/, \"\") };\n\t} finally {\n\t\ttry {\n\t\t\trmSync(directory, { recursive: true, force: true });\n\t\t} catch {\n\t\t\t// Cleanup is best effort.\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/interactive-mode.d.ts b/dist/modes/interactive/interactive-mode.d.ts new file mode 100644 index 0000000..8eeeedd --- /dev/null +++ b/dist/modes/interactive/interactive-mode.d.ts @@ -0,0 +1,395 @@ +/** + * Interactive mode for the coding agent. + * Handles TUI rendering and user interaction, delegating business logic to AgentSession. + */ +import type { ImageContent } from "@earendil-works/pi-ai/compat"; +import { type AgentSessionRuntime } from "../../core/agent-session-runtime.ts"; +import { SessionManager } from "../../core/session-manager.ts"; +import { type LatestPiRelease } from "../../utils/version-check.ts"; +export declare function formatResumeCommand(sessionManager: SessionManager): string | undefined; +/** + * Options for InteractiveMode initialization. + */ +export interface InteractiveModeOptions { + /** Providers that were migrated to auth.json (shows warning) */ + migratedProviders?: string[]; + /** Warning message if session model couldn't be restored */ + modelFallbackMessage?: string; + /** Cwd to trust after reload if it gained a .pi directory during this implicitly trusted session. */ + autoTrustOnReloadCwd?: string; + /** Initial message to send on startup (can include @file content) */ + initialMessage?: string; + /** Images to attach to the initial message */ + initialImages?: ImageContent[]; + /** Additional messages to send after the initial message */ + initialMessages?: string[]; + /** Force verbose startup (overrides quietStartup setting) */ + verbose?: boolean; +} +export declare class InteractiveMode { + private runtimeHost; + private ui; + private loadedResourcesContainer; + private chatContainer; + private pendingMessagesContainer; + private statusContainer; + private defaultEditor; + private editor; + private editorComponentFactory; + private autocompleteProvider; + private autocompleteProviderWrappers; + private fdPath; + private editorContainer; + private footer; + private footerDataProvider; + private keybindings; + private version; + private isInitialized; + private onInputCallback?; + private pendingUserInputs; + private activeStatusIndicator; + private readonly idleStatus; + private workingMessage; + private workingVisible; + private workingIndicatorOptions; + private readonly defaultWorkingMessage; + private readonly defaultHiddenThinkingLabel; + private hiddenThinkingLabel; + private lastSigintTime; + private lastEscapeTime; + private changelogMarkdown; + private startupNoticesShown; + private anthropicSubscriptionWarningShown; + private lastStatusSpacer; + private lastStatusText; + private streamingComponent; + private streamingMessage; + private pendingTools; + private toolOutputExpanded; + private hideThinkingBlock; + private outputPad; + private skillCommands; + private unsubscribe?; + private signalCleanupHandlers; + private isBashMode; + private bashComponent; + private pendingBashComponents; + private autoCompactionEscapeHandler?; + private retryEscapeHandler?; + private compactionQueuedMessages; + private shutdownRequested; + private extensionSelector; + private extensionInput; + private extensionEditor; + private extensionTerminalInputUnsubscribers; + private extensionWidgetsAbove; + private extensionWidgetsBelow; + private widgetContainerAbove; + private widgetContainerBelow; + private customFooter; + private headerContainer; + private builtInHeader; + private customHeader; + private options; + private autoTrustOnReloadCwd; + private themeController; + private get session(); + private get agent(); + private get sessionManager(); + private get settingsManager(); + constructor(runtimeHost: AgentSessionRuntime, options?: InteractiveModeOptions); + private getAutocompleteSourceTag; + private prefixAutocompleteDescription; + private getBuiltInCommandConflictDiagnostics; + private createBaseAutocompleteProvider; + private setupAutocompleteProvider; + private showStartupNoticesIfNeeded; + init(): Promise; + /** + * Update terminal title with session name and cwd. + */ + private updateTerminalTitle; + /** + * Run the interactive mode. This is the main entry point. + * Initializes the UI, shows warnings, processes initial messages, and starts the interactive loop. + */ + run(): Promise; + private checkForPackageUpdates; + private checkTmuxKeyboardSetup; + /** + * Get changelog entries to display on startup. + * Only shows new entries since last seen version, skips for resumed sessions. + */ + private getChangelogForDisplay; + private reportInstallTelemetry; + private getMarkdownThemeWithSettings; + private formatDisplayPath; + private formatExtensionDisplayPath; + private formatContextPath; + private getStartupExpansionState; + /** + * Get a short path relative to the package root for display. + */ + private getShortPath; + private getCompactPathLabel; + private getCompactPackageSourceLabel; + private getCompactExtensionLabel; + private getCompactDisplayPathSegments; + private getCompactNonPackageExtensionLabel; + private getCompactExtensionLabels; + private getDisplaySourceInfo; + private getScopeGroup; + private isPackageSource; + private buildScopeGroups; + private formatScopeGroups; + private findSourceInfoForPath; + private formatPathWithSource; + private formatDiagnostics; + private showLoadedResources; + private bindCurrentSessionExtensions; + private applyRuntimeSettings; + private rebindCurrentSession; + private handleFatalRuntimeError; + private renderCurrentSessionState; + /** + * Get a registered tool definition by name (for custom rendering). + */ + private getRegisteredToolDefinition; + /** + * Set up keyboard shortcuts registered by extensions. + */ + private setupExtensionShortcuts; + /** + * Set extension status text in the footer. + */ + private setExtensionStatus; + private showStatusIndicator; + private clearStatusIndicator; + private setWorkingVisible; + private setWorkingIndicator; + private setHiddenThinkingLabel; + /** + * Set an extension widget (string array or custom component). + */ + private setExtensionWidget; + private clearExtensionWidgets; + private resetExtensionUI; + private static readonly MAX_WIDGET_LINES; + /** + * Render all extension widgets to the widget container. + */ + private renderWidgets; + private renderWidgetContainer; + /** + * Set a custom footer component, or restore the built-in footer. + */ + private setExtensionFooter; + /** + * Set a custom header component, or restore the built-in header. + */ + private setExtensionHeader; + private addExtensionTerminalInputListener; + private clearExtensionTerminalInputListeners; + /** + * Create the ExtensionUIContext for extensions. + */ + private createProjectTrustContext; + private createExtensionUIContext; + /** + * Show a selector for extensions. + */ + private showExtensionSelector; + /** + * Hide the extension selector. + */ + private hideExtensionSelector; + private showExtensionConfirm; + private promptForMissingSessionCwd; + /** + * Show a text input for extensions. + */ + private showExtensionInput; + /** + * Hide the extension input. + */ + private hideExtensionInput; + /** + * Show a multi-line editor for extensions (with Ctrl+G support). + */ + private showExtensionEditor; + /** + * Hide the extension editor. + */ + private hideExtensionEditor; + /** + * Set a custom editor component from an extension. + * Pass undefined to restore the default editor. + */ + private setCustomEditorComponent; + /** + * Show a notification for extensions. + */ + private showExtensionNotify; + private showExtensionCustom; + /** + * Show an extension error in the UI. + */ + private showExtensionError; + private setupKeyHandlers; + private handleClipboardPaste; + private setupEditorSubmitHandler; + private subscribeToAgent; + private handleEvent; + /** Extract text content from a user message */ + private getUserMessageText; + /** + * Show a status message in the chat. + * + * If multiple status messages are emitted back-to-back (without anything else being added to the chat), + * we update the previous status line instead of appending new ones to avoid log spam. + */ + private showStatus; + private addCustomEntryToChat; + private addMessageToChat; + private renderSessionItems; + /** + * Render session entries to chat. Used for initial load and rebuild after compaction. + * @param entries Compaction-aware session entries to render + * @param options.updateFooter Update footer state + * @param options.populateHistory Add user messages to editor history + */ + private renderSessionEntries; + /** + * Show a transcript notice when a completed assistant message paid for a + * significant cache miss. Only states observable facts: the miss itself, + * a model switch, or an idle gap past the cache TTL. + */ + private maybeShowCacheMissNotice; + private addCacheMissNotice; + renderInitialMessages(): void; + private renderProjectTrustWarningIfNeeded; + getUserInput(): Promise; + private rebuildChatFromMessages; + private handleCtrlC; + private handleCtrlD; + /** + * Gracefully shutdown the agent. + * Stops the TUI before emitting shutdown events so extension UI cleanup cannot + * repaint the final frame while the process is exiting. + */ + private isShuttingDown; + private shutdown; + private emergencyTerminalExit; + /** + * Last-resort handler for uncaught exceptions. The TUI puts stdin into raw + * mode and hides the cursor; without this handler, an uncaught throw from + * anywhere (e.g. an extension's async `ChildProcess.on("exit")` callback) + * tears down the process while leaving the terminal in raw mode with no + * cursor, requiring `stty sane && reset` to recover. + * + * Unlike emergencyTerminalExit, the terminal is still alive here, so we + * call ui.stop() to restore cooked mode, the cursor, and disable bracketed + * paste / Kitty / modifyOtherKeys sequences. + */ + private uncaughtCrash; + private checkShutdownRequested; + private registerSignalHandlers; + private unregisterSignalHandlers; + private handleCtrlZ; + private handleFollowUp; + private handleDequeue; + private updateEditorBorderColor; + private cycleThinkingLevel; + private cycleModel; + private toggleToolOutputExpansion; + private setToolsExpanded; + private toggleThinkingBlockVisibility; + private handleOpenExternalEditor; + clearEditor(): void; + showError(errorMessage: string): void; + showWarning(warningMessage: string): void; + showNewVersionNotification(release: LatestPiRelease): void; + showPackageUpdateNotification(packages: string[]): void; + /** + * Get all queued messages (read-only). + * Combines session queue and compaction queue. + */ + private getAllQueuedMessages; + /** + * Clear all queued messages and return their contents. + * Clears both session queue and compaction queue. + */ + private clearAllQueues; + private updatePendingMessagesDisplay; + private restoreQueuedMessagesToEditor; + private queueCompactionMessage; + private isExtensionCommand; + private flushCompactionQueue; + /** Move pending bash components from pending area to chat */ + private flushPendingBashComponents; + /** + * Shows a selector component in place of the editor. + * @param create Factory that receives a `done` callback and returns the component and focus target + */ + private showSelector; + private showSettingsSelector; + private handleModelCommand; + private findExactModelMatch; + private getModelCandidates; + /** Update the footer's available provider count from the current snapshot without refreshing catalogs. */ + private updateAvailableProviderCount; + private maybeWarnAboutAnthropicSubscriptionAuth; + private maybeSaveImplicitProjectTrustAfterReload; + private showTrustSelector; + private showModelSelector; + private showModelsSelector; + private showUserMessageSelector; + private handleCloneCommand; + private showTreeSelector; + private showSessionSelector; + private handleResumeSession; + private getLoginProviderOptions; + private getLogoutProviderOptions; + private findLoginProviderOptions; + private handleLoginCommand; + private startProviderLogin; + private showLoginAuthTypeSelector; + private showLoginProviderSelector; + private showOAuthSelector; + private completeProviderAuthentication; + private showAmbientAuthDialog; + private showApiKeyLoginDialog; + private showAuthSelect; + private showAuthPrompt; + private notifyAuthDialog; + private loginProvider; + private showLoginDialog; + private handleReloadCommand; + private handleExportCommand; + private getPathCommandArgument; + private handleImportCommand; + private handleShareCommand; + private handleCopyCommand; + private handleNameCommand; + private handleSessionCommand; + private handleChangelogCommand; + /** + * Get capitalized display string for an app keybinding action. + */ + private getAppKeyDisplay; + /** + * Get capitalized display string for an editor keybinding action. + */ + private getEditorKeyDisplay; + private handleHotkeysCommand; + private handleClearCommand; + private handleDebugCommand; + private handleArminSaysHi; + private handleDementedDelves; + private handleDaxnuts; + private checkDaxnutsEasterEgg; + private handleBashCommand; + private handleCompactCommand; + stop(): void; +} +//# sourceMappingURL=interactive-mode.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/interactive-mode.d.ts.map b/dist/modes/interactive/interactive-mode.d.ts.map new file mode 100644 index 0000000..9a900c2 --- /dev/null +++ b/dist/modes/interactive/interactive-mode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"interactive-mode.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-mode.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAQH,OAAO,KAAK,EAAoB,YAAY,EAAkB,MAAM,8BAA8B,CAAC;AA2CnG,O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AC,yBAAyB;IA0DjC,OAAO,CAAC,yBAAyB;YA2CnB,iBAAiB;YA+CjB,8BAA8B;IAqD5C,OAAO,CAAC,qBAAqB;YAuBf,qBAAqB;IA6CnC,OAAO,CAAC,cAAc;YAiCR,cAAc;IAwB5B,OAAO,CAAC,gBAAgB;YAaV,aAAa;YAYb,eAAe;YAgCf,mBAAmB;YAwGnB,mBAAmB;IAgBjC,OAAO,CAAC,sBAAsB;YA6BhB,mBAAmB;YA4CnB,kBAAkB;YA8FlB,iBAAiB;IAe/B,OAAO,CAAC,iBAAiB;IAwBzB,OAAO,CAAC,oBAAoB;IA+D5B,OAAO,CAAC,sBAAsB;IAqB9B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAIxB;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,oBAAoB;YAqHd,kBAAkB;IAehC,OAAO,CAAC,kBAAkB;IAiC1B,OAAO,CAAC,iBAAiB;IAMzB,OAAO,CAAC,oBAAoB;IAM5B,OAAO,CAAC,aAAa;IAMrB,OAAO,CAAC,qBAAqB;YAMf,iBAAiB;YAuFjB,oBAAoB;IAUlC,IAAI,IAAI,IAAI,CAiBX;CACD","sourcesContent":["/**\n * Interactive mode for the coding agent.\n * Handles TUI rendering and user interaction, delegating business logic to AgentSession.\n */\n\nimport * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AuthEvent, AuthPrompt } from \"@earendil-works/pi-ai\";\nimport type { AssistantMessage, ImageContent, Message, Model } from \"@earendil-works/pi-ai/compat\";\nimport type {\n\tAutocompleteItem,\n\tAutocompleteProvider,\n\tEditorComponent,\n\tKeybinding,\n\tKeyId,\n\tMarkdownTheme,\n\tOverlayHandle,\n\tOverlayOptions,\n\tSlashCommand,\n} from \"@earendil-works/pi-tui\";\nimport {\n\tCombinedAutocompleteProvider,\n\ttype Component,\n\tContainer,\n\tfuzzyFilter,\n\tgetCapabilities,\n\thyperlink,\n\tMarkdown,\n\tmatchesKey,\n\tProcessTerminal,\n\tSpacer,\n\tsetKeybindings,\n\tText,\n\tTruncatedText,\n\tTUI,\n\tvisibleWidth,\n} from \"@earendil-works/pi-tui\";\nimport chalk from \"chalk\";\nimport { spawn, spawnSync } from \"child_process\";\nimport {\n\tAPP_NAME,\n\tAPP_TITLE,\n\tCONFIG_DIR_NAME,\n\tgetAgentDir,\n\tgetAuthPath,\n\tgetDebugLogPath,\n\tgetDocsPath,\n\tgetShareViewerUrl,\n\tVERSION,\n} from \"../../config.ts\";\nimport { type AgentSession, type AgentSessionEvent, parseSkillBlock } from \"../../core/agent-session.ts\";\nimport { type AgentSessionRuntime, SessionImportFileNotFoundError } from \"../../core/agent-session-runtime.ts\";\nimport {\n\tCACHE_TTL_MS,\n\ttype CacheMiss,\n\tcollectCacheMisses,\n\tcomputeCacheWaste,\n\tdetectCacheMiss,\n} from \"../../core/cache-stats.ts\";\nimport type {\n\tAutocompleteProviderFactory,\n\tEditorFactory,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tProjectTrustContext,\n\tWorkingIndicatorOptions,\n} from \"../../core/extensions/index.ts\";\nimport { FooterDataProvider, type ReadonlyFooterDataProvider } from \"../../core/footer-data-provider.ts\";\nimport { configureHttpDispatcher, formatHttpIdleTimeoutMs } from \"../../core/http-dispatcher.ts\";\nimport { type AppKeybinding, KeybindingsManager } from \"../../core/keybindings.ts\";\nimport { createCompactionSummaryMessage } from \"../../core/messages.ts\";\nimport {\n\tdefaultModelPerProvider,\n\tfindExactModelReferenceMatch,\n\tresolveModelScope,\n\tresolveModelScopeWithDiagnostics,\n} from \"../../core/model-resolver.ts\";\nimport { DefaultPackageManager } from \"../../core/package-manager.ts\";\nimport type { ResourceDiagnostic } from \"../../core/resource-loader.ts\";\nimport { formatMissingSessionCwdPrompt, MissingSessionCwdError } from \"../../core/session-cwd.ts\";\nimport { type SessionEntry, SessionManager, sessionEntryToContextMessages } from \"../../core/session-manager.ts\";\nimport { BUILTIN_SLASH_COMMANDS } from \"../../core/slash-commands.ts\";\nimport type { SourceInfo } from \"../../core/source-info.ts\";\nimport { isInstallTelemetryEnabled } from \"../../core/telemetry.ts\";\nimport type { TruncationResult } from \"../../core/tools/truncate.ts\";\nimport { hasTrustRequiringProjectResources, ProjectTrustStore } from \"../../core/trust-manager.ts\";\nimport { getUsageCostBreakdown } from \"../../core/usage-totals.ts\";\nimport { getChangelogPath, getNewEntries, normalizeChangelogLinks, parseChangelog } from \"../../utils/changelog.ts\";\nimport { copyToClipboard, readClipboardText } from \"../../utils/clipboard.ts\";\nimport { extensionForImageMimeType, readClipboardImage } from \"../../utils/clipboard-image.ts\";\nimport { parseGitUrl } from \"../../utils/git.ts\";\nimport { getCwdRelativePath } from \"../../utils/paths.ts\";\nimport { getPiUserAgent } from \"../../utils/pi-user-agent.ts\";\nimport { killTrackedDetachedChildren } from \"../../utils/shell.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport { checkForNewPiVersion, type LatestPiRelease } from \"../../utils/version-check.ts\";\nimport { ArminComponent } from \"./components/armin.ts\";\nimport { AssistantMessageComponent } from \"./components/assistant-message.ts\";\nimport { BashExecutionComponent } from \"./components/bash-execution.ts\";\nimport { BorderedLoader } from \"./components/bordered-loader.ts\";\nimport { BranchSummaryMessageComponent } from \"./components/branch-summary-message.ts\";\nimport { CompactionSummaryMessageComponent } from \"./components/compaction-summary-message.ts\";\nimport { CustomEditor } from \"./components/custom-editor.ts\";\nimport { CustomEntryComponent } from \"./components/custom-entry.ts\";\nimport { CustomMessageComponent } from \"./components/custom-message.ts\";\nimport { DaxnutsComponent } from \"./components/daxnuts.ts\";\nimport { DynamicBorder } from \"./components/dynamic-border.ts\";\nimport { EarendilAnnouncementComponent } from \"./components/earendil-announcement.ts\";\nimport { ExtensionEditorComponent } from \"./components/extension-editor.ts\";\nimport { ExtensionInputComponent } from \"./components/extension-input.ts\";\nimport { ExtensionSelectorComponent } from \"./components/extension-selector.ts\";\nimport { FooterComponent, formatTokens } from \"./components/footer.ts\";\nimport { formatKeyText, keyDisplayText, keyHint, keyText, rawKeyHint } from \"./components/keybinding-hints.ts\";\nimport { LoginDialogComponent } from \"./components/login-dialog.ts\";\nimport { ModelSelectorComponent } from \"./components/model-selector.ts\";\nimport {\n\ttype AuthSelectorProvider,\n\tformatAuthSelectorProviderType,\n\tOAuthSelectorComponent,\n} from \"./components/oauth-selector.ts\";\nimport { ScopedModelsSelectorComponent } from \"./components/scoped-models-selector.ts\";\nimport { SessionSelectorComponent } from \"./components/session-selector.ts\";\nimport { SettingsSelectorComponent } from \"./components/settings-selector.ts\";\nimport { SkillInvocationMessageComponent } from \"./components/skill-invocation-message.ts\";\nimport {\n\tBranchSummaryStatusIndicator,\n\tCompactionStatusIndicator,\n\tIdleStatus,\n\tRetryStatusIndicator,\n\ttype StatusIndicator,\n\tWorkingStatusIndicator,\n} from \"./components/status-indicator.ts\";\nimport { ToolExecutionComponent } from \"./components/tool-execution.ts\";\nimport { TreeSelectorComponent } from \"./components/tree-selector.ts\";\nimport { TrustSelectorComponent } from \"./components/trust-selector.ts\";\nimport { UserMessageComponent } from \"./components/user-message.ts\";\nimport { UserMessageSelectorComponent } from \"./components/user-message-selector.ts\";\nimport { editInExternalEditor } from \"./external-editor.ts\";\nimport { getModelSearchText } from \"./model-search.ts\";\nimport {\n\tgetAvailableThemes,\n\tgetAvailableThemesWithPaths,\n\tgetEditorTheme,\n\tgetMarkdownTheme,\n\tgetThemeByName,\n\tonThemeChange,\n\tsetRegisteredThemes,\n\tstopThemeWatcher,\n\tTheme,\n\ttype ThemeColor,\n\ttheme,\n} from \"./theme/theme.ts\";\nimport { InteractiveThemeController } from \"./theme/theme-controller.ts\";\n\n/** Interface for components that can be expanded/collapsed */\ninterface Expandable {\n\tsetExpanded(expanded: boolean): void;\n}\n\nfunction isExpandable(obj: unknown): obj is Expandable {\n\treturn typeof obj === \"object\" && obj !== null && \"setExpanded\" in obj && typeof obj.setExpanded === \"function\";\n}\n\nclass ExpandableText extends Text implements Expandable {\n\tprivate readonly getCollapsedText: () => string;\n\tprivate readonly getExpandedText: () => string;\n\n\tconstructor(\n\t\tgetCollapsedText: () => string,\n\t\tgetExpandedText: () => string,\n\t\texpanded = false,\n\t\tpaddingX = 0,\n\t\tpaddingY = 0,\n\t) {\n\t\tsuper(expanded ? getExpandedText() : getCollapsedText(), paddingX, paddingY);\n\t\tthis.getCollapsedText = getCollapsedText;\n\t\tthis.getExpandedText = getExpandedText;\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.setText(expanded ? this.getExpandedText() : this.getCollapsedText());\n\t}\n}\n\ntype CompactionQueuedMessage = {\n\ttext: string;\n\tmode: \"steer\" | \"followUp\";\n};\n\ntype RenderSessionItem = AgentMessage | Extract;\n\nfunction isCustomSessionEntry(item: RenderSessionItem): item is Extract {\n\treturn \"type\" in item && item.type === \"custom\";\n}\n\nconst DEAD_TERMINAL_ERROR_CODES = new Set([\"EIO\", \"EPIPE\", \"ENOTCONN\"]);\n\nfunction isDeadTerminalError(error: unknown): boolean {\n\tif (!error || typeof error !== \"object\" || !(\"code\" in error)) {\n\t\treturn false;\n\t}\n\tconst code = (error as NodeJS.ErrnoException).code;\n\treturn code !== undefined && DEAD_TERMINAL_ERROR_CODES.has(code);\n}\n\nconst ANTHROPIC_SUBSCRIPTION_AUTH_WARNING =\n\t\"Anthropic subscription auth is active. Third-party harness usage draws from extra usage and is billed per token, not your Claude plan limits. Manage extra usage at https://claude.ai/settings/usage. Disable this warning in /settings.\";\n\nfunction isAnthropicSubscriptionAuthKey(apiKey: string | undefined): boolean {\n\treturn typeof apiKey === \"string\" && apiKey.startsWith(\"sk-ant-oat\");\n}\n\nfunction isUnknownModel(model: Model | undefined): boolean {\n\treturn !!model && model.provider === \"unknown\" && model.id === \"unknown\" && model.api === \"unknown\";\n}\n\nfunction quoteIfNeeded(value: string): string {\n\tif (value.length > 0 && !/[^a-zA-Z0-9_\\-./~:@]/.test(value)) {\n\t\treturn value;\n\t}\n\treturn `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\nexport function formatResumeCommand(sessionManager: SessionManager): string | undefined {\n\tif (!process.stdout.isTTY) return undefined;\n\tif (!sessionManager.isPersisted()) return undefined;\n\n\tconst sessionFile = sessionManager.getSessionFile();\n\tif (!sessionFile || !fs.existsSync(sessionFile)) return undefined;\n\n\tconst args = [APP_NAME];\n\tif (!sessionManager.usesDefaultSessionDir()) {\n\t\targs.push(\"--session-dir\", quoteIfNeeded(sessionManager.getSessionDir()));\n\t}\n\targs.push(\"--session\", sessionManager.getSessionId());\n\treturn args.join(\" \");\n}\n\nfunction hasDefaultModelProvider(providerId: string): providerId is keyof typeof defaultModelPerProvider {\n\treturn providerId in defaultModelPerProvider;\n}\n\ntype LoginProviderCompletionOption = {\n\tid: string;\n\tname: string;\n\tauthTypes: AuthSelectorProvider[\"authType\"][];\n};\n\nconst AUTH_TYPE_ORDER = { oauth: 0, api_key: 1 } satisfies Record;\n\nfunction createFuzzyAutocompleteItems(\n\titems: T[],\n\tprefix: string,\n\tgetSearchText: (item: T) => string,\n\ttoAutocompleteItem: (item: T) => AutocompleteItem,\n): AutocompleteItem[] | null {\n\tconst filtered = fuzzyFilter(items, prefix, getSearchText);\n\tif (filtered.length === 0) return null;\n\treturn filtered.map(toAutocompleteItem);\n}\n\nfunction getLoginProviderCompletionOptions(\n\tproviderOptions: readonly AuthSelectorProvider[],\n): LoginProviderCompletionOption[] {\n\tconst byId = new Map();\n\tfor (const provider of providerOptions) {\n\t\tconst existing = byId.get(provider.id);\n\t\tif (existing) {\n\t\t\tif (!existing.authTypes.includes(provider.authType)) {\n\t\t\t\texisting.authTypes.push(provider.authType);\n\t\t\t\texisting.authTypes.sort((a, b) => AUTH_TYPE_ORDER[a] - AUTH_TYPE_ORDER[b]);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tbyId.set(provider.id, {\n\t\t\tid: provider.id,\n\t\t\tname: provider.name,\n\t\t\tauthTypes: [provider.authType],\n\t\t});\n\t}\n\treturn Array.from(byId.values()).sort((a, b) => a.name.localeCompare(b.name));\n}\n\nfunction getLoginProviderSearchText(provider: LoginProviderCompletionOption): string {\n\tconst authTypes = provider.authTypes\n\t\t.map((authType) => `${authType} ${formatAuthSelectorProviderType(authType)}`)\n\t\t.join(\" \");\n\treturn `${provider.id} ${provider.name} ${authTypes}`;\n}\n\nfunction formatLoginProviderCompletionDescription(provider: LoginProviderCompletionOption): string {\n\tconst authTypes = provider.authTypes.map(formatAuthSelectorProviderType).join(\"/\");\n\treturn provider.name === provider.id ? authTypes : `${provider.name} · ${authTypes}`;\n}\n\n/**\n * Options for InteractiveMode initialization.\n */\nexport interface InteractiveModeOptions {\n\t/** Providers that were migrated to auth.json (shows warning) */\n\tmigratedProviders?: string[];\n\t/** Warning message if session model couldn't be restored */\n\tmodelFallbackMessage?: string;\n\t/** Cwd to trust after reload if it gained a .pi directory during this implicitly trusted session. */\n\tautoTrustOnReloadCwd?: string;\n\t/** Initial message to send on startup (can include @file content) */\n\tinitialMessage?: string;\n\t/** Images to attach to the initial message */\n\tinitialImages?: ImageContent[];\n\t/** Additional messages to send after the initial message */\n\tinitialMessages?: string[];\n\t/** Force verbose startup (overrides quietStartup setting) */\n\tverbose?: boolean;\n}\n\nexport class InteractiveMode {\n\tprivate runtimeHost: AgentSessionRuntime;\n\tprivate ui: TUI;\n\tprivate loadedResourcesContainer: Container;\n\tprivate chatContainer: Container;\n\tprivate pendingMessagesContainer: Container;\n\tprivate statusContainer: Container;\n\tprivate defaultEditor: CustomEditor;\n\tprivate editor: EditorComponent;\n\tprivate editorComponentFactory: EditorFactory | undefined;\n\tprivate autocompleteProvider: AutocompleteProvider | undefined;\n\tprivate autocompleteProviderWrappers: AutocompleteProviderFactory[] = [];\n\tprivate fdPath: string | undefined;\n\tprivate editorContainer: Container;\n\tprivate footer: FooterComponent;\n\tprivate footerDataProvider: FooterDataProvider;\n\t// Stored so the same manager can be injected into custom editors, selectors, and extension UI.\n\tprivate keybindings: KeybindingsManager;\n\tprivate version: string;\n\tprivate isInitialized = false;\n\tprivate onInputCallback?: (text: string) => void;\n\tprivate pendingUserInputs: string[] = [];\n\tprivate activeStatusIndicator: StatusIndicator | undefined = undefined;\n\tprivate readonly idleStatus = new IdleStatus();\n\tprivate workingMessage: string | undefined = undefined;\n\tprivate workingVisible = true;\n\tprivate workingIndicatorOptions: WorkingIndicatorOptions | undefined = undefined;\n\tprivate readonly defaultWorkingMessage = \"Working...\";\n\tprivate readonly defaultHiddenThinkingLabel = \"Thinking...\";\n\tprivate hiddenThinkingLabel = this.defaultHiddenThinkingLabel;\n\n\tprivate lastSigintTime = 0;\n\tprivate lastEscapeTime = 0;\n\tprivate changelogMarkdown: string | undefined = undefined;\n\tprivate startupNoticesShown = false;\n\tprivate anthropicSubscriptionWarningShown = false;\n\n\t// Status line tracking (for mutating immediately-sequential status updates)\n\tprivate lastStatusSpacer: Spacer | undefined = undefined;\n\tprivate lastStatusText: Text | undefined = undefined;\n\n\t// Streaming message tracking\n\tprivate streamingComponent: AssistantMessageComponent | undefined = undefined;\n\tprivate streamingMessage: AssistantMessage | undefined = undefined;\n\n\t// Tool execution tracking: toolCallId -> component\n\tprivate pendingTools = new Map();\n\n\t// Tool output expansion state\n\tprivate toolOutputExpanded = false;\n\n\t// Thinking block visibility state\n\tprivate hideThinkingBlock = false;\n\tprivate outputPad = 1;\n\n\t// Skill commands: command name -> skill file path\n\tprivate skillCommands = new Map();\n\n\t// Agent subscription unsubscribe function\n\tprivate unsubscribe?: () => void;\n\tprivate signalCleanupHandlers: Array<() => void> = [];\n\n\t// Track if editor is in bash mode (text starts with !)\n\tprivate isBashMode = false;\n\n\t// Track current bash execution component\n\tprivate bashComponent: BashExecutionComponent | undefined = undefined;\n\n\t// Track pending bash components (shown in pending area, moved to chat on submit)\n\tprivate pendingBashComponents: BashExecutionComponent[] = [];\n\n\t// Auto-compaction state\n\tprivate autoCompactionEscapeHandler?: () => void;\n\n\t// Auto-retry state\n\tprivate retryEscapeHandler?: () => void;\n\n\t// Messages queued while compaction is running\n\tprivate compactionQueuedMessages: CompactionQueuedMessage[] = [];\n\n\t// Shutdown state\n\tprivate shutdownRequested = false;\n\n\t// Extension UI state\n\tprivate extensionSelector: ExtensionSelectorComponent | undefined = undefined;\n\tprivate extensionInput: ExtensionInputComponent | undefined = undefined;\n\tprivate extensionEditor: ExtensionEditorComponent | undefined = undefined;\n\tprivate extensionTerminalInputUnsubscribers = new Set<() => void>();\n\n\t// Extension widgets (components rendered above/below the editor)\n\tprivate extensionWidgetsAbove = new Map();\n\tprivate extensionWidgetsBelow = new Map();\n\tprivate widgetContainerAbove!: Container;\n\tprivate widgetContainerBelow!: Container;\n\n\t// Custom footer from extension (undefined = use built-in footer)\n\tprivate customFooter: (Component & { dispose?(): void }) | undefined = undefined;\n\n\t// Header container that holds the built-in or custom header\n\tprivate headerContainer: Container;\n\n\t// Built-in header (logo + keybinding hints + changelog)\n\tprivate builtInHeader: Component | undefined = undefined;\n\n\t// Custom header from extension (undefined = use built-in header)\n\tprivate customHeader: (Component & { dispose?(): void }) | undefined = undefined;\n\n\tprivate options: InteractiveModeOptions;\n\tprivate autoTrustOnReloadCwd: string | undefined;\n\tprivate themeController: InteractiveThemeController;\n\n\t// Convenience accessors\n\tprivate get session(): AgentSession {\n\t\treturn this.runtimeHost.session;\n\t}\n\tprivate get agent() {\n\t\treturn this.session.agent;\n\t}\n\tprivate get sessionManager() {\n\t\treturn this.session.sessionManager;\n\t}\n\tprivate get settingsManager() {\n\t\treturn this.session.settingsManager;\n\t}\n\n\tconstructor(runtimeHost: AgentSessionRuntime, options: InteractiveModeOptions = {}) {\n\t\tthis.runtimeHost = runtimeHost;\n\t\tthis.options = options;\n\t\tthis.autoTrustOnReloadCwd = options.autoTrustOnReloadCwd;\n\t\tthis.runtimeHost.setBeforeSessionInvalidate(() => {\n\t\t\tthis.resetExtensionUI();\n\t\t});\n\t\tthis.runtimeHost.setRebindSession(async () => {\n\t\t\tawait this.rebindCurrentSession({ renderBeforeBind: true });\n\t\t});\n\t\tthis.version = VERSION;\n\t\tthis.ui = new TUI(new ProcessTerminal(), this.settingsManager.getShowHardwareCursor(), getAgentDir());\n\t\tthis.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());\n\t\tthis.headerContainer = new Container();\n\t\tthis.loadedResourcesContainer = new Container();\n\t\tthis.chatContainer = new Container();\n\t\tthis.pendingMessagesContainer = new Container();\n\t\tthis.statusContainer = new Container();\n\t\tthis.widgetContainerAbove = new Container();\n\t\tthis.widgetContainerBelow = new Container();\n\t\tthis.keybindings = KeybindingsManager.create();\n\t\tsetKeybindings(this.keybindings);\n\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\tthis.defaultEditor = new CustomEditor(this.ui, getEditorTheme(), this.keybindings, {\n\t\t\tpaddingX: editorPaddingX,\n\t\t\tautocompleteMaxVisible,\n\t\t});\n\t\tthis.editor = this.defaultEditor;\n\t\tthis.editorContainer = new Container();\n\t\tthis.editorContainer.addChild(this.editor as Component);\n\t\tthis.footerDataProvider = new FooterDataProvider(this.sessionManager.getCwd());\n\t\tthis.footer = new FooterComponent(this.session, this.footerDataProvider);\n\t\tthis.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);\n\n\t\t// Load hide thinking block setting\n\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\n\t\t// Register themes from resource loader and initialize\n\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\tthis.themeController = new InteractiveThemeController(\n\t\t\tthis.ui,\n\t\t\tthis.settingsManager,\n\t\t\t(message) => this.showError(message),\n\t\t\t() => this.updateEditorBorderColor(),\n\t\t);\n\t}\n\n\tprivate getAutocompleteSourceTag(sourceInfo?: SourceInfo): string | undefined {\n\t\tif (!sourceInfo) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst scopePrefix = sourceInfo.scope === \"user\" ? \"u\" : sourceInfo.scope === \"project\" ? \"p\" : \"t\";\n\t\tconst source = sourceInfo.source.trim();\n\n\t\tif (source === \"auto\" || source === \"local\" || source === \"cli\") {\n\t\t\treturn scopePrefix;\n\t\t}\n\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\treturn `${scopePrefix}:${source}`;\n\t\t}\n\n\t\tconst gitSource = parseGitUrl(source);\n\t\tif (gitSource) {\n\t\t\tconst ref = gitSource.ref ? `@${gitSource.ref}` : \"\";\n\t\t\treturn `${scopePrefix}:git:${gitSource.host}/${gitSource.path}${ref}`;\n\t\t}\n\n\t\treturn scopePrefix;\n\t}\n\n\tprivate prefixAutocompleteDescription(description: string | undefined, sourceInfo?: SourceInfo): string | undefined {\n\t\tconst sourceTag = this.getAutocompleteSourceTag(sourceInfo);\n\t\tif (!sourceTag) {\n\t\t\treturn description;\n\t\t}\n\t\treturn description ? `[${sourceTag}] ${description}` : `[${sourceTag}]`;\n\t}\n\n\tprivate getBuiltInCommandConflictDiagnostics(extensionRunner: ExtensionRunner): ResourceDiagnostic[] {\n\t\tconst builtinNames = new Set(BUILTIN_SLASH_COMMANDS.map((command) => command.name));\n\t\treturn extensionRunner\n\t\t\t.getRegisteredCommands()\n\t\t\t.filter((command) => builtinNames.has(command.name))\n\t\t\t.map((command) => ({\n\t\t\t\ttype: \"warning\" as const,\n\t\t\t\tmessage:\n\t\t\t\t\tcommand.invocationName === command.name\n\t\t\t\t\t\t? `Extension command '/${command.name}' conflicts with built-in interactive command. Skipping in autocomplete.`\n\t\t\t\t\t\t: `Extension command '/${command.name}' conflicts with built-in interactive command. Available as '/${command.invocationName}'.`,\n\t\t\t\tpath: command.sourceInfo.path,\n\t\t\t}));\n\t}\n\n\tprivate createBaseAutocompleteProvider(): AutocompleteProvider {\n\t\t// Define commands for autocomplete\n\t\tconst slashCommands: SlashCommand[] = BUILTIN_SLASH_COMMANDS.map((command) => ({\n\t\t\tname: command.name,\n\t\t\tdescription: command.description,\n\t\t\t...(command.argumentHint && { argumentHint: command.argumentHint }),\n\t\t}));\n\n\t\tconst modelCommand = slashCommands.find((command) => command.name === \"model\");\n\t\tif (modelCommand) {\n\t\t\tmodelCommand.getArgumentCompletions = async (prefix: string): Promise => {\n\t\t\t\t// Get available models (scoped or from registry)\n\t\t\t\tconst models =\n\t\t\t\t\tthis.session.scopedModels.length > 0\n\t\t\t\t\t\t? this.session.scopedModels.map((s) => s.model)\n\t\t\t\t\t\t: await this.session.modelRuntime.getAvailable();\n\n\t\t\t\tif (models.length === 0) return null;\n\n\t\t\t\t// Create items with provider/id format\n\t\t\t\tconst items = models.map((m) => ({\n\t\t\t\t\tid: m.id,\n\t\t\t\t\tprovider: m.provider,\n\t\t\t\t\tname: m.name,\n\t\t\t\t\tlabel: `${m.provider}/${m.id}`,\n\t\t\t\t}));\n\n\t\t\t\treturn createFuzzyAutocompleteItems(items, prefix, getModelSearchText, (item) => ({\n\t\t\t\t\tvalue: item.label,\n\t\t\t\t\tlabel: item.id,\n\t\t\t\t\tdescription: item.provider,\n\t\t\t\t}));\n\t\t\t};\n\t\t}\n\n\t\tconst loginCommand = slashCommands.find((command) => command.name === \"login\");\n\t\tif (loginCommand) {\n\t\t\tloginCommand.getArgumentCompletions = (prefix: string): AutocompleteItem[] | null => {\n\t\t\t\tconst providers = getLoginProviderCompletionOptions(this.getLoginProviderOptions());\n\t\t\t\treturn createFuzzyAutocompleteItems(providers, prefix, getLoginProviderSearchText, (provider) => ({\n\t\t\t\t\tvalue: provider.id,\n\t\t\t\t\tlabel: provider.id,\n\t\t\t\t\tdescription: formatLoginProviderCompletionDescription(provider),\n\t\t\t\t}));\n\t\t\t};\n\t\t}\n\n\t\t// Convert prompt templates to SlashCommand format for autocomplete\n\t\tconst templateCommands: SlashCommand[] = this.session.promptTemplates.map((cmd) => ({\n\t\t\tname: cmd.name,\n\t\t\tdescription: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),\n\t\t\t...(cmd.argumentHint && { argumentHint: cmd.argumentHint }),\n\t\t}));\n\n\t\t// Convert extension commands to SlashCommand format\n\t\tconst builtinCommandNames = new Set(slashCommands.map((c) => c.name));\n\t\tconst extensionCommands: SlashCommand[] = this.session.extensionRunner\n\t\t\t.getRegisteredCommands()\n\t\t\t.filter((cmd) => !builtinCommandNames.has(cmd.name))\n\t\t\t.map((cmd) => ({\n\t\t\t\tname: cmd.invocationName,\n\t\t\t\tdescription: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),\n\t\t\t\tgetArgumentCompletions: cmd.getArgumentCompletions,\n\t\t\t}));\n\n\t\t// Build skill commands from session.skills (if enabled)\n\t\tthis.skillCommands.clear();\n\t\tconst skillCommandList: SlashCommand[] = [];\n\t\tif (this.settingsManager.getEnableSkillCommands()) {\n\t\t\tfor (const skill of this.session.resourceLoader.getSkills().skills) {\n\t\t\t\tconst commandName = `skill:${skill.name}`;\n\t\t\t\tthis.skillCommands.set(commandName, skill.filePath);\n\t\t\t\tskillCommandList.push({\n\t\t\t\t\tname: commandName,\n\t\t\t\t\tdescription: this.prefixAutocompleteDescription(skill.description, skill.sourceInfo),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn new CombinedAutocompleteProvider(\n\t\t\t[...slashCommands, ...templateCommands, ...extensionCommands, ...skillCommandList],\n\t\t\tthis.sessionManager.getCwd(),\n\t\t\tthis.fdPath,\n\t\t);\n\t}\n\n\tprivate setupAutocompleteProvider(): void {\n\t\tlet provider = this.createBaseAutocompleteProvider();\n\t\tconst triggerCharacters: string[] = [];\n\t\tfor (const wrapProvider of this.autocompleteProviderWrappers) {\n\t\t\tprovider = wrapProvider(provider);\n\t\t\ttriggerCharacters.push(...(provider.triggerCharacters ?? []));\n\t\t}\n\t\tif (triggerCharacters.length > 0) {\n\t\t\tprovider.triggerCharacters = [...new Set(triggerCharacters)];\n\t\t}\n\n\t\tthis.autocompleteProvider = provider;\n\t\tthis.defaultEditor.setAutocompleteProvider(provider);\n\t\tif (this.editor !== this.defaultEditor) {\n\t\t\tthis.editor.setAutocompleteProvider?.(provider);\n\t\t}\n\t}\n\n\tprivate showStartupNoticesIfNeeded(): void {\n\t\tif (this.startupNoticesShown) {\n\t\t\treturn;\n\t\t}\n\t\tthis.startupNoticesShown = true;\n\n\t\tif (!this.changelogMarkdown) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.chatContainer.children.length > 0) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tif (this.settingsManager.getCollapseChangelog()) {\n\t\t\tconst versionMatch = this.changelogMarkdown.match(/##\\s+\\[?(\\d+\\.\\d+\\.\\d+)\\]?/);\n\t\t\tconst latestVersion = versionMatch ? versionMatch[1] : this.version;\n\t\t\tconst condensedText = `Updated to v${latestVersion}. Use ${theme.bold(\"/changelog\")} to view full changelog.`;\n\t\t\tthis.chatContainer.addChild(new Text(condensedText, 1, 0));\n\t\t} else {\n\t\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(\n\t\t\t\tnew Markdown(this.changelogMarkdown.trim(), 1, 0, this.getMarkdownThemeWithSettings()),\n\t\t\t);\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t}\n\n\tasync init(): Promise {\n\t\tif (this.isInitialized) return;\n\n\t\tthis.registerSignalHandlers();\n\n\t\t// Load changelog (only show new entries, skip for resumed sessions)\n\t\tthis.changelogMarkdown = this.getChangelogForDisplay();\n\n\t\t// Ensure fd and rg are available (downloads if missing, adds to PATH via getBinDir)\n\t\t// Both are needed: fd for autocomplete, rg for grep tool and bash commands\n\t\tconst [fdPath] = await Promise.all([ensureTool(\"fd\"), ensureTool(\"rg\")]);\n\t\tthis.fdPath = fdPath;\n\n\t\tif (this.session.scopedModels.length > 0 && (this.options.verbose || !this.settingsManager.getQuietStartup())) {\n\t\t\tconst modelList = this.session.scopedModels\n\t\t\t\t.map((sm) => {\n\t\t\t\t\tconst thinkingStr = sm.thinkingLevel ? `:${sm.thinkingLevel}` : \"\";\n\t\t\t\t\treturn `${sm.model.id}${thinkingStr}`;\n\t\t\t\t})\n\t\t\t\t.join(\", \");\n\t\t\tconst cycleKeys = this.keybindings.getKeys(\"app.model.cycleForward\");\n\t\t\tconst cycleHint =\n\t\t\t\tcycleKeys.length > 0\n\t\t\t\t\t? theme.fg(\"muted\", ` (${formatKeyText(cycleKeys.join(\"/\"), { capitalize: true })} to cycle)`)\n\t\t\t\t\t: \"\";\n\t\t\tconsole.log(theme.fg(\"dim\", `Model scope: ${modelList}${cycleHint}`));\n\t\t}\n\n\t\t// Add header container as first child. Populate it after applying theme settings.\n\t\t// Keep loaded resources before chat so restored session messages never precede them.\n\t\tthis.ui.addChild(this.headerContainer);\n\t\tthis.ui.addChild(this.loadedResourcesContainer);\n\n\t\tthis.ui.addChild(this.chatContainer);\n\t\tthis.ui.addChild(this.pendingMessagesContainer);\n\t\tthis.ui.addChild(this.statusContainer);\n\t\tthis.renderWidgets(); // Initialize with default spacer\n\t\tthis.ui.addChild(this.widgetContainerAbove);\n\t\tthis.ui.addChild(this.editorContainer);\n\t\tthis.ui.addChild(this.widgetContainerBelow);\n\t\tthis.ui.addChild(this.footer);\n\t\tthis.ui.setFocus(this.editor);\n\n\t\tthis.setupKeyHandlers();\n\t\tthis.setupEditorSubmitHandler();\n\n\t\t// Start the UI before initializing extensions so session_start handlers can use interactive dialogs\n\t\tthis.ui.start();\n\t\tthis.isInitialized = true;\n\n\t\tawait this.themeController.applyFromSettings();\n\n\t\t// Add header with keybindings from config (unless silenced)\n\t\tif (this.options.verbose || !this.settingsManager.getQuietStartup()) {\n\t\t\tconst logo = theme.bold(theme.fg(\"accent\", APP_NAME)) + theme.fg(\"dim\", ` v${this.version}`);\n\n\t\t\t// Build startup instructions using keybinding hint helpers\n\t\t\tconst hint = (keybinding: AppKeybinding, description: string) => keyHint(keybinding, description);\n\n\t\t\tconst expandedInstructions = [\n\t\t\t\thint(\"app.interrupt\", \"to interrupt\"),\n\t\t\t\thint(\"app.clear\", \"to clear\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.clear\")} twice`, \"to exit\"),\n\t\t\t\thint(\"app.exit\", \"to exit (empty)\"),\n\t\t\t\thint(\"app.suspend\", \"to suspend\"),\n\t\t\t\tkeyHint(\"tui.editor.deleteToLineEnd\", \"to delete to end\"),\n\t\t\t\thint(\"app.thinking.cycle\", \"to cycle thinking level\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.model.cycleForward\")}/${keyText(\"app.model.cycleBackward\")}`, \"to cycle models\"),\n\t\t\t\thint(\"app.model.select\", \"to select model\"),\n\t\t\t\thint(\"app.tools.expand\", \"to expand tools\"),\n\t\t\t\thint(\"app.thinking.toggle\", \"to expand thinking\"),\n\t\t\t\thint(\"app.editor.external\", \"for external editor\"),\n\t\t\t\trawKeyHint(\"/\", \"for commands\"),\n\t\t\t\trawKeyHint(\"!\", \"to run bash\"),\n\t\t\t\trawKeyHint(\"!!\", \"to run bash (no context)\"),\n\t\t\t\thint(\"app.message.followUp\", \"to queue follow-up\"),\n\t\t\t\thint(\"app.message.dequeue\", \"to edit all queued messages\"),\n\t\t\t\thint(\"app.clipboard.pasteImage\", \"to paste image (with text fallback)\"),\n\t\t\t\trawKeyHint(\"drop files\", \"to attach\"),\n\t\t\t].join(\"\\n\");\n\t\t\tconst compactInstructions = [\n\t\t\t\thint(\"app.interrupt\", \"interrupt\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.clear\")}/${keyText(\"app.exit\")}`, \"clear/exit\"),\n\t\t\t\trawKeyHint(\"/\", \"commands\"),\n\t\t\t\trawKeyHint(\"!\", \"bash\"),\n\t\t\t\thint(\"app.tools.expand\", \"more\"),\n\t\t\t].join(theme.fg(\"muted\", \" · \"));\n\t\t\tconst compactOnboarding = theme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t`Press ${keyText(\"app.tools.expand\")} to show full startup help and loaded resources.`,\n\t\t\t);\n\t\t\tconst onboarding = theme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t`Pi can explain its own features and look up its docs. Ask it how to use or extend Pi.`,\n\t\t\t);\n\t\t\tthis.builtInHeader = new ExpandableText(\n\t\t\t\t() => `${logo}\\n${compactInstructions}\\n${compactOnboarding}\\n\\n${onboarding}`,\n\t\t\t\t() => `${logo}\\n${expandedInstructions}\\n\\n${onboarding}`,\n\t\t\t\tthis.getStartupExpansionState(),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t);\n\n\t\t\t// Setup UI layout\n\t\t\tthis.headerContainer.addChild(new Spacer(1));\n\t\t\tthis.headerContainer.addChild(this.builtInHeader);\n\t\t\tthis.headerContainer.addChild(new Spacer(1));\n\t\t} else {\n\t\t\t// Minimal header when silenced\n\t\t\tthis.builtInHeader = new Text(\"\", 0, 0);\n\t\t\tthis.headerContainer.addChild(this.builtInHeader);\n\t\t}\n\t\tthis.ui.requestRender();\n\n\t\t// Initialize extensions first so resources are shown before messages\n\t\tawait this.rebindCurrentSession();\n\n\t\t// Render initial messages AFTER showing loaded resources\n\t\tthis.renderInitialMessages();\n\n\t\t// Set up theme file watcher\n\t\tonThemeChange(() => {\n\t\t\tthis.ui.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.ui.requestRender();\n\t\t});\n\n\t\t// Set up git branch watcher (uses provider instead of footer)\n\t\tthis.footerDataProvider.onBranchChange(() => {\n\t\t\tthis.ui.requestRender();\n\t\t});\n\n\t\t// Initialize available provider count for footer display\n\t\tawait this.updateAvailableProviderCount();\n\t}\n\n\t/**\n\t * Update terminal title with session name and cwd.\n\t */\n\tprivate updateTerminalTitle(): void {\n\t\tconst cwdBasename = path.basename(this.sessionManager.getCwd());\n\t\tconst sessionName = this.sessionManager.getSessionName();\n\t\tif (sessionName) {\n\t\t\tthis.ui.terminal.setTitle(`${APP_TITLE} - ${sessionName} - ${cwdBasename}`);\n\t\t} else {\n\t\t\tthis.ui.terminal.setTitle(`${APP_TITLE} - ${cwdBasename}`);\n\t\t}\n\t}\n\n\t/**\n\t * Run the interactive mode. This is the main entry point.\n\t * Initializes the UI, shows warnings, processes initial messages, and starts the interactive loop.\n\t */\n\tasync run(): Promise {\n\t\tawait this.init();\n\n\t\tif (!process.env.PI_OFFLINE) {\n\t\t\tvoid this.session.modelRuntime\n\t\t\t\t.refresh()\n\t\t\t\t.then(() => this.updateAvailableProviderCount())\n\t\t\t\t.catch(() => {});\n\t\t}\n\n\t\t// Start version check asynchronously\n\t\tcheckForNewPiVersion(this.version).then((newRelease) => {\n\t\t\tif (newRelease) {\n\t\t\t\tthis.showNewVersionNotification(newRelease);\n\t\t\t}\n\t\t});\n\n\t\t// Start package update check asynchronously\n\t\tthis.checkForPackageUpdates()\n\t\t\t.then((updates) => {\n\t\t\t\tif (updates.length > 0) {\n\t\t\t\t\tthis.showPackageUpdateNotification(updates);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\t// On Windows, npm can overwrite the shared console title while checking\n\t\t\t\t// extension package versions. Restore Pi's title after the startup check.\n\t\t\t\tif (process.platform === \"win32\" && this.isInitialized) {\n\t\t\t\t\tthis.updateTerminalTitle();\n\t\t\t\t}\n\t\t\t});\n\n\t\t// Check tmux keyboard setup asynchronously\n\t\tthis.checkTmuxKeyboardSetup().then((warning) => {\n\t\t\tif (warning) {\n\t\t\t\tthis.showWarning(warning);\n\t\t\t}\n\t\t});\n\n\t\t// Show startup warnings\n\t\tconst { migratedProviders, modelFallbackMessage, initialMessage, initialImages, initialMessages } = this.options;\n\n\t\tif (migratedProviders && migratedProviders.length > 0) {\n\t\t\tthis.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(\", \")}`);\n\t\t}\n\n\t\tconst modelsJsonError = this.session.modelRuntime.getError();\n\t\tif (modelsJsonError) {\n\t\t\tthis.showError(`models.json error: ${modelsJsonError}`);\n\t\t}\n\n\t\tif (modelFallbackMessage) {\n\t\t\tthis.showWarning(modelFallbackMessage);\n\t\t}\n\n\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth();\n\n\t\t// Process initial messages\n\t\tif (initialMessage) {\n\t\t\ttry {\n\t\t\t\tawait this.session.prompt(initialMessage, { images: initialImages });\n\t\t\t} catch (error: unknown) {\n\t\t\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\t\tthis.showError(errorMessage);\n\t\t\t}\n\t\t}\n\n\t\tif (initialMessages) {\n\t\t\tfor (const message of initialMessages) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.session.prompt(message);\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\t\t\tthis.showError(errorMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Main interactive loop\n\t\twhile (true) {\n\t\t\tconst userInput = await this.getUserInput();\n\t\t\ttry {\n\t\t\t\tawait this.session.prompt(userInput);\n\t\t\t} catch (error: unknown) {\n\t\t\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\t\tthis.showError(errorMessage);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async checkForPackageUpdates(): Promise {\n\t\tif (process.env.PI_OFFLINE) {\n\t\t\treturn [];\n\t\t}\n\n\t\ttry {\n\t\t\tconst packageManager = new DefaultPackageManager({\n\t\t\t\tcwd: this.sessionManager.getCwd(),\n\t\t\t\tagentDir: getAgentDir(),\n\t\t\t\tsettingsManager: this.settingsManager,\n\t\t\t});\n\t\t\tconst updates = await packageManager.checkForAvailableUpdates();\n\t\t\treturn updates.map((update) => update.displayName);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\tprivate async checkTmuxKeyboardSetup(): Promise {\n\t\tif (!process.env.TMUX) return undefined;\n\n\t\tconst runTmuxShow = (option: string): Promise => {\n\t\t\treturn new Promise((resolve) => {\n\t\t\t\tconst proc = spawn(\"tmux\", [\"show\", \"-gv\", option], {\n\t\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t\t});\n\t\t\t\tlet stdout = \"\";\n\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\tproc.kill();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t}, 2000);\n\n\t\t\t\tproc.stdout?.on(\"data\", (data) => {\n\t\t\t\t\tstdout += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.on(\"error\", () => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t});\n\t\t\t\tproc.on(\"close\", (code) => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(code === 0 ? stdout.trim() : undefined);\n\t\t\t\t});\n\t\t\t});\n\t\t};\n\n\t\tconst [extendedKeys, extendedKeysFormat] = await Promise.all([\n\t\t\trunTmuxShow(\"extended-keys\"),\n\t\t\trunTmuxShow(\"extended-keys-format\"),\n\t\t]);\n\n\t\t// If we couldn't query tmux (timeout, sandbox, etc.), don't warn\n\t\tif (extendedKeys === undefined) return undefined;\n\n\t\tif (extendedKeys !== \"on\" && extendedKeys !== \"always\") {\n\t\t\treturn \"tmux extended-keys is off. Modified Enter keys may not work. Add `set -g extended-keys on` to ~/.tmux.conf and restart tmux.\";\n\t\t}\n\n\t\tif (extendedKeysFormat === \"xterm\") {\n\t\t\treturn \"tmux extended-keys-format is xterm. Pi works best with csi-u. Add `set -g extended-keys-format csi-u` to ~/.tmux.conf and restart tmux.\";\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Get changelog entries to display on startup.\n\t * Only shows new entries since last seen version, skips for resumed sessions.\n\t */\n\tprivate getChangelogForDisplay(): string | undefined {\n\t\t// Skip changelog for resumed/continued sessions (already have messages)\n\t\tif (this.session.state.messages.length > 0) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst lastVersion = this.settingsManager.getLastChangelogVersion();\n\t\tconst changelogPath = getChangelogPath();\n\t\tconst entries = parseChangelog(changelogPath);\n\n\t\tif (!lastVersion) {\n\t\t\t// Fresh install - record the version, send telemetry, don't show changelog\n\t\t\tthis.settingsManager.setLastChangelogVersion(VERSION);\n\t\t\tthis.reportInstallTelemetry(VERSION);\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst newEntries = getNewEntries(entries, lastVersion);\n\t\tif (newEntries.length > 0) {\n\t\t\tthis.settingsManager.setLastChangelogVersion(VERSION);\n\t\t\tthis.reportInstallTelemetry(VERSION);\n\t\t\treturn newEntries.map((e) => normalizeChangelogLinks(e.content, e)).join(\"\\n\\n\");\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate reportInstallTelemetry(version: string): void {\n\t\tif (process.env.PI_OFFLINE) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!isInstallTelemetryEnabled(this.settingsManager)) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid fetch(`https://pi.dev/api/report-install?version=${encodeURIComponent(version)}`, {\n\t\t\theaders: {\n\t\t\t\t\"User-Agent\": getPiUserAgent(version),\n\t\t\t},\n\t\t\tsignal: AbortSignal.timeout(5000),\n\t\t})\n\t\t\t.then(() => undefined)\n\t\t\t.catch(() => undefined);\n\t}\n\n\tprivate getMarkdownThemeWithSettings(): MarkdownTheme {\n\t\treturn {\n\t\t\t...getMarkdownTheme(),\n\t\t\tcodeBlockIndent: this.settingsManager.getCodeBlockIndent(),\n\t\t};\n\t}\n\n\t// =========================================================================\n\t// Extension System\n\t// =========================================================================\n\n\tprivate formatDisplayPath(p: string): string {\n\t\tconst home = os.homedir();\n\t\tlet result = p;\n\n\t\t// Replace home directory with ~\n\t\tif (result.startsWith(home)) {\n\t\t\tresult = `~${result.slice(home.length)}`;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate formatExtensionDisplayPath(path: string): string {\n\t\tlet result = this.formatDisplayPath(path);\n\t\tresult = result.replace(/\\/index\\.ts$/, \"\").replace(/\\/index\\.js$/, \"\");\n\t\treturn result;\n\t}\n\n\tprivate formatContextPath(p: string): string {\n\t\tconst cwd = path.resolve(this.sessionManager.getCwd());\n\t\tconst absolutePath = path.isAbsolute(p) ? path.resolve(p) : path.resolve(cwd, p);\n\t\tconst relativePath = getCwdRelativePath(absolutePath, cwd);\n\t\tif (relativePath !== undefined) {\n\t\t\treturn relativePath;\n\t\t}\n\n\t\treturn this.formatDisplayPath(absolutePath);\n\t}\n\n\tprivate getStartupExpansionState(): boolean {\n\t\treturn this.options.verbose || this.toolOutputExpanded;\n\t}\n\n\t/**\n\t * Get a short path relative to the package root for display.\n\t */\n\tprivate getShortPath(fullPath: string, sourceInfo?: SourceInfo): string {\n\t\tconst normalizedFullPath = fullPath.replace(/\\\\/g, \"/\");\n\t\tconst baseDir = sourceInfo?.baseDir;\n\t\tif (baseDir && this.isPackageSource(sourceInfo)) {\n\t\t\tconst normalizedBaseDir = baseDir.replace(/\\\\/g, \"/\");\n\t\t\tconst npmRootMatch = normalizedBaseDir.match(/^(.*\\/node_modules)\\/(@?[^/]+(?:\\/[^/]+)?)$/);\n\t\t\t// If fullPath is under the same node_modules root as baseDir, preserve that relative topology.\n\t\t\tif (npmRootMatch?.[1] && normalizedFullPath.startsWith(`${npmRootMatch[1]}/`)) {\n\t\t\t\treturn path.posix.relative(normalizedBaseDir, normalizedFullPath);\n\t\t\t}\n\n\t\t\tconst relativePath = path.relative(path.resolve(baseDir), path.resolve(fullPath));\n\t\t\tif (\n\t\t\t\trelativePath &&\n\t\t\t\trelativePath !== \".\" &&\n\t\t\t\t!relativePath.startsWith(\"..\") &&\n\t\t\t\t!relativePath.startsWith(`..${path.sep}`) &&\n\t\t\t\t!path.isAbsolute(relativePath)\n\t\t\t) {\n\t\t\t\treturn relativePath.replace(/\\\\/g, \"/\");\n\t\t\t}\n\t\t}\n\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\tconst npmMatch = normalizedFullPath.match(/node_modules\\/(@?[^/]+(?:\\/[^/]+)?)\\/(.*)/);\n\t\tif (npmMatch && source.startsWith(\"npm:\")) {\n\t\t\treturn npmMatch[2];\n\t\t}\n\n\t\tconst gitMatch = normalizedFullPath.match(/git\\/[^/]+\\/[^/]+\\/(.*)/);\n\t\tif (gitMatch && source.startsWith(\"git:\")) {\n\t\t\treturn gitMatch[1];\n\t\t}\n\n\t\treturn this.formatDisplayPath(fullPath);\n\t}\n\n\tprivate getCompactPathLabel(resourcePath: string, sourceInfo?: SourceInfo): string {\n\t\tconst shortPath = this.getShortPath(resourcePath, sourceInfo);\n\t\tconst normalizedPath = shortPath.replace(/\\\\/g, \"/\");\n\t\tconst segments = normalizedPath.split(\"/\").filter((segment) => segment.length > 0 && segment !== \"~\");\n\t\tif (segments.length > 0) {\n\t\t\treturn segments[segments.length - 1]!;\n\t\t}\n\t\treturn shortPath;\n\t}\n\n\tprivate getCompactPackageSourceLabel(sourceInfo?: SourceInfo): string {\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\treturn source.slice(\"npm:\".length) || source;\n\t\t}\n\n\t\tconst gitSource = parseGitUrl(source);\n\t\tif (gitSource) {\n\t\t\treturn gitSource.path || source;\n\t\t}\n\n\t\treturn source;\n\t}\n\n\tprivate getCompactExtensionLabel(resourcePath: string, sourceInfo?: SourceInfo): string {\n\t\tif (!this.isPackageSource(sourceInfo)) {\n\t\t\treturn this.getCompactPathLabel(resourcePath, sourceInfo);\n\t\t}\n\n\t\tconst sourceLabel = this.getCompactPackageSourceLabel(sourceInfo);\n\t\tif (!sourceLabel) {\n\t\t\treturn this.getCompactPathLabel(resourcePath, sourceInfo);\n\t\t}\n\n\t\tconst shortPath = this.getShortPath(resourcePath, sourceInfo).replace(/\\\\/g, \"/\");\n\t\tconst packagePath = shortPath.startsWith(\"extensions/\") ? shortPath.slice(\"extensions/\".length) : shortPath;\n\t\tconst parsedPath = path.posix.parse(packagePath);\n\n\t\tif (parsedPath.name === \"index\") {\n\t\t\treturn !parsedPath.dir || parsedPath.dir === \".\" ? sourceLabel : `${sourceLabel}:${parsedPath.dir}`;\n\t\t}\n\n\t\treturn `${sourceLabel}:${packagePath}`;\n\t}\n\n\tprivate getCompactDisplayPathSegments(resourcePath: string): string[] {\n\t\treturn this.formatDisplayPath(resourcePath)\n\t\t\t.replace(/\\\\/g, \"/\")\n\t\t\t.split(\"/\")\n\t\t\t.filter((segment) => segment.length > 0 && segment !== \"~\");\n\t}\n\n\tprivate getCompactNonPackageExtensionLabel(\n\t\tresourcePath: string,\n\t\tindex: number,\n\t\tallPaths: Array<{ path: string; segments: string[] }>,\n\t): string {\n\t\tconst segments = allPaths[index]?.segments;\n\t\tif (!segments || segments.length === 0) {\n\t\t\treturn this.getCompactPathLabel(resourcePath);\n\t\t}\n\n\t\tfor (let segmentCount = 1; segmentCount <= segments.length; segmentCount += 1) {\n\t\t\tconst candidate = segments.slice(-segmentCount).join(\"/\");\n\t\t\tconst isUnique = allPaths.every((item, itemIndex) => {\n\t\t\t\tif (itemIndex === index) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn item.segments.slice(-segmentCount).join(\"/\") !== candidate;\n\t\t\t});\n\n\t\t\tif (isUnique) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\n\t\treturn segments.join(\"/\");\n\t}\n\n\tprivate getCompactExtensionLabels(extensions: Array<{ path: string; sourceInfo?: SourceInfo }>): string[] {\n\t\tconst nonPackageExtensions = extensions\n\t\t\t.map((extension) => {\n\t\t\t\tconst segments = this.getCompactDisplayPathSegments(extension.path);\n\t\t\t\tconst lastSegment = segments[segments.length - 1];\n\t\t\t\tif (segments.length > 1 && (lastSegment === \"index.ts\" || lastSegment === \"index.js\")) {\n\t\t\t\t\tsegments.pop();\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tpath: extension.path,\n\t\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\t\tsegments,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter((extension) => !this.isPackageSource(extension.sourceInfo));\n\n\t\treturn extensions.map((extension) => {\n\t\t\tif (this.isPackageSource(extension.sourceInfo)) {\n\t\t\t\treturn this.getCompactExtensionLabel(extension.path, extension.sourceInfo);\n\t\t\t}\n\n\t\t\tconst nonPackageIndex = nonPackageExtensions.findIndex((item) => item.path === extension.path);\n\t\t\tif (nonPackageIndex === -1) {\n\t\t\t\treturn this.getCompactPathLabel(extension.path, extension.sourceInfo);\n\t\t\t}\n\n\t\t\treturn this.getCompactNonPackageExtensionLabel(extension.path, nonPackageIndex, nonPackageExtensions);\n\t\t});\n\t}\n\n\tprivate getDisplaySourceInfo(sourceInfo?: SourceInfo): {\n\t\tlabel: string;\n\t\tscopeLabel?: string;\n\t\tcolor: \"accent\" | \"muted\";\n\t} {\n\t\tconst source = sourceInfo?.source ?? \"local\";\n\t\tconst scope = sourceInfo?.scope ?? \"project\";\n\t\tif (source === \"local\") {\n\t\t\tif (scope === \"user\") {\n\t\t\t\treturn { label: \"user\", color: \"muted\" };\n\t\t\t}\n\t\t\tif (scope === \"project\") {\n\t\t\t\treturn { label: \"project\", color: \"muted\" };\n\t\t\t}\n\t\t\tif (scope === \"temporary\") {\n\t\t\t\treturn { label: \"path\", scopeLabel: \"temp\", color: \"muted\" };\n\t\t\t}\n\t\t\treturn { label: \"path\", color: \"muted\" };\n\t\t}\n\n\t\tif (source === \"cli\") {\n\t\t\treturn { label: \"path\", scopeLabel: scope === \"temporary\" ? \"temp\" : undefined, color: \"muted\" };\n\t\t}\n\n\t\tconst scopeLabel =\n\t\t\tscope === \"user\" ? \"user\" : scope === \"project\" ? \"project\" : scope === \"temporary\" ? \"temp\" : undefined;\n\t\treturn { label: source, scopeLabel, color: \"accent\" };\n\t}\n\n\tprivate getScopeGroup(sourceInfo?: SourceInfo): \"user\" | \"project\" | \"path\" {\n\t\tconst source = sourceInfo?.source ?? \"local\";\n\t\tconst scope = sourceInfo?.scope ?? \"project\";\n\t\tif (source === \"cli\" || scope === \"temporary\") return \"path\";\n\t\tif (scope === \"user\") return \"user\";\n\t\tif (scope === \"project\") return \"project\";\n\t\treturn \"path\";\n\t}\n\n\tprivate isPackageSource(sourceInfo?: SourceInfo): boolean {\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\treturn source.startsWith(\"npm:\") || source.startsWith(\"git:\");\n\t}\n\n\tprivate buildScopeGroups(items: Array<{ path: string; sourceInfo?: SourceInfo }>): Array<{\n\t\tscope: \"user\" | \"project\" | \"path\";\n\t\tpaths: Array<{ path: string; sourceInfo?: SourceInfo }>;\n\t\tpackages: Map>;\n\t}> {\n\t\tconst groups: Record<\n\t\t\t\"user\" | \"project\" | \"path\",\n\t\t\t{\n\t\t\t\tscope: \"user\" | \"project\" | \"path\";\n\t\t\t\tpaths: Array<{ path: string; sourceInfo?: SourceInfo }>;\n\t\t\t\tpackages: Map>;\n\t\t\t}\n\t\t> = {\n\t\t\tuser: { scope: \"user\", paths: [], packages: new Map() },\n\t\t\tproject: { scope: \"project\", paths: [], packages: new Map() },\n\t\t\tpath: { scope: \"path\", paths: [], packages: new Map() },\n\t\t};\n\n\t\tfor (const item of items) {\n\t\t\tconst groupKey = this.getScopeGroup(item.sourceInfo);\n\t\t\tconst group = groups[groupKey];\n\t\t\tconst source = item.sourceInfo?.source ?? \"local\";\n\n\t\t\tif (this.isPackageSource(item.sourceInfo)) {\n\t\t\t\tconst list = group.packages.get(source) ?? [];\n\t\t\t\tlist.push(item);\n\t\t\t\tgroup.packages.set(source, list);\n\t\t\t} else {\n\t\t\t\tgroup.paths.push(item);\n\t\t\t}\n\t\t}\n\n\t\treturn [groups.project, groups.user, groups.path].filter(\n\t\t\t(group) => group.paths.length > 0 || group.packages.size > 0,\n\t\t);\n\t}\n\n\tprivate formatScopeGroups(\n\t\tgroups: Array<{\n\t\t\tscope: \"user\" | \"project\" | \"path\";\n\t\t\tpaths: Array<{ path: string; sourceInfo?: SourceInfo }>;\n\t\t\tpackages: Map>;\n\t\t}>,\n\t\toptions: {\n\t\t\tformatPath: (item: { path: string; sourceInfo?: SourceInfo }) => string;\n\t\t\tformatPackagePath: (item: { path: string; sourceInfo?: SourceInfo }, source: string) => string;\n\t\t},\n\t): string {\n\t\tconst lines: string[] = [];\n\n\t\tfor (const group of groups) {\n\t\t\tlines.push(` ${theme.fg(\"accent\", group.scope)}`);\n\n\t\t\tconst sortedPaths = [...group.paths].sort((a, b) => a.path.localeCompare(b.path));\n\t\t\tfor (const item of sortedPaths) {\n\t\t\t\tlines.push(theme.fg(\"dim\", ` ${options.formatPath(item)}`));\n\t\t\t}\n\n\t\t\tconst sortedPackages = Array.from(group.packages.entries()).sort(([a], [b]) => a.localeCompare(b));\n\t\t\tfor (const [source, items] of sortedPackages) {\n\t\t\t\tlines.push(` ${theme.fg(\"mdLink\", source)}`);\n\t\t\t\tconst sortedPackagePaths = [...items].sort((a, b) => a.path.localeCompare(b.path));\n\t\t\t\tfor (const item of sortedPackagePaths) {\n\t\t\t\t\tlines.push(theme.fg(\"dim\", ` ${options.formatPackagePath(item, source)}`));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tprivate findSourceInfoForPath(p: string, sourceInfos: Map): SourceInfo | undefined {\n\t\tconst exact = sourceInfos.get(p);\n\t\tif (exact) return exact;\n\n\t\tlet current = p;\n\t\twhile (current.includes(\"/\")) {\n\t\t\tcurrent = current.substring(0, current.lastIndexOf(\"/\"));\n\t\t\tconst parent = sourceInfos.get(current);\n\t\t\tif (parent) return parent;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate formatPathWithSource(p: string, sourceInfo?: SourceInfo): string {\n\t\tif (sourceInfo) {\n\t\t\tconst shortPath = this.getShortPath(p, sourceInfo);\n\t\t\tconst { label, scopeLabel } = this.getDisplaySourceInfo(sourceInfo);\n\t\t\tconst labelText = scopeLabel ? `${label} (${scopeLabel})` : label;\n\t\t\treturn `${labelText} ${shortPath}`;\n\t\t}\n\t\treturn this.formatDisplayPath(p);\n\t}\n\n\tprivate formatDiagnostics(diagnostics: readonly ResourceDiagnostic[], sourceInfos: Map): string {\n\t\tconst lines: string[] = [];\n\n\t\t// Group collision diagnostics by name\n\t\tconst collisions = new Map();\n\t\tconst otherDiagnostics: ResourceDiagnostic[] = [];\n\n\t\tfor (const d of diagnostics) {\n\t\t\tif (d.type === \"collision\" && d.collision) {\n\t\t\t\tconst list = collisions.get(d.collision.name) ?? [];\n\t\t\t\tlist.push(d);\n\t\t\t\tcollisions.set(d.collision.name, list);\n\t\t\t} else {\n\t\t\t\totherDiagnostics.push(d);\n\t\t\t}\n\t\t}\n\n\t\t// Format collision diagnostics grouped by name\n\t\tfor (const [name, collisionList] of collisions) {\n\t\t\tconst first = collisionList[0]?.collision;\n\t\t\tif (!first) continue;\n\t\t\tlines.push(theme.fg(\"warning\", ` \"${name}\" collision:`));\n\t\t\tlines.push(\n\t\t\t\ttheme.fg(\n\t\t\t\t\t\"dim\",\n\t\t\t\t\t` ${theme.fg(\"success\", \"✓\")} ${this.formatPathWithSource(first.winnerPath, this.findSourceInfoForPath(first.winnerPath, sourceInfos))}`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tfor (const d of collisionList) {\n\t\t\t\tif (d.collision) {\n\t\t\t\t\tlines.push(\n\t\t\t\t\t\ttheme.fg(\n\t\t\t\t\t\t\t\"dim\",\n\t\t\t\t\t\t\t` ${theme.fg(\"warning\", \"✗\")} ${this.formatPathWithSource(d.collision.loserPath, this.findSourceInfoForPath(d.collision.loserPath, sourceInfos))} (skipped)`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const d of otherDiagnostics) {\n\t\t\tif (d.path) {\n\t\t\t\tconst formattedPath = this.formatPathWithSource(d.path, this.findSourceInfoForPath(d.path, sourceInfos));\n\t\t\t\tlines.push(theme.fg(d.type === \"error\" ? \"error\" : \"warning\", ` ${formattedPath}`));\n\t\t\t\tlines.push(theme.fg(d.type === \"error\" ? \"error\" : \"warning\", ` ${d.message}`));\n\t\t\t} else {\n\t\t\t\tlines.push(theme.fg(d.type === \"error\" ? \"error\" : \"warning\", ` ${d.message}`));\n\t\t\t}\n\t\t}\n\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tprivate showLoadedResources(options?: {\n\t\textensions?: Array<{ path: string; sourceInfo?: SourceInfo }>;\n\t\tforce?: boolean;\n\t\tshowDiagnosticsWhenQuiet?: boolean;\n\t}): void {\n\t\t// Resource rendering is idempotent; chat clears no longer clear this separate container.\n\t\tthis.loadedResourcesContainer.clear();\n\n\t\tconst showListing = options?.force || this.options.verbose || !this.settingsManager.getQuietStartup();\n\t\tconst showDiagnostics = showListing || options?.showDiagnosticsWhenQuiet === true;\n\t\tif (!showListing && !showDiagnostics) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst sectionHeader = (name: string, color: ThemeColor = \"mdHeading\") => theme.fg(color, `[${name}]`);\n\t\tconst formatCompactList = (items: string[], options?: { sort?: boolean }): string => {\n\t\t\tconst labels = items.map((item) => item.trim()).filter((item) => item.length > 0);\n\t\t\tif (options?.sort !== false) {\n\t\t\t\tlabels.sort((a, b) => a.localeCompare(b));\n\t\t\t}\n\t\t\treturn theme.fg(\"dim\", ` ${labels.join(\", \")}`);\n\t\t};\n\t\tconst addLoadedSection = (\n\t\t\tname: string,\n\t\t\tcollapsedBody: string,\n\t\t\texpandedBody = collapsedBody,\n\t\t\tcolor: ThemeColor = \"mdHeading\",\n\t\t): void => {\n\t\t\tconst section = new ExpandableText(\n\t\t\t\t() => `${sectionHeader(name, color)}\\n${collapsedBody}`,\n\t\t\t\t() => `${sectionHeader(name, color)}\\n${expandedBody}`,\n\t\t\t\tthis.getStartupExpansionState(),\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t);\n\t\t\tthis.loadedResourcesContainer.addChild(section);\n\t\t\tthis.loadedResourcesContainer.addChild(new Spacer(1));\n\t\t};\n\n\t\tconst skillsResult = this.session.resourceLoader.getSkills();\n\t\tconst promptsResult = this.session.resourceLoader.getPrompts();\n\t\tconst themesResult = this.session.resourceLoader.getThemes();\n\t\tconst extensions =\n\t\t\toptions?.extensions ??\n\t\t\tthis.session.resourceLoader\n\t\t\t\t.getExtensions()\n\t\t\t\t.extensions.filter((extension) => !extension.hidden)\n\t\t\t\t.map((extension) => ({\n\t\t\t\t\tpath: extension.path,\n\t\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\t}));\n\t\tconst sourceInfos = new Map();\n\t\tfor (const extension of extensions) {\n\t\t\tif (extension.sourceInfo) {\n\t\t\t\tsourceInfos.set(extension.path, extension.sourceInfo);\n\t\t\t}\n\t\t}\n\t\tfor (const skill of skillsResult.skills) {\n\t\t\tif (skill.sourceInfo) {\n\t\t\t\tsourceInfos.set(skill.filePath, skill.sourceInfo);\n\t\t\t}\n\t\t}\n\t\tfor (const prompt of promptsResult.prompts) {\n\t\t\tif (prompt.sourceInfo) {\n\t\t\t\tsourceInfos.set(prompt.filePath, prompt.sourceInfo);\n\t\t\t}\n\t\t}\n\t\tfor (const loadedTheme of themesResult.themes) {\n\t\t\tif (loadedTheme.sourcePath && loadedTheme.sourceInfo) {\n\t\t\t\tsourceInfos.set(loadedTheme.sourcePath, loadedTheme.sourceInfo);\n\t\t\t}\n\t\t}\n\n\t\tif (showListing) {\n\t\t\tconst systemPromptSource = this.session.resourceLoader.getSystemPromptSource();\n\t\t\tconst contextFiles = [\n\t\t\t\t...(systemPromptSource ? [systemPromptSource] : []),\n\t\t\t\t...this.session.resourceLoader.getAppendSystemPromptSources(),\n\t\t\t\t...this.session.resourceLoader.getAgentsFiles().agentsFiles,\n\t\t\t];\n\t\t\tif (contextFiles.length > 0) {\n\t\t\t\tthis.loadedResourcesContainer.addChild(new Spacer(1));\n\t\t\t\tconst contextList = contextFiles\n\t\t\t\t\t.map((f) => theme.fg(\"dim\", ` ${this.formatDisplayPath(f.path)}`))\n\t\t\t\t\t.join(\"\\n\");\n\t\t\t\tconst contextCompactList = formatCompactList(\n\t\t\t\t\tcontextFiles.map((contextFile) => this.formatContextPath(contextFile.path)),\n\t\t\t\t\t{ sort: false },\n\t\t\t\t);\n\t\t\t\taddLoadedSection(\"Context\", contextCompactList, contextList);\n\t\t\t}\n\n\t\t\tconst skills = skillsResult.skills;\n\t\t\tif (skills.length > 0) {\n\t\t\t\tconst groups = this.buildScopeGroups(\n\t\t\t\t\tskills.map((skill) => ({ path: skill.filePath, sourceInfo: skill.sourceInfo })),\n\t\t\t\t);\n\t\t\t\tconst skillList = this.formatScopeGroups(groups, {\n\t\t\t\t\tformatPath: (item) => this.formatDisplayPath(item.path),\n\t\t\t\t\tformatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),\n\t\t\t\t});\n\t\t\t\tconst skillCompactList = formatCompactList(skills.map((skill) => skill.name));\n\t\t\t\taddLoadedSection(\"Skills\", skillCompactList, skillList);\n\t\t\t}\n\n\t\t\tconst templates = this.session.promptTemplates;\n\t\t\tif (templates.length > 0) {\n\t\t\t\tconst groups = this.buildScopeGroups(\n\t\t\t\t\ttemplates.map((template) => ({ path: template.filePath, sourceInfo: template.sourceInfo })),\n\t\t\t\t);\n\t\t\t\tconst templateByPath = new Map(templates.map((t) => [t.filePath, t]));\n\t\t\t\tconst templateList = this.formatScopeGroups(groups, {\n\t\t\t\t\tformatPath: (item) => {\n\t\t\t\t\t\tconst template = templateByPath.get(item.path);\n\t\t\t\t\t\treturn template ? `/${template.name}` : this.formatDisplayPath(item.path);\n\t\t\t\t\t},\n\t\t\t\t\tformatPackagePath: (item) => {\n\t\t\t\t\t\tconst template = templateByPath.get(item.path);\n\t\t\t\t\t\treturn template ? `/${template.name}` : this.formatDisplayPath(item.path);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tconst promptCompactList = formatCompactList(templates.map((template) => `/${template.name}`));\n\t\t\t\taddLoadedSection(\"Prompts\", promptCompactList, templateList);\n\t\t\t}\n\n\t\t\tif (extensions.length > 0) {\n\t\t\t\tconst groups = this.buildScopeGroups(extensions);\n\t\t\t\tconst extList = this.formatScopeGroups(groups, {\n\t\t\t\t\tformatPath: (item) => this.formatExtensionDisplayPath(item.path),\n\t\t\t\t\tformatPackagePath: (item) =>\n\t\t\t\t\t\tthis.formatExtensionDisplayPath(this.getShortPath(item.path, item.sourceInfo)),\n\t\t\t\t});\n\t\t\t\tconst extensionCompactList = formatCompactList(this.getCompactExtensionLabels(extensions));\n\t\t\t\taddLoadedSection(\"Extensions\", extensionCompactList, extList, \"mdHeading\");\n\t\t\t}\n\n\t\t\t// Show loaded themes (excluding built-in)\n\t\t\tconst loadedThemes = themesResult.themes;\n\t\t\tconst customThemes = loadedThemes.filter((t) => t.sourcePath);\n\t\t\tif (customThemes.length > 0) {\n\t\t\t\tconst groups = this.buildScopeGroups(\n\t\t\t\t\tcustomThemes.map((loadedTheme) => ({\n\t\t\t\t\t\tpath: loadedTheme.sourcePath!,\n\t\t\t\t\t\tsourceInfo: loadedTheme.sourceInfo,\n\t\t\t\t\t})),\n\t\t\t\t);\n\t\t\t\tconst themeList = this.formatScopeGroups(groups, {\n\t\t\t\t\tformatPath: (item) => this.formatDisplayPath(item.path),\n\t\t\t\t\tformatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),\n\t\t\t\t});\n\t\t\t\tconst themeCompactList = formatCompactList(\n\t\t\t\t\tcustomThemes.map(\n\t\t\t\t\t\t(loadedTheme) =>\n\t\t\t\t\t\t\tloadedTheme.name ?? this.getCompactPathLabel(loadedTheme.sourcePath!, loadedTheme.sourceInfo),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\taddLoadedSection(\"Themes\", themeCompactList, themeList);\n\t\t\t}\n\t\t}\n\n\t\tif (showDiagnostics) {\n\t\t\tconst skillDiagnostics = skillsResult.diagnostics;\n\t\t\tif (skillDiagnostics.length > 0) {\n\t\t\t\tconst warningLines = this.formatDiagnostics(skillDiagnostics, sourceInfos);\n\t\t\t\tthis.loadedResourcesContainer.addChild(\n\t\t\t\t\tnew Text(`${theme.fg(\"warning\", \"[Skill conflicts]\")}\\n${warningLines}`, 0, 0),\n\t\t\t\t);\n\t\t\t\tthis.loadedResourcesContainer.addChild(new Spacer(1));\n\t\t\t}\n\n\t\t\tconst promptDiagnostics = promptsResult.diagnostics;\n\t\t\tif (promptDiagnostics.length > 0) {\n\t\t\t\tconst warningLines = this.formatDiagnostics(promptDiagnostics, sourceInfos);\n\t\t\t\tthis.loadedResourcesContainer.addChild(\n\t\t\t\t\tnew Text(`${theme.fg(\"warning\", \"[Prompt conflicts]\")}\\n${warningLines}`, 0, 0),\n\t\t\t\t);\n\t\t\t\tthis.loadedResourcesContainer.addChild(new Spacer(1));\n\t\t\t}\n\n\t\t\tconst extensionDiagnostics: ResourceDiagnostic[] = [];\n\t\t\tconst extensionErrors = this.session.resourceLoader.getExtensions().errors;\n\t\t\tif (extensionErrors.length > 0) {\n\t\t\t\tfor (const error of extensionErrors) {\n\t\t\t\t\textensionDiagnostics.push({ type: \"error\", message: error.error, path: error.path });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst commandDiagnostics = this.session.extensionRunner.getCommandDiagnostics();\n\t\t\textensionDiagnostics.push(...commandDiagnostics);\n\t\t\textensionDiagnostics.push(...this.getBuiltInCommandConflictDiagnostics(this.session.extensionRunner));\n\n\t\t\tconst shortcutDiagnostics = this.session.extensionRunner.getShortcutDiagnostics();\n\t\t\textensionDiagnostics.push(...shortcutDiagnostics);\n\n\t\t\tif (extensionDiagnostics.length > 0) {\n\t\t\t\tconst warningLines = this.formatDiagnostics(extensionDiagnostics, sourceInfos);\n\t\t\t\tthis.loadedResourcesContainer.addChild(\n\t\t\t\t\tnew Text(`${theme.fg(\"warning\", \"[Extension issues]\")}\\n${warningLines}`, 0, 0),\n\t\t\t\t);\n\t\t\t\tthis.loadedResourcesContainer.addChild(new Spacer(1));\n\t\t\t}\n\n\t\t\tconst themeDiagnostics = themesResult.diagnostics;\n\t\t\tif (themeDiagnostics.length > 0) {\n\t\t\t\tconst warningLines = this.formatDiagnostics(themeDiagnostics, sourceInfos);\n\t\t\t\tthis.loadedResourcesContainer.addChild(\n\t\t\t\t\tnew Text(`${theme.fg(\"warning\", \"[Theme conflicts]\")}\\n${warningLines}`, 0, 0),\n\t\t\t\t);\n\t\t\t\tthis.loadedResourcesContainer.addChild(new Spacer(1));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Initialize the extension system with TUI-based UI context.\n\t */\n\tprivate async bindCurrentSessionExtensions(): Promise {\n\t\tconst uiContext = this.createExtensionUIContext();\n\t\tawait this.session.bindExtensions({\n\t\t\tuiContext,\n\t\t\tmode: \"tui\",\n\t\t\tabortHandler: () => {\n\t\t\t\tthis.restoreQueuedMessagesToEditor({ abort: true });\n\t\t\t},\n\t\t\tcommandContextActions: {\n\t\t\t\twaitForIdle: () => this.session.waitForIdle(),\n\t\t\t\tnewSession: async (options) => {\n\t\t\t\t\tthis.clearStatusIndicator();\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await this.runtimeHost.newSession(options);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\treturn this.handleFatalRuntimeError(\"Failed to create session\", error);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tfork: async (entryId, options) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.runtimeHost.fork(entryId, options);\n\t\t\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\t\t\tthis.editor.setText(result.selectedText ?? \"\");\n\t\t\t\t\t\t\tthis.showStatus(\"Forked to new session\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { cancelled: result.cancelled };\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\treturn this.handleFatalRuntimeError(\"Failed to fork session\", error);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tnavigateTree: async (targetId, options) => {\n\t\t\t\t\tconst result = await this.session.navigateTree(targetId, {\n\t\t\t\t\t\tsummarize: options?.summarize,\n\t\t\t\t\t\tcustomInstructions: options?.customInstructions,\n\t\t\t\t\t\treplaceInstructions: options?.replaceInstructions,\n\t\t\t\t\t\tlabel: options?.label,\n\t\t\t\t\t});\n\t\t\t\t\tif (result.cancelled) {\n\t\t\t\t\t\treturn { cancelled: true };\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\tthis.renderInitialMessages();\n\t\t\t\t\tif (result.editorText && !this.editor.getText().trim()) {\n\t\t\t\t\t\tthis.editor.setText(result.editorText);\n\t\t\t\t\t}\n\t\t\t\t\tthis.showStatus(\"Navigated to selected point\");\n\t\t\t\t\tvoid this.flushCompactionQueue({ willRetry: false });\n\t\t\t\t\treturn { cancelled: false };\n\t\t\t\t},\n\t\t\t\tswitchSession: async (sessionPath, options) => {\n\t\t\t\t\treturn this.handleResumeSession(sessionPath, options);\n\t\t\t\t},\n\t\t\t\treload: async () => {\n\t\t\t\t\tawait this.handleReloadCommand();\n\t\t\t\t},\n\t\t\t},\n\t\t\tshutdownHandler: () => {\n\t\t\t\tthis.shutdownRequested = true;\n\t\t\t\tif (this.session.isIdle) {\n\t\t\t\t\tvoid this.shutdown();\n\t\t\t\t}\n\t\t\t},\n\t\t\tonError: (error) => {\n\t\t\t\tthis.showExtensionError(error.extensionPath, error.error, error.stack);\n\t\t\t},\n\t\t});\n\n\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\tthis.setupAutocompleteProvider();\n\n\t\tconst extensionRunner = this.session.extensionRunner;\n\t\tthis.setupExtensionShortcuts(extensionRunner);\n\t\tthis.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });\n\t\tthis.showStartupNoticesIfNeeded();\n\t}\n\n\tprivate applyRuntimeSettings(): void {\n\t\tconfigureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs());\n\t\tthis.footer.setSession(this.session);\n\t\tthis.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);\n\t\tthis.footerDataProvider.setCwd(this.sessionManager.getCwd());\n\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\t\tthis.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());\n\t\tconst clearOnShrink = this.settingsManager.getClearOnShrink();\n\t\tthis.ui.setClearOnShrink(clearOnShrink);\n\t\tif (!clearOnShrink && !this.activeStatusIndicator) {\n\t\t\tthis.statusContainer.clear();\n\t\t}\n\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\tthis.defaultEditor.setPaddingX(editorPaddingX);\n\t\tthis.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);\n\t\tif (this.editor !== this.defaultEditor) {\n\t\t\tthis.editor.setPaddingX?.(editorPaddingX);\n\t\t\tthis.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);\n\t\t}\n\t}\n\n\tprivate async rebindCurrentSession(options: { renderBeforeBind?: boolean } = {}): Promise {\n\t\tconst session = this.session;\n\n\t\tthis.unsubscribe?.();\n\t\tthis.unsubscribe = undefined;\n\t\tthis.applyRuntimeSettings();\n\n\t\tif (options.renderBeforeBind) {\n\t\t\tthis.renderCurrentSessionState();\n\t\t\tthis.subscribeToAgent();\n\t\t}\n\n\t\tawait this.bindCurrentSessionExtensions();\n\n\t\tif (this.session !== session) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!options.renderBeforeBind) {\n\t\t\tthis.subscribeToAgent();\n\t\t}\n\n\t\tawait this.updateAvailableProviderCount();\n\t\tthis.updateEditorBorderColor();\n\t\tthis.updateTerminalTitle();\n\t}\n\n\tprivate async handleFatalRuntimeError(prefix: string, error: unknown): Promise {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis.showError(`${prefix}: ${message}`);\n\t\tstopThemeWatcher();\n\t\tthis.stop();\n\t\tprocess.exit(1);\n\t}\n\n\tprivate renderCurrentSessionState(): void {\n\t\tthis.loadedResourcesContainer.clear();\n\t\tthis.chatContainer.clear();\n\t\tthis.pendingMessagesContainer.clear();\n\t\tthis.compactionQueuedMessages = [];\n\t\tthis.streamingComponent = undefined;\n\t\tthis.streamingMessage = undefined;\n\t\tthis.pendingTools.clear();\n\t\tthis.renderInitialMessages();\n\t}\n\n\t/**\n\t * Get a registered tool definition by name (for custom rendering).\n\t */\n\tprivate getRegisteredToolDefinition(toolName: string) {\n\t\treturn this.session.getToolDefinition(toolName);\n\t}\n\n\t/**\n\t * Set up keyboard shortcuts registered by extensions.\n\t */\n\tprivate setupExtensionShortcuts(extensionRunner: ExtensionRunner): void {\n\t\tconst shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());\n\t\tif (shortcuts.size === 0) return;\n\n\t\t// Create a context for shortcut handlers\n\t\tconst createContext = (): ExtensionContext => ({\n\t\t\tui: this.createExtensionUIContext(),\n\t\t\tmode: \"tui\",\n\t\t\thasUI: true,\n\t\t\tcwd: this.sessionManager.getCwd(),\n\t\t\tsessionManager: this.sessionManager,\n\t\t\tmodelRegistry: extensionRunner.getModelRegistry(),\n\t\t\tmodel: this.session.model,\n\t\t\tscopedModels: this.session.scopedModels,\n\t\t\tthinkingLevel: this.session.thinkingLevel,\n\t\t\tisIdle: () => this.session.isIdle,\n\t\t\tisProjectTrusted: () => this.settingsManager.isProjectTrusted(),\n\t\t\tsignal: this.session.agent.signal,\n\t\t\tabort: () => {\n\t\t\t\tthis.restoreQueuedMessagesToEditor({ abort: true });\n\t\t\t},\n\t\t\thasPendingMessages: () => this.session.pendingMessageCount > 0,\n\t\t\tshutdown: () => {\n\t\t\t\tthis.shutdownRequested = true;\n\t\t\t},\n\t\t\tgetContextUsage: () => this.session.getContextUsage(),\n\t\t\tcompact: (options) => {\n\t\t\t\tvoid (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.session.compact(options?.customInstructions);\n\t\t\t\t\t\toptions?.onComplete?.(result);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\t\toptions?.onError?.(err);\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t},\n\t\t\tgetSystemPrompt: () => this.session.systemPrompt,\n\t\t});\n\n\t\t// Set up the extension shortcut handler on the default editor\n\t\tthis.defaultEditor.onExtensionShortcut = (data: string) => {\n\t\t\tfor (const [shortcutStr, shortcut] of shortcuts) {\n\t\t\t\t// Cast to KeyId - extension shortcuts use the same format\n\t\t\t\tif (matchesKey(data, shortcutStr as KeyId)) {\n\t\t\t\t\t// Run handler async, don't block input\n\t\t\t\t\tPromise.resolve(shortcut.handler(createContext())).catch((err) => {\n\t\t\t\t\t\tthis.showError(`Shortcut handler error: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t\t\t});\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t};\n\t}\n\n\t/**\n\t * Set extension status text in the footer.\n\t */\n\tprivate setExtensionStatus(key: string, text: string | undefined): void {\n\t\tthis.footerDataProvider.setExtensionStatus(key, text);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate showStatusIndicator(indicator: StatusIndicator): void {\n\t\tthis.activeStatusIndicator?.dispose();\n\t\tthis.activeStatusIndicator = indicator;\n\t\tthis.statusContainer.clear();\n\t\tthis.statusContainer.addChild(indicator);\n\t}\n\n\tprivate clearStatusIndicator(kind?: StatusIndicator[\"kind\"]): void {\n\t\tif (kind && this.activeStatusIndicator?.kind !== kind) {\n\t\t\treturn;\n\t\t}\n\t\tconst hadActiveStatusIndicator = this.activeStatusIndicator !== undefined;\n\t\tthis.activeStatusIndicator?.dispose();\n\t\tthis.activeStatusIndicator = undefined;\n\t\tthis.statusContainer.clear();\n\t\tif (hadActiveStatusIndicator && this.ui.getClearOnShrink()) {\n\t\t\tthis.statusContainer.addChild(this.idleStatus);\n\t\t}\n\t}\n\n\tprivate setWorkingVisible(visible: boolean): void {\n\t\tthis.workingVisible = visible;\n\t\tif (!visible) {\n\t\t\tthis.clearStatusIndicator(\"working\");\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (this.session.isStreaming && this.activeStatusIndicator?.kind !== \"working\") {\n\t\t\tthis.showStatusIndicator(\n\t\t\t\tnew WorkingStatusIndicator(\n\t\t\t\t\tthis.ui,\n\t\t\t\t\tthis.workingMessage ?? this.defaultWorkingMessage,\n\t\t\t\t\tthis.workingIndicatorOptions,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate setWorkingIndicator(options?: WorkingIndicatorOptions): void {\n\t\tthis.workingIndicatorOptions = options;\n\t\tif (this.activeStatusIndicator?.kind === \"working\") {\n\t\t\tthis.activeStatusIndicator.setIndicator(options);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate setHiddenThinkingLabel(label?: string): void {\n\t\tthis.hiddenThinkingLabel = label ?? this.defaultHiddenThinkingLabel;\n\t\tfor (const child of this.chatContainer.children) {\n\t\t\tif (child instanceof AssistantMessageComponent) {\n\t\t\t\tchild.setHiddenThinkingLabel(this.hiddenThinkingLabel);\n\t\t\t}\n\t\t}\n\t\tif (this.streamingComponent) {\n\t\t\tthis.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Set an extension widget (string array or custom component).\n\t */\n\tprivate setExtensionWidget(\n\t\tkey: string,\n\t\tcontent: string[] | ((tui: TUI, thm: Theme) => Component & { dispose?(): void }) | undefined,\n\t\toptions?: ExtensionWidgetOptions,\n\t): void {\n\t\tconst placement = options?.placement ?? \"aboveEditor\";\n\t\tconst removeExisting = (map: Map) => {\n\t\t\tconst existing = map.get(key);\n\t\t\tif (existing?.dispose) existing.dispose();\n\t\t\tmap.delete(key);\n\t\t};\n\n\t\tremoveExisting(this.extensionWidgetsAbove);\n\t\tremoveExisting(this.extensionWidgetsBelow);\n\n\t\tif (content === undefined) {\n\t\t\tthis.renderWidgets();\n\t\t\treturn;\n\t\t}\n\n\t\tlet component: Component & { dispose?(): void };\n\n\t\tif (Array.isArray(content)) {\n\t\t\t// Wrap string array in a Container with Text components\n\t\t\tconst container = new Container();\n\t\t\tfor (const line of content.slice(0, InteractiveMode.MAX_WIDGET_LINES)) {\n\t\t\t\tcontainer.addChild(new Text(line, 1, 0));\n\t\t\t}\n\t\t\tif (content.length > InteractiveMode.MAX_WIDGET_LINES) {\n\t\t\t\tcontainer.addChild(new Text(theme.fg(\"muted\", \"... (widget truncated)\"), 1, 0));\n\t\t\t}\n\t\t\tcomponent = container;\n\t\t} else {\n\t\t\t// Factory function - create component\n\t\t\tcomponent = content(this.ui, theme);\n\t\t}\n\n\t\tconst targetMap = placement === \"belowEditor\" ? this.extensionWidgetsBelow : this.extensionWidgetsAbove;\n\t\ttargetMap.set(key, component);\n\t\tthis.renderWidgets();\n\t}\n\n\tprivate clearExtensionWidgets(): void {\n\t\tfor (const widget of this.extensionWidgetsAbove.values()) {\n\t\t\twidget.dispose?.();\n\t\t}\n\t\tfor (const widget of this.extensionWidgetsBelow.values()) {\n\t\t\twidget.dispose?.();\n\t\t}\n\t\tthis.extensionWidgetsAbove.clear();\n\t\tthis.extensionWidgetsBelow.clear();\n\t\tthis.renderWidgets();\n\t}\n\n\tprivate resetExtensionUI(): void {\n\t\tif (this.extensionSelector) {\n\t\t\tthis.hideExtensionSelector();\n\t\t}\n\t\tif (this.extensionInput) {\n\t\t\tthis.hideExtensionInput();\n\t\t}\n\t\tif (this.extensionEditor) {\n\t\t\tthis.hideExtensionEditor();\n\t\t}\n\t\tthis.ui.hideOverlay();\n\t\tthis.clearExtensionTerminalInputListeners();\n\t\tthis.setExtensionFooter(undefined);\n\t\tthis.setExtensionHeader(undefined);\n\t\tthis.clearExtensionWidgets();\n\t\tthis.footerDataProvider.clearExtensionStatuses();\n\t\tthis.footer.invalidate();\n\t\tthis.autocompleteProviderWrappers = [];\n\t\tthis.setCustomEditorComponent(undefined);\n\t\tthis.setupAutocompleteProvider();\n\t\tthis.defaultEditor.onExtensionShortcut = undefined;\n\t\tthis.updateTerminalTitle();\n\t\tthis.workingMessage = undefined;\n\t\tthis.workingVisible = true;\n\t\tthis.setWorkingIndicator();\n\t\tif (this.activeStatusIndicator?.kind === \"working\") {\n\t\t\tthis.activeStatusIndicator.setMessage(\n\t\t\t\t`${this.defaultWorkingMessage} (${keyText(\"app.interrupt\")} to interrupt)`,\n\t\t\t);\n\t\t}\n\t\tthis.setHiddenThinkingLabel();\n\t}\n\n\t// Maximum total widget lines to prevent viewport overflow\n\tprivate static readonly MAX_WIDGET_LINES = 10;\n\n\t/**\n\t * Render all extension widgets to the widget container.\n\t */\n\tprivate renderWidgets(): void {\n\t\tif (!this.widgetContainerAbove || !this.widgetContainerBelow) return;\n\t\tthis.renderWidgetContainer(this.widgetContainerAbove, this.extensionWidgetsAbove, true, true);\n\t\tthis.renderWidgetContainer(this.widgetContainerBelow, this.extensionWidgetsBelow, false, false);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate renderWidgetContainer(\n\t\tcontainer: Container,\n\t\twidgets: Map,\n\t\tspacerWhenEmpty: boolean,\n\t\tleadingSpacer: boolean,\n\t): void {\n\t\tcontainer.clear();\n\n\t\tif (widgets.size === 0) {\n\t\t\tif (spacerWhenEmpty) {\n\t\t\t\tcontainer.addChild(new Spacer(1));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (leadingSpacer) {\n\t\t\tcontainer.addChild(new Spacer(1));\n\t\t}\n\t\tfor (const component of widgets.values()) {\n\t\t\tcontainer.addChild(component);\n\t\t}\n\t}\n\n\t/**\n\t * Set a custom footer component, or restore the built-in footer.\n\t */\n\tprivate setExtensionFooter(\n\t\tfactory:\n\t\t\t| ((tui: TUI, thm: Theme, footerData: ReadonlyFooterDataProvider) => Component & { dispose?(): void })\n\t\t\t| undefined,\n\t): void {\n\t\t// Dispose existing custom footer\n\t\tif (this.customFooter?.dispose) {\n\t\t\tthis.customFooter.dispose();\n\t\t}\n\n\t\t// Remove current footer from UI\n\t\tif (this.customFooter) {\n\t\t\tthis.ui.removeChild(this.customFooter);\n\t\t} else {\n\t\t\tthis.ui.removeChild(this.footer);\n\t\t}\n\n\t\tif (factory) {\n\t\t\t// Create and add custom footer, passing the data provider\n\t\t\tthis.customFooter = factory(this.ui, theme, this.footerDataProvider);\n\t\t\tthis.ui.addChild(this.customFooter);\n\t\t} else {\n\t\t\t// Restore built-in footer\n\t\t\tthis.customFooter = undefined;\n\t\t\tthis.ui.addChild(this.footer);\n\t\t}\n\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Set a custom header component, or restore the built-in header.\n\t */\n\tprivate setExtensionHeader(factory: ((tui: TUI, thm: Theme) => Component & { dispose?(): void }) | undefined): void {\n\t\t// Header may not be initialized yet if called during early initialization\n\t\tif (!this.builtInHeader) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Dispose existing custom header\n\t\tif (this.customHeader?.dispose) {\n\t\t\tthis.customHeader.dispose();\n\t\t}\n\n\t\t// Find the index of the current header in the header container\n\t\tconst currentHeader = this.customHeader || this.builtInHeader;\n\t\tconst index = this.headerContainer.children.indexOf(currentHeader);\n\n\t\tif (factory) {\n\t\t\t// Create and add custom header\n\t\t\tthis.customHeader = factory(this.ui, theme);\n\t\t\tif (isExpandable(this.customHeader)) {\n\t\t\t\tthis.customHeader.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.headerContainer.children[index] = this.customHeader;\n\t\t\t} else {\n\t\t\t\t// If not found (e.g. builtInHeader was never added), add at the top\n\t\t\t\tthis.headerContainer.children.unshift(this.customHeader);\n\t\t\t}\n\t\t} else {\n\t\t\t// Restore built-in header\n\t\t\tthis.customHeader = undefined;\n\t\t\tif (isExpandable(this.builtInHeader)) {\n\t\t\t\tthis.builtInHeader.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.headerContainer.children[index] = this.builtInHeader;\n\t\t\t}\n\t\t}\n\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate addExtensionTerminalInputListener(\n\t\thandler: (data: string) => { consume?: boolean; data?: string } | undefined,\n\t): () => void {\n\t\tconst unsubscribe = this.ui.addInputListener(handler);\n\t\tthis.extensionTerminalInputUnsubscribers.add(unsubscribe);\n\t\treturn () => {\n\t\t\tunsubscribe();\n\t\t\tthis.extensionTerminalInputUnsubscribers.delete(unsubscribe);\n\t\t};\n\t}\n\n\tprivate clearExtensionTerminalInputListeners(): void {\n\t\tfor (const unsubscribe of this.extensionTerminalInputUnsubscribers) {\n\t\t\tunsubscribe();\n\t\t}\n\t\tthis.extensionTerminalInputUnsubscribers.clear();\n\t}\n\n\t/**\n\t * Create the ExtensionUIContext for extensions.\n\t */\n\tprivate createProjectTrustContext(cwd: string): ProjectTrustContext {\n\t\tconst ui = this.createExtensionUIContext();\n\t\treturn {\n\t\t\tcwd,\n\t\t\tmode: \"tui\",\n\t\t\thasUI: true,\n\t\t\tui: {\n\t\t\t\tselect: ui.select,\n\t\t\t\tconfirm: ui.confirm,\n\t\t\t\tinput: ui.input,\n\t\t\t\tnotify: ui.notify,\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate createExtensionUIContext(): ExtensionUIContext {\n\t\treturn {\n\t\t\tselect: (title, options, opts) => this.showExtensionSelector(title, options, opts),\n\t\t\tconfirm: (title, message, opts) => this.showExtensionConfirm(title, message, opts),\n\t\t\tinput: (title, placeholder, opts) => this.showExtensionInput(title, placeholder, opts),\n\t\t\tnotify: (message, type) => this.showExtensionNotify(message, type),\n\t\t\tonTerminalInput: (handler) => this.addExtensionTerminalInputListener(handler),\n\t\t\tsetStatus: (key, text) => this.setExtensionStatus(key, text),\n\t\t\tsetWorkingMessage: (message) => {\n\t\t\t\tthis.workingMessage = message;\n\t\t\t\tif (this.activeStatusIndicator?.kind === \"working\") {\n\t\t\t\t\tthis.activeStatusIndicator.setMessage(message ?? this.defaultWorkingMessage);\n\t\t\t\t}\n\t\t\t},\n\t\t\tsetWorkingVisible: (visible) => this.setWorkingVisible(visible),\n\t\t\tsetWorkingIndicator: (options) => this.setWorkingIndicator(options),\n\t\t\tsetHiddenThinkingLabel: (label) => this.setHiddenThinkingLabel(label),\n\t\t\tsetWidget: (key, content, options) => this.setExtensionWidget(key, content, options),\n\t\t\tsetFooter: (factory) => this.setExtensionFooter(factory),\n\t\t\tsetHeader: (factory) => this.setExtensionHeader(factory),\n\t\t\tsetTitle: (title) => this.ui.terminal.setTitle(title),\n\t\t\tcustom: (factory, options) => this.showExtensionCustom(factory, options),\n\t\t\tpasteToEditor: (text) => this.editor.handleInput(`\\x1b[200~${text}\\x1b[201~`),\n\t\t\tsetEditorText: (text) => this.editor.setText(text),\n\t\t\tgetEditorText: () => this.editor.getExpandedText?.() ?? this.editor.getText(),\n\t\t\teditor: (title, prefill) => this.showExtensionEditor(title, prefill),\n\t\t\taddAutocompleteProvider: (factory) => {\n\t\t\t\tthis.autocompleteProviderWrappers.push(factory);\n\t\t\t\tthis.setupAutocompleteProvider();\n\t\t\t},\n\t\t\tsetEditorComponent: (factory) => this.setCustomEditorComponent(factory),\n\t\t\tgetEditorComponent: () => this.editorComponentFactory,\n\t\t\tget theme() {\n\t\t\t\treturn theme;\n\t\t\t},\n\t\t\tgetAllThemes: () => getAvailableThemesWithPaths(),\n\t\t\tgetTheme: (name) => getThemeByName(name),\n\t\t\tsetTheme: (themeOrName) => {\n\t\t\t\tif (themeOrName instanceof Theme) {\n\t\t\t\t\treturn this.themeController.setThemeInstance(themeOrName);\n\t\t\t\t}\n\t\t\t\tconst result = this.themeController.setThemeName(themeOrName);\n\t\t\t\tif (result.success) {\n\t\t\t\t\tif (this.settingsManager.getTheme() !== themeOrName) {\n\t\t\t\t\t\tthis.settingsManager.setTheme(themeOrName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tgetToolsExpanded: () => this.toolOutputExpanded,\n\t\t\tsetToolsExpanded: (expanded) => this.setToolsExpanded(expanded),\n\t\t};\n\t}\n\n\t/**\n\t * Show a selector for extensions.\n\t */\n\tprivate showExtensionSelector(\n\t\ttitle: string,\n\t\toptions: string[],\n\t\topts?: ExtensionUIDialogOptions,\n\t): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tif (opts?.signal?.aborted) {\n\t\t\t\tresolve(undefined);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tthis.hideExtensionSelector();\n\t\t\t\tresolve(undefined);\n\t\t\t};\n\t\t\topts?.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\tthis.extensionSelector = new ExtensionSelectorComponent(\n\t\t\t\ttitle,\n\t\t\t\toptions,\n\t\t\t\t(option) => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionSelector();\n\t\t\t\t\tresolve(option);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionSelector();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t\t{ tui: this.ui, timeout: opts?.timeout, onToggleToolsExpanded: () => this.toggleToolOutputExpansion() },\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.extensionSelector);\n\t\t\tthis.ui.setFocus(this.extensionSelector);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the extension selector.\n\t */\n\tprivate hideExtensionSelector(): void {\n\t\tthis.extensionSelector?.dispose();\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.extensionSelector = undefined;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a confirmation dialog for extensions.\n\t */\n\tprivate async showExtensionConfirm(\n\t\ttitle: string,\n\t\tmessage: string,\n\t\topts?: ExtensionUIDialogOptions,\n\t): Promise {\n\t\tconst result = await this.showExtensionSelector(`${title}\\n${message}`, [\"Yes\", \"No\"], opts);\n\t\treturn result === \"Yes\";\n\t}\n\n\tprivate async promptForMissingSessionCwd(error: MissingSessionCwdError): Promise {\n\t\tconst confirmed = await this.showExtensionConfirm(\n\t\t\t\"Session cwd not found\",\n\t\t\tformatMissingSessionCwdPrompt(error.issue),\n\t\t);\n\t\treturn confirmed ? error.issue.fallbackCwd : undefined;\n\t}\n\n\t/**\n\t * Show a text input for extensions.\n\t */\n\tprivate showExtensionInput(\n\t\ttitle: string,\n\t\tplaceholder?: string,\n\t\topts?: ExtensionUIDialogOptions,\n\t): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tif (opts?.signal?.aborted) {\n\t\t\t\tresolve(undefined);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tthis.hideExtensionInput();\n\t\t\t\tresolve(undefined);\n\t\t\t};\n\t\t\topts?.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\tthis.extensionInput = new ExtensionInputComponent(\n\t\t\t\ttitle,\n\t\t\t\tplaceholder,\n\t\t\t\t(value) => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionInput();\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionInput();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t\t{ tui: this.ui, timeout: opts?.timeout },\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.extensionInput);\n\t\t\tthis.ui.setFocus(this.extensionInput);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the extension input.\n\t */\n\tprivate hideExtensionInput(): void {\n\t\tthis.extensionInput?.dispose();\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.extensionInput = undefined;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a multi-line editor for extensions (with Ctrl+G support).\n\t */\n\tprivate showExtensionEditor(title: string, prefill?: string): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.extensionEditor = new ExtensionEditorComponent(\n\t\t\t\tthis.ui,\n\t\t\t\tthis.keybindings,\n\t\t\t\ttitle,\n\t\t\t\tprefill,\n\t\t\t\t(value) => {\n\t\t\t\t\tthis.hideExtensionEditor();\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tthis.hideExtensionEditor();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t\tundefined,\n\t\t\t\tthis.settingsManager.getExternalEditorCommand(),\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.extensionEditor);\n\t\t\tthis.ui.setFocus(this.extensionEditor);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the extension editor.\n\t */\n\tprivate hideExtensionEditor(): void {\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.extensionEditor = undefined;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Set a custom editor component from an extension.\n\t * Pass undefined to restore the default editor.\n\t */\n\tprivate setCustomEditorComponent(factory: EditorFactory | undefined): void {\n\t\tthis.editorComponentFactory = factory;\n\n\t\t// Save text from current editor before switching\n\t\tconst currentText = this.editor.getText();\n\n\t\tthis.editorContainer.clear();\n\n\t\tif (factory) {\n\t\t\t// Create the custom editor with tui, theme, and keybindings\n\t\t\tconst newEditor = factory(this.ui, getEditorTheme(), this.keybindings);\n\n\t\t\t// Wire up callbacks from the default editor\n\t\t\tnewEditor.onSubmit = this.defaultEditor.onSubmit;\n\t\t\tnewEditor.onChange = this.defaultEditor.onChange;\n\n\t\t\t// Copy text from previous editor\n\t\t\tnewEditor.setText(currentText);\n\n\t\t\t// Copy appearance settings if supported\n\t\t\tif (newEditor.borderColor !== undefined) {\n\t\t\t\tnewEditor.borderColor = this.defaultEditor.borderColor;\n\t\t\t}\n\t\t\tif (newEditor.setPaddingX !== undefined) {\n\t\t\t\tnewEditor.setPaddingX(this.defaultEditor.getPaddingX());\n\t\t\t}\n\n\t\t\t// Set autocomplete if supported\n\t\t\tif (newEditor.setAutocompleteProvider && this.autocompleteProvider) {\n\t\t\t\tnewEditor.setAutocompleteProvider(this.autocompleteProvider);\n\t\t\t}\n\n\t\t\t// If extending CustomEditor, copy app-level handlers\n\t\t\t// Use duck typing since instanceof fails across jiti module boundaries\n\t\t\tconst customEditor = newEditor as unknown as Record;\n\t\t\tif (\"actionHandlers\" in customEditor && customEditor.actionHandlers instanceof Map) {\n\t\t\t\tif (!customEditor.onEscape) {\n\t\t\t\t\tcustomEditor.onEscape = () => this.defaultEditor.onEscape?.();\n\t\t\t\t}\n\t\t\t\tif (!customEditor.onCtrlD) {\n\t\t\t\t\tcustomEditor.onCtrlD = () => this.defaultEditor.onCtrlD?.();\n\t\t\t\t}\n\t\t\t\tif (!customEditor.onPasteImage) {\n\t\t\t\t\tcustomEditor.onPasteImage = () => this.defaultEditor.onPasteImage?.();\n\t\t\t\t}\n\t\t\t\tif (!customEditor.onExtensionShortcut) {\n\t\t\t\t\tcustomEditor.onExtensionShortcut = (data: string) => this.defaultEditor.onExtensionShortcut?.(data);\n\t\t\t\t}\n\t\t\t\t// Copy action handlers (clear, suspend, model switching, etc.)\n\t\t\t\tfor (const [action, handler] of this.defaultEditor.actionHandlers) {\n\t\t\t\t\t(customEditor.actionHandlers as Map void>).set(action, handler);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.editor = newEditor;\n\t\t} else {\n\t\t\t// Restore default editor with text from custom editor\n\t\t\tthis.defaultEditor.setText(currentText);\n\t\t\tthis.editor = this.defaultEditor;\n\t\t}\n\n\t\tthis.editorContainer.addChild(this.editor as Component);\n\t\tthis.ui.setFocus(this.editor as Component);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a notification for extensions.\n\t */\n\tprivate showExtensionNotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void {\n\t\tif (type === \"error\") {\n\t\t\tthis.showError(message);\n\t\t} else if (type === \"warning\") {\n\t\t\tthis.showWarning(message);\n\t\t} else {\n\t\t\tthis.showStatus(message);\n\t\t}\n\t}\n\n\t/** Show a custom component with keyboard focus. Overlay mode renders on top of existing content. */\n\tprivate async showExtensionCustom(\n\t\tfactory: (\n\t\t\ttui: TUI,\n\t\t\ttheme: Theme,\n\t\t\tkeybindings: KeybindingsManager,\n\t\t\tdone: (result: T) => void,\n\t\t) => (Component & { dispose?(): void }) | Promise,\n\t\toptions?: {\n\t\t\toverlay?: boolean;\n\t\t\toverlayOptions?: OverlayOptions | (() => OverlayOptions);\n\t\t\tonHandle?: (handle: OverlayHandle) => void;\n\t\t},\n\t): Promise {\n\t\tconst savedText = this.editor.getText();\n\t\tconst isOverlay = options?.overlay ?? false;\n\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.editor.setText(savedText);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet component: Component & { dispose?(): void };\n\t\t\tlet closed = false;\n\n\t\t\tconst close = (result: T) => {\n\t\t\t\tif (closed) return;\n\t\t\t\tclosed = true;\n\t\t\t\tif (isOverlay) this.ui.hideOverlay();\n\t\t\t\telse restoreEditor();\n\t\t\t\t// Note: both branches above already call requestRender\n\t\t\t\tresolve(result);\n\t\t\t\ttry {\n\t\t\t\t\tcomponent?.dispose?.();\n\t\t\t\t} catch {\n\t\t\t\t\t/* ignore dispose errors */\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tPromise.resolve(factory(this.ui, theme, this.keybindings, close))\n\t\t\t\t.then((c) => {\n\t\t\t\t\tif (closed) return;\n\t\t\t\t\tcomponent = c;\n\t\t\t\t\tif (isOverlay) {\n\t\t\t\t\t\t// Resolve overlay options - can be static or dynamic function\n\t\t\t\t\t\tconst resolveOptions = (): OverlayOptions | undefined => {\n\t\t\t\t\t\t\tif (options?.overlayOptions) {\n\t\t\t\t\t\t\t\tconst opts =\n\t\t\t\t\t\t\t\t\ttypeof options.overlayOptions === \"function\"\n\t\t\t\t\t\t\t\t\t\t? options.overlayOptions()\n\t\t\t\t\t\t\t\t\t\t: options.overlayOptions;\n\t\t\t\t\t\t\t\treturn opts;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Fallback: use component's width property if available\n\t\t\t\t\t\t\tconst w = (component as { width?: number }).width;\n\t\t\t\t\t\t\treturn w ? { width: w } : undefined;\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst handle = this.ui.showOverlay(component, resolveOptions());\n\t\t\t\t\t\t// Expose handle to caller for visibility control\n\t\t\t\t\t\toptions?.onHandle?.(handle);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.editorContainer.clear();\n\t\t\t\t\t\tthis.editorContainer.addChild(component);\n\t\t\t\t\t\tthis.ui.setFocus(component);\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tif (closed) return;\n\t\t\t\t\tif (!isOverlay) restoreEditor();\n\t\t\t\t\treject(err);\n\t\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Show an extension error in the UI.\n\t */\n\tprivate showExtensionError(extensionPath: string, error: string, stack?: string): void {\n\t\tconst errorMsg = `Extension \"${extensionPath}\" error: ${error}`;\n\t\tconst errorText = new Text(theme.fg(\"error\", errorMsg), 1, 0);\n\t\tthis.chatContainer.addChild(errorText);\n\t\tif (stack) {\n\t\t\t// Show stack trace in dim color, indented\n\t\t\tconst stackLines = stack\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.slice(1) // Skip first line (duplicates error message)\n\t\t\t\t.map((line) => theme.fg(\"dim\", ` ${line.trim()}`))\n\t\t\t\t.join(\"\\n\");\n\t\t\tif (stackLines) {\n\t\t\t\tthis.chatContainer.addChild(new Text(stackLines, 1, 0));\n\t\t\t}\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\t// =========================================================================\n\t// Key Handlers\n\t// =========================================================================\n\n\tprivate setupKeyHandlers(): void {\n\t\t// Set up handlers on defaultEditor - they use this.editor for text access\n\t\t// so they work correctly regardless of which editor is active\n\t\tthis.defaultEditor.onEscape = () => {\n\t\t\tif (this.session.isStreaming) {\n\t\t\t\tthis.restoreQueuedMessagesToEditor({ abort: true });\n\t\t\t} else if (this.session.isBashRunning) {\n\t\t\t\tthis.session.abortBash();\n\t\t\t} else if (this.isBashMode) {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tthis.isBashMode = false;\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t} else if (!this.editor.getText().trim()) {\n\t\t\t\t// Double-escape with empty editor triggers /tree, /fork, or nothing based on setting\n\t\t\t\tconst action = this.settingsManager.getDoubleEscapeAction();\n\t\t\t\tif (action !== \"none\") {\n\t\t\t\t\tconst now = Date.now();\n\t\t\t\t\tif (now - this.lastEscapeTime < 500) {\n\t\t\t\t\t\tif (action === \"tree\") {\n\t\t\t\t\t\t\tthis.showTreeSelector();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.showUserMessageSelector();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.lastEscapeTime = 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.lastEscapeTime = now;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Register app action handlers\n\t\tthis.defaultEditor.onAction(\"app.clear\", () => this.handleCtrlC());\n\t\tthis.defaultEditor.onCtrlD = () => this.handleCtrlD();\n\t\tthis.defaultEditor.onAction(\"app.suspend\", () => this.handleCtrlZ());\n\t\tthis.defaultEditor.onAction(\"app.thinking.cycle\", () => this.cycleThinkingLevel());\n\t\tthis.defaultEditor.onAction(\"app.model.cycleForward\", () => this.cycleModel(\"forward\"));\n\t\tthis.defaultEditor.onAction(\"app.model.cycleBackward\", () => this.cycleModel(\"backward\"));\n\n\t\t// Global debug handler on TUI (works regardless of focus)\n\t\tthis.ui.onDebug = () => this.handleDebugCommand();\n\t\tthis.defaultEditor.onAction(\"app.model.select\", () => this.showModelSelector());\n\t\tthis.defaultEditor.onAction(\"app.tools.expand\", () => this.toggleToolOutputExpansion());\n\t\tthis.defaultEditor.onAction(\"app.thinking.toggle\", () => this.toggleThinkingBlockVisibility());\n\t\tthis.defaultEditor.onAction(\"app.editor.external\", () => void this.handleOpenExternalEditor());\n\t\tthis.defaultEditor.onAction(\"app.message.copy\", () => void this.handleCopyCommand());\n\t\tthis.defaultEditor.onAction(\"app.message.followUp\", () => this.handleFollowUp());\n\t\tthis.defaultEditor.onAction(\"app.message.dequeue\", () => this.handleDequeue());\n\t\tthis.defaultEditor.onAction(\"app.session.new\", () => this.handleClearCommand());\n\t\tthis.defaultEditor.onAction(\"app.session.tree\", () => this.showTreeSelector());\n\t\tthis.defaultEditor.onAction(\"app.session.fork\", () => this.showUserMessageSelector());\n\t\tthis.defaultEditor.onAction(\"app.session.resume\", () => this.showSessionSelector());\n\n\t\tthis.defaultEditor.onChange = (text: string) => {\n\t\t\tconst wasBashMode = this.isBashMode;\n\t\t\tthis.isBashMode = text.trimStart().startsWith(\"!\");\n\t\t\tif (wasBashMode !== this.isBashMode) {\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t}\n\t\t};\n\n\t\t// Handle clipboard paste (triggered on Ctrl+V). Images are attached by path;\n\t\t// otherwise, paste plain text from the system clipboard.\n\t\tthis.defaultEditor.onPasteImage = () => {\n\t\t\tvoid this.handleClipboardPaste();\n\t\t};\n\t}\n\n\tprivate async handleClipboardPaste(): Promise {\n\t\ttry {\n\t\t\tconst image = await readClipboardImage();\n\t\t\tif (image) {\n\t\t\t\tconst tmpDir = os.tmpdir();\n\t\t\t\tconst ext = extensionForImageMimeType(image.mimeType) ?? \"png\";\n\t\t\t\tconst fileName = `pi-clipboard-${crypto.randomUUID()}.${ext}`;\n\t\t\t\tconst filePath = path.join(tmpDir, fileName);\n\t\t\t\tfs.writeFileSync(filePath, Buffer.from(image.bytes));\n\n\t\t\t\tthis.editor.insertTextAtCursor?.(filePath);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst text = await readClipboardText();\n\t\t\tif (text) {\n\t\t\t\tthis.editor.insertTextAtCursor?.(text);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t}\n\t\t} catch {\n\t\t\t// Silently ignore clipboard errors (may not have permission, etc.)\n\t\t}\n\t}\n\n\tprivate setupEditorSubmitHandler(): void {\n\t\tthis.defaultEditor.onSubmit = async (text: string) => {\n\t\t\ttext = text.trim();\n\t\t\tif (!text) return;\n\n\t\t\t// Handle commands\n\t\t\tif (text === \"/settings\") {\n\t\t\t\tthis.showSettingsSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/scoped-models\") {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.showModelsSelector();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/model\" || text.startsWith(\"/model \")) {\n\t\t\t\tconst searchTerm = text.startsWith(\"/model \") ? text.slice(7).trim() : undefined;\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.handleModelCommand(searchTerm);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/export\" || text.startsWith(\"/export \")) {\n\t\t\t\tawait this.handleExportCommand(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/import\" || text.startsWith(\"/import \")) {\n\t\t\t\tawait this.handleImportCommand(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/share\") {\n\t\t\t\tawait this.handleShareCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/copy\") {\n\t\t\t\tawait this.handleCopyCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/name\" || text.startsWith(\"/name \")) {\n\t\t\t\tthis.handleNameCommand(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/session\") {\n\t\t\t\tthis.handleSessionCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/changelog\") {\n\t\t\t\tthis.handleChangelogCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/hotkeys\") {\n\t\t\t\tthis.handleHotkeysCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/fork\") {\n\t\t\t\tthis.showUserMessageSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/clone\") {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.handleCloneCommand();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/tree\") {\n\t\t\t\tthis.showTreeSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/trust\") {\n\t\t\t\tthis.showTrustSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/login\" || text.startsWith(\"/login \")) {\n\t\t\t\tconst providerRef = text.startsWith(\"/login \") ? text.slice(7).trim() : undefined;\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.handleLoginCommand(providerRef);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/logout\") {\n\t\t\t\tthis.showOAuthSelector(\"logout\");\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/new\") {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.handleClearCommand();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/compact\" || text.startsWith(\"/compact \")) {\n\t\t\t\tconst customInstructions = text.startsWith(\"/compact \") ? text.slice(9).trim() : undefined;\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.handleCompactCommand(customInstructions);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/reload\") {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.handleReloadCommand();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/debug\") {\n\t\t\t\tthis.handleDebugCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/arminsayshi\") {\n\t\t\t\tthis.handleArminSaysHi();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/dementedelves\") {\n\t\t\t\tthis.handleDementedDelves();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/resume\") {\n\t\t\t\tthis.showSessionSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/quit\") {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.shutdown();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Handle bash command (! for normal, !! for excluded from context)\n\t\t\tif (text.startsWith(\"!\")) {\n\t\t\t\tconst isExcluded = text.startsWith(\"!!\");\n\t\t\t\tconst command = isExcluded ? text.slice(2).trim() : text.slice(1).trim();\n\t\t\t\tif (command) {\n\t\t\t\t\tif (this.session.isBashRunning) {\n\t\t\t\t\t\tthis.showWarning(\"A bash command is already running. Press Esc to cancel it first.\");\n\t\t\t\t\t\tthis.editor.setText(text);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthis.editor.addToHistory?.(text);\n\t\t\t\t\tawait this.handleBashCommand(command, isExcluded);\n\t\t\t\t\tthis.isBashMode = false;\n\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Queue input during compaction (extension commands execute immediately)\n\t\t\tif (this.session.isCompacting) {\n\t\t\t\tif (this.isExtensionCommand(text)) {\n\t\t\t\t\tthis.editor.addToHistory?.(text);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.session.prompt(text);\n\t\t\t\t} else {\n\t\t\t\t\tthis.queueCompactionMessage(text, \"steer\");\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// If streaming, use prompt() with steer behavior\n\t\t\t// This handles extension commands (execute immediately), prompt template expansion, and queueing\n\t\t\tif (this.session.isStreaming) {\n\t\t\t\tthis.editor.addToHistory?.(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.session.prompt(text, { streamingBehavior: \"steer\" });\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Normal message submission\n\t\t\t// First, move any pending bash components to chat\n\t\t\tthis.flushPendingBashComponents();\n\n\t\t\tif (this.onInputCallback) {\n\t\t\t\tthis.onInputCallback(text);\n\t\t\t} else {\n\t\t\t\tthis.pendingUserInputs.push(text);\n\t\t\t}\n\t\t\tthis.editor.addToHistory?.(text);\n\t\t};\n\t}\n\n\tprivate subscribeToAgent(): void {\n\t\tthis.unsubscribe = this.session.subscribe(async (event) => {\n\t\t\tawait this.handleEvent(event);\n\t\t});\n\t}\n\n\tprivate async handleEvent(event: AgentSessionEvent): Promise {\n\t\tif (!this.isInitialized) {\n\t\t\tawait this.init();\n\t\t}\n\n\t\tthis.footer.invalidate();\n\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\t\tthis.pendingTools.clear();\n\t\t\t\tif (this.settingsManager.getShowTerminalProgress()) {\n\t\t\t\t\tthis.ui.terminal.setProgress(true);\n\t\t\t\t}\n\t\t\t\t// Restore main escape handler if retry handler is still active\n\t\t\t\t// (retry success event fires later, but we need main handler now)\n\t\t\t\tif (this.retryEscapeHandler) {\n\t\t\t\t\tthis.defaultEditor.onEscape = this.retryEscapeHandler;\n\t\t\t\t\tthis.retryEscapeHandler = undefined;\n\t\t\t\t}\n\t\t\t\tif (this.workingVisible) {\n\t\t\t\t\tthis.showStatusIndicator(\n\t\t\t\t\t\tnew WorkingStatusIndicator(\n\t\t\t\t\t\t\tthis.ui,\n\t\t\t\t\t\t\tthis.workingMessage ?? this.defaultWorkingMessage,\n\t\t\t\t\t\t\tthis.workingIndicatorOptions,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tthis.clearStatusIndicator();\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"queue_update\":\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"entry_appended\":\n\t\t\t\tif (event.entry.type === \"custom\") {\n\t\t\t\t\tthis.addCustomEntryToChat(event.entry);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"session_info_changed\":\n\t\t\t\tthis.updateTerminalTitle();\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"thinking_level_changed\":\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_start\":\n\t\t\t\tif (event.message.role === \"custom\") {\n\t\t\t\t\tthis.addMessageToChat(event.message);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t} else if (event.message.role === \"user\") {\n\t\t\t\t\tthis.addMessageToChat(event.message);\n\t\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t} else if (event.message.role === \"assistant\") {\n\t\t\t\t\tthis.streamingComponent = new AssistantMessageComponent(\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tthis.hideThinkingBlock,\n\t\t\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\t\t\tthis.hiddenThinkingLabel,\n\t\t\t\t\t\tthis.outputPad,\n\t\t\t\t\t);\n\t\t\t\t\tthis.streamingMessage = event.message;\n\t\t\t\t\tthis.chatContainer.addChild(this.streamingComponent);\n\t\t\t\t\tthis.streamingComponent.updateContent(this.streamingMessage);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tif (this.streamingComponent && event.message.role === \"assistant\") {\n\t\t\t\t\tthis.streamingMessage = event.message;\n\t\t\t\t\tthis.streamingComponent.updateContent(this.streamingMessage);\n\n\t\t\t\t\tfor (const content of this.streamingMessage.content) {\n\t\t\t\t\t\tif (content.type === \"toolCall\") {\n\t\t\t\t\t\t\tif (!this.pendingTools.has(content.id)) {\n\t\t\t\t\t\t\t\tconst component = new ToolExecutionComponent(\n\t\t\t\t\t\t\t\t\tcontent.name,\n\t\t\t\t\t\t\t\t\tcontent.id,\n\t\t\t\t\t\t\t\t\tcontent.arguments,\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\t\t\t\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tthis.getRegisteredToolDefinition(content.name),\n\t\t\t\t\t\t\t\t\tthis.ui,\n\t\t\t\t\t\t\t\t\tthis.sessionManager.getCwd(),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t\t\t\t\tthis.pendingTools.set(content.id, component);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst component = this.pendingTools.get(content.id);\n\t\t\t\t\t\t\t\tif (component) {\n\t\t\t\t\t\t\t\t\tcomponent.updateArgs(content.arguments);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tif (event.message.role === \"user\") break;\n\t\t\t\tif (this.streamingComponent && event.message.role === \"assistant\") {\n\t\t\t\t\tthis.streamingMessage = event.message;\n\t\t\t\t\tlet errorMessage: string | undefined;\n\t\t\t\t\tif (this.streamingMessage.stopReason === \"aborted\") {\n\t\t\t\t\t\tconst retryAttempt = this.session.retryAttempt;\n\t\t\t\t\t\terrorMessage =\n\t\t\t\t\t\t\tretryAttempt > 0\n\t\t\t\t\t\t\t\t? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? \"s\" : \"\"}`\n\t\t\t\t\t\t\t\t: \"Operation aborted\";\n\t\t\t\t\t\tthis.streamingMessage.errorMessage = errorMessage;\n\t\t\t\t\t}\n\t\t\t\t\tthis.streamingComponent.updateContent(this.streamingMessage);\n\n\t\t\t\t\tif (this.streamingMessage.stopReason === \"aborted\" || this.streamingMessage.stopReason === \"error\") {\n\t\t\t\t\t\tif (!errorMessage) {\n\t\t\t\t\t\t\terrorMessage = this.streamingMessage.errorMessage || \"Error\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const [, component] of this.pendingTools.entries()) {\n\t\t\t\t\t\t\tcomponent.updateResult({\n\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: errorMessage }],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.pendingTools.clear();\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Args are now complete - trigger diff computation for edit tools\n\t\t\t\t\t\tfor (const [, component] of this.pendingTools.entries()) {\n\t\t\t\t\t\t\tcomponent.setArgsComplete();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.maybeShowCacheMissNotice(this.streamingMessage);\n\t\t\t\t\t}\n\t\t\t\t\tthis.streamingComponent = undefined;\n\t\t\t\t\tthis.streamingMessage = undefined;\n\t\t\t\t\tthis.footer.invalidate();\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"bash_execution_update\":\n\t\t\t\t// The bash execution callback handles TUI output rendering.\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tlet component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (!component) {\n\t\t\t\t\tcomponent = new ToolExecutionComponent(\n\t\t\t\t\t\tevent.toolName,\n\t\t\t\t\t\tevent.toolCallId,\n\t\t\t\t\t\tevent.args,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tthis.getRegisteredToolDefinition(event.toolName),\n\t\t\t\t\t\tthis.ui,\n\t\t\t\t\t\tthis.sessionManager.getCwd(),\n\t\t\t\t\t);\n\t\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t\tthis.pendingTools.set(event.toolCallId, component);\n\t\t\t\t}\n\t\t\t\tcomponent.markExecutionStarted();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_update\": {\n\t\t\t\tconst component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\tcomponent.updateResult({ ...event.partialResult, isError: false }, true);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\tcomponent.updateResult({ ...event.result, isError: event.isError });\n\t\t\t\t\tthis.pendingTools.delete(event.toolCallId);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tif (this.settingsManager.getShowTerminalProgress()) {\n\t\t\t\t\tthis.ui.terminal.setProgress(false);\n\t\t\t\t}\n\t\t\t\tthis.clearStatusIndicator(\"working\");\n\t\t\t\tif (this.streamingComponent) {\n\t\t\t\t\tthis.chatContainer.removeChild(this.streamingComponent);\n\t\t\t\t\tthis.streamingComponent = undefined;\n\t\t\t\t\tthis.streamingMessage = undefined;\n\t\t\t\t}\n\t\t\t\tthis.pendingTools.clear();\n\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_settled\":\n\t\t\t\tawait this.checkShutdownRequested();\n\t\t\t\tbreak;\n\n\t\t\tcase \"compaction_start\": {\n\t\t\t\tif (this.settingsManager.getShowTerminalProgress()) {\n\t\t\t\t\tthis.ui.terminal.setProgress(true);\n\t\t\t\t}\n\t\t\t\t// Keep editor active; submissions are queued during compaction.\n\t\t\t\tthis.autoCompactionEscapeHandler = this.defaultEditor.onEscape;\n\t\t\t\tthis.defaultEditor.onEscape = () => {\n\t\t\t\t\tthis.session.abortCompaction();\n\t\t\t\t};\n\t\t\t\tthis.showStatusIndicator(new CompactionStatusIndicator(this.ui, event.reason));\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"compaction_end\": {\n\t\t\t\tif (this.settingsManager.getShowTerminalProgress()) {\n\t\t\t\t\tthis.ui.terminal.setProgress(false);\n\t\t\t\t}\n\t\t\t\tif (this.autoCompactionEscapeHandler) {\n\t\t\t\t\tthis.defaultEditor.onEscape = this.autoCompactionEscapeHandler;\n\t\t\t\t\tthis.autoCompactionEscapeHandler = undefined;\n\t\t\t\t}\n\t\t\t\tthis.clearStatusIndicator(\"compaction\");\n\t\t\t\tif (event.aborted) {\n\t\t\t\t\tif (event.reason === \"manual\") {\n\t\t\t\t\t\tthis.showError(\"Compaction cancelled\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.showStatus(\"Auto-compaction cancelled\");\n\t\t\t\t\t}\n\t\t\t\t} else if (event.result) {\n\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\t\tthis.addMessageToChat(\n\t\t\t\t\t\tcreateCompactionSummaryMessage(\n\t\t\t\t\t\t\tevent.result.summary,\n\t\t\t\t\t\t\tevent.result.tokensBefore,\n\t\t\t\t\t\t\tnew Date().toISOString(),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tthis.footer.invalidate();\n\t\t\t\t} else if (event.errorMessage) {\n\t\t\t\t\tif (event.reason === \"manual\") {\n\t\t\t\t\t\tthis.showError(event.errorMessage);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"error\", event.errorMessage), 1, 0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvoid this.flushCompactionQueue({ willRetry: event.willRetry });\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"auto_retry_start\": {\n\t\t\t\t// Set up escape to abort retry\n\t\t\t\tthis.retryEscapeHandler = this.defaultEditor.onEscape;\n\t\t\t\tthis.defaultEditor.onEscape = () => {\n\t\t\t\t\tthis.session.abortRetry();\n\t\t\t\t};\n\t\t\t\tthis.showStatusIndicator(\n\t\t\t\t\tnew RetryStatusIndicator(this.ui, event.attempt, event.maxAttempts, event.delayMs),\n\t\t\t\t);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"auto_retry_end\": {\n\t\t\t\t// Restore escape handler\n\t\t\t\tif (this.retryEscapeHandler) {\n\t\t\t\t\tthis.defaultEditor.onEscape = this.retryEscapeHandler;\n\t\t\t\t\tthis.retryEscapeHandler = undefined;\n\t\t\t\t}\n\t\t\t\tthis.clearStatusIndicator(\"retry\");\n\t\t\t\t// Show error only on final failure (success shows normal response)\n\t\t\t\tif (!event.success) {\n\t\t\t\t\tthis.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError || \"Unknown error\"}`);\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"summarization_retry_scheduled\": {\n\t\t\t\tthis.showError(event.errorMessage);\n\t\t\t\tthis.showStatusIndicator(\n\t\t\t\t\tnew RetryStatusIndicator(this.ui, event.attempt, event.maxAttempts, event.delayMs),\n\t\t\t\t);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"summarization_retry_attempt_start\": {\n\t\t\t\tthis.clearStatusIndicator(\"retry\");\n\t\t\t\tif (event.source === \"branchSummary\") {\n\t\t\t\t\tthis.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui));\n\t\t\t\t} else {\n\t\t\t\t\tthis.showStatusIndicator(new CompactionStatusIndicator(this.ui, event.reason));\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"summarization_retry_finished\": {\n\t\t\t\tthis.clearStatusIndicator(\"retry\");\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Extract text content from a user message */\n\tprivate getUserMessageText(message: Message): string {\n\t\tif (message.role !== \"user\") return \"\";\n\t\tconst textBlocks =\n\t\t\ttypeof message.content === \"string\"\n\t\t\t\t? [{ type: \"text\", text: message.content }]\n\t\t\t\t: message.content.filter((c: { type: string }) => c.type === \"text\");\n\t\treturn textBlocks.map((c) => (c as { text: string }).text).join(\"\");\n\t}\n\n\t/**\n\t * Show a status message in the chat.\n\t *\n\t * If multiple status messages are emitted back-to-back (without anything else being added to the chat),\n\t * we update the previous status line instead of appending new ones to avoid log spam.\n\t */\n\tprivate showStatus(message: string): void {\n\t\tconst children = this.chatContainer.children;\n\t\tconst last = children.length > 0 ? children[children.length - 1] : undefined;\n\t\tconst secondLast = children.length > 1 ? children[children.length - 2] : undefined;\n\n\t\tif (last && secondLast && last === this.lastStatusText && secondLast === this.lastStatusSpacer) {\n\t\t\tthis.lastStatusText.setText(theme.fg(\"dim\", message));\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\tconst spacer = new Spacer(1);\n\t\tconst text = new Text(theme.fg(\"dim\", message), 1, 0);\n\t\tthis.chatContainer.addChild(spacer);\n\t\tthis.chatContainer.addChild(text);\n\t\tthis.lastStatusSpacer = spacer;\n\t\tthis.lastStatusText = text;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate addCustomEntryToChat(entry: Extract): void {\n\t\tconst renderer = this.session.extensionRunner.getEntryRenderer(entry.customType);\n\t\tif (!renderer) {\n\t\t\treturn;\n\t\t}\n\t\tconst component = new CustomEntryComponent(entry, renderer);\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tif (!component.hasContent()) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.streamingComponent) {\n\t\t\tconst streamingIndex = this.chatContainer.children.indexOf(this.streamingComponent);\n\t\t\tif (streamingIndex >= 0) {\n\t\t\t\tthis.chatContainer.children.splice(streamingIndex, 0, component);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.chatContainer.addChild(component);\n\t}\n\n\tprivate addMessageToChat(message: AgentMessage, options?: { populateHistory?: boolean }): void {\n\t\tswitch (message.role) {\n\t\t\tcase \"bashExecution\": {\n\t\t\t\tconst component = new BashExecutionComponent(message.command, this.ui, message.excludeFromContext);\n\t\t\t\tif (message.output) {\n\t\t\t\t\tcomponent.appendOutput(message.output);\n\t\t\t\t}\n\t\t\t\tcomponent.setComplete(\n\t\t\t\t\tmessage.exitCode,\n\t\t\t\t\tmessage.cancelled,\n\t\t\t\t\tmessage.truncated ? ({ truncated: true } as TruncationResult) : undefined,\n\t\t\t\t\tmessage.fullOutputPath,\n\t\t\t\t);\n\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"custom\": {\n\t\t\t\tif (message.display) {\n\t\t\t\t\tconst renderer = this.session.extensionRunner.getMessageRenderer(message.customType);\n\t\t\t\t\tconst component = new CustomMessageComponent(\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\trenderer,\n\t\t\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\t\t\tthis.outputPad,\n\t\t\t\t\t);\n\t\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"compactionSummary\": {\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tconst component = new CompactionSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());\n\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"branchSummary\": {\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tconst component = new BranchSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());\n\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"user\": {\n\t\t\t\tconst textContent = this.getUserMessageText(message);\n\t\t\t\tif (textContent) {\n\t\t\t\t\tif (this.chatContainer.children.length > 0) {\n\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t}\n\t\t\t\t\tconst skillBlock = parseSkillBlock(textContent);\n\t\t\t\t\tif (skillBlock) {\n\t\t\t\t\t\t// Render skill block (collapsible)\n\t\t\t\t\t\tconst component = new SkillInvocationMessageComponent(\n\t\t\t\t\t\t\tskillBlock,\n\t\t\t\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t\t\t// Render user message separately if present\n\t\t\t\t\t\tif (skillBlock.userMessage) {\n\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\tconst userComponent = new UserMessageComponent(\n\t\t\t\t\t\t\t\tskillBlock.userMessage,\n\t\t\t\t\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\t\t\t\t\tthis.outputPad,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tthis.chatContainer.addChild(userComponent);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst userComponent = new UserMessageComponent(\n\t\t\t\t\t\t\ttextContent,\n\t\t\t\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\t\t\t\tthis.outputPad,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.chatContainer.addChild(userComponent);\n\t\t\t\t\t}\n\t\t\t\t\tif (options?.populateHistory) {\n\t\t\t\t\t\tthis.editor.addToHistory?.(textContent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"assistant\": {\n\t\t\t\tconst assistantComponent = new AssistantMessageComponent(\n\t\t\t\t\tmessage,\n\t\t\t\t\tthis.hideThinkingBlock,\n\t\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\t\tthis.hiddenThinkingLabel,\n\t\t\t\t\tthis.outputPad,\n\t\t\t\t);\n\t\t\t\tthis.chatContainer.addChild(assistantComponent);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"toolResult\": {\n\t\t\t\t// Tool results are rendered inline with tool calls, handled separately\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustive: never = message;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate renderSessionItems(\n\t\titems: readonly RenderSessionItem[],\n\t\toptions: { updateFooter?: boolean; populateHistory?: boolean } = {},\n\t): void {\n\t\tthis.pendingTools.clear();\n\t\tconst renderedPendingTools = new Map();\n\t\t// Cache-miss notices are not persisted; re-derive them from the full entry\n\t\t// list and re-inject them after the assistant messages that paid for them.\n\t\tconst cacheMisses = this.settingsManager.getShowCacheMissNotices()\n\t\t\t? collectCacheMisses(this.sessionManager.getEntries(), this.session.modelRuntime)\n\t\t\t: new Map();\n\n\t\tif (options.updateFooter) {\n\t\t\tthis.footer.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t}\n\n\t\tfor (const item of items) {\n\t\t\tif (isCustomSessionEntry(item)) {\n\t\t\t\tthis.addCustomEntryToChat(item);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst message = item;\n\t\t\t// Assistant messages need special handling for tool calls\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tthis.addMessageToChat(message);\n\t\t\t\t// Render tool call components\n\t\t\t\tfor (const content of message.content) {\n\t\t\t\t\tif (content.type === \"toolCall\") {\n\t\t\t\t\t\tconst component = new ToolExecutionComponent(\n\t\t\t\t\t\t\tcontent.name,\n\t\t\t\t\t\t\tcontent.id,\n\t\t\t\t\t\t\tcontent.arguments,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\t\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tthis.getRegisteredToolDefinition(content.name),\n\t\t\t\t\t\t\tthis.ui,\n\t\t\t\t\t\t\tthis.sessionManager.getCwd(),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\t\tthis.chatContainer.addChild(component);\n\n\t\t\t\t\t\tif (message.stopReason === \"aborted\" || message.stopReason === \"error\") {\n\t\t\t\t\t\t\tlet errorMessage: string;\n\t\t\t\t\t\t\tif (message.stopReason === \"aborted\") {\n\t\t\t\t\t\t\t\tconst retryAttempt = this.session.retryAttempt;\n\t\t\t\t\t\t\t\terrorMessage =\n\t\t\t\t\t\t\t\t\tretryAttempt > 0\n\t\t\t\t\t\t\t\t\t\t? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? \"s\" : \"\"}`\n\t\t\t\t\t\t\t\t\t\t: \"Operation aborted\";\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\terrorMessage = message.errorMessage || \"Error\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcomponent.updateResult({ content: [{ type: \"text\", text: errorMessage }], isError: true });\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\trenderedPendingTools.set(content.id, component);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (message.stopReason !== \"aborted\" && message.stopReason !== \"error\") {\n\t\t\t\t\tconst miss = cacheMisses.get(message);\n\t\t\t\t\tif (miss) this.addCacheMissNotice(miss);\n\t\t\t\t}\n\t\t\t} else if (message.role === \"toolResult\") {\n\t\t\t\t// Match tool results to pending tool components\n\t\t\t\tconst component = renderedPendingTools.get(message.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\tcomponent.updateResult(message);\n\t\t\t\t\trenderedPendingTools.delete(message.toolCallId);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// All other messages use standard rendering\n\t\t\t\tthis.addMessageToChat(message, options);\n\t\t\t}\n\t\t}\n\n\t\tfor (const [toolCallId, component] of renderedPendingTools) {\n\t\t\tthis.pendingTools.set(toolCallId, component);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Render session entries to chat. Used for initial load and rebuild after compaction.\n\t * @param entries Compaction-aware session entries to render\n\t * @param options.updateFooter Update footer state\n\t * @param options.populateHistory Add user messages to editor history\n\t */\n\tprivate renderSessionEntries(\n\t\tentries: SessionEntry[],\n\t\toptions: { updateFooter?: boolean; populateHistory?: boolean } = {},\n\t): void {\n\t\tconst items = entries.flatMap((entry): RenderSessionItem[] => {\n\t\t\tif (entry.type === \"custom\") {\n\t\t\t\treturn [entry];\n\t\t\t}\n\t\t\treturn sessionEntryToContextMessages(entry);\n\t\t});\n\t\tthis.renderSessionItems(items, options);\n\t}\n\n\t/**\n\t * Show a transcript notice when a completed assistant message paid for a\n\t * significant cache miss. Only states observable facts: the miss itself,\n\t * a model switch, or an idle gap past the cache TTL.\n\t */\n\tprivate maybeShowCacheMissNotice(message: AssistantMessage): void {\n\t\tif (!this.settingsManager.getShowCacheMissNotices()) return;\n\n\t\t// Entries don't contain `message` yet: message_end fires before persistence.\n\t\tconst miss = detectCacheMiss(this.sessionManager.getEntries(), message, this.session.modelRuntime);\n\t\tif (miss) this.addCacheMissNotice(miss);\n\t}\n\n\tprivate addCacheMissNotice(miss: CacheMiss): void {\n\t\tif (miss.missedTokens < 20_000 && miss.missedCost < 0.1) return;\n\n\t\tconst cost = miss.missedCost >= 0.01 ? ` (~$${miss.missedCost.toFixed(2)})` : \"\";\n\t\tconst reBilled = `${formatTokens(miss.missedTokens)} tokens re-billed${cost}`;\n\t\tlet label = \"Cache miss\";\n\t\tif (miss.modelChanged) {\n\t\t\tlabel = \"Cache miss after model switch\";\n\t\t} else if (miss.idleMs >= CACHE_TTL_MS) {\n\t\t\tlabel = `Cache miss after ${Math.round(miss.idleMs / 60_000)}m idle`;\n\t\t}\n\t\tconst text = theme.fg(\"warning\", `${label}: ${reBilled}`);\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(text, 1, 0));\n\t}\n\n\trenderInitialMessages(): void {\n\t\tconst entries = this.sessionManager.buildContextEntries();\n\t\tthis.renderSessionEntries(entries, {\n\t\t\tupdateFooter: true,\n\t\t\tpopulateHistory: true,\n\t\t});\n\t\tthis.renderProjectTrustWarningIfNeeded();\n\n\t\t// Show compaction info if session was compacted\n\t\tconst allEntries = this.sessionManager.getEntries();\n\t\tconst compactionCount = allEntries.filter((e) => e.type === \"compaction\").length;\n\t\tif (compactionCount > 0) {\n\t\t\tconst times = compactionCount === 1 ? \"1 time\" : `${compactionCount} times`;\n\t\t\tthis.showStatus(`Session compacted ${times}`);\n\t\t}\n\t}\n\n\tprivate renderProjectTrustWarningIfNeeded(): void {\n\t\tif (this.settingsManager.isProjectTrusted() || !hasTrustRequiringProjectResources(this.sessionManager.getCwd())) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.chatContainer.children.length > 0) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.fg(\n\t\t\t\t\t\"warning\",\n\t\t\t\t\t`This project is not trusted. Project ${CONFIG_DIR_NAME} resources and packages are ignored. Use /trust to save a trust decision, then restart pi.`,\n\t\t\t\t),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t}\n\n\tasync getUserInput(): Promise {\n\t\tconst queuedInput = this.pendingUserInputs.shift();\n\t\tif (queuedInput !== undefined) {\n\t\t\treturn queuedInput;\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.onInputCallback = (text: string) => {\n\t\t\t\tthis.onInputCallback = undefined;\n\t\t\t\tresolve(text);\n\t\t\t};\n\t\t});\n\t}\n\n\tprivate rebuildChatFromMessages(): void {\n\t\tthis.chatContainer.clear();\n\t\tthis.renderSessionEntries(this.sessionManager.buildContextEntries());\n\t}\n\n\t// =========================================================================\n\t// Key handlers\n\t// =========================================================================\n\n\tprivate handleCtrlC(): void {\n\t\tconst now = Date.now();\n\t\tif (now - this.lastSigintTime < 500) {\n\t\t\tvoid this.shutdown();\n\t\t} else {\n\t\t\tthis.clearEditor();\n\t\t\tthis.lastSigintTime = now;\n\t\t}\n\t}\n\n\tprivate handleCtrlD(): void {\n\t\t// Only called when editor is empty (enforced by CustomEditor)\n\t\tvoid this.shutdown();\n\t}\n\n\t/**\n\t * Gracefully shutdown the agent.\n\t * Stops the TUI before emitting shutdown events so extension UI cleanup cannot\n\t * repaint the final frame while the process is exiting.\n\t */\n\tprivate isShuttingDown = false;\n\n\tprivate async shutdown(options?: { fromSignal?: boolean }): Promise {\n\t\tif (this.isShuttingDown) return;\n\t\tthis.isShuttingDown = true;\n\t\t// Keep signal handlers registered until terminal cleanup has completed.\n\t\t// `signal-exit` checks the listener list during the same SIGTERM/SIGHUP\n\t\t// dispatch and re-sends the signal if only its own listeners remain.\n\n\t\tif (options?.fromSignal) {\n\t\t\t// Signal-triggered shutdown (SIGTERM/SIGHUP). Emit extension cleanup\n\t\t\t// (session_shutdown) BEFORE touching the terminal. Extension teardown\n\t\t\t// such as removing sockets does not write to the tty, so it must not be\n\t\t\t// skipped if a later terminal-restore write fails on a dead or stalled\n\t\t\t// terminal. If the terminal is gone, the restore writes below emit EIO,\n\t\t\t// which the stdout/stderr error handler turns into emergencyTerminalExit;\n\t\t\t// the render loop is already idle, so this cannot hot-spin (see #4144).\n\t\t\tawait this.runtimeHost.dispose();\n\t\t\tthis.themeController.disableAutoSync();\n\t\t\tawait this.ui.terminal.drainInput(1000);\n\t\t\tthis.stop();\n\t\t\tprocess.exit(0);\n\t\t}\n\n\t\t// Interactive quit (Ctrl+D, Ctrl+C, /quit, extension shutdown()). Stop the\n\t\t// TUI before emitting shutdown events so extension UI cleanup cannot repaint\n\t\t// the final frame while the process is exiting.\n\t\t// Drain any in-flight Kitty key release events before stopping.\n\t\t// This prevents escape sequences from leaking to the parent shell over slow SSH.\n\t\tthis.themeController.disableAutoSync();\n\t\tawait this.ui.terminal.drainInput(1000);\n\n\t\tthis.stop();\n\t\tawait this.runtimeHost.dispose();\n\n\t\tconst resumeCommand = formatResumeCommand(this.sessionManager);\n\t\tif (resumeCommand) {\n\t\t\tprocess.stdout.write(`${chalk.dim(\"To resume this session:\")} ${resumeCommand}\\n`);\n\t\t}\n\n\t\tprocess.exit(0);\n\t}\n\n\tprivate emergencyTerminalExit(): never {\n\t\tthis.isShuttingDown = true;\n\t\tthis.unregisterSignalHandlers();\n\t\tkillTrackedDetachedChildren();\n\t\t// The terminal is gone. Do not run normal shutdown because TUI and\n\t\t// extension cleanup can write restore sequences and re-trigger EIO.\n\t\tprocess.exit(129);\n\t}\n\n\t/**\n\t * Last-resort handler for uncaught exceptions. The TUI puts stdin into raw\n\t * mode and hides the cursor; without this handler, an uncaught throw from\n\t * anywhere (e.g. an extension's async `ChildProcess.on(\"exit\")` callback)\n\t * tears down the process while leaving the terminal in raw mode with no\n\t * cursor, requiring `stty sane && reset` to recover.\n\t *\n\t * Unlike emergencyTerminalExit, the terminal is still alive here, so we\n\t * call ui.stop() to restore cooked mode, the cursor, and disable bracketed\n\t * paste / Kitty / modifyOtherKeys sequences.\n\t */\n\tprivate uncaughtCrash(error: Error): never {\n\t\tif (this.isShuttingDown) {\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tthis.isShuttingDown = true;\n\t\ttry {\n\t\t\tthis.unregisterSignalHandlers();\n\t\t} catch {}\n\t\ttry {\n\t\t\tkillTrackedDetachedChildren();\n\t\t} catch {}\n\t\ttry {\n\t\t\tthis.ui.stop();\n\t\t} catch {}\n\t\tconsole.error(\"pi exiting due to uncaughtException:\");\n\t\tconsole.error(error);\n\t\tprocess.exit(1);\n\t}\n\n\t/**\n\t * Check if shutdown was requested and perform shutdown if so.\n\t */\n\tprivate async checkShutdownRequested(): Promise {\n\t\tif (!this.shutdownRequested) return;\n\t\tawait this.shutdown();\n\t}\n\n\tprivate registerSignalHandlers(): void {\n\t\tthis.unregisterSignalHandlers();\n\n\t\tconst signals: NodeJS.Signals[] = [\"SIGTERM\"];\n\t\tif (process.platform !== \"win32\") {\n\t\t\tsignals.push(\"SIGHUP\");\n\t\t}\n\n\t\tfor (const signal of signals) {\n\t\t\tconst handler = () => {\n\t\t\t\t// SIGHUP no longer hard-exits: graceful shutdown emits session_shutdown\n\t\t\t\t// first, then attempts terminal restore. A genuinely dead terminal\n\t\t\t\t// surfaces as an EIO on the restore writes, which the stdout/stderr\n\t\t\t\t// error handler converts into emergencyTerminalExit (see #4144, #5080).\n\t\t\t\tkillTrackedDetachedChildren();\n\t\t\t\tvoid this.shutdown({ fromSignal: true });\n\t\t\t};\n\t\t\tprocess.prependListener(signal, handler);\n\t\t\tthis.signalCleanupHandlers.push(() => process.off(signal, handler));\n\t\t}\n\n\t\tconst terminalErrorHandler = (error: Error) => {\n\t\t\tif (isDeadTerminalError(error)) {\n\t\t\t\tthis.emergencyTerminalExit();\n\t\t\t}\n\t\t\tthrow error;\n\t\t};\n\t\tprocess.stdout.on(\"error\", terminalErrorHandler);\n\t\tprocess.stderr.on(\"error\", terminalErrorHandler);\n\t\tthis.signalCleanupHandlers.push(() => process.stdout.off(\"error\", terminalErrorHandler));\n\t\tthis.signalCleanupHandlers.push(() => process.stderr.off(\"error\", terminalErrorHandler));\n\n\t\t// Restore the terminal before the process dies on any uncaught throw.\n\t\t// Without this, an unhandled exception from extension code (or anywhere\n\t\t// in pi) leaves the terminal in raw mode with no cursor.\n\t\tconst uncaughtExceptionHandler = (error: Error) => this.uncaughtCrash(error);\n\t\tprocess.prependListener(\"uncaughtException\", uncaughtExceptionHandler);\n\t\tthis.signalCleanupHandlers.push(() => process.off(\"uncaughtException\", uncaughtExceptionHandler));\n\t}\n\n\tprivate unregisterSignalHandlers(): void {\n\t\tfor (const cleanup of this.signalCleanupHandlers) {\n\t\t\tcleanup();\n\t\t}\n\t\tthis.signalCleanupHandlers = [];\n\t}\n\n\tprivate handleCtrlZ(): void {\n\t\tif (process.platform === \"win32\") {\n\t\t\tthis.showStatus(\"Suspend to background is not supported on Windows\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Keep the event loop alive while suspended. Without this, stopping the TUI\n\t\t// can leave Node with no ref'ed handles, causing the process to exit on fg\n\t\t// before the SIGCONT handler gets a chance to restore the terminal.\n\t\tconst suspendKeepAlive = setInterval(() => {}, 2 ** 30);\n\n\t\t// Ignore SIGINT while suspended so Ctrl+C in the terminal does not\n\t\t// kill the backgrounded process. The handler is removed on resume.\n\t\tconst ignoreSigint = () => {};\n\t\tprocess.on(\"SIGINT\", ignoreSigint);\n\n\t\t// Set up handler to restore TUI when resumed\n\t\tprocess.once(\"SIGCONT\", () => {\n\t\t\tclearInterval(suspendKeepAlive);\n\t\t\tprocess.removeListener(\"SIGINT\", ignoreSigint);\n\t\t\tthis.ui.start();\n\t\t\tthis.ui.requestRender(true);\n\t\t});\n\n\t\ttry {\n\t\t\t// Stop the TUI (restore terminal to normal mode)\n\t\t\tthis.ui.stop();\n\n\t\t\t// Send SIGTSTP to process group (pid=0 means all processes in group)\n\t\t\tprocess.kill(0, \"SIGTSTP\");\n\t\t} catch (error) {\n\t\t\tclearInterval(suspendKeepAlive);\n\t\t\tprocess.removeListener(\"SIGINT\", ignoreSigint);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async handleFollowUp(): Promise {\n\t\tconst text = (this.editor.getExpandedText?.() ?? this.editor.getText()).trim();\n\t\tif (!text) return;\n\n\t\t// Queue input during compaction (extension commands execute immediately)\n\t\tif (this.session.isCompacting) {\n\t\t\tif (this.isExtensionCommand(text)) {\n\t\t\t\tthis.editor.addToHistory?.(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.session.prompt(text);\n\t\t\t} else {\n\t\t\t\tthis.queueCompactionMessage(text, \"followUp\");\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Alt+Enter queues a follow-up message (waits until agent finishes)\n\t\t// This handles extension commands (execute immediately), prompt template expansion, and queueing\n\t\tif (this.session.isStreaming) {\n\t\t\tthis.editor.addToHistory?.(text);\n\t\t\tthis.editor.setText(\"\");\n\t\t\tawait this.session.prompt(text, { streamingBehavior: \"followUp\" });\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tthis.ui.requestRender();\n\t\t}\n\t\t// If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)\n\t\telse if (this.editor.onSubmit) {\n\t\t\tthis.editor.setText(\"\");\n\t\t\tthis.editor.onSubmit(text);\n\t\t}\n\t}\n\n\tprivate handleDequeue(): void {\n\t\tconst restored = this.restoreQueuedMessagesToEditor();\n\t\tif (restored === 0) {\n\t\t\tthis.showStatus(\"No queued messages to restore\");\n\t\t} else {\n\t\t\tthis.showStatus(`Restored ${restored} queued message${restored > 1 ? \"s\" : \"\"} to editor`);\n\t\t}\n\t}\n\n\tprivate updateEditorBorderColor(): void {\n\t\tif (this.isBashMode) {\n\t\t\tthis.editor.borderColor = theme.getBashModeBorderColor();\n\t\t} else {\n\t\t\tconst level = this.session.thinkingLevel || \"off\";\n\t\t\tthis.editor.borderColor = theme.getThinkingBorderColor(level);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate cycleThinkingLevel(): void {\n\t\tconst newLevel = this.session.cycleThinkingLevel();\n\t\tif (newLevel === undefined) {\n\t\t\tthis.showStatus(\"Current model does not support thinking\");\n\t\t} else {\n\t\t\tthis.footer.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.showStatus(`Thinking level: ${newLevel}`);\n\t\t}\n\t}\n\n\tprivate async cycleModel(direction: \"forward\" | \"backward\"): Promise {\n\t\ttry {\n\t\t\tconst result = await this.session.cycleModel(direction);\n\t\t\tif (result === undefined) {\n\t\t\t\tconst msg = this.session.scopedModels.length > 0 ? \"Only one model in scope\" : \"Only one model available\";\n\t\t\t\tthis.showStatus(msg);\n\t\t\t} else {\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tconst thinkingStr =\n\t\t\t\t\tresult.model.reasoning && result.thinkingLevel !== \"off\" ? ` (thinking: ${result.thinkingLevel})` : \"\";\n\t\t\t\tthis.showStatus(`Switched to ${result.model.name || result.model.id}${thinkingStr}`);\n\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(result.model);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate toggleToolOutputExpansion(): void {\n\t\tthis.setToolsExpanded(!this.toolOutputExpanded);\n\t}\n\n\tprivate setToolsExpanded(expanded: boolean): void {\n\t\tthis.toolOutputExpanded = expanded;\n\t\tconst activeHeader = this.customHeader ?? this.builtInHeader;\n\t\tif (isExpandable(activeHeader)) {\n\t\t\tactiveHeader.setExpanded(expanded);\n\t\t}\n\t\tfor (const container of [this.loadedResourcesContainer, this.chatContainer]) {\n\t\t\tfor (const child of container.children) {\n\t\t\t\tif (isExpandable(child)) {\n\t\t\t\t\tchild.setExpanded(expanded);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.showStatus(`Tool output: ${expanded ? \"expanded\" : \"collapsed\"}`);\n\t}\n\n\tprivate toggleThinkingBlockVisibility(): void {\n\t\tthis.hideThinkingBlock = !this.hideThinkingBlock;\n\t\tthis.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);\n\n\t\t// Rebuild chat from session messages\n\t\tthis.chatContainer.clear();\n\t\tthis.rebuildChatFromMessages();\n\n\t\t// If streaming, re-add the streaming component with updated visibility and re-render\n\t\tif (this.streamingComponent && this.streamingMessage) {\n\t\t\tthis.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock);\n\t\t\tthis.streamingComponent.updateContent(this.streamingMessage);\n\t\t\tthis.chatContainer.addChild(this.streamingComponent);\n\t\t}\n\n\t\tthis.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? \"hidden\" : \"visible\"}`);\n\t}\n\n\tprivate async handleOpenExternalEditor(): Promise {\n\t\tconst editorCmd = this.settingsManager.getExternalEditorCommand();\n\t\tconst content = this.editor.getExpandedText?.() ?? this.editor.getText();\n\t\tthis.ui.stop();\n\t\ttry {\n\t\t\tconst result = await editInExternalEditor({\n\t\t\t\tcommand: editorCmd,\n\t\t\t\tcontent,\n\t\t\t});\n\t\t\tif (result.status === \"complete\") {\n\t\t\t\tthis.editor.setText(result.content);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.ui.start();\n\t\t\tthis.ui.requestRender(true);\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// UI helpers\n\t// =========================================================================\n\n\tclearEditor(): void {\n\t\tthis.editor.setText(\"\");\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowError(errorMessage: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"error\", `Error: ${errorMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowWarning(warningMessage: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"warning\", `Warning: ${warningMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowNewVersionNotification(release: LatestPiRelease): void {\n\t\tconst action = theme.fg(\"accent\", `${APP_NAME} update`);\n\t\tconst updateInstruction = theme.fg(\"muted\", `New version ${release.version} is available. Run `) + action;\n\t\tconst changelogUrl = \"https://pi.dev/changelog\";\n\t\tconst changelogLink = getCapabilities().hyperlinks\n\t\t\t? hyperlink(theme.fg(\"accent\", changelogUrl), changelogUrl)\n\t\t\t: theme.fg(\"accent\", changelogUrl);\n\t\tconst changelogLine = theme.fg(\"muted\", \"Changelog: \") + changelogLink;\n\t\tconst note = release.note?.trim();\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(`${theme.bold(theme.fg(\"warning\", \"Update Available\"))}\\n${updateInstruction}`, 1, 0),\n\t\t);\n\t\tif (note) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(\n\t\t\t\tnew Markdown(note, 1, 0, this.getMarkdownThemeWithSettings(), {\n\t\t\t\t\tcolor: (text) => theme.fg(\"muted\", text),\n\t\t\t\t}),\n\t\t\t);\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new Text(changelogLine, 1, 0));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowPackageUpdateNotification(packages: string[]): void {\n\t\tconst action = theme.fg(\"accent\", `${APP_NAME} update --extensions`);\n\t\tconst updateInstruction = theme.fg(\"muted\", \"Package updates are available. Run \") + action;\n\t\tconst packageLines = packages.map((pkg) => `- ${pkg}`).join(\"\\n\");\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(\n\t\t\t\t`${theme.bold(theme.fg(\"warning\", \"Package Updates Available\"))}\\n${updateInstruction}\\n${theme.fg(\"muted\", \"Packages:\")}\\n${packageLines}`,\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Get all queued messages (read-only).\n\t * Combines session queue and compaction queue.\n\t */\n\tprivate getAllQueuedMessages(): { steering: string[]; followUp: string[] } {\n\t\treturn {\n\t\t\tsteering: [\n\t\t\t\t...this.session.getSteeringMessages(),\n\t\t\t\t...this.compactionQueuedMessages.filter((msg) => msg.mode === \"steer\").map((msg) => msg.text),\n\t\t\t],\n\t\t\tfollowUp: [\n\t\t\t\t...this.session.getFollowUpMessages(),\n\t\t\t\t...this.compactionQueuedMessages.filter((msg) => msg.mode === \"followUp\").map((msg) => msg.text),\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Clear all queued messages and return their contents.\n\t * Clears both session queue and compaction queue.\n\t */\n\tprivate clearAllQueues(): { steering: string[]; followUp: string[] } {\n\t\tconst { steering, followUp } = this.session.clearQueue();\n\t\tconst compactionSteering = this.compactionQueuedMessages\n\t\t\t.filter((msg) => msg.mode === \"steer\")\n\t\t\t.map((msg) => msg.text);\n\t\tconst compactionFollowUp = this.compactionQueuedMessages\n\t\t\t.filter((msg) => msg.mode === \"followUp\")\n\t\t\t.map((msg) => msg.text);\n\t\tthis.compactionQueuedMessages = [];\n\t\treturn {\n\t\t\tsteering: [...steering, ...compactionSteering],\n\t\t\tfollowUp: [...followUp, ...compactionFollowUp],\n\t\t};\n\t}\n\n\tprivate updatePendingMessagesDisplay(): void {\n\t\tthis.pendingMessagesContainer.clear();\n\t\tconst { steering: steeringMessages, followUp: followUpMessages } = this.getAllQueuedMessages();\n\t\tif (steeringMessages.length > 0 || followUpMessages.length > 0) {\n\t\t\tthis.pendingMessagesContainer.addChild(new Spacer(1));\n\t\t\tfor (const message of steeringMessages) {\n\t\t\t\tconst text = theme.fg(\"dim\", `Steering: ${message}`);\n\t\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));\n\t\t\t}\n\t\t\tfor (const message of followUpMessages) {\n\t\t\t\tconst text = theme.fg(\"dim\", `Follow-up: ${message}`);\n\t\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));\n\t\t\t}\n\t\t\tconst dequeueHint = this.getAppKeyDisplay(\"app.message.dequeue\");\n\t\t\tconst hintText = theme.fg(\"dim\", `↳ ${dequeueHint} to edit all queued messages`);\n\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(hintText, 1, 0));\n\t\t}\n\t}\n\n\tprivate restoreQueuedMessagesToEditor(options?: { abort?: boolean; currentText?: string }): number {\n\t\tconst { steering, followUp } = this.clearAllQueues();\n\t\tconst allQueued = [...steering, ...followUp];\n\t\tif (allQueued.length === 0) {\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tif (options?.abort) {\n\t\t\t\tthis.agent.abort();\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\tconst queuedText = allQueued.join(\"\\n\\n\");\n\t\tconst currentText = options?.currentText ?? this.editor.getText();\n\t\tconst combinedText = [queuedText, currentText].filter((t) => t.trim()).join(\"\\n\\n\");\n\t\tthis.editor.setText(combinedText);\n\t\tthis.updatePendingMessagesDisplay();\n\t\tif (options?.abort) {\n\t\t\tthis.agent.abort();\n\t\t}\n\t\treturn allQueued.length;\n\t}\n\n\tprivate queueCompactionMessage(text: string, mode: \"steer\" | \"followUp\"): void {\n\t\tthis.compactionQueuedMessages.push({ text, mode });\n\t\tthis.editor.addToHistory?.(text);\n\t\tthis.editor.setText(\"\");\n\t\tthis.updatePendingMessagesDisplay();\n\t\tthis.showStatus(\"Queued message for after compaction\");\n\t}\n\n\tprivate isExtensionCommand(text: string): boolean {\n\t\tif (!text.startsWith(\"/\")) return false;\n\n\t\tconst extensionRunner = this.session.extensionRunner;\n\n\t\tconst spaceIndex = text.indexOf(\" \");\n\t\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\t\treturn !!extensionRunner.getCommand(commandName);\n\t}\n\n\tprivate async flushCompactionQueue(options?: { willRetry?: boolean }): Promise {\n\t\tif (this.compactionQueuedMessages.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst queuedMessages = [...this.compactionQueuedMessages];\n\t\tthis.compactionQueuedMessages = [];\n\t\tthis.updatePendingMessagesDisplay();\n\n\t\tconst restoreQueue = (error: unknown) => {\n\t\t\tthis.session.clearQueue();\n\t\t\tthis.compactionQueuedMessages = queuedMessages;\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tthis.showError(\n\t\t\t\t`Failed to send queued message${queuedMessages.length > 1 ? \"s\" : \"\"}: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t);\n\t\t};\n\n\t\ttry {\n\t\t\tif (options?.willRetry) {\n\t\t\t\t// When retry is pending, queue messages for the retry turn\n\t\t\t\tfor (const message of queuedMessages) {\n\t\t\t\t\tif (this.isExtensionCommand(message.text)) {\n\t\t\t\t\t\tawait this.session.prompt(message.text);\n\t\t\t\t\t} else if (message.mode === \"followUp\") {\n\t\t\t\t\t\tawait this.session.followUp(message.text);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.session.steer(message.text);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Find first non-extension-command message to use as prompt\n\t\t\tconst firstPromptIndex = queuedMessages.findIndex((message) => !this.isExtensionCommand(message.text));\n\t\t\tif (firstPromptIndex === -1) {\n\t\t\t\t// All extension commands - execute them all\n\t\t\t\tfor (const message of queuedMessages) {\n\t\t\t\t\tawait this.session.prompt(message.text);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Execute any extension commands before the first prompt\n\t\t\tconst preCommands = queuedMessages.slice(0, firstPromptIndex);\n\t\t\tconst firstPrompt = queuedMessages[firstPromptIndex];\n\t\t\tconst rest = queuedMessages.slice(firstPromptIndex + 1);\n\n\t\t\tfor (const message of preCommands) {\n\t\t\t\tawait this.session.prompt(message.text);\n\t\t\t}\n\n\t\t\t// Start a prompt when idle, or queue it into a run still finishing compaction.\n\t\t\tconst promptPromise = this.session\n\t\t\t\t.prompt(firstPrompt.text, { streamingBehavior: firstPrompt.mode })\n\t\t\t\t.catch((error) => {\n\t\t\t\t\trestoreQueue(error);\n\t\t\t\t});\n\n\t\t\t// Queue remaining messages\n\t\t\tfor (const message of rest) {\n\t\t\t\tif (this.isExtensionCommand(message.text)) {\n\t\t\t\t\tawait this.session.prompt(message.text);\n\t\t\t\t} else if (message.mode === \"followUp\") {\n\t\t\t\t\tawait this.session.followUp(message.text);\n\t\t\t\t} else {\n\t\t\t\t\tawait this.session.steer(message.text);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tvoid promptPromise;\n\t\t} catch (error) {\n\t\t\trestoreQueue(error);\n\t\t}\n\t}\n\n\t/** Move pending bash components from pending area to chat */\n\tprivate flushPendingBashComponents(): void {\n\t\tfor (const component of this.pendingBashComponents) {\n\t\t\tthis.pendingMessagesContainer.removeChild(component);\n\t\t\tthis.chatContainer.addChild(component);\n\t\t}\n\t\tthis.pendingBashComponents = [];\n\t}\n\n\t// =========================================================================\n\t// Selectors\n\t// =========================================================================\n\n\t/**\n\t * Shows a selector component in place of the editor.\n\t * @param create Factory that receives a `done` callback and returns the component and focus target\n\t */\n\tprivate showSelector(create: (done: () => void) => { component: Component; focus: Component }): void {\n\t\tconst done = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t};\n\t\tconst { component, focus } = create(done);\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(component);\n\t\tthis.ui.setFocus(focus);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate showSettingsSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new SettingsSelectorComponent(\n\t\t\t\t{\n\t\t\t\t\tautoCompact: this.session.autoCompactionEnabled,\n\t\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t\t\tautoResizeImages: this.settingsManager.getImageAutoResize(),\n\t\t\t\t\tblockImages: this.settingsManager.getBlockImages(),\n\t\t\t\t\tenableSkillCommands: this.settingsManager.getEnableSkillCommands(),\n\t\t\t\t\tsteeringMode: this.session.steeringMode,\n\t\t\t\t\tfollowUpMode: this.session.followUpMode,\n\t\t\t\t\ttransport: this.settingsManager.getTransport(),\n\t\t\t\t\thttpIdleTimeoutMs: this.settingsManager.getHttpIdleTimeoutMs(),\n\t\t\t\t\tthinkingLevel: this.session.thinkingLevel,\n\t\t\t\t\tavailableThinkingLevels: this.session.getAvailableThinkingLevels(),\n\t\t\t\t\tcurrentTheme: this.settingsManager.getThemeSetting() || \"dark\",\n\t\t\t\t\tterminalTheme: this.themeController.getTerminalTheme(),\n\t\t\t\t\tavailableThemes: getAvailableThemes(),\n\t\t\t\t\thideThinkingBlock: this.hideThinkingBlock,\n\t\t\t\t\tcollapseChangelog: this.settingsManager.getCollapseChangelog(),\n\t\t\t\t\tenableInstallTelemetry: this.settingsManager.getEnableInstallTelemetry(),\n\t\t\t\t\tdoubleEscapeAction: this.settingsManager.getDoubleEscapeAction(),\n\t\t\t\t\ttreeFilterMode: this.settingsManager.getTreeFilterMode(),\n\t\t\t\t\tshowHardwareCursor: this.settingsManager.getShowHardwareCursor(),\n\t\t\t\t\tshowCacheMissNotices: this.settingsManager.getShowCacheMissNotices(),\n\t\t\t\t\tdefaultProjectTrust: this.settingsManager.getDefaultProjectTrust(),\n\t\t\t\t\teditorPaddingX: this.settingsManager.getEditorPaddingX(),\n\t\t\t\t\toutputPad: this.settingsManager.getOutputPad(),\n\t\t\t\t\tautocompleteMaxVisible: this.settingsManager.getAutocompleteMaxVisible(),\n\t\t\t\t\tquietStartup: this.settingsManager.getQuietStartup(),\n\t\t\t\t\tclearOnShrink: this.settingsManager.getClearOnShrink(),\n\t\t\t\t\tshowTerminalProgress: this.settingsManager.getShowTerminalProgress(),\n\t\t\t\t\twarnings: this.settingsManager.getWarnings(),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tonAutoCompactChange: (enabled) => {\n\t\t\t\t\t\tthis.session.setAutoCompactionEnabled(enabled);\n\t\t\t\t\t\tthis.footer.setAutoCompactEnabled(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonShowImagesChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setShowImages(enabled);\n\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\tif (child instanceof ToolExecutionComponent) {\n\t\t\t\t\t\t\t\tchild.setShowImages(enabled);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonImageWidthCellsChange: (width) => {\n\t\t\t\t\t\tthis.settingsManager.setImageWidthCells(width);\n\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\tif (child instanceof ToolExecutionComponent) {\n\t\t\t\t\t\t\t\tchild.setImageWidthCells(width);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonAutoResizeImagesChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setImageAutoResize(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonBlockImagesChange: (blocked) => {\n\t\t\t\t\t\tthis.settingsManager.setBlockImages(blocked);\n\t\t\t\t\t},\n\t\t\t\t\tonEnableSkillCommandsChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setEnableSkillCommands(enabled);\n\t\t\t\t\t\tthis.setupAutocompleteProvider();\n\t\t\t\t\t},\n\t\t\t\t\tonSteeringModeChange: (mode) => {\n\t\t\t\t\t\tthis.session.setSteeringMode(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonFollowUpModeChange: (mode) => {\n\t\t\t\t\t\tthis.session.setFollowUpMode(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonTransportChange: (transport) => {\n\t\t\t\t\t\tthis.settingsManager.setTransport(transport);\n\t\t\t\t\t\tthis.session.agent.transport = transport;\n\t\t\t\t\t},\n\t\t\t\t\tonHttpIdleTimeoutMsChange: (timeoutMs) => {\n\t\t\t\t\t\tthis.settingsManager.setHttpIdleTimeoutMs(timeoutMs);\n\t\t\t\t\t\tconfigureHttpDispatcher(timeoutMs);\n\t\t\t\t\t\tthis.showStatus(`HTTP idle timeout: ${formatHttpIdleTimeoutMs(timeoutMs)}`);\n\t\t\t\t\t},\n\t\t\t\t\tonThinkingLevelChange: (level) => {\n\t\t\t\t\t\tthis.session.setThinkingLevel(level);\n\t\t\t\t\t\tthis.footer.invalidate();\n\t\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\t},\n\t\t\t\t\tonThemeChange: (themeSetting) => {\n\t\t\t\t\t\tthis.settingsManager.setTheme(themeSetting);\n\t\t\t\t\t\tvoid this.themeController.applyFromSettings();\n\t\t\t\t\t},\n\t\t\t\t\tonThemePreview: (themeName) => this.themeController.preview(themeName),\n\t\t\t\t\tonHideThinkingBlockChange: (hidden) => {\n\t\t\t\t\t\tthis.hideThinkingBlock = hidden;\n\t\t\t\t\t\tthis.settingsManager.setHideThinkingBlock(hidden);\n\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\tif (child instanceof AssistantMessageComponent) {\n\t\t\t\t\t\t\t\tchild.setHideThinkingBlock(hidden);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\t\t},\n\t\t\t\t\tonShowCacheMissNoticesChange: (shown) => {\n\t\t\t\t\t\tthis.settingsManager.setShowCacheMissNotices(shown);\n\t\t\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\t\t},\n\t\t\t\t\tonCollapseChangelogChange: (collapsed) => {\n\t\t\t\t\t\tthis.settingsManager.setCollapseChangelog(collapsed);\n\t\t\t\t\t},\n\t\t\t\t\tonEnableInstallTelemetryChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setEnableInstallTelemetry(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonQuietStartupChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setQuietStartup(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonDefaultProjectTrustChange: (defaultProjectTrust) => {\n\t\t\t\t\t\tthis.settingsManager.setDefaultProjectTrust(defaultProjectTrust);\n\t\t\t\t\t},\n\t\t\t\t\tonDoubleEscapeActionChange: (action) => {\n\t\t\t\t\t\tthis.settingsManager.setDoubleEscapeAction(action);\n\t\t\t\t\t},\n\t\t\t\t\tonTreeFilterModeChange: (mode) => {\n\t\t\t\t\t\tthis.settingsManager.setTreeFilterMode(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonShowHardwareCursorChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setShowHardwareCursor(enabled);\n\t\t\t\t\t\tthis.ui.setShowHardwareCursor(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonEditorPaddingXChange: (padding) => {\n\t\t\t\t\t\tthis.settingsManager.setEditorPaddingX(padding);\n\t\t\t\t\t\tthis.defaultEditor.setPaddingX(padding);\n\t\t\t\t\t\tif (this.editor !== this.defaultEditor && this.editor.setPaddingX !== undefined) {\n\t\t\t\t\t\t\tthis.editor.setPaddingX(padding);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonOutputPadChange: (padding) => {\n\t\t\t\t\t\tthis.settingsManager.setOutputPad(padding);\n\t\t\t\t\t\tthis.outputPad = padding;\n\t\t\t\t\t\tif (this.streamingComponent || this.session.isStreaming) {\n\t\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\tchild instanceof AssistantMessageComponent ||\n\t\t\t\t\t\t\t\t\tchild instanceof CustomMessageComponent ||\n\t\t\t\t\t\t\t\t\tchild instanceof UserMessageComponent\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tchild.setOutputPad(padding);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (this.streamingComponent) {\n\t\t\t\t\t\t\t\tthis.streamingComponent.setOutputPad(padding);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\t\t},\n\t\t\t\t\tonAutocompleteMaxVisibleChange: (maxVisible) => {\n\t\t\t\t\t\tthis.settingsManager.setAutocompleteMaxVisible(maxVisible);\n\t\t\t\t\t\tthis.defaultEditor.setAutocompleteMaxVisible(maxVisible);\n\t\t\t\t\t\tif (this.editor !== this.defaultEditor && this.editor.setAutocompleteMaxVisible !== undefined) {\n\t\t\t\t\t\t\tthis.editor.setAutocompleteMaxVisible(maxVisible);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonClearOnShrinkChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setClearOnShrink(enabled);\n\t\t\t\t\t\tthis.ui.setClearOnShrink(enabled);\n\t\t\t\t\t\tif (!enabled && !this.activeStatusIndicator) {\n\t\t\t\t\t\t\tthis.statusContainer.clear();\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonShowTerminalProgressChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setShowTerminalProgress(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonWarningsChange: (warnings) => {\n\t\t\t\t\t\tthis.settingsManager.setWarnings(warnings);\n\t\t\t\t\t},\n\t\t\t\t\tonCancel: () => {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getSettingsList() };\n\t\t});\n\t}\n\n\tprivate async handleModelCommand(searchTerm?: string): Promise {\n\t\tif (!searchTerm) {\n\t\t\tthis.showModelSelector();\n\t\t\treturn;\n\t\t}\n\n\t\tconst model = await this.findExactModelMatch(searchTerm);\n\t\tif (model) {\n\t\t\ttry {\n\t\t\t\tawait this.session.setModel(model);\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tthis.showStatus(`Model: ${model.id}`);\n\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(model);\n\t\t\t\tthis.checkDaxnutsEasterEgg(model);\n\t\t\t} catch (error) {\n\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showModelSelector(searchTerm);\n\t}\n\n\tprivate async findExactModelMatch(searchTerm: string): Promise | undefined> {\n\t\tconst models = await this.getModelCandidates();\n\t\treturn findExactModelReferenceMatch(searchTerm, models);\n\t}\n\n\tprivate async getModelCandidates(): Promise[]> {\n\t\tif (this.session.scopedModels.length > 0) {\n\t\t\treturn this.session.scopedModels.map((scoped) => scoped.model);\n\t\t}\n\n\t\ttry {\n\t\t\tawait this.session.modelRuntime.refresh();\n\t\t\treturn [...(await this.session.modelRuntime.getAvailable())];\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\t/** Update the footer's available provider count from the current snapshot without refreshing catalogs. */\n\tprivate updateAvailableProviderCount(): void {\n\t\tconst models =\n\t\t\tthis.session.scopedModels.length > 0\n\t\t\t\t? this.session.scopedModels.map((scoped) => scoped.model)\n\t\t\t\t: this.session.modelRuntime.getAvailableSnapshot();\n\t\tconst uniqueProviders = new Set(models.map((model) => model.provider));\n\t\tthis.footerDataProvider.setAvailableProviderCount(uniqueProviders.size);\n\t}\n\n\tprivate async maybeWarnAboutAnthropicSubscriptionAuth(\n\t\tmodel: Model | undefined = this.session.model,\n\t): Promise {\n\t\tif (this.settingsManager.getWarnings().anthropicExtraUsage === false) {\n\t\t\treturn;\n\t\t}\n\t\tif (this.anthropicSubscriptionWarningShown) {\n\t\t\treturn;\n\t\t}\n\t\tif (!model || model.provider !== \"anthropic\") {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tif ((await this.session.modelRuntime.checkAuth(\"anthropic\"))?.type === \"oauth\") {\n\t\t\t\tthis.anthropicSubscriptionWarningShown = true;\n\t\t\t\tthis.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst apiKey = (await this.session.modelRuntime.getAuth(model.provider))?.auth.apiKey;\n\t\t\tif (!isAnthropicSubscriptionAuthKey(apiKey)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.anthropicSubscriptionWarningShown = true;\n\t\t\tthis.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);\n\t\t} catch {\n\t\t\t// Ignore auth lookup failures for warning-only checks.\n\t\t}\n\t}\n\n\tprivate maybeSaveImplicitProjectTrustAfterReload(): boolean {\n\t\tconst cwd = this.sessionManager.getCwd();\n\t\tif (this.autoTrustOnReloadCwd !== cwd) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!this.settingsManager.isProjectTrusted() || !hasTrustRequiringProjectResources(cwd)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst trustStore = new ProjectTrustStore(this.runtimeHost.services.agentDir);\n\t\ttry {\n\t\t\tif (trustStore.get(cwd) !== null) {\n\t\t\t\tthis.autoTrustOnReloadCwd = undefined;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ttrustStore.set(cwd, true);\n\t\t\tthis.autoTrustOnReloadCwd = undefined;\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tthis.showWarning(\n\t\t\t\t`Could not save project trust after reload: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate showTrustSelector(): void {\n\t\tconst cwd = this.sessionManager.getCwd();\n\t\tconst trustStore = new ProjectTrustStore(this.runtimeHost.services.agentDir);\n\t\tconst savedDecision = trustStore.getEntry(cwd);\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new TrustSelectorComponent({\n\t\t\t\tcwd,\n\t\t\t\tsavedDecision,\n\t\t\t\tprojectTrusted: this.settingsManager.isProjectTrusted(),\n\t\t\t\tonSelect: (selection) => {\n\t\t\t\t\ttrustStore.setMany(selection.updates);\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showStatus(\n\t\t\t\t\t\t`Saved trust decision: ${selection.trusted ? \"trusted\" : \"untrusted\"}. Restart pi for this to take effect.`,\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tonCancel: () => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showModelSelector(initialSearchInput?: string): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ModelSelectorComponent(\n\t\t\t\tthis.ui,\n\t\t\t\tthis.session.model,\n\t\t\t\tthis.settingsManager,\n\t\t\t\tthis.session.modelRuntime,\n\t\t\t\tthis.session.scopedModels,\n\t\t\t\tasync (model) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.session.setModel(model);\n\t\t\t\t\t\tthis.footer.invalidate();\n\t\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.showStatus(`Model: ${model.id}`);\n\t\t\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(model);\n\t\t\t\t\t\tthis.checkDaxnutsEasterEgg(model);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tinitialSearchInput,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async showModelsSelector(): Promise {\n\t\t// Get all available models\n\t\tawait this.session.modelRuntime.refresh();\n\t\tconst allModels = [...(await this.session.modelRuntime.getAvailable())];\n\t\tconst allModelIds = new Set(allModels.map((model) => `${model.provider}/${model.id}`));\n\t\tconst configuredPatterns = this.settingsManager.getEnabledModels();\n\t\tconst sessionScopedModels = this.session.scopedModels;\n\n\t\tif (allModels.length === 0 && !configuredPatterns?.length && sessionScopedModels.length === 0) {\n\t\t\tthis.showStatus(\"No models available\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst configuredScope = configuredPatterns?.length\n\t\t\t? await resolveModelScopeWithDiagnostics(configuredPatterns, this.session.modelRuntime)\n\t\t\t: undefined;\n\n\t\t// Check if session has scoped models (from previous session-only changes or CLI --models)\n\t\tconst hasSessionScope = sessionScopedModels.length > 0;\n\n\t\t// Build enabled model IDs from session state or settings\n\t\tlet currentEnabledIds: string[] | null = null;\n\n\t\tif (hasSessionScope) {\n\t\t\t// Use current session's scoped models\n\t\t\tcurrentEnabledIds = sessionScopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);\n\t\t} else if (configuredScope) {\n\t\t\tcurrentEnabledIds = configuredScope.scopedModels.map(\n\t\t\t\t(scoped) => `${scoped.model.provider}/${scoped.model.id}`,\n\t\t\t);\n\t\t}\n\n\t\tfor (const diagnostic of configuredScope?.diagnostics ?? []) {\n\t\t\tif (diagnostic.code !== \"no-match\") continue;\n\t\t\tcurrentEnabledIds ??= [];\n\t\t\tif (!currentEnabledIds.includes(diagnostic.pattern)) currentEnabledIds.push(diagnostic.pattern);\n\t\t}\n\n\t\t// Helper to update session's scoped models (session-only, no persist)\n\t\tconst updateSessionModels = async (enabledIds: string[] | null) => {\n\t\t\tcurrentEnabledIds = enabledIds === null ? null : [...enabledIds];\n\t\t\tconst hasEnabledAvailableModel = enabledIds?.some((id) => allModelIds.has(id)) ?? false;\n\t\t\tconst allAvailableModelsEnabled =\n\t\t\t\tenabledIds !== null && [...allModelIds].every((id) => enabledIds.includes(id));\n\t\t\tif (enabledIds && hasEnabledAvailableModel && !allAvailableModelsEnabled) {\n\t\t\t\tconst newScopedModels = await resolveModelScope(enabledIds, this.session.modelRuntime);\n\t\t\t\tthis.session.setScopedModels(\n\t\t\t\t\tnewScopedModels.map((sm) => ({\n\t\t\t\t\t\tmodel: sm.model,\n\t\t\t\t\t\tthinkingLevel: sm.thinkingLevel,\n\t\t\t\t\t})),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// All enabled or none enabled = no filter\n\t\t\t\tthis.session.setScopedModels([]);\n\t\t\t}\n\t\t\tawait this.updateAvailableProviderCount();\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ScopedModelsSelectorComponent(\n\t\t\t\t{\n\t\t\t\t\tallModels,\n\t\t\t\t\tenabledModelIds: currentEnabledIds,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tonChange: async (enabledIds) => {\n\t\t\t\t\t\tawait updateSessionModels(enabledIds);\n\t\t\t\t\t},\n\t\t\t\t\tonPersist: (enabledIds) => {\n\t\t\t\t\t\t// Persist to settings\n\t\t\t\t\t\tconst allEnabled =\n\t\t\t\t\t\t\tenabledIds !== null &&\n\t\t\t\t\t\t\tenabledIds.length === allModels.length &&\n\t\t\t\t\t\t\tenabledIds.every((id) => allModelIds.has(id));\n\t\t\t\t\t\tconst newPatterns = enabledIds === null || allEnabled ? undefined : enabledIds;\n\t\t\t\t\t\tthis.settingsManager.setEnabledModels(newPatterns ? [...newPatterns] : undefined);\n\t\t\t\t\t\tthis.showStatus(\"Model selection saved to settings\");\n\t\t\t\t\t},\n\t\t\t\t\tonCancel: () => {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showUserMessageSelector(): void {\n\t\tconst userMessages = this.session.getUserMessagesForForking();\n\n\t\tif (userMessages.length === 0) {\n\t\t\tthis.showStatus(\"No messages to fork from\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst initialSelectedId = userMessages[userMessages.length - 1]?.entryId;\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new UserMessageSelectorComponent(\n\t\t\t\tuserMessages.map((m) => ({ id: m.entryId, text: m.text })),\n\t\t\t\tasync (entryId) => {\n\t\t\t\t\tdone();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.runtimeHost.fork(entryId);\n\t\t\t\t\t\tif (result.cancelled) {\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis.editor.setText(result.selectedText ?? \"\");\n\t\t\t\t\t\tthis.showStatus(\"Forked to new session\");\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tinitialSelectedId,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getMessageList() };\n\t\t});\n\t}\n\n\tprivate async handleCloneCommand(): Promise {\n\t\tconst leafId = this.sessionManager.getLeafId();\n\t\tif (!leafId) {\n\t\t\tthis.showStatus(\"Nothing to clone yet\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.fork(leafId, { position: \"at\" });\n\t\t\tif (result.cancelled) {\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.editor.setText(\"\");\n\t\t\tthis.showStatus(\"Cloned to new session\");\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate showTreeSelector(initialSelectedId?: string): void {\n\t\tconst tree = this.sessionManager.getTree();\n\t\tconst realLeafId = this.sessionManager.getLeafId();\n\t\tconst initialFilterMode = this.settingsManager.getTreeFilterMode();\n\n\t\tif (tree.length === 0) {\n\t\t\tthis.showStatus(\"No entries in session\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new TreeSelectorComponent(\n\t\t\t\ttree,\n\t\t\t\trealLeafId,\n\t\t\t\tthis.ui.terminal.rows,\n\t\t\t\tasync (entryId) => {\n\t\t\t\t\t// Selecting the current leaf is a no-op (already there)\n\t\t\t\t\tif (entryId === this.sessionManager.getLeafId()) {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.showStatus(\"Already at this point\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Ask about summarization\n\t\t\t\t\tdone(); // Close selector first\n\n\t\t\t\t\t// Loop until user makes a complete choice or cancels to tree\n\t\t\t\t\tlet wantsSummary = false;\n\t\t\t\t\tlet customInstructions: string | undefined;\n\n\t\t\t\t\t// Check if we should skip the prompt (user preference to always default to no summary)\n\t\t\t\t\tif (!this.settingsManager.getBranchSummarySkipPrompt()) {\n\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\tconst summaryChoice = await this.showExtensionSelector(\"Summarize branch?\", [\n\t\t\t\t\t\t\t\t\"No summary\",\n\t\t\t\t\t\t\t\t\"Summarize\",\n\t\t\t\t\t\t\t\t\"Summarize with custom prompt\",\n\t\t\t\t\t\t\t]);\n\n\t\t\t\t\t\t\tif (summaryChoice === undefined) {\n\t\t\t\t\t\t\t\t// User pressed escape - re-show tree selector with same selection\n\t\t\t\t\t\t\t\tthis.showTreeSelector(entryId);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\twantsSummary = summaryChoice !== \"No summary\";\n\n\t\t\t\t\t\t\tif (summaryChoice === \"Summarize with custom prompt\") {\n\t\t\t\t\t\t\t\tcustomInstructions = await this.showExtensionEditor(\"Custom summarization instructions\");\n\t\t\t\t\t\t\t\tif (customInstructions === undefined) {\n\t\t\t\t\t\t\t\t\t// User cancelled - loop back to summary selector\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// User made a complete choice\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// The user committed to navigating: stop the active response first.\n\t\t\t\t\tif (this.session.isStreaming) {\n\t\t\t\t\t\tthis.restoreQueuedMessagesToEditor();\n\t\t\t\t\t\tawait this.session.abort();\n\t\t\t\t\t}\n\n\t\t\t\t\t// Set up escape handler and status indicator if summarizing\n\t\t\t\t\tlet showingSummaryIndicator = false;\n\t\t\t\t\tconst originalOnEscape = this.defaultEditor.onEscape;\n\n\t\t\t\t\tif (wantsSummary) {\n\t\t\t\t\t\tthis.defaultEditor.onEscape = () => {\n\t\t\t\t\t\t\tthis.session.abortBranchSummary();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\tthis.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui));\n\t\t\t\t\t\tshowingSummaryIndicator = true;\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.session.navigateTree(entryId, {\n\t\t\t\t\t\t\tsummarize: wantsSummary,\n\t\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (result.aborted) {\n\t\t\t\t\t\t\t// Summarization aborted - re-show tree selector with same selection\n\t\t\t\t\t\t\tthis.showStatus(\"Branch summarization cancelled\");\n\t\t\t\t\t\t\tthis.showTreeSelector(entryId);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.cancelled) {\n\t\t\t\t\t\t\tthis.showStatus(\"Navigation cancelled\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Update UI\n\t\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\t\tthis.renderInitialMessages();\n\t\t\t\t\t\tif (result.editorText && !this.editor.getText().trim()) {\n\t\t\t\t\t\t\tthis.editor.setText(result.editorText);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.showStatus(\"Navigated to selected point\");\n\t\t\t\t\t\tvoid this.flushCompactionQueue({ willRetry: false });\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (showingSummaryIndicator) {\n\t\t\t\t\t\t\tthis.clearStatusIndicator(\"branchSummary\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.defaultEditor.onEscape = originalOnEscape;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\t(entryId, label) => {\n\t\t\t\t\tthis.sessionManager.appendLabelChange(entryId, label);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tinitialSelectedId,\n\t\t\t\tinitialFilterMode,\n\t\t\t);\n\t\t\tselector.onCopy = async (text) => {\n\t\t\t\tif (!text) {\n\t\t\t\t\tthis.showError(\"Selected entry has no text to copy\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait copyToClipboard(text);\n\t\t\t\t\tthis.showStatus(\"Copied selected message to clipboard\");\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t};\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showSessionSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new SessionSelectorComponent(\n\t\t\t\t(onProgress) =>\n\t\t\t\t\tSessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir(), onProgress),\n\t\t\t\t(onProgress) =>\n\t\t\t\t\tthis.sessionManager.usesDefaultSessionDir()\n\t\t\t\t\t\t? SessionManager.listAll(onProgress)\n\t\t\t\t\t\t: SessionManager.listAll(this.sessionManager.getSessionDir(), onProgress),\n\t\t\t\tasync (sessionPath) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tawait this.handleResumeSession(sessionPath);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tvoid this.shutdown();\n\t\t\t\t},\n\t\t\t\t() => this.ui.requestRender(),\n\t\t\t\t{\n\t\t\t\t\trenameSession: async (sessionFilePath: string, nextName: string | undefined) => {\n\t\t\t\t\t\tconst next = (nextName ?? \"\").trim();\n\t\t\t\t\t\tif (!next) return;\n\t\t\t\t\t\tconst mgr = SessionManager.open(sessionFilePath);\n\t\t\t\t\t\tmgr.appendSessionInfo(next);\n\t\t\t\t\t},\n\t\t\t\t\tshowRenameHint: true,\n\t\t\t\t\tkeybindings: this.keybindings,\n\t\t\t\t},\n\n\t\t\t\tthis.sessionManager.getSessionFile(),\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async handleResumeSession(\n\t\tsessionPath: string,\n\t\toptions?: Parameters[1],\n\t): Promise<{ cancelled: boolean }> {\n\t\tthis.clearStatusIndicator();\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.switchSession(sessionPath, {\n\t\t\t\twithSession: options?.withSession,\n\t\t\t\tprojectTrustContextFactory: (cwd) => this.createProjectTrustContext(cwd),\n\t\t\t});\n\t\t\tif (result.cancelled) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthis.showStatus(\"Resumed session\");\n\t\t\treturn result;\n\t\t} catch (error: unknown) {\n\t\t\tif (error instanceof MissingSessionCwdError) {\n\t\t\t\tconst selectedCwd = await this.promptForMissingSessionCwd(error);\n\t\t\t\tif (!selectedCwd) {\n\t\t\t\t\tthis.showStatus(\"Resume cancelled\");\n\t\t\t\t\treturn { cancelled: true };\n\t\t\t\t}\n\t\t\t\tconst result = await this.runtimeHost.switchSession(sessionPath, {\n\t\t\t\t\tcwdOverride: selectedCwd,\n\t\t\t\t\twithSession: options?.withSession,\n\t\t\t\t\tprojectTrustContextFactory: (cwd) => this.createProjectTrustContext(cwd),\n\t\t\t\t});\n\t\t\t\tif (result.cancelled) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\tthis.showStatus(\"Resumed session in current cwd\");\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\treturn this.handleFatalRuntimeError(\"Failed to resume session\", error);\n\t\t}\n\t}\n\n\tprivate getLoginProviderOptions(authType?: \"oauth\" | \"api_key\"): AuthSelectorProvider[] {\n\t\tconst options: AuthSelectorProvider[] = [];\n\t\tfor (const provider of this.session.modelRuntime.getProviders()) {\n\t\t\tconst authStatus = this.session.modelRuntime.getProviderAuthStatus(provider.id);\n\t\t\tconst status = authStatus.configured\n\t\t\t\t? {\n\t\t\t\t\t\ttype: this.session.modelRuntime.isUsingOAuth(provider.id) ? (\"oauth\" as const) : (\"api_key\" as const),\n\t\t\t\t\t\tsource: authStatus.label ?? authStatus.source,\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\t\tif ((!authType || authType === \"oauth\") && provider.auth.oauth) {\n\t\t\t\toptions.push({\n\t\t\t\t\tid: provider.id,\n\t\t\t\t\tname: provider.name,\n\t\t\t\t\tauthType: \"oauth\",\n\t\t\t\t\tmethod: provider.auth.oauth,\n\t\t\t\t\tstatus,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif ((!authType || authType === \"api_key\") && provider.auth.apiKey) {\n\t\t\t\toptions.push({\n\t\t\t\t\tid: provider.id,\n\t\t\t\t\tname: provider.name,\n\t\t\t\t\tauthType: \"api_key\",\n\t\t\t\t\tmethod: provider.auth.apiKey,\n\t\t\t\t\tstatus,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn options.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tprivate async getLogoutProviderOptions(): Promise {\n\t\treturn (await this.session.modelRuntime.listCredentials())\n\t\t\t.map(({ providerId, type }) => ({\n\t\t\t\tid: providerId,\n\t\t\t\tname: this.session.modelRuntime.getProvider(providerId)?.name ?? providerId,\n\t\t\t\tauthType: type,\n\t\t\t\tstatus: { type, source: \"stored credential\" },\n\t\t\t}))\n\t\t\t.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tprivate findLoginProviderOptions(providerRef: string): AuthSelectorProvider[] {\n\t\tconst normalizedProviderRef = providerRef.trim().toLowerCase();\n\t\tif (!normalizedProviderRef) {\n\t\t\treturn [];\n\t\t}\n\n\t\treturn this.getLoginProviderOptions().filter(\n\t\t\t(provider) =>\n\t\t\t\tprovider.id.toLowerCase() === normalizedProviderRef ||\n\t\t\t\tprovider.name.toLowerCase() === normalizedProviderRef,\n\t\t);\n\t}\n\n\tprivate async handleLoginCommand(providerRef?: string): Promise {\n\t\tawait this.session.modelRuntime.getAvailable();\n\t\tif (!providerRef) {\n\t\t\tthis.showLoginAuthTypeSelector();\n\t\t\treturn;\n\t\t}\n\n\t\tconst providerOptions = this.findLoginProviderOptions(providerRef);\n\t\tif (providerOptions.length === 1) {\n\t\t\tawait this.startProviderLogin(providerOptions[0]!);\n\t\t\treturn;\n\t\t}\n\n\t\tif (providerOptions.length > 1) {\n\t\t\tconst providerIds = new Set(providerOptions.map((provider) => provider.id));\n\t\t\tif (providerIds.size === 1) {\n\t\t\t\tthis.showLoginAuthTypeSelector(providerOptions);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.showLoginProviderSelector(undefined, providerRef);\n\t}\n\n\tprivate async startProviderLogin(providerOption: AuthSelectorProvider): Promise {\n\t\tif (providerOption.authType === \"oauth\") {\n\t\t\tawait this.showLoginDialog(providerOption.id, providerOption.name);\n\t\t} else if (providerOption.method?.login) {\n\t\t\tawait this.showApiKeyLoginDialog(providerOption.id, providerOption.name);\n\t\t} else {\n\t\t\tthis.showAmbientAuthDialog(providerOption);\n\t\t}\n\t}\n\n\tprivate showLoginAuthTypeSelector(providerOptions?: AuthSelectorProvider[]): void {\n\t\tconst oauthProvider = providerOptions?.find((provider) => provider.authType === \"oauth\");\n\t\tconst oauthLoginLabel =\n\t\t\toauthProvider?.method && \"loginLabel\" in oauthProvider.method ? oauthProvider.method.loginLabel : undefined;\n\t\tconst subscriptionLabel = oauthLoginLabel ?? \"Sign in with an account\";\n\t\tconst apiKeyLabel = \"Sign in with an API key\";\n\t\tconst availableAuthTypes = providerOptions\n\t\t\t? new Set(providerOptions.map((provider) => provider.authType))\n\t\t\t: new Set([\"oauth\", \"api_key\"]);\n\t\tconst options: string[] = [];\n\t\tif (availableAuthTypes.has(\"oauth\")) {\n\t\t\toptions.push(subscriptionLabel);\n\t\t}\n\t\tif (availableAuthTypes.has(\"api_key\")) {\n\t\t\toptions.push(apiKeyLabel);\n\t\t}\n\n\t\tif (options.length === 0) {\n\t\t\tthis.showStatus(\"No login methods available.\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (providerOptions && options.length === 1) {\n\t\t\tconst providerOption = providerOptions[0];\n\t\t\tif (providerOption) {\n\t\t\t\tvoid this.startProviderLogin(providerOption);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst title = providerOptions?.[0]\n\t\t\t? `Select authentication method for ${providerOptions[0].name}:`\n\t\t\t: \"Select authentication method:\";\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\t\ttitle,\n\t\t\t\toptions,\n\t\t\t\t(option) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tconst authType = option === subscriptionLabel ? \"oauth\" : \"api_key\";\n\t\t\t\t\tif (providerOptions) {\n\t\t\t\t\t\tconst providerOption = providerOptions.find((provider) => provider.authType === authType);\n\t\t\t\t\t\tif (providerOption) {\n\t\t\t\t\t\t\tvoid this.startProviderLogin(providerOption);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthis.showLoginProviderSelector(authType);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showLoginProviderSelector(authType?: AuthSelectorProvider[\"authType\"], initialSearchInput?: string): void {\n\t\tconst providerOptions = this.getLoginProviderOptions(authType);\n\t\tif (providerOptions.length === 0) {\n\t\t\tconst message =\n\t\t\t\tauthType === \"oauth\"\n\t\t\t\t\t? \"No subscription providers available.\"\n\t\t\t\t\t: authType === \"api_key\"\n\t\t\t\t\t\t? \"No API key providers available.\"\n\t\t\t\t\t\t: \"No login providers available.\";\n\t\t\tthis.showStatus(message);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new OAuthSelectorComponent(\n\t\t\t\t\"login\",\n\t\t\t\tproviderOptions,\n\t\t\t\tasync (providerId, selectedAuthType) => {\n\t\t\t\t\tdone();\n\n\t\t\t\t\tconst providerOption = providerOptions.find(\n\t\t\t\t\t\t(provider) => provider.id === providerId && provider.authType === selectedAuthType,\n\t\t\t\t\t);\n\t\t\t\t\tif (!providerOption) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tawait this.startProviderLogin(providerOption);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tif (authType) {\n\t\t\t\t\t\tthis.showLoginAuthTypeSelector();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tinitialSearchInput,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async showOAuthSelector(mode: \"login\" | \"logout\"): Promise {\n\t\tif (mode === \"login\") {\n\t\t\tthis.showLoginAuthTypeSelector();\n\t\t\treturn;\n\t\t}\n\n\t\tconst providerOptions = await this.getLogoutProviderOptions();\n\t\tif (providerOptions.length === 0) {\n\t\t\tthis.showStatus(\n\t\t\t\t\"No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new OAuthSelectorComponent(\n\t\t\t\tmode,\n\t\t\t\tproviderOptions,\n\t\t\t\tasync (providerId: string) => {\n\t\t\t\t\tdone();\n\n\t\t\t\t\tconst providerOption = providerOptions.find((provider) => provider.id === providerId);\n\t\t\t\t\tif (!providerOption) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.session.modelRuntime.logout(providerOption.id);\n\t\t\t\t\t\tawait this.updateAvailableProviderCount();\n\t\t\t\t\t\tconst message =\n\t\t\t\t\t\t\tproviderOption.authType === \"oauth\"\n\t\t\t\t\t\t\t\t? `Logged out of ${providerOption.name}`\n\t\t\t\t\t\t\t\t: `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;\n\t\t\t\t\t\tthis.showStatus(message);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tthis.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async completeProviderAuthentication(\n\t\tproviderId: string,\n\t\tproviderName: string,\n\t\tauthType: \"oauth\" | \"api_key\",\n\t\tpreviousModel: Model | undefined,\n\t): Promise {\n\t\tawait this.session.modelRuntime.getAvailable();\n\n\t\tconst actionLabel = authType === \"oauth\" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;\n\n\t\tlet selectedModel: Model | undefined;\n\t\tlet selectionError: string | undefined;\n\t\tif (isUnknownModel(previousModel)) {\n\t\t\tconst availableModels = await this.session.modelRuntime.getAvailable();\n\t\t\tconst providerModels = availableModels.filter((model) => model.provider === providerId);\n\t\t\tif (!hasDefaultModelProvider(providerId)) {\n\t\t\t\tselectionError = `${actionLabel}, but no default model is configured for provider \"${providerId}\". Use /model to select a model.`;\n\t\t\t} else if (providerModels.length === 0) {\n\t\t\t\tselectionError = `${actionLabel}, but no models are available for that provider. Use /model to select a model.`;\n\t\t\t} else {\n\t\t\t\tconst defaultModelId = defaultModelPerProvider[providerId];\n\t\t\t\tselectedModel = providerModels.find((model) => model.id === defaultModelId);\n\t\t\t\tif (!selectedModel) {\n\t\t\t\t\tselectionError = `${actionLabel}, but its default model \"${defaultModelId}\" is not available. Use /model to select a model.`;\n\t\t\t\t} else {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.session.setModel(selectedModel);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tselectedModel = undefined;\n\t\t\t\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tselectionError = `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tawait this.updateAvailableProviderCount();\n\t\tthis.footer.invalidate();\n\t\tthis.updateEditorBorderColor();\n\t\tif (selectedModel) {\n\t\t\tthis.showStatus(`${actionLabel}. Selected ${selectedModel.id}. Credentials saved to ${getAuthPath()}`);\n\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel);\n\t\t\tthis.checkDaxnutsEasterEgg(selectedModel);\n\t\t} else {\n\t\t\tthis.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`);\n\t\t\tif (selectionError) {\n\t\t\t\tthis.showError(selectionError);\n\t\t\t} else {\n\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate showAmbientAuthDialog(providerOption: AuthSelectorProvider): void {\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui,\n\t\t\tproviderOption.id,\n\t\t\t() => restoreEditor(),\n\t\t\tproviderOption.name,\n\t\t\t`${providerOption.name} setup`,\n\t\t);\n\t\tdialog.showInfo(`${providerOption.method?.name ?? \"Authentication\"} is configured outside pi.`, [], true);\n\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(dialog);\n\t\tthis.ui.setFocus(dialog);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async showApiKeyLoginDialog(providerId: string, providerName: string): Promise {\n\t\tconst previousModel = this.session.model;\n\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui,\n\t\t\tproviderId,\n\t\t\t(_success, _message) => {\n\t\t\t\t// Completion handled below\n\t\t\t},\n\t\t\tproviderName,\n\t\t);\n\n\t\tif (providerId === \"amazon-bedrock\") {\n\t\t\tdialog.showDetails([\n\t\t\t\ttheme.fg(\"text\", \"You can also use an AWS profile, IAM keys, or role-based credentials.\"),\n\t\t\t\ttheme.fg(\"muted\", \"See:\"),\n\t\t\t\ttheme.fg(\"accent\", ` ${path.join(getDocsPath(), \"providers.md\")}`),\n\t\t\t]);\n\t\t}\n\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(dialog);\n\t\tthis.ui.setFocus(dialog);\n\t\tthis.ui.requestRender();\n\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\ttry {\n\t\t\tawait this.loginProvider(dialog, providerId, \"api_key\");\n\t\t\trestoreEditor();\n\t\t\tawait this.completeProviderAuthentication(providerId, providerName, \"api_key\", previousModel);\n\t\t} catch (error: unknown) {\n\t\t\trestoreEditor();\n\t\t\tconst errorMsg = error instanceof Error ? error.message : String(error);\n\t\t\tif (errorMsg !== \"Login cancelled\") {\n\t\t\t\tthis.showError(`Failed to save API key for ${providerName}: ${errorMsg}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate showAuthSelect(\n\t\tdialog: LoginDialogComponent,\n\t\tprompt: Extract,\n\t): Promise {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst restoreDialog = () => {\n\t\t\t\tthis.editorContainer.clear();\n\t\t\t\tthis.editorContainer.addChild(dialog);\n\t\t\t\tthis.ui.setFocus(dialog);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t};\n\t\t\tconst labels = prompt.options.map((option) => option.label);\n\t\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\t\tprompt.message,\n\t\t\t\tlabels,\n\t\t\t\t(optionLabel) => {\n\t\t\t\t\trestoreDialog();\n\t\t\t\t\tconst id = prompt.options.find((option) => option.label === optionLabel)?.id;\n\t\t\t\t\tif (id) resolve(id);\n\t\t\t\t\telse reject(new Error(\"Login cancelled\"));\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\trestoreDialog();\n\t\t\t\t\treject(new Error(\"Login cancelled\"));\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(selector);\n\t\t\tthis.ui.setFocus(selector);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\tprivate async showAuthPrompt(dialog: LoginDialogComponent, prompt: AuthPrompt): Promise {\n\t\tlet response: Promise;\n\t\tif (prompt.type === \"select\") {\n\t\t\tresponse = this.showAuthSelect(dialog, prompt);\n\t\t} else if (prompt.type === \"manual_code\") {\n\t\t\tresponse = dialog.showManualInput(prompt.message);\n\t\t} else {\n\t\t\tresponse = dialog.showPrompt(prompt.message, prompt.placeholder);\n\t\t}\n\t\tif (!prompt.signal) return response;\n\t\tif (prompt.signal.aborted) throw new Error(\"Login cancelled\");\n\t\tconst signal = prompt.signal;\n\t\tlet onAbort: (() => void) | undefined;\n\t\tconst aborted = new Promise((_resolve, reject) => {\n\t\t\tonAbort = () => reject(new Error(\"Login cancelled\"));\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t});\n\t\ttry {\n\t\t\treturn await Promise.race([response, aborted]);\n\t\t} finally {\n\t\t\tif (onAbort) signal.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t}\n\n\tprivate notifyAuthDialog(dialog: LoginDialogComponent, event: AuthEvent): void {\n\t\tif (event.type === \"auth_url\") {\n\t\t\tdialog.showAuth(event.url, event.instructions);\n\t\t} else if (event.type === \"device_code\") {\n\t\t\tdialog.showDeviceCode(event);\n\t\t\tdialog.showWaiting(\"Waiting for authentication...\");\n\t\t} else if (event.type === \"info\") {\n\t\t\tdialog.showInfo(event.message, event.links);\n\t\t} else {\n\t\t\tdialog.showProgress(event.message);\n\t\t}\n\t}\n\n\tprivate async loginProvider(\n\t\tdialog: LoginDialogComponent,\n\t\tproviderId: string,\n\t\tmethod: \"api_key\" | \"oauth\",\n\t): Promise {\n\t\tawait this.session.modelRuntime.login(providerId, method, {\n\t\t\tsignal: dialog.signal,\n\t\t\tprompt: (prompt) => this.showAuthPrompt(dialog, prompt),\n\t\t\tnotify: (event) => this.notifyAuthDialog(dialog, event),\n\t\t});\n\t}\n\n\tprivate async showLoginDialog(providerId: string, providerName: string): Promise {\n\t\tconst previousModel = this.session.model;\n\t\tconst dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => {}, providerName);\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(dialog);\n\t\tthis.ui.setFocus(dialog);\n\t\tthis.ui.requestRender();\n\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\ttry {\n\t\t\tawait this.loginProvider(dialog, providerId, \"oauth\");\n\t\t\trestoreEditor();\n\t\t\tawait this.completeProviderAuthentication(providerId, providerName, \"oauth\", previousModel);\n\t\t} catch (error: unknown) {\n\t\t\trestoreEditor();\n\t\t\tconst errorMsg = error instanceof Error ? error.message : String(error);\n\t\t\tif (errorMsg !== \"Login cancelled\") {\n\t\t\t\tthis.showError(`Failed to login to ${providerName}: ${errorMsg}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Command handlers\n\t// =========================================================================\n\n\tprivate async handleReloadCommand(): Promise {\n\t\tif (this.session.isStreaming) {\n\t\t\tthis.showWarning(\"Wait for the current response to finish before reloading.\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.session.isCompacting) {\n\t\t\tthis.showWarning(\"Wait for compaction to finish before reloading.\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.resetExtensionUI();\n\n\t\tconst reloadBox = new Container();\n\t\tconst borderColor = (s: string) => theme.fg(\"border\", s);\n\t\treloadBox.addChild(new DynamicBorder(borderColor));\n\t\treloadBox.addChild(new Spacer(1));\n\t\treloadBox.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.fg(\"muted\", \"Reloading keybindings, extensions, skills, prompts, themes, and context files...\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\treloadBox.addChild(new Spacer(1));\n\t\treloadBox.addChild(new DynamicBorder(borderColor));\n\n\t\tconst previousEditor = this.editor;\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(reloadBox);\n\t\tthis.ui.setFocus(reloadBox);\n\t\tthis.ui.requestRender(true);\n\t\tawait new Promise((resolve) => process.nextTick(resolve));\n\n\t\tconst dismissReloadBox = (editor: Component) => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(editor);\n\t\t\tthis.ui.setFocus(editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\tlet chatRestoredBeforeSessionStart = false;\n\t\tlet reloadBoxDismissed = false;\n\t\tconst restoreChatBeforeSessionStart = () => {\n\t\t\tif (chatRestoredBeforeSessionStart) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\t\t\tthis.rebuildChatFromMessages();\n\t\t\tchatRestoredBeforeSessionStart = true;\n\t\t};\n\n\t\ttry {\n\t\t\tawait this.session.reload({ beforeSessionStart: restoreChatBeforeSessionStart });\n\t\t\trestoreChatBeforeSessionStart();\n\t\t\tconfigureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs());\n\t\t\tthis.keybindings.reload();\n\t\t\tconst activeHeader = this.customHeader ?? this.builtInHeader;\n\t\t\tif (isExpandable(activeHeader)) {\n\t\t\t\tactiveHeader.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\t\tawait this.themeController.applyFromSettings();\n\t\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\t\tthis.defaultEditor.setPaddingX(editorPaddingX);\n\t\t\tthis.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);\n\t\t\tif (this.editor !== this.defaultEditor) {\n\t\t\t\tthis.editor.setPaddingX?.(editorPaddingX);\n\t\t\t\tthis.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);\n\t\t\t}\n\t\t\tthis.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());\n\t\t\tconst clearOnShrink = this.settingsManager.getClearOnShrink();\n\t\t\tthis.ui.setClearOnShrink(clearOnShrink);\n\t\t\tif (!clearOnShrink && !this.activeStatusIndicator) {\n\t\t\t\tthis.statusContainer.clear();\n\t\t\t}\n\t\t\tthis.setupAutocompleteProvider();\n\t\t\tconst runner = this.session.extensionRunner;\n\t\t\tthis.setupExtensionShortcuts(runner);\n\t\t\tthis.showLoadedResources({\n\t\t\t\tforce: false,\n\t\t\t\tshowDiagnosticsWhenQuiet: true,\n\t\t\t});\n\t\t\tconst savedImplicitProjectTrust = this.maybeSaveImplicitProjectTrustAfterReload();\n\t\t\tconst modelsJsonError = this.session.modelRuntime.getError();\n\t\t\tif (modelsJsonError) {\n\t\t\t\tthis.showError(`models.json error: ${modelsJsonError}`);\n\t\t\t}\n\t\t\tthis.showStatus(\n\t\t\t\tsavedImplicitProjectTrust\n\t\t\t\t\t? \"Reloaded keybindings, extensions, skills, prompts, themes, and context files; saved project trust\"\n\t\t\t\t\t: \"Reloaded keybindings, extensions, skills, prompts, themes, and context files\",\n\t\t\t);\n\t\t\tdismissReloadBox(this.editor as Component);\n\t\t\treloadBoxDismissed = true;\n\t\t} catch (error) {\n\t\t\tif (!reloadBoxDismissed) {\n\t\t\t\tdismissReloadBox(previousEditor as Component);\n\t\t\t}\n\t\t\tthis.showError(`Reload failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\n\tprivate async handleExportCommand(text: string): Promise {\n\t\tconst outputPath = this.getPathCommandArgument(text, \"/export\");\n\n\t\ttry {\n\t\t\tif (outputPath?.endsWith(\".jsonl\")) {\n\t\t\t\tconst filePath = this.session.exportToJsonl(outputPath);\n\t\t\t\tthis.showStatus(`Session exported to: ${filePath}`);\n\t\t\t} else {\n\t\t\t\tconst filePath = await this.session.exportToHtml(outputPath);\n\t\t\t\tthis.showStatus(`Session exported to: ${filePath}`);\n\t\t\t}\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(`Failed to export session: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t}\n\t}\n\n\tprivate getPathCommandArgument(text: string, command: \"/export\" | \"/import\"): string | undefined {\n\t\tif (text === command) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!text.startsWith(`${command} `)) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst argsString = text.slice(command.length + 1).trimStart();\n\t\tif (!argsString) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst firstChar = argsString[0];\n\t\tif (firstChar === '\"' || firstChar === \"'\") {\n\t\t\tconst closingQuoteIndex = argsString.indexOf(firstChar, 1);\n\t\t\tif (closingQuoteIndex < 0) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn argsString.slice(1, closingQuoteIndex);\n\t\t}\n\n\t\tconst firstWhitespaceIndex = argsString.search(/\\s/);\n\t\tif (firstWhitespaceIndex < 0) {\n\t\t\treturn argsString;\n\t\t}\n\t\treturn argsString.slice(0, firstWhitespaceIndex);\n\t}\n\n\tprivate async handleImportCommand(text: string): Promise {\n\t\tconst inputPath = this.getPathCommandArgument(text, \"/import\");\n\t\tif (!inputPath) {\n\t\t\tthis.showError(\"Usage: /import \");\n\t\t\treturn;\n\t\t}\n\n\t\tconst confirmed = await this.showExtensionConfirm(\"Import session\", `Replace current session with ${inputPath}?`);\n\t\tif (!confirmed) {\n\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.clearStatusIndicator();\n\t\t\tconst result = await this.runtimeHost.importFromJsonl(inputPath);\n\t\t\tif (result.cancelled) {\n\t\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.showStatus(`Session imported from: ${inputPath}`);\n\t\t} catch (error: unknown) {\n\t\t\tif (error instanceof MissingSessionCwdError) {\n\t\t\t\tconst selectedCwd = await this.promptForMissingSessionCwd(error);\n\t\t\t\tif (!selectedCwd) {\n\t\t\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst result = await this.runtimeHost.importFromJsonl(inputPath, selectedCwd);\n\t\t\t\tif (result.cancelled) {\n\t\t\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.showStatus(`Session imported from: ${inputPath}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (error instanceof SessionImportFileNotFoundError) {\n\t\t\t\tthis.showError(`Failed to import session: ${error.message}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.handleFatalRuntimeError(\"Failed to import session\", error);\n\t\t}\n\t}\n\n\tprivate async handleShareCommand(): Promise {\n\t\t// Check if gh is available and logged in\n\t\ttry {\n\t\t\tconst authResult = spawnSync(\"gh\", [\"auth\", \"status\"], { encoding: \"utf-8\" });\n\t\t\tif (authResult.status !== 0) {\n\t\t\t\tthis.showError(\"GitHub CLI is not logged in. Run 'gh auth login' first.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.showError(\"GitHub CLI (gh) is not installed. Install it from https://cli.github.com/\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Export to a temp file\n\t\tconst tmpFile = path.join(os.tmpdir(), \"session.html\");\n\t\ttry {\n\t\t\tawait this.session.exportToHtml(tmpFile);\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(`Failed to export session: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Show cancellable loader, replacing the editor\n\t\tconst loader = new BorderedLoader(this.ui, theme, \"Creating gist...\");\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(loader);\n\t\tthis.ui.setFocus(loader);\n\t\tthis.ui.requestRender();\n\n\t\tconst restoreEditor = () => {\n\t\t\tloader.dispose();\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\ttry {\n\t\t\t\tfs.unlinkSync(tmpFile);\n\t\t\t} catch {\n\t\t\t\t// Ignore cleanup errors\n\t\t\t}\n\t\t};\n\n\t\t// Create a secret gist asynchronously\n\t\tlet proc: ReturnType | null = null;\n\n\t\tloader.onAbort = () => {\n\t\t\tproc?.kill();\n\t\t\trestoreEditor();\n\t\t\tthis.showStatus(\"Share cancelled\");\n\t\t};\n\n\t\ttry {\n\t\t\tconst result = await new Promise<{ stdout: string; stderr: string; code: number | null }>((resolve) => {\n\t\t\t\tproc = spawn(\"gh\", [\"gist\", \"create\", \"--public=false\", tmpFile]);\n\t\t\t\tlet stdout = \"\";\n\t\t\t\tlet stderr = \"\";\n\t\t\t\tproc.stdout?.on(\"data\", (data) => {\n\t\t\t\t\tstdout += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.stderr?.on(\"data\", (data) => {\n\t\t\t\t\tstderr += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.on(\"close\", (code) => resolve({ stdout, stderr, code }));\n\t\t\t});\n\n\t\t\tif (loader.signal.aborted) return;\n\n\t\t\trestoreEditor();\n\n\t\t\tif (result.code !== 0) {\n\t\t\t\tconst errorMsg = result.stderr?.trim() || \"Unknown error\";\n\t\t\t\tthis.showError(`Failed to create gist: ${errorMsg}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Extract gist ID from the URL returned by gh\n\t\t\t// gh returns something like: https://gist.github.com/username/GIST_ID\n\t\t\tconst gistUrl = result.stdout?.trim();\n\t\t\tconst gistId = gistUrl?.split(\"/\").pop();\n\t\t\tif (!gistId) {\n\t\t\t\tthis.showError(\"Failed to parse gist ID from gh output\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Create the preview URL\n\t\t\tconst previewUrl = getShareViewerUrl(gistId);\n\t\t\tthis.showStatus(`Share URL: ${previewUrl}\\nGist: ${gistUrl}`);\n\t\t} catch (error: unknown) {\n\t\t\tif (!loader.signal.aborted) {\n\t\t\t\trestoreEditor();\n\t\t\t\tthis.showError(`Failed to create gist: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async handleCopyCommand(): Promise {\n\t\tconst text = this.session.getLastAssistantText();\n\t\tif (!text) {\n\t\t\tthis.showError(\"No agent messages to copy yet.\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tawait copyToClipboard(text);\n\t\t\tthis.showStatus(\"Copied last agent message to clipboard\");\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate handleNameCommand(text: string): void {\n\t\tconst name = text.replace(/^\\/name\\s*/, \"\").trim();\n\t\tif (!name) {\n\t\t\tconst currentName = this.sessionManager.getSessionName();\n\t\t\tif (currentName) {\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"dim\", `Session name: ${currentName}`), 1, 0));\n\t\t\t} else {\n\t\t\t\tthis.showWarning(\"Usage: /name \");\n\t\t\t}\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.session.setSessionName(name);\n\t\tconst sessionName = this.sessionManager.getSessionName();\n\t\tif (sessionName !== name) {\n\t\t\tthis.showWarning(`Session name was normalized from ${JSON.stringify(name)} to ${JSON.stringify(sessionName)}`);\n\t\t}\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"dim\", `Session name set: ${sessionName ?? name}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleSessionCommand(): void {\n\t\tconst stats = this.session.getSessionStats();\n\t\tconst sessionName = this.sessionManager.getSessionName();\n\t\tconst entries = this.sessionManager.getEntries();\n\t\tconst cacheWaste = computeCacheWaste(entries, this.session.modelRuntime);\n\n\t\t// Cost/token totals per provider/model actually used (e.g. OpenRouter `auto`\n\t\t// resolves to a concrete responseModel). Usage without model attribution is\n\t\t// grouped separately so the breakdown reconciles with the session total.\n\t\tconst usageBreakdown = getUsageCostBreakdown(entries);\n\n\t\tlet info = `${theme.bold(\"Session Info\")}\\n\\n`;\n\t\tif (sessionName) {\n\t\t\tinfo += `${theme.fg(\"dim\", \"Name:\")} ${sessionName}\\n`;\n\t\t}\n\t\tinfo += `${theme.fg(\"dim\", \"File:\")} ${stats.sessionFile ?? \"In-memory\"}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"ID:\")} ${stats.sessionId}\\n\\n`;\n\t\tinfo += `${theme.bold(\"Messages\")}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.totalMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"User:\")} ${stats.userMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Assistant:\")} ${stats.assistantMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Tools:\")} ${stats.toolCalls} calls, ${stats.toolResults} results\\n\\n`;\n\t\tinfo += `${theme.bold(\"Tokens\")}\\n`;\n\t\t// \"Input\" is the full prompt volume. With cache activity, split it into\n\t\t// cached (served from cache) vs uncached (everything else) - the only\n\t\t// provider-independent split. Cache writes, where reported, are a detail\n\t\t// of the uncached portion.\n\t\tconst { input, cacheRead, cacheWrite } = stats.tokens;\n\t\tconst promptTokens = input + cacheRead + cacheWrite;\n\t\tinfo += `${theme.fg(\"dim\", \"Input:\")} ${promptTokens.toLocaleString()}\\n`;\n\t\tif (promptTokens > 0 && (cacheRead > 0 || cacheWrite > 0)) {\n\t\t\tconst hitRate = theme.fg(\"dim\", `(${((cacheRead / promptTokens) * 100).toFixed(1)}%)`);\n\t\t\tinfo += ` ${theme.fg(\"dim\", \"Cached:\")} ${cacheRead.toLocaleString()} ${hitRate}\\n`;\n\t\t\tconst written =\n\t\t\t\tcacheWrite > 0 ? ` ${theme.fg(\"dim\", `(${cacheWrite.toLocaleString()} written to cache)`)}` : \"\";\n\t\t\tinfo += ` ${theme.fg(\"dim\", \"Uncached:\")} ${(input + cacheWrite).toLocaleString()}${written}\\n`;\n\t\t}\n\t\tinfo += `${theme.fg(\"dim\", \"Output:\")} ${stats.tokens.output.toLocaleString()}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.tokens.total.toLocaleString()}\\n`;\n\n\t\tif (stats.cost > 0 || cacheWaste.missedTokens > 0) {\n\t\t\tinfo += `\\n${theme.bold(\"Cost\")}\\n`;\n\t\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} $${stats.cost.toFixed(3)}`;\n\t\t\tif (usageBreakdown.length > 1) {\n\t\t\t\tfor (const entry of usageBreakdown) {\n\t\t\t\t\tinfo += `\\n ${theme.fg(\"dim\", `${entry.key}:`)} $${entry.cost.toFixed(3)} ${theme.fg(\"dim\", `(${formatTokens(entry.tokens)} tokens)`)}`;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (cacheWaste.missedTokens > 0) {\n\t\t\t\tconst missLabel = cacheWaste.missCount === 1 ? \"1 miss\" : `${cacheWaste.missCount} misses`;\n\t\t\t\tconst detail = `${cacheWaste.missedTokens.toLocaleString()} tokens, ${missLabel}`;\n\t\t\t\tinfo +=\n\t\t\t\t\tcacheWaste.missedCost >= 0.0001\n\t\t\t\t\t\t? `\\n${theme.fg(\"dim\", \"Cache Re-billed:\")} $${cacheWaste.missedCost.toFixed(3)} ${theme.fg(\"dim\", `(${detail})`)}`\n\t\t\t\t\t\t: `\\n${theme.fg(\"dim\", \"Cache Re-billed:\")} ${detail}`;\n\t\t\t}\n\t\t}\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(info, 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleChangelogCommand(): void {\n\t\tconst changelogPath = getChangelogPath();\n\t\tconst allEntries = parseChangelog(changelogPath);\n\n\t\tconst changelogMarkdown =\n\t\t\tallEntries.length > 0\n\t\t\t\t? allEntries\n\t\t\t\t\t\t.reverse()\n\t\t\t\t\t\t.map((e) => normalizeChangelogLinks(e.content, e))\n\t\t\t\t\t\t.join(\"\\n\\n\")\n\t\t\t\t: \"No changelog entries found.\";\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, this.getMarkdownThemeWithSettings()));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Get capitalized display string for an app keybinding action.\n\t */\n\tprivate getAppKeyDisplay(action: AppKeybinding): string {\n\t\treturn keyDisplayText(action);\n\t}\n\n\t/**\n\t * Get capitalized display string for an editor keybinding action.\n\t */\n\tprivate getEditorKeyDisplay(action: Keybinding): string {\n\t\treturn keyDisplayText(action);\n\t}\n\n\tprivate handleHotkeysCommand(): void {\n\t\t// Navigation keybindings\n\t\tconst cursorUp = this.getEditorKeyDisplay(\"tui.editor.cursorUp\");\n\t\tconst cursorDown = this.getEditorKeyDisplay(\"tui.editor.cursorDown\");\n\t\tconst cursorLeft = this.getEditorKeyDisplay(\"tui.editor.cursorLeft\");\n\t\tconst cursorRight = this.getEditorKeyDisplay(\"tui.editor.cursorRight\");\n\t\tconst cursorWordLeft = this.getEditorKeyDisplay(\"tui.editor.cursorWordLeft\");\n\t\tconst cursorWordRight = this.getEditorKeyDisplay(\"tui.editor.cursorWordRight\");\n\t\tconst cursorLineStart = this.getEditorKeyDisplay(\"tui.editor.cursorLineStart\");\n\t\tconst cursorLineEnd = this.getEditorKeyDisplay(\"tui.editor.cursorLineEnd\");\n\t\tconst jumpForward = this.getEditorKeyDisplay(\"tui.editor.jumpForward\");\n\t\tconst jumpBackward = this.getEditorKeyDisplay(\"tui.editor.jumpBackward\");\n\t\tconst pageUp = this.getEditorKeyDisplay(\"tui.editor.pageUp\");\n\t\tconst pageDown = this.getEditorKeyDisplay(\"tui.editor.pageDown\");\n\n\t\t// Editing keybindings\n\t\tconst submit = this.getEditorKeyDisplay(\"tui.input.submit\");\n\t\tconst newLine = this.getEditorKeyDisplay(\"tui.input.newLine\");\n\t\tconst deleteWordBackward = this.getEditorKeyDisplay(\"tui.editor.deleteWordBackward\");\n\t\tconst deleteWordForward = this.getEditorKeyDisplay(\"tui.editor.deleteWordForward\");\n\t\tconst deleteToLineStart = this.getEditorKeyDisplay(\"tui.editor.deleteToLineStart\");\n\t\tconst deleteToLineEnd = this.getEditorKeyDisplay(\"tui.editor.deleteToLineEnd\");\n\t\tconst yank = this.getEditorKeyDisplay(\"tui.editor.yank\");\n\t\tconst yankPop = this.getEditorKeyDisplay(\"tui.editor.yankPop\");\n\t\tconst undo = this.getEditorKeyDisplay(\"tui.editor.undo\");\n\t\tconst tab = this.getEditorKeyDisplay(\"tui.input.tab\");\n\n\t\t// App keybindings\n\t\tconst interrupt = this.getAppKeyDisplay(\"app.interrupt\");\n\t\tconst clear = this.getAppKeyDisplay(\"app.clear\");\n\t\tconst exit = this.getAppKeyDisplay(\"app.exit\");\n\t\tconst suspend = this.getAppKeyDisplay(\"app.suspend\");\n\t\tconst cycleThinkingLevel = this.getAppKeyDisplay(\"app.thinking.cycle\");\n\t\tconst cycleModelForward = this.getAppKeyDisplay(\"app.model.cycleForward\");\n\t\tconst selectModel = this.getAppKeyDisplay(\"app.model.select\");\n\t\tconst expandTools = this.getAppKeyDisplay(\"app.tools.expand\");\n\t\tconst toggleThinking = this.getAppKeyDisplay(\"app.thinking.toggle\");\n\t\tconst externalEditor = this.getAppKeyDisplay(\"app.editor.external\");\n\t\tconst cycleModelBackward = this.getAppKeyDisplay(\"app.model.cycleBackward\");\n\t\tconst copyMessage = this.getAppKeyDisplay(\"app.message.copy\");\n\t\tconst followUp = this.getAppKeyDisplay(\"app.message.followUp\");\n\t\tconst dequeue = this.getAppKeyDisplay(\"app.message.dequeue\");\n\t\tconst pasteImage = this.getAppKeyDisplay(\"app.clipboard.pasteImage\");\n\n\t\tlet hotkeys = `\n**Navigation**\n| Key | Action |\n|-----|--------|\n| \\`${cursorUp}\\` / \\`${cursorDown}\\` / \\`${cursorLeft}\\` / \\`${cursorRight}\\` | Move cursor / browse history |\n| \\`${cursorWordLeft}\\` / \\`${cursorWordRight}\\` | Move by word |\n| \\`${cursorLineStart}\\` | Start of line |\n| \\`${cursorLineEnd}\\` | End of line |\n| \\`${jumpForward}\\` | Jump forward to character |\n| \\`${jumpBackward}\\` | Jump backward to character |\n| \\`${pageUp}\\` / \\`${pageDown}\\` | Scroll by page |\n\n**Editing**\n| Key | Action |\n|-----|--------|\n| \\`${submit}\\` | Send message |\n| \\`${newLine}\\` | New line${process.platform === \"win32\" ? \" (Ctrl+Enter on Windows Terminal)\" : \"\"} |\n| \\`${deleteWordBackward}\\` | Delete word backwards |\n| \\`${deleteWordForward}\\` | Delete word forwards |\n| \\`${deleteToLineStart}\\` | Delete to start of line |\n| \\`${deleteToLineEnd}\\` | Delete to end of line |\n| \\`${yank}\\` | Paste the most-recently-deleted text |\n| \\`${yankPop}\\` | Cycle through the deleted text after pasting |\n| \\`${undo}\\` | Undo |\n\n**Other**\n| Key | Action |\n|-----|--------|\n| \\`${tab}\\` | Path completion / accept autocomplete |\n| \\`${interrupt}\\` | Cancel autocomplete / abort streaming |\n| \\`${clear}\\` | Clear editor (first) / exit (second) |\n| \\`${exit}\\` | Exit (when editor is empty) |\n| \\`${suspend}\\` | Suspend to background |\n| \\`${cycleThinkingLevel}\\` | Cycle thinking level |\n| \\`${cycleModelForward}\\` / \\`${cycleModelBackward}\\` | Cycle models |\n| \\`${selectModel}\\` | Open model selector |\n| \\`${expandTools}\\` | Toggle tool output expansion |\n| \\`${toggleThinking}\\` | Toggle thinking block visibility |\n| \\`${externalEditor}\\` | Edit message in external editor |\n| \\`${copyMessage}\\` | Copy last assistant message |\n| \\`${followUp}\\` | Queue follow-up message |\n| \\`${dequeue}\\` | Restore queued messages |\n| \\`${pasteImage}\\` | Paste image or text from clipboard |\n| \\`/\\` | Slash commands |\n| \\`!\\` | Run bash command |\n| \\`!!\\` | Run bash command (excluded from context) |\n`;\n\n\t\t// Add extension-registered shortcuts\n\t\tconst extensionRunner = this.session.extensionRunner;\n\t\tconst shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());\n\t\tif (shortcuts.size > 0) {\n\t\t\thotkeys += `\n**Extensions**\n| Key | Action |\n|-----|--------|\n`;\n\t\t\tfor (const [key, shortcut] of shortcuts) {\n\t\t\t\tconst description = shortcut.description ?? shortcut.extensionPath;\n\t\t\t\tconst keyDisplay = formatKeyText(key, { capitalize: true });\n\t\t\t\thotkeys += `| \\`${keyDisplay}\\` | ${description} |\\n`;\n\t\t\t}\n\t\t}\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"Keyboard Shortcuts\")), 1, 0));\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Markdown(hotkeys.trim(), 1, 1, this.getMarkdownThemeWithSettings()));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleClearCommand(): Promise {\n\t\tthis.clearStatusIndicator();\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.newSession();\n\t\t\tif (result.cancelled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(new Text(`${theme.fg(\"accent\", \"✓ New session started\")}`, 1, 1));\n\t\t\tthis.ui.requestRender();\n\t\t} catch (error: unknown) {\n\t\t\tawait this.handleFatalRuntimeError(\"Failed to create session\", error);\n\t\t}\n\t}\n\n\tprivate handleDebugCommand(): void {\n\t\tconst width = this.ui.terminal.columns;\n\t\tconst height = this.ui.terminal.rows;\n\t\tconst allLines = this.ui.render(width);\n\n\t\tconst debugLogPath = getDebugLogPath();\n\t\tconst debugData = [\n\t\t\t`Debug output at ${new Date().toISOString()}`,\n\t\t\t`Terminal: ${width}x${height}`,\n\t\t\t`Total lines: ${allLines.length}`,\n\t\t\t\"\",\n\t\t\t\"=== All rendered lines with visible widths ===\",\n\t\t\t...allLines.map((line, idx) => {\n\t\t\t\tconst vw = visibleWidth(line);\n\t\t\t\tconst escaped = JSON.stringify(line);\n\t\t\t\treturn `[${idx}] (w=${vw}) ${escaped}`;\n\t\t\t}),\n\t\t\t\"\",\n\t\t\t\"=== Agent messages (JSONL) ===\",\n\t\t\t...this.session.messages.map((msg) => JSON.stringify(msg)),\n\t\t\t\"\",\n\t\t].join(\"\\n\");\n\n\t\tfs.mkdirSync(path.dirname(debugLogPath), { recursive: true });\n\t\tfs.writeFileSync(debugLogPath, debugData);\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(`${theme.fg(\"accent\", \"✓ Debug log written\")}\\n${theme.fg(\"muted\", debugLogPath)}`, 1, 1),\n\t\t);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleArminSaysHi(): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new ArminComponent(this.ui));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleDementedDelves(): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new EarendilAnnouncementComponent());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleDaxnuts(): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DaxnutsComponent(this.ui));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate checkDaxnutsEasterEgg(model: { provider: string; id: string }): void {\n\t\tif (model.provider === \"opencode\" && model.id.toLowerCase().includes(\"kimi-k2.5\")) {\n\t\t\tthis.handleDaxnuts();\n\t\t}\n\t}\n\n\tprivate async handleBashCommand(command: string, excludeFromContext = false): Promise {\n\t\tconst extensionRunner = this.session.extensionRunner;\n\n\t\t// Emit user_bash event to let extensions intercept\n\t\tconst eventResult = await extensionRunner.emitUserBash({\n\t\t\ttype: \"user_bash\",\n\t\t\tcommand,\n\t\t\texcludeFromContext,\n\t\t\tcwd: this.sessionManager.getCwd(),\n\t\t});\n\n\t\t// If extension returned a full result, use it directly\n\t\tif (eventResult?.result) {\n\t\t\tconst result = eventResult.result;\n\n\t\t\t// Create UI component for display\n\t\t\tthis.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);\n\t\t\tif (this.session.isStreaming) {\n\t\t\t\tthis.pendingMessagesContainer.addChild(this.bashComponent);\n\t\t\t\tthis.pendingBashComponents.push(this.bashComponent);\n\t\t\t} else {\n\t\t\t\tthis.chatContainer.addChild(this.bashComponent);\n\t\t\t}\n\n\t\t\t// Show output and complete\n\t\t\tif (result.output) {\n\t\t\t\tthis.bashComponent.appendOutput(result.output);\n\t\t\t}\n\t\t\tthis.bashComponent.setComplete(\n\t\t\t\tresult.exitCode,\n\t\t\t\tresult.cancelled,\n\t\t\t\tresult.truncated ? ({ truncated: true, content: result.output } as TruncationResult) : undefined,\n\t\t\t\tresult.fullOutputPath,\n\t\t\t);\n\n\t\t\t// Record the result in session\n\t\t\tthis.session.recordBashResult(command, result, { excludeFromContext });\n\t\t\tthis.bashComponent = undefined;\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\t// Normal execution path (possibly with custom operations)\n\t\tconst isDeferred = this.session.isStreaming;\n\t\tthis.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);\n\n\t\tif (isDeferred) {\n\t\t\t// Show in pending area when agent is streaming\n\t\t\tthis.pendingMessagesContainer.addChild(this.bashComponent);\n\t\t\tthis.pendingBashComponents.push(this.bashComponent);\n\t\t} else {\n\t\t\t// Show in chat immediately when agent is idle\n\t\t\tthis.chatContainer.addChild(this.bashComponent);\n\t\t}\n\t\tthis.ui.requestRender();\n\n\t\ttry {\n\t\t\tconst result = await this.session.executeBash(\n\t\t\t\tcommand,\n\t\t\t\t(chunk) => {\n\t\t\t\t\tif (this.bashComponent) {\n\t\t\t\t\t\tthis.bashComponent.appendOutput(chunk);\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ excludeFromContext, operations: eventResult?.operations },\n\t\t\t);\n\n\t\t\tif (this.bashComponent) {\n\t\t\t\tthis.bashComponent.setComplete(\n\t\t\t\t\tresult.exitCode,\n\t\t\t\t\tresult.cancelled,\n\t\t\t\t\tresult.truncated ? ({ truncated: true, content: result.output } as TruncationResult) : undefined,\n\t\t\t\t\tresult.fullOutputPath,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (this.bashComponent) {\n\t\t\t\tthis.bashComponent.setComplete(undefined, false);\n\t\t\t}\n\t\t\tthis.showError(`Bash command failed: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t}\n\n\t\tthis.bashComponent = undefined;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleCompactCommand(customInstructions?: string): Promise {\n\t\tthis.clearStatusIndicator();\n\n\t\ttry {\n\t\t\tawait this.session.compact(customInstructions);\n\t\t} catch {\n\t\t\t// Ignore, will be emitted as an event\n\t\t}\n\t}\n\n\tstop(): void {\n\t\tif (this.settingsManager.getShowTerminalProgress()) {\n\t\t\tthis.ui.terminal.setProgress(false);\n\t\t}\n\t\tthis.clearStatusIndicator();\n\t\tthis.themeController.disableAutoSync();\n\t\tthis.clearExtensionTerminalInputListeners();\n\t\tthis.footer.dispose();\n\t\tthis.footerDataProvider.dispose();\n\t\tif (this.unsubscribe) {\n\t\t\tthis.unsubscribe();\n\t\t}\n\t\tif (this.isInitialized) {\n\t\t\tthis.ui.stop();\n\t\t\tthis.isInitialized = false;\n\t\t}\n\t\tthis.unregisterSignalHandlers();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/interactive-mode.js b/dist/modes/interactive/interactive-mode.js new file mode 100644 index 0000000..462e240 --- /dev/null +++ b/dist/modes/interactive/interactive-mode.js @@ -0,0 +1,5071 @@ +/** + * Interactive mode for the coding agent. + * Handles TUI rendering and user interaction, delegating business logic to AgentSession. + */ +import * as crypto from "node:crypto"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { CombinedAutocompleteProvider, Container, fuzzyFilter, getCapabilities, hyperlink, Markdown, matchesKey, ProcessTerminal, Spacer, setKeybindings, Text, TruncatedText, TUI, visibleWidth, } from "@earendil-works/pi-tui"; +import chalk from "chalk"; +import { spawn, spawnSync } from "child_process"; +import { APP_NAME, APP_TITLE, CONFIG_DIR_NAME, getAgentDir, getAuthPath, getDebugLogPath, getDocsPath, getShareViewerUrl, VERSION, } from "../../config.js"; +import { parseSkillBlock } from "../../core/agent-session.js"; +import { SessionImportFileNotFoundError } from "../../core/agent-session-runtime.js"; +import { CACHE_TTL_MS, collectCacheMisses, computeCacheWaste, detectCacheMiss, } from "../../core/cache-stats.js"; +import { FooterDataProvider } from "../../core/footer-data-provider.js"; +import { configureHttpDispatcher, formatHttpIdleTimeoutMs } from "../../core/http-dispatcher.js"; +import { KeybindingsManager } from "../../core/keybindings.js"; +import { createCompactionSummaryMessage } from "../../core/messages.js"; +import { defaultModelPerProvider, findExactModelReferenceMatch, resolveModelScope, resolveModelScopeWithDiagnostics, } from "../../core/model-resolver.js"; +import { DefaultPackageManager } from "../../core/package-manager.js"; +import { formatMissingSessionCwdPrompt, MissingSessionCwdError } from "../../core/session-cwd.js"; +import { SessionManager, sessionEntryToContextMessages } from "../../core/session-manager.js"; +import { BUILTIN_SLASH_COMMANDS } from "../../core/slash-commands.js"; +import { isInstallTelemetryEnabled } from "../../core/telemetry.js"; +import { hasTrustRequiringProjectResources, ProjectTrustStore } from "../../core/trust-manager.js"; +import { getUsageCostBreakdown } from "../../core/usage-totals.js"; +import { getChangelogPath, getNewEntries, normalizeChangelogLinks, parseChangelog } from "../../utils/changelog.js"; +import { copyToClipboard, readClipboardText } from "../../utils/clipboard.js"; +import { extensionForImageMimeType, readClipboardImage } from "../../utils/clipboard-image.js"; +import { parseGitUrl } from "../../utils/git.js"; +import { getCwdRelativePath } from "../../utils/paths.js"; +import { getPiUserAgent } from "../../utils/pi-user-agent.js"; +import { killTrackedDetachedChildren } from "../../utils/shell.js"; +import { ensureTool } from "../../utils/tools-manager.js"; +import { checkForNewPiVersion } from "../../utils/version-check.js"; +import { ArminComponent } from "./components/armin.js"; +import { AssistantMessageComponent } from "./components/assistant-message.js"; +import { BashExecutionComponent } from "./components/bash-execution.js"; +import { BorderedLoader } from "./components/bordered-loader.js"; +import { BranchSummaryMessageComponent } from "./components/branch-summary-message.js"; +import { CompactionSummaryMessageComponent } from "./components/compaction-summary-message.js"; +import { CustomEditor } from "./components/custom-editor.js"; +import { CustomEntryComponent } from "./components/custom-entry.js"; +import { CustomMessageComponent } from "./components/custom-message.js"; +import { DaxnutsComponent } from "./components/daxnuts.js"; +import { DynamicBorder } from "./components/dynamic-border.js"; +import { EarendilAnnouncementComponent } from "./components/earendil-announcement.js"; +import { ExtensionEditorComponent } from "./components/extension-editor.js"; +import { ExtensionInputComponent } from "./components/extension-input.js"; +import { ExtensionSelectorComponent } from "./components/extension-selector.js"; +import { FooterComponent, formatTokens } from "./components/footer.js"; +import { formatKeyText, keyDisplayText, keyHint, keyText, rawKeyHint } from "./components/keybinding-hints.js"; +import { LoginDialogComponent } from "./components/login-dialog.js"; +import { ModelSelectorComponent } from "./components/model-selector.js"; +import { formatAuthSelectorProviderType, OAuthSelectorComponent, } from "./components/oauth-selector.js"; +import { ScopedModelsSelectorComponent } from "./components/scoped-models-selector.js"; +import { SessionSelectorComponent } from "./components/session-selector.js"; +import { SettingsSelectorComponent } from "./components/settings-selector.js"; +import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js"; +import { BranchSummaryStatusIndicator, CompactionStatusIndicator, IdleStatus, RetryStatusIndicator, WorkingStatusIndicator, } from "./components/status-indicator.js"; +import { ToolExecutionComponent } from "./components/tool-execution.js"; +import { TreeSelectorComponent } from "./components/tree-selector.js"; +import { TrustSelectorComponent } from "./components/trust-selector.js"; +import { UserMessageComponent } from "./components/user-message.js"; +import { UserMessageSelectorComponent } from "./components/user-message-selector.js"; +import { editInExternalEditor } from "./external-editor.js"; +import { getModelSearchText } from "./model-search.js"; +import { getAvailableThemes, getAvailableThemesWithPaths, getEditorTheme, getMarkdownTheme, getThemeByName, onThemeChange, setRegisteredThemes, stopThemeWatcher, Theme, theme, } from "./theme/theme.js"; +import { InteractiveThemeController } from "./theme/theme-controller.js"; +function isExpandable(obj) { + return typeof obj === "object" && obj !== null && "setExpanded" in obj && typeof obj.setExpanded === "function"; +} +class ExpandableText extends Text { + getCollapsedText; + getExpandedText; + constructor(getCollapsedText, getExpandedText, expanded = false, paddingX = 0, paddingY = 0) { + super(expanded ? getExpandedText() : getCollapsedText(), paddingX, paddingY); + this.getCollapsedText = getCollapsedText; + this.getExpandedText = getExpandedText; + } + setExpanded(expanded) { + this.setText(expanded ? this.getExpandedText() : this.getCollapsedText()); + } +} +function isCustomSessionEntry(item) { + return "type" in item && item.type === "custom"; +} +const DEAD_TERMINAL_ERROR_CODES = new Set(["EIO", "EPIPE", "ENOTCONN"]); +function isDeadTerminalError(error) { + if (!error || typeof error !== "object" || !("code" in error)) { + return false; + } + const code = error.code; + return code !== undefined && DEAD_TERMINAL_ERROR_CODES.has(code); +} +const ANTHROPIC_SUBSCRIPTION_AUTH_WARNING = "Anthropic subscription auth is active. Third-party harness usage draws from extra usage and is billed per token, not your Claude plan limits. Manage extra usage at https://claude.ai/settings/usage. Disable this warning in /settings."; +function isAnthropicSubscriptionAuthKey(apiKey) { + return typeof apiKey === "string" && apiKey.startsWith("sk-ant-oat"); +} +function isUnknownModel(model) { + return !!model && model.provider === "unknown" && model.id === "unknown" && model.api === "unknown"; +} +function quoteIfNeeded(value) { + if (value.length > 0 && !/[^a-zA-Z0-9_\-./~:@]/.test(value)) { + return value; + } + return `'${value.replace(/'/g, `'\\''`)}'`; +} +export function formatResumeCommand(sessionManager) { + if (!process.stdout.isTTY) + return undefined; + if (!sessionManager.isPersisted()) + return undefined; + const sessionFile = sessionManager.getSessionFile(); + if (!sessionFile || !fs.existsSync(sessionFile)) + return undefined; + const args = [APP_NAME]; + if (!sessionManager.usesDefaultSessionDir()) { + args.push("--session-dir", quoteIfNeeded(sessionManager.getSessionDir())); + } + args.push("--session", sessionManager.getSessionId()); + return args.join(" "); +} +function hasDefaultModelProvider(providerId) { + return providerId in defaultModelPerProvider; +} +const AUTH_TYPE_ORDER = { oauth: 0, api_key: 1 }; +function createFuzzyAutocompleteItems(items, prefix, getSearchText, toAutocompleteItem) { + const filtered = fuzzyFilter(items, prefix, getSearchText); + if (filtered.length === 0) + return null; + return filtered.map(toAutocompleteItem); +} +function getLoginProviderCompletionOptions(providerOptions) { + const byId = new Map(); + for (const provider of providerOptions) { + const existing = byId.get(provider.id); + if (existing) { + if (!existing.authTypes.includes(provider.authType)) { + existing.authTypes.push(provider.authType); + existing.authTypes.sort((a, b) => AUTH_TYPE_ORDER[a] - AUTH_TYPE_ORDER[b]); + } + continue; + } + byId.set(provider.id, { + id: provider.id, + name: provider.name, + authTypes: [provider.authType], + }); + } + return Array.from(byId.values()).sort((a, b) => a.name.localeCompare(b.name)); +} +function getLoginProviderSearchText(provider) { + const authTypes = provider.authTypes + .map((authType) => `${authType} ${formatAuthSelectorProviderType(authType)}`) + .join(" "); + return `${provider.id} ${provider.name} ${authTypes}`; +} +function formatLoginProviderCompletionDescription(provider) { + const authTypes = provider.authTypes.map(formatAuthSelectorProviderType).join("/"); + return provider.name === provider.id ? authTypes : `${provider.name} · ${authTypes}`; +} +export class InteractiveMode { + runtimeHost; + ui; + loadedResourcesContainer; + chatContainer; + pendingMessagesContainer; + statusContainer; + defaultEditor; + editor; + editorComponentFactory; + autocompleteProvider; + autocompleteProviderWrappers = []; + fdPath; + editorContainer; + footer; + footerDataProvider; + // Stored so the same manager can be injected into custom editors, selectors, and extension UI. + keybindings; + version; + isInitialized = false; + onInputCallback; + pendingUserInputs = []; + activeStatusIndicator = undefined; + idleStatus = new IdleStatus(); + workingMessage = undefined; + workingVisible = true; + workingIndicatorOptions = undefined; + defaultWorkingMessage = "Working..."; + defaultHiddenThinkingLabel = "Thinking..."; + hiddenThinkingLabel = this.defaultHiddenThinkingLabel; + lastSigintTime = 0; + lastEscapeTime = 0; + changelogMarkdown = undefined; + startupNoticesShown = false; + anthropicSubscriptionWarningShown = false; + // Status line tracking (for mutating immediately-sequential status updates) + lastStatusSpacer = undefined; + lastStatusText = undefined; + // Streaming message tracking + streamingComponent = undefined; + streamingMessage = undefined; + // Tool execution tracking: toolCallId -> component + pendingTools = new Map(); + // Tool output expansion state + toolOutputExpanded = false; + // Thinking block visibility state + hideThinkingBlock = false; + outputPad = 1; + // Skill commands: command name -> skill file path + skillCommands = new Map(); + // Agent subscription unsubscribe function + unsubscribe; + signalCleanupHandlers = []; + // Track if editor is in bash mode (text starts with !) + isBashMode = false; + // Track current bash execution component + bashComponent = undefined; + // Track pending bash components (shown in pending area, moved to chat on submit) + pendingBashComponents = []; + // Auto-compaction state + autoCompactionEscapeHandler; + // Auto-retry state + retryEscapeHandler; + // Messages queued while compaction is running + compactionQueuedMessages = []; + // Shutdown state + shutdownRequested = false; + // Extension UI state + extensionSelector = undefined; + extensionInput = undefined; + extensionEditor = undefined; + extensionTerminalInputUnsubscribers = new Set(); + // Extension widgets (components rendered above/below the editor) + extensionWidgetsAbove = new Map(); + extensionWidgetsBelow = new Map(); + widgetContainerAbove; + widgetContainerBelow; + // Custom footer from extension (undefined = use built-in footer) + customFooter = undefined; + // Header container that holds the built-in or custom header + headerContainer; + // Built-in header (logo + keybinding hints + changelog) + builtInHeader = undefined; + // Custom header from extension (undefined = use built-in header) + customHeader = undefined; + options; + autoTrustOnReloadCwd; + themeController; + // Convenience accessors + get session() { + return this.runtimeHost.session; + } + get agent() { + return this.session.agent; + } + get sessionManager() { + return this.session.sessionManager; + } + get settingsManager() { + return this.session.settingsManager; + } + constructor(runtimeHost, options = {}) { + this.runtimeHost = runtimeHost; + this.options = options; + this.autoTrustOnReloadCwd = options.autoTrustOnReloadCwd; + this.runtimeHost.setBeforeSessionInvalidate(() => { + this.resetExtensionUI(); + }); + this.runtimeHost.setRebindSession(async () => { + await this.rebindCurrentSession({ renderBeforeBind: true }); + }); + this.version = VERSION; + this.ui = new TUI(new ProcessTerminal(), this.settingsManager.getShowHardwareCursor(), getAgentDir()); + this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink()); + this.headerContainer = new Container(); + this.loadedResourcesContainer = new Container(); + this.chatContainer = new Container(); + this.pendingMessagesContainer = new Container(); + this.statusContainer = new Container(); + this.widgetContainerAbove = new Container(); + this.widgetContainerBelow = new Container(); + this.keybindings = KeybindingsManager.create(); + setKeybindings(this.keybindings); + const editorPaddingX = this.settingsManager.getEditorPaddingX(); + const autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible(); + this.defaultEditor = new CustomEditor(this.ui, getEditorTheme(), this.keybindings, { + paddingX: editorPaddingX, + autocompleteMaxVisible, + }); + this.editor = this.defaultEditor; + this.editorContainer = new Container(); + this.editorContainer.addChild(this.editor); + this.footerDataProvider = new FooterDataProvider(this.sessionManager.getCwd()); + this.footer = new FooterComponent(this.session, this.footerDataProvider); + this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled); + // Load hide thinking block setting + this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock(); + this.outputPad = this.settingsManager.getOutputPad(); + // Register themes from resource loader and initialize + setRegisteredThemes(this.session.resourceLoader.getThemes().themes); + this.themeController = new InteractiveThemeController(this.ui, this.settingsManager, (message) => this.showError(message), () => this.updateEditorBorderColor()); + } + getAutocompleteSourceTag(sourceInfo) { + if (!sourceInfo) { + return undefined; + } + const scopePrefix = sourceInfo.scope === "user" ? "u" : sourceInfo.scope === "project" ? "p" : "t"; + const source = sourceInfo.source.trim(); + if (source === "auto" || source === "local" || source === "cli") { + return scopePrefix; + } + if (source.startsWith("npm:")) { + return `${scopePrefix}:${source}`; + } + const gitSource = parseGitUrl(source); + if (gitSource) { + const ref = gitSource.ref ? `@${gitSource.ref}` : ""; + return `${scopePrefix}:git:${gitSource.host}/${gitSource.path}${ref}`; + } + return scopePrefix; + } + prefixAutocompleteDescription(description, sourceInfo) { + const sourceTag = this.getAutocompleteSourceTag(sourceInfo); + if (!sourceTag) { + return description; + } + return description ? `[${sourceTag}] ${description}` : `[${sourceTag}]`; + } + getBuiltInCommandConflictDiagnostics(extensionRunner) { + const builtinNames = new Set(BUILTIN_SLASH_COMMANDS.map((command) => command.name)); + return extensionRunner + .getRegisteredCommands() + .filter((command) => builtinNames.has(command.name)) + .map((command) => ({ + type: "warning", + message: command.invocationName === command.name + ? `Extension command '/${command.name}' conflicts with built-in interactive command. Skipping in autocomplete.` + : `Extension command '/${command.name}' conflicts with built-in interactive command. Available as '/${command.invocationName}'.`, + path: command.sourceInfo.path, + })); + } + createBaseAutocompleteProvider() { + // Define commands for autocomplete + const slashCommands = BUILTIN_SLASH_COMMANDS.map((command) => ({ + name: command.name, + description: command.description, + ...(command.argumentHint && { argumentHint: command.argumentHint }), + })); + const modelCommand = slashCommands.find((command) => command.name === "model"); + if (modelCommand) { + modelCommand.getArgumentCompletions = async (prefix) => { + // Get available models (scoped or from registry) + const models = this.session.scopedModels.length > 0 + ? this.session.scopedModels.map((s) => s.model) + : await this.session.modelRuntime.getAvailable(); + if (models.length === 0) + return null; + // Create items with provider/id format + const items = models.map((m) => ({ + id: m.id, + provider: m.provider, + name: m.name, + label: `${m.provider}/${m.id}`, + })); + return createFuzzyAutocompleteItems(items, prefix, getModelSearchText, (item) => ({ + value: item.label, + label: item.id, + description: item.provider, + })); + }; + } + const loginCommand = slashCommands.find((command) => command.name === "login"); + if (loginCommand) { + loginCommand.getArgumentCompletions = (prefix) => { + const providers = getLoginProviderCompletionOptions(this.getLoginProviderOptions()); + return createFuzzyAutocompleteItems(providers, prefix, getLoginProviderSearchText, (provider) => ({ + value: provider.id, + label: provider.id, + description: formatLoginProviderCompletionDescription(provider), + })); + }; + } + // Convert prompt templates to SlashCommand format for autocomplete + const templateCommands = this.session.promptTemplates.map((cmd) => ({ + name: cmd.name, + description: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo), + ...(cmd.argumentHint && { argumentHint: cmd.argumentHint }), + })); + // Convert extension commands to SlashCommand format + const builtinCommandNames = new Set(slashCommands.map((c) => c.name)); + const extensionCommands = this.session.extensionRunner + .getRegisteredCommands() + .filter((cmd) => !builtinCommandNames.has(cmd.name)) + .map((cmd) => ({ + name: cmd.invocationName, + description: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo), + getArgumentCompletions: cmd.getArgumentCompletions, + })); + // Build skill commands from session.skills (if enabled) + this.skillCommands.clear(); + const skillCommandList = []; + if (this.settingsManager.getEnableSkillCommands()) { + for (const skill of this.session.resourceLoader.getSkills().skills) { + const commandName = `skill:${skill.name}`; + this.skillCommands.set(commandName, skill.filePath); + skillCommandList.push({ + name: commandName, + description: this.prefixAutocompleteDescription(skill.description, skill.sourceInfo), + }); + } + } + return new CombinedAutocompleteProvider([...slashCommands, ...templateCommands, ...extensionCommands, ...skillCommandList], this.sessionManager.getCwd(), this.fdPath); + } + setupAutocompleteProvider() { + let provider = this.createBaseAutocompleteProvider(); + const triggerCharacters = []; + for (const wrapProvider of this.autocompleteProviderWrappers) { + provider = wrapProvider(provider); + triggerCharacters.push(...(provider.triggerCharacters ?? [])); + } + if (triggerCharacters.length > 0) { + provider.triggerCharacters = [...new Set(triggerCharacters)]; + } + this.autocompleteProvider = provider; + this.defaultEditor.setAutocompleteProvider(provider); + if (this.editor !== this.defaultEditor) { + this.editor.setAutocompleteProvider?.(provider); + } + } + showStartupNoticesIfNeeded() { + if (this.startupNoticesShown) { + return; + } + this.startupNoticesShown = true; + if (!this.changelogMarkdown) { + return; + } + if (this.chatContainer.children.length > 0) { + this.chatContainer.addChild(new Spacer(1)); + } + this.chatContainer.addChild(new DynamicBorder()); + if (this.settingsManager.getCollapseChangelog()) { + const versionMatch = this.changelogMarkdown.match(/##\s+\[?(\d+\.\d+\.\d+)\]?/); + const latestVersion = versionMatch ? versionMatch[1] : this.version; + const condensedText = `Updated to v${latestVersion}. Use ${theme.bold("/changelog")} to view full changelog.`; + this.chatContainer.addChild(new Text(condensedText, 1, 0)); + } + else { + this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0)); + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Markdown(this.changelogMarkdown.trim(), 1, 0, this.getMarkdownThemeWithSettings())); + this.chatContainer.addChild(new Spacer(1)); + } + this.chatContainer.addChild(new DynamicBorder()); + } + async init() { + if (this.isInitialized) + return; + this.registerSignalHandlers(); + // Load changelog (only show new entries, skip for resumed sessions) + this.changelogMarkdown = this.getChangelogForDisplay(); + // Ensure fd and rg are available (downloads if missing, adds to PATH via getBinDir) + // Both are needed: fd for autocomplete, rg for grep tool and bash commands + const [fdPath] = await Promise.all([ensureTool("fd"), ensureTool("rg")]); + this.fdPath = fdPath; + if (this.session.scopedModels.length > 0 && (this.options.verbose || !this.settingsManager.getQuietStartup())) { + const modelList = this.session.scopedModels + .map((sm) => { + const thinkingStr = sm.thinkingLevel ? `:${sm.thinkingLevel}` : ""; + return `${sm.model.id}${thinkingStr}`; + }) + .join(", "); + const cycleKeys = this.keybindings.getKeys("app.model.cycleForward"); + const cycleHint = cycleKeys.length > 0 + ? theme.fg("muted", ` (${formatKeyText(cycleKeys.join("/"), { capitalize: true })} to cycle)`) + : ""; + console.log(theme.fg("dim", `Model scope: ${modelList}${cycleHint}`)); + } + // Add header container as first child. Populate it after applying theme settings. + // Keep loaded resources before chat so restored session messages never precede them. + this.ui.addChild(this.headerContainer); + this.ui.addChild(this.loadedResourcesContainer); + this.ui.addChild(this.chatContainer); + this.ui.addChild(this.pendingMessagesContainer); + this.ui.addChild(this.statusContainer); + this.renderWidgets(); // Initialize with default spacer + this.ui.addChild(this.widgetContainerAbove); + this.ui.addChild(this.editorContainer); + this.ui.addChild(this.widgetContainerBelow); + this.ui.addChild(this.footer); + this.ui.setFocus(this.editor); + this.setupKeyHandlers(); + this.setupEditorSubmitHandler(); + // Start the UI before initializing extensions so session_start handlers can use interactive dialogs + this.ui.start(); + this.isInitialized = true; + await this.themeController.applyFromSettings(); + // Add header with keybindings from config (unless silenced) + if (this.options.verbose || !this.settingsManager.getQuietStartup()) { + const logo = theme.bold(theme.fg("accent", APP_NAME)) + theme.fg("dim", ` v${this.version}`); + // Build startup instructions using keybinding hint helpers + const hint = (keybinding, description) => keyHint(keybinding, description); + const expandedInstructions = [ + hint("app.interrupt", "to interrupt"), + hint("app.clear", "to clear"), + rawKeyHint(`${keyText("app.clear")} twice`, "to exit"), + hint("app.exit", "to exit (empty)"), + hint("app.suspend", "to suspend"), + keyHint("tui.editor.deleteToLineEnd", "to delete to end"), + hint("app.thinking.cycle", "to cycle thinking level"), + rawKeyHint(`${keyText("app.model.cycleForward")}/${keyText("app.model.cycleBackward")}`, "to cycle models"), + hint("app.model.select", "to select model"), + hint("app.tools.expand", "to expand tools"), + hint("app.thinking.toggle", "to expand thinking"), + hint("app.editor.external", "for external editor"), + rawKeyHint("/", "for commands"), + rawKeyHint("!", "to run bash"), + rawKeyHint("!!", "to run bash (no context)"), + hint("app.message.followUp", "to queue follow-up"), + hint("app.message.dequeue", "to edit all queued messages"), + hint("app.clipboard.pasteImage", "to paste image (with text fallback)"), + rawKeyHint("drop files", "to attach"), + ].join("\n"); + const compactInstructions = [ + hint("app.interrupt", "interrupt"), + rawKeyHint(`${keyText("app.clear")}/${keyText("app.exit")}`, "clear/exit"), + rawKeyHint("/", "commands"), + rawKeyHint("!", "bash"), + hint("app.tools.expand", "more"), + ].join(theme.fg("muted", " · ")); + const compactOnboarding = theme.fg("dim", `Press ${keyText("app.tools.expand")} to show full startup help and loaded resources.`); + const onboarding = theme.fg("dim", `Pi can explain its own features and look up its docs. Ask it how to use or extend Pi.`); + this.builtInHeader = new ExpandableText(() => `${logo}\n${compactInstructions}\n${compactOnboarding}\n\n${onboarding}`, () => `${logo}\n${expandedInstructions}\n\n${onboarding}`, this.getStartupExpansionState(), 1, 0); + // Setup UI layout + this.headerContainer.addChild(new Spacer(1)); + this.headerContainer.addChild(this.builtInHeader); + this.headerContainer.addChild(new Spacer(1)); + } + else { + // Minimal header when silenced + this.builtInHeader = new Text("", 0, 0); + this.headerContainer.addChild(this.builtInHeader); + } + this.ui.requestRender(); + // Initialize extensions first so resources are shown before messages + await this.rebindCurrentSession(); + // Render initial messages AFTER showing loaded resources + this.renderInitialMessages(); + // Set up theme file watcher + onThemeChange(() => { + this.ui.invalidate(); + this.updateEditorBorderColor(); + this.ui.requestRender(); + }); + // Set up git branch watcher (uses provider instead of footer) + this.footerDataProvider.onBranchChange(() => { + this.ui.requestRender(); + }); + // Initialize available provider count for footer display + await this.updateAvailableProviderCount(); + } + /** + * Update terminal title with session name and cwd. + */ + updateTerminalTitle() { + const cwdBasename = path.basename(this.sessionManager.getCwd()); + const sessionName = this.sessionManager.getSessionName(); + if (sessionName) { + this.ui.terminal.setTitle(`${APP_TITLE} - ${sessionName} - ${cwdBasename}`); + } + else { + this.ui.terminal.setTitle(`${APP_TITLE} - ${cwdBasename}`); + } + } + /** + * Run the interactive mode. This is the main entry point. + * Initializes the UI, shows warnings, processes initial messages, and starts the interactive loop. + */ + async run() { + await this.init(); + if (!process.env.PI_OFFLINE) { + void this.session.modelRuntime + .refresh() + .then(() => this.updateAvailableProviderCount()) + .catch(() => { }); + } + // Start version check asynchronously + checkForNewPiVersion(this.version).then((newRelease) => { + if (newRelease) { + this.showNewVersionNotification(newRelease); + } + }); + // Start package update check asynchronously + this.checkForPackageUpdates() + .then((updates) => { + if (updates.length > 0) { + this.showPackageUpdateNotification(updates); + } + }) + .finally(() => { + // On Windows, npm can overwrite the shared console title while checking + // extension package versions. Restore Pi's title after the startup check. + if (process.platform === "win32" && this.isInitialized) { + this.updateTerminalTitle(); + } + }); + // Check tmux keyboard setup asynchronously + this.checkTmuxKeyboardSetup().then((warning) => { + if (warning) { + this.showWarning(warning); + } + }); + // Show startup warnings + const { migratedProviders, modelFallbackMessage, initialMessage, initialImages, initialMessages } = this.options; + if (migratedProviders && migratedProviders.length > 0) { + this.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(", ")}`); + } + const modelsJsonError = this.session.modelRuntime.getError(); + if (modelsJsonError) { + this.showError(`models.json error: ${modelsJsonError}`); + } + if (modelFallbackMessage) { + this.showWarning(modelFallbackMessage); + } + void this.maybeWarnAboutAnthropicSubscriptionAuth(); + // Process initial messages + if (initialMessage) { + try { + await this.session.prompt(initialMessage, { images: initialImages }); + } + catch (error) { + const errorMessage = error instanceof Error ? error.message : "Unknown error occurred"; + this.showError(errorMessage); + } + } + if (initialMessages) { + for (const message of initialMessages) { + try { + await this.session.prompt(message); + } + catch (error) { + const errorMessage = error instanceof Error ? error.message : "Unknown error occurred"; + this.showError(errorMessage); + } + } + } + // Main interactive loop + while (true) { + const userInput = await this.getUserInput(); + try { + await this.session.prompt(userInput); + } + catch (error) { + const errorMessage = error instanceof Error ? error.message : "Unknown error occurred"; + this.showError(errorMessage); + } + } + } + async checkForPackageUpdates() { + if (process.env.PI_OFFLINE) { + return []; + } + try { + const packageManager = new DefaultPackageManager({ + cwd: this.sessionManager.getCwd(), + agentDir: getAgentDir(), + settingsManager: this.settingsManager, + }); + const updates = await packageManager.checkForAvailableUpdates(); + return updates.map((update) => update.displayName); + } + catch { + return []; + } + } + async checkTmuxKeyboardSetup() { + if (!process.env.TMUX) + return undefined; + const runTmuxShow = (option) => { + return new Promise((resolve) => { + const proc = spawn("tmux", ["show", "-gv", option], { + stdio: ["ignore", "pipe", "ignore"], + }); + let stdout = ""; + const timer = setTimeout(() => { + proc.kill(); + resolve(undefined); + }, 2000); + proc.stdout?.on("data", (data) => { + stdout += data.toString(); + }); + proc.on("error", () => { + clearTimeout(timer); + resolve(undefined); + }); + proc.on("close", (code) => { + clearTimeout(timer); + resolve(code === 0 ? stdout.trim() : undefined); + }); + }); + }; + const [extendedKeys, extendedKeysFormat] = await Promise.all([ + runTmuxShow("extended-keys"), + runTmuxShow("extended-keys-format"), + ]); + // If we couldn't query tmux (timeout, sandbox, etc.), don't warn + if (extendedKeys === undefined) + return undefined; + if (extendedKeys !== "on" && extendedKeys !== "always") { + return "tmux extended-keys is off. Modified Enter keys may not work. Add `set -g extended-keys on` to ~/.tmux.conf and restart tmux."; + } + if (extendedKeysFormat === "xterm") { + return "tmux extended-keys-format is xterm. Pi works best with csi-u. Add `set -g extended-keys-format csi-u` to ~/.tmux.conf and restart tmux."; + } + return undefined; + } + /** + * Get changelog entries to display on startup. + * Only shows new entries since last seen version, skips for resumed sessions. + */ + getChangelogForDisplay() { + // Skip changelog for resumed/continued sessions (already have messages) + if (this.session.state.messages.length > 0) { + return undefined; + } + const lastVersion = this.settingsManager.getLastChangelogVersion(); + const changelogPath = getChangelogPath(); + const entries = parseChangelog(changelogPath); + if (!lastVersion) { + // Fresh install - record the version, send telemetry, don't show changelog + this.settingsManager.setLastChangelogVersion(VERSION); + this.reportInstallTelemetry(VERSION); + return undefined; + } + const newEntries = getNewEntries(entries, lastVersion); + if (newEntries.length > 0) { + this.settingsManager.setLastChangelogVersion(VERSION); + this.reportInstallTelemetry(VERSION); + return newEntries.map((e) => normalizeChangelogLinks(e.content, e)).join("\n\n"); + } + return undefined; + } + reportInstallTelemetry(version) { + if (process.env.PI_OFFLINE) { + return; + } + if (!isInstallTelemetryEnabled(this.settingsManager)) { + return; + } + void fetch(`https://pi.dev/api/report-install?version=${encodeURIComponent(version)}`, { + headers: { + "User-Agent": getPiUserAgent(version), + }, + signal: AbortSignal.timeout(5000), + }) + .then(() => undefined) + .catch(() => undefined); + } + getMarkdownThemeWithSettings() { + return { + ...getMarkdownTheme(), + codeBlockIndent: this.settingsManager.getCodeBlockIndent(), + }; + } + // ========================================================================= + // Extension System + // ========================================================================= + formatDisplayPath(p) { + const home = os.homedir(); + let result = p; + // Replace home directory with ~ + if (result.startsWith(home)) { + result = `~${result.slice(home.length)}`; + } + return result; + } + formatExtensionDisplayPath(path) { + let result = this.formatDisplayPath(path); + result = result.replace(/\/index\.ts$/, "").replace(/\/index\.js$/, ""); + return result; + } + formatContextPath(p) { + const cwd = path.resolve(this.sessionManager.getCwd()); + const absolutePath = path.isAbsolute(p) ? path.resolve(p) : path.resolve(cwd, p); + const relativePath = getCwdRelativePath(absolutePath, cwd); + if (relativePath !== undefined) { + return relativePath; + } + return this.formatDisplayPath(absolutePath); + } + getStartupExpansionState() { + return this.options.verbose || this.toolOutputExpanded; + } + /** + * Get a short path relative to the package root for display. + */ + getShortPath(fullPath, sourceInfo) { + const normalizedFullPath = fullPath.replace(/\\/g, "/"); + const baseDir = sourceInfo?.baseDir; + if (baseDir && this.isPackageSource(sourceInfo)) { + const normalizedBaseDir = baseDir.replace(/\\/g, "/"); + const npmRootMatch = normalizedBaseDir.match(/^(.*\/node_modules)\/(@?[^/]+(?:\/[^/]+)?)$/); + // If fullPath is under the same node_modules root as baseDir, preserve that relative topology. + if (npmRootMatch?.[1] && normalizedFullPath.startsWith(`${npmRootMatch[1]}/`)) { + return path.posix.relative(normalizedBaseDir, normalizedFullPath); + } + const relativePath = path.relative(path.resolve(baseDir), path.resolve(fullPath)); + if (relativePath && + relativePath !== "." && + !relativePath.startsWith("..") && + !relativePath.startsWith(`..${path.sep}`) && + !path.isAbsolute(relativePath)) { + return relativePath.replace(/\\/g, "/"); + } + } + const source = sourceInfo?.source ?? ""; + const npmMatch = normalizedFullPath.match(/node_modules\/(@?[^/]+(?:\/[^/]+)?)\/(.*)/); + if (npmMatch && source.startsWith("npm:")) { + return npmMatch[2]; + } + const gitMatch = normalizedFullPath.match(/git\/[^/]+\/[^/]+\/(.*)/); + if (gitMatch && source.startsWith("git:")) { + return gitMatch[1]; + } + return this.formatDisplayPath(fullPath); + } + getCompactPathLabel(resourcePath, sourceInfo) { + const shortPath = this.getShortPath(resourcePath, sourceInfo); + const normalizedPath = shortPath.replace(/\\/g, "/"); + const segments = normalizedPath.split("/").filter((segment) => segment.length > 0 && segment !== "~"); + if (segments.length > 0) { + return segments[segments.length - 1]; + } + return shortPath; + } + getCompactPackageSourceLabel(sourceInfo) { + const source = sourceInfo?.source ?? ""; + if (source.startsWith("npm:")) { + return source.slice("npm:".length) || source; + } + const gitSource = parseGitUrl(source); + if (gitSource) { + return gitSource.path || source; + } + return source; + } + getCompactExtensionLabel(resourcePath, sourceInfo) { + if (!this.isPackageSource(sourceInfo)) { + return this.getCompactPathLabel(resourcePath, sourceInfo); + } + const sourceLabel = this.getCompactPackageSourceLabel(sourceInfo); + if (!sourceLabel) { + return this.getCompactPathLabel(resourcePath, sourceInfo); + } + const shortPath = this.getShortPath(resourcePath, sourceInfo).replace(/\\/g, "/"); + const packagePath = shortPath.startsWith("extensions/") ? shortPath.slice("extensions/".length) : shortPath; + const parsedPath = path.posix.parse(packagePath); + if (parsedPath.name === "index") { + return !parsedPath.dir || parsedPath.dir === "." ? sourceLabel : `${sourceLabel}:${parsedPath.dir}`; + } + return `${sourceLabel}:${packagePath}`; + } + getCompactDisplayPathSegments(resourcePath) { + return this.formatDisplayPath(resourcePath) + .replace(/\\/g, "/") + .split("/") + .filter((segment) => segment.length > 0 && segment !== "~"); + } + getCompactNonPackageExtensionLabel(resourcePath, index, allPaths) { + const segments = allPaths[index]?.segments; + if (!segments || segments.length === 0) { + return this.getCompactPathLabel(resourcePath); + } + for (let segmentCount = 1; segmentCount <= segments.length; segmentCount += 1) { + const candidate = segments.slice(-segmentCount).join("/"); + const isUnique = allPaths.every((item, itemIndex) => { + if (itemIndex === index) { + return true; + } + return item.segments.slice(-segmentCount).join("/") !== candidate; + }); + if (isUnique) { + return candidate; + } + } + return segments.join("/"); + } + getCompactExtensionLabels(extensions) { + const nonPackageExtensions = extensions + .map((extension) => { + const segments = this.getCompactDisplayPathSegments(extension.path); + const lastSegment = segments[segments.length - 1]; + if (segments.length > 1 && (lastSegment === "index.ts" || lastSegment === "index.js")) { + segments.pop(); + } + return { + path: extension.path, + sourceInfo: extension.sourceInfo, + segments, + }; + }) + .filter((extension) => !this.isPackageSource(extension.sourceInfo)); + return extensions.map((extension) => { + if (this.isPackageSource(extension.sourceInfo)) { + return this.getCompactExtensionLabel(extension.path, extension.sourceInfo); + } + const nonPackageIndex = nonPackageExtensions.findIndex((item) => item.path === extension.path); + if (nonPackageIndex === -1) { + return this.getCompactPathLabel(extension.path, extension.sourceInfo); + } + return this.getCompactNonPackageExtensionLabel(extension.path, nonPackageIndex, nonPackageExtensions); + }); + } + getDisplaySourceInfo(sourceInfo) { + const source = sourceInfo?.source ?? "local"; + const scope = sourceInfo?.scope ?? "project"; + if (source === "local") { + if (scope === "user") { + return { label: "user", color: "muted" }; + } + if (scope === "project") { + return { label: "project", color: "muted" }; + } + if (scope === "temporary") { + return { label: "path", scopeLabel: "temp", color: "muted" }; + } + return { label: "path", color: "muted" }; + } + if (source === "cli") { + return { label: "path", scopeLabel: scope === "temporary" ? "temp" : undefined, color: "muted" }; + } + const scopeLabel = scope === "user" ? "user" : scope === "project" ? "project" : scope === "temporary" ? "temp" : undefined; + return { label: source, scopeLabel, color: "accent" }; + } + getScopeGroup(sourceInfo) { + const source = sourceInfo?.source ?? "local"; + const scope = sourceInfo?.scope ?? "project"; + if (source === "cli" || scope === "temporary") + return "path"; + if (scope === "user") + return "user"; + if (scope === "project") + return "project"; + return "path"; + } + isPackageSource(sourceInfo) { + const source = sourceInfo?.source ?? ""; + return source.startsWith("npm:") || source.startsWith("git:"); + } + buildScopeGroups(items) { + const groups = { + user: { scope: "user", paths: [], packages: new Map() }, + project: { scope: "project", paths: [], packages: new Map() }, + path: { scope: "path", paths: [], packages: new Map() }, + }; + for (const item of items) { + const groupKey = this.getScopeGroup(item.sourceInfo); + const group = groups[groupKey]; + const source = item.sourceInfo?.source ?? "local"; + if (this.isPackageSource(item.sourceInfo)) { + const list = group.packages.get(source) ?? []; + list.push(item); + group.packages.set(source, list); + } + else { + group.paths.push(item); + } + } + return [groups.project, groups.user, groups.path].filter((group) => group.paths.length > 0 || group.packages.size > 0); + } + formatScopeGroups(groups, options) { + const lines = []; + for (const group of groups) { + lines.push(` ${theme.fg("accent", group.scope)}`); + const sortedPaths = [...group.paths].sort((a, b) => a.path.localeCompare(b.path)); + for (const item of sortedPaths) { + lines.push(theme.fg("dim", ` ${options.formatPath(item)}`)); + } + const sortedPackages = Array.from(group.packages.entries()).sort(([a], [b]) => a.localeCompare(b)); + for (const [source, items] of sortedPackages) { + lines.push(` ${theme.fg("mdLink", source)}`); + const sortedPackagePaths = [...items].sort((a, b) => a.path.localeCompare(b.path)); + for (const item of sortedPackagePaths) { + lines.push(theme.fg("dim", ` ${options.formatPackagePath(item, source)}`)); + } + } + } + return lines.join("\n"); + } + findSourceInfoForPath(p, sourceInfos) { + const exact = sourceInfos.get(p); + if (exact) + return exact; + let current = p; + while (current.includes("/")) { + current = current.substring(0, current.lastIndexOf("/")); + const parent = sourceInfos.get(current); + if (parent) + return parent; + } + return undefined; + } + formatPathWithSource(p, sourceInfo) { + if (sourceInfo) { + const shortPath = this.getShortPath(p, sourceInfo); + const { label, scopeLabel } = this.getDisplaySourceInfo(sourceInfo); + const labelText = scopeLabel ? `${label} (${scopeLabel})` : label; + return `${labelText} ${shortPath}`; + } + return this.formatDisplayPath(p); + } + formatDiagnostics(diagnostics, sourceInfos) { + const lines = []; + // Group collision diagnostics by name + const collisions = new Map(); + const otherDiagnostics = []; + for (const d of diagnostics) { + if (d.type === "collision" && d.collision) { + const list = collisions.get(d.collision.name) ?? []; + list.push(d); + collisions.set(d.collision.name, list); + } + else { + otherDiagnostics.push(d); + } + } + // Format collision diagnostics grouped by name + for (const [name, collisionList] of collisions) { + const first = collisionList[0]?.collision; + if (!first) + continue; + lines.push(theme.fg("warning", ` "${name}" collision:`)); + lines.push(theme.fg("dim", ` ${theme.fg("success", "✓")} ${this.formatPathWithSource(first.winnerPath, this.findSourceInfoForPath(first.winnerPath, sourceInfos))}`)); + for (const d of collisionList) { + if (d.collision) { + lines.push(theme.fg("dim", ` ${theme.fg("warning", "✗")} ${this.formatPathWithSource(d.collision.loserPath, this.findSourceInfoForPath(d.collision.loserPath, sourceInfos))} (skipped)`)); + } + } + } + for (const d of otherDiagnostics) { + if (d.path) { + const formattedPath = this.formatPathWithSource(d.path, this.findSourceInfoForPath(d.path, sourceInfos)); + lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${formattedPath}`)); + lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${d.message}`)); + } + else { + lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${d.message}`)); + } + } + return lines.join("\n"); + } + showLoadedResources(options) { + // Resource rendering is idempotent; chat clears no longer clear this separate container. + this.loadedResourcesContainer.clear(); + const showListing = options?.force || this.options.verbose || !this.settingsManager.getQuietStartup(); + const showDiagnostics = showListing || options?.showDiagnosticsWhenQuiet === true; + if (!showListing && !showDiagnostics) { + return; + } + const sectionHeader = (name, color = "mdHeading") => theme.fg(color, `[${name}]`); + const formatCompactList = (items, options) => { + const labels = items.map((item) => item.trim()).filter((item) => item.length > 0); + if (options?.sort !== false) { + labels.sort((a, b) => a.localeCompare(b)); + } + return theme.fg("dim", ` ${labels.join(", ")}`); + }; + const addLoadedSection = (name, collapsedBody, expandedBody = collapsedBody, color = "mdHeading") => { + const section = new ExpandableText(() => `${sectionHeader(name, color)}\n${collapsedBody}`, () => `${sectionHeader(name, color)}\n${expandedBody}`, this.getStartupExpansionState(), 0, 0); + this.loadedResourcesContainer.addChild(section); + this.loadedResourcesContainer.addChild(new Spacer(1)); + }; + const skillsResult = this.session.resourceLoader.getSkills(); + const promptsResult = this.session.resourceLoader.getPrompts(); + const themesResult = this.session.resourceLoader.getThemes(); + const extensions = options?.extensions ?? + this.session.resourceLoader + .getExtensions() + .extensions.filter((extension) => !extension.hidden) + .map((extension) => ({ + path: extension.path, + sourceInfo: extension.sourceInfo, + })); + const sourceInfos = new Map(); + for (const extension of extensions) { + if (extension.sourceInfo) { + sourceInfos.set(extension.path, extension.sourceInfo); + } + } + for (const skill of skillsResult.skills) { + if (skill.sourceInfo) { + sourceInfos.set(skill.filePath, skill.sourceInfo); + } + } + for (const prompt of promptsResult.prompts) { + if (prompt.sourceInfo) { + sourceInfos.set(prompt.filePath, prompt.sourceInfo); + } + } + for (const loadedTheme of themesResult.themes) { + if (loadedTheme.sourcePath && loadedTheme.sourceInfo) { + sourceInfos.set(loadedTheme.sourcePath, loadedTheme.sourceInfo); + } + } + if (showListing) { + const systemPromptSource = this.session.resourceLoader.getSystemPromptSource(); + const contextFiles = [ + ...(systemPromptSource ? [systemPromptSource] : []), + ...this.session.resourceLoader.getAppendSystemPromptSources(), + ...this.session.resourceLoader.getAgentsFiles().agentsFiles, + ]; + if (contextFiles.length > 0) { + this.loadedResourcesContainer.addChild(new Spacer(1)); + const contextList = contextFiles + .map((f) => theme.fg("dim", ` ${this.formatDisplayPath(f.path)}`)) + .join("\n"); + const contextCompactList = formatCompactList(contextFiles.map((contextFile) => this.formatContextPath(contextFile.path)), { sort: false }); + addLoadedSection("Context", contextCompactList, contextList); + } + const skills = skillsResult.skills; + if (skills.length > 0) { + const groups = this.buildScopeGroups(skills.map((skill) => ({ path: skill.filePath, sourceInfo: skill.sourceInfo }))); + const skillList = this.formatScopeGroups(groups, { + formatPath: (item) => this.formatDisplayPath(item.path), + formatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo), + }); + const skillCompactList = formatCompactList(skills.map((skill) => skill.name)); + addLoadedSection("Skills", skillCompactList, skillList); + } + const templates = this.session.promptTemplates; + if (templates.length > 0) { + const groups = this.buildScopeGroups(templates.map((template) => ({ path: template.filePath, sourceInfo: template.sourceInfo }))); + const templateByPath = new Map(templates.map((t) => [t.filePath, t])); + const templateList = this.formatScopeGroups(groups, { + formatPath: (item) => { + const template = templateByPath.get(item.path); + return template ? `/${template.name}` : this.formatDisplayPath(item.path); + }, + formatPackagePath: (item) => { + const template = templateByPath.get(item.path); + return template ? `/${template.name}` : this.formatDisplayPath(item.path); + }, + }); + const promptCompactList = formatCompactList(templates.map((template) => `/${template.name}`)); + addLoadedSection("Prompts", promptCompactList, templateList); + } + if (extensions.length > 0) { + const groups = this.buildScopeGroups(extensions); + const extList = this.formatScopeGroups(groups, { + formatPath: (item) => this.formatExtensionDisplayPath(item.path), + formatPackagePath: (item) => this.formatExtensionDisplayPath(this.getShortPath(item.path, item.sourceInfo)), + }); + const extensionCompactList = formatCompactList(this.getCompactExtensionLabels(extensions)); + addLoadedSection("Extensions", extensionCompactList, extList, "mdHeading"); + } + // Show loaded themes (excluding built-in) + const loadedThemes = themesResult.themes; + const customThemes = loadedThemes.filter((t) => t.sourcePath); + if (customThemes.length > 0) { + const groups = this.buildScopeGroups(customThemes.map((loadedTheme) => ({ + path: loadedTheme.sourcePath, + sourceInfo: loadedTheme.sourceInfo, + }))); + const themeList = this.formatScopeGroups(groups, { + formatPath: (item) => this.formatDisplayPath(item.path), + formatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo), + }); + const themeCompactList = formatCompactList(customThemes.map((loadedTheme) => loadedTheme.name ?? this.getCompactPathLabel(loadedTheme.sourcePath, loadedTheme.sourceInfo))); + addLoadedSection("Themes", themeCompactList, themeList); + } + } + if (showDiagnostics) { + const skillDiagnostics = skillsResult.diagnostics; + if (skillDiagnostics.length > 0) { + const warningLines = this.formatDiagnostics(skillDiagnostics, sourceInfos); + this.loadedResourcesContainer.addChild(new Text(`${theme.fg("warning", "[Skill conflicts]")}\n${warningLines}`, 0, 0)); + this.loadedResourcesContainer.addChild(new Spacer(1)); + } + const promptDiagnostics = promptsResult.diagnostics; + if (promptDiagnostics.length > 0) { + const warningLines = this.formatDiagnostics(promptDiagnostics, sourceInfos); + this.loadedResourcesContainer.addChild(new Text(`${theme.fg("warning", "[Prompt conflicts]")}\n${warningLines}`, 0, 0)); + this.loadedResourcesContainer.addChild(new Spacer(1)); + } + const extensionDiagnostics = []; + const extensionErrors = this.session.resourceLoader.getExtensions().errors; + if (extensionErrors.length > 0) { + for (const error of extensionErrors) { + extensionDiagnostics.push({ type: "error", message: error.error, path: error.path }); + } + } + const commandDiagnostics = this.session.extensionRunner.getCommandDiagnostics(); + extensionDiagnostics.push(...commandDiagnostics); + extensionDiagnostics.push(...this.getBuiltInCommandConflictDiagnostics(this.session.extensionRunner)); + const shortcutDiagnostics = this.session.extensionRunner.getShortcutDiagnostics(); + extensionDiagnostics.push(...shortcutDiagnostics); + if (extensionDiagnostics.length > 0) { + const warningLines = this.formatDiagnostics(extensionDiagnostics, sourceInfos); + this.loadedResourcesContainer.addChild(new Text(`${theme.fg("warning", "[Extension issues]")}\n${warningLines}`, 0, 0)); + this.loadedResourcesContainer.addChild(new Spacer(1)); + } + const themeDiagnostics = themesResult.diagnostics; + if (themeDiagnostics.length > 0) { + const warningLines = this.formatDiagnostics(themeDiagnostics, sourceInfos); + this.loadedResourcesContainer.addChild(new Text(`${theme.fg("warning", "[Theme conflicts]")}\n${warningLines}`, 0, 0)); + this.loadedResourcesContainer.addChild(new Spacer(1)); + } + } + } + /** + * Initialize the extension system with TUI-based UI context. + */ + async bindCurrentSessionExtensions() { + const uiContext = this.createExtensionUIContext(); + await this.session.bindExtensions({ + uiContext, + mode: "tui", + abortHandler: () => { + this.restoreQueuedMessagesToEditor({ abort: true }); + }, + commandContextActions: { + waitForIdle: () => this.session.waitForIdle(), + newSession: async (options) => { + this.clearStatusIndicator(); + try { + return await this.runtimeHost.newSession(options); + } + catch (error) { + return this.handleFatalRuntimeError("Failed to create session", error); + } + }, + fork: async (entryId, options) => { + try { + const result = await this.runtimeHost.fork(entryId, options); + if (!result.cancelled) { + this.editor.setText(result.selectedText ?? ""); + this.showStatus("Forked to new session"); + } + return { cancelled: result.cancelled }; + } + catch (error) { + return this.handleFatalRuntimeError("Failed to fork session", error); + } + }, + navigateTree: async (targetId, options) => { + const result = await this.session.navigateTree(targetId, { + summarize: options?.summarize, + customInstructions: options?.customInstructions, + replaceInstructions: options?.replaceInstructions, + label: options?.label, + }); + if (result.cancelled) { + return { cancelled: true }; + } + this.chatContainer.clear(); + this.renderInitialMessages(); + if (result.editorText && !this.editor.getText().trim()) { + this.editor.setText(result.editorText); + } + this.showStatus("Navigated to selected point"); + void this.flushCompactionQueue({ willRetry: false }); + return { cancelled: false }; + }, + switchSession: async (sessionPath, options) => { + return this.handleResumeSession(sessionPath, options); + }, + reload: async () => { + await this.handleReloadCommand(); + }, + }, + shutdownHandler: () => { + this.shutdownRequested = true; + if (this.session.isIdle) { + void this.shutdown(); + } + }, + onError: (error) => { + this.showExtensionError(error.extensionPath, error.error, error.stack); + }, + }); + setRegisteredThemes(this.session.resourceLoader.getThemes().themes); + this.setupAutocompleteProvider(); + const extensionRunner = this.session.extensionRunner; + this.setupExtensionShortcuts(extensionRunner); + this.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true }); + this.showStartupNoticesIfNeeded(); + } + applyRuntimeSettings() { + configureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs()); + this.footer.setSession(this.session); + this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled); + this.footerDataProvider.setCwd(this.sessionManager.getCwd()); + this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock(); + this.outputPad = this.settingsManager.getOutputPad(); + this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor()); + const clearOnShrink = this.settingsManager.getClearOnShrink(); + this.ui.setClearOnShrink(clearOnShrink); + if (!clearOnShrink && !this.activeStatusIndicator) { + this.statusContainer.clear(); + } + const editorPaddingX = this.settingsManager.getEditorPaddingX(); + const autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible(); + this.defaultEditor.setPaddingX(editorPaddingX); + this.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible); + if (this.editor !== this.defaultEditor) { + this.editor.setPaddingX?.(editorPaddingX); + this.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible); + } + } + async rebindCurrentSession(options = {}) { + const session = this.session; + this.unsubscribe?.(); + this.unsubscribe = undefined; + this.applyRuntimeSettings(); + if (options.renderBeforeBind) { + this.renderCurrentSessionState(); + this.subscribeToAgent(); + } + await this.bindCurrentSessionExtensions(); + if (this.session !== session) { + return; + } + if (!options.renderBeforeBind) { + this.subscribeToAgent(); + } + await this.updateAvailableProviderCount(); + this.updateEditorBorderColor(); + this.updateTerminalTitle(); + } + async handleFatalRuntimeError(prefix, error) { + const message = error instanceof Error ? error.message : String(error); + this.showError(`${prefix}: ${message}`); + stopThemeWatcher(); + this.stop(); + process.exit(1); + } + renderCurrentSessionState() { + this.loadedResourcesContainer.clear(); + this.chatContainer.clear(); + this.pendingMessagesContainer.clear(); + this.compactionQueuedMessages = []; + this.streamingComponent = undefined; + this.streamingMessage = undefined; + this.pendingTools.clear(); + this.renderInitialMessages(); + } + /** + * Get a registered tool definition by name (for custom rendering). + */ + getRegisteredToolDefinition(toolName) { + return this.session.getToolDefinition(toolName); + } + /** + * Set up keyboard shortcuts registered by extensions. + */ + setupExtensionShortcuts(extensionRunner) { + const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig()); + if (shortcuts.size === 0) + return; + // Create a context for shortcut handlers + const createContext = () => ({ + ui: this.createExtensionUIContext(), + mode: "tui", + hasUI: true, + cwd: this.sessionManager.getCwd(), + sessionManager: this.sessionManager, + modelRegistry: extensionRunner.getModelRegistry(), + model: this.session.model, + scopedModels: this.session.scopedModels, + thinkingLevel: this.session.thinkingLevel, + isIdle: () => this.session.isIdle, + isProjectTrusted: () => this.settingsManager.isProjectTrusted(), + signal: this.session.agent.signal, + abort: () => { + this.restoreQueuedMessagesToEditor({ abort: true }); + }, + hasPendingMessages: () => this.session.pendingMessageCount > 0, + shutdown: () => { + this.shutdownRequested = true; + }, + getContextUsage: () => this.session.getContextUsage(), + compact: (options) => { + void (async () => { + try { + const result = await this.session.compact(options?.customInstructions); + options?.onComplete?.(result); + } + catch (error) { + const err = error instanceof Error ? error : new Error(String(error)); + options?.onError?.(err); + } + })(); + }, + getSystemPrompt: () => this.session.systemPrompt, + }); + // Set up the extension shortcut handler on the default editor + this.defaultEditor.onExtensionShortcut = (data) => { + for (const [shortcutStr, shortcut] of shortcuts) { + // Cast to KeyId - extension shortcuts use the same format + if (matchesKey(data, shortcutStr)) { + // Run handler async, don't block input + Promise.resolve(shortcut.handler(createContext())).catch((err) => { + this.showError(`Shortcut handler error: ${err instanceof Error ? err.message : String(err)}`); + }); + return true; + } + } + return false; + }; + } + /** + * Set extension status text in the footer. + */ + setExtensionStatus(key, text) { + this.footerDataProvider.setExtensionStatus(key, text); + this.ui.requestRender(); + } + showStatusIndicator(indicator) { + this.activeStatusIndicator?.dispose(); + this.activeStatusIndicator = indicator; + this.statusContainer.clear(); + this.statusContainer.addChild(indicator); + } + clearStatusIndicator(kind) { + if (kind && this.activeStatusIndicator?.kind !== kind) { + return; + } + const hadActiveStatusIndicator = this.activeStatusIndicator !== undefined; + this.activeStatusIndicator?.dispose(); + this.activeStatusIndicator = undefined; + this.statusContainer.clear(); + if (hadActiveStatusIndicator && this.ui.getClearOnShrink()) { + this.statusContainer.addChild(this.idleStatus); + } + } + setWorkingVisible(visible) { + this.workingVisible = visible; + if (!visible) { + this.clearStatusIndicator("working"); + this.ui.requestRender(); + return; + } + if (this.session.isStreaming && this.activeStatusIndicator?.kind !== "working") { + this.showStatusIndicator(new WorkingStatusIndicator(this.ui, this.workingMessage ?? this.defaultWorkingMessage, this.workingIndicatorOptions)); + } + this.ui.requestRender(); + } + setWorkingIndicator(options) { + this.workingIndicatorOptions = options; + if (this.activeStatusIndicator?.kind === "working") { + this.activeStatusIndicator.setIndicator(options); + } + this.ui.requestRender(); + } + setHiddenThinkingLabel(label) { + this.hiddenThinkingLabel = label ?? this.defaultHiddenThinkingLabel; + for (const child of this.chatContainer.children) { + if (child instanceof AssistantMessageComponent) { + child.setHiddenThinkingLabel(this.hiddenThinkingLabel); + } + } + if (this.streamingComponent) { + this.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel); + } + this.ui.requestRender(); + } + /** + * Set an extension widget (string array or custom component). + */ + setExtensionWidget(key, content, options) { + const placement = options?.placement ?? "aboveEditor"; + const removeExisting = (map) => { + const existing = map.get(key); + if (existing?.dispose) + existing.dispose(); + map.delete(key); + }; + removeExisting(this.extensionWidgetsAbove); + removeExisting(this.extensionWidgetsBelow); + if (content === undefined) { + this.renderWidgets(); + return; + } + let component; + if (Array.isArray(content)) { + // Wrap string array in a Container with Text components + const container = new Container(); + for (const line of content.slice(0, InteractiveMode.MAX_WIDGET_LINES)) { + container.addChild(new Text(line, 1, 0)); + } + if (content.length > InteractiveMode.MAX_WIDGET_LINES) { + container.addChild(new Text(theme.fg("muted", "... (widget truncated)"), 1, 0)); + } + component = container; + } + else { + // Factory function - create component + component = content(this.ui, theme); + } + const targetMap = placement === "belowEditor" ? this.extensionWidgetsBelow : this.extensionWidgetsAbove; + targetMap.set(key, component); + this.renderWidgets(); + } + clearExtensionWidgets() { + for (const widget of this.extensionWidgetsAbove.values()) { + widget.dispose?.(); + } + for (const widget of this.extensionWidgetsBelow.values()) { + widget.dispose?.(); + } + this.extensionWidgetsAbove.clear(); + this.extensionWidgetsBelow.clear(); + this.renderWidgets(); + } + resetExtensionUI() { + if (this.extensionSelector) { + this.hideExtensionSelector(); + } + if (this.extensionInput) { + this.hideExtensionInput(); + } + if (this.extensionEditor) { + this.hideExtensionEditor(); + } + this.ui.hideOverlay(); + this.clearExtensionTerminalInputListeners(); + this.setExtensionFooter(undefined); + this.setExtensionHeader(undefined); + this.clearExtensionWidgets(); + this.footerDataProvider.clearExtensionStatuses(); + this.footer.invalidate(); + this.autocompleteProviderWrappers = []; + this.setCustomEditorComponent(undefined); + this.setupAutocompleteProvider(); + this.defaultEditor.onExtensionShortcut = undefined; + this.updateTerminalTitle(); + this.workingMessage = undefined; + this.workingVisible = true; + this.setWorkingIndicator(); + if (this.activeStatusIndicator?.kind === "working") { + this.activeStatusIndicator.setMessage(`${this.defaultWorkingMessage} (${keyText("app.interrupt")} to interrupt)`); + } + this.setHiddenThinkingLabel(); + } + // Maximum total widget lines to prevent viewport overflow + static MAX_WIDGET_LINES = 10; + /** + * Render all extension widgets to the widget container. + */ + renderWidgets() { + if (!this.widgetContainerAbove || !this.widgetContainerBelow) + return; + this.renderWidgetContainer(this.widgetContainerAbove, this.extensionWidgetsAbove, true, true); + this.renderWidgetContainer(this.widgetContainerBelow, this.extensionWidgetsBelow, false, false); + this.ui.requestRender(); + } + renderWidgetContainer(container, widgets, spacerWhenEmpty, leadingSpacer) { + container.clear(); + if (widgets.size === 0) { + if (spacerWhenEmpty) { + container.addChild(new Spacer(1)); + } + return; + } + if (leadingSpacer) { + container.addChild(new Spacer(1)); + } + for (const component of widgets.values()) { + container.addChild(component); + } + } + /** + * Set a custom footer component, or restore the built-in footer. + */ + setExtensionFooter(factory) { + // Dispose existing custom footer + if (this.customFooter?.dispose) { + this.customFooter.dispose(); + } + // Remove current footer from UI + if (this.customFooter) { + this.ui.removeChild(this.customFooter); + } + else { + this.ui.removeChild(this.footer); + } + if (factory) { + // Create and add custom footer, passing the data provider + this.customFooter = factory(this.ui, theme, this.footerDataProvider); + this.ui.addChild(this.customFooter); + } + else { + // Restore built-in footer + this.customFooter = undefined; + this.ui.addChild(this.footer); + } + this.ui.requestRender(); + } + /** + * Set a custom header component, or restore the built-in header. + */ + setExtensionHeader(factory) { + // Header may not be initialized yet if called during early initialization + if (!this.builtInHeader) { + return; + } + // Dispose existing custom header + if (this.customHeader?.dispose) { + this.customHeader.dispose(); + } + // Find the index of the current header in the header container + const currentHeader = this.customHeader || this.builtInHeader; + const index = this.headerContainer.children.indexOf(currentHeader); + if (factory) { + // Create and add custom header + this.customHeader = factory(this.ui, theme); + if (isExpandable(this.customHeader)) { + this.customHeader.setExpanded(this.toolOutputExpanded); + } + if (index !== -1) { + this.headerContainer.children[index] = this.customHeader; + } + else { + // If not found (e.g. builtInHeader was never added), add at the top + this.headerContainer.children.unshift(this.customHeader); + } + } + else { + // Restore built-in header + this.customHeader = undefined; + if (isExpandable(this.builtInHeader)) { + this.builtInHeader.setExpanded(this.toolOutputExpanded); + } + if (index !== -1) { + this.headerContainer.children[index] = this.builtInHeader; + } + } + this.ui.requestRender(); + } + addExtensionTerminalInputListener(handler) { + const unsubscribe = this.ui.addInputListener(handler); + this.extensionTerminalInputUnsubscribers.add(unsubscribe); + return () => { + unsubscribe(); + this.extensionTerminalInputUnsubscribers.delete(unsubscribe); + }; + } + clearExtensionTerminalInputListeners() { + for (const unsubscribe of this.extensionTerminalInputUnsubscribers) { + unsubscribe(); + } + this.extensionTerminalInputUnsubscribers.clear(); + } + /** + * Create the ExtensionUIContext for extensions. + */ + createProjectTrustContext(cwd) { + const ui = this.createExtensionUIContext(); + return { + cwd, + mode: "tui", + hasUI: true, + ui: { + select: ui.select, + confirm: ui.confirm, + input: ui.input, + notify: ui.notify, + }, + }; + } + createExtensionUIContext() { + return { + select: (title, options, opts) => this.showExtensionSelector(title, options, opts), + confirm: (title, message, opts) => this.showExtensionConfirm(title, message, opts), + input: (title, placeholder, opts) => this.showExtensionInput(title, placeholder, opts), + notify: (message, type) => this.showExtensionNotify(message, type), + onTerminalInput: (handler) => this.addExtensionTerminalInputListener(handler), + setStatus: (key, text) => this.setExtensionStatus(key, text), + setWorkingMessage: (message) => { + this.workingMessage = message; + if (this.activeStatusIndicator?.kind === "working") { + this.activeStatusIndicator.setMessage(message ?? this.defaultWorkingMessage); + } + }, + setWorkingVisible: (visible) => this.setWorkingVisible(visible), + setWorkingIndicator: (options) => this.setWorkingIndicator(options), + setHiddenThinkingLabel: (label) => this.setHiddenThinkingLabel(label), + setWidget: (key, content, options) => this.setExtensionWidget(key, content, options), + setFooter: (factory) => this.setExtensionFooter(factory), + setHeader: (factory) => this.setExtensionHeader(factory), + setTitle: (title) => this.ui.terminal.setTitle(title), + custom: (factory, options) => this.showExtensionCustom(factory, options), + pasteToEditor: (text) => this.editor.handleInput(`\x1b[200~${text}\x1b[201~`), + setEditorText: (text) => this.editor.setText(text), + getEditorText: () => this.editor.getExpandedText?.() ?? this.editor.getText(), + editor: (title, prefill) => this.showExtensionEditor(title, prefill), + addAutocompleteProvider: (factory) => { + this.autocompleteProviderWrappers.push(factory); + this.setupAutocompleteProvider(); + }, + setEditorComponent: (factory) => this.setCustomEditorComponent(factory), + getEditorComponent: () => this.editorComponentFactory, + get theme() { + return theme; + }, + getAllThemes: () => getAvailableThemesWithPaths(), + getTheme: (name) => getThemeByName(name), + setTheme: (themeOrName) => { + if (themeOrName instanceof Theme) { + return this.themeController.setThemeInstance(themeOrName); + } + const result = this.themeController.setThemeName(themeOrName); + if (result.success) { + if (this.settingsManager.getTheme() !== themeOrName) { + this.settingsManager.setTheme(themeOrName); + } + } + return result; + }, + getToolsExpanded: () => this.toolOutputExpanded, + setToolsExpanded: (expanded) => this.setToolsExpanded(expanded), + }; + } + /** + * Show a selector for extensions. + */ + showExtensionSelector(title, options, opts) { + return new Promise((resolve) => { + if (opts?.signal?.aborted) { + resolve(undefined); + return; + } + const onAbort = () => { + this.hideExtensionSelector(); + resolve(undefined); + }; + opts?.signal?.addEventListener("abort", onAbort, { once: true }); + this.extensionSelector = new ExtensionSelectorComponent(title, options, (option) => { + opts?.signal?.removeEventListener("abort", onAbort); + this.hideExtensionSelector(); + resolve(option); + }, () => { + opts?.signal?.removeEventListener("abort", onAbort); + this.hideExtensionSelector(); + resolve(undefined); + }, { tui: this.ui, timeout: opts?.timeout, onToggleToolsExpanded: () => this.toggleToolOutputExpansion() }); + this.editorContainer.clear(); + this.editorContainer.addChild(this.extensionSelector); + this.ui.setFocus(this.extensionSelector); + this.ui.requestRender(); + }); + } + /** + * Hide the extension selector. + */ + hideExtensionSelector() { + this.extensionSelector?.dispose(); + this.editorContainer.clear(); + this.editorContainer.addChild(this.editor); + this.extensionSelector = undefined; + this.ui.setFocus(this.editor); + this.ui.requestRender(); + } + /** + * Show a confirmation dialog for extensions. + */ + async showExtensionConfirm(title, message, opts) { + const result = await this.showExtensionSelector(`${title}\n${message}`, ["Yes", "No"], opts); + return result === "Yes"; + } + async promptForMissingSessionCwd(error) { + const confirmed = await this.showExtensionConfirm("Session cwd not found", formatMissingSessionCwdPrompt(error.issue)); + return confirmed ? error.issue.fallbackCwd : undefined; + } + /** + * Show a text input for extensions. + */ + showExtensionInput(title, placeholder, opts) { + return new Promise((resolve) => { + if (opts?.signal?.aborted) { + resolve(undefined); + return; + } + const onAbort = () => { + this.hideExtensionInput(); + resolve(undefined); + }; + opts?.signal?.addEventListener("abort", onAbort, { once: true }); + this.extensionInput = new ExtensionInputComponent(title, placeholder, (value) => { + opts?.signal?.removeEventListener("abort", onAbort); + this.hideExtensionInput(); + resolve(value); + }, () => { + opts?.signal?.removeEventListener("abort", onAbort); + this.hideExtensionInput(); + resolve(undefined); + }, { tui: this.ui, timeout: opts?.timeout }); + this.editorContainer.clear(); + this.editorContainer.addChild(this.extensionInput); + this.ui.setFocus(this.extensionInput); + this.ui.requestRender(); + }); + } + /** + * Hide the extension input. + */ + hideExtensionInput() { + this.extensionInput?.dispose(); + this.editorContainer.clear(); + this.editorContainer.addChild(this.editor); + this.extensionInput = undefined; + this.ui.setFocus(this.editor); + this.ui.requestRender(); + } + /** + * Show a multi-line editor for extensions (with Ctrl+G support). + */ + showExtensionEditor(title, prefill) { + return new Promise((resolve) => { + this.extensionEditor = new ExtensionEditorComponent(this.ui, this.keybindings, title, prefill, (value) => { + this.hideExtensionEditor(); + resolve(value); + }, () => { + this.hideExtensionEditor(); + resolve(undefined); + }, undefined, this.settingsManager.getExternalEditorCommand()); + this.editorContainer.clear(); + this.editorContainer.addChild(this.extensionEditor); + this.ui.setFocus(this.extensionEditor); + this.ui.requestRender(); + }); + } + /** + * Hide the extension editor. + */ + hideExtensionEditor() { + this.editorContainer.clear(); + this.editorContainer.addChild(this.editor); + this.extensionEditor = undefined; + this.ui.setFocus(this.editor); + this.ui.requestRender(); + } + /** + * Set a custom editor component from an extension. + * Pass undefined to restore the default editor. + */ + setCustomEditorComponent(factory) { + this.editorComponentFactory = factory; + // Save text from current editor before switching + const currentText = this.editor.getText(); + this.editorContainer.clear(); + if (factory) { + // Create the custom editor with tui, theme, and keybindings + const newEditor = factory(this.ui, getEditorTheme(), this.keybindings); + // Wire up callbacks from the default editor + newEditor.onSubmit = this.defaultEditor.onSubmit; + newEditor.onChange = this.defaultEditor.onChange; + // Copy text from previous editor + newEditor.setText(currentText); + // Copy appearance settings if supported + if (newEditor.borderColor !== undefined) { + newEditor.borderColor = this.defaultEditor.borderColor; + } + if (newEditor.setPaddingX !== undefined) { + newEditor.setPaddingX(this.defaultEditor.getPaddingX()); + } + // Set autocomplete if supported + if (newEditor.setAutocompleteProvider && this.autocompleteProvider) { + newEditor.setAutocompleteProvider(this.autocompleteProvider); + } + // If extending CustomEditor, copy app-level handlers + // Use duck typing since instanceof fails across jiti module boundaries + const customEditor = newEditor; + if ("actionHandlers" in customEditor && customEditor.actionHandlers instanceof Map) { + if (!customEditor.onEscape) { + customEditor.onEscape = () => this.defaultEditor.onEscape?.(); + } + if (!customEditor.onCtrlD) { + customEditor.onCtrlD = () => this.defaultEditor.onCtrlD?.(); + } + if (!customEditor.onPasteImage) { + customEditor.onPasteImage = () => this.defaultEditor.onPasteImage?.(); + } + if (!customEditor.onExtensionShortcut) { + customEditor.onExtensionShortcut = (data) => this.defaultEditor.onExtensionShortcut?.(data); + } + // Copy action handlers (clear, suspend, model switching, etc.) + for (const [action, handler] of this.defaultEditor.actionHandlers) { + customEditor.actionHandlers.set(action, handler); + } + } + this.editor = newEditor; + } + else { + // Restore default editor with text from custom editor + this.defaultEditor.setText(currentText); + this.editor = this.defaultEditor; + } + this.editorContainer.addChild(this.editor); + this.ui.setFocus(this.editor); + this.ui.requestRender(); + } + /** + * Show a notification for extensions. + */ + showExtensionNotify(message, type) { + if (type === "error") { + this.showError(message); + } + else if (type === "warning") { + this.showWarning(message); + } + else { + this.showStatus(message); + } + } + /** Show a custom component with keyboard focus. Overlay mode renders on top of existing content. */ + async showExtensionCustom(factory, options) { + const savedText = this.editor.getText(); + const isOverlay = options?.overlay ?? false; + const restoreEditor = () => { + this.editorContainer.clear(); + this.editorContainer.addChild(this.editor); + this.editor.setText(savedText); + this.ui.setFocus(this.editor); + this.ui.requestRender(); + }; + return new Promise((resolve, reject) => { + let component; + let closed = false; + const close = (result) => { + if (closed) + return; + closed = true; + if (isOverlay) + this.ui.hideOverlay(); + else + restoreEditor(); + // Note: both branches above already call requestRender + resolve(result); + try { + component?.dispose?.(); + } + catch { + /* ignore dispose errors */ + } + }; + Promise.resolve(factory(this.ui, theme, this.keybindings, close)) + .then((c) => { + if (closed) + return; + component = c; + if (isOverlay) { + // Resolve overlay options - can be static or dynamic function + const resolveOptions = () => { + if (options?.overlayOptions) { + const opts = typeof options.overlayOptions === "function" + ? options.overlayOptions() + : options.overlayOptions; + return opts; + } + // Fallback: use component's width property if available + const w = component.width; + return w ? { width: w } : undefined; + }; + const handle = this.ui.showOverlay(component, resolveOptions()); + // Expose handle to caller for visibility control + options?.onHandle?.(handle); + } + else { + this.editorContainer.clear(); + this.editorContainer.addChild(component); + this.ui.setFocus(component); + this.ui.requestRender(); + } + }) + .catch((err) => { + if (closed) + return; + if (!isOverlay) + restoreEditor(); + reject(err); + }); + }); + } + /** + * Show an extension error in the UI. + */ + showExtensionError(extensionPath, error, stack) { + const errorMsg = `Extension "${extensionPath}" error: ${error}`; + const errorText = new Text(theme.fg("error", errorMsg), 1, 0); + this.chatContainer.addChild(errorText); + if (stack) { + // Show stack trace in dim color, indented + const stackLines = stack + .split("\n") + .slice(1) // Skip first line (duplicates error message) + .map((line) => theme.fg("dim", ` ${line.trim()}`)) + .join("\n"); + if (stackLines) { + this.chatContainer.addChild(new Text(stackLines, 1, 0)); + } + } + this.ui.requestRender(); + } + // ========================================================================= + // Key Handlers + // ========================================================================= + setupKeyHandlers() { + // Set up handlers on defaultEditor - they use this.editor for text access + // so they work correctly regardless of which editor is active + this.defaultEditor.onEscape = () => { + if (this.session.isStreaming) { + this.restoreQueuedMessagesToEditor({ abort: true }); + } + else if (this.session.isBashRunning) { + this.session.abortBash(); + } + else if (this.isBashMode) { + this.editor.setText(""); + this.isBashMode = false; + this.updateEditorBorderColor(); + } + else if (!this.editor.getText().trim()) { + // Double-escape with empty editor triggers /tree, /fork, or nothing based on setting + const action = this.settingsManager.getDoubleEscapeAction(); + if (action !== "none") { + const now = Date.now(); + if (now - this.lastEscapeTime < 500) { + if (action === "tree") { + this.showTreeSelector(); + } + else { + this.showUserMessageSelector(); + } + this.lastEscapeTime = 0; + } + else { + this.lastEscapeTime = now; + } + } + } + }; + // Register app action handlers + this.defaultEditor.onAction("app.clear", () => this.handleCtrlC()); + this.defaultEditor.onCtrlD = () => this.handleCtrlD(); + this.defaultEditor.onAction("app.suspend", () => this.handleCtrlZ()); + this.defaultEditor.onAction("app.thinking.cycle", () => this.cycleThinkingLevel()); + this.defaultEditor.onAction("app.model.cycleForward", () => this.cycleModel("forward")); + this.defaultEditor.onAction("app.model.cycleBackward", () => this.cycleModel("backward")); + // Global debug handler on TUI (works regardless of focus) + this.ui.onDebug = () => this.handleDebugCommand(); + this.defaultEditor.onAction("app.model.select", () => this.showModelSelector()); + this.defaultEditor.onAction("app.tools.expand", () => this.toggleToolOutputExpansion()); + this.defaultEditor.onAction("app.thinking.toggle", () => this.toggleThinkingBlockVisibility()); + this.defaultEditor.onAction("app.editor.external", () => void this.handleOpenExternalEditor()); + this.defaultEditor.onAction("app.message.copy", () => void this.handleCopyCommand()); + this.defaultEditor.onAction("app.message.followUp", () => this.handleFollowUp()); + this.defaultEditor.onAction("app.message.dequeue", () => this.handleDequeue()); + this.defaultEditor.onAction("app.session.new", () => this.handleClearCommand()); + this.defaultEditor.onAction("app.session.tree", () => this.showTreeSelector()); + this.defaultEditor.onAction("app.session.fork", () => this.showUserMessageSelector()); + this.defaultEditor.onAction("app.session.resume", () => this.showSessionSelector()); + this.defaultEditor.onChange = (text) => { + const wasBashMode = this.isBashMode; + this.isBashMode = text.trimStart().startsWith("!"); + if (wasBashMode !== this.isBashMode) { + this.updateEditorBorderColor(); + } + }; + // Handle clipboard paste (triggered on Ctrl+V). Images are attached by path; + // otherwise, paste plain text from the system clipboard. + this.defaultEditor.onPasteImage = () => { + void this.handleClipboardPaste(); + }; + } + async handleClipboardPaste() { + try { + const image = await readClipboardImage(); + if (image) { + const tmpDir = os.tmpdir(); + const ext = extensionForImageMimeType(image.mimeType) ?? "png"; + const fileName = `pi-clipboard-${crypto.randomUUID()}.${ext}`; + const filePath = path.join(tmpDir, fileName); + fs.writeFileSync(filePath, Buffer.from(image.bytes)); + this.editor.insertTextAtCursor?.(filePath); + this.ui.requestRender(); + return; + } + const text = await readClipboardText(); + if (text) { + this.editor.insertTextAtCursor?.(text); + this.ui.requestRender(); + } + } + catch { + // Silently ignore clipboard errors (may not have permission, etc.) + } + } + setupEditorSubmitHandler() { + this.defaultEditor.onSubmit = async (text) => { + text = text.trim(); + if (!text) + return; + // Handle commands + if (text === "/settings") { + this.showSettingsSelector(); + this.editor.setText(""); + return; + } + if (text === "/scoped-models") { + this.editor.setText(""); + await this.showModelsSelector(); + return; + } + if (text === "/model" || text.startsWith("/model ")) { + const searchTerm = text.startsWith("/model ") ? text.slice(7).trim() : undefined; + this.editor.setText(""); + await this.handleModelCommand(searchTerm); + return; + } + if (text === "/export" || text.startsWith("/export ")) { + await this.handleExportCommand(text); + this.editor.setText(""); + return; + } + if (text === "/import" || text.startsWith("/import ")) { + await this.handleImportCommand(text); + this.editor.setText(""); + return; + } + if (text === "/share") { + await this.handleShareCommand(); + this.editor.setText(""); + return; + } + if (text === "/copy") { + await this.handleCopyCommand(); + this.editor.setText(""); + return; + } + if (text === "/name" || text.startsWith("/name ")) { + this.handleNameCommand(text); + this.editor.setText(""); + return; + } + if (text === "/session") { + this.handleSessionCommand(); + this.editor.setText(""); + return; + } + if (text === "/changelog") { + this.handleChangelogCommand(); + this.editor.setText(""); + return; + } + if (text === "/hotkeys") { + this.handleHotkeysCommand(); + this.editor.setText(""); + return; + } + if (text === "/fork") { + this.showUserMessageSelector(); + this.editor.setText(""); + return; + } + if (text === "/clone") { + this.editor.setText(""); + await this.handleCloneCommand(); + return; + } + if (text === "/tree") { + this.showTreeSelector(); + this.editor.setText(""); + return; + } + if (text === "/trust") { + this.showTrustSelector(); + this.editor.setText(""); + return; + } + if (text === "/login" || text.startsWith("/login ")) { + const providerRef = text.startsWith("/login ") ? text.slice(7).trim() : undefined; + this.editor.setText(""); + await this.handleLoginCommand(providerRef); + return; + } + if (text === "/logout") { + this.showOAuthSelector("logout"); + this.editor.setText(""); + return; + } + if (text === "/new") { + this.editor.setText(""); + await this.handleClearCommand(); + return; + } + if (text === "/compact" || text.startsWith("/compact ")) { + const customInstructions = text.startsWith("/compact ") ? text.slice(9).trim() : undefined; + this.editor.setText(""); + await this.handleCompactCommand(customInstructions); + return; + } + if (text === "/reload") { + this.editor.setText(""); + await this.handleReloadCommand(); + return; + } + if (text === "/debug") { + this.handleDebugCommand(); + this.editor.setText(""); + return; + } + if (text === "/arminsayshi") { + this.handleArminSaysHi(); + this.editor.setText(""); + return; + } + if (text === "/dementedelves") { + this.handleDementedDelves(); + this.editor.setText(""); + return; + } + if (text === "/resume") { + this.showSessionSelector(); + this.editor.setText(""); + return; + } + if (text === "/quit") { + this.editor.setText(""); + await this.shutdown(); + return; + } + // Handle bash command (! for normal, !! for excluded from context) + if (text.startsWith("!")) { + const isExcluded = text.startsWith("!!"); + const command = isExcluded ? text.slice(2).trim() : text.slice(1).trim(); + if (command) { + if (this.session.isBashRunning) { + this.showWarning("A bash command is already running. Press Esc to cancel it first."); + this.editor.setText(text); + return; + } + this.editor.addToHistory?.(text); + await this.handleBashCommand(command, isExcluded); + this.isBashMode = false; + this.updateEditorBorderColor(); + return; + } + } + // Queue input during compaction (extension commands execute immediately) + if (this.session.isCompacting) { + if (this.isExtensionCommand(text)) { + this.editor.addToHistory?.(text); + this.editor.setText(""); + await this.session.prompt(text); + } + else { + this.queueCompactionMessage(text, "steer"); + } + return; + } + // If streaming, use prompt() with steer behavior + // This handles extension commands (execute immediately), prompt template expansion, and queueing + if (this.session.isStreaming) { + this.editor.addToHistory?.(text); + this.editor.setText(""); + await this.session.prompt(text, { streamingBehavior: "steer" }); + this.updatePendingMessagesDisplay(); + this.ui.requestRender(); + return; + } + // Normal message submission + // First, move any pending bash components to chat + this.flushPendingBashComponents(); + if (this.onInputCallback) { + this.onInputCallback(text); + } + else { + this.pendingUserInputs.push(text); + } + this.editor.addToHistory?.(text); + }; + } + subscribeToAgent() { + this.unsubscribe = this.session.subscribe(async (event) => { + await this.handleEvent(event); + }); + } + async handleEvent(event) { + if (!this.isInitialized) { + await this.init(); + } + this.footer.invalidate(); + switch (event.type) { + case "agent_start": + this.pendingTools.clear(); + if (this.settingsManager.getShowTerminalProgress()) { + this.ui.terminal.setProgress(true); + } + // Restore main escape handler if retry handler is still active + // (retry success event fires later, but we need main handler now) + if (this.retryEscapeHandler) { + this.defaultEditor.onEscape = this.retryEscapeHandler; + this.retryEscapeHandler = undefined; + } + if (this.workingVisible) { + this.showStatusIndicator(new WorkingStatusIndicator(this.ui, this.workingMessage ?? this.defaultWorkingMessage, this.workingIndicatorOptions)); + } + else { + this.clearStatusIndicator(); + } + this.ui.requestRender(); + break; + case "queue_update": + this.updatePendingMessagesDisplay(); + this.ui.requestRender(); + break; + case "entry_appended": + if (event.entry.type === "custom") { + this.addCustomEntryToChat(event.entry); + this.ui.requestRender(); + } + break; + case "session_info_changed": + this.updateTerminalTitle(); + this.footer.invalidate(); + this.ui.requestRender(); + break; + case "thinking_level_changed": + this.footer.invalidate(); + this.updateEditorBorderColor(); + break; + case "message_start": + if (event.message.role === "custom") { + this.addMessageToChat(event.message); + this.ui.requestRender(); + } + else if (event.message.role === "user") { + this.addMessageToChat(event.message); + this.updatePendingMessagesDisplay(); + this.ui.requestRender(); + } + else if (event.message.role === "assistant") { + this.streamingComponent = new AssistantMessageComponent(undefined, this.hideThinkingBlock, this.getMarkdownThemeWithSettings(), this.hiddenThinkingLabel, this.outputPad); + this.streamingMessage = event.message; + this.chatContainer.addChild(this.streamingComponent); + this.streamingComponent.updateContent(this.streamingMessage); + this.ui.requestRender(); + } + break; + case "message_update": + if (this.streamingComponent && event.message.role === "assistant") { + this.streamingMessage = event.message; + this.streamingComponent.updateContent(this.streamingMessage); + for (const content of this.streamingMessage.content) { + if (content.type === "toolCall") { + if (!this.pendingTools.has(content.id)) { + const component = new ToolExecutionComponent(content.name, content.id, content.arguments, { + showImages: this.settingsManager.getShowImages(), + imageWidthCells: this.settingsManager.getImageWidthCells(), + }, this.getRegisteredToolDefinition(content.name), this.ui, this.sessionManager.getCwd()); + component.setExpanded(this.toolOutputExpanded); + this.chatContainer.addChild(component); + this.pendingTools.set(content.id, component); + } + else { + const component = this.pendingTools.get(content.id); + if (component) { + component.updateArgs(content.arguments); + } + } + } + } + this.ui.requestRender(); + } + break; + case "message_end": + if (event.message.role === "user") + break; + if (this.streamingComponent && event.message.role === "assistant") { + this.streamingMessage = event.message; + let errorMessage; + if (this.streamingMessage.stopReason === "aborted") { + const retryAttempt = this.session.retryAttempt; + errorMessage = + retryAttempt > 0 + ? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? "s" : ""}` + : "Operation aborted"; + this.streamingMessage.errorMessage = errorMessage; + } + this.streamingComponent.updateContent(this.streamingMessage); + if (this.streamingMessage.stopReason === "aborted" || this.streamingMessage.stopReason === "error") { + if (!errorMessage) { + errorMessage = this.streamingMessage.errorMessage || "Error"; + } + for (const [, component] of this.pendingTools.entries()) { + component.updateResult({ + content: [{ type: "text", text: errorMessage }], + isError: true, + }); + } + this.pendingTools.clear(); + } + else { + // Args are now complete - trigger diff computation for edit tools + for (const [, component] of this.pendingTools.entries()) { + component.setArgsComplete(); + } + this.maybeShowCacheMissNotice(this.streamingMessage); + } + this.streamingComponent = undefined; + this.streamingMessage = undefined; + this.footer.invalidate(); + } + this.ui.requestRender(); + break; + case "bash_execution_update": + // The bash execution callback handles TUI output rendering. + break; + case "tool_execution_start": { + let component = this.pendingTools.get(event.toolCallId); + if (!component) { + component = new ToolExecutionComponent(event.toolName, event.toolCallId, event.args, { + showImages: this.settingsManager.getShowImages(), + imageWidthCells: this.settingsManager.getImageWidthCells(), + }, this.getRegisteredToolDefinition(event.toolName), this.ui, this.sessionManager.getCwd()); + component.setExpanded(this.toolOutputExpanded); + this.chatContainer.addChild(component); + this.pendingTools.set(event.toolCallId, component); + } + component.markExecutionStarted(); + this.ui.requestRender(); + break; + } + case "tool_execution_update": { + const component = this.pendingTools.get(event.toolCallId); + if (component) { + component.updateResult({ ...event.partialResult, isError: false }, true); + this.ui.requestRender(); + } + break; + } + case "tool_execution_end": { + const component = this.pendingTools.get(event.toolCallId); + if (component) { + component.updateResult({ ...event.result, isError: event.isError }); + this.pendingTools.delete(event.toolCallId); + this.ui.requestRender(); + } + break; + } + case "agent_end": + if (this.settingsManager.getShowTerminalProgress()) { + this.ui.terminal.setProgress(false); + } + this.clearStatusIndicator("working"); + if (this.streamingComponent) { + this.chatContainer.removeChild(this.streamingComponent); + this.streamingComponent = undefined; + this.streamingMessage = undefined; + } + this.pendingTools.clear(); + this.ui.requestRender(); + break; + case "agent_settled": + await this.checkShutdownRequested(); + break; + case "compaction_start": { + if (this.settingsManager.getShowTerminalProgress()) { + this.ui.terminal.setProgress(true); + } + // Keep editor active; submissions are queued during compaction. + this.autoCompactionEscapeHandler = this.defaultEditor.onEscape; + this.defaultEditor.onEscape = () => { + this.session.abortCompaction(); + }; + this.showStatusIndicator(new CompactionStatusIndicator(this.ui, event.reason)); + this.ui.requestRender(); + break; + } + case "compaction_end": { + if (this.settingsManager.getShowTerminalProgress()) { + this.ui.terminal.setProgress(false); + } + if (this.autoCompactionEscapeHandler) { + this.defaultEditor.onEscape = this.autoCompactionEscapeHandler; + this.autoCompactionEscapeHandler = undefined; + } + this.clearStatusIndicator("compaction"); + if (event.aborted) { + if (event.reason === "manual") { + this.showError("Compaction cancelled"); + } + else { + this.showStatus("Auto-compaction cancelled"); + } + } + else if (event.result) { + this.chatContainer.clear(); + this.rebuildChatFromMessages(); + this.addMessageToChat(createCompactionSummaryMessage(event.result.summary, event.result.tokensBefore, new Date().toISOString())); + this.footer.invalidate(); + } + else if (event.errorMessage) { + if (event.reason === "manual") { + this.showError(event.errorMessage); + } + else { + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Text(theme.fg("error", event.errorMessage), 1, 0)); + } + } + void this.flushCompactionQueue({ willRetry: event.willRetry }); + this.ui.requestRender(); + break; + } + case "auto_retry_start": { + // Set up escape to abort retry + this.retryEscapeHandler = this.defaultEditor.onEscape; + this.defaultEditor.onEscape = () => { + this.session.abortRetry(); + }; + this.showStatusIndicator(new RetryStatusIndicator(this.ui, event.attempt, event.maxAttempts, event.delayMs)); + this.ui.requestRender(); + break; + } + case "auto_retry_end": { + // Restore escape handler + if (this.retryEscapeHandler) { + this.defaultEditor.onEscape = this.retryEscapeHandler; + this.retryEscapeHandler = undefined; + } + this.clearStatusIndicator("retry"); + // Show error only on final failure (success shows normal response) + if (!event.success) { + this.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError || "Unknown error"}`); + } + this.ui.requestRender(); + break; + } + case "summarization_retry_scheduled": { + this.showError(event.errorMessage); + this.showStatusIndicator(new RetryStatusIndicator(this.ui, event.attempt, event.maxAttempts, event.delayMs)); + this.ui.requestRender(); + break; + } + case "summarization_retry_attempt_start": { + this.clearStatusIndicator("retry"); + if (event.source === "branchSummary") { + this.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui)); + } + else { + this.showStatusIndicator(new CompactionStatusIndicator(this.ui, event.reason)); + } + this.ui.requestRender(); + break; + } + case "summarization_retry_finished": { + this.clearStatusIndicator("retry"); + this.ui.requestRender(); + break; + } + } + } + /** Extract text content from a user message */ + getUserMessageText(message) { + if (message.role !== "user") + return ""; + const textBlocks = typeof message.content === "string" + ? [{ type: "text", text: message.content }] + : message.content.filter((c) => c.type === "text"); + return textBlocks.map((c) => c.text).join(""); + } + /** + * Show a status message in the chat. + * + * If multiple status messages are emitted back-to-back (without anything else being added to the chat), + * we update the previous status line instead of appending new ones to avoid log spam. + */ + showStatus(message) { + const children = this.chatContainer.children; + const last = children.length > 0 ? children[children.length - 1] : undefined; + const secondLast = children.length > 1 ? children[children.length - 2] : undefined; + if (last && secondLast && last === this.lastStatusText && secondLast === this.lastStatusSpacer) { + this.lastStatusText.setText(theme.fg("dim", message)); + this.ui.requestRender(); + return; + } + const spacer = new Spacer(1); + const text = new Text(theme.fg("dim", message), 1, 0); + this.chatContainer.addChild(spacer); + this.chatContainer.addChild(text); + this.lastStatusSpacer = spacer; + this.lastStatusText = text; + this.ui.requestRender(); + } + addCustomEntryToChat(entry) { + const renderer = this.session.extensionRunner.getEntryRenderer(entry.customType); + if (!renderer) { + return; + } + const component = new CustomEntryComponent(entry, renderer); + component.setExpanded(this.toolOutputExpanded); + if (!component.hasContent()) { + return; + } + if (this.streamingComponent) { + const streamingIndex = this.chatContainer.children.indexOf(this.streamingComponent); + if (streamingIndex >= 0) { + this.chatContainer.children.splice(streamingIndex, 0, component); + return; + } + } + this.chatContainer.addChild(component); + } + addMessageToChat(message, options) { + switch (message.role) { + case "bashExecution": { + const component = new BashExecutionComponent(message.command, this.ui, message.excludeFromContext); + if (message.output) { + component.appendOutput(message.output); + } + component.setComplete(message.exitCode, message.cancelled, message.truncated ? { truncated: true } : undefined, message.fullOutputPath); + this.chatContainer.addChild(component); + break; + } + case "custom": { + if (message.display) { + const renderer = this.session.extensionRunner.getMessageRenderer(message.customType); + const component = new CustomMessageComponent(message, renderer, this.getMarkdownThemeWithSettings(), this.outputPad); + component.setExpanded(this.toolOutputExpanded); + this.chatContainer.addChild(component); + } + break; + } + case "compactionSummary": { + this.chatContainer.addChild(new Spacer(1)); + const component = new CompactionSummaryMessageComponent(message, this.getMarkdownThemeWithSettings()); + component.setExpanded(this.toolOutputExpanded); + this.chatContainer.addChild(component); + break; + } + case "branchSummary": { + this.chatContainer.addChild(new Spacer(1)); + const component = new BranchSummaryMessageComponent(message, this.getMarkdownThemeWithSettings()); + component.setExpanded(this.toolOutputExpanded); + this.chatContainer.addChild(component); + break; + } + case "user": { + const textContent = this.getUserMessageText(message); + if (textContent) { + if (this.chatContainer.children.length > 0) { + this.chatContainer.addChild(new Spacer(1)); + } + const skillBlock = parseSkillBlock(textContent); + if (skillBlock) { + // Render skill block (collapsible) + const component = new SkillInvocationMessageComponent(skillBlock, this.getMarkdownThemeWithSettings()); + component.setExpanded(this.toolOutputExpanded); + this.chatContainer.addChild(component); + // Render user message separately if present + if (skillBlock.userMessage) { + this.chatContainer.addChild(new Spacer(1)); + const userComponent = new UserMessageComponent(skillBlock.userMessage, this.getMarkdownThemeWithSettings(), this.outputPad); + this.chatContainer.addChild(userComponent); + } + } + else { + const userComponent = new UserMessageComponent(textContent, this.getMarkdownThemeWithSettings(), this.outputPad); + this.chatContainer.addChild(userComponent); + } + if (options?.populateHistory) { + this.editor.addToHistory?.(textContent); + } + } + break; + } + case "assistant": { + const assistantComponent = new AssistantMessageComponent(message, this.hideThinkingBlock, this.getMarkdownThemeWithSettings(), this.hiddenThinkingLabel, this.outputPad); + this.chatContainer.addChild(assistantComponent); + break; + } + case "toolResult": { + // Tool results are rendered inline with tool calls, handled separately + break; + } + default: { + const _exhaustive = message; + } + } + } + renderSessionItems(items, options = {}) { + this.pendingTools.clear(); + const renderedPendingTools = new Map(); + // Cache-miss notices are not persisted; re-derive them from the full entry + // list and re-inject them after the assistant messages that paid for them. + const cacheMisses = this.settingsManager.getShowCacheMissNotices() + ? collectCacheMisses(this.sessionManager.getEntries(), this.session.modelRuntime) + : new Map(); + if (options.updateFooter) { + this.footer.invalidate(); + this.updateEditorBorderColor(); + } + for (const item of items) { + if (isCustomSessionEntry(item)) { + this.addCustomEntryToChat(item); + continue; + } + const message = item; + // Assistant messages need special handling for tool calls + if (message.role === "assistant") { + this.addMessageToChat(message); + // Render tool call components + for (const content of message.content) { + if (content.type === "toolCall") { + const component = new ToolExecutionComponent(content.name, content.id, content.arguments, { + showImages: this.settingsManager.getShowImages(), + imageWidthCells: this.settingsManager.getImageWidthCells(), + }, this.getRegisteredToolDefinition(content.name), this.ui, this.sessionManager.getCwd()); + component.setExpanded(this.toolOutputExpanded); + this.chatContainer.addChild(component); + if (message.stopReason === "aborted" || message.stopReason === "error") { + let errorMessage; + if (message.stopReason === "aborted") { + const retryAttempt = this.session.retryAttempt; + errorMessage = + retryAttempt > 0 + ? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? "s" : ""}` + : "Operation aborted"; + } + else { + errorMessage = message.errorMessage || "Error"; + } + component.updateResult({ content: [{ type: "text", text: errorMessage }], isError: true }); + } + else { + renderedPendingTools.set(content.id, component); + } + } + } + if (message.stopReason !== "aborted" && message.stopReason !== "error") { + const miss = cacheMisses.get(message); + if (miss) + this.addCacheMissNotice(miss); + } + } + else if (message.role === "toolResult") { + // Match tool results to pending tool components + const component = renderedPendingTools.get(message.toolCallId); + if (component) { + component.updateResult(message); + renderedPendingTools.delete(message.toolCallId); + } + } + else { + // All other messages use standard rendering + this.addMessageToChat(message, options); + } + } + for (const [toolCallId, component] of renderedPendingTools) { + this.pendingTools.set(toolCallId, component); + } + this.ui.requestRender(); + } + /** + * Render session entries to chat. Used for initial load and rebuild after compaction. + * @param entries Compaction-aware session entries to render + * @param options.updateFooter Update footer state + * @param options.populateHistory Add user messages to editor history + */ + renderSessionEntries(entries, options = {}) { + const items = entries.flatMap((entry) => { + if (entry.type === "custom") { + return [entry]; + } + return sessionEntryToContextMessages(entry); + }); + this.renderSessionItems(items, options); + } + /** + * Show a transcript notice when a completed assistant message paid for a + * significant cache miss. Only states observable facts: the miss itself, + * a model switch, or an idle gap past the cache TTL. + */ + maybeShowCacheMissNotice(message) { + if (!this.settingsManager.getShowCacheMissNotices()) + return; + // Entries don't contain `message` yet: message_end fires before persistence. + const miss = detectCacheMiss(this.sessionManager.getEntries(), message, this.session.modelRuntime); + if (miss) + this.addCacheMissNotice(miss); + } + addCacheMissNotice(miss) { + if (miss.missedTokens < 20_000 && miss.missedCost < 0.1) + return; + const cost = miss.missedCost >= 0.01 ? ` (~$${miss.missedCost.toFixed(2)})` : ""; + const reBilled = `${formatTokens(miss.missedTokens)} tokens re-billed${cost}`; + let label = "Cache miss"; + if (miss.modelChanged) { + label = "Cache miss after model switch"; + } + else if (miss.idleMs >= CACHE_TTL_MS) { + label = `Cache miss after ${Math.round(miss.idleMs / 60_000)}m idle`; + } + const text = theme.fg("warning", `${label}: ${reBilled}`); + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Text(text, 1, 0)); + } + renderInitialMessages() { + const entries = this.sessionManager.buildContextEntries(); + this.renderSessionEntries(entries, { + updateFooter: true, + populateHistory: true, + }); + this.renderProjectTrustWarningIfNeeded(); + // Show compaction info if session was compacted + const allEntries = this.sessionManager.getEntries(); + const compactionCount = allEntries.filter((e) => e.type === "compaction").length; + if (compactionCount > 0) { + const times = compactionCount === 1 ? "1 time" : `${compactionCount} times`; + this.showStatus(`Session compacted ${times}`); + } + } + renderProjectTrustWarningIfNeeded() { + if (this.settingsManager.isProjectTrusted() || !hasTrustRequiringProjectResources(this.sessionManager.getCwd())) { + return; + } + if (this.chatContainer.children.length > 0) { + this.chatContainer.addChild(new Spacer(1)); + } + this.chatContainer.addChild(new Text(theme.fg("warning", `This project is not trusted. Project ${CONFIG_DIR_NAME} resources and packages are ignored. Use /trust to save a trust decision, then restart pi.`), 1, 0)); + } + async getUserInput() { + const queuedInput = this.pendingUserInputs.shift(); + if (queuedInput !== undefined) { + return queuedInput; + } + return new Promise((resolve) => { + this.onInputCallback = (text) => { + this.onInputCallback = undefined; + resolve(text); + }; + }); + } + rebuildChatFromMessages() { + this.chatContainer.clear(); + this.renderSessionEntries(this.sessionManager.buildContextEntries()); + } + // ========================================================================= + // Key handlers + // ========================================================================= + handleCtrlC() { + const now = Date.now(); + if (now - this.lastSigintTime < 500) { + void this.shutdown(); + } + else { + this.clearEditor(); + this.lastSigintTime = now; + } + } + handleCtrlD() { + // Only called when editor is empty (enforced by CustomEditor) + void this.shutdown(); + } + /** + * Gracefully shutdown the agent. + * Stops the TUI before emitting shutdown events so extension UI cleanup cannot + * repaint the final frame while the process is exiting. + */ + isShuttingDown = false; + async shutdown(options) { + if (this.isShuttingDown) + return; + this.isShuttingDown = true; + // Keep signal handlers registered until terminal cleanup has completed. + // `signal-exit` checks the listener list during the same SIGTERM/SIGHUP + // dispatch and re-sends the signal if only its own listeners remain. + if (options?.fromSignal) { + // Signal-triggered shutdown (SIGTERM/SIGHUP). Emit extension cleanup + // (session_shutdown) BEFORE touching the terminal. Extension teardown + // such as removing sockets does not write to the tty, so it must not be + // skipped if a later terminal-restore write fails on a dead or stalled + // terminal. If the terminal is gone, the restore writes below emit EIO, + // which the stdout/stderr error handler turns into emergencyTerminalExit; + // the render loop is already idle, so this cannot hot-spin (see #4144). + await this.runtimeHost.dispose(); + this.themeController.disableAutoSync(); + await this.ui.terminal.drainInput(1000); + this.stop(); + process.exit(0); + } + // Interactive quit (Ctrl+D, Ctrl+C, /quit, extension shutdown()). Stop the + // TUI before emitting shutdown events so extension UI cleanup cannot repaint + // the final frame while the process is exiting. + // Drain any in-flight Kitty key release events before stopping. + // This prevents escape sequences from leaking to the parent shell over slow SSH. + this.themeController.disableAutoSync(); + await this.ui.terminal.drainInput(1000); + this.stop(); + await this.runtimeHost.dispose(); + const resumeCommand = formatResumeCommand(this.sessionManager); + if (resumeCommand) { + process.stdout.write(`${chalk.dim("To resume this session:")} ${resumeCommand}\n`); + } + process.exit(0); + } + emergencyTerminalExit() { + this.isShuttingDown = true; + this.unregisterSignalHandlers(); + killTrackedDetachedChildren(); + // The terminal is gone. Do not run normal shutdown because TUI and + // extension cleanup can write restore sequences and re-trigger EIO. + process.exit(129); + } + /** + * Last-resort handler for uncaught exceptions. The TUI puts stdin into raw + * mode and hides the cursor; without this handler, an uncaught throw from + * anywhere (e.g. an extension's async `ChildProcess.on("exit")` callback) + * tears down the process while leaving the terminal in raw mode with no + * cursor, requiring `stty sane && reset` to recover. + * + * Unlike emergencyTerminalExit, the terminal is still alive here, so we + * call ui.stop() to restore cooked mode, the cursor, and disable bracketed + * paste / Kitty / modifyOtherKeys sequences. + */ + uncaughtCrash(error) { + if (this.isShuttingDown) { + process.exit(1); + } + this.isShuttingDown = true; + try { + this.unregisterSignalHandlers(); + } + catch { } + try { + killTrackedDetachedChildren(); + } + catch { } + try { + this.ui.stop(); + } + catch { } + console.error("pi exiting due to uncaughtException:"); + console.error(error); + process.exit(1); + } + /** + * Check if shutdown was requested and perform shutdown if so. + */ + async checkShutdownRequested() { + if (!this.shutdownRequested) + return; + await this.shutdown(); + } + registerSignalHandlers() { + this.unregisterSignalHandlers(); + const signals = ["SIGTERM"]; + if (process.platform !== "win32") { + signals.push("SIGHUP"); + } + for (const signal of signals) { + const handler = () => { + // SIGHUP no longer hard-exits: graceful shutdown emits session_shutdown + // first, then attempts terminal restore. A genuinely dead terminal + // surfaces as an EIO on the restore writes, which the stdout/stderr + // error handler converts into emergencyTerminalExit (see #4144, #5080). + killTrackedDetachedChildren(); + void this.shutdown({ fromSignal: true }); + }; + process.prependListener(signal, handler); + this.signalCleanupHandlers.push(() => process.off(signal, handler)); + } + const terminalErrorHandler = (error) => { + if (isDeadTerminalError(error)) { + this.emergencyTerminalExit(); + } + throw error; + }; + process.stdout.on("error", terminalErrorHandler); + process.stderr.on("error", terminalErrorHandler); + this.signalCleanupHandlers.push(() => process.stdout.off("error", terminalErrorHandler)); + this.signalCleanupHandlers.push(() => process.stderr.off("error", terminalErrorHandler)); + // Restore the terminal before the process dies on any uncaught throw. + // Without this, an unhandled exception from extension code (or anywhere + // in pi) leaves the terminal in raw mode with no cursor. + const uncaughtExceptionHandler = (error) => this.uncaughtCrash(error); + process.prependListener("uncaughtException", uncaughtExceptionHandler); + this.signalCleanupHandlers.push(() => process.off("uncaughtException", uncaughtExceptionHandler)); + } + unregisterSignalHandlers() { + for (const cleanup of this.signalCleanupHandlers) { + cleanup(); + } + this.signalCleanupHandlers = []; + } + handleCtrlZ() { + if (process.platform === "win32") { + this.showStatus("Suspend to background is not supported on Windows"); + return; + } + // Keep the event loop alive while suspended. Without this, stopping the TUI + // can leave Node with no ref'ed handles, causing the process to exit on fg + // before the SIGCONT handler gets a chance to restore the terminal. + const suspendKeepAlive = setInterval(() => { }, 2 ** 30); + // Ignore SIGINT while suspended so Ctrl+C in the terminal does not + // kill the backgrounded process. The handler is removed on resume. + const ignoreSigint = () => { }; + process.on("SIGINT", ignoreSigint); + // Set up handler to restore TUI when resumed + process.once("SIGCONT", () => { + clearInterval(suspendKeepAlive); + process.removeListener("SIGINT", ignoreSigint); + this.ui.start(); + this.ui.requestRender(true); + }); + try { + // Stop the TUI (restore terminal to normal mode) + this.ui.stop(); + // Send SIGTSTP to process group (pid=0 means all processes in group) + process.kill(0, "SIGTSTP"); + } + catch (error) { + clearInterval(suspendKeepAlive); + process.removeListener("SIGINT", ignoreSigint); + throw error; + } + } + async handleFollowUp() { + const text = (this.editor.getExpandedText?.() ?? this.editor.getText()).trim(); + if (!text) + return; + // Queue input during compaction (extension commands execute immediately) + if (this.session.isCompacting) { + if (this.isExtensionCommand(text)) { + this.editor.addToHistory?.(text); + this.editor.setText(""); + await this.session.prompt(text); + } + else { + this.queueCompactionMessage(text, "followUp"); + } + return; + } + // Alt+Enter queues a follow-up message (waits until agent finishes) + // This handles extension commands (execute immediately), prompt template expansion, and queueing + if (this.session.isStreaming) { + this.editor.addToHistory?.(text); + this.editor.setText(""); + await this.session.prompt(text, { streamingBehavior: "followUp" }); + this.updatePendingMessagesDisplay(); + this.ui.requestRender(); + } + // If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit) + else if (this.editor.onSubmit) { + this.editor.setText(""); + this.editor.onSubmit(text); + } + } + handleDequeue() { + const restored = this.restoreQueuedMessagesToEditor(); + if (restored === 0) { + this.showStatus("No queued messages to restore"); + } + else { + this.showStatus(`Restored ${restored} queued message${restored > 1 ? "s" : ""} to editor`); + } + } + updateEditorBorderColor() { + if (this.isBashMode) { + this.editor.borderColor = theme.getBashModeBorderColor(); + } + else { + const level = this.session.thinkingLevel || "off"; + this.editor.borderColor = theme.getThinkingBorderColor(level); + } + this.ui.requestRender(); + } + cycleThinkingLevel() { + const newLevel = this.session.cycleThinkingLevel(); + if (newLevel === undefined) { + this.showStatus("Current model does not support thinking"); + } + else { + this.footer.invalidate(); + this.updateEditorBorderColor(); + this.showStatus(`Thinking level: ${newLevel}`); + } + } + async cycleModel(direction) { + try { + const result = await this.session.cycleModel(direction); + if (result === undefined) { + const msg = this.session.scopedModels.length > 0 ? "Only one model in scope" : "Only one model available"; + this.showStatus(msg); + } + else { + this.footer.invalidate(); + this.updateEditorBorderColor(); + const thinkingStr = result.model.reasoning && result.thinkingLevel !== "off" ? ` (thinking: ${result.thinkingLevel})` : ""; + this.showStatus(`Switched to ${result.model.name || result.model.id}${thinkingStr}`); + void this.maybeWarnAboutAnthropicSubscriptionAuth(result.model); + } + } + catch (error) { + this.showError(error instanceof Error ? error.message : String(error)); + } + } + toggleToolOutputExpansion() { + this.setToolsExpanded(!this.toolOutputExpanded); + } + setToolsExpanded(expanded) { + this.toolOutputExpanded = expanded; + const activeHeader = this.customHeader ?? this.builtInHeader; + if (isExpandable(activeHeader)) { + activeHeader.setExpanded(expanded); + } + for (const container of [this.loadedResourcesContainer, this.chatContainer]) { + for (const child of container.children) { + if (isExpandable(child)) { + child.setExpanded(expanded); + } + } + } + this.showStatus(`Tool output: ${expanded ? "expanded" : "collapsed"}`); + } + toggleThinkingBlockVisibility() { + this.hideThinkingBlock = !this.hideThinkingBlock; + this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock); + // Rebuild chat from session messages + this.chatContainer.clear(); + this.rebuildChatFromMessages(); + // If streaming, re-add the streaming component with updated visibility and re-render + if (this.streamingComponent && this.streamingMessage) { + this.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock); + this.streamingComponent.updateContent(this.streamingMessage); + this.chatContainer.addChild(this.streamingComponent); + } + this.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? "hidden" : "visible"}`); + } + async handleOpenExternalEditor() { + const editorCmd = this.settingsManager.getExternalEditorCommand(); + const content = this.editor.getExpandedText?.() ?? this.editor.getText(); + this.ui.stop(); + try { + const result = await editInExternalEditor({ + command: editorCmd, + content, + }); + if (result.status === "complete") { + this.editor.setText(result.content); + } + } + finally { + this.ui.start(); + this.ui.requestRender(true); + } + } + // ========================================================================= + // UI helpers + // ========================================================================= + clearEditor() { + this.editor.setText(""); + this.ui.requestRender(); + } + showError(errorMessage) { + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Text(theme.fg("error", `Error: ${errorMessage}`), 1, 0)); + this.ui.requestRender(); + } + showWarning(warningMessage) { + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Text(theme.fg("warning", `Warning: ${warningMessage}`), 1, 0)); + this.ui.requestRender(); + } + showNewVersionNotification(release) { + const action = theme.fg("accent", `${APP_NAME} update`); + const updateInstruction = theme.fg("muted", `New version ${release.version} is available. Run `) + action; + const changelogUrl = "https://pi.dev/changelog"; + const changelogLink = getCapabilities().hyperlinks + ? hyperlink(theme.fg("accent", changelogUrl), changelogUrl) + : theme.fg("accent", changelogUrl); + const changelogLine = theme.fg("muted", "Changelog: ") + changelogLink; + const note = release.note?.trim(); + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text))); + this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning", "Update Available"))}\n${updateInstruction}`, 1, 0)); + if (note) { + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Markdown(note, 1, 0, this.getMarkdownThemeWithSettings(), { + color: (text) => theme.fg("muted", text), + })); + this.chatContainer.addChild(new Spacer(1)); + } + this.chatContainer.addChild(new Text(changelogLine, 1, 0)); + this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text))); + this.ui.requestRender(); + } + showPackageUpdateNotification(packages) { + const action = theme.fg("accent", `${APP_NAME} update --extensions`); + const updateInstruction = theme.fg("muted", "Package updates are available. Run ") + action; + const packageLines = packages.map((pkg) => `- ${pkg}`).join("\n"); + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text))); + this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning", "Package Updates Available"))}\n${updateInstruction}\n${theme.fg("muted", "Packages:")}\n${packageLines}`, 1, 0)); + this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text))); + this.ui.requestRender(); + } + /** + * Get all queued messages (read-only). + * Combines session queue and compaction queue. + */ + getAllQueuedMessages() { + return { + steering: [ + ...this.session.getSteeringMessages(), + ...this.compactionQueuedMessages.filter((msg) => msg.mode === "steer").map((msg) => msg.text), + ], + followUp: [ + ...this.session.getFollowUpMessages(), + ...this.compactionQueuedMessages.filter((msg) => msg.mode === "followUp").map((msg) => msg.text), + ], + }; + } + /** + * Clear all queued messages and return their contents. + * Clears both session queue and compaction queue. + */ + clearAllQueues() { + const { steering, followUp } = this.session.clearQueue(); + const compactionSteering = this.compactionQueuedMessages + .filter((msg) => msg.mode === "steer") + .map((msg) => msg.text); + const compactionFollowUp = this.compactionQueuedMessages + .filter((msg) => msg.mode === "followUp") + .map((msg) => msg.text); + this.compactionQueuedMessages = []; + return { + steering: [...steering, ...compactionSteering], + followUp: [...followUp, ...compactionFollowUp], + }; + } + updatePendingMessagesDisplay() { + this.pendingMessagesContainer.clear(); + const { steering: steeringMessages, followUp: followUpMessages } = this.getAllQueuedMessages(); + if (steeringMessages.length > 0 || followUpMessages.length > 0) { + this.pendingMessagesContainer.addChild(new Spacer(1)); + for (const message of steeringMessages) { + const text = theme.fg("dim", `Steering: ${message}`); + this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0)); + } + for (const message of followUpMessages) { + const text = theme.fg("dim", `Follow-up: ${message}`); + this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0)); + } + const dequeueHint = this.getAppKeyDisplay("app.message.dequeue"); + const hintText = theme.fg("dim", `↳ ${dequeueHint} to edit all queued messages`); + this.pendingMessagesContainer.addChild(new TruncatedText(hintText, 1, 0)); + } + } + restoreQueuedMessagesToEditor(options) { + const { steering, followUp } = this.clearAllQueues(); + const allQueued = [...steering, ...followUp]; + if (allQueued.length === 0) { + this.updatePendingMessagesDisplay(); + if (options?.abort) { + this.agent.abort(); + } + return 0; + } + const queuedText = allQueued.join("\n\n"); + const currentText = options?.currentText ?? this.editor.getText(); + const combinedText = [queuedText, currentText].filter((t) => t.trim()).join("\n\n"); + this.editor.setText(combinedText); + this.updatePendingMessagesDisplay(); + if (options?.abort) { + this.agent.abort(); + } + return allQueued.length; + } + queueCompactionMessage(text, mode) { + this.compactionQueuedMessages.push({ text, mode }); + this.editor.addToHistory?.(text); + this.editor.setText(""); + this.updatePendingMessagesDisplay(); + this.showStatus("Queued message for after compaction"); + } + isExtensionCommand(text) { + if (!text.startsWith("/")) + return false; + const extensionRunner = this.session.extensionRunner; + const spaceIndex = text.indexOf(" "); + const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex); + return !!extensionRunner.getCommand(commandName); + } + async flushCompactionQueue(options) { + if (this.compactionQueuedMessages.length === 0) { + return; + } + const queuedMessages = [...this.compactionQueuedMessages]; + this.compactionQueuedMessages = []; + this.updatePendingMessagesDisplay(); + const restoreQueue = (error) => { + this.session.clearQueue(); + this.compactionQueuedMessages = queuedMessages; + this.updatePendingMessagesDisplay(); + this.showError(`Failed to send queued message${queuedMessages.length > 1 ? "s" : ""}: ${error instanceof Error ? error.message : String(error)}`); + }; + try { + if (options?.willRetry) { + // When retry is pending, queue messages for the retry turn + for (const message of queuedMessages) { + if (this.isExtensionCommand(message.text)) { + await this.session.prompt(message.text); + } + else if (message.mode === "followUp") { + await this.session.followUp(message.text); + } + else { + await this.session.steer(message.text); + } + } + this.updatePendingMessagesDisplay(); + return; + } + // Find first non-extension-command message to use as prompt + const firstPromptIndex = queuedMessages.findIndex((message) => !this.isExtensionCommand(message.text)); + if (firstPromptIndex === -1) { + // All extension commands - execute them all + for (const message of queuedMessages) { + await this.session.prompt(message.text); + } + return; + } + // Execute any extension commands before the first prompt + const preCommands = queuedMessages.slice(0, firstPromptIndex); + const firstPrompt = queuedMessages[firstPromptIndex]; + const rest = queuedMessages.slice(firstPromptIndex + 1); + for (const message of preCommands) { + await this.session.prompt(message.text); + } + // Start a prompt when idle, or queue it into a run still finishing compaction. + const promptPromise = this.session + .prompt(firstPrompt.text, { streamingBehavior: firstPrompt.mode }) + .catch((error) => { + restoreQueue(error); + }); + // Queue remaining messages + for (const message of rest) { + if (this.isExtensionCommand(message.text)) { + await this.session.prompt(message.text); + } + else if (message.mode === "followUp") { + await this.session.followUp(message.text); + } + else { + await this.session.steer(message.text); + } + } + this.updatePendingMessagesDisplay(); + void promptPromise; + } + catch (error) { + restoreQueue(error); + } + } + /** Move pending bash components from pending area to chat */ + flushPendingBashComponents() { + for (const component of this.pendingBashComponents) { + this.pendingMessagesContainer.removeChild(component); + this.chatContainer.addChild(component); + } + this.pendingBashComponents = []; + } + // ========================================================================= + // Selectors + // ========================================================================= + /** + * Shows a selector component in place of the editor. + * @param create Factory that receives a `done` callback and returns the component and focus target + */ + showSelector(create) { + const done = () => { + this.editorContainer.clear(); + this.editorContainer.addChild(this.editor); + this.ui.setFocus(this.editor); + }; + const { component, focus } = create(done); + this.editorContainer.clear(); + this.editorContainer.addChild(component); + this.ui.setFocus(focus); + this.ui.requestRender(); + } + showSettingsSelector() { + this.showSelector((done) => { + const selector = new SettingsSelectorComponent({ + autoCompact: this.session.autoCompactionEnabled, + showImages: this.settingsManager.getShowImages(), + imageWidthCells: this.settingsManager.getImageWidthCells(), + autoResizeImages: this.settingsManager.getImageAutoResize(), + blockImages: this.settingsManager.getBlockImages(), + enableSkillCommands: this.settingsManager.getEnableSkillCommands(), + steeringMode: this.session.steeringMode, + followUpMode: this.session.followUpMode, + transport: this.settingsManager.getTransport(), + httpIdleTimeoutMs: this.settingsManager.getHttpIdleTimeoutMs(), + thinkingLevel: this.session.thinkingLevel, + availableThinkingLevels: this.session.getAvailableThinkingLevels(), + currentTheme: this.settingsManager.getThemeSetting() || "dark", + terminalTheme: this.themeController.getTerminalTheme(), + availableThemes: getAvailableThemes(), + hideThinkingBlock: this.hideThinkingBlock, + collapseChangelog: this.settingsManager.getCollapseChangelog(), + enableInstallTelemetry: this.settingsManager.getEnableInstallTelemetry(), + doubleEscapeAction: this.settingsManager.getDoubleEscapeAction(), + treeFilterMode: this.settingsManager.getTreeFilterMode(), + showHardwareCursor: this.settingsManager.getShowHardwareCursor(), + showCacheMissNotices: this.settingsManager.getShowCacheMissNotices(), + defaultProjectTrust: this.settingsManager.getDefaultProjectTrust(), + editorPaddingX: this.settingsManager.getEditorPaddingX(), + outputPad: this.settingsManager.getOutputPad(), + autocompleteMaxVisible: this.settingsManager.getAutocompleteMaxVisible(), + quietStartup: this.settingsManager.getQuietStartup(), + clearOnShrink: this.settingsManager.getClearOnShrink(), + showTerminalProgress: this.settingsManager.getShowTerminalProgress(), + warnings: this.settingsManager.getWarnings(), + }, { + onAutoCompactChange: (enabled) => { + this.session.setAutoCompactionEnabled(enabled); + this.footer.setAutoCompactEnabled(enabled); + }, + onShowImagesChange: (enabled) => { + this.settingsManager.setShowImages(enabled); + for (const child of this.chatContainer.children) { + if (child instanceof ToolExecutionComponent) { + child.setShowImages(enabled); + } + } + }, + onImageWidthCellsChange: (width) => { + this.settingsManager.setImageWidthCells(width); + for (const child of this.chatContainer.children) { + if (child instanceof ToolExecutionComponent) { + child.setImageWidthCells(width); + } + } + }, + onAutoResizeImagesChange: (enabled) => { + this.settingsManager.setImageAutoResize(enabled); + }, + onBlockImagesChange: (blocked) => { + this.settingsManager.setBlockImages(blocked); + }, + onEnableSkillCommandsChange: (enabled) => { + this.settingsManager.setEnableSkillCommands(enabled); + this.setupAutocompleteProvider(); + }, + onSteeringModeChange: (mode) => { + this.session.setSteeringMode(mode); + }, + onFollowUpModeChange: (mode) => { + this.session.setFollowUpMode(mode); + }, + onTransportChange: (transport) => { + this.settingsManager.setTransport(transport); + this.session.agent.transport = transport; + }, + onHttpIdleTimeoutMsChange: (timeoutMs) => { + this.settingsManager.setHttpIdleTimeoutMs(timeoutMs); + configureHttpDispatcher(timeoutMs); + this.showStatus(`HTTP idle timeout: ${formatHttpIdleTimeoutMs(timeoutMs)}`); + }, + onThinkingLevelChange: (level) => { + this.session.setThinkingLevel(level); + this.footer.invalidate(); + this.updateEditorBorderColor(); + }, + onThemeChange: (themeSetting) => { + this.settingsManager.setTheme(themeSetting); + void this.themeController.applyFromSettings(); + }, + onThemePreview: (themeName) => this.themeController.preview(themeName), + onHideThinkingBlockChange: (hidden) => { + this.hideThinkingBlock = hidden; + this.settingsManager.setHideThinkingBlock(hidden); + for (const child of this.chatContainer.children) { + if (child instanceof AssistantMessageComponent) { + child.setHideThinkingBlock(hidden); + } + } + this.chatContainer.clear(); + this.rebuildChatFromMessages(); + }, + onShowCacheMissNoticesChange: (shown) => { + this.settingsManager.setShowCacheMissNotices(shown); + this.rebuildChatFromMessages(); + }, + onCollapseChangelogChange: (collapsed) => { + this.settingsManager.setCollapseChangelog(collapsed); + }, + onEnableInstallTelemetryChange: (enabled) => { + this.settingsManager.setEnableInstallTelemetry(enabled); + }, + onQuietStartupChange: (enabled) => { + this.settingsManager.setQuietStartup(enabled); + }, + onDefaultProjectTrustChange: (defaultProjectTrust) => { + this.settingsManager.setDefaultProjectTrust(defaultProjectTrust); + }, + onDoubleEscapeActionChange: (action) => { + this.settingsManager.setDoubleEscapeAction(action); + }, + onTreeFilterModeChange: (mode) => { + this.settingsManager.setTreeFilterMode(mode); + }, + onShowHardwareCursorChange: (enabled) => { + this.settingsManager.setShowHardwareCursor(enabled); + this.ui.setShowHardwareCursor(enabled); + }, + onEditorPaddingXChange: (padding) => { + this.settingsManager.setEditorPaddingX(padding); + this.defaultEditor.setPaddingX(padding); + if (this.editor !== this.defaultEditor && this.editor.setPaddingX !== undefined) { + this.editor.setPaddingX(padding); + } + }, + onOutputPadChange: (padding) => { + this.settingsManager.setOutputPad(padding); + this.outputPad = padding; + if (this.streamingComponent || this.session.isStreaming) { + for (const child of this.chatContainer.children) { + if (child instanceof AssistantMessageComponent || + child instanceof CustomMessageComponent || + child instanceof UserMessageComponent) { + child.setOutputPad(padding); + } + } + if (this.streamingComponent) { + this.streamingComponent.setOutputPad(padding); + } + this.ui.requestRender(); + return; + } + this.rebuildChatFromMessages(); + }, + onAutocompleteMaxVisibleChange: (maxVisible) => { + this.settingsManager.setAutocompleteMaxVisible(maxVisible); + this.defaultEditor.setAutocompleteMaxVisible(maxVisible); + if (this.editor !== this.defaultEditor && this.editor.setAutocompleteMaxVisible !== undefined) { + this.editor.setAutocompleteMaxVisible(maxVisible); + } + }, + onClearOnShrinkChange: (enabled) => { + this.settingsManager.setClearOnShrink(enabled); + this.ui.setClearOnShrink(enabled); + if (!enabled && !this.activeStatusIndicator) { + this.statusContainer.clear(); + } + }, + onShowTerminalProgressChange: (enabled) => { + this.settingsManager.setShowTerminalProgress(enabled); + }, + onWarningsChange: (warnings) => { + this.settingsManager.setWarnings(warnings); + }, + onCancel: () => { + done(); + this.ui.requestRender(); + }, + }); + return { component: selector, focus: selector.getSettingsList() }; + }); + } + async handleModelCommand(searchTerm) { + if (!searchTerm) { + this.showModelSelector(); + return; + } + const model = await this.findExactModelMatch(searchTerm); + if (model) { + try { + await this.session.setModel(model); + this.footer.invalidate(); + this.updateEditorBorderColor(); + this.showStatus(`Model: ${model.id}`); + void this.maybeWarnAboutAnthropicSubscriptionAuth(model); + this.checkDaxnutsEasterEgg(model); + } + catch (error) { + this.showError(error instanceof Error ? error.message : String(error)); + } + return; + } + this.showModelSelector(searchTerm); + } + async findExactModelMatch(searchTerm) { + const models = await this.getModelCandidates(); + return findExactModelReferenceMatch(searchTerm, models); + } + async getModelCandidates() { + if (this.session.scopedModels.length > 0) { + return this.session.scopedModels.map((scoped) => scoped.model); + } + try { + await this.session.modelRuntime.refresh(); + return [...(await this.session.modelRuntime.getAvailable())]; + } + catch { + return []; + } + } + /** Update the footer's available provider count from the current snapshot without refreshing catalogs. */ + updateAvailableProviderCount() { + const models = this.session.scopedModels.length > 0 + ? this.session.scopedModels.map((scoped) => scoped.model) + : this.session.modelRuntime.getAvailableSnapshot(); + const uniqueProviders = new Set(models.map((model) => model.provider)); + this.footerDataProvider.setAvailableProviderCount(uniqueProviders.size); + } + async maybeWarnAboutAnthropicSubscriptionAuth(model = this.session.model) { + if (this.settingsManager.getWarnings().anthropicExtraUsage === false) { + return; + } + if (this.anthropicSubscriptionWarningShown) { + return; + } + if (!model || model.provider !== "anthropic") { + return; + } + try { + if ((await this.session.modelRuntime.checkAuth("anthropic"))?.type === "oauth") { + this.anthropicSubscriptionWarningShown = true; + this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING); + return; + } + const apiKey = (await this.session.modelRuntime.getAuth(model.provider))?.auth.apiKey; + if (!isAnthropicSubscriptionAuthKey(apiKey)) { + return; + } + this.anthropicSubscriptionWarningShown = true; + this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING); + } + catch { + // Ignore auth lookup failures for warning-only checks. + } + } + maybeSaveImplicitProjectTrustAfterReload() { + const cwd = this.sessionManager.getCwd(); + if (this.autoTrustOnReloadCwd !== cwd) { + return false; + } + if (!this.settingsManager.isProjectTrusted() || !hasTrustRequiringProjectResources(cwd)) { + return false; + } + const trustStore = new ProjectTrustStore(this.runtimeHost.services.agentDir); + try { + if (trustStore.get(cwd) !== null) { + this.autoTrustOnReloadCwd = undefined; + return false; + } + trustStore.set(cwd, true); + this.autoTrustOnReloadCwd = undefined; + return true; + } + catch (error) { + this.showWarning(`Could not save project trust after reload: ${error instanceof Error ? error.message : String(error)}`); + return false; + } + } + showTrustSelector() { + const cwd = this.sessionManager.getCwd(); + const trustStore = new ProjectTrustStore(this.runtimeHost.services.agentDir); + const savedDecision = trustStore.getEntry(cwd); + this.showSelector((done) => { + const selector = new TrustSelectorComponent({ + cwd, + savedDecision, + projectTrusted: this.settingsManager.isProjectTrusted(), + onSelect: (selection) => { + trustStore.setMany(selection.updates); + done(); + this.showStatus(`Saved trust decision: ${selection.trusted ? "trusted" : "untrusted"}. Restart pi for this to take effect.`); + }, + onCancel: () => { + done(); + this.ui.requestRender(); + }, + }); + return { component: selector, focus: selector }; + }); + } + showModelSelector(initialSearchInput) { + this.showSelector((done) => { + const selector = new ModelSelectorComponent(this.ui, this.session.model, this.settingsManager, this.session.modelRuntime, this.session.scopedModels, async (model) => { + try { + await this.session.setModel(model); + this.footer.invalidate(); + this.updateEditorBorderColor(); + done(); + this.showStatus(`Model: ${model.id}`); + void this.maybeWarnAboutAnthropicSubscriptionAuth(model); + this.checkDaxnutsEasterEgg(model); + } + catch (error) { + done(); + this.showError(error instanceof Error ? error.message : String(error)); + } + }, () => { + done(); + this.ui.requestRender(); + }, initialSearchInput); + return { component: selector, focus: selector }; + }); + } + async showModelsSelector() { + // Get all available models + await this.session.modelRuntime.refresh(); + const allModels = [...(await this.session.modelRuntime.getAvailable())]; + const allModelIds = new Set(allModels.map((model) => `${model.provider}/${model.id}`)); + const configuredPatterns = this.settingsManager.getEnabledModels(); + const sessionScopedModels = this.session.scopedModels; + if (allModels.length === 0 && !configuredPatterns?.length && sessionScopedModels.length === 0) { + this.showStatus("No models available"); + return; + } + const configuredScope = configuredPatterns?.length + ? await resolveModelScopeWithDiagnostics(configuredPatterns, this.session.modelRuntime) + : undefined; + // Check if session has scoped models (from previous session-only changes or CLI --models) + const hasSessionScope = sessionScopedModels.length > 0; + // Build enabled model IDs from session state or settings + let currentEnabledIds = null; + if (hasSessionScope) { + // Use current session's scoped models + currentEnabledIds = sessionScopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`); + } + else if (configuredScope) { + currentEnabledIds = configuredScope.scopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`); + } + for (const diagnostic of configuredScope?.diagnostics ?? []) { + if (diagnostic.code !== "no-match") + continue; + currentEnabledIds ??= []; + if (!currentEnabledIds.includes(diagnostic.pattern)) + currentEnabledIds.push(diagnostic.pattern); + } + // Helper to update session's scoped models (session-only, no persist) + const updateSessionModels = async (enabledIds) => { + currentEnabledIds = enabledIds === null ? null : [...enabledIds]; + const hasEnabledAvailableModel = enabledIds?.some((id) => allModelIds.has(id)) ?? false; + const allAvailableModelsEnabled = enabledIds !== null && [...allModelIds].every((id) => enabledIds.includes(id)); + if (enabledIds && hasEnabledAvailableModel && !allAvailableModelsEnabled) { + const newScopedModels = await resolveModelScope(enabledIds, this.session.modelRuntime); + this.session.setScopedModels(newScopedModels.map((sm) => ({ + model: sm.model, + thinkingLevel: sm.thinkingLevel, + }))); + } + else { + // All enabled or none enabled = no filter + this.session.setScopedModels([]); + } + await this.updateAvailableProviderCount(); + this.ui.requestRender(); + }; + this.showSelector((done) => { + const selector = new ScopedModelsSelectorComponent({ + allModels, + enabledModelIds: currentEnabledIds, + }, { + onChange: async (enabledIds) => { + await updateSessionModels(enabledIds); + }, + onPersist: (enabledIds) => { + // Persist to settings + const allEnabled = enabledIds !== null && + enabledIds.length === allModels.length && + enabledIds.every((id) => allModelIds.has(id)); + const newPatterns = enabledIds === null || allEnabled ? undefined : enabledIds; + this.settingsManager.setEnabledModels(newPatterns ? [...newPatterns] : undefined); + this.showStatus("Model selection saved to settings"); + }, + onCancel: () => { + done(); + this.ui.requestRender(); + }, + }); + return { component: selector, focus: selector }; + }); + } + showUserMessageSelector() { + const userMessages = this.session.getUserMessagesForForking(); + if (userMessages.length === 0) { + this.showStatus("No messages to fork from"); + return; + } + const initialSelectedId = userMessages[userMessages.length - 1]?.entryId; + this.showSelector((done) => { + const selector = new UserMessageSelectorComponent(userMessages.map((m) => ({ id: m.entryId, text: m.text })), async (entryId) => { + done(); + try { + const result = await this.runtimeHost.fork(entryId); + if (result.cancelled) { + this.ui.requestRender(); + return; + } + this.editor.setText(result.selectedText ?? ""); + this.showStatus("Forked to new session"); + } + catch (error) { + this.showError(error instanceof Error ? error.message : String(error)); + } + }, () => { + done(); + this.ui.requestRender(); + }, initialSelectedId); + return { component: selector, focus: selector.getMessageList() }; + }); + } + async handleCloneCommand() { + const leafId = this.sessionManager.getLeafId(); + if (!leafId) { + this.showStatus("Nothing to clone yet"); + return; + } + try { + const result = await this.runtimeHost.fork(leafId, { position: "at" }); + if (result.cancelled) { + this.ui.requestRender(); + return; + } + this.editor.setText(""); + this.showStatus("Cloned to new session"); + } + catch (error) { + this.showError(error instanceof Error ? error.message : String(error)); + } + } + showTreeSelector(initialSelectedId) { + const tree = this.sessionManager.getTree(); + const realLeafId = this.sessionManager.getLeafId(); + const initialFilterMode = this.settingsManager.getTreeFilterMode(); + if (tree.length === 0) { + this.showStatus("No entries in session"); + return; + } + this.showSelector((done) => { + const selector = new TreeSelectorComponent(tree, realLeafId, this.ui.terminal.rows, async (entryId) => { + // Selecting the current leaf is a no-op (already there) + if (entryId === this.sessionManager.getLeafId()) { + done(); + this.showStatus("Already at this point"); + return; + } + // Ask about summarization + done(); // Close selector first + // Loop until user makes a complete choice or cancels to tree + let wantsSummary = false; + let customInstructions; + // Check if we should skip the prompt (user preference to always default to no summary) + if (!this.settingsManager.getBranchSummarySkipPrompt()) { + while (true) { + const summaryChoice = await this.showExtensionSelector("Summarize branch?", [ + "No summary", + "Summarize", + "Summarize with custom prompt", + ]); + if (summaryChoice === undefined) { + // User pressed escape - re-show tree selector with same selection + this.showTreeSelector(entryId); + return; + } + wantsSummary = summaryChoice !== "No summary"; + if (summaryChoice === "Summarize with custom prompt") { + customInstructions = await this.showExtensionEditor("Custom summarization instructions"); + if (customInstructions === undefined) { + // User cancelled - loop back to summary selector + continue; + } + } + // User made a complete choice + break; + } + } + // The user committed to navigating: stop the active response first. + if (this.session.isStreaming) { + this.restoreQueuedMessagesToEditor(); + await this.session.abort(); + } + // Set up escape handler and status indicator if summarizing + let showingSummaryIndicator = false; + const originalOnEscape = this.defaultEditor.onEscape; + if (wantsSummary) { + this.defaultEditor.onEscape = () => { + this.session.abortBranchSummary(); + }; + this.chatContainer.addChild(new Spacer(1)); + this.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui)); + showingSummaryIndicator = true; + this.ui.requestRender(); + } + try { + const result = await this.session.navigateTree(entryId, { + summarize: wantsSummary, + customInstructions, + }); + if (result.aborted) { + // Summarization aborted - re-show tree selector with same selection + this.showStatus("Branch summarization cancelled"); + this.showTreeSelector(entryId); + return; + } + if (result.cancelled) { + this.showStatus("Navigation cancelled"); + return; + } + // Update UI + this.chatContainer.clear(); + this.renderInitialMessages(); + if (result.editorText && !this.editor.getText().trim()) { + this.editor.setText(result.editorText); + } + this.showStatus("Navigated to selected point"); + void this.flushCompactionQueue({ willRetry: false }); + } + catch (error) { + this.showError(error instanceof Error ? error.message : String(error)); + } + finally { + if (showingSummaryIndicator) { + this.clearStatusIndicator("branchSummary"); + } + this.defaultEditor.onEscape = originalOnEscape; + } + }, () => { + done(); + this.ui.requestRender(); + }, (entryId, label) => { + this.sessionManager.appendLabelChange(entryId, label); + this.ui.requestRender(); + }, initialSelectedId, initialFilterMode); + selector.onCopy = async (text) => { + if (!text) { + this.showError("Selected entry has no text to copy"); + return; + } + try { + await copyToClipboard(text); + this.showStatus("Copied selected message to clipboard"); + } + catch (error) { + this.showError(error instanceof Error ? error.message : String(error)); + } + }; + return { component: selector, focus: selector }; + }); + } + showSessionSelector() { + this.showSelector((done) => { + const selector = new SessionSelectorComponent((onProgress) => SessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir(), onProgress), (onProgress) => this.sessionManager.usesDefaultSessionDir() + ? SessionManager.listAll(onProgress) + : SessionManager.listAll(this.sessionManager.getSessionDir(), onProgress), async (sessionPath) => { + done(); + await this.handleResumeSession(sessionPath); + }, () => { + done(); + this.ui.requestRender(); + }, () => { + void this.shutdown(); + }, () => this.ui.requestRender(), { + renameSession: async (sessionFilePath, nextName) => { + const next = (nextName ?? "").trim(); + if (!next) + return; + const mgr = SessionManager.open(sessionFilePath); + mgr.appendSessionInfo(next); + }, + showRenameHint: true, + keybindings: this.keybindings, + }, this.sessionManager.getSessionFile()); + return { component: selector, focus: selector }; + }); + } + async handleResumeSession(sessionPath, options) { + this.clearStatusIndicator(); + try { + const result = await this.runtimeHost.switchSession(sessionPath, { + withSession: options?.withSession, + projectTrustContextFactory: (cwd) => this.createProjectTrustContext(cwd), + }); + if (result.cancelled) { + return result; + } + this.showStatus("Resumed session"); + return result; + } + catch (error) { + if (error instanceof MissingSessionCwdError) { + const selectedCwd = await this.promptForMissingSessionCwd(error); + if (!selectedCwd) { + this.showStatus("Resume cancelled"); + return { cancelled: true }; + } + const result = await this.runtimeHost.switchSession(sessionPath, { + cwdOverride: selectedCwd, + withSession: options?.withSession, + projectTrustContextFactory: (cwd) => this.createProjectTrustContext(cwd), + }); + if (result.cancelled) { + return result; + } + this.showStatus("Resumed session in current cwd"); + return result; + } + return this.handleFatalRuntimeError("Failed to resume session", error); + } + } + getLoginProviderOptions(authType) { + const options = []; + for (const provider of this.session.modelRuntime.getProviders()) { + const authStatus = this.session.modelRuntime.getProviderAuthStatus(provider.id); + const status = authStatus.configured + ? { + type: this.session.modelRuntime.isUsingOAuth(provider.id) ? "oauth" : "api_key", + source: authStatus.label ?? authStatus.source, + } + : undefined; + if ((!authType || authType === "oauth") && provider.auth.oauth) { + options.push({ + id: provider.id, + name: provider.name, + authType: "oauth", + method: provider.auth.oauth, + status, + }); + } + if ((!authType || authType === "api_key") && provider.auth.apiKey) { + options.push({ + id: provider.id, + name: provider.name, + authType: "api_key", + method: provider.auth.apiKey, + status, + }); + } + } + return options.sort((a, b) => a.name.localeCompare(b.name)); + } + async getLogoutProviderOptions() { + return (await this.session.modelRuntime.listCredentials()) + .map(({ providerId, type }) => ({ + id: providerId, + name: this.session.modelRuntime.getProvider(providerId)?.name ?? providerId, + authType: type, + status: { type, source: "stored credential" }, + })) + .sort((a, b) => a.name.localeCompare(b.name)); + } + findLoginProviderOptions(providerRef) { + const normalizedProviderRef = providerRef.trim().toLowerCase(); + if (!normalizedProviderRef) { + return []; + } + return this.getLoginProviderOptions().filter((provider) => provider.id.toLowerCase() === normalizedProviderRef || + provider.name.toLowerCase() === normalizedProviderRef); + } + async handleLoginCommand(providerRef) { + await this.session.modelRuntime.getAvailable(); + if (!providerRef) { + this.showLoginAuthTypeSelector(); + return; + } + const providerOptions = this.findLoginProviderOptions(providerRef); + if (providerOptions.length === 1) { + await this.startProviderLogin(providerOptions[0]); + return; + } + if (providerOptions.length > 1) { + const providerIds = new Set(providerOptions.map((provider) => provider.id)); + if (providerIds.size === 1) { + this.showLoginAuthTypeSelector(providerOptions); + return; + } + } + this.showLoginProviderSelector(undefined, providerRef); + } + async startProviderLogin(providerOption) { + if (providerOption.authType === "oauth") { + await this.showLoginDialog(providerOption.id, providerOption.name); + } + else if (providerOption.method?.login) { + await this.showApiKeyLoginDialog(providerOption.id, providerOption.name); + } + else { + this.showAmbientAuthDialog(providerOption); + } + } + showLoginAuthTypeSelector(providerOptions) { + const oauthProvider = providerOptions?.find((provider) => provider.authType === "oauth"); + const oauthLoginLabel = oauthProvider?.method && "loginLabel" in oauthProvider.method ? oauthProvider.method.loginLabel : undefined; + const subscriptionLabel = oauthLoginLabel ?? "Sign in with an account"; + const apiKeyLabel = "Sign in with an API key"; + const availableAuthTypes = providerOptions + ? new Set(providerOptions.map((provider) => provider.authType)) + : new Set(["oauth", "api_key"]); + const options = []; + if (availableAuthTypes.has("oauth")) { + options.push(subscriptionLabel); + } + if (availableAuthTypes.has("api_key")) { + options.push(apiKeyLabel); + } + if (options.length === 0) { + this.showStatus("No login methods available."); + return; + } + if (providerOptions && options.length === 1) { + const providerOption = providerOptions[0]; + if (providerOption) { + void this.startProviderLogin(providerOption); + } + return; + } + const title = providerOptions?.[0] + ? `Select authentication method for ${providerOptions[0].name}:` + : "Select authentication method:"; + this.showSelector((done) => { + const selector = new ExtensionSelectorComponent(title, options, (option) => { + done(); + const authType = option === subscriptionLabel ? "oauth" : "api_key"; + if (providerOptions) { + const providerOption = providerOptions.find((provider) => provider.authType === authType); + if (providerOption) { + void this.startProviderLogin(providerOption); + } + return; + } + this.showLoginProviderSelector(authType); + }, () => { + done(); + this.ui.requestRender(); + }); + return { component: selector, focus: selector }; + }); + } + showLoginProviderSelector(authType, initialSearchInput) { + const providerOptions = this.getLoginProviderOptions(authType); + if (providerOptions.length === 0) { + const message = authType === "oauth" + ? "No subscription providers available." + : authType === "api_key" + ? "No API key providers available." + : "No login providers available."; + this.showStatus(message); + return; + } + this.showSelector((done) => { + const selector = new OAuthSelectorComponent("login", providerOptions, async (providerId, selectedAuthType) => { + done(); + const providerOption = providerOptions.find((provider) => provider.id === providerId && provider.authType === selectedAuthType); + if (!providerOption) { + return; + } + await this.startProviderLogin(providerOption); + }, () => { + done(); + if (authType) { + this.showLoginAuthTypeSelector(); + } + else { + this.ui.requestRender(); + } + }, initialSearchInput); + return { component: selector, focus: selector }; + }); + } + async showOAuthSelector(mode) { + if (mode === "login") { + this.showLoginAuthTypeSelector(); + return; + } + const providerOptions = await this.getLogoutProviderOptions(); + if (providerOptions.length === 0) { + this.showStatus("No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged."); + return; + } + this.showSelector((done) => { + const selector = new OAuthSelectorComponent(mode, providerOptions, async (providerId) => { + done(); + const providerOption = providerOptions.find((provider) => provider.id === providerId); + if (!providerOption) { + return; + } + try { + await this.session.modelRuntime.logout(providerOption.id); + await this.updateAvailableProviderCount(); + const message = providerOption.authType === "oauth" + ? `Logged out of ${providerOption.name}` + : `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`; + this.showStatus(message); + } + catch (error) { + this.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`); + } + }, () => { + done(); + this.ui.requestRender(); + }); + return { component: selector, focus: selector }; + }); + } + async completeProviderAuthentication(providerId, providerName, authType, previousModel) { + await this.session.modelRuntime.getAvailable(); + const actionLabel = authType === "oauth" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`; + let selectedModel; + let selectionError; + if (isUnknownModel(previousModel)) { + const availableModels = await this.session.modelRuntime.getAvailable(); + const providerModels = availableModels.filter((model) => model.provider === providerId); + if (!hasDefaultModelProvider(providerId)) { + selectionError = `${actionLabel}, but no default model is configured for provider "${providerId}". Use /model to select a model.`; + } + else if (providerModels.length === 0) { + selectionError = `${actionLabel}, but no models are available for that provider. Use /model to select a model.`; + } + else { + const defaultModelId = defaultModelPerProvider[providerId]; + selectedModel = providerModels.find((model) => model.id === defaultModelId); + if (!selectedModel) { + selectionError = `${actionLabel}, but its default model "${defaultModelId}" is not available. Use /model to select a model.`; + } + else { + try { + await this.session.setModel(selectedModel); + } + catch (error) { + selectedModel = undefined; + const errorMessage = error instanceof Error ? error.message : String(error); + selectionError = `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`; + } + } + } + } + await this.updateAvailableProviderCount(); + this.footer.invalidate(); + this.updateEditorBorderColor(); + if (selectedModel) { + this.showStatus(`${actionLabel}. Selected ${selectedModel.id}. Credentials saved to ${getAuthPath()}`); + void this.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel); + this.checkDaxnutsEasterEgg(selectedModel); + } + else { + this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`); + if (selectionError) { + this.showError(selectionError); + } + else { + void this.maybeWarnAboutAnthropicSubscriptionAuth(); + } + } + } + showAmbientAuthDialog(providerOption) { + const restoreEditor = () => { + this.editorContainer.clear(); + this.editorContainer.addChild(this.editor); + this.ui.setFocus(this.editor); + this.ui.requestRender(); + }; + const dialog = new LoginDialogComponent(this.ui, providerOption.id, () => restoreEditor(), providerOption.name, `${providerOption.name} setup`); + dialog.showInfo(`${providerOption.method?.name ?? "Authentication"} is configured outside pi.`, [], true); + this.editorContainer.clear(); + this.editorContainer.addChild(dialog); + this.ui.setFocus(dialog); + this.ui.requestRender(); + } + async showApiKeyLoginDialog(providerId, providerName) { + const previousModel = this.session.model; + const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => { + // Completion handled below + }, providerName); + if (providerId === "amazon-bedrock") { + dialog.showDetails([ + theme.fg("text", "You can also use an AWS profile, IAM keys, or role-based credentials."), + theme.fg("muted", "See:"), + theme.fg("accent", ` ${path.join(getDocsPath(), "providers.md")}`), + ]); + } + this.editorContainer.clear(); + this.editorContainer.addChild(dialog); + this.ui.setFocus(dialog); + this.ui.requestRender(); + const restoreEditor = () => { + this.editorContainer.clear(); + this.editorContainer.addChild(this.editor); + this.ui.setFocus(this.editor); + this.ui.requestRender(); + }; + try { + await this.loginProvider(dialog, providerId, "api_key"); + restoreEditor(); + await this.completeProviderAuthentication(providerId, providerName, "api_key", previousModel); + } + catch (error) { + restoreEditor(); + const errorMsg = error instanceof Error ? error.message : String(error); + if (errorMsg !== "Login cancelled") { + this.showError(`Failed to save API key for ${providerName}: ${errorMsg}`); + } + } + } + showAuthSelect(dialog, prompt) { + return new Promise((resolve, reject) => { + const restoreDialog = () => { + this.editorContainer.clear(); + this.editorContainer.addChild(dialog); + this.ui.setFocus(dialog); + this.ui.requestRender(); + }; + const labels = prompt.options.map((option) => option.label); + const selector = new ExtensionSelectorComponent(prompt.message, labels, (optionLabel) => { + restoreDialog(); + const id = prompt.options.find((option) => option.label === optionLabel)?.id; + if (id) + resolve(id); + else + reject(new Error("Login cancelled")); + }, () => { + restoreDialog(); + reject(new Error("Login cancelled")); + }); + this.editorContainer.clear(); + this.editorContainer.addChild(selector); + this.ui.setFocus(selector); + this.ui.requestRender(); + }); + } + async showAuthPrompt(dialog, prompt) { + let response; + if (prompt.type === "select") { + response = this.showAuthSelect(dialog, prompt); + } + else if (prompt.type === "manual_code") { + response = dialog.showManualInput(prompt.message); + } + else { + response = dialog.showPrompt(prompt.message, prompt.placeholder); + } + if (!prompt.signal) + return response; + if (prompt.signal.aborted) + throw new Error("Login cancelled"); + const signal = prompt.signal; + let onAbort; + const aborted = new Promise((_resolve, reject) => { + onAbort = () => reject(new Error("Login cancelled")); + signal.addEventListener("abort", onAbort, { once: true }); + }); + try { + return await Promise.race([response, aborted]); + } + finally { + if (onAbort) + signal.removeEventListener("abort", onAbort); + } + } + notifyAuthDialog(dialog, event) { + if (event.type === "auth_url") { + dialog.showAuth(event.url, event.instructions); + } + else if (event.type === "device_code") { + dialog.showDeviceCode(event); + dialog.showWaiting("Waiting for authentication..."); + } + else if (event.type === "info") { + dialog.showInfo(event.message, event.links); + } + else { + dialog.showProgress(event.message); + } + } + async loginProvider(dialog, providerId, method) { + await this.session.modelRuntime.login(providerId, method, { + signal: dialog.signal, + prompt: (prompt) => this.showAuthPrompt(dialog, prompt), + notify: (event) => this.notifyAuthDialog(dialog, event), + }); + } + async showLoginDialog(providerId, providerName) { + const previousModel = this.session.model; + const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => { }, providerName); + this.editorContainer.clear(); + this.editorContainer.addChild(dialog); + this.ui.setFocus(dialog); + this.ui.requestRender(); + const restoreEditor = () => { + this.editorContainer.clear(); + this.editorContainer.addChild(this.editor); + this.ui.setFocus(this.editor); + this.ui.requestRender(); + }; + try { + await this.loginProvider(dialog, providerId, "oauth"); + restoreEditor(); + await this.completeProviderAuthentication(providerId, providerName, "oauth", previousModel); + } + catch (error) { + restoreEditor(); + const errorMsg = error instanceof Error ? error.message : String(error); + if (errorMsg !== "Login cancelled") { + this.showError(`Failed to login to ${providerName}: ${errorMsg}`); + } + } + } + // ========================================================================= + // Command handlers + // ========================================================================= + async handleReloadCommand() { + if (this.session.isStreaming) { + this.showWarning("Wait for the current response to finish before reloading."); + return; + } + if (this.session.isCompacting) { + this.showWarning("Wait for compaction to finish before reloading."); + return; + } + this.resetExtensionUI(); + const reloadBox = new Container(); + const borderColor = (s) => theme.fg("border", s); + reloadBox.addChild(new DynamicBorder(borderColor)); + reloadBox.addChild(new Spacer(1)); + reloadBox.addChild(new Text(theme.fg("muted", "Reloading keybindings, extensions, skills, prompts, themes, and context files..."), 1, 0)); + reloadBox.addChild(new Spacer(1)); + reloadBox.addChild(new DynamicBorder(borderColor)); + const previousEditor = this.editor; + this.editorContainer.clear(); + this.editorContainer.addChild(reloadBox); + this.ui.setFocus(reloadBox); + this.ui.requestRender(true); + await new Promise((resolve) => process.nextTick(resolve)); + const dismissReloadBox = (editor) => { + this.editorContainer.clear(); + this.editorContainer.addChild(editor); + this.ui.setFocus(editor); + this.ui.requestRender(); + }; + let chatRestoredBeforeSessionStart = false; + let reloadBoxDismissed = false; + const restoreChatBeforeSessionStart = () => { + if (chatRestoredBeforeSessionStart) { + return; + } + this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock(); + this.outputPad = this.settingsManager.getOutputPad(); + this.rebuildChatFromMessages(); + chatRestoredBeforeSessionStart = true; + }; + try { + await this.session.reload({ beforeSessionStart: restoreChatBeforeSessionStart }); + restoreChatBeforeSessionStart(); + configureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs()); + this.keybindings.reload(); + const activeHeader = this.customHeader ?? this.builtInHeader; + if (isExpandable(activeHeader)) { + activeHeader.setExpanded(this.toolOutputExpanded); + } + setRegisteredThemes(this.session.resourceLoader.getThemes().themes); + await this.themeController.applyFromSettings(); + const editorPaddingX = this.settingsManager.getEditorPaddingX(); + const autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible(); + this.defaultEditor.setPaddingX(editorPaddingX); + this.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible); + if (this.editor !== this.defaultEditor) { + this.editor.setPaddingX?.(editorPaddingX); + this.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible); + } + this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor()); + const clearOnShrink = this.settingsManager.getClearOnShrink(); + this.ui.setClearOnShrink(clearOnShrink); + if (!clearOnShrink && !this.activeStatusIndicator) { + this.statusContainer.clear(); + } + this.setupAutocompleteProvider(); + const runner = this.session.extensionRunner; + this.setupExtensionShortcuts(runner); + this.showLoadedResources({ + force: false, + showDiagnosticsWhenQuiet: true, + }); + const savedImplicitProjectTrust = this.maybeSaveImplicitProjectTrustAfterReload(); + const modelsJsonError = this.session.modelRuntime.getError(); + if (modelsJsonError) { + this.showError(`models.json error: ${modelsJsonError}`); + } + this.showStatus(savedImplicitProjectTrust + ? "Reloaded keybindings, extensions, skills, prompts, themes, and context files; saved project trust" + : "Reloaded keybindings, extensions, skills, prompts, themes, and context files"); + dismissReloadBox(this.editor); + reloadBoxDismissed = true; + } + catch (error) { + if (!reloadBoxDismissed) { + dismissReloadBox(previousEditor); + } + this.showError(`Reload failed: ${error instanceof Error ? error.message : String(error)}`); + } + } + async handleExportCommand(text) { + const outputPath = this.getPathCommandArgument(text, "/export"); + try { + if (outputPath?.endsWith(".jsonl")) { + const filePath = this.session.exportToJsonl(outputPath); + this.showStatus(`Session exported to: ${filePath}`); + } + else { + const filePath = await this.session.exportToHtml(outputPath); + this.showStatus(`Session exported to: ${filePath}`); + } + } + catch (error) { + this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`); + } + } + getPathCommandArgument(text, command) { + if (text === command) { + return undefined; + } + if (!text.startsWith(`${command} `)) { + return undefined; + } + const argsString = text.slice(command.length + 1).trimStart(); + if (!argsString) { + return undefined; + } + const firstChar = argsString[0]; + if (firstChar === '"' || firstChar === "'") { + const closingQuoteIndex = argsString.indexOf(firstChar, 1); + if (closingQuoteIndex < 0) { + return undefined; + } + return argsString.slice(1, closingQuoteIndex); + } + const firstWhitespaceIndex = argsString.search(/\s/); + if (firstWhitespaceIndex < 0) { + return argsString; + } + return argsString.slice(0, firstWhitespaceIndex); + } + async handleImportCommand(text) { + const inputPath = this.getPathCommandArgument(text, "/import"); + if (!inputPath) { + this.showError("Usage: /import "); + return; + } + const confirmed = await this.showExtensionConfirm("Import session", `Replace current session with ${inputPath}?`); + if (!confirmed) { + this.showStatus("Import cancelled"); + return; + } + try { + this.clearStatusIndicator(); + const result = await this.runtimeHost.importFromJsonl(inputPath); + if (result.cancelled) { + this.showStatus("Import cancelled"); + return; + } + this.showStatus(`Session imported from: ${inputPath}`); + } + catch (error) { + if (error instanceof MissingSessionCwdError) { + const selectedCwd = await this.promptForMissingSessionCwd(error); + if (!selectedCwd) { + this.showStatus("Import cancelled"); + return; + } + const result = await this.runtimeHost.importFromJsonl(inputPath, selectedCwd); + if (result.cancelled) { + this.showStatus("Import cancelled"); + return; + } + this.showStatus(`Session imported from: ${inputPath}`); + return; + } + if (error instanceof SessionImportFileNotFoundError) { + this.showError(`Failed to import session: ${error.message}`); + return; + } + await this.handleFatalRuntimeError("Failed to import session", error); + } + } + async handleShareCommand() { + // Check if gh is available and logged in + try { + const authResult = spawnSync("gh", ["auth", "status"], { encoding: "utf-8" }); + if (authResult.status !== 0) { + this.showError("GitHub CLI is not logged in. Run 'gh auth login' first."); + return; + } + } + catch { + this.showError("GitHub CLI (gh) is not installed. Install it from https://cli.github.com/"); + return; + } + // Export to a temp file + const tmpFile = path.join(os.tmpdir(), "session.html"); + try { + await this.session.exportToHtml(tmpFile); + } + catch (error) { + this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`); + return; + } + // Show cancellable loader, replacing the editor + const loader = new BorderedLoader(this.ui, theme, "Creating gist..."); + this.editorContainer.clear(); + this.editorContainer.addChild(loader); + this.ui.setFocus(loader); + this.ui.requestRender(); + const restoreEditor = () => { + loader.dispose(); + this.editorContainer.clear(); + this.editorContainer.addChild(this.editor); + this.ui.setFocus(this.editor); + try { + fs.unlinkSync(tmpFile); + } + catch { + // Ignore cleanup errors + } + }; + // Create a secret gist asynchronously + let proc = null; + loader.onAbort = () => { + proc?.kill(); + restoreEditor(); + this.showStatus("Share cancelled"); + }; + try { + const result = await new Promise((resolve) => { + proc = spawn("gh", ["gist", "create", "--public=false", tmpFile]); + let stdout = ""; + let stderr = ""; + proc.stdout?.on("data", (data) => { + stdout += data.toString(); + }); + proc.stderr?.on("data", (data) => { + stderr += data.toString(); + }); + proc.on("close", (code) => resolve({ stdout, stderr, code })); + }); + if (loader.signal.aborted) + return; + restoreEditor(); + if (result.code !== 0) { + const errorMsg = result.stderr?.trim() || "Unknown error"; + this.showError(`Failed to create gist: ${errorMsg}`); + return; + } + // Extract gist ID from the URL returned by gh + // gh returns something like: https://gist.github.com/username/GIST_ID + const gistUrl = result.stdout?.trim(); + const gistId = gistUrl?.split("/").pop(); + if (!gistId) { + this.showError("Failed to parse gist ID from gh output"); + return; + } + // Create the preview URL + const previewUrl = getShareViewerUrl(gistId); + this.showStatus(`Share URL: ${previewUrl}\nGist: ${gistUrl}`); + } + catch (error) { + if (!loader.signal.aborted) { + restoreEditor(); + this.showError(`Failed to create gist: ${error instanceof Error ? error.message : "Unknown error"}`); + } + } + } + async handleCopyCommand() { + const text = this.session.getLastAssistantText(); + if (!text) { + this.showError("No agent messages to copy yet."); + return; + } + try { + await copyToClipboard(text); + this.showStatus("Copied last agent message to clipboard"); + } + catch (error) { + this.showError(error instanceof Error ? error.message : String(error)); + } + } + handleNameCommand(text) { + const name = text.replace(/^\/name\s*/, "").trim(); + if (!name) { + const currentName = this.sessionManager.getSessionName(); + if (currentName) { + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Text(theme.fg("dim", `Session name: ${currentName}`), 1, 0)); + } + else { + this.showWarning("Usage: /name "); + } + this.ui.requestRender(); + return; + } + this.session.setSessionName(name); + const sessionName = this.sessionManager.getSessionName(); + if (sessionName !== name) { + this.showWarning(`Session name was normalized from ${JSON.stringify(name)} to ${JSON.stringify(sessionName)}`); + } + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Text(theme.fg("dim", `Session name set: ${sessionName ?? name}`), 1, 0)); + this.ui.requestRender(); + } + handleSessionCommand() { + const stats = this.session.getSessionStats(); + const sessionName = this.sessionManager.getSessionName(); + const entries = this.sessionManager.getEntries(); + const cacheWaste = computeCacheWaste(entries, this.session.modelRuntime); + // Cost/token totals per provider/model actually used (e.g. OpenRouter `auto` + // resolves to a concrete responseModel). Usage without model attribution is + // grouped separately so the breakdown reconciles with the session total. + const usageBreakdown = getUsageCostBreakdown(entries); + let info = `${theme.bold("Session Info")}\n\n`; + if (sessionName) { + info += `${theme.fg("dim", "Name:")} ${sessionName}\n`; + } + info += `${theme.fg("dim", "File:")} ${stats.sessionFile ?? "In-memory"}\n`; + info += `${theme.fg("dim", "ID:")} ${stats.sessionId}\n\n`; + info += `${theme.bold("Messages")}\n`; + info += `${theme.fg("dim", "Total:")} ${stats.totalMessages}\n`; + info += `${theme.fg("dim", "User:")} ${stats.userMessages}\n`; + info += `${theme.fg("dim", "Assistant:")} ${stats.assistantMessages}\n`; + info += `${theme.fg("dim", "Tools:")} ${stats.toolCalls} calls, ${stats.toolResults} results\n\n`; + info += `${theme.bold("Tokens")}\n`; + // "Input" is the full prompt volume. With cache activity, split it into + // cached (served from cache) vs uncached (everything else) - the only + // provider-independent split. Cache writes, where reported, are a detail + // of the uncached portion. + const { input, cacheRead, cacheWrite } = stats.tokens; + const promptTokens = input + cacheRead + cacheWrite; + info += `${theme.fg("dim", "Input:")} ${promptTokens.toLocaleString()}\n`; + if (promptTokens > 0 && (cacheRead > 0 || cacheWrite > 0)) { + const hitRate = theme.fg("dim", `(${((cacheRead / promptTokens) * 100).toFixed(1)}%)`); + info += ` ${theme.fg("dim", "Cached:")} ${cacheRead.toLocaleString()} ${hitRate}\n`; + const written = cacheWrite > 0 ? ` ${theme.fg("dim", `(${cacheWrite.toLocaleString()} written to cache)`)}` : ""; + info += ` ${theme.fg("dim", "Uncached:")} ${(input + cacheWrite).toLocaleString()}${written}\n`; + } + info += `${theme.fg("dim", "Output:")} ${stats.tokens.output.toLocaleString()}\n`; + info += `${theme.fg("dim", "Total:")} ${stats.tokens.total.toLocaleString()}\n`; + if (stats.cost > 0 || cacheWaste.missedTokens > 0) { + info += `\n${theme.bold("Cost")}\n`; + info += `${theme.fg("dim", "Total:")} $${stats.cost.toFixed(3)}`; + if (usageBreakdown.length > 1) { + for (const entry of usageBreakdown) { + info += `\n ${theme.fg("dim", `${entry.key}:`)} $${entry.cost.toFixed(3)} ${theme.fg("dim", `(${formatTokens(entry.tokens)} tokens)`)}`; + } + } + if (cacheWaste.missedTokens > 0) { + const missLabel = cacheWaste.missCount === 1 ? "1 miss" : `${cacheWaste.missCount} misses`; + const detail = `${cacheWaste.missedTokens.toLocaleString()} tokens, ${missLabel}`; + info += + cacheWaste.missedCost >= 0.0001 + ? `\n${theme.fg("dim", "Cache Re-billed:")} $${cacheWaste.missedCost.toFixed(3)} ${theme.fg("dim", `(${detail})`)}` + : `\n${theme.fg("dim", "Cache Re-billed:")} ${detail}`; + } + } + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Text(info, 1, 0)); + this.ui.requestRender(); + } + handleChangelogCommand() { + const changelogPath = getChangelogPath(); + const allEntries = parseChangelog(changelogPath); + const changelogMarkdown = allEntries.length > 0 + ? allEntries + .reverse() + .map((e) => normalizeChangelogLinks(e.content, e)) + .join("\n\n") + : "No changelog entries found."; + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new DynamicBorder()); + this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0)); + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, this.getMarkdownThemeWithSettings())); + this.chatContainer.addChild(new DynamicBorder()); + this.ui.requestRender(); + } + /** + * Get capitalized display string for an app keybinding action. + */ + getAppKeyDisplay(action) { + return keyDisplayText(action); + } + /** + * Get capitalized display string for an editor keybinding action. + */ + getEditorKeyDisplay(action) { + return keyDisplayText(action); + } + handleHotkeysCommand() { + // Navigation keybindings + const cursorUp = this.getEditorKeyDisplay("tui.editor.cursorUp"); + const cursorDown = this.getEditorKeyDisplay("tui.editor.cursorDown"); + const cursorLeft = this.getEditorKeyDisplay("tui.editor.cursorLeft"); + const cursorRight = this.getEditorKeyDisplay("tui.editor.cursorRight"); + const cursorWordLeft = this.getEditorKeyDisplay("tui.editor.cursorWordLeft"); + const cursorWordRight = this.getEditorKeyDisplay("tui.editor.cursorWordRight"); + const cursorLineStart = this.getEditorKeyDisplay("tui.editor.cursorLineStart"); + const cursorLineEnd = this.getEditorKeyDisplay("tui.editor.cursorLineEnd"); + const jumpForward = this.getEditorKeyDisplay("tui.editor.jumpForward"); + const jumpBackward = this.getEditorKeyDisplay("tui.editor.jumpBackward"); + const pageUp = this.getEditorKeyDisplay("tui.editor.pageUp"); + const pageDown = this.getEditorKeyDisplay("tui.editor.pageDown"); + // Editing keybindings + const submit = this.getEditorKeyDisplay("tui.input.submit"); + const newLine = this.getEditorKeyDisplay("tui.input.newLine"); + const deleteWordBackward = this.getEditorKeyDisplay("tui.editor.deleteWordBackward"); + const deleteWordForward = this.getEditorKeyDisplay("tui.editor.deleteWordForward"); + const deleteToLineStart = this.getEditorKeyDisplay("tui.editor.deleteToLineStart"); + const deleteToLineEnd = this.getEditorKeyDisplay("tui.editor.deleteToLineEnd"); + const yank = this.getEditorKeyDisplay("tui.editor.yank"); + const yankPop = this.getEditorKeyDisplay("tui.editor.yankPop"); + const undo = this.getEditorKeyDisplay("tui.editor.undo"); + const tab = this.getEditorKeyDisplay("tui.input.tab"); + // App keybindings + const interrupt = this.getAppKeyDisplay("app.interrupt"); + const clear = this.getAppKeyDisplay("app.clear"); + const exit = this.getAppKeyDisplay("app.exit"); + const suspend = this.getAppKeyDisplay("app.suspend"); + const cycleThinkingLevel = this.getAppKeyDisplay("app.thinking.cycle"); + const cycleModelForward = this.getAppKeyDisplay("app.model.cycleForward"); + const selectModel = this.getAppKeyDisplay("app.model.select"); + const expandTools = this.getAppKeyDisplay("app.tools.expand"); + const toggleThinking = this.getAppKeyDisplay("app.thinking.toggle"); + const externalEditor = this.getAppKeyDisplay("app.editor.external"); + const cycleModelBackward = this.getAppKeyDisplay("app.model.cycleBackward"); + const copyMessage = this.getAppKeyDisplay("app.message.copy"); + const followUp = this.getAppKeyDisplay("app.message.followUp"); + const dequeue = this.getAppKeyDisplay("app.message.dequeue"); + const pasteImage = this.getAppKeyDisplay("app.clipboard.pasteImage"); + let hotkeys = ` +**Navigation** +| Key | Action | +|-----|--------| +| \`${cursorUp}\` / \`${cursorDown}\` / \`${cursorLeft}\` / \`${cursorRight}\` | Move cursor / browse history | +| \`${cursorWordLeft}\` / \`${cursorWordRight}\` | Move by word | +| \`${cursorLineStart}\` | Start of line | +| \`${cursorLineEnd}\` | End of line | +| \`${jumpForward}\` | Jump forward to character | +| \`${jumpBackward}\` | Jump backward to character | +| \`${pageUp}\` / \`${pageDown}\` | Scroll by page | + +**Editing** +| Key | Action | +|-----|--------| +| \`${submit}\` | Send message | +| \`${newLine}\` | New line${process.platform === "win32" ? " (Ctrl+Enter on Windows Terminal)" : ""} | +| \`${deleteWordBackward}\` | Delete word backwards | +| \`${deleteWordForward}\` | Delete word forwards | +| \`${deleteToLineStart}\` | Delete to start of line | +| \`${deleteToLineEnd}\` | Delete to end of line | +| \`${yank}\` | Paste the most-recently-deleted text | +| \`${yankPop}\` | Cycle through the deleted text after pasting | +| \`${undo}\` | Undo | + +**Other** +| Key | Action | +|-----|--------| +| \`${tab}\` | Path completion / accept autocomplete | +| \`${interrupt}\` | Cancel autocomplete / abort streaming | +| \`${clear}\` | Clear editor (first) / exit (second) | +| \`${exit}\` | Exit (when editor is empty) | +| \`${suspend}\` | Suspend to background | +| \`${cycleThinkingLevel}\` | Cycle thinking level | +| \`${cycleModelForward}\` / \`${cycleModelBackward}\` | Cycle models | +| \`${selectModel}\` | Open model selector | +| \`${expandTools}\` | Toggle tool output expansion | +| \`${toggleThinking}\` | Toggle thinking block visibility | +| \`${externalEditor}\` | Edit message in external editor | +| \`${copyMessage}\` | Copy last assistant message | +| \`${followUp}\` | Queue follow-up message | +| \`${dequeue}\` | Restore queued messages | +| \`${pasteImage}\` | Paste image or text from clipboard | +| \`/\` | Slash commands | +| \`!\` | Run bash command | +| \`!!\` | Run bash command (excluded from context) | +`; + // Add extension-registered shortcuts + const extensionRunner = this.session.extensionRunner; + const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig()); + if (shortcuts.size > 0) { + hotkeys += ` +**Extensions** +| Key | Action | +|-----|--------| +`; + for (const [key, shortcut] of shortcuts) { + const description = shortcut.description ?? shortcut.extensionPath; + const keyDisplay = formatKeyText(key, { capitalize: true }); + hotkeys += `| \`${keyDisplay}\` | ${description} |\n`; + } + } + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new DynamicBorder()); + this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "Keyboard Shortcuts")), 1, 0)); + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Markdown(hotkeys.trim(), 1, 1, this.getMarkdownThemeWithSettings())); + this.chatContainer.addChild(new DynamicBorder()); + this.ui.requestRender(); + } + async handleClearCommand() { + this.clearStatusIndicator(); + try { + const result = await this.runtimeHost.newSession(); + if (result.cancelled) { + return; + } + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ New session started")}`, 1, 1)); + this.ui.requestRender(); + } + catch (error) { + await this.handleFatalRuntimeError("Failed to create session", error); + } + } + handleDebugCommand() { + const width = this.ui.terminal.columns; + const height = this.ui.terminal.rows; + const allLines = this.ui.render(width); + const debugLogPath = getDebugLogPath(); + const debugData = [ + `Debug output at ${new Date().toISOString()}`, + `Terminal: ${width}x${height}`, + `Total lines: ${allLines.length}`, + "", + "=== All rendered lines with visible widths ===", + ...allLines.map((line, idx) => { + const vw = visibleWidth(line); + const escaped = JSON.stringify(line); + return `[${idx}] (w=${vw}) ${escaped}`; + }), + "", + "=== Agent messages (JSONL) ===", + ...this.session.messages.map((msg) => JSON.stringify(msg)), + "", + ].join("\n"); + fs.mkdirSync(path.dirname(debugLogPath), { recursive: true }); + fs.writeFileSync(debugLogPath, debugData); + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ Debug log written")}\n${theme.fg("muted", debugLogPath)}`, 1, 1)); + this.ui.requestRender(); + } + handleArminSaysHi() { + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new ArminComponent(this.ui)); + this.ui.requestRender(); + } + handleDementedDelves() { + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new EarendilAnnouncementComponent()); + this.ui.requestRender(); + } + handleDaxnuts() { + this.chatContainer.addChild(new Spacer(1)); + this.chatContainer.addChild(new DaxnutsComponent(this.ui)); + this.ui.requestRender(); + } + checkDaxnutsEasterEgg(model) { + if (model.provider === "opencode" && model.id.toLowerCase().includes("kimi-k2.5")) { + this.handleDaxnuts(); + } + } + async handleBashCommand(command, excludeFromContext = false) { + const extensionRunner = this.session.extensionRunner; + // Emit user_bash event to let extensions intercept + const eventResult = await extensionRunner.emitUserBash({ + type: "user_bash", + command, + excludeFromContext, + cwd: this.sessionManager.getCwd(), + }); + // If extension returned a full result, use it directly + if (eventResult?.result) { + const result = eventResult.result; + // Create UI component for display + this.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext); + if (this.session.isStreaming) { + this.pendingMessagesContainer.addChild(this.bashComponent); + this.pendingBashComponents.push(this.bashComponent); + } + else { + this.chatContainer.addChild(this.bashComponent); + } + // Show output and complete + if (result.output) { + this.bashComponent.appendOutput(result.output); + } + this.bashComponent.setComplete(result.exitCode, result.cancelled, result.truncated ? { truncated: true, content: result.output } : undefined, result.fullOutputPath); + // Record the result in session + this.session.recordBashResult(command, result, { excludeFromContext }); + this.bashComponent = undefined; + this.ui.requestRender(); + return; + } + // Normal execution path (possibly with custom operations) + const isDeferred = this.session.isStreaming; + this.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext); + if (isDeferred) { + // Show in pending area when agent is streaming + this.pendingMessagesContainer.addChild(this.bashComponent); + this.pendingBashComponents.push(this.bashComponent); + } + else { + // Show in chat immediately when agent is idle + this.chatContainer.addChild(this.bashComponent); + } + this.ui.requestRender(); + try { + const result = await this.session.executeBash(command, (chunk) => { + if (this.bashComponent) { + this.bashComponent.appendOutput(chunk); + this.ui.requestRender(); + } + }, { excludeFromContext, operations: eventResult?.operations }); + if (this.bashComponent) { + this.bashComponent.setComplete(result.exitCode, result.cancelled, result.truncated ? { truncated: true, content: result.output } : undefined, result.fullOutputPath); + } + } + catch (error) { + if (this.bashComponent) { + this.bashComponent.setComplete(undefined, false); + } + this.showError(`Bash command failed: ${error instanceof Error ? error.message : "Unknown error"}`); + } + this.bashComponent = undefined; + this.ui.requestRender(); + } + async handleCompactCommand(customInstructions) { + this.clearStatusIndicator(); + try { + await this.session.compact(customInstructions); + } + catch { + // Ignore, will be emitted as an event + } + } + stop() { + if (this.settingsManager.getShowTerminalProgress()) { + this.ui.terminal.setProgress(false); + } + this.clearStatusIndicator(); + this.themeController.disableAutoSync(); + this.clearExtensionTerminalInputListeners(); + this.footer.dispose(); + this.footerDataProvider.dispose(); + if (this.unsubscribe) { + this.unsubscribe(); + } + if (this.isInitialized) { + this.ui.stop(); + this.isInitialized = false; + } + this.unregisterSignalHandlers(); + } +} +//# sourceMappingURL=interactive-mode.js.map \ No newline at end of file diff --git a/dist/modes/interactive/interactive-mode.js.map b/dist/modes/interactive/interactive-mode.js.map new file mode 100644 index 0000000..88ee6fc --- /dev/null +++ b/dist/modes/interactive/interactive-mode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"interactive-mode.js","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-mode.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAelC,OAAO,EACN,4BAA4B,EAE5B,SAAS,EACT,WAAW,EACX,eAAe,EACf,SAAS,EACT,QAAQ,EACR,UAAU,EACV,eAAe,EACf,MAAM,EACN,cAAc,EACd,IAAI,EACJ,aAAa,EACb,GAAG,EACH,YAAY,GACZ,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EACN,QAAQ,EACR,SAAS,EACT,eAAe,EACf,WAAW,EACX,WAAW,EACX,eAAe,EACf,WAAW,EACX,iBAAiB,EACjB,OAAO,GACP,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAA6C,eAAe,EAAE,MAAM,6BAA6B,CAAC;AACzG,OAAO,EAA4B,8BAA8B,EAAE,MAAM,qCAAqC,CAAC;AAC/G,OAAO,EACN,YAAY,EAEZ,kBAAkB,EAClB,iBAAiB,EACjB,eAAe,GACf,MAAM,2BAA2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;IAAA,CACD;IAED,IAAI,GAAS;QACZ,IAAI,IAAI,CAAC,eAAe,CAAC,uBAAuB,EAAE,EAAE,CAAC;YACpD,IAAI,CAAC,EAAE,CAAC,QAAQ,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;QACrC,CAAC;QACD,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAC5B,IAAI,CAAC,eAAe,CAAC,eAAe,EAAE,CAAC;QACvC,IAAI,CAAC,oCAAoC,EAAE,CAAC;QAC5C,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACtB,IAAI,CAAC,kBAAkB,CAAC,OAAO,EAAE,CAAC;QAClC,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACtB,IAAI,CAAC,WAAW,EAAE,CAAC;QACpB,CAAC;QACD,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YACxB,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC;YACf,IAAI,CAAC,aAAa,GAAG,KAAK,CAAC;QAC5B,CAAC;QACD,IAAI,CAAC,wBAAwB,EAAE,CAAC;IAAA,CAChC;CACD","sourcesContent":["/**\n * Interactive mode for the coding agent.\n * Handles TUI rendering and user interaction, delegating business logic to AgentSession.\n */\n\nimport * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AuthEvent, AuthPrompt } from \"@earendil-works/pi-ai\";\nimport type { AssistantMessage, ImageContent, Message, Model } from \"@earendil-works/pi-ai/compat\";\nimport type {\n\tAutocompleteItem,\n\tAutocompleteProvider,\n\tEditorComponent,\n\tKeybinding,\n\tKeyId,\n\tMarkdownTheme,\n\tOverlayHandle,\n\tOverlayOptions,\n\tSlashCommand,\n} from \"@earendil-works/pi-tui\";\nimport {\n\tCombinedAutocompleteProvider,\n\ttype Component,\n\tContainer,\n\tfuzzyFilter,\n\tgetCapabilities,\n\thyperlink,\n\tMarkdown,\n\tmatchesKey,\n\tProcessTerminal,\n\tSpacer,\n\tsetKeybindings,\n\tText,\n\tTruncatedText,\n\tTUI,\n\tvisibleWidth,\n} from \"@earendil-works/pi-tui\";\nimport chalk from \"chalk\";\nimport { spawn, spawnSync } from \"child_process\";\nimport {\n\tAPP_NAME,\n\tAPP_TITLE,\n\tCONFIG_DIR_NAME,\n\tgetAgentDir,\n\tgetAuthPath,\n\tgetDebugLogPath,\n\tgetDocsPath,\n\tgetShareViewerUrl,\n\tVERSION,\n} from \"../../config.ts\";\nimport { type AgentSession, type AgentSessionEvent, parseSkillBlock } from \"../../core/agent-session.ts\";\nimport { type AgentSessionRuntime, SessionImportFileNotFoundError } from \"../../core/agent-session-runtime.ts\";\nimport {\n\tCACHE_TTL_MS,\n\ttype CacheMiss,\n\tcollectCacheMisses,\n\tcomputeCacheWaste,\n\tdetectCacheMiss,\n} from \"../../core/cache-stats.ts\";\nimport type {\n\tAutocompleteProviderFactory,\n\tEditorFactory,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tProjectTrustContext,\n\tWorkingIndicatorOptions,\n} from \"../../core/extensions/index.ts\";\nimport { FooterDataProvider, type ReadonlyFooterDataProvider } from \"../../core/footer-data-provider.ts\";\nimport { configureHttpDispatcher, formatHttpIdleTimeoutMs } from \"../../core/http-dispatcher.ts\";\nimport { type AppKeybinding, KeybindingsManager } from \"../../core/keybindings.ts\";\nimport { createCompactionSummaryMessage } from \"../../core/messages.ts\";\nimport {\n\tdefaultModelPerProvider,\n\tfindExactModelReferenceMatch,\n\tresolveModelScope,\n\tresolveModelScopeWithDiagnostics,\n} from \"../../core/model-resolver.ts\";\nimport { DefaultPackageManager } from \"../../core/package-manager.ts\";\nimport type { ResourceDiagnostic } from \"../../core/resource-loader.ts\";\nimport { formatMissingSessionCwdPrompt, MissingSessionCwdError } from \"../../core/session-cwd.ts\";\nimport { type SessionEntry, SessionManager, sessionEntryToContextMessages } from \"../../core/session-manager.ts\";\nimport { BUILTIN_SLASH_COMMANDS } from \"../../core/slash-commands.ts\";\nimport type { SourceInfo } from \"../../core/source-info.ts\";\nimport { isInstallTelemetryEnabled } from \"../../core/telemetry.ts\";\nimport type { TruncationResult } from \"../../core/tools/truncate.ts\";\nimport { hasTrustRequiringProjectResources, ProjectTrustStore } from \"../../core/trust-manager.ts\";\nimport { getUsageCostBreakdown } from \"../../core/usage-totals.ts\";\nimport { getChangelogPath, getNewEntries, normalizeChangelogLinks, parseChangelog } from \"../../utils/changelog.ts\";\nimport { copyToClipboard, readClipboardText } from \"../../utils/clipboard.ts\";\nimport { extensionForImageMimeType, readClipboardImage } from \"../../utils/clipboard-image.ts\";\nimport { parseGitUrl } from \"../../utils/git.ts\";\nimport { getCwdRelativePath } from \"../../utils/paths.ts\";\nimport { getPiUserAgent } from \"../../utils/pi-user-agent.ts\";\nimport { killTrackedDetachedChildren } from \"../../utils/shell.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport { checkForNewPiVersion, type LatestPiRelease } from \"../../utils/version-check.ts\";\nimport { ArminComponent } from \"./components/armin.ts\";\nimport { AssistantMessageComponent } from \"./components/assistant-message.ts\";\nimport { BashExecutionComponent } from \"./components/bash-execution.ts\";\nimport { BorderedLoader } from \"./components/bordered-loader.ts\";\nimport { BranchSummaryMessageComponent } from \"./components/branch-summary-message.ts\";\nimport { CompactionSummaryMessageComponent } from \"./components/compaction-summary-message.ts\";\nimport { CustomEditor } from \"./components/custom-editor.ts\";\nimport { CustomEntryComponent } from \"./components/custom-entry.ts\";\nimport { CustomMessageComponent } from \"./components/custom-message.ts\";\nimport { DaxnutsComponent } from \"./components/daxnuts.ts\";\nimport { DynamicBorder } from \"./components/dynamic-border.ts\";\nimport { EarendilAnnouncementComponent } from \"./components/earendil-announcement.ts\";\nimport { ExtensionEditorComponent } from \"./components/extension-editor.ts\";\nimport { ExtensionInputComponent } from \"./components/extension-input.ts\";\nimport { ExtensionSelectorComponent } from \"./components/extension-selector.ts\";\nimport { FooterComponent, formatTokens } from \"./components/footer.ts\";\nimport { formatKeyText, keyDisplayText, keyHint, keyText, rawKeyHint } from \"./components/keybinding-hints.ts\";\nimport { LoginDialogComponent } from \"./components/login-dialog.ts\";\nimport { ModelSelectorComponent } from \"./components/model-selector.ts\";\nimport {\n\ttype AuthSelectorProvider,\n\tformatAuthSelectorProviderType,\n\tOAuthSelectorComponent,\n} from \"./components/oauth-selector.ts\";\nimport { ScopedModelsSelectorComponent } from \"./components/scoped-models-selector.ts\";\nimport { SessionSelectorComponent } from \"./components/session-selector.ts\";\nimport { SettingsSelectorComponent } from \"./components/settings-selector.ts\";\nimport { SkillInvocationMessageComponent } from \"./components/skill-invocation-message.ts\";\nimport {\n\tBranchSummaryStatusIndicator,\n\tCompactionStatusIndicator,\n\tIdleStatus,\n\tRetryStatusIndicator,\n\ttype StatusIndicator,\n\tWorkingStatusIndicator,\n} from \"./components/status-indicator.ts\";\nimport { ToolExecutionComponent } from \"./components/tool-execution.ts\";\nimport { TreeSelectorComponent } from \"./components/tree-selector.ts\";\nimport { TrustSelectorComponent } from \"./components/trust-selector.ts\";\nimport { UserMessageComponent } from \"./components/user-message.ts\";\nimport { UserMessageSelectorComponent } from \"./components/user-message-selector.ts\";\nimport { editInExternalEditor } from \"./external-editor.ts\";\nimport { getModelSearchText } from \"./model-search.ts\";\nimport {\n\tgetAvailableThemes,\n\tgetAvailableThemesWithPaths,\n\tgetEditorTheme,\n\tgetMarkdownTheme,\n\tgetThemeByName,\n\tonThemeChange,\n\tsetRegisteredThemes,\n\tstopThemeWatcher,\n\tTheme,\n\ttype ThemeColor,\n\ttheme,\n} from \"./theme/theme.ts\";\nimport { InteractiveThemeController } from \"./theme/theme-controller.ts\";\n\n/** Interface for components that can be expanded/collapsed */\ninterface Expandable {\n\tsetExpanded(expanded: boolean): void;\n}\n\nfunction isExpandable(obj: unknown): obj is Expandable {\n\treturn typeof obj === \"object\" && obj !== null && \"setExpanded\" in obj && typeof obj.setExpanded === \"function\";\n}\n\nclass ExpandableText extends Text implements Expandable {\n\tprivate readonly getCollapsedText: () => string;\n\tprivate readonly getExpandedText: () => string;\n\n\tconstructor(\n\t\tgetCollapsedText: () => string,\n\t\tgetExpandedText: () => string,\n\t\texpanded = false,\n\t\tpaddingX = 0,\n\t\tpaddingY = 0,\n\t) {\n\t\tsuper(expanded ? getExpandedText() : getCollapsedText(), paddingX, paddingY);\n\t\tthis.getCollapsedText = getCollapsedText;\n\t\tthis.getExpandedText = getExpandedText;\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.setText(expanded ? this.getExpandedText() : this.getCollapsedText());\n\t}\n}\n\ntype CompactionQueuedMessage = {\n\ttext: string;\n\tmode: \"steer\" | \"followUp\";\n};\n\ntype RenderSessionItem = AgentMessage | Extract;\n\nfunction isCustomSessionEntry(item: RenderSessionItem): item is Extract {\n\treturn \"type\" in item && item.type === \"custom\";\n}\n\nconst DEAD_TERMINAL_ERROR_CODES = new Set([\"EIO\", \"EPIPE\", \"ENOTCONN\"]);\n\nfunction isDeadTerminalError(error: unknown): boolean {\n\tif (!error || typeof error !== \"object\" || !(\"code\" in error)) {\n\t\treturn false;\n\t}\n\tconst code = (error as NodeJS.ErrnoException).code;\n\treturn code !== undefined && DEAD_TERMINAL_ERROR_CODES.has(code);\n}\n\nconst ANTHROPIC_SUBSCRIPTION_AUTH_WARNING =\n\t\"Anthropic subscription auth is active. Third-party harness usage draws from extra usage and is billed per token, not your Claude plan limits. Manage extra usage at https://claude.ai/settings/usage. Disable this warning in /settings.\";\n\nfunction isAnthropicSubscriptionAuthKey(apiKey: string | undefined): boolean {\n\treturn typeof apiKey === \"string\" && apiKey.startsWith(\"sk-ant-oat\");\n}\n\nfunction isUnknownModel(model: Model | undefined): boolean {\n\treturn !!model && model.provider === \"unknown\" && model.id === \"unknown\" && model.api === \"unknown\";\n}\n\nfunction quoteIfNeeded(value: string): string {\n\tif (value.length > 0 && !/[^a-zA-Z0-9_\\-./~:@]/.test(value)) {\n\t\treturn value;\n\t}\n\treturn `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\nexport function formatResumeCommand(sessionManager: SessionManager): string | undefined {\n\tif (!process.stdout.isTTY) return undefined;\n\tif (!sessionManager.isPersisted()) return undefined;\n\n\tconst sessionFile = sessionManager.getSessionFile();\n\tif (!sessionFile || !fs.existsSync(sessionFile)) return undefined;\n\n\tconst args = [APP_NAME];\n\tif (!sessionManager.usesDefaultSessionDir()) {\n\t\targs.push(\"--session-dir\", quoteIfNeeded(sessionManager.getSessionDir()));\n\t}\n\targs.push(\"--session\", sessionManager.getSessionId());\n\treturn args.join(\" \");\n}\n\nfunction hasDefaultModelProvider(providerId: string): providerId is keyof typeof defaultModelPerProvider {\n\treturn providerId in defaultModelPerProvider;\n}\n\ntype LoginProviderCompletionOption = {\n\tid: string;\n\tname: string;\n\tauthTypes: AuthSelectorProvider[\"authType\"][];\n};\n\nconst AUTH_TYPE_ORDER = { oauth: 0, api_key: 1 } satisfies Record;\n\nfunction createFuzzyAutocompleteItems(\n\titems: T[],\n\tprefix: string,\n\tgetSearchText: (item: T) => string,\n\ttoAutocompleteItem: (item: T) => AutocompleteItem,\n): AutocompleteItem[] | null {\n\tconst filtered = fuzzyFilter(items, prefix, getSearchText);\n\tif (filtered.length === 0) return null;\n\treturn filtered.map(toAutocompleteItem);\n}\n\nfunction getLoginProviderCompletionOptions(\n\tproviderOptions: readonly AuthSelectorProvider[],\n): LoginProviderCompletionOption[] {\n\tconst byId = new Map();\n\tfor (const provider of providerOptions) {\n\t\tconst existing = byId.get(provider.id);\n\t\tif (existing) {\n\t\t\tif (!existing.authTypes.includes(provider.authType)) {\n\t\t\t\texisting.authTypes.push(provider.authType);\n\t\t\t\texisting.authTypes.sort((a, b) => AUTH_TYPE_ORDER[a] - AUTH_TYPE_ORDER[b]);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tbyId.set(provider.id, {\n\t\t\tid: provider.id,\n\t\t\tname: provider.name,\n\t\t\tauthTypes: [provider.authType],\n\t\t});\n\t}\n\treturn Array.from(byId.values()).sort((a, b) => a.name.localeCompare(b.name));\n}\n\nfunction getLoginProviderSearchText(provider: LoginProviderCompletionOption): string {\n\tconst authTypes = provider.authTypes\n\t\t.map((authType) => `${authType} ${formatAuthSelectorProviderType(authType)}`)\n\t\t.join(\" \");\n\treturn `${provider.id} ${provider.name} ${authTypes}`;\n}\n\nfunction formatLoginProviderCompletionDescription(provider: LoginProviderCompletionOption): string {\n\tconst authTypes = provider.authTypes.map(formatAuthSelectorProviderType).join(\"/\");\n\treturn provider.name === provider.id ? authTypes : `${provider.name} · ${authTypes}`;\n}\n\n/**\n * Options for InteractiveMode initialization.\n */\nexport interface InteractiveModeOptions {\n\t/** Providers that were migrated to auth.json (shows warning) */\n\tmigratedProviders?: string[];\n\t/** Warning message if session model couldn't be restored */\n\tmodelFallbackMessage?: string;\n\t/** Cwd to trust after reload if it gained a .pi directory during this implicitly trusted session. */\n\tautoTrustOnReloadCwd?: string;\n\t/** Initial message to send on startup (can include @file content) */\n\tinitialMessage?: string;\n\t/** Images to attach to the initial message */\n\tinitialImages?: ImageContent[];\n\t/** Additional messages to send after the initial message */\n\tinitialMessages?: string[];\n\t/** Force verbose startup (overrides quietStartup setting) */\n\tverbose?: boolean;\n}\n\nexport class InteractiveMode {\n\tprivate runtimeHost: AgentSessionRuntime;\n\tprivate ui: TUI;\n\tprivate loadedResourcesContainer: Container;\n\tprivate chatContainer: Container;\n\tprivate pendingMessagesContainer: Container;\n\tprivate statusContainer: Container;\n\tprivate defaultEditor: CustomEditor;\n\tprivate editor: EditorComponent;\n\tprivate editorComponentFactory: EditorFactory | undefined;\n\tprivate autocompleteProvider: AutocompleteProvider | undefined;\n\tprivate autocompleteProviderWrappers: AutocompleteProviderFactory[] = [];\n\tprivate fdPath: string | undefined;\n\tprivate editorContainer: Container;\n\tprivate footer: FooterComponent;\n\tprivate footerDataProvider: FooterDataProvider;\n\t// Stored so the same manager can be injected into custom editors, selectors, and extension UI.\n\tprivate keybindings: KeybindingsManager;\n\tprivate version: string;\n\tprivate isInitialized = false;\n\tprivate onInputCallback?: (text: string) => void;\n\tprivate pendingUserInputs: string[] = [];\n\tprivate activeStatusIndicator: StatusIndicator | undefined = undefined;\n\tprivate readonly idleStatus = new IdleStatus();\n\tprivate workingMessage: string | undefined = undefined;\n\tprivate workingVisible = true;\n\tprivate workingIndicatorOptions: WorkingIndicatorOptions | undefined = undefined;\n\tprivate readonly defaultWorkingMessage = \"Working...\";\n\tprivate readonly defaultHiddenThinkingLabel = \"Thinking...\";\n\tprivate hiddenThinkingLabel = this.defaultHiddenThinkingLabel;\n\n\tprivate lastSigintTime = 0;\n\tprivate lastEscapeTime = 0;\n\tprivate changelogMarkdown: string | undefined = undefined;\n\tprivate startupNoticesShown = false;\n\tprivate anthropicSubscriptionWarningShown = false;\n\n\t// Status line tracking (for mutating immediately-sequential status updates)\n\tprivate lastStatusSpacer: Spacer | undefined = undefined;\n\tprivate lastStatusText: Text | undefined = undefined;\n\n\t// Streaming message tracking\n\tprivate streamingComponent: AssistantMessageComponent | undefined = undefined;\n\tprivate streamingMessage: AssistantMessage | undefined = undefined;\n\n\t// Tool execution tracking: toolCallId -> component\n\tprivate pendingTools = new Map();\n\n\t// Tool output expansion state\n\tprivate toolOutputExpanded = false;\n\n\t// Thinking block visibility state\n\tprivate hideThinkingBlock = false;\n\tprivate outputPad = 1;\n\n\t// Skill commands: command name -> skill file path\n\tprivate skillCommands = new Map();\n\n\t// Agent subscription unsubscribe function\n\tprivate unsubscribe?: () => void;\n\tprivate signalCleanupHandlers: Array<() => void> = [];\n\n\t// Track if editor is in bash mode (text starts with !)\n\tprivate isBashMode = false;\n\n\t// Track current bash execution component\n\tprivate bashComponent: BashExecutionComponent | undefined = undefined;\n\n\t// Track pending bash components (shown in pending area, moved to chat on submit)\n\tprivate pendingBashComponents: BashExecutionComponent[] = [];\n\n\t// Auto-compaction state\n\tprivate autoCompactionEscapeHandler?: () => void;\n\n\t// Auto-retry state\n\tprivate retryEscapeHandler?: () => void;\n\n\t// Messages queued while compaction is running\n\tprivate compactionQueuedMessages: CompactionQueuedMessage[] = [];\n\n\t// Shutdown state\n\tprivate shutdownRequested = false;\n\n\t// Extension UI state\n\tprivate extensionSelector: ExtensionSelectorComponent | undefined = undefined;\n\tprivate extensionInput: ExtensionInputComponent | undefined = undefined;\n\tprivate extensionEditor: ExtensionEditorComponent | undefined = undefined;\n\tprivate extensionTerminalInputUnsubscribers = new Set<() => void>();\n\n\t// Extension widgets (components rendered above/below the editor)\n\tprivate extensionWidgetsAbove = new Map();\n\tprivate extensionWidgetsBelow = new Map();\n\tprivate widgetContainerAbove!: Container;\n\tprivate widgetContainerBelow!: Container;\n\n\t// Custom footer from extension (undefined = use built-in footer)\n\tprivate customFooter: (Component & { dispose?(): void }) | undefined = undefined;\n\n\t// Header container that holds the built-in or custom header\n\tprivate headerContainer: Container;\n\n\t// Built-in header (logo + keybinding hints + changelog)\n\tprivate builtInHeader: Component | undefined = undefined;\n\n\t// Custom header from extension (undefined = use built-in header)\n\tprivate customHeader: (Component & { dispose?(): void }) | undefined = undefined;\n\n\tprivate options: InteractiveModeOptions;\n\tprivate autoTrustOnReloadCwd: string | undefined;\n\tprivate themeController: InteractiveThemeController;\n\n\t// Convenience accessors\n\tprivate get session(): AgentSession {\n\t\treturn this.runtimeHost.session;\n\t}\n\tprivate get agent() {\n\t\treturn this.session.agent;\n\t}\n\tprivate get sessionManager() {\n\t\treturn this.session.sessionManager;\n\t}\n\tprivate get settingsManager() {\n\t\treturn this.session.settingsManager;\n\t}\n\n\tconstructor(runtimeHost: AgentSessionRuntime, options: InteractiveModeOptions = {}) {\n\t\tthis.runtimeHost = runtimeHost;\n\t\tthis.options = options;\n\t\tthis.autoTrustOnReloadCwd = options.autoTrustOnReloadCwd;\n\t\tthis.runtimeHost.setBeforeSessionInvalidate(() => {\n\t\t\tthis.resetExtensionUI();\n\t\t});\n\t\tthis.runtimeHost.setRebindSession(async () => {\n\t\t\tawait this.rebindCurrentSession({ renderBeforeBind: true });\n\t\t});\n\t\tthis.version = VERSION;\n\t\tthis.ui = new TUI(new ProcessTerminal(), this.settingsManager.getShowHardwareCursor(), getAgentDir());\n\t\tthis.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());\n\t\tthis.headerContainer = new Container();\n\t\tthis.loadedResourcesContainer = new Container();\n\t\tthis.chatContainer = new Container();\n\t\tthis.pendingMessagesContainer = new Container();\n\t\tthis.statusContainer = new Container();\n\t\tthis.widgetContainerAbove = new Container();\n\t\tthis.widgetContainerBelow = new Container();\n\t\tthis.keybindings = KeybindingsManager.create();\n\t\tsetKeybindings(this.keybindings);\n\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\tthis.defaultEditor = new CustomEditor(this.ui, getEditorTheme(), this.keybindings, {\n\t\t\tpaddingX: editorPaddingX,\n\t\t\tautocompleteMaxVisible,\n\t\t});\n\t\tthis.editor = this.defaultEditor;\n\t\tthis.editorContainer = new Container();\n\t\tthis.editorContainer.addChild(this.editor as Component);\n\t\tthis.footerDataProvider = new FooterDataProvider(this.sessionManager.getCwd());\n\t\tthis.footer = new FooterComponent(this.session, this.footerDataProvider);\n\t\tthis.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);\n\n\t\t// Load hide thinking block setting\n\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\n\t\t// Register themes from resource loader and initialize\n\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\tthis.themeController = new InteractiveThemeController(\n\t\t\tthis.ui,\n\t\t\tthis.settingsManager,\n\t\t\t(message) => this.showError(message),\n\t\t\t() => this.updateEditorBorderColor(),\n\t\t);\n\t}\n\n\tprivate getAutocompleteSourceTag(sourceInfo?: SourceInfo): string | undefined {\n\t\tif (!sourceInfo) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst scopePrefix = sourceInfo.scope === \"user\" ? \"u\" : sourceInfo.scope === \"project\" ? \"p\" : \"t\";\n\t\tconst source = sourceInfo.source.trim();\n\n\t\tif (source === \"auto\" || source === \"local\" || source === \"cli\") {\n\t\t\treturn scopePrefix;\n\t\t}\n\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\treturn `${scopePrefix}:${source}`;\n\t\t}\n\n\t\tconst gitSource = parseGitUrl(source);\n\t\tif (gitSource) {\n\t\t\tconst ref = gitSource.ref ? `@${gitSource.ref}` : \"\";\n\t\t\treturn `${scopePrefix}:git:${gitSource.host}/${gitSource.path}${ref}`;\n\t\t}\n\n\t\treturn scopePrefix;\n\t}\n\n\tprivate prefixAutocompleteDescription(description: string | undefined, sourceInfo?: SourceInfo): string | undefined {\n\t\tconst sourceTag = this.getAutocompleteSourceTag(sourceInfo);\n\t\tif (!sourceTag) {\n\t\t\treturn description;\n\t\t}\n\t\treturn description ? `[${sourceTag}] ${description}` : `[${sourceTag}]`;\n\t}\n\n\tprivate getBuiltInCommandConflictDiagnostics(extensionRunner: ExtensionRunner): ResourceDiagnostic[] {\n\t\tconst builtinNames = new Set(BUILTIN_SLASH_COMMANDS.map((command) => command.name));\n\t\treturn extensionRunner\n\t\t\t.getRegisteredCommands()\n\t\t\t.filter((command) => builtinNames.has(command.name))\n\t\t\t.map((command) => ({\n\t\t\t\ttype: \"warning\" as const,\n\t\t\t\tmessage:\n\t\t\t\t\tcommand.invocationName === command.name\n\t\t\t\t\t\t? `Extension command '/${command.name}' conflicts with built-in interactive command. Skipping in autocomplete.`\n\t\t\t\t\t\t: `Extension command '/${command.name}' conflicts with built-in interactive command. Available as '/${command.invocationName}'.`,\n\t\t\t\tpath: command.sourceInfo.path,\n\t\t\t}));\n\t}\n\n\tprivate createBaseAutocompleteProvider(): AutocompleteProvider {\n\t\t// Define commands for autocomplete\n\t\tconst slashCommands: SlashCommand[] = BUILTIN_SLASH_COMMANDS.map((command) => ({\n\t\t\tname: command.name,\n\t\t\tdescription: command.description,\n\t\t\t...(command.argumentHint && { argumentHint: command.argumentHint }),\n\t\t}));\n\n\t\tconst modelCommand = slashCommands.find((command) => command.name === \"model\");\n\t\tif (modelCommand) {\n\t\t\tmodelCommand.getArgumentCompletions = async (prefix: string): Promise => {\n\t\t\t\t// Get available models (scoped or from registry)\n\t\t\t\tconst models =\n\t\t\t\t\tthis.session.scopedModels.length > 0\n\t\t\t\t\t\t? this.session.scopedModels.map((s) => s.model)\n\t\t\t\t\t\t: await this.session.modelRuntime.getAvailable();\n\n\t\t\t\tif (models.length === 0) return null;\n\n\t\t\t\t// Create items with provider/id format\n\t\t\t\tconst items = models.map((m) => ({\n\t\t\t\t\tid: m.id,\n\t\t\t\t\tprovider: m.provider,\n\t\t\t\t\tname: m.name,\n\t\t\t\t\tlabel: `${m.provider}/${m.id}`,\n\t\t\t\t}));\n\n\t\t\t\treturn createFuzzyAutocompleteItems(items, prefix, getModelSearchText, (item) => ({\n\t\t\t\t\tvalue: item.label,\n\t\t\t\t\tlabel: item.id,\n\t\t\t\t\tdescription: item.provider,\n\t\t\t\t}));\n\t\t\t};\n\t\t}\n\n\t\tconst loginCommand = slashCommands.find((command) => command.name === \"login\");\n\t\tif (loginCommand) {\n\t\t\tloginCommand.getArgumentCompletions = (prefix: string): AutocompleteItem[] | null => {\n\t\t\t\tconst providers = getLoginProviderCompletionOptions(this.getLoginProviderOptions());\n\t\t\t\treturn createFuzzyAutocompleteItems(providers, prefix, getLoginProviderSearchText, (provider) => ({\n\t\t\t\t\tvalue: provider.id,\n\t\t\t\t\tlabel: provider.id,\n\t\t\t\t\tdescription: formatLoginProviderCompletionDescription(provider),\n\t\t\t\t}));\n\t\t\t};\n\t\t}\n\n\t\t// Convert prompt templates to SlashCommand format for autocomplete\n\t\tconst templateCommands: SlashCommand[] = this.session.promptTemplates.map((cmd) => ({\n\t\t\tname: cmd.name,\n\t\t\tdescription: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),\n\t\t\t...(cmd.argumentHint && { argumentHint: cmd.argumentHint }),\n\t\t}));\n\n\t\t// Convert extension commands to SlashCommand format\n\t\tconst builtinCommandNames = new Set(slashCommands.map((c) => c.name));\n\t\tconst extensionCommands: SlashCommand[] = this.session.extensionRunner\n\t\t\t.getRegisteredCommands()\n\t\t\t.filter((cmd) => !builtinCommandNames.has(cmd.name))\n\t\t\t.map((cmd) => ({\n\t\t\t\tname: cmd.invocationName,\n\t\t\t\tdescription: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),\n\t\t\t\tgetArgumentCompletions: cmd.getArgumentCompletions,\n\t\t\t}));\n\n\t\t// Build skill commands from session.skills (if enabled)\n\t\tthis.skillCommands.clear();\n\t\tconst skillCommandList: SlashCommand[] = [];\n\t\tif (this.settingsManager.getEnableSkillCommands()) {\n\t\t\tfor (const skill of this.session.resourceLoader.getSkills().skills) {\n\t\t\t\tconst commandName = `skill:${skill.name}`;\n\t\t\t\tthis.skillCommands.set(commandName, skill.filePath);\n\t\t\t\tskillCommandList.push({\n\t\t\t\t\tname: commandName,\n\t\t\t\t\tdescription: this.prefixAutocompleteDescription(skill.description, skill.sourceInfo),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn new CombinedAutocompleteProvider(\n\t\t\t[...slashCommands, ...templateCommands, ...extensionCommands, ...skillCommandList],\n\t\t\tthis.sessionManager.getCwd(),\n\t\t\tthis.fdPath,\n\t\t);\n\t}\n\n\tprivate setupAutocompleteProvider(): void {\n\t\tlet provider = this.createBaseAutocompleteProvider();\n\t\tconst triggerCharacters: string[] = [];\n\t\tfor (const wrapProvider of this.autocompleteProviderWrappers) {\n\t\t\tprovider = wrapProvider(provider);\n\t\t\ttriggerCharacters.push(...(provider.triggerCharacters ?? []));\n\t\t}\n\t\tif (triggerCharacters.length > 0) {\n\t\t\tprovider.triggerCharacters = [...new Set(triggerCharacters)];\n\t\t}\n\n\t\tthis.autocompleteProvider = provider;\n\t\tthis.defaultEditor.setAutocompleteProvider(provider);\n\t\tif (this.editor !== this.defaultEditor) {\n\t\t\tthis.editor.setAutocompleteProvider?.(provider);\n\t\t}\n\t}\n\n\tprivate showStartupNoticesIfNeeded(): void {\n\t\tif (this.startupNoticesShown) {\n\t\t\treturn;\n\t\t}\n\t\tthis.startupNoticesShown = true;\n\n\t\tif (!this.changelogMarkdown) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.chatContainer.children.length > 0) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tif (this.settingsManager.getCollapseChangelog()) {\n\t\t\tconst versionMatch = this.changelogMarkdown.match(/##\\s+\\[?(\\d+\\.\\d+\\.\\d+)\\]?/);\n\t\t\tconst latestVersion = versionMatch ? versionMatch[1] : this.version;\n\t\t\tconst condensedText = `Updated to v${latestVersion}. Use ${theme.bold(\"/changelog\")} to view full changelog.`;\n\t\t\tthis.chatContainer.addChild(new Text(condensedText, 1, 0));\n\t\t} else {\n\t\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(\n\t\t\t\tnew Markdown(this.changelogMarkdown.trim(), 1, 0, this.getMarkdownThemeWithSettings()),\n\t\t\t);\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t}\n\n\tasync init(): Promise {\n\t\tif (this.isInitialized) return;\n\n\t\tthis.registerSignalHandlers();\n\n\t\t// Load changelog (only show new entries, skip for resumed sessions)\n\t\tthis.changelogMarkdown = this.getChangelogForDisplay();\n\n\t\t// Ensure fd and rg are available (downloads if missing, adds to PATH via getBinDir)\n\t\t// Both are needed: fd for autocomplete, rg for grep tool and bash commands\n\t\tconst [fdPath] = await Promise.all([ensureTool(\"fd\"), ensureTool(\"rg\")]);\n\t\tthis.fdPath = fdPath;\n\n\t\tif (this.session.scopedModels.length > 0 && (this.options.verbose || !this.settingsManager.getQuietStartup())) {\n\t\t\tconst modelList = this.session.scopedModels\n\t\t\t\t.map((sm) => {\n\t\t\t\t\tconst thinkingStr = sm.thinkingLevel ? `:${sm.thinkingLevel}` : \"\";\n\t\t\t\t\treturn `${sm.model.id}${thinkingStr}`;\n\t\t\t\t})\n\t\t\t\t.join(\", \");\n\t\t\tconst cycleKeys = this.keybindings.getKeys(\"app.model.cycleForward\");\n\t\t\tconst cycleHint =\n\t\t\t\tcycleKeys.length > 0\n\t\t\t\t\t? theme.fg(\"muted\", ` (${formatKeyText(cycleKeys.join(\"/\"), { capitalize: true })} to cycle)`)\n\t\t\t\t\t: \"\";\n\t\t\tconsole.log(theme.fg(\"dim\", `Model scope: ${modelList}${cycleHint}`));\n\t\t}\n\n\t\t// Add header container as first child. Populate it after applying theme settings.\n\t\t// Keep loaded resources before chat so restored session messages never precede them.\n\t\tthis.ui.addChild(this.headerContainer);\n\t\tthis.ui.addChild(this.loadedResourcesContainer);\n\n\t\tthis.ui.addChild(this.chatContainer);\n\t\tthis.ui.addChild(this.pendingMessagesContainer);\n\t\tthis.ui.addChild(this.statusContainer);\n\t\tthis.renderWidgets(); // Initialize with default spacer\n\t\tthis.ui.addChild(this.widgetContainerAbove);\n\t\tthis.ui.addChild(this.editorContainer);\n\t\tthis.ui.addChild(this.widgetContainerBelow);\n\t\tthis.ui.addChild(this.footer);\n\t\tthis.ui.setFocus(this.editor);\n\n\t\tthis.setupKeyHandlers();\n\t\tthis.setupEditorSubmitHandler();\n\n\t\t// Start the UI before initializing extensions so session_start handlers can use interactive dialogs\n\t\tthis.ui.start();\n\t\tthis.isInitialized = true;\n\n\t\tawait this.themeController.applyFromSettings();\n\n\t\t// Add header with keybindings from config (unless silenced)\n\t\tif (this.options.verbose || !this.settingsManager.getQuietStartup()) {\n\t\t\tconst logo = theme.bold(theme.fg(\"accent\", APP_NAME)) + theme.fg(\"dim\", ` v${this.version}`);\n\n\t\t\t// Build startup instructions using keybinding hint helpers\n\t\t\tconst hint = (keybinding: AppKeybinding, description: string) => keyHint(keybinding, description);\n\n\t\t\tconst expandedInstructions = [\n\t\t\t\thint(\"app.interrupt\", \"to interrupt\"),\n\t\t\t\thint(\"app.clear\", \"to clear\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.clear\")} twice`, \"to exit\"),\n\t\t\t\thint(\"app.exit\", \"to exit (empty)\"),\n\t\t\t\thint(\"app.suspend\", \"to suspend\"),\n\t\t\t\tkeyHint(\"tui.editor.deleteToLineEnd\", \"to delete to end\"),\n\t\t\t\thint(\"app.thinking.cycle\", \"to cycle thinking level\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.model.cycleForward\")}/${keyText(\"app.model.cycleBackward\")}`, \"to cycle models\"),\n\t\t\t\thint(\"app.model.select\", \"to select model\"),\n\t\t\t\thint(\"app.tools.expand\", \"to expand tools\"),\n\t\t\t\thint(\"app.thinking.toggle\", \"to expand thinking\"),\n\t\t\t\thint(\"app.editor.external\", \"for external editor\"),\n\t\t\t\trawKeyHint(\"/\", \"for commands\"),\n\t\t\t\trawKeyHint(\"!\", \"to run bash\"),\n\t\t\t\trawKeyHint(\"!!\", \"to run bash (no context)\"),\n\t\t\t\thint(\"app.message.followUp\", \"to queue follow-up\"),\n\t\t\t\thint(\"app.message.dequeue\", \"to edit all queued messages\"),\n\t\t\t\thint(\"app.clipboard.pasteImage\", \"to paste image (with text fallback)\"),\n\t\t\t\trawKeyHint(\"drop files\", \"to attach\"),\n\t\t\t].join(\"\\n\");\n\t\t\tconst compactInstructions = [\n\t\t\t\thint(\"app.interrupt\", \"interrupt\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.clear\")}/${keyText(\"app.exit\")}`, \"clear/exit\"),\n\t\t\t\trawKeyHint(\"/\", \"commands\"),\n\t\t\t\trawKeyHint(\"!\", \"bash\"),\n\t\t\t\thint(\"app.tools.expand\", \"more\"),\n\t\t\t].join(theme.fg(\"muted\", \" · \"));\n\t\t\tconst compactOnboarding = theme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t`Press ${keyText(\"app.tools.expand\")} to show full startup help and loaded resources.`,\n\t\t\t);\n\t\t\tconst onboarding = theme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t`Pi can explain its own features and look up its docs. Ask it how to use or extend Pi.`,\n\t\t\t);\n\t\t\tthis.builtInHeader = new ExpandableText(\n\t\t\t\t() => `${logo}\\n${compactInstructions}\\n${compactOnboarding}\\n\\n${onboarding}`,\n\t\t\t\t() => `${logo}\\n${expandedInstructions}\\n\\n${onboarding}`,\n\t\t\t\tthis.getStartupExpansionState(),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t);\n\n\t\t\t// Setup UI layout\n\t\t\tthis.headerContainer.addChild(new Spacer(1));\n\t\t\tthis.headerContainer.addChild(this.builtInHeader);\n\t\t\tthis.headerContainer.addChild(new Spacer(1));\n\t\t} else {\n\t\t\t// Minimal header when silenced\n\t\t\tthis.builtInHeader = new Text(\"\", 0, 0);\n\t\t\tthis.headerContainer.addChild(this.builtInHeader);\n\t\t}\n\t\tthis.ui.requestRender();\n\n\t\t// Initialize extensions first so resources are shown before messages\n\t\tawait this.rebindCurrentSession();\n\n\t\t// Render initial messages AFTER showing loaded resources\n\t\tthis.renderInitialMessages();\n\n\t\t// Set up theme file watcher\n\t\tonThemeChange(() => {\n\t\t\tthis.ui.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.ui.requestRender();\n\t\t});\n\n\t\t// Set up git branch watcher (uses provider instead of footer)\n\t\tthis.footerDataProvider.onBranchChange(() => {\n\t\t\tthis.ui.requestRender();\n\t\t});\n\n\t\t// Initialize available provider count for footer display\n\t\tawait this.updateAvailableProviderCount();\n\t}\n\n\t/**\n\t * Update terminal title with session name and cwd.\n\t */\n\tprivate updateTerminalTitle(): void {\n\t\tconst cwdBasename = path.basename(this.sessionManager.getCwd());\n\t\tconst sessionName = this.sessionManager.getSessionName();\n\t\tif (sessionName) {\n\t\t\tthis.ui.terminal.setTitle(`${APP_TITLE} - ${sessionName} - ${cwdBasename}`);\n\t\t} else {\n\t\t\tthis.ui.terminal.setTitle(`${APP_TITLE} - ${cwdBasename}`);\n\t\t}\n\t}\n\n\t/**\n\t * Run the interactive mode. This is the main entry point.\n\t * Initializes the UI, shows warnings, processes initial messages, and starts the interactive loop.\n\t */\n\tasync run(): Promise {\n\t\tawait this.init();\n\n\t\tif (!process.env.PI_OFFLINE) {\n\t\t\tvoid this.session.modelRuntime\n\t\t\t\t.refresh()\n\t\t\t\t.then(() => this.updateAvailableProviderCount())\n\t\t\t\t.catch(() => {});\n\t\t}\n\n\t\t// Start version check asynchronously\n\t\tcheckForNewPiVersion(this.version).then((newRelease) => {\n\t\t\tif (newRelease) {\n\t\t\t\tthis.showNewVersionNotification(newRelease);\n\t\t\t}\n\t\t});\n\n\t\t// Start package update check asynchronously\n\t\tthis.checkForPackageUpdates()\n\t\t\t.then((updates) => {\n\t\t\t\tif (updates.length > 0) {\n\t\t\t\t\tthis.showPackageUpdateNotification(updates);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\t// On Windows, npm can overwrite the shared console title while checking\n\t\t\t\t// extension package versions. Restore Pi's title after the startup check.\n\t\t\t\tif (process.platform === \"win32\" && this.isInitialized) {\n\t\t\t\t\tthis.updateTerminalTitle();\n\t\t\t\t}\n\t\t\t});\n\n\t\t// Check tmux keyboard setup asynchronously\n\t\tthis.checkTmuxKeyboardSetup().then((warning) => {\n\t\t\tif (warning) {\n\t\t\t\tthis.showWarning(warning);\n\t\t\t}\n\t\t});\n\n\t\t// Show startup warnings\n\t\tconst { migratedProviders, modelFallbackMessage, initialMessage, initialImages, initialMessages } = this.options;\n\n\t\tif (migratedProviders && migratedProviders.length > 0) {\n\t\t\tthis.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(\", \")}`);\n\t\t}\n\n\t\tconst modelsJsonError = this.session.modelRuntime.getError();\n\t\tif (modelsJsonError) {\n\t\t\tthis.showError(`models.json error: ${modelsJsonError}`);\n\t\t}\n\n\t\tif (modelFallbackMessage) {\n\t\t\tthis.showWarning(modelFallbackMessage);\n\t\t}\n\n\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth();\n\n\t\t// Process initial messages\n\t\tif (initialMessage) {\n\t\t\ttry {\n\t\t\t\tawait this.session.prompt(initialMessage, { images: initialImages });\n\t\t\t} catch (error: unknown) {\n\t\t\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\t\tthis.showError(errorMessage);\n\t\t\t}\n\t\t}\n\n\t\tif (initialMessages) {\n\t\t\tfor (const message of initialMessages) {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.session.prompt(message);\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\t\t\tthis.showError(errorMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Main interactive loop\n\t\twhile (true) {\n\t\t\tconst userInput = await this.getUserInput();\n\t\t\ttry {\n\t\t\t\tawait this.session.prompt(userInput);\n\t\t\t} catch (error: unknown) {\n\t\t\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\t\tthis.showError(errorMessage);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async checkForPackageUpdates(): Promise {\n\t\tif (process.env.PI_OFFLINE) {\n\t\t\treturn [];\n\t\t}\n\n\t\ttry {\n\t\t\tconst packageManager = new DefaultPackageManager({\n\t\t\t\tcwd: this.sessionManager.getCwd(),\n\t\t\t\tagentDir: getAgentDir(),\n\t\t\t\tsettingsManager: this.settingsManager,\n\t\t\t});\n\t\t\tconst updates = await packageManager.checkForAvailableUpdates();\n\t\t\treturn updates.map((update) => update.displayName);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\tprivate async checkTmuxKeyboardSetup(): Promise {\n\t\tif (!process.env.TMUX) return undefined;\n\n\t\tconst runTmuxShow = (option: string): Promise => {\n\t\t\treturn new Promise((resolve) => {\n\t\t\t\tconst proc = spawn(\"tmux\", [\"show\", \"-gv\", option], {\n\t\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t\t});\n\t\t\t\tlet stdout = \"\";\n\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\tproc.kill();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t}, 2000);\n\n\t\t\t\tproc.stdout?.on(\"data\", (data) => {\n\t\t\t\t\tstdout += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.on(\"error\", () => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t});\n\t\t\t\tproc.on(\"close\", (code) => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(code === 0 ? stdout.trim() : undefined);\n\t\t\t\t});\n\t\t\t});\n\t\t};\n\n\t\tconst [extendedKeys, extendedKeysFormat] = await Promise.all([\n\t\t\trunTmuxShow(\"extended-keys\"),\n\t\t\trunTmuxShow(\"extended-keys-format\"),\n\t\t]);\n\n\t\t// If we couldn't query tmux (timeout, sandbox, etc.), don't warn\n\t\tif (extendedKeys === undefined) return undefined;\n\n\t\tif (extendedKeys !== \"on\" && extendedKeys !== \"always\") {\n\t\t\treturn \"tmux extended-keys is off. Modified Enter keys may not work. Add `set -g extended-keys on` to ~/.tmux.conf and restart tmux.\";\n\t\t}\n\n\t\tif (extendedKeysFormat === \"xterm\") {\n\t\t\treturn \"tmux extended-keys-format is xterm. Pi works best with csi-u. Add `set -g extended-keys-format csi-u` to ~/.tmux.conf and restart tmux.\";\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Get changelog entries to display on startup.\n\t * Only shows new entries since last seen version, skips for resumed sessions.\n\t */\n\tprivate getChangelogForDisplay(): string | undefined {\n\t\t// Skip changelog for resumed/continued sessions (already have messages)\n\t\tif (this.session.state.messages.length > 0) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst lastVersion = this.settingsManager.getLastChangelogVersion();\n\t\tconst changelogPath = getChangelogPath();\n\t\tconst entries = parseChangelog(changelogPath);\n\n\t\tif (!lastVersion) {\n\t\t\t// Fresh install - record the version, send telemetry, don't show changelog\n\t\t\tthis.settingsManager.setLastChangelogVersion(VERSION);\n\t\t\tthis.reportInstallTelemetry(VERSION);\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst newEntries = getNewEntries(entries, lastVersion);\n\t\tif (newEntries.length > 0) {\n\t\t\tthis.settingsManager.setLastChangelogVersion(VERSION);\n\t\t\tthis.reportInstallTelemetry(VERSION);\n\t\t\treturn newEntries.map((e) => normalizeChangelogLinks(e.content, e)).join(\"\\n\\n\");\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate reportInstallTelemetry(version: string): void {\n\t\tif (process.env.PI_OFFLINE) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!isInstallTelemetryEnabled(this.settingsManager)) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid fetch(`https://pi.dev/api/report-install?version=${encodeURIComponent(version)}`, {\n\t\t\theaders: {\n\t\t\t\t\"User-Agent\": getPiUserAgent(version),\n\t\t\t},\n\t\t\tsignal: AbortSignal.timeout(5000),\n\t\t})\n\t\t\t.then(() => undefined)\n\t\t\t.catch(() => undefined);\n\t}\n\n\tprivate getMarkdownThemeWithSettings(): MarkdownTheme {\n\t\treturn {\n\t\t\t...getMarkdownTheme(),\n\t\t\tcodeBlockIndent: this.settingsManager.getCodeBlockIndent(),\n\t\t};\n\t}\n\n\t// =========================================================================\n\t// Extension System\n\t// =========================================================================\n\n\tprivate formatDisplayPath(p: string): string {\n\t\tconst home = os.homedir();\n\t\tlet result = p;\n\n\t\t// Replace home directory with ~\n\t\tif (result.startsWith(home)) {\n\t\t\tresult = `~${result.slice(home.length)}`;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate formatExtensionDisplayPath(path: string): string {\n\t\tlet result = this.formatDisplayPath(path);\n\t\tresult = result.replace(/\\/index\\.ts$/, \"\").replace(/\\/index\\.js$/, \"\");\n\t\treturn result;\n\t}\n\n\tprivate formatContextPath(p: string): string {\n\t\tconst cwd = path.resolve(this.sessionManager.getCwd());\n\t\tconst absolutePath = path.isAbsolute(p) ? path.resolve(p) : path.resolve(cwd, p);\n\t\tconst relativePath = getCwdRelativePath(absolutePath, cwd);\n\t\tif (relativePath !== undefined) {\n\t\t\treturn relativePath;\n\t\t}\n\n\t\treturn this.formatDisplayPath(absolutePath);\n\t}\n\n\tprivate getStartupExpansionState(): boolean {\n\t\treturn this.options.verbose || this.toolOutputExpanded;\n\t}\n\n\t/**\n\t * Get a short path relative to the package root for display.\n\t */\n\tprivate getShortPath(fullPath: string, sourceInfo?: SourceInfo): string {\n\t\tconst normalizedFullPath = fullPath.replace(/\\\\/g, \"/\");\n\t\tconst baseDir = sourceInfo?.baseDir;\n\t\tif (baseDir && this.isPackageSource(sourceInfo)) {\n\t\t\tconst normalizedBaseDir = baseDir.replace(/\\\\/g, \"/\");\n\t\t\tconst npmRootMatch = normalizedBaseDir.match(/^(.*\\/node_modules)\\/(@?[^/]+(?:\\/[^/]+)?)$/);\n\t\t\t// If fullPath is under the same node_modules root as baseDir, preserve that relative topology.\n\t\t\tif (npmRootMatch?.[1] && normalizedFullPath.startsWith(`${npmRootMatch[1]}/`)) {\n\t\t\t\treturn path.posix.relative(normalizedBaseDir, normalizedFullPath);\n\t\t\t}\n\n\t\t\tconst relativePath = path.relative(path.resolve(baseDir), path.resolve(fullPath));\n\t\t\tif (\n\t\t\t\trelativePath &&\n\t\t\t\trelativePath !== \".\" &&\n\t\t\t\t!relativePath.startsWith(\"..\") &&\n\t\t\t\t!relativePath.startsWith(`..${path.sep}`) &&\n\t\t\t\t!path.isAbsolute(relativePath)\n\t\t\t) {\n\t\t\t\treturn relativePath.replace(/\\\\/g, \"/\");\n\t\t\t}\n\t\t}\n\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\tconst npmMatch = normalizedFullPath.match(/node_modules\\/(@?[^/]+(?:\\/[^/]+)?)\\/(.*)/);\n\t\tif (npmMatch && source.startsWith(\"npm:\")) {\n\t\t\treturn npmMatch[2];\n\t\t}\n\n\t\tconst gitMatch = normalizedFullPath.match(/git\\/[^/]+\\/[^/]+\\/(.*)/);\n\t\tif (gitMatch && source.startsWith(\"git:\")) {\n\t\t\treturn gitMatch[1];\n\t\t}\n\n\t\treturn this.formatDisplayPath(fullPath);\n\t}\n\n\tprivate getCompactPathLabel(resourcePath: string, sourceInfo?: SourceInfo): string {\n\t\tconst shortPath = this.getShortPath(resourcePath, sourceInfo);\n\t\tconst normalizedPath = shortPath.replace(/\\\\/g, \"/\");\n\t\tconst segments = normalizedPath.split(\"/\").filter((segment) => segment.length > 0 && segment !== \"~\");\n\t\tif (segments.length > 0) {\n\t\t\treturn segments[segments.length - 1]!;\n\t\t}\n\t\treturn shortPath;\n\t}\n\n\tprivate getCompactPackageSourceLabel(sourceInfo?: SourceInfo): string {\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\treturn source.slice(\"npm:\".length) || source;\n\t\t}\n\n\t\tconst gitSource = parseGitUrl(source);\n\t\tif (gitSource) {\n\t\t\treturn gitSource.path || source;\n\t\t}\n\n\t\treturn source;\n\t}\n\n\tprivate getCompactExtensionLabel(resourcePath: string, sourceInfo?: SourceInfo): string {\n\t\tif (!this.isPackageSource(sourceInfo)) {\n\t\t\treturn this.getCompactPathLabel(resourcePath, sourceInfo);\n\t\t}\n\n\t\tconst sourceLabel = this.getCompactPackageSourceLabel(sourceInfo);\n\t\tif (!sourceLabel) {\n\t\t\treturn this.getCompactPathLabel(resourcePath, sourceInfo);\n\t\t}\n\n\t\tconst shortPath = this.getShortPath(resourcePath, sourceInfo).replace(/\\\\/g, \"/\");\n\t\tconst packagePath = shortPath.startsWith(\"extensions/\") ? shortPath.slice(\"extensions/\".length) : shortPath;\n\t\tconst parsedPath = path.posix.parse(packagePath);\n\n\t\tif (parsedPath.name === \"index\") {\n\t\t\treturn !parsedPath.dir || parsedPath.dir === \".\" ? sourceLabel : `${sourceLabel}:${parsedPath.dir}`;\n\t\t}\n\n\t\treturn `${sourceLabel}:${packagePath}`;\n\t}\n\n\tprivate getCompactDisplayPathSegments(resourcePath: string): string[] {\n\t\treturn this.formatDisplayPath(resourcePath)\n\t\t\t.replace(/\\\\/g, \"/\")\n\t\t\t.split(\"/\")\n\t\t\t.filter((segment) => segment.length > 0 && segment !== \"~\");\n\t}\n\n\tprivate getCompactNonPackageExtensionLabel(\n\t\tresourcePath: string,\n\t\tindex: number,\n\t\tallPaths: Array<{ path: string; segments: string[] }>,\n\t): string {\n\t\tconst segments = allPaths[index]?.segments;\n\t\tif (!segments || segments.length === 0) {\n\t\t\treturn this.getCompactPathLabel(resourcePath);\n\t\t}\n\n\t\tfor (let segmentCount = 1; segmentCount <= segments.length; segmentCount += 1) {\n\t\t\tconst candidate = segments.slice(-segmentCount).join(\"/\");\n\t\t\tconst isUnique = allPaths.every((item, itemIndex) => {\n\t\t\t\tif (itemIndex === index) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn item.segments.slice(-segmentCount).join(\"/\") !== candidate;\n\t\t\t});\n\n\t\t\tif (isUnique) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\n\t\treturn segments.join(\"/\");\n\t}\n\n\tprivate getCompactExtensionLabels(extensions: Array<{ path: string; sourceInfo?: SourceInfo }>): string[] {\n\t\tconst nonPackageExtensions = extensions\n\t\t\t.map((extension) => {\n\t\t\t\tconst segments = this.getCompactDisplayPathSegments(extension.path);\n\t\t\t\tconst lastSegment = segments[segments.length - 1];\n\t\t\t\tif (segments.length > 1 && (lastSegment === \"index.ts\" || lastSegment === \"index.js\")) {\n\t\t\t\t\tsegments.pop();\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tpath: extension.path,\n\t\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\t\tsegments,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter((extension) => !this.isPackageSource(extension.sourceInfo));\n\n\t\treturn extensions.map((extension) => {\n\t\t\tif (this.isPackageSource(extension.sourceInfo)) {\n\t\t\t\treturn this.getCompactExtensionLabel(extension.path, extension.sourceInfo);\n\t\t\t}\n\n\t\t\tconst nonPackageIndex = nonPackageExtensions.findIndex((item) => item.path === extension.path);\n\t\t\tif (nonPackageIndex === -1) {\n\t\t\t\treturn this.getCompactPathLabel(extension.path, extension.sourceInfo);\n\t\t\t}\n\n\t\t\treturn this.getCompactNonPackageExtensionLabel(extension.path, nonPackageIndex, nonPackageExtensions);\n\t\t});\n\t}\n\n\tprivate getDisplaySourceInfo(sourceInfo?: SourceInfo): {\n\t\tlabel: string;\n\t\tscopeLabel?: string;\n\t\tcolor: \"accent\" | \"muted\";\n\t} {\n\t\tconst source = sourceInfo?.source ?? \"local\";\n\t\tconst scope = sourceInfo?.scope ?? \"project\";\n\t\tif (source === \"local\") {\n\t\t\tif (scope === \"user\") {\n\t\t\t\treturn { label: \"user\", color: \"muted\" };\n\t\t\t}\n\t\t\tif (scope === \"project\") {\n\t\t\t\treturn { label: \"project\", color: \"muted\" };\n\t\t\t}\n\t\t\tif (scope === \"temporary\") {\n\t\t\t\treturn { label: \"path\", scopeLabel: \"temp\", color: \"muted\" };\n\t\t\t}\n\t\t\treturn { label: \"path\", color: \"muted\" };\n\t\t}\n\n\t\tif (source === \"cli\") {\n\t\t\treturn { label: \"path\", scopeLabel: scope === \"temporary\" ? \"temp\" : undefined, color: \"muted\" };\n\t\t}\n\n\t\tconst scopeLabel =\n\t\t\tscope === \"user\" ? \"user\" : scope === \"project\" ? \"project\" : scope === \"temporary\" ? \"temp\" : undefined;\n\t\treturn { label: source, scopeLabel, color: \"accent\" };\n\t}\n\n\tprivate getScopeGroup(sourceInfo?: SourceInfo): \"user\" | \"project\" | \"path\" {\n\t\tconst source = sourceInfo?.source ?? \"local\";\n\t\tconst scope = sourceInfo?.scope ?? \"project\";\n\t\tif (source === \"cli\" || scope === \"temporary\") return \"path\";\n\t\tif (scope === \"user\") return \"user\";\n\t\tif (scope === \"project\") return \"project\";\n\t\treturn \"path\";\n\t}\n\n\tprivate isPackageSource(sourceInfo?: SourceInfo): boolean {\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\treturn source.startsWith(\"npm:\") || source.startsWith(\"git:\");\n\t}\n\n\tprivate buildScopeGroups(items: Array<{ path: string; sourceInfo?: SourceInfo }>): Array<{\n\t\tscope: \"user\" | \"project\" | \"path\";\n\t\tpaths: Array<{ path: string; sourceInfo?: SourceInfo }>;\n\t\tpackages: Map>;\n\t}> {\n\t\tconst groups: Record<\n\t\t\t\"user\" | \"project\" | \"path\",\n\t\t\t{\n\t\t\t\tscope: \"user\" | \"project\" | \"path\";\n\t\t\t\tpaths: Array<{ path: string; sourceInfo?: SourceInfo }>;\n\t\t\t\tpackages: Map>;\n\t\t\t}\n\t\t> = {\n\t\t\tuser: { scope: \"user\", paths: [], packages: new Map() },\n\t\t\tproject: { scope: \"project\", paths: [], packages: new Map() },\n\t\t\tpath: { scope: \"path\", paths: [], packages: new Map() },\n\t\t};\n\n\t\tfor (const item of items) {\n\t\t\tconst groupKey = this.getScopeGroup(item.sourceInfo);\n\t\t\tconst group = groups[groupKey];\n\t\t\tconst source = item.sourceInfo?.source ?? \"local\";\n\n\t\t\tif (this.isPackageSource(item.sourceInfo)) {\n\t\t\t\tconst list = group.packages.get(source) ?? [];\n\t\t\t\tlist.push(item);\n\t\t\t\tgroup.packages.set(source, list);\n\t\t\t} else {\n\t\t\t\tgroup.paths.push(item);\n\t\t\t}\n\t\t}\n\n\t\treturn [groups.project, groups.user, groups.path].filter(\n\t\t\t(group) => group.paths.length > 0 || group.packages.size > 0,\n\t\t);\n\t}\n\n\tprivate formatScopeGroups(\n\t\tgroups: Array<{\n\t\t\tscope: \"user\" | \"project\" | \"path\";\n\t\t\tpaths: Array<{ path: string; sourceInfo?: SourceInfo }>;\n\t\t\tpackages: Map>;\n\t\t}>,\n\t\toptions: {\n\t\t\tformatPath: (item: { path: string; sourceInfo?: SourceInfo }) => string;\n\t\t\tformatPackagePath: (item: { path: string; sourceInfo?: SourceInfo }, source: string) => string;\n\t\t},\n\t): string {\n\t\tconst lines: string[] = [];\n\n\t\tfor (const group of groups) {\n\t\t\tlines.push(` ${theme.fg(\"accent\", group.scope)}`);\n\n\t\t\tconst sortedPaths = [...group.paths].sort((a, b) => a.path.localeCompare(b.path));\n\t\t\tfor (const item of sortedPaths) {\n\t\t\t\tlines.push(theme.fg(\"dim\", ` ${options.formatPath(item)}`));\n\t\t\t}\n\n\t\t\tconst sortedPackages = Array.from(group.packages.entries()).sort(([a], [b]) => a.localeCompare(b));\n\t\t\tfor (const [source, items] of sortedPackages) {\n\t\t\t\tlines.push(` ${theme.fg(\"mdLink\", source)}`);\n\t\t\t\tconst sortedPackagePaths = [...items].sort((a, b) => a.path.localeCompare(b.path));\n\t\t\t\tfor (const item of sortedPackagePaths) {\n\t\t\t\t\tlines.push(theme.fg(\"dim\", ` ${options.formatPackagePath(item, source)}`));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tprivate findSourceInfoForPath(p: string, sourceInfos: Map): SourceInfo | undefined {\n\t\tconst exact = sourceInfos.get(p);\n\t\tif (exact) return exact;\n\n\t\tlet current = p;\n\t\twhile (current.includes(\"/\")) {\n\t\t\tcurrent = current.substring(0, current.lastIndexOf(\"/\"));\n\t\t\tconst parent = sourceInfos.get(current);\n\t\t\tif (parent) return parent;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate formatPathWithSource(p: string, sourceInfo?: SourceInfo): string {\n\t\tif (sourceInfo) {\n\t\t\tconst shortPath = this.getShortPath(p, sourceInfo);\n\t\t\tconst { label, scopeLabel } = this.getDisplaySourceInfo(sourceInfo);\n\t\t\tconst labelText = scopeLabel ? `${label} (${scopeLabel})` : label;\n\t\t\treturn `${labelText} ${shortPath}`;\n\t\t}\n\t\treturn this.formatDisplayPath(p);\n\t}\n\n\tprivate formatDiagnostics(diagnostics: readonly ResourceDiagnostic[], sourceInfos: Map): string {\n\t\tconst lines: string[] = [];\n\n\t\t// Group collision diagnostics by name\n\t\tconst collisions = new Map();\n\t\tconst otherDiagnostics: ResourceDiagnostic[] = [];\n\n\t\tfor (const d of diagnostics) {\n\t\t\tif (d.type === \"collision\" && d.collision) {\n\t\t\t\tconst list = collisions.get(d.collision.name) ?? [];\n\t\t\t\tlist.push(d);\n\t\t\t\tcollisions.set(d.collision.name, list);\n\t\t\t} else {\n\t\t\t\totherDiagnostics.push(d);\n\t\t\t}\n\t\t}\n\n\t\t// Format collision diagnostics grouped by name\n\t\tfor (const [name, collisionList] of collisions) {\n\t\t\tconst first = collisionList[0]?.collision;\n\t\t\tif (!first) continue;\n\t\t\tlines.push(theme.fg(\"warning\", ` \"${name}\" collision:`));\n\t\t\tlines.push(\n\t\t\t\ttheme.fg(\n\t\t\t\t\t\"dim\",\n\t\t\t\t\t` ${theme.fg(\"success\", \"✓\")} ${this.formatPathWithSource(first.winnerPath, this.findSourceInfoForPath(first.winnerPath, sourceInfos))}`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tfor (const d of collisionList) {\n\t\t\t\tif (d.collision) {\n\t\t\t\t\tlines.push(\n\t\t\t\t\t\ttheme.fg(\n\t\t\t\t\t\t\t\"dim\",\n\t\t\t\t\t\t\t` ${theme.fg(\"warning\", \"✗\")} ${this.formatPathWithSource(d.collision.loserPath, this.findSourceInfoForPath(d.collision.loserPath, sourceInfos))} (skipped)`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const d of otherDiagnostics) {\n\t\t\tif (d.path) {\n\t\t\t\tconst formattedPath = this.formatPathWithSource(d.path, this.findSourceInfoForPath(d.path, sourceInfos));\n\t\t\t\tlines.push(theme.fg(d.type === \"error\" ? \"error\" : \"warning\", ` ${formattedPath}`));\n\t\t\t\tlines.push(theme.fg(d.type === \"error\" ? \"error\" : \"warning\", ` ${d.message}`));\n\t\t\t} else {\n\t\t\t\tlines.push(theme.fg(d.type === \"error\" ? \"error\" : \"warning\", ` ${d.message}`));\n\t\t\t}\n\t\t}\n\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tprivate showLoadedResources(options?: {\n\t\textensions?: Array<{ path: string; sourceInfo?: SourceInfo }>;\n\t\tforce?: boolean;\n\t\tshowDiagnosticsWhenQuiet?: boolean;\n\t}): void {\n\t\t// Resource rendering is idempotent; chat clears no longer clear this separate container.\n\t\tthis.loadedResourcesContainer.clear();\n\n\t\tconst showListing = options?.force || this.options.verbose || !this.settingsManager.getQuietStartup();\n\t\tconst showDiagnostics = showListing || options?.showDiagnosticsWhenQuiet === true;\n\t\tif (!showListing && !showDiagnostics) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst sectionHeader = (name: string, color: ThemeColor = \"mdHeading\") => theme.fg(color, `[${name}]`);\n\t\tconst formatCompactList = (items: string[], options?: { sort?: boolean }): string => {\n\t\t\tconst labels = items.map((item) => item.trim()).filter((item) => item.length > 0);\n\t\t\tif (options?.sort !== false) {\n\t\t\t\tlabels.sort((a, b) => a.localeCompare(b));\n\t\t\t}\n\t\t\treturn theme.fg(\"dim\", ` ${labels.join(\", \")}`);\n\t\t};\n\t\tconst addLoadedSection = (\n\t\t\tname: string,\n\t\t\tcollapsedBody: string,\n\t\t\texpandedBody = collapsedBody,\n\t\t\tcolor: ThemeColor = \"mdHeading\",\n\t\t): void => {\n\t\t\tconst section = new ExpandableText(\n\t\t\t\t() => `${sectionHeader(name, color)}\\n${collapsedBody}`,\n\t\t\t\t() => `${sectionHeader(name, color)}\\n${expandedBody}`,\n\t\t\t\tthis.getStartupExpansionState(),\n\t\t\t\t0,\n\t\t\t\t0,\n\t\t\t);\n\t\t\tthis.loadedResourcesContainer.addChild(section);\n\t\t\tthis.loadedResourcesContainer.addChild(new Spacer(1));\n\t\t};\n\n\t\tconst skillsResult = this.session.resourceLoader.getSkills();\n\t\tconst promptsResult = this.session.resourceLoader.getPrompts();\n\t\tconst themesResult = this.session.resourceLoader.getThemes();\n\t\tconst extensions =\n\t\t\toptions?.extensions ??\n\t\t\tthis.session.resourceLoader\n\t\t\t\t.getExtensions()\n\t\t\t\t.extensions.filter((extension) => !extension.hidden)\n\t\t\t\t.map((extension) => ({\n\t\t\t\t\tpath: extension.path,\n\t\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\t}));\n\t\tconst sourceInfos = new Map();\n\t\tfor (const extension of extensions) {\n\t\t\tif (extension.sourceInfo) {\n\t\t\t\tsourceInfos.set(extension.path, extension.sourceInfo);\n\t\t\t}\n\t\t}\n\t\tfor (const skill of skillsResult.skills) {\n\t\t\tif (skill.sourceInfo) {\n\t\t\t\tsourceInfos.set(skill.filePath, skill.sourceInfo);\n\t\t\t}\n\t\t}\n\t\tfor (const prompt of promptsResult.prompts) {\n\t\t\tif (prompt.sourceInfo) {\n\t\t\t\tsourceInfos.set(prompt.filePath, prompt.sourceInfo);\n\t\t\t}\n\t\t}\n\t\tfor (const loadedTheme of themesResult.themes) {\n\t\t\tif (loadedTheme.sourcePath && loadedTheme.sourceInfo) {\n\t\t\t\tsourceInfos.set(loadedTheme.sourcePath, loadedTheme.sourceInfo);\n\t\t\t}\n\t\t}\n\n\t\tif (showListing) {\n\t\t\tconst systemPromptSource = this.session.resourceLoader.getSystemPromptSource();\n\t\t\tconst contextFiles = [\n\t\t\t\t...(systemPromptSource ? [systemPromptSource] : []),\n\t\t\t\t...this.session.resourceLoader.getAppendSystemPromptSources(),\n\t\t\t\t...this.session.resourceLoader.getAgentsFiles().agentsFiles,\n\t\t\t];\n\t\t\tif (contextFiles.length > 0) {\n\t\t\t\tthis.loadedResourcesContainer.addChild(new Spacer(1));\n\t\t\t\tconst contextList = contextFiles\n\t\t\t\t\t.map((f) => theme.fg(\"dim\", ` ${this.formatDisplayPath(f.path)}`))\n\t\t\t\t\t.join(\"\\n\");\n\t\t\t\tconst contextCompactList = formatCompactList(\n\t\t\t\t\tcontextFiles.map((contextFile) => this.formatContextPath(contextFile.path)),\n\t\t\t\t\t{ sort: false },\n\t\t\t\t);\n\t\t\t\taddLoadedSection(\"Context\", contextCompactList, contextList);\n\t\t\t}\n\n\t\t\tconst skills = skillsResult.skills;\n\t\t\tif (skills.length > 0) {\n\t\t\t\tconst groups = this.buildScopeGroups(\n\t\t\t\t\tskills.map((skill) => ({ path: skill.filePath, sourceInfo: skill.sourceInfo })),\n\t\t\t\t);\n\t\t\t\tconst skillList = this.formatScopeGroups(groups, {\n\t\t\t\t\tformatPath: (item) => this.formatDisplayPath(item.path),\n\t\t\t\t\tformatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),\n\t\t\t\t});\n\t\t\t\tconst skillCompactList = formatCompactList(skills.map((skill) => skill.name));\n\t\t\t\taddLoadedSection(\"Skills\", skillCompactList, skillList);\n\t\t\t}\n\n\t\t\tconst templates = this.session.promptTemplates;\n\t\t\tif (templates.length > 0) {\n\t\t\t\tconst groups = this.buildScopeGroups(\n\t\t\t\t\ttemplates.map((template) => ({ path: template.filePath, sourceInfo: template.sourceInfo })),\n\t\t\t\t);\n\t\t\t\tconst templateByPath = new Map(templates.map((t) => [t.filePath, t]));\n\t\t\t\tconst templateList = this.formatScopeGroups(groups, {\n\t\t\t\t\tformatPath: (item) => {\n\t\t\t\t\t\tconst template = templateByPath.get(item.path);\n\t\t\t\t\t\treturn template ? `/${template.name}` : this.formatDisplayPath(item.path);\n\t\t\t\t\t},\n\t\t\t\t\tformatPackagePath: (item) => {\n\t\t\t\t\t\tconst template = templateByPath.get(item.path);\n\t\t\t\t\t\treturn template ? `/${template.name}` : this.formatDisplayPath(item.path);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tconst promptCompactList = formatCompactList(templates.map((template) => `/${template.name}`));\n\t\t\t\taddLoadedSection(\"Prompts\", promptCompactList, templateList);\n\t\t\t}\n\n\t\t\tif (extensions.length > 0) {\n\t\t\t\tconst groups = this.buildScopeGroups(extensions);\n\t\t\t\tconst extList = this.formatScopeGroups(groups, {\n\t\t\t\t\tformatPath: (item) => this.formatExtensionDisplayPath(item.path),\n\t\t\t\t\tformatPackagePath: (item) =>\n\t\t\t\t\t\tthis.formatExtensionDisplayPath(this.getShortPath(item.path, item.sourceInfo)),\n\t\t\t\t});\n\t\t\t\tconst extensionCompactList = formatCompactList(this.getCompactExtensionLabels(extensions));\n\t\t\t\taddLoadedSection(\"Extensions\", extensionCompactList, extList, \"mdHeading\");\n\t\t\t}\n\n\t\t\t// Show loaded themes (excluding built-in)\n\t\t\tconst loadedThemes = themesResult.themes;\n\t\t\tconst customThemes = loadedThemes.filter((t) => t.sourcePath);\n\t\t\tif (customThemes.length > 0) {\n\t\t\t\tconst groups = this.buildScopeGroups(\n\t\t\t\t\tcustomThemes.map((loadedTheme) => ({\n\t\t\t\t\t\tpath: loadedTheme.sourcePath!,\n\t\t\t\t\t\tsourceInfo: loadedTheme.sourceInfo,\n\t\t\t\t\t})),\n\t\t\t\t);\n\t\t\t\tconst themeList = this.formatScopeGroups(groups, {\n\t\t\t\t\tformatPath: (item) => this.formatDisplayPath(item.path),\n\t\t\t\t\tformatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),\n\t\t\t\t});\n\t\t\t\tconst themeCompactList = formatCompactList(\n\t\t\t\t\tcustomThemes.map(\n\t\t\t\t\t\t(loadedTheme) =>\n\t\t\t\t\t\t\tloadedTheme.name ?? this.getCompactPathLabel(loadedTheme.sourcePath!, loadedTheme.sourceInfo),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\taddLoadedSection(\"Themes\", themeCompactList, themeList);\n\t\t\t}\n\t\t}\n\n\t\tif (showDiagnostics) {\n\t\t\tconst skillDiagnostics = skillsResult.diagnostics;\n\t\t\tif (skillDiagnostics.length > 0) {\n\t\t\t\tconst warningLines = this.formatDiagnostics(skillDiagnostics, sourceInfos);\n\t\t\t\tthis.loadedResourcesContainer.addChild(\n\t\t\t\t\tnew Text(`${theme.fg(\"warning\", \"[Skill conflicts]\")}\\n${warningLines}`, 0, 0),\n\t\t\t\t);\n\t\t\t\tthis.loadedResourcesContainer.addChild(new Spacer(1));\n\t\t\t}\n\n\t\t\tconst promptDiagnostics = promptsResult.diagnostics;\n\t\t\tif (promptDiagnostics.length > 0) {\n\t\t\t\tconst warningLines = this.formatDiagnostics(promptDiagnostics, sourceInfos);\n\t\t\t\tthis.loadedResourcesContainer.addChild(\n\t\t\t\t\tnew Text(`${theme.fg(\"warning\", \"[Prompt conflicts]\")}\\n${warningLines}`, 0, 0),\n\t\t\t\t);\n\t\t\t\tthis.loadedResourcesContainer.addChild(new Spacer(1));\n\t\t\t}\n\n\t\t\tconst extensionDiagnostics: ResourceDiagnostic[] = [];\n\t\t\tconst extensionErrors = this.session.resourceLoader.getExtensions().errors;\n\t\t\tif (extensionErrors.length > 0) {\n\t\t\t\tfor (const error of extensionErrors) {\n\t\t\t\t\textensionDiagnostics.push({ type: \"error\", message: error.error, path: error.path });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst commandDiagnostics = this.session.extensionRunner.getCommandDiagnostics();\n\t\t\textensionDiagnostics.push(...commandDiagnostics);\n\t\t\textensionDiagnostics.push(...this.getBuiltInCommandConflictDiagnostics(this.session.extensionRunner));\n\n\t\t\tconst shortcutDiagnostics = this.session.extensionRunner.getShortcutDiagnostics();\n\t\t\textensionDiagnostics.push(...shortcutDiagnostics);\n\n\t\t\tif (extensionDiagnostics.length > 0) {\n\t\t\t\tconst warningLines = this.formatDiagnostics(extensionDiagnostics, sourceInfos);\n\t\t\t\tthis.loadedResourcesContainer.addChild(\n\t\t\t\t\tnew Text(`${theme.fg(\"warning\", \"[Extension issues]\")}\\n${warningLines}`, 0, 0),\n\t\t\t\t);\n\t\t\t\tthis.loadedResourcesContainer.addChild(new Spacer(1));\n\t\t\t}\n\n\t\t\tconst themeDiagnostics = themesResult.diagnostics;\n\t\t\tif (themeDiagnostics.length > 0) {\n\t\t\t\tconst warningLines = this.formatDiagnostics(themeDiagnostics, sourceInfos);\n\t\t\t\tthis.loadedResourcesContainer.addChild(\n\t\t\t\t\tnew Text(`${theme.fg(\"warning\", \"[Theme conflicts]\")}\\n${warningLines}`, 0, 0),\n\t\t\t\t);\n\t\t\t\tthis.loadedResourcesContainer.addChild(new Spacer(1));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Initialize the extension system with TUI-based UI context.\n\t */\n\tprivate async bindCurrentSessionExtensions(): Promise {\n\t\tconst uiContext = this.createExtensionUIContext();\n\t\tawait this.session.bindExtensions({\n\t\t\tuiContext,\n\t\t\tmode: \"tui\",\n\t\t\tabortHandler: () => {\n\t\t\t\tthis.restoreQueuedMessagesToEditor({ abort: true });\n\t\t\t},\n\t\t\tcommandContextActions: {\n\t\t\t\twaitForIdle: () => this.session.waitForIdle(),\n\t\t\t\tnewSession: async (options) => {\n\t\t\t\t\tthis.clearStatusIndicator();\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await this.runtimeHost.newSession(options);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\treturn this.handleFatalRuntimeError(\"Failed to create session\", error);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tfork: async (entryId, options) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.runtimeHost.fork(entryId, options);\n\t\t\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\t\t\tthis.editor.setText(result.selectedText ?? \"\");\n\t\t\t\t\t\t\tthis.showStatus(\"Forked to new session\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { cancelled: result.cancelled };\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\treturn this.handleFatalRuntimeError(\"Failed to fork session\", error);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tnavigateTree: async (targetId, options) => {\n\t\t\t\t\tconst result = await this.session.navigateTree(targetId, {\n\t\t\t\t\t\tsummarize: options?.summarize,\n\t\t\t\t\t\tcustomInstructions: options?.customInstructions,\n\t\t\t\t\t\treplaceInstructions: options?.replaceInstructions,\n\t\t\t\t\t\tlabel: options?.label,\n\t\t\t\t\t});\n\t\t\t\t\tif (result.cancelled) {\n\t\t\t\t\t\treturn { cancelled: true };\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\tthis.renderInitialMessages();\n\t\t\t\t\tif (result.editorText && !this.editor.getText().trim()) {\n\t\t\t\t\t\tthis.editor.setText(result.editorText);\n\t\t\t\t\t}\n\t\t\t\t\tthis.showStatus(\"Navigated to selected point\");\n\t\t\t\t\tvoid this.flushCompactionQueue({ willRetry: false });\n\t\t\t\t\treturn { cancelled: false };\n\t\t\t\t},\n\t\t\t\tswitchSession: async (sessionPath, options) => {\n\t\t\t\t\treturn this.handleResumeSession(sessionPath, options);\n\t\t\t\t},\n\t\t\t\treload: async () => {\n\t\t\t\t\tawait this.handleReloadCommand();\n\t\t\t\t},\n\t\t\t},\n\t\t\tshutdownHandler: () => {\n\t\t\t\tthis.shutdownRequested = true;\n\t\t\t\tif (this.session.isIdle) {\n\t\t\t\t\tvoid this.shutdown();\n\t\t\t\t}\n\t\t\t},\n\t\t\tonError: (error) => {\n\t\t\t\tthis.showExtensionError(error.extensionPath, error.error, error.stack);\n\t\t\t},\n\t\t});\n\n\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\tthis.setupAutocompleteProvider();\n\n\t\tconst extensionRunner = this.session.extensionRunner;\n\t\tthis.setupExtensionShortcuts(extensionRunner);\n\t\tthis.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });\n\t\tthis.showStartupNoticesIfNeeded();\n\t}\n\n\tprivate applyRuntimeSettings(): void {\n\t\tconfigureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs());\n\t\tthis.footer.setSession(this.session);\n\t\tthis.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);\n\t\tthis.footerDataProvider.setCwd(this.sessionManager.getCwd());\n\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\t\tthis.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());\n\t\tconst clearOnShrink = this.settingsManager.getClearOnShrink();\n\t\tthis.ui.setClearOnShrink(clearOnShrink);\n\t\tif (!clearOnShrink && !this.activeStatusIndicator) {\n\t\t\tthis.statusContainer.clear();\n\t\t}\n\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\tthis.defaultEditor.setPaddingX(editorPaddingX);\n\t\tthis.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);\n\t\tif (this.editor !== this.defaultEditor) {\n\t\t\tthis.editor.setPaddingX?.(editorPaddingX);\n\t\t\tthis.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);\n\t\t}\n\t}\n\n\tprivate async rebindCurrentSession(options: { renderBeforeBind?: boolean } = {}): Promise {\n\t\tconst session = this.session;\n\n\t\tthis.unsubscribe?.();\n\t\tthis.unsubscribe = undefined;\n\t\tthis.applyRuntimeSettings();\n\n\t\tif (options.renderBeforeBind) {\n\t\t\tthis.renderCurrentSessionState();\n\t\t\tthis.subscribeToAgent();\n\t\t}\n\n\t\tawait this.bindCurrentSessionExtensions();\n\n\t\tif (this.session !== session) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!options.renderBeforeBind) {\n\t\t\tthis.subscribeToAgent();\n\t\t}\n\n\t\tawait this.updateAvailableProviderCount();\n\t\tthis.updateEditorBorderColor();\n\t\tthis.updateTerminalTitle();\n\t}\n\n\tprivate async handleFatalRuntimeError(prefix: string, error: unknown): Promise {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis.showError(`${prefix}: ${message}`);\n\t\tstopThemeWatcher();\n\t\tthis.stop();\n\t\tprocess.exit(1);\n\t}\n\n\tprivate renderCurrentSessionState(): void {\n\t\tthis.loadedResourcesContainer.clear();\n\t\tthis.chatContainer.clear();\n\t\tthis.pendingMessagesContainer.clear();\n\t\tthis.compactionQueuedMessages = [];\n\t\tthis.streamingComponent = undefined;\n\t\tthis.streamingMessage = undefined;\n\t\tthis.pendingTools.clear();\n\t\tthis.renderInitialMessages();\n\t}\n\n\t/**\n\t * Get a registered tool definition by name (for custom rendering).\n\t */\n\tprivate getRegisteredToolDefinition(toolName: string) {\n\t\treturn this.session.getToolDefinition(toolName);\n\t}\n\n\t/**\n\t * Set up keyboard shortcuts registered by extensions.\n\t */\n\tprivate setupExtensionShortcuts(extensionRunner: ExtensionRunner): void {\n\t\tconst shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());\n\t\tif (shortcuts.size === 0) return;\n\n\t\t// Create a context for shortcut handlers\n\t\tconst createContext = (): ExtensionContext => ({\n\t\t\tui: this.createExtensionUIContext(),\n\t\t\tmode: \"tui\",\n\t\t\thasUI: true,\n\t\t\tcwd: this.sessionManager.getCwd(),\n\t\t\tsessionManager: this.sessionManager,\n\t\t\tmodelRegistry: extensionRunner.getModelRegistry(),\n\t\t\tmodel: this.session.model,\n\t\t\tscopedModels: this.session.scopedModels,\n\t\t\tthinkingLevel: this.session.thinkingLevel,\n\t\t\tisIdle: () => this.session.isIdle,\n\t\t\tisProjectTrusted: () => this.settingsManager.isProjectTrusted(),\n\t\t\tsignal: this.session.agent.signal,\n\t\t\tabort: () => {\n\t\t\t\tthis.restoreQueuedMessagesToEditor({ abort: true });\n\t\t\t},\n\t\t\thasPendingMessages: () => this.session.pendingMessageCount > 0,\n\t\t\tshutdown: () => {\n\t\t\t\tthis.shutdownRequested = true;\n\t\t\t},\n\t\t\tgetContextUsage: () => this.session.getContextUsage(),\n\t\t\tcompact: (options) => {\n\t\t\t\tvoid (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.session.compact(options?.customInstructions);\n\t\t\t\t\t\toptions?.onComplete?.(result);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\t\toptions?.onError?.(err);\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t},\n\t\t\tgetSystemPrompt: () => this.session.systemPrompt,\n\t\t});\n\n\t\t// Set up the extension shortcut handler on the default editor\n\t\tthis.defaultEditor.onExtensionShortcut = (data: string) => {\n\t\t\tfor (const [shortcutStr, shortcut] of shortcuts) {\n\t\t\t\t// Cast to KeyId - extension shortcuts use the same format\n\t\t\t\tif (matchesKey(data, shortcutStr as KeyId)) {\n\t\t\t\t\t// Run handler async, don't block input\n\t\t\t\t\tPromise.resolve(shortcut.handler(createContext())).catch((err) => {\n\t\t\t\t\t\tthis.showError(`Shortcut handler error: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t\t\t});\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t};\n\t}\n\n\t/**\n\t * Set extension status text in the footer.\n\t */\n\tprivate setExtensionStatus(key: string, text: string | undefined): void {\n\t\tthis.footerDataProvider.setExtensionStatus(key, text);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate showStatusIndicator(indicator: StatusIndicator): void {\n\t\tthis.activeStatusIndicator?.dispose();\n\t\tthis.activeStatusIndicator = indicator;\n\t\tthis.statusContainer.clear();\n\t\tthis.statusContainer.addChild(indicator);\n\t}\n\n\tprivate clearStatusIndicator(kind?: StatusIndicator[\"kind\"]): void {\n\t\tif (kind && this.activeStatusIndicator?.kind !== kind) {\n\t\t\treturn;\n\t\t}\n\t\tconst hadActiveStatusIndicator = this.activeStatusIndicator !== undefined;\n\t\tthis.activeStatusIndicator?.dispose();\n\t\tthis.activeStatusIndicator = undefined;\n\t\tthis.statusContainer.clear();\n\t\tif (hadActiveStatusIndicator && this.ui.getClearOnShrink()) {\n\t\t\tthis.statusContainer.addChild(this.idleStatus);\n\t\t}\n\t}\n\n\tprivate setWorkingVisible(visible: boolean): void {\n\t\tthis.workingVisible = visible;\n\t\tif (!visible) {\n\t\t\tthis.clearStatusIndicator(\"working\");\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (this.session.isStreaming && this.activeStatusIndicator?.kind !== \"working\") {\n\t\t\tthis.showStatusIndicator(\n\t\t\t\tnew WorkingStatusIndicator(\n\t\t\t\t\tthis.ui,\n\t\t\t\t\tthis.workingMessage ?? this.defaultWorkingMessage,\n\t\t\t\t\tthis.workingIndicatorOptions,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate setWorkingIndicator(options?: WorkingIndicatorOptions): void {\n\t\tthis.workingIndicatorOptions = options;\n\t\tif (this.activeStatusIndicator?.kind === \"working\") {\n\t\t\tthis.activeStatusIndicator.setIndicator(options);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate setHiddenThinkingLabel(label?: string): void {\n\t\tthis.hiddenThinkingLabel = label ?? this.defaultHiddenThinkingLabel;\n\t\tfor (const child of this.chatContainer.children) {\n\t\t\tif (child instanceof AssistantMessageComponent) {\n\t\t\t\tchild.setHiddenThinkingLabel(this.hiddenThinkingLabel);\n\t\t\t}\n\t\t}\n\t\tif (this.streamingComponent) {\n\t\t\tthis.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Set an extension widget (string array or custom component).\n\t */\n\tprivate setExtensionWidget(\n\t\tkey: string,\n\t\tcontent: string[] | ((tui: TUI, thm: Theme) => Component & { dispose?(): void }) | undefined,\n\t\toptions?: ExtensionWidgetOptions,\n\t): void {\n\t\tconst placement = options?.placement ?? \"aboveEditor\";\n\t\tconst removeExisting = (map: Map) => {\n\t\t\tconst existing = map.get(key);\n\t\t\tif (existing?.dispose) existing.dispose();\n\t\t\tmap.delete(key);\n\t\t};\n\n\t\tremoveExisting(this.extensionWidgetsAbove);\n\t\tremoveExisting(this.extensionWidgetsBelow);\n\n\t\tif (content === undefined) {\n\t\t\tthis.renderWidgets();\n\t\t\treturn;\n\t\t}\n\n\t\tlet component: Component & { dispose?(): void };\n\n\t\tif (Array.isArray(content)) {\n\t\t\t// Wrap string array in a Container with Text components\n\t\t\tconst container = new Container();\n\t\t\tfor (const line of content.slice(0, InteractiveMode.MAX_WIDGET_LINES)) {\n\t\t\t\tcontainer.addChild(new Text(line, 1, 0));\n\t\t\t}\n\t\t\tif (content.length > InteractiveMode.MAX_WIDGET_LINES) {\n\t\t\t\tcontainer.addChild(new Text(theme.fg(\"muted\", \"... (widget truncated)\"), 1, 0));\n\t\t\t}\n\t\t\tcomponent = container;\n\t\t} else {\n\t\t\t// Factory function - create component\n\t\t\tcomponent = content(this.ui, theme);\n\t\t}\n\n\t\tconst targetMap = placement === \"belowEditor\" ? this.extensionWidgetsBelow : this.extensionWidgetsAbove;\n\t\ttargetMap.set(key, component);\n\t\tthis.renderWidgets();\n\t}\n\n\tprivate clearExtensionWidgets(): void {\n\t\tfor (const widget of this.extensionWidgetsAbove.values()) {\n\t\t\twidget.dispose?.();\n\t\t}\n\t\tfor (const widget of this.extensionWidgetsBelow.values()) {\n\t\t\twidget.dispose?.();\n\t\t}\n\t\tthis.extensionWidgetsAbove.clear();\n\t\tthis.extensionWidgetsBelow.clear();\n\t\tthis.renderWidgets();\n\t}\n\n\tprivate resetExtensionUI(): void {\n\t\tif (this.extensionSelector) {\n\t\t\tthis.hideExtensionSelector();\n\t\t}\n\t\tif (this.extensionInput) {\n\t\t\tthis.hideExtensionInput();\n\t\t}\n\t\tif (this.extensionEditor) {\n\t\t\tthis.hideExtensionEditor();\n\t\t}\n\t\tthis.ui.hideOverlay();\n\t\tthis.clearExtensionTerminalInputListeners();\n\t\tthis.setExtensionFooter(undefined);\n\t\tthis.setExtensionHeader(undefined);\n\t\tthis.clearExtensionWidgets();\n\t\tthis.footerDataProvider.clearExtensionStatuses();\n\t\tthis.footer.invalidate();\n\t\tthis.autocompleteProviderWrappers = [];\n\t\tthis.setCustomEditorComponent(undefined);\n\t\tthis.setupAutocompleteProvider();\n\t\tthis.defaultEditor.onExtensionShortcut = undefined;\n\t\tthis.updateTerminalTitle();\n\t\tthis.workingMessage = undefined;\n\t\tthis.workingVisible = true;\n\t\tthis.setWorkingIndicator();\n\t\tif (this.activeStatusIndicator?.kind === \"working\") {\n\t\t\tthis.activeStatusIndicator.setMessage(\n\t\t\t\t`${this.defaultWorkingMessage} (${keyText(\"app.interrupt\")} to interrupt)`,\n\t\t\t);\n\t\t}\n\t\tthis.setHiddenThinkingLabel();\n\t}\n\n\t// Maximum total widget lines to prevent viewport overflow\n\tprivate static readonly MAX_WIDGET_LINES = 10;\n\n\t/**\n\t * Render all extension widgets to the widget container.\n\t */\n\tprivate renderWidgets(): void {\n\t\tif (!this.widgetContainerAbove || !this.widgetContainerBelow) return;\n\t\tthis.renderWidgetContainer(this.widgetContainerAbove, this.extensionWidgetsAbove, true, true);\n\t\tthis.renderWidgetContainer(this.widgetContainerBelow, this.extensionWidgetsBelow, false, false);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate renderWidgetContainer(\n\t\tcontainer: Container,\n\t\twidgets: Map,\n\t\tspacerWhenEmpty: boolean,\n\t\tleadingSpacer: boolean,\n\t): void {\n\t\tcontainer.clear();\n\n\t\tif (widgets.size === 0) {\n\t\t\tif (spacerWhenEmpty) {\n\t\t\t\tcontainer.addChild(new Spacer(1));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (leadingSpacer) {\n\t\t\tcontainer.addChild(new Spacer(1));\n\t\t}\n\t\tfor (const component of widgets.values()) {\n\t\t\tcontainer.addChild(component);\n\t\t}\n\t}\n\n\t/**\n\t * Set a custom footer component, or restore the built-in footer.\n\t */\n\tprivate setExtensionFooter(\n\t\tfactory:\n\t\t\t| ((tui: TUI, thm: Theme, footerData: ReadonlyFooterDataProvider) => Component & { dispose?(): void })\n\t\t\t| undefined,\n\t): void {\n\t\t// Dispose existing custom footer\n\t\tif (this.customFooter?.dispose) {\n\t\t\tthis.customFooter.dispose();\n\t\t}\n\n\t\t// Remove current footer from UI\n\t\tif (this.customFooter) {\n\t\t\tthis.ui.removeChild(this.customFooter);\n\t\t} else {\n\t\t\tthis.ui.removeChild(this.footer);\n\t\t}\n\n\t\tif (factory) {\n\t\t\t// Create and add custom footer, passing the data provider\n\t\t\tthis.customFooter = factory(this.ui, theme, this.footerDataProvider);\n\t\t\tthis.ui.addChild(this.customFooter);\n\t\t} else {\n\t\t\t// Restore built-in footer\n\t\t\tthis.customFooter = undefined;\n\t\t\tthis.ui.addChild(this.footer);\n\t\t}\n\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Set a custom header component, or restore the built-in header.\n\t */\n\tprivate setExtensionHeader(factory: ((tui: TUI, thm: Theme) => Component & { dispose?(): void }) | undefined): void {\n\t\t// Header may not be initialized yet if called during early initialization\n\t\tif (!this.builtInHeader) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Dispose existing custom header\n\t\tif (this.customHeader?.dispose) {\n\t\t\tthis.customHeader.dispose();\n\t\t}\n\n\t\t// Find the index of the current header in the header container\n\t\tconst currentHeader = this.customHeader || this.builtInHeader;\n\t\tconst index = this.headerContainer.children.indexOf(currentHeader);\n\n\t\tif (factory) {\n\t\t\t// Create and add custom header\n\t\t\tthis.customHeader = factory(this.ui, theme);\n\t\t\tif (isExpandable(this.customHeader)) {\n\t\t\t\tthis.customHeader.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.headerContainer.children[index] = this.customHeader;\n\t\t\t} else {\n\t\t\t\t// If not found (e.g. builtInHeader was never added), add at the top\n\t\t\t\tthis.headerContainer.children.unshift(this.customHeader);\n\t\t\t}\n\t\t} else {\n\t\t\t// Restore built-in header\n\t\t\tthis.customHeader = undefined;\n\t\t\tif (isExpandable(this.builtInHeader)) {\n\t\t\t\tthis.builtInHeader.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.headerContainer.children[index] = this.builtInHeader;\n\t\t\t}\n\t\t}\n\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate addExtensionTerminalInputListener(\n\t\thandler: (data: string) => { consume?: boolean; data?: string } | undefined,\n\t): () => void {\n\t\tconst unsubscribe = this.ui.addInputListener(handler);\n\t\tthis.extensionTerminalInputUnsubscribers.add(unsubscribe);\n\t\treturn () => {\n\t\t\tunsubscribe();\n\t\t\tthis.extensionTerminalInputUnsubscribers.delete(unsubscribe);\n\t\t};\n\t}\n\n\tprivate clearExtensionTerminalInputListeners(): void {\n\t\tfor (const unsubscribe of this.extensionTerminalInputUnsubscribers) {\n\t\t\tunsubscribe();\n\t\t}\n\t\tthis.extensionTerminalInputUnsubscribers.clear();\n\t}\n\n\t/**\n\t * Create the ExtensionUIContext for extensions.\n\t */\n\tprivate createProjectTrustContext(cwd: string): ProjectTrustContext {\n\t\tconst ui = this.createExtensionUIContext();\n\t\treturn {\n\t\t\tcwd,\n\t\t\tmode: \"tui\",\n\t\t\thasUI: true,\n\t\t\tui: {\n\t\t\t\tselect: ui.select,\n\t\t\t\tconfirm: ui.confirm,\n\t\t\t\tinput: ui.input,\n\t\t\t\tnotify: ui.notify,\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate createExtensionUIContext(): ExtensionUIContext {\n\t\treturn {\n\t\t\tselect: (title, options, opts) => this.showExtensionSelector(title, options, opts),\n\t\t\tconfirm: (title, message, opts) => this.showExtensionConfirm(title, message, opts),\n\t\t\tinput: (title, placeholder, opts) => this.showExtensionInput(title, placeholder, opts),\n\t\t\tnotify: (message, type) => this.showExtensionNotify(message, type),\n\t\t\tonTerminalInput: (handler) => this.addExtensionTerminalInputListener(handler),\n\t\t\tsetStatus: (key, text) => this.setExtensionStatus(key, text),\n\t\t\tsetWorkingMessage: (message) => {\n\t\t\t\tthis.workingMessage = message;\n\t\t\t\tif (this.activeStatusIndicator?.kind === \"working\") {\n\t\t\t\t\tthis.activeStatusIndicator.setMessage(message ?? this.defaultWorkingMessage);\n\t\t\t\t}\n\t\t\t},\n\t\t\tsetWorkingVisible: (visible) => this.setWorkingVisible(visible),\n\t\t\tsetWorkingIndicator: (options) => this.setWorkingIndicator(options),\n\t\t\tsetHiddenThinkingLabel: (label) => this.setHiddenThinkingLabel(label),\n\t\t\tsetWidget: (key, content, options) => this.setExtensionWidget(key, content, options),\n\t\t\tsetFooter: (factory) => this.setExtensionFooter(factory),\n\t\t\tsetHeader: (factory) => this.setExtensionHeader(factory),\n\t\t\tsetTitle: (title) => this.ui.terminal.setTitle(title),\n\t\t\tcustom: (factory, options) => this.showExtensionCustom(factory, options),\n\t\t\tpasteToEditor: (text) => this.editor.handleInput(`\\x1b[200~${text}\\x1b[201~`),\n\t\t\tsetEditorText: (text) => this.editor.setText(text),\n\t\t\tgetEditorText: () => this.editor.getExpandedText?.() ?? this.editor.getText(),\n\t\t\teditor: (title, prefill) => this.showExtensionEditor(title, prefill),\n\t\t\taddAutocompleteProvider: (factory) => {\n\t\t\t\tthis.autocompleteProviderWrappers.push(factory);\n\t\t\t\tthis.setupAutocompleteProvider();\n\t\t\t},\n\t\t\tsetEditorComponent: (factory) => this.setCustomEditorComponent(factory),\n\t\t\tgetEditorComponent: () => this.editorComponentFactory,\n\t\t\tget theme() {\n\t\t\t\treturn theme;\n\t\t\t},\n\t\t\tgetAllThemes: () => getAvailableThemesWithPaths(),\n\t\t\tgetTheme: (name) => getThemeByName(name),\n\t\t\tsetTheme: (themeOrName) => {\n\t\t\t\tif (themeOrName instanceof Theme) {\n\t\t\t\t\treturn this.themeController.setThemeInstance(themeOrName);\n\t\t\t\t}\n\t\t\t\tconst result = this.themeController.setThemeName(themeOrName);\n\t\t\t\tif (result.success) {\n\t\t\t\t\tif (this.settingsManager.getTheme() !== themeOrName) {\n\t\t\t\t\t\tthis.settingsManager.setTheme(themeOrName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tgetToolsExpanded: () => this.toolOutputExpanded,\n\t\t\tsetToolsExpanded: (expanded) => this.setToolsExpanded(expanded),\n\t\t};\n\t}\n\n\t/**\n\t * Show a selector for extensions.\n\t */\n\tprivate showExtensionSelector(\n\t\ttitle: string,\n\t\toptions: string[],\n\t\topts?: ExtensionUIDialogOptions,\n\t): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tif (opts?.signal?.aborted) {\n\t\t\t\tresolve(undefined);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tthis.hideExtensionSelector();\n\t\t\t\tresolve(undefined);\n\t\t\t};\n\t\t\topts?.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\tthis.extensionSelector = new ExtensionSelectorComponent(\n\t\t\t\ttitle,\n\t\t\t\toptions,\n\t\t\t\t(option) => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionSelector();\n\t\t\t\t\tresolve(option);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionSelector();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t\t{ tui: this.ui, timeout: opts?.timeout, onToggleToolsExpanded: () => this.toggleToolOutputExpansion() },\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.extensionSelector);\n\t\t\tthis.ui.setFocus(this.extensionSelector);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the extension selector.\n\t */\n\tprivate hideExtensionSelector(): void {\n\t\tthis.extensionSelector?.dispose();\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.extensionSelector = undefined;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a confirmation dialog for extensions.\n\t */\n\tprivate async showExtensionConfirm(\n\t\ttitle: string,\n\t\tmessage: string,\n\t\topts?: ExtensionUIDialogOptions,\n\t): Promise {\n\t\tconst result = await this.showExtensionSelector(`${title}\\n${message}`, [\"Yes\", \"No\"], opts);\n\t\treturn result === \"Yes\";\n\t}\n\n\tprivate async promptForMissingSessionCwd(error: MissingSessionCwdError): Promise {\n\t\tconst confirmed = await this.showExtensionConfirm(\n\t\t\t\"Session cwd not found\",\n\t\t\tformatMissingSessionCwdPrompt(error.issue),\n\t\t);\n\t\treturn confirmed ? error.issue.fallbackCwd : undefined;\n\t}\n\n\t/**\n\t * Show a text input for extensions.\n\t */\n\tprivate showExtensionInput(\n\t\ttitle: string,\n\t\tplaceholder?: string,\n\t\topts?: ExtensionUIDialogOptions,\n\t): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tif (opts?.signal?.aborted) {\n\t\t\t\tresolve(undefined);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tthis.hideExtensionInput();\n\t\t\t\tresolve(undefined);\n\t\t\t};\n\t\t\topts?.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\tthis.extensionInput = new ExtensionInputComponent(\n\t\t\t\ttitle,\n\t\t\t\tplaceholder,\n\t\t\t\t(value) => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionInput();\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionInput();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t\t{ tui: this.ui, timeout: opts?.timeout },\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.extensionInput);\n\t\t\tthis.ui.setFocus(this.extensionInput);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the extension input.\n\t */\n\tprivate hideExtensionInput(): void {\n\t\tthis.extensionInput?.dispose();\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.extensionInput = undefined;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a multi-line editor for extensions (with Ctrl+G support).\n\t */\n\tprivate showExtensionEditor(title: string, prefill?: string): Promise {\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.extensionEditor = new ExtensionEditorComponent(\n\t\t\t\tthis.ui,\n\t\t\t\tthis.keybindings,\n\t\t\t\ttitle,\n\t\t\t\tprefill,\n\t\t\t\t(value) => {\n\t\t\t\t\tthis.hideExtensionEditor();\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tthis.hideExtensionEditor();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t\tundefined,\n\t\t\t\tthis.settingsManager.getExternalEditorCommand(),\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.extensionEditor);\n\t\t\tthis.ui.setFocus(this.extensionEditor);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the extension editor.\n\t */\n\tprivate hideExtensionEditor(): void {\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.extensionEditor = undefined;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Set a custom editor component from an extension.\n\t * Pass undefined to restore the default editor.\n\t */\n\tprivate setCustomEditorComponent(factory: EditorFactory | undefined): void {\n\t\tthis.editorComponentFactory = factory;\n\n\t\t// Save text from current editor before switching\n\t\tconst currentText = this.editor.getText();\n\n\t\tthis.editorContainer.clear();\n\n\t\tif (factory) {\n\t\t\t// Create the custom editor with tui, theme, and keybindings\n\t\t\tconst newEditor = factory(this.ui, getEditorTheme(), this.keybindings);\n\n\t\t\t// Wire up callbacks from the default editor\n\t\t\tnewEditor.onSubmit = this.defaultEditor.onSubmit;\n\t\t\tnewEditor.onChange = this.defaultEditor.onChange;\n\n\t\t\t// Copy text from previous editor\n\t\t\tnewEditor.setText(currentText);\n\n\t\t\t// Copy appearance settings if supported\n\t\t\tif (newEditor.borderColor !== undefined) {\n\t\t\t\tnewEditor.borderColor = this.defaultEditor.borderColor;\n\t\t\t}\n\t\t\tif (newEditor.setPaddingX !== undefined) {\n\t\t\t\tnewEditor.setPaddingX(this.defaultEditor.getPaddingX());\n\t\t\t}\n\n\t\t\t// Set autocomplete if supported\n\t\t\tif (newEditor.setAutocompleteProvider && this.autocompleteProvider) {\n\t\t\t\tnewEditor.setAutocompleteProvider(this.autocompleteProvider);\n\t\t\t}\n\n\t\t\t// If extending CustomEditor, copy app-level handlers\n\t\t\t// Use duck typing since instanceof fails across jiti module boundaries\n\t\t\tconst customEditor = newEditor as unknown as Record;\n\t\t\tif (\"actionHandlers\" in customEditor && customEditor.actionHandlers instanceof Map) {\n\t\t\t\tif (!customEditor.onEscape) {\n\t\t\t\t\tcustomEditor.onEscape = () => this.defaultEditor.onEscape?.();\n\t\t\t\t}\n\t\t\t\tif (!customEditor.onCtrlD) {\n\t\t\t\t\tcustomEditor.onCtrlD = () => this.defaultEditor.onCtrlD?.();\n\t\t\t\t}\n\t\t\t\tif (!customEditor.onPasteImage) {\n\t\t\t\t\tcustomEditor.onPasteImage = () => this.defaultEditor.onPasteImage?.();\n\t\t\t\t}\n\t\t\t\tif (!customEditor.onExtensionShortcut) {\n\t\t\t\t\tcustomEditor.onExtensionShortcut = (data: string) => this.defaultEditor.onExtensionShortcut?.(data);\n\t\t\t\t}\n\t\t\t\t// Copy action handlers (clear, suspend, model switching, etc.)\n\t\t\t\tfor (const [action, handler] of this.defaultEditor.actionHandlers) {\n\t\t\t\t\t(customEditor.actionHandlers as Map void>).set(action, handler);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.editor = newEditor;\n\t\t} else {\n\t\t\t// Restore default editor with text from custom editor\n\t\t\tthis.defaultEditor.setText(currentText);\n\t\t\tthis.editor = this.defaultEditor;\n\t\t}\n\n\t\tthis.editorContainer.addChild(this.editor as Component);\n\t\tthis.ui.setFocus(this.editor as Component);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a notification for extensions.\n\t */\n\tprivate showExtensionNotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void {\n\t\tif (type === \"error\") {\n\t\t\tthis.showError(message);\n\t\t} else if (type === \"warning\") {\n\t\t\tthis.showWarning(message);\n\t\t} else {\n\t\t\tthis.showStatus(message);\n\t\t}\n\t}\n\n\t/** Show a custom component with keyboard focus. Overlay mode renders on top of existing content. */\n\tprivate async showExtensionCustom(\n\t\tfactory: (\n\t\t\ttui: TUI,\n\t\t\ttheme: Theme,\n\t\t\tkeybindings: KeybindingsManager,\n\t\t\tdone: (result: T) => void,\n\t\t) => (Component & { dispose?(): void }) | Promise,\n\t\toptions?: {\n\t\t\toverlay?: boolean;\n\t\t\toverlayOptions?: OverlayOptions | (() => OverlayOptions);\n\t\t\tonHandle?: (handle: OverlayHandle) => void;\n\t\t},\n\t): Promise {\n\t\tconst savedText = this.editor.getText();\n\t\tconst isOverlay = options?.overlay ?? false;\n\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.editor.setText(savedText);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet component: Component & { dispose?(): void };\n\t\t\tlet closed = false;\n\n\t\t\tconst close = (result: T) => {\n\t\t\t\tif (closed) return;\n\t\t\t\tclosed = true;\n\t\t\t\tif (isOverlay) this.ui.hideOverlay();\n\t\t\t\telse restoreEditor();\n\t\t\t\t// Note: both branches above already call requestRender\n\t\t\t\tresolve(result);\n\t\t\t\ttry {\n\t\t\t\t\tcomponent?.dispose?.();\n\t\t\t\t} catch {\n\t\t\t\t\t/* ignore dispose errors */\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tPromise.resolve(factory(this.ui, theme, this.keybindings, close))\n\t\t\t\t.then((c) => {\n\t\t\t\t\tif (closed) return;\n\t\t\t\t\tcomponent = c;\n\t\t\t\t\tif (isOverlay) {\n\t\t\t\t\t\t// Resolve overlay options - can be static or dynamic function\n\t\t\t\t\t\tconst resolveOptions = (): OverlayOptions | undefined => {\n\t\t\t\t\t\t\tif (options?.overlayOptions) {\n\t\t\t\t\t\t\t\tconst opts =\n\t\t\t\t\t\t\t\t\ttypeof options.overlayOptions === \"function\"\n\t\t\t\t\t\t\t\t\t\t? options.overlayOptions()\n\t\t\t\t\t\t\t\t\t\t: options.overlayOptions;\n\t\t\t\t\t\t\t\treturn opts;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Fallback: use component's width property if available\n\t\t\t\t\t\t\tconst w = (component as { width?: number }).width;\n\t\t\t\t\t\t\treturn w ? { width: w } : undefined;\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst handle = this.ui.showOverlay(component, resolveOptions());\n\t\t\t\t\t\t// Expose handle to caller for visibility control\n\t\t\t\t\t\toptions?.onHandle?.(handle);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.editorContainer.clear();\n\t\t\t\t\t\tthis.editorContainer.addChild(component);\n\t\t\t\t\t\tthis.ui.setFocus(component);\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tif (closed) return;\n\t\t\t\t\tif (!isOverlay) restoreEditor();\n\t\t\t\t\treject(err);\n\t\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Show an extension error in the UI.\n\t */\n\tprivate showExtensionError(extensionPath: string, error: string, stack?: string): void {\n\t\tconst errorMsg = `Extension \"${extensionPath}\" error: ${error}`;\n\t\tconst errorText = new Text(theme.fg(\"error\", errorMsg), 1, 0);\n\t\tthis.chatContainer.addChild(errorText);\n\t\tif (stack) {\n\t\t\t// Show stack trace in dim color, indented\n\t\t\tconst stackLines = stack\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.slice(1) // Skip first line (duplicates error message)\n\t\t\t\t.map((line) => theme.fg(\"dim\", ` ${line.trim()}`))\n\t\t\t\t.join(\"\\n\");\n\t\t\tif (stackLines) {\n\t\t\t\tthis.chatContainer.addChild(new Text(stackLines, 1, 0));\n\t\t\t}\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\t// =========================================================================\n\t// Key Handlers\n\t// =========================================================================\n\n\tprivate setupKeyHandlers(): void {\n\t\t// Set up handlers on defaultEditor - they use this.editor for text access\n\t\t// so they work correctly regardless of which editor is active\n\t\tthis.defaultEditor.onEscape = () => {\n\t\t\tif (this.session.isStreaming) {\n\t\t\t\tthis.restoreQueuedMessagesToEditor({ abort: true });\n\t\t\t} else if (this.session.isBashRunning) {\n\t\t\t\tthis.session.abortBash();\n\t\t\t} else if (this.isBashMode) {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tthis.isBashMode = false;\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t} else if (!this.editor.getText().trim()) {\n\t\t\t\t// Double-escape with empty editor triggers /tree, /fork, or nothing based on setting\n\t\t\t\tconst action = this.settingsManager.getDoubleEscapeAction();\n\t\t\t\tif (action !== \"none\") {\n\t\t\t\t\tconst now = Date.now();\n\t\t\t\t\tif (now - this.lastEscapeTime < 500) {\n\t\t\t\t\t\tif (action === \"tree\") {\n\t\t\t\t\t\t\tthis.showTreeSelector();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.showUserMessageSelector();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.lastEscapeTime = 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.lastEscapeTime = now;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Register app action handlers\n\t\tthis.defaultEditor.onAction(\"app.clear\", () => this.handleCtrlC());\n\t\tthis.defaultEditor.onCtrlD = () => this.handleCtrlD();\n\t\tthis.defaultEditor.onAction(\"app.suspend\", () => this.handleCtrlZ());\n\t\tthis.defaultEditor.onAction(\"app.thinking.cycle\", () => this.cycleThinkingLevel());\n\t\tthis.defaultEditor.onAction(\"app.model.cycleForward\", () => this.cycleModel(\"forward\"));\n\t\tthis.defaultEditor.onAction(\"app.model.cycleBackward\", () => this.cycleModel(\"backward\"));\n\n\t\t// Global debug handler on TUI (works regardless of focus)\n\t\tthis.ui.onDebug = () => this.handleDebugCommand();\n\t\tthis.defaultEditor.onAction(\"app.model.select\", () => this.showModelSelector());\n\t\tthis.defaultEditor.onAction(\"app.tools.expand\", () => this.toggleToolOutputExpansion());\n\t\tthis.defaultEditor.onAction(\"app.thinking.toggle\", () => this.toggleThinkingBlockVisibility());\n\t\tthis.defaultEditor.onAction(\"app.editor.external\", () => void this.handleOpenExternalEditor());\n\t\tthis.defaultEditor.onAction(\"app.message.copy\", () => void this.handleCopyCommand());\n\t\tthis.defaultEditor.onAction(\"app.message.followUp\", () => this.handleFollowUp());\n\t\tthis.defaultEditor.onAction(\"app.message.dequeue\", () => this.handleDequeue());\n\t\tthis.defaultEditor.onAction(\"app.session.new\", () => this.handleClearCommand());\n\t\tthis.defaultEditor.onAction(\"app.session.tree\", () => this.showTreeSelector());\n\t\tthis.defaultEditor.onAction(\"app.session.fork\", () => this.showUserMessageSelector());\n\t\tthis.defaultEditor.onAction(\"app.session.resume\", () => this.showSessionSelector());\n\n\t\tthis.defaultEditor.onChange = (text: string) => {\n\t\t\tconst wasBashMode = this.isBashMode;\n\t\t\tthis.isBashMode = text.trimStart().startsWith(\"!\");\n\t\t\tif (wasBashMode !== this.isBashMode) {\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t}\n\t\t};\n\n\t\t// Handle clipboard paste (triggered on Ctrl+V). Images are attached by path;\n\t\t// otherwise, paste plain text from the system clipboard.\n\t\tthis.defaultEditor.onPasteImage = () => {\n\t\t\tvoid this.handleClipboardPaste();\n\t\t};\n\t}\n\n\tprivate async handleClipboardPaste(): Promise {\n\t\ttry {\n\t\t\tconst image = await readClipboardImage();\n\t\t\tif (image) {\n\t\t\t\tconst tmpDir = os.tmpdir();\n\t\t\t\tconst ext = extensionForImageMimeType(image.mimeType) ?? \"png\";\n\t\t\t\tconst fileName = `pi-clipboard-${crypto.randomUUID()}.${ext}`;\n\t\t\t\tconst filePath = path.join(tmpDir, fileName);\n\t\t\t\tfs.writeFileSync(filePath, Buffer.from(image.bytes));\n\n\t\t\t\tthis.editor.insertTextAtCursor?.(filePath);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst text = await readClipboardText();\n\t\t\tif (text) {\n\t\t\t\tthis.editor.insertTextAtCursor?.(text);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t}\n\t\t} catch {\n\t\t\t// Silently ignore clipboard errors (may not have permission, etc.)\n\t\t}\n\t}\n\n\tprivate setupEditorSubmitHandler(): void {\n\t\tthis.defaultEditor.onSubmit = async (text: string) => {\n\t\t\ttext = text.trim();\n\t\t\tif (!text) return;\n\n\t\t\t// Handle commands\n\t\t\tif (text === \"/settings\") {\n\t\t\t\tthis.showSettingsSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/scoped-models\") {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.showModelsSelector();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/model\" || text.startsWith(\"/model \")) {\n\t\t\t\tconst searchTerm = text.startsWith(\"/model \") ? text.slice(7).trim() : undefined;\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.handleModelCommand(searchTerm);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/export\" || text.startsWith(\"/export \")) {\n\t\t\t\tawait this.handleExportCommand(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/import\" || text.startsWith(\"/import \")) {\n\t\t\t\tawait this.handleImportCommand(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/share\") {\n\t\t\t\tawait this.handleShareCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/copy\") {\n\t\t\t\tawait this.handleCopyCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/name\" || text.startsWith(\"/name \")) {\n\t\t\t\tthis.handleNameCommand(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/session\") {\n\t\t\t\tthis.handleSessionCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/changelog\") {\n\t\t\t\tthis.handleChangelogCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/hotkeys\") {\n\t\t\t\tthis.handleHotkeysCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/fork\") {\n\t\t\t\tthis.showUserMessageSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/clone\") {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.handleCloneCommand();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/tree\") {\n\t\t\t\tthis.showTreeSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/trust\") {\n\t\t\t\tthis.showTrustSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/login\" || text.startsWith(\"/login \")) {\n\t\t\t\tconst providerRef = text.startsWith(\"/login \") ? text.slice(7).trim() : undefined;\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.handleLoginCommand(providerRef);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/logout\") {\n\t\t\t\tthis.showOAuthSelector(\"logout\");\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/new\") {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.handleClearCommand();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/compact\" || text.startsWith(\"/compact \")) {\n\t\t\t\tconst customInstructions = text.startsWith(\"/compact \") ? text.slice(9).trim() : undefined;\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.handleCompactCommand(customInstructions);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/reload\") {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.handleReloadCommand();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/debug\") {\n\t\t\t\tthis.handleDebugCommand();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/arminsayshi\") {\n\t\t\t\tthis.handleArminSaysHi();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/dementedelves\") {\n\t\t\t\tthis.handleDementedDelves();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/resume\") {\n\t\t\t\tthis.showSessionSelector();\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text === \"/quit\") {\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.shutdown();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Handle bash command (! for normal, !! for excluded from context)\n\t\t\tif (text.startsWith(\"!\")) {\n\t\t\t\tconst isExcluded = text.startsWith(\"!!\");\n\t\t\t\tconst command = isExcluded ? text.slice(2).trim() : text.slice(1).trim();\n\t\t\t\tif (command) {\n\t\t\t\t\tif (this.session.isBashRunning) {\n\t\t\t\t\t\tthis.showWarning(\"A bash command is already running. Press Esc to cancel it first.\");\n\t\t\t\t\t\tthis.editor.setText(text);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthis.editor.addToHistory?.(text);\n\t\t\t\t\tawait this.handleBashCommand(command, isExcluded);\n\t\t\t\t\tthis.isBashMode = false;\n\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Queue input during compaction (extension commands execute immediately)\n\t\t\tif (this.session.isCompacting) {\n\t\t\t\tif (this.isExtensionCommand(text)) {\n\t\t\t\t\tthis.editor.addToHistory?.(text);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.session.prompt(text);\n\t\t\t\t} else {\n\t\t\t\t\tthis.queueCompactionMessage(text, \"steer\");\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// If streaming, use prompt() with steer behavior\n\t\t\t// This handles extension commands (execute immediately), prompt template expansion, and queueing\n\t\t\tif (this.session.isStreaming) {\n\t\t\t\tthis.editor.addToHistory?.(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.session.prompt(text, { streamingBehavior: \"steer\" });\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Normal message submission\n\t\t\t// First, move any pending bash components to chat\n\t\t\tthis.flushPendingBashComponents();\n\n\t\t\tif (this.onInputCallback) {\n\t\t\t\tthis.onInputCallback(text);\n\t\t\t} else {\n\t\t\t\tthis.pendingUserInputs.push(text);\n\t\t\t}\n\t\t\tthis.editor.addToHistory?.(text);\n\t\t};\n\t}\n\n\tprivate subscribeToAgent(): void {\n\t\tthis.unsubscribe = this.session.subscribe(async (event) => {\n\t\t\tawait this.handleEvent(event);\n\t\t});\n\t}\n\n\tprivate async handleEvent(event: AgentSessionEvent): Promise {\n\t\tif (!this.isInitialized) {\n\t\t\tawait this.init();\n\t\t}\n\n\t\tthis.footer.invalidate();\n\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\t\tthis.pendingTools.clear();\n\t\t\t\tif (this.settingsManager.getShowTerminalProgress()) {\n\t\t\t\t\tthis.ui.terminal.setProgress(true);\n\t\t\t\t}\n\t\t\t\t// Restore main escape handler if retry handler is still active\n\t\t\t\t// (retry success event fires later, but we need main handler now)\n\t\t\t\tif (this.retryEscapeHandler) {\n\t\t\t\t\tthis.defaultEditor.onEscape = this.retryEscapeHandler;\n\t\t\t\t\tthis.retryEscapeHandler = undefined;\n\t\t\t\t}\n\t\t\t\tif (this.workingVisible) {\n\t\t\t\t\tthis.showStatusIndicator(\n\t\t\t\t\t\tnew WorkingStatusIndicator(\n\t\t\t\t\t\t\tthis.ui,\n\t\t\t\t\t\t\tthis.workingMessage ?? this.defaultWorkingMessage,\n\t\t\t\t\t\t\tthis.workingIndicatorOptions,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tthis.clearStatusIndicator();\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"queue_update\":\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"entry_appended\":\n\t\t\t\tif (event.entry.type === \"custom\") {\n\t\t\t\t\tthis.addCustomEntryToChat(event.entry);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"session_info_changed\":\n\t\t\t\tthis.updateTerminalTitle();\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"thinking_level_changed\":\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_start\":\n\t\t\t\tif (event.message.role === \"custom\") {\n\t\t\t\t\tthis.addMessageToChat(event.message);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t} else if (event.message.role === \"user\") {\n\t\t\t\t\tthis.addMessageToChat(event.message);\n\t\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t} else if (event.message.role === \"assistant\") {\n\t\t\t\t\tthis.streamingComponent = new AssistantMessageComponent(\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tthis.hideThinkingBlock,\n\t\t\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\t\t\tthis.hiddenThinkingLabel,\n\t\t\t\t\t\tthis.outputPad,\n\t\t\t\t\t);\n\t\t\t\t\tthis.streamingMessage = event.message;\n\t\t\t\t\tthis.chatContainer.addChild(this.streamingComponent);\n\t\t\t\t\tthis.streamingComponent.updateContent(this.streamingMessage);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tif (this.streamingComponent && event.message.role === \"assistant\") {\n\t\t\t\t\tthis.streamingMessage = event.message;\n\t\t\t\t\tthis.streamingComponent.updateContent(this.streamingMessage);\n\n\t\t\t\t\tfor (const content of this.streamingMessage.content) {\n\t\t\t\t\t\tif (content.type === \"toolCall\") {\n\t\t\t\t\t\t\tif (!this.pendingTools.has(content.id)) {\n\t\t\t\t\t\t\t\tconst component = new ToolExecutionComponent(\n\t\t\t\t\t\t\t\t\tcontent.name,\n\t\t\t\t\t\t\t\t\tcontent.id,\n\t\t\t\t\t\t\t\t\tcontent.arguments,\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\t\t\t\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tthis.getRegisteredToolDefinition(content.name),\n\t\t\t\t\t\t\t\t\tthis.ui,\n\t\t\t\t\t\t\t\t\tthis.sessionManager.getCwd(),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t\t\t\t\tthis.pendingTools.set(content.id, component);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tconst component = this.pendingTools.get(content.id);\n\t\t\t\t\t\t\t\tif (component) {\n\t\t\t\t\t\t\t\t\tcomponent.updateArgs(content.arguments);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tif (event.message.role === \"user\") break;\n\t\t\t\tif (this.streamingComponent && event.message.role === \"assistant\") {\n\t\t\t\t\tthis.streamingMessage = event.message;\n\t\t\t\t\tlet errorMessage: string | undefined;\n\t\t\t\t\tif (this.streamingMessage.stopReason === \"aborted\") {\n\t\t\t\t\t\tconst retryAttempt = this.session.retryAttempt;\n\t\t\t\t\t\terrorMessage =\n\t\t\t\t\t\t\tretryAttempt > 0\n\t\t\t\t\t\t\t\t? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? \"s\" : \"\"}`\n\t\t\t\t\t\t\t\t: \"Operation aborted\";\n\t\t\t\t\t\tthis.streamingMessage.errorMessage = errorMessage;\n\t\t\t\t\t}\n\t\t\t\t\tthis.streamingComponent.updateContent(this.streamingMessage);\n\n\t\t\t\t\tif (this.streamingMessage.stopReason === \"aborted\" || this.streamingMessage.stopReason === \"error\") {\n\t\t\t\t\t\tif (!errorMessage) {\n\t\t\t\t\t\t\terrorMessage = this.streamingMessage.errorMessage || \"Error\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const [, component] of this.pendingTools.entries()) {\n\t\t\t\t\t\t\tcomponent.updateResult({\n\t\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: errorMessage }],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.pendingTools.clear();\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Args are now complete - trigger diff computation for edit tools\n\t\t\t\t\t\tfor (const [, component] of this.pendingTools.entries()) {\n\t\t\t\t\t\t\tcomponent.setArgsComplete();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.maybeShowCacheMissNotice(this.streamingMessage);\n\t\t\t\t\t}\n\t\t\t\t\tthis.streamingComponent = undefined;\n\t\t\t\t\tthis.streamingMessage = undefined;\n\t\t\t\t\tthis.footer.invalidate();\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"bash_execution_update\":\n\t\t\t\t// The bash execution callback handles TUI output rendering.\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tlet component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (!component) {\n\t\t\t\t\tcomponent = new ToolExecutionComponent(\n\t\t\t\t\t\tevent.toolName,\n\t\t\t\t\t\tevent.toolCallId,\n\t\t\t\t\t\tevent.args,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tthis.getRegisteredToolDefinition(event.toolName),\n\t\t\t\t\t\tthis.ui,\n\t\t\t\t\t\tthis.sessionManager.getCwd(),\n\t\t\t\t\t);\n\t\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t\tthis.pendingTools.set(event.toolCallId, component);\n\t\t\t\t}\n\t\t\t\tcomponent.markExecutionStarted();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_update\": {\n\t\t\t\tconst component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\tcomponent.updateResult({ ...event.partialResult, isError: false }, true);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\tcomponent.updateResult({ ...event.result, isError: event.isError });\n\t\t\t\t\tthis.pendingTools.delete(event.toolCallId);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tif (this.settingsManager.getShowTerminalProgress()) {\n\t\t\t\t\tthis.ui.terminal.setProgress(false);\n\t\t\t\t}\n\t\t\t\tthis.clearStatusIndicator(\"working\");\n\t\t\t\tif (this.streamingComponent) {\n\t\t\t\t\tthis.chatContainer.removeChild(this.streamingComponent);\n\t\t\t\t\tthis.streamingComponent = undefined;\n\t\t\t\t\tthis.streamingMessage = undefined;\n\t\t\t\t}\n\t\t\t\tthis.pendingTools.clear();\n\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_settled\":\n\t\t\t\tawait this.checkShutdownRequested();\n\t\t\t\tbreak;\n\n\t\t\tcase \"compaction_start\": {\n\t\t\t\tif (this.settingsManager.getShowTerminalProgress()) {\n\t\t\t\t\tthis.ui.terminal.setProgress(true);\n\t\t\t\t}\n\t\t\t\t// Keep editor active; submissions are queued during compaction.\n\t\t\t\tthis.autoCompactionEscapeHandler = this.defaultEditor.onEscape;\n\t\t\t\tthis.defaultEditor.onEscape = () => {\n\t\t\t\t\tthis.session.abortCompaction();\n\t\t\t\t};\n\t\t\t\tthis.showStatusIndicator(new CompactionStatusIndicator(this.ui, event.reason));\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"compaction_end\": {\n\t\t\t\tif (this.settingsManager.getShowTerminalProgress()) {\n\t\t\t\t\tthis.ui.terminal.setProgress(false);\n\t\t\t\t}\n\t\t\t\tif (this.autoCompactionEscapeHandler) {\n\t\t\t\t\tthis.defaultEditor.onEscape = this.autoCompactionEscapeHandler;\n\t\t\t\t\tthis.autoCompactionEscapeHandler = undefined;\n\t\t\t\t}\n\t\t\t\tthis.clearStatusIndicator(\"compaction\");\n\t\t\t\tif (event.aborted) {\n\t\t\t\t\tif (event.reason === \"manual\") {\n\t\t\t\t\t\tthis.showError(\"Compaction cancelled\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.showStatus(\"Auto-compaction cancelled\");\n\t\t\t\t\t}\n\t\t\t\t} else if (event.result) {\n\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\t\tthis.addMessageToChat(\n\t\t\t\t\t\tcreateCompactionSummaryMessage(\n\t\t\t\t\t\t\tevent.result.summary,\n\t\t\t\t\t\t\tevent.result.tokensBefore,\n\t\t\t\t\t\t\tnew Date().toISOString(),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tthis.footer.invalidate();\n\t\t\t\t} else if (event.errorMessage) {\n\t\t\t\t\tif (event.reason === \"manual\") {\n\t\t\t\t\t\tthis.showError(event.errorMessage);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"error\", event.errorMessage), 1, 0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvoid this.flushCompactionQueue({ willRetry: event.willRetry });\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"auto_retry_start\": {\n\t\t\t\t// Set up escape to abort retry\n\t\t\t\tthis.retryEscapeHandler = this.defaultEditor.onEscape;\n\t\t\t\tthis.defaultEditor.onEscape = () => {\n\t\t\t\t\tthis.session.abortRetry();\n\t\t\t\t};\n\t\t\t\tthis.showStatusIndicator(\n\t\t\t\t\tnew RetryStatusIndicator(this.ui, event.attempt, event.maxAttempts, event.delayMs),\n\t\t\t\t);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"auto_retry_end\": {\n\t\t\t\t// Restore escape handler\n\t\t\t\tif (this.retryEscapeHandler) {\n\t\t\t\t\tthis.defaultEditor.onEscape = this.retryEscapeHandler;\n\t\t\t\t\tthis.retryEscapeHandler = undefined;\n\t\t\t\t}\n\t\t\t\tthis.clearStatusIndicator(\"retry\");\n\t\t\t\t// Show error only on final failure (success shows normal response)\n\t\t\t\tif (!event.success) {\n\t\t\t\t\tthis.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError || \"Unknown error\"}`);\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"summarization_retry_scheduled\": {\n\t\t\t\tthis.showError(event.errorMessage);\n\t\t\t\tthis.showStatusIndicator(\n\t\t\t\t\tnew RetryStatusIndicator(this.ui, event.attempt, event.maxAttempts, event.delayMs),\n\t\t\t\t);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"summarization_retry_attempt_start\": {\n\t\t\t\tthis.clearStatusIndicator(\"retry\");\n\t\t\t\tif (event.source === \"branchSummary\") {\n\t\t\t\t\tthis.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui));\n\t\t\t\t} else {\n\t\t\t\t\tthis.showStatusIndicator(new CompactionStatusIndicator(this.ui, event.reason));\n\t\t\t\t}\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"summarization_retry_finished\": {\n\t\t\t\tthis.clearStatusIndicator(\"retry\");\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Extract text content from a user message */\n\tprivate getUserMessageText(message: Message): string {\n\t\tif (message.role !== \"user\") return \"\";\n\t\tconst textBlocks =\n\t\t\ttypeof message.content === \"string\"\n\t\t\t\t? [{ type: \"text\", text: message.content }]\n\t\t\t\t: message.content.filter((c: { type: string }) => c.type === \"text\");\n\t\treturn textBlocks.map((c) => (c as { text: string }).text).join(\"\");\n\t}\n\n\t/**\n\t * Show a status message in the chat.\n\t *\n\t * If multiple status messages are emitted back-to-back (without anything else being added to the chat),\n\t * we update the previous status line instead of appending new ones to avoid log spam.\n\t */\n\tprivate showStatus(message: string): void {\n\t\tconst children = this.chatContainer.children;\n\t\tconst last = children.length > 0 ? children[children.length - 1] : undefined;\n\t\tconst secondLast = children.length > 1 ? children[children.length - 2] : undefined;\n\n\t\tif (last && secondLast && last === this.lastStatusText && secondLast === this.lastStatusSpacer) {\n\t\t\tthis.lastStatusText.setText(theme.fg(\"dim\", message));\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\tconst spacer = new Spacer(1);\n\t\tconst text = new Text(theme.fg(\"dim\", message), 1, 0);\n\t\tthis.chatContainer.addChild(spacer);\n\t\tthis.chatContainer.addChild(text);\n\t\tthis.lastStatusSpacer = spacer;\n\t\tthis.lastStatusText = text;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate addCustomEntryToChat(entry: Extract): void {\n\t\tconst renderer = this.session.extensionRunner.getEntryRenderer(entry.customType);\n\t\tif (!renderer) {\n\t\t\treturn;\n\t\t}\n\t\tconst component = new CustomEntryComponent(entry, renderer);\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tif (!component.hasContent()) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.streamingComponent) {\n\t\t\tconst streamingIndex = this.chatContainer.children.indexOf(this.streamingComponent);\n\t\t\tif (streamingIndex >= 0) {\n\t\t\t\tthis.chatContainer.children.splice(streamingIndex, 0, component);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.chatContainer.addChild(component);\n\t}\n\n\tprivate addMessageToChat(message: AgentMessage, options?: { populateHistory?: boolean }): void {\n\t\tswitch (message.role) {\n\t\t\tcase \"bashExecution\": {\n\t\t\t\tconst component = new BashExecutionComponent(message.command, this.ui, message.excludeFromContext);\n\t\t\t\tif (message.output) {\n\t\t\t\t\tcomponent.appendOutput(message.output);\n\t\t\t\t}\n\t\t\t\tcomponent.setComplete(\n\t\t\t\t\tmessage.exitCode,\n\t\t\t\t\tmessage.cancelled,\n\t\t\t\t\tmessage.truncated ? ({ truncated: true } as TruncationResult) : undefined,\n\t\t\t\t\tmessage.fullOutputPath,\n\t\t\t\t);\n\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"custom\": {\n\t\t\t\tif (message.display) {\n\t\t\t\t\tconst renderer = this.session.extensionRunner.getMessageRenderer(message.customType);\n\t\t\t\t\tconst component = new CustomMessageComponent(\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\trenderer,\n\t\t\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\t\t\tthis.outputPad,\n\t\t\t\t\t);\n\t\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"compactionSummary\": {\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tconst component = new CompactionSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());\n\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"branchSummary\": {\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tconst component = new BranchSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());\n\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"user\": {\n\t\t\t\tconst textContent = this.getUserMessageText(message);\n\t\t\t\tif (textContent) {\n\t\t\t\t\tif (this.chatContainer.children.length > 0) {\n\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t}\n\t\t\t\t\tconst skillBlock = parseSkillBlock(textContent);\n\t\t\t\t\tif (skillBlock) {\n\t\t\t\t\t\t// Render skill block (collapsible)\n\t\t\t\t\t\tconst component = new SkillInvocationMessageComponent(\n\t\t\t\t\t\t\tskillBlock,\n\t\t\t\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\t\tthis.chatContainer.addChild(component);\n\t\t\t\t\t\t// Render user message separately if present\n\t\t\t\t\t\tif (skillBlock.userMessage) {\n\t\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\t\tconst userComponent = new UserMessageComponent(\n\t\t\t\t\t\t\t\tskillBlock.userMessage,\n\t\t\t\t\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\t\t\t\t\tthis.outputPad,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tthis.chatContainer.addChild(userComponent);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst userComponent = new UserMessageComponent(\n\t\t\t\t\t\t\ttextContent,\n\t\t\t\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\t\t\t\tthis.outputPad,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.chatContainer.addChild(userComponent);\n\t\t\t\t\t}\n\t\t\t\t\tif (options?.populateHistory) {\n\t\t\t\t\t\tthis.editor.addToHistory?.(textContent);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"assistant\": {\n\t\t\t\tconst assistantComponent = new AssistantMessageComponent(\n\t\t\t\t\tmessage,\n\t\t\t\t\tthis.hideThinkingBlock,\n\t\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\t\tthis.hiddenThinkingLabel,\n\t\t\t\t\tthis.outputPad,\n\t\t\t\t);\n\t\t\t\tthis.chatContainer.addChild(assistantComponent);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"toolResult\": {\n\t\t\t\t// Tool results are rendered inline with tool calls, handled separately\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustive: never = message;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate renderSessionItems(\n\t\titems: readonly RenderSessionItem[],\n\t\toptions: { updateFooter?: boolean; populateHistory?: boolean } = {},\n\t): void {\n\t\tthis.pendingTools.clear();\n\t\tconst renderedPendingTools = new Map();\n\t\t// Cache-miss notices are not persisted; re-derive them from the full entry\n\t\t// list and re-inject them after the assistant messages that paid for them.\n\t\tconst cacheMisses = this.settingsManager.getShowCacheMissNotices()\n\t\t\t? collectCacheMisses(this.sessionManager.getEntries(), this.session.modelRuntime)\n\t\t\t: new Map();\n\n\t\tif (options.updateFooter) {\n\t\t\tthis.footer.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t}\n\n\t\tfor (const item of items) {\n\t\t\tif (isCustomSessionEntry(item)) {\n\t\t\t\tthis.addCustomEntryToChat(item);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst message = item;\n\t\t\t// Assistant messages need special handling for tool calls\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tthis.addMessageToChat(message);\n\t\t\t\t// Render tool call components\n\t\t\t\tfor (const content of message.content) {\n\t\t\t\t\tif (content.type === \"toolCall\") {\n\t\t\t\t\t\tconst component = new ToolExecutionComponent(\n\t\t\t\t\t\t\tcontent.name,\n\t\t\t\t\t\t\tcontent.id,\n\t\t\t\t\t\t\tcontent.arguments,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\t\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tthis.getRegisteredToolDefinition(content.name),\n\t\t\t\t\t\t\tthis.ui,\n\t\t\t\t\t\t\tthis.sessionManager.getCwd(),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\t\t\t\t\tthis.chatContainer.addChild(component);\n\n\t\t\t\t\t\tif (message.stopReason === \"aborted\" || message.stopReason === \"error\") {\n\t\t\t\t\t\t\tlet errorMessage: string;\n\t\t\t\t\t\t\tif (message.stopReason === \"aborted\") {\n\t\t\t\t\t\t\t\tconst retryAttempt = this.session.retryAttempt;\n\t\t\t\t\t\t\t\terrorMessage =\n\t\t\t\t\t\t\t\t\tretryAttempt > 0\n\t\t\t\t\t\t\t\t\t\t? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? \"s\" : \"\"}`\n\t\t\t\t\t\t\t\t\t\t: \"Operation aborted\";\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\terrorMessage = message.errorMessage || \"Error\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcomponent.updateResult({ content: [{ type: \"text\", text: errorMessage }], isError: true });\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\trenderedPendingTools.set(content.id, component);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (message.stopReason !== \"aborted\" && message.stopReason !== \"error\") {\n\t\t\t\t\tconst miss = cacheMisses.get(message);\n\t\t\t\t\tif (miss) this.addCacheMissNotice(miss);\n\t\t\t\t}\n\t\t\t} else if (message.role === \"toolResult\") {\n\t\t\t\t// Match tool results to pending tool components\n\t\t\t\tconst component = renderedPendingTools.get(message.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\tcomponent.updateResult(message);\n\t\t\t\t\trenderedPendingTools.delete(message.toolCallId);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// All other messages use standard rendering\n\t\t\t\tthis.addMessageToChat(message, options);\n\t\t\t}\n\t\t}\n\n\t\tfor (const [toolCallId, component] of renderedPendingTools) {\n\t\t\tthis.pendingTools.set(toolCallId, component);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Render session entries to chat. Used for initial load and rebuild after compaction.\n\t * @param entries Compaction-aware session entries to render\n\t * @param options.updateFooter Update footer state\n\t * @param options.populateHistory Add user messages to editor history\n\t */\n\tprivate renderSessionEntries(\n\t\tentries: SessionEntry[],\n\t\toptions: { updateFooter?: boolean; populateHistory?: boolean } = {},\n\t): void {\n\t\tconst items = entries.flatMap((entry): RenderSessionItem[] => {\n\t\t\tif (entry.type === \"custom\") {\n\t\t\t\treturn [entry];\n\t\t\t}\n\t\t\treturn sessionEntryToContextMessages(entry);\n\t\t});\n\t\tthis.renderSessionItems(items, options);\n\t}\n\n\t/**\n\t * Show a transcript notice when a completed assistant message paid for a\n\t * significant cache miss. Only states observable facts: the miss itself,\n\t * a model switch, or an idle gap past the cache TTL.\n\t */\n\tprivate maybeShowCacheMissNotice(message: AssistantMessage): void {\n\t\tif (!this.settingsManager.getShowCacheMissNotices()) return;\n\n\t\t// Entries don't contain `message` yet: message_end fires before persistence.\n\t\tconst miss = detectCacheMiss(this.sessionManager.getEntries(), message, this.session.modelRuntime);\n\t\tif (miss) this.addCacheMissNotice(miss);\n\t}\n\n\tprivate addCacheMissNotice(miss: CacheMiss): void {\n\t\tif (miss.missedTokens < 20_000 && miss.missedCost < 0.1) return;\n\n\t\tconst cost = miss.missedCost >= 0.01 ? ` (~$${miss.missedCost.toFixed(2)})` : \"\";\n\t\tconst reBilled = `${formatTokens(miss.missedTokens)} tokens re-billed${cost}`;\n\t\tlet label = \"Cache miss\";\n\t\tif (miss.modelChanged) {\n\t\t\tlabel = \"Cache miss after model switch\";\n\t\t} else if (miss.idleMs >= CACHE_TTL_MS) {\n\t\t\tlabel = `Cache miss after ${Math.round(miss.idleMs / 60_000)}m idle`;\n\t\t}\n\t\tconst text = theme.fg(\"warning\", `${label}: ${reBilled}`);\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(text, 1, 0));\n\t}\n\n\trenderInitialMessages(): void {\n\t\tconst entries = this.sessionManager.buildContextEntries();\n\t\tthis.renderSessionEntries(entries, {\n\t\t\tupdateFooter: true,\n\t\t\tpopulateHistory: true,\n\t\t});\n\t\tthis.renderProjectTrustWarningIfNeeded();\n\n\t\t// Show compaction info if session was compacted\n\t\tconst allEntries = this.sessionManager.getEntries();\n\t\tconst compactionCount = allEntries.filter((e) => e.type === \"compaction\").length;\n\t\tif (compactionCount > 0) {\n\t\t\tconst times = compactionCount === 1 ? \"1 time\" : `${compactionCount} times`;\n\t\t\tthis.showStatus(`Session compacted ${times}`);\n\t\t}\n\t}\n\n\tprivate renderProjectTrustWarningIfNeeded(): void {\n\t\tif (this.settingsManager.isProjectTrusted() || !hasTrustRequiringProjectResources(this.sessionManager.getCwd())) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.chatContainer.children.length > 0) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.fg(\n\t\t\t\t\t\"warning\",\n\t\t\t\t\t`This project is not trusted. Project ${CONFIG_DIR_NAME} resources and packages are ignored. Use /trust to save a trust decision, then restart pi.`,\n\t\t\t\t),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t}\n\n\tasync getUserInput(): Promise {\n\t\tconst queuedInput = this.pendingUserInputs.shift();\n\t\tif (queuedInput !== undefined) {\n\t\t\treturn queuedInput;\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.onInputCallback = (text: string) => {\n\t\t\t\tthis.onInputCallback = undefined;\n\t\t\t\tresolve(text);\n\t\t\t};\n\t\t});\n\t}\n\n\tprivate rebuildChatFromMessages(): void {\n\t\tthis.chatContainer.clear();\n\t\tthis.renderSessionEntries(this.sessionManager.buildContextEntries());\n\t}\n\n\t// =========================================================================\n\t// Key handlers\n\t// =========================================================================\n\n\tprivate handleCtrlC(): void {\n\t\tconst now = Date.now();\n\t\tif (now - this.lastSigintTime < 500) {\n\t\t\tvoid this.shutdown();\n\t\t} else {\n\t\t\tthis.clearEditor();\n\t\t\tthis.lastSigintTime = now;\n\t\t}\n\t}\n\n\tprivate handleCtrlD(): void {\n\t\t// Only called when editor is empty (enforced by CustomEditor)\n\t\tvoid this.shutdown();\n\t}\n\n\t/**\n\t * Gracefully shutdown the agent.\n\t * Stops the TUI before emitting shutdown events so extension UI cleanup cannot\n\t * repaint the final frame while the process is exiting.\n\t */\n\tprivate isShuttingDown = false;\n\n\tprivate async shutdown(options?: { fromSignal?: boolean }): Promise {\n\t\tif (this.isShuttingDown) return;\n\t\tthis.isShuttingDown = true;\n\t\t// Keep signal handlers registered until terminal cleanup has completed.\n\t\t// `signal-exit` checks the listener list during the same SIGTERM/SIGHUP\n\t\t// dispatch and re-sends the signal if only its own listeners remain.\n\n\t\tif (options?.fromSignal) {\n\t\t\t// Signal-triggered shutdown (SIGTERM/SIGHUP). Emit extension cleanup\n\t\t\t// (session_shutdown) BEFORE touching the terminal. Extension teardown\n\t\t\t// such as removing sockets does not write to the tty, so it must not be\n\t\t\t// skipped if a later terminal-restore write fails on a dead or stalled\n\t\t\t// terminal. If the terminal is gone, the restore writes below emit EIO,\n\t\t\t// which the stdout/stderr error handler turns into emergencyTerminalExit;\n\t\t\t// the render loop is already idle, so this cannot hot-spin (see #4144).\n\t\t\tawait this.runtimeHost.dispose();\n\t\t\tthis.themeController.disableAutoSync();\n\t\t\tawait this.ui.terminal.drainInput(1000);\n\t\t\tthis.stop();\n\t\t\tprocess.exit(0);\n\t\t}\n\n\t\t// Interactive quit (Ctrl+D, Ctrl+C, /quit, extension shutdown()). Stop the\n\t\t// TUI before emitting shutdown events so extension UI cleanup cannot repaint\n\t\t// the final frame while the process is exiting.\n\t\t// Drain any in-flight Kitty key release events before stopping.\n\t\t// This prevents escape sequences from leaking to the parent shell over slow SSH.\n\t\tthis.themeController.disableAutoSync();\n\t\tawait this.ui.terminal.drainInput(1000);\n\n\t\tthis.stop();\n\t\tawait this.runtimeHost.dispose();\n\n\t\tconst resumeCommand = formatResumeCommand(this.sessionManager);\n\t\tif (resumeCommand) {\n\t\t\tprocess.stdout.write(`${chalk.dim(\"To resume this session:\")} ${resumeCommand}\\n`);\n\t\t}\n\n\t\tprocess.exit(0);\n\t}\n\n\tprivate emergencyTerminalExit(): never {\n\t\tthis.isShuttingDown = true;\n\t\tthis.unregisterSignalHandlers();\n\t\tkillTrackedDetachedChildren();\n\t\t// The terminal is gone. Do not run normal shutdown because TUI and\n\t\t// extension cleanup can write restore sequences and re-trigger EIO.\n\t\tprocess.exit(129);\n\t}\n\n\t/**\n\t * Last-resort handler for uncaught exceptions. The TUI puts stdin into raw\n\t * mode and hides the cursor; without this handler, an uncaught throw from\n\t * anywhere (e.g. an extension's async `ChildProcess.on(\"exit\")` callback)\n\t * tears down the process while leaving the terminal in raw mode with no\n\t * cursor, requiring `stty sane && reset` to recover.\n\t *\n\t * Unlike emergencyTerminalExit, the terminal is still alive here, so we\n\t * call ui.stop() to restore cooked mode, the cursor, and disable bracketed\n\t * paste / Kitty / modifyOtherKeys sequences.\n\t */\n\tprivate uncaughtCrash(error: Error): never {\n\t\tif (this.isShuttingDown) {\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tthis.isShuttingDown = true;\n\t\ttry {\n\t\t\tthis.unregisterSignalHandlers();\n\t\t} catch {}\n\t\ttry {\n\t\t\tkillTrackedDetachedChildren();\n\t\t} catch {}\n\t\ttry {\n\t\t\tthis.ui.stop();\n\t\t} catch {}\n\t\tconsole.error(\"pi exiting due to uncaughtException:\");\n\t\tconsole.error(error);\n\t\tprocess.exit(1);\n\t}\n\n\t/**\n\t * Check if shutdown was requested and perform shutdown if so.\n\t */\n\tprivate async checkShutdownRequested(): Promise {\n\t\tif (!this.shutdownRequested) return;\n\t\tawait this.shutdown();\n\t}\n\n\tprivate registerSignalHandlers(): void {\n\t\tthis.unregisterSignalHandlers();\n\n\t\tconst signals: NodeJS.Signals[] = [\"SIGTERM\"];\n\t\tif (process.platform !== \"win32\") {\n\t\t\tsignals.push(\"SIGHUP\");\n\t\t}\n\n\t\tfor (const signal of signals) {\n\t\t\tconst handler = () => {\n\t\t\t\t// SIGHUP no longer hard-exits: graceful shutdown emits session_shutdown\n\t\t\t\t// first, then attempts terminal restore. A genuinely dead terminal\n\t\t\t\t// surfaces as an EIO on the restore writes, which the stdout/stderr\n\t\t\t\t// error handler converts into emergencyTerminalExit (see #4144, #5080).\n\t\t\t\tkillTrackedDetachedChildren();\n\t\t\t\tvoid this.shutdown({ fromSignal: true });\n\t\t\t};\n\t\t\tprocess.prependListener(signal, handler);\n\t\t\tthis.signalCleanupHandlers.push(() => process.off(signal, handler));\n\t\t}\n\n\t\tconst terminalErrorHandler = (error: Error) => {\n\t\t\tif (isDeadTerminalError(error)) {\n\t\t\t\tthis.emergencyTerminalExit();\n\t\t\t}\n\t\t\tthrow error;\n\t\t};\n\t\tprocess.stdout.on(\"error\", terminalErrorHandler);\n\t\tprocess.stderr.on(\"error\", terminalErrorHandler);\n\t\tthis.signalCleanupHandlers.push(() => process.stdout.off(\"error\", terminalErrorHandler));\n\t\tthis.signalCleanupHandlers.push(() => process.stderr.off(\"error\", terminalErrorHandler));\n\n\t\t// Restore the terminal before the process dies on any uncaught throw.\n\t\t// Without this, an unhandled exception from extension code (or anywhere\n\t\t// in pi) leaves the terminal in raw mode with no cursor.\n\t\tconst uncaughtExceptionHandler = (error: Error) => this.uncaughtCrash(error);\n\t\tprocess.prependListener(\"uncaughtException\", uncaughtExceptionHandler);\n\t\tthis.signalCleanupHandlers.push(() => process.off(\"uncaughtException\", uncaughtExceptionHandler));\n\t}\n\n\tprivate unregisterSignalHandlers(): void {\n\t\tfor (const cleanup of this.signalCleanupHandlers) {\n\t\t\tcleanup();\n\t\t}\n\t\tthis.signalCleanupHandlers = [];\n\t}\n\n\tprivate handleCtrlZ(): void {\n\t\tif (process.platform === \"win32\") {\n\t\t\tthis.showStatus(\"Suspend to background is not supported on Windows\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Keep the event loop alive while suspended. Without this, stopping the TUI\n\t\t// can leave Node with no ref'ed handles, causing the process to exit on fg\n\t\t// before the SIGCONT handler gets a chance to restore the terminal.\n\t\tconst suspendKeepAlive = setInterval(() => {}, 2 ** 30);\n\n\t\t// Ignore SIGINT while suspended so Ctrl+C in the terminal does not\n\t\t// kill the backgrounded process. The handler is removed on resume.\n\t\tconst ignoreSigint = () => {};\n\t\tprocess.on(\"SIGINT\", ignoreSigint);\n\n\t\t// Set up handler to restore TUI when resumed\n\t\tprocess.once(\"SIGCONT\", () => {\n\t\t\tclearInterval(suspendKeepAlive);\n\t\t\tprocess.removeListener(\"SIGINT\", ignoreSigint);\n\t\t\tthis.ui.start();\n\t\t\tthis.ui.requestRender(true);\n\t\t});\n\n\t\ttry {\n\t\t\t// Stop the TUI (restore terminal to normal mode)\n\t\t\tthis.ui.stop();\n\n\t\t\t// Send SIGTSTP to process group (pid=0 means all processes in group)\n\t\t\tprocess.kill(0, \"SIGTSTP\");\n\t\t} catch (error) {\n\t\t\tclearInterval(suspendKeepAlive);\n\t\t\tprocess.removeListener(\"SIGINT\", ignoreSigint);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async handleFollowUp(): Promise {\n\t\tconst text = (this.editor.getExpandedText?.() ?? this.editor.getText()).trim();\n\t\tif (!text) return;\n\n\t\t// Queue input during compaction (extension commands execute immediately)\n\t\tif (this.session.isCompacting) {\n\t\t\tif (this.isExtensionCommand(text)) {\n\t\t\t\tthis.editor.addToHistory?.(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.session.prompt(text);\n\t\t\t} else {\n\t\t\t\tthis.queueCompactionMessage(text, \"followUp\");\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Alt+Enter queues a follow-up message (waits until agent finishes)\n\t\t// This handles extension commands (execute immediately), prompt template expansion, and queueing\n\t\tif (this.session.isStreaming) {\n\t\t\tthis.editor.addToHistory?.(text);\n\t\t\tthis.editor.setText(\"\");\n\t\t\tawait this.session.prompt(text, { streamingBehavior: \"followUp\" });\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tthis.ui.requestRender();\n\t\t}\n\t\t// If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)\n\t\telse if (this.editor.onSubmit) {\n\t\t\tthis.editor.setText(\"\");\n\t\t\tthis.editor.onSubmit(text);\n\t\t}\n\t}\n\n\tprivate handleDequeue(): void {\n\t\tconst restored = this.restoreQueuedMessagesToEditor();\n\t\tif (restored === 0) {\n\t\t\tthis.showStatus(\"No queued messages to restore\");\n\t\t} else {\n\t\t\tthis.showStatus(`Restored ${restored} queued message${restored > 1 ? \"s\" : \"\"} to editor`);\n\t\t}\n\t}\n\n\tprivate updateEditorBorderColor(): void {\n\t\tif (this.isBashMode) {\n\t\t\tthis.editor.borderColor = theme.getBashModeBorderColor();\n\t\t} else {\n\t\t\tconst level = this.session.thinkingLevel || \"off\";\n\t\t\tthis.editor.borderColor = theme.getThinkingBorderColor(level);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate cycleThinkingLevel(): void {\n\t\tconst newLevel = this.session.cycleThinkingLevel();\n\t\tif (newLevel === undefined) {\n\t\t\tthis.showStatus(\"Current model does not support thinking\");\n\t\t} else {\n\t\t\tthis.footer.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.showStatus(`Thinking level: ${newLevel}`);\n\t\t}\n\t}\n\n\tprivate async cycleModel(direction: \"forward\" | \"backward\"): Promise {\n\t\ttry {\n\t\t\tconst result = await this.session.cycleModel(direction);\n\t\t\tif (result === undefined) {\n\t\t\t\tconst msg = this.session.scopedModels.length > 0 ? \"Only one model in scope\" : \"Only one model available\";\n\t\t\t\tthis.showStatus(msg);\n\t\t\t} else {\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tconst thinkingStr =\n\t\t\t\t\tresult.model.reasoning && result.thinkingLevel !== \"off\" ? ` (thinking: ${result.thinkingLevel})` : \"\";\n\t\t\t\tthis.showStatus(`Switched to ${result.model.name || result.model.id}${thinkingStr}`);\n\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(result.model);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate toggleToolOutputExpansion(): void {\n\t\tthis.setToolsExpanded(!this.toolOutputExpanded);\n\t}\n\n\tprivate setToolsExpanded(expanded: boolean): void {\n\t\tthis.toolOutputExpanded = expanded;\n\t\tconst activeHeader = this.customHeader ?? this.builtInHeader;\n\t\tif (isExpandable(activeHeader)) {\n\t\t\tactiveHeader.setExpanded(expanded);\n\t\t}\n\t\tfor (const container of [this.loadedResourcesContainer, this.chatContainer]) {\n\t\t\tfor (const child of container.children) {\n\t\t\t\tif (isExpandable(child)) {\n\t\t\t\t\tchild.setExpanded(expanded);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.showStatus(`Tool output: ${expanded ? \"expanded\" : \"collapsed\"}`);\n\t}\n\n\tprivate toggleThinkingBlockVisibility(): void {\n\t\tthis.hideThinkingBlock = !this.hideThinkingBlock;\n\t\tthis.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);\n\n\t\t// Rebuild chat from session messages\n\t\tthis.chatContainer.clear();\n\t\tthis.rebuildChatFromMessages();\n\n\t\t// If streaming, re-add the streaming component with updated visibility and re-render\n\t\tif (this.streamingComponent && this.streamingMessage) {\n\t\t\tthis.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock);\n\t\t\tthis.streamingComponent.updateContent(this.streamingMessage);\n\t\t\tthis.chatContainer.addChild(this.streamingComponent);\n\t\t}\n\n\t\tthis.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? \"hidden\" : \"visible\"}`);\n\t}\n\n\tprivate async handleOpenExternalEditor(): Promise {\n\t\tconst editorCmd = this.settingsManager.getExternalEditorCommand();\n\t\tconst content = this.editor.getExpandedText?.() ?? this.editor.getText();\n\t\tthis.ui.stop();\n\t\ttry {\n\t\t\tconst result = await editInExternalEditor({\n\t\t\t\tcommand: editorCmd,\n\t\t\t\tcontent,\n\t\t\t});\n\t\t\tif (result.status === \"complete\") {\n\t\t\t\tthis.editor.setText(result.content);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.ui.start();\n\t\t\tthis.ui.requestRender(true);\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// UI helpers\n\t// =========================================================================\n\n\tclearEditor(): void {\n\t\tthis.editor.setText(\"\");\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowError(errorMessage: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"error\", `Error: ${errorMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowWarning(warningMessage: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"warning\", `Warning: ${warningMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowNewVersionNotification(release: LatestPiRelease): void {\n\t\tconst action = theme.fg(\"accent\", `${APP_NAME} update`);\n\t\tconst updateInstruction = theme.fg(\"muted\", `New version ${release.version} is available. Run `) + action;\n\t\tconst changelogUrl = \"https://pi.dev/changelog\";\n\t\tconst changelogLink = getCapabilities().hyperlinks\n\t\t\t? hyperlink(theme.fg(\"accent\", changelogUrl), changelogUrl)\n\t\t\t: theme.fg(\"accent\", changelogUrl);\n\t\tconst changelogLine = theme.fg(\"muted\", \"Changelog: \") + changelogLink;\n\t\tconst note = release.note?.trim();\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(`${theme.bold(theme.fg(\"warning\", \"Update Available\"))}\\n${updateInstruction}`, 1, 0),\n\t\t);\n\t\tif (note) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(\n\t\t\t\tnew Markdown(note, 1, 0, this.getMarkdownThemeWithSettings(), {\n\t\t\t\t\tcolor: (text) => theme.fg(\"muted\", text),\n\t\t\t\t}),\n\t\t\t);\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new Text(changelogLine, 1, 0));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowPackageUpdateNotification(packages: string[]): void {\n\t\tconst action = theme.fg(\"accent\", `${APP_NAME} update --extensions`);\n\t\tconst updateInstruction = theme.fg(\"muted\", \"Package updates are available. Run \") + action;\n\t\tconst packageLines = packages.map((pkg) => `- ${pkg}`).join(\"\\n\");\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(\n\t\t\t\t`${theme.bold(theme.fg(\"warning\", \"Package Updates Available\"))}\\n${updateInstruction}\\n${theme.fg(\"muted\", \"Packages:\")}\\n${packageLines}`,\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Get all queued messages (read-only).\n\t * Combines session queue and compaction queue.\n\t */\n\tprivate getAllQueuedMessages(): { steering: string[]; followUp: string[] } {\n\t\treturn {\n\t\t\tsteering: [\n\t\t\t\t...this.session.getSteeringMessages(),\n\t\t\t\t...this.compactionQueuedMessages.filter((msg) => msg.mode === \"steer\").map((msg) => msg.text),\n\t\t\t],\n\t\t\tfollowUp: [\n\t\t\t\t...this.session.getFollowUpMessages(),\n\t\t\t\t...this.compactionQueuedMessages.filter((msg) => msg.mode === \"followUp\").map((msg) => msg.text),\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Clear all queued messages and return their contents.\n\t * Clears both session queue and compaction queue.\n\t */\n\tprivate clearAllQueues(): { steering: string[]; followUp: string[] } {\n\t\tconst { steering, followUp } = this.session.clearQueue();\n\t\tconst compactionSteering = this.compactionQueuedMessages\n\t\t\t.filter((msg) => msg.mode === \"steer\")\n\t\t\t.map((msg) => msg.text);\n\t\tconst compactionFollowUp = this.compactionQueuedMessages\n\t\t\t.filter((msg) => msg.mode === \"followUp\")\n\t\t\t.map((msg) => msg.text);\n\t\tthis.compactionQueuedMessages = [];\n\t\treturn {\n\t\t\tsteering: [...steering, ...compactionSteering],\n\t\t\tfollowUp: [...followUp, ...compactionFollowUp],\n\t\t};\n\t}\n\n\tprivate updatePendingMessagesDisplay(): void {\n\t\tthis.pendingMessagesContainer.clear();\n\t\tconst { steering: steeringMessages, followUp: followUpMessages } = this.getAllQueuedMessages();\n\t\tif (steeringMessages.length > 0 || followUpMessages.length > 0) {\n\t\t\tthis.pendingMessagesContainer.addChild(new Spacer(1));\n\t\t\tfor (const message of steeringMessages) {\n\t\t\t\tconst text = theme.fg(\"dim\", `Steering: ${message}`);\n\t\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));\n\t\t\t}\n\t\t\tfor (const message of followUpMessages) {\n\t\t\t\tconst text = theme.fg(\"dim\", `Follow-up: ${message}`);\n\t\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));\n\t\t\t}\n\t\t\tconst dequeueHint = this.getAppKeyDisplay(\"app.message.dequeue\");\n\t\t\tconst hintText = theme.fg(\"dim\", `↳ ${dequeueHint} to edit all queued messages`);\n\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(hintText, 1, 0));\n\t\t}\n\t}\n\n\tprivate restoreQueuedMessagesToEditor(options?: { abort?: boolean; currentText?: string }): number {\n\t\tconst { steering, followUp } = this.clearAllQueues();\n\t\tconst allQueued = [...steering, ...followUp];\n\t\tif (allQueued.length === 0) {\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tif (options?.abort) {\n\t\t\t\tthis.agent.abort();\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\tconst queuedText = allQueued.join(\"\\n\\n\");\n\t\tconst currentText = options?.currentText ?? this.editor.getText();\n\t\tconst combinedText = [queuedText, currentText].filter((t) => t.trim()).join(\"\\n\\n\");\n\t\tthis.editor.setText(combinedText);\n\t\tthis.updatePendingMessagesDisplay();\n\t\tif (options?.abort) {\n\t\t\tthis.agent.abort();\n\t\t}\n\t\treturn allQueued.length;\n\t}\n\n\tprivate queueCompactionMessage(text: string, mode: \"steer\" | \"followUp\"): void {\n\t\tthis.compactionQueuedMessages.push({ text, mode });\n\t\tthis.editor.addToHistory?.(text);\n\t\tthis.editor.setText(\"\");\n\t\tthis.updatePendingMessagesDisplay();\n\t\tthis.showStatus(\"Queued message for after compaction\");\n\t}\n\n\tprivate isExtensionCommand(text: string): boolean {\n\t\tif (!text.startsWith(\"/\")) return false;\n\n\t\tconst extensionRunner = this.session.extensionRunner;\n\n\t\tconst spaceIndex = text.indexOf(\" \");\n\t\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\t\treturn !!extensionRunner.getCommand(commandName);\n\t}\n\n\tprivate async flushCompactionQueue(options?: { willRetry?: boolean }): Promise {\n\t\tif (this.compactionQueuedMessages.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst queuedMessages = [...this.compactionQueuedMessages];\n\t\tthis.compactionQueuedMessages = [];\n\t\tthis.updatePendingMessagesDisplay();\n\n\t\tconst restoreQueue = (error: unknown) => {\n\t\t\tthis.session.clearQueue();\n\t\t\tthis.compactionQueuedMessages = queuedMessages;\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tthis.showError(\n\t\t\t\t`Failed to send queued message${queuedMessages.length > 1 ? \"s\" : \"\"}: ${\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t}`,\n\t\t\t);\n\t\t};\n\n\t\ttry {\n\t\t\tif (options?.willRetry) {\n\t\t\t\t// When retry is pending, queue messages for the retry turn\n\t\t\t\tfor (const message of queuedMessages) {\n\t\t\t\t\tif (this.isExtensionCommand(message.text)) {\n\t\t\t\t\t\tawait this.session.prompt(message.text);\n\t\t\t\t\t} else if (message.mode === \"followUp\") {\n\t\t\t\t\t\tawait this.session.followUp(message.text);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.session.steer(message.text);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Find first non-extension-command message to use as prompt\n\t\t\tconst firstPromptIndex = queuedMessages.findIndex((message) => !this.isExtensionCommand(message.text));\n\t\t\tif (firstPromptIndex === -1) {\n\t\t\t\t// All extension commands - execute them all\n\t\t\t\tfor (const message of queuedMessages) {\n\t\t\t\t\tawait this.session.prompt(message.text);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Execute any extension commands before the first prompt\n\t\t\tconst preCommands = queuedMessages.slice(0, firstPromptIndex);\n\t\t\tconst firstPrompt = queuedMessages[firstPromptIndex];\n\t\t\tconst rest = queuedMessages.slice(firstPromptIndex + 1);\n\n\t\t\tfor (const message of preCommands) {\n\t\t\t\tawait this.session.prompt(message.text);\n\t\t\t}\n\n\t\t\t// Start a prompt when idle, or queue it into a run still finishing compaction.\n\t\t\tconst promptPromise = this.session\n\t\t\t\t.prompt(firstPrompt.text, { streamingBehavior: firstPrompt.mode })\n\t\t\t\t.catch((error) => {\n\t\t\t\t\trestoreQueue(error);\n\t\t\t\t});\n\n\t\t\t// Queue remaining messages\n\t\t\tfor (const message of rest) {\n\t\t\t\tif (this.isExtensionCommand(message.text)) {\n\t\t\t\t\tawait this.session.prompt(message.text);\n\t\t\t\t} else if (message.mode === \"followUp\") {\n\t\t\t\t\tawait this.session.followUp(message.text);\n\t\t\t\t} else {\n\t\t\t\t\tawait this.session.steer(message.text);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tvoid promptPromise;\n\t\t} catch (error) {\n\t\t\trestoreQueue(error);\n\t\t}\n\t}\n\n\t/** Move pending bash components from pending area to chat */\n\tprivate flushPendingBashComponents(): void {\n\t\tfor (const component of this.pendingBashComponents) {\n\t\t\tthis.pendingMessagesContainer.removeChild(component);\n\t\t\tthis.chatContainer.addChild(component);\n\t\t}\n\t\tthis.pendingBashComponents = [];\n\t}\n\n\t// =========================================================================\n\t// Selectors\n\t// =========================================================================\n\n\t/**\n\t * Shows a selector component in place of the editor.\n\t * @param create Factory that receives a `done` callback and returns the component and focus target\n\t */\n\tprivate showSelector(create: (done: () => void) => { component: Component; focus: Component }): void {\n\t\tconst done = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t};\n\t\tconst { component, focus } = create(done);\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(component);\n\t\tthis.ui.setFocus(focus);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate showSettingsSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new SettingsSelectorComponent(\n\t\t\t\t{\n\t\t\t\t\tautoCompact: this.session.autoCompactionEnabled,\n\t\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t\t\tautoResizeImages: this.settingsManager.getImageAutoResize(),\n\t\t\t\t\tblockImages: this.settingsManager.getBlockImages(),\n\t\t\t\t\tenableSkillCommands: this.settingsManager.getEnableSkillCommands(),\n\t\t\t\t\tsteeringMode: this.session.steeringMode,\n\t\t\t\t\tfollowUpMode: this.session.followUpMode,\n\t\t\t\t\ttransport: this.settingsManager.getTransport(),\n\t\t\t\t\thttpIdleTimeoutMs: this.settingsManager.getHttpIdleTimeoutMs(),\n\t\t\t\t\tthinkingLevel: this.session.thinkingLevel,\n\t\t\t\t\tavailableThinkingLevels: this.session.getAvailableThinkingLevels(),\n\t\t\t\t\tcurrentTheme: this.settingsManager.getThemeSetting() || \"dark\",\n\t\t\t\t\tterminalTheme: this.themeController.getTerminalTheme(),\n\t\t\t\t\tavailableThemes: getAvailableThemes(),\n\t\t\t\t\thideThinkingBlock: this.hideThinkingBlock,\n\t\t\t\t\tcollapseChangelog: this.settingsManager.getCollapseChangelog(),\n\t\t\t\t\tenableInstallTelemetry: this.settingsManager.getEnableInstallTelemetry(),\n\t\t\t\t\tdoubleEscapeAction: this.settingsManager.getDoubleEscapeAction(),\n\t\t\t\t\ttreeFilterMode: this.settingsManager.getTreeFilterMode(),\n\t\t\t\t\tshowHardwareCursor: this.settingsManager.getShowHardwareCursor(),\n\t\t\t\t\tshowCacheMissNotices: this.settingsManager.getShowCacheMissNotices(),\n\t\t\t\t\tdefaultProjectTrust: this.settingsManager.getDefaultProjectTrust(),\n\t\t\t\t\teditorPaddingX: this.settingsManager.getEditorPaddingX(),\n\t\t\t\t\toutputPad: this.settingsManager.getOutputPad(),\n\t\t\t\t\tautocompleteMaxVisible: this.settingsManager.getAutocompleteMaxVisible(),\n\t\t\t\t\tquietStartup: this.settingsManager.getQuietStartup(),\n\t\t\t\t\tclearOnShrink: this.settingsManager.getClearOnShrink(),\n\t\t\t\t\tshowTerminalProgress: this.settingsManager.getShowTerminalProgress(),\n\t\t\t\t\twarnings: this.settingsManager.getWarnings(),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tonAutoCompactChange: (enabled) => {\n\t\t\t\t\t\tthis.session.setAutoCompactionEnabled(enabled);\n\t\t\t\t\t\tthis.footer.setAutoCompactEnabled(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonShowImagesChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setShowImages(enabled);\n\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\tif (child instanceof ToolExecutionComponent) {\n\t\t\t\t\t\t\t\tchild.setShowImages(enabled);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonImageWidthCellsChange: (width) => {\n\t\t\t\t\t\tthis.settingsManager.setImageWidthCells(width);\n\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\tif (child instanceof ToolExecutionComponent) {\n\t\t\t\t\t\t\t\tchild.setImageWidthCells(width);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonAutoResizeImagesChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setImageAutoResize(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonBlockImagesChange: (blocked) => {\n\t\t\t\t\t\tthis.settingsManager.setBlockImages(blocked);\n\t\t\t\t\t},\n\t\t\t\t\tonEnableSkillCommandsChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setEnableSkillCommands(enabled);\n\t\t\t\t\t\tthis.setupAutocompleteProvider();\n\t\t\t\t\t},\n\t\t\t\t\tonSteeringModeChange: (mode) => {\n\t\t\t\t\t\tthis.session.setSteeringMode(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonFollowUpModeChange: (mode) => {\n\t\t\t\t\t\tthis.session.setFollowUpMode(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonTransportChange: (transport) => {\n\t\t\t\t\t\tthis.settingsManager.setTransport(transport);\n\t\t\t\t\t\tthis.session.agent.transport = transport;\n\t\t\t\t\t},\n\t\t\t\t\tonHttpIdleTimeoutMsChange: (timeoutMs) => {\n\t\t\t\t\t\tthis.settingsManager.setHttpIdleTimeoutMs(timeoutMs);\n\t\t\t\t\t\tconfigureHttpDispatcher(timeoutMs);\n\t\t\t\t\t\tthis.showStatus(`HTTP idle timeout: ${formatHttpIdleTimeoutMs(timeoutMs)}`);\n\t\t\t\t\t},\n\t\t\t\t\tonThinkingLevelChange: (level) => {\n\t\t\t\t\t\tthis.session.setThinkingLevel(level);\n\t\t\t\t\t\tthis.footer.invalidate();\n\t\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\t},\n\t\t\t\t\tonThemeChange: (themeSetting) => {\n\t\t\t\t\t\tthis.settingsManager.setTheme(themeSetting);\n\t\t\t\t\t\tvoid this.themeController.applyFromSettings();\n\t\t\t\t\t},\n\t\t\t\t\tonThemePreview: (themeName) => this.themeController.preview(themeName),\n\t\t\t\t\tonHideThinkingBlockChange: (hidden) => {\n\t\t\t\t\t\tthis.hideThinkingBlock = hidden;\n\t\t\t\t\t\tthis.settingsManager.setHideThinkingBlock(hidden);\n\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\tif (child instanceof AssistantMessageComponent) {\n\t\t\t\t\t\t\t\tchild.setHideThinkingBlock(hidden);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\t\t},\n\t\t\t\t\tonShowCacheMissNoticesChange: (shown) => {\n\t\t\t\t\t\tthis.settingsManager.setShowCacheMissNotices(shown);\n\t\t\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\t\t},\n\t\t\t\t\tonCollapseChangelogChange: (collapsed) => {\n\t\t\t\t\t\tthis.settingsManager.setCollapseChangelog(collapsed);\n\t\t\t\t\t},\n\t\t\t\t\tonEnableInstallTelemetryChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setEnableInstallTelemetry(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonQuietStartupChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setQuietStartup(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonDefaultProjectTrustChange: (defaultProjectTrust) => {\n\t\t\t\t\t\tthis.settingsManager.setDefaultProjectTrust(defaultProjectTrust);\n\t\t\t\t\t},\n\t\t\t\t\tonDoubleEscapeActionChange: (action) => {\n\t\t\t\t\t\tthis.settingsManager.setDoubleEscapeAction(action);\n\t\t\t\t\t},\n\t\t\t\t\tonTreeFilterModeChange: (mode) => {\n\t\t\t\t\t\tthis.settingsManager.setTreeFilterMode(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonShowHardwareCursorChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setShowHardwareCursor(enabled);\n\t\t\t\t\t\tthis.ui.setShowHardwareCursor(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonEditorPaddingXChange: (padding) => {\n\t\t\t\t\t\tthis.settingsManager.setEditorPaddingX(padding);\n\t\t\t\t\t\tthis.defaultEditor.setPaddingX(padding);\n\t\t\t\t\t\tif (this.editor !== this.defaultEditor && this.editor.setPaddingX !== undefined) {\n\t\t\t\t\t\t\tthis.editor.setPaddingX(padding);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonOutputPadChange: (padding) => {\n\t\t\t\t\t\tthis.settingsManager.setOutputPad(padding);\n\t\t\t\t\t\tthis.outputPad = padding;\n\t\t\t\t\t\tif (this.streamingComponent || this.session.isStreaming) {\n\t\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\tchild instanceof AssistantMessageComponent ||\n\t\t\t\t\t\t\t\t\tchild instanceof CustomMessageComponent ||\n\t\t\t\t\t\t\t\t\tchild instanceof UserMessageComponent\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tchild.setOutputPad(padding);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (this.streamingComponent) {\n\t\t\t\t\t\t\t\tthis.streamingComponent.setOutputPad(padding);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\t\t},\n\t\t\t\t\tonAutocompleteMaxVisibleChange: (maxVisible) => {\n\t\t\t\t\t\tthis.settingsManager.setAutocompleteMaxVisible(maxVisible);\n\t\t\t\t\t\tthis.defaultEditor.setAutocompleteMaxVisible(maxVisible);\n\t\t\t\t\t\tif (this.editor !== this.defaultEditor && this.editor.setAutocompleteMaxVisible !== undefined) {\n\t\t\t\t\t\t\tthis.editor.setAutocompleteMaxVisible(maxVisible);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonClearOnShrinkChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setClearOnShrink(enabled);\n\t\t\t\t\t\tthis.ui.setClearOnShrink(enabled);\n\t\t\t\t\t\tif (!enabled && !this.activeStatusIndicator) {\n\t\t\t\t\t\t\tthis.statusContainer.clear();\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonShowTerminalProgressChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setShowTerminalProgress(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonWarningsChange: (warnings) => {\n\t\t\t\t\t\tthis.settingsManager.setWarnings(warnings);\n\t\t\t\t\t},\n\t\t\t\t\tonCancel: () => {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getSettingsList() };\n\t\t});\n\t}\n\n\tprivate async handleModelCommand(searchTerm?: string): Promise {\n\t\tif (!searchTerm) {\n\t\t\tthis.showModelSelector();\n\t\t\treturn;\n\t\t}\n\n\t\tconst model = await this.findExactModelMatch(searchTerm);\n\t\tif (model) {\n\t\t\ttry {\n\t\t\t\tawait this.session.setModel(model);\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tthis.showStatus(`Model: ${model.id}`);\n\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(model);\n\t\t\t\tthis.checkDaxnutsEasterEgg(model);\n\t\t\t} catch (error) {\n\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showModelSelector(searchTerm);\n\t}\n\n\tprivate async findExactModelMatch(searchTerm: string): Promise | undefined> {\n\t\tconst models = await this.getModelCandidates();\n\t\treturn findExactModelReferenceMatch(searchTerm, models);\n\t}\n\n\tprivate async getModelCandidates(): Promise[]> {\n\t\tif (this.session.scopedModels.length > 0) {\n\t\t\treturn this.session.scopedModels.map((scoped) => scoped.model);\n\t\t}\n\n\t\ttry {\n\t\t\tawait this.session.modelRuntime.refresh();\n\t\t\treturn [...(await this.session.modelRuntime.getAvailable())];\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\t/** Update the footer's available provider count from the current snapshot without refreshing catalogs. */\n\tprivate updateAvailableProviderCount(): void {\n\t\tconst models =\n\t\t\tthis.session.scopedModels.length > 0\n\t\t\t\t? this.session.scopedModels.map((scoped) => scoped.model)\n\t\t\t\t: this.session.modelRuntime.getAvailableSnapshot();\n\t\tconst uniqueProviders = new Set(models.map((model) => model.provider));\n\t\tthis.footerDataProvider.setAvailableProviderCount(uniqueProviders.size);\n\t}\n\n\tprivate async maybeWarnAboutAnthropicSubscriptionAuth(\n\t\tmodel: Model | undefined = this.session.model,\n\t): Promise {\n\t\tif (this.settingsManager.getWarnings().anthropicExtraUsage === false) {\n\t\t\treturn;\n\t\t}\n\t\tif (this.anthropicSubscriptionWarningShown) {\n\t\t\treturn;\n\t\t}\n\t\tif (!model || model.provider !== \"anthropic\") {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tif ((await this.session.modelRuntime.checkAuth(\"anthropic\"))?.type === \"oauth\") {\n\t\t\t\tthis.anthropicSubscriptionWarningShown = true;\n\t\t\t\tthis.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst apiKey = (await this.session.modelRuntime.getAuth(model.provider))?.auth.apiKey;\n\t\t\tif (!isAnthropicSubscriptionAuthKey(apiKey)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.anthropicSubscriptionWarningShown = true;\n\t\t\tthis.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);\n\t\t} catch {\n\t\t\t// Ignore auth lookup failures for warning-only checks.\n\t\t}\n\t}\n\n\tprivate maybeSaveImplicitProjectTrustAfterReload(): boolean {\n\t\tconst cwd = this.sessionManager.getCwd();\n\t\tif (this.autoTrustOnReloadCwd !== cwd) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!this.settingsManager.isProjectTrusted() || !hasTrustRequiringProjectResources(cwd)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst trustStore = new ProjectTrustStore(this.runtimeHost.services.agentDir);\n\t\ttry {\n\t\t\tif (trustStore.get(cwd) !== null) {\n\t\t\t\tthis.autoTrustOnReloadCwd = undefined;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ttrustStore.set(cwd, true);\n\t\t\tthis.autoTrustOnReloadCwd = undefined;\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tthis.showWarning(\n\t\t\t\t`Could not save project trust after reload: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate showTrustSelector(): void {\n\t\tconst cwd = this.sessionManager.getCwd();\n\t\tconst trustStore = new ProjectTrustStore(this.runtimeHost.services.agentDir);\n\t\tconst savedDecision = trustStore.getEntry(cwd);\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new TrustSelectorComponent({\n\t\t\t\tcwd,\n\t\t\t\tsavedDecision,\n\t\t\t\tprojectTrusted: this.settingsManager.isProjectTrusted(),\n\t\t\t\tonSelect: (selection) => {\n\t\t\t\t\ttrustStore.setMany(selection.updates);\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showStatus(\n\t\t\t\t\t\t`Saved trust decision: ${selection.trusted ? \"trusted\" : \"untrusted\"}. Restart pi for this to take effect.`,\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tonCancel: () => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showModelSelector(initialSearchInput?: string): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ModelSelectorComponent(\n\t\t\t\tthis.ui,\n\t\t\t\tthis.session.model,\n\t\t\t\tthis.settingsManager,\n\t\t\t\tthis.session.modelRuntime,\n\t\t\t\tthis.session.scopedModels,\n\t\t\t\tasync (model) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.session.setModel(model);\n\t\t\t\t\t\tthis.footer.invalidate();\n\t\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.showStatus(`Model: ${model.id}`);\n\t\t\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(model);\n\t\t\t\t\t\tthis.checkDaxnutsEasterEgg(model);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tinitialSearchInput,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async showModelsSelector(): Promise {\n\t\t// Get all available models\n\t\tawait this.session.modelRuntime.refresh();\n\t\tconst allModels = [...(await this.session.modelRuntime.getAvailable())];\n\t\tconst allModelIds = new Set(allModels.map((model) => `${model.provider}/${model.id}`));\n\t\tconst configuredPatterns = this.settingsManager.getEnabledModels();\n\t\tconst sessionScopedModels = this.session.scopedModels;\n\n\t\tif (allModels.length === 0 && !configuredPatterns?.length && sessionScopedModels.length === 0) {\n\t\t\tthis.showStatus(\"No models available\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst configuredScope = configuredPatterns?.length\n\t\t\t? await resolveModelScopeWithDiagnostics(configuredPatterns, this.session.modelRuntime)\n\t\t\t: undefined;\n\n\t\t// Check if session has scoped models (from previous session-only changes or CLI --models)\n\t\tconst hasSessionScope = sessionScopedModels.length > 0;\n\n\t\t// Build enabled model IDs from session state or settings\n\t\tlet currentEnabledIds: string[] | null = null;\n\n\t\tif (hasSessionScope) {\n\t\t\t// Use current session's scoped models\n\t\t\tcurrentEnabledIds = sessionScopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);\n\t\t} else if (configuredScope) {\n\t\t\tcurrentEnabledIds = configuredScope.scopedModels.map(\n\t\t\t\t(scoped) => `${scoped.model.provider}/${scoped.model.id}`,\n\t\t\t);\n\t\t}\n\n\t\tfor (const diagnostic of configuredScope?.diagnostics ?? []) {\n\t\t\tif (diagnostic.code !== \"no-match\") continue;\n\t\t\tcurrentEnabledIds ??= [];\n\t\t\tif (!currentEnabledIds.includes(diagnostic.pattern)) currentEnabledIds.push(diagnostic.pattern);\n\t\t}\n\n\t\t// Helper to update session's scoped models (session-only, no persist)\n\t\tconst updateSessionModels = async (enabledIds: string[] | null) => {\n\t\t\tcurrentEnabledIds = enabledIds === null ? null : [...enabledIds];\n\t\t\tconst hasEnabledAvailableModel = enabledIds?.some((id) => allModelIds.has(id)) ?? false;\n\t\t\tconst allAvailableModelsEnabled =\n\t\t\t\tenabledIds !== null && [...allModelIds].every((id) => enabledIds.includes(id));\n\t\t\tif (enabledIds && hasEnabledAvailableModel && !allAvailableModelsEnabled) {\n\t\t\t\tconst newScopedModels = await resolveModelScope(enabledIds, this.session.modelRuntime);\n\t\t\t\tthis.session.setScopedModels(\n\t\t\t\t\tnewScopedModels.map((sm) => ({\n\t\t\t\t\t\tmodel: sm.model,\n\t\t\t\t\t\tthinkingLevel: sm.thinkingLevel,\n\t\t\t\t\t})),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// All enabled or none enabled = no filter\n\t\t\t\tthis.session.setScopedModels([]);\n\t\t\t}\n\t\t\tawait this.updateAvailableProviderCount();\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ScopedModelsSelectorComponent(\n\t\t\t\t{\n\t\t\t\t\tallModels,\n\t\t\t\t\tenabledModelIds: currentEnabledIds,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tonChange: async (enabledIds) => {\n\t\t\t\t\t\tawait updateSessionModels(enabledIds);\n\t\t\t\t\t},\n\t\t\t\t\tonPersist: (enabledIds) => {\n\t\t\t\t\t\t// Persist to settings\n\t\t\t\t\t\tconst allEnabled =\n\t\t\t\t\t\t\tenabledIds !== null &&\n\t\t\t\t\t\t\tenabledIds.length === allModels.length &&\n\t\t\t\t\t\t\tenabledIds.every((id) => allModelIds.has(id));\n\t\t\t\t\t\tconst newPatterns = enabledIds === null || allEnabled ? undefined : enabledIds;\n\t\t\t\t\t\tthis.settingsManager.setEnabledModels(newPatterns ? [...newPatterns] : undefined);\n\t\t\t\t\t\tthis.showStatus(\"Model selection saved to settings\");\n\t\t\t\t\t},\n\t\t\t\t\tonCancel: () => {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showUserMessageSelector(): void {\n\t\tconst userMessages = this.session.getUserMessagesForForking();\n\n\t\tif (userMessages.length === 0) {\n\t\t\tthis.showStatus(\"No messages to fork from\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst initialSelectedId = userMessages[userMessages.length - 1]?.entryId;\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new UserMessageSelectorComponent(\n\t\t\t\tuserMessages.map((m) => ({ id: m.entryId, text: m.text })),\n\t\t\t\tasync (entryId) => {\n\t\t\t\t\tdone();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.runtimeHost.fork(entryId);\n\t\t\t\t\t\tif (result.cancelled) {\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis.editor.setText(result.selectedText ?? \"\");\n\t\t\t\t\t\tthis.showStatus(\"Forked to new session\");\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tinitialSelectedId,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getMessageList() };\n\t\t});\n\t}\n\n\tprivate async handleCloneCommand(): Promise {\n\t\tconst leafId = this.sessionManager.getLeafId();\n\t\tif (!leafId) {\n\t\t\tthis.showStatus(\"Nothing to clone yet\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.fork(leafId, { position: \"at\" });\n\t\t\tif (result.cancelled) {\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.editor.setText(\"\");\n\t\t\tthis.showStatus(\"Cloned to new session\");\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate showTreeSelector(initialSelectedId?: string): void {\n\t\tconst tree = this.sessionManager.getTree();\n\t\tconst realLeafId = this.sessionManager.getLeafId();\n\t\tconst initialFilterMode = this.settingsManager.getTreeFilterMode();\n\n\t\tif (tree.length === 0) {\n\t\t\tthis.showStatus(\"No entries in session\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new TreeSelectorComponent(\n\t\t\t\ttree,\n\t\t\t\trealLeafId,\n\t\t\t\tthis.ui.terminal.rows,\n\t\t\t\tasync (entryId) => {\n\t\t\t\t\t// Selecting the current leaf is a no-op (already there)\n\t\t\t\t\tif (entryId === this.sessionManager.getLeafId()) {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.showStatus(\"Already at this point\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Ask about summarization\n\t\t\t\t\tdone(); // Close selector first\n\n\t\t\t\t\t// Loop until user makes a complete choice or cancels to tree\n\t\t\t\t\tlet wantsSummary = false;\n\t\t\t\t\tlet customInstructions: string | undefined;\n\n\t\t\t\t\t// Check if we should skip the prompt (user preference to always default to no summary)\n\t\t\t\t\tif (!this.settingsManager.getBranchSummarySkipPrompt()) {\n\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\tconst summaryChoice = await this.showExtensionSelector(\"Summarize branch?\", [\n\t\t\t\t\t\t\t\t\"No summary\",\n\t\t\t\t\t\t\t\t\"Summarize\",\n\t\t\t\t\t\t\t\t\"Summarize with custom prompt\",\n\t\t\t\t\t\t\t]);\n\n\t\t\t\t\t\t\tif (summaryChoice === undefined) {\n\t\t\t\t\t\t\t\t// User pressed escape - re-show tree selector with same selection\n\t\t\t\t\t\t\t\tthis.showTreeSelector(entryId);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\twantsSummary = summaryChoice !== \"No summary\";\n\n\t\t\t\t\t\t\tif (summaryChoice === \"Summarize with custom prompt\") {\n\t\t\t\t\t\t\t\tcustomInstructions = await this.showExtensionEditor(\"Custom summarization instructions\");\n\t\t\t\t\t\t\t\tif (customInstructions === undefined) {\n\t\t\t\t\t\t\t\t\t// User cancelled - loop back to summary selector\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// User made a complete choice\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// The user committed to navigating: stop the active response first.\n\t\t\t\t\tif (this.session.isStreaming) {\n\t\t\t\t\t\tthis.restoreQueuedMessagesToEditor();\n\t\t\t\t\t\tawait this.session.abort();\n\t\t\t\t\t}\n\n\t\t\t\t\t// Set up escape handler and status indicator if summarizing\n\t\t\t\t\tlet showingSummaryIndicator = false;\n\t\t\t\t\tconst originalOnEscape = this.defaultEditor.onEscape;\n\n\t\t\t\t\tif (wantsSummary) {\n\t\t\t\t\t\tthis.defaultEditor.onEscape = () => {\n\t\t\t\t\t\t\tthis.session.abortBranchSummary();\n\t\t\t\t\t\t};\n\t\t\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\t\t\tthis.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui));\n\t\t\t\t\t\tshowingSummaryIndicator = true;\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.session.navigateTree(entryId, {\n\t\t\t\t\t\t\tsummarize: wantsSummary,\n\t\t\t\t\t\t\tcustomInstructions,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tif (result.aborted) {\n\t\t\t\t\t\t\t// Summarization aborted - re-show tree selector with same selection\n\t\t\t\t\t\t\tthis.showStatus(\"Branch summarization cancelled\");\n\t\t\t\t\t\t\tthis.showTreeSelector(entryId);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.cancelled) {\n\t\t\t\t\t\t\tthis.showStatus(\"Navigation cancelled\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Update UI\n\t\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\t\tthis.renderInitialMessages();\n\t\t\t\t\t\tif (result.editorText && !this.editor.getText().trim()) {\n\t\t\t\t\t\t\tthis.editor.setText(result.editorText);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.showStatus(\"Navigated to selected point\");\n\t\t\t\t\t\tvoid this.flushCompactionQueue({ willRetry: false });\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (showingSummaryIndicator) {\n\t\t\t\t\t\t\tthis.clearStatusIndicator(\"branchSummary\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.defaultEditor.onEscape = originalOnEscape;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\t(entryId, label) => {\n\t\t\t\t\tthis.sessionManager.appendLabelChange(entryId, label);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tinitialSelectedId,\n\t\t\t\tinitialFilterMode,\n\t\t\t);\n\t\t\tselector.onCopy = async (text) => {\n\t\t\t\tif (!text) {\n\t\t\t\t\tthis.showError(\"Selected entry has no text to copy\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait copyToClipboard(text);\n\t\t\t\t\tthis.showStatus(\"Copied selected message to clipboard\");\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t};\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showSessionSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new SessionSelectorComponent(\n\t\t\t\t(onProgress) =>\n\t\t\t\t\tSessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir(), onProgress),\n\t\t\t\t(onProgress) =>\n\t\t\t\t\tthis.sessionManager.usesDefaultSessionDir()\n\t\t\t\t\t\t? SessionManager.listAll(onProgress)\n\t\t\t\t\t\t: SessionManager.listAll(this.sessionManager.getSessionDir(), onProgress),\n\t\t\t\tasync (sessionPath) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tawait this.handleResumeSession(sessionPath);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tvoid this.shutdown();\n\t\t\t\t},\n\t\t\t\t() => this.ui.requestRender(),\n\t\t\t\t{\n\t\t\t\t\trenameSession: async (sessionFilePath: string, nextName: string | undefined) => {\n\t\t\t\t\t\tconst next = (nextName ?? \"\").trim();\n\t\t\t\t\t\tif (!next) return;\n\t\t\t\t\t\tconst mgr = SessionManager.open(sessionFilePath);\n\t\t\t\t\t\tmgr.appendSessionInfo(next);\n\t\t\t\t\t},\n\t\t\t\t\tshowRenameHint: true,\n\t\t\t\t\tkeybindings: this.keybindings,\n\t\t\t\t},\n\n\t\t\t\tthis.sessionManager.getSessionFile(),\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async handleResumeSession(\n\t\tsessionPath: string,\n\t\toptions?: Parameters[1],\n\t): Promise<{ cancelled: boolean }> {\n\t\tthis.clearStatusIndicator();\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.switchSession(sessionPath, {\n\t\t\t\twithSession: options?.withSession,\n\t\t\t\tprojectTrustContextFactory: (cwd) => this.createProjectTrustContext(cwd),\n\t\t\t});\n\t\t\tif (result.cancelled) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthis.showStatus(\"Resumed session\");\n\t\t\treturn result;\n\t\t} catch (error: unknown) {\n\t\t\tif (error instanceof MissingSessionCwdError) {\n\t\t\t\tconst selectedCwd = await this.promptForMissingSessionCwd(error);\n\t\t\t\tif (!selectedCwd) {\n\t\t\t\t\tthis.showStatus(\"Resume cancelled\");\n\t\t\t\t\treturn { cancelled: true };\n\t\t\t\t}\n\t\t\t\tconst result = await this.runtimeHost.switchSession(sessionPath, {\n\t\t\t\t\tcwdOverride: selectedCwd,\n\t\t\t\t\twithSession: options?.withSession,\n\t\t\t\t\tprojectTrustContextFactory: (cwd) => this.createProjectTrustContext(cwd),\n\t\t\t\t});\n\t\t\t\tif (result.cancelled) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\tthis.showStatus(\"Resumed session in current cwd\");\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\treturn this.handleFatalRuntimeError(\"Failed to resume session\", error);\n\t\t}\n\t}\n\n\tprivate getLoginProviderOptions(authType?: \"oauth\" | \"api_key\"): AuthSelectorProvider[] {\n\t\tconst options: AuthSelectorProvider[] = [];\n\t\tfor (const provider of this.session.modelRuntime.getProviders()) {\n\t\t\tconst authStatus = this.session.modelRuntime.getProviderAuthStatus(provider.id);\n\t\t\tconst status = authStatus.configured\n\t\t\t\t? {\n\t\t\t\t\t\ttype: this.session.modelRuntime.isUsingOAuth(provider.id) ? (\"oauth\" as const) : (\"api_key\" as const),\n\t\t\t\t\t\tsource: authStatus.label ?? authStatus.source,\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\t\tif ((!authType || authType === \"oauth\") && provider.auth.oauth) {\n\t\t\t\toptions.push({\n\t\t\t\t\tid: provider.id,\n\t\t\t\t\tname: provider.name,\n\t\t\t\t\tauthType: \"oauth\",\n\t\t\t\t\tmethod: provider.auth.oauth,\n\t\t\t\t\tstatus,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif ((!authType || authType === \"api_key\") && provider.auth.apiKey) {\n\t\t\t\toptions.push({\n\t\t\t\t\tid: provider.id,\n\t\t\t\t\tname: provider.name,\n\t\t\t\t\tauthType: \"api_key\",\n\t\t\t\t\tmethod: provider.auth.apiKey,\n\t\t\t\t\tstatus,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn options.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tprivate async getLogoutProviderOptions(): Promise {\n\t\treturn (await this.session.modelRuntime.listCredentials())\n\t\t\t.map(({ providerId, type }) => ({\n\t\t\t\tid: providerId,\n\t\t\t\tname: this.session.modelRuntime.getProvider(providerId)?.name ?? providerId,\n\t\t\t\tauthType: type,\n\t\t\t\tstatus: { type, source: \"stored credential\" },\n\t\t\t}))\n\t\t\t.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tprivate findLoginProviderOptions(providerRef: string): AuthSelectorProvider[] {\n\t\tconst normalizedProviderRef = providerRef.trim().toLowerCase();\n\t\tif (!normalizedProviderRef) {\n\t\t\treturn [];\n\t\t}\n\n\t\treturn this.getLoginProviderOptions().filter(\n\t\t\t(provider) =>\n\t\t\t\tprovider.id.toLowerCase() === normalizedProviderRef ||\n\t\t\t\tprovider.name.toLowerCase() === normalizedProviderRef,\n\t\t);\n\t}\n\n\tprivate async handleLoginCommand(providerRef?: string): Promise {\n\t\tawait this.session.modelRuntime.getAvailable();\n\t\tif (!providerRef) {\n\t\t\tthis.showLoginAuthTypeSelector();\n\t\t\treturn;\n\t\t}\n\n\t\tconst providerOptions = this.findLoginProviderOptions(providerRef);\n\t\tif (providerOptions.length === 1) {\n\t\t\tawait this.startProviderLogin(providerOptions[0]!);\n\t\t\treturn;\n\t\t}\n\n\t\tif (providerOptions.length > 1) {\n\t\t\tconst providerIds = new Set(providerOptions.map((provider) => provider.id));\n\t\t\tif (providerIds.size === 1) {\n\t\t\t\tthis.showLoginAuthTypeSelector(providerOptions);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.showLoginProviderSelector(undefined, providerRef);\n\t}\n\n\tprivate async startProviderLogin(providerOption: AuthSelectorProvider): Promise {\n\t\tif (providerOption.authType === \"oauth\") {\n\t\t\tawait this.showLoginDialog(providerOption.id, providerOption.name);\n\t\t} else if (providerOption.method?.login) {\n\t\t\tawait this.showApiKeyLoginDialog(providerOption.id, providerOption.name);\n\t\t} else {\n\t\t\tthis.showAmbientAuthDialog(providerOption);\n\t\t}\n\t}\n\n\tprivate showLoginAuthTypeSelector(providerOptions?: AuthSelectorProvider[]): void {\n\t\tconst oauthProvider = providerOptions?.find((provider) => provider.authType === \"oauth\");\n\t\tconst oauthLoginLabel =\n\t\t\toauthProvider?.method && \"loginLabel\" in oauthProvider.method ? oauthProvider.method.loginLabel : undefined;\n\t\tconst subscriptionLabel = oauthLoginLabel ?? \"Sign in with an account\";\n\t\tconst apiKeyLabel = \"Sign in with an API key\";\n\t\tconst availableAuthTypes = providerOptions\n\t\t\t? new Set(providerOptions.map((provider) => provider.authType))\n\t\t\t: new Set([\"oauth\", \"api_key\"]);\n\t\tconst options: string[] = [];\n\t\tif (availableAuthTypes.has(\"oauth\")) {\n\t\t\toptions.push(subscriptionLabel);\n\t\t}\n\t\tif (availableAuthTypes.has(\"api_key\")) {\n\t\t\toptions.push(apiKeyLabel);\n\t\t}\n\n\t\tif (options.length === 0) {\n\t\t\tthis.showStatus(\"No login methods available.\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (providerOptions && options.length === 1) {\n\t\t\tconst providerOption = providerOptions[0];\n\t\t\tif (providerOption) {\n\t\t\t\tvoid this.startProviderLogin(providerOption);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst title = providerOptions?.[0]\n\t\t\t? `Select authentication method for ${providerOptions[0].name}:`\n\t\t\t: \"Select authentication method:\";\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\t\ttitle,\n\t\t\t\toptions,\n\t\t\t\t(option) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tconst authType = option === subscriptionLabel ? \"oauth\" : \"api_key\";\n\t\t\t\t\tif (providerOptions) {\n\t\t\t\t\t\tconst providerOption = providerOptions.find((provider) => provider.authType === authType);\n\t\t\t\t\t\tif (providerOption) {\n\t\t\t\t\t\t\tvoid this.startProviderLogin(providerOption);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthis.showLoginProviderSelector(authType);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showLoginProviderSelector(authType?: AuthSelectorProvider[\"authType\"], initialSearchInput?: string): void {\n\t\tconst providerOptions = this.getLoginProviderOptions(authType);\n\t\tif (providerOptions.length === 0) {\n\t\t\tconst message =\n\t\t\t\tauthType === \"oauth\"\n\t\t\t\t\t? \"No subscription providers available.\"\n\t\t\t\t\t: authType === \"api_key\"\n\t\t\t\t\t\t? \"No API key providers available.\"\n\t\t\t\t\t\t: \"No login providers available.\";\n\t\t\tthis.showStatus(message);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new OAuthSelectorComponent(\n\t\t\t\t\"login\",\n\t\t\t\tproviderOptions,\n\t\t\t\tasync (providerId, selectedAuthType) => {\n\t\t\t\t\tdone();\n\n\t\t\t\t\tconst providerOption = providerOptions.find(\n\t\t\t\t\t\t(provider) => provider.id === providerId && provider.authType === selectedAuthType,\n\t\t\t\t\t);\n\t\t\t\t\tif (!providerOption) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tawait this.startProviderLogin(providerOption);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tif (authType) {\n\t\t\t\t\t\tthis.showLoginAuthTypeSelector();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tinitialSearchInput,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async showOAuthSelector(mode: \"login\" | \"logout\"): Promise {\n\t\tif (mode === \"login\") {\n\t\t\tthis.showLoginAuthTypeSelector();\n\t\t\treturn;\n\t\t}\n\n\t\tconst providerOptions = await this.getLogoutProviderOptions();\n\t\tif (providerOptions.length === 0) {\n\t\t\tthis.showStatus(\n\t\t\t\t\"No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new OAuthSelectorComponent(\n\t\t\t\tmode,\n\t\t\t\tproviderOptions,\n\t\t\t\tasync (providerId: string) => {\n\t\t\t\t\tdone();\n\n\t\t\t\t\tconst providerOption = providerOptions.find((provider) => provider.id === providerId);\n\t\t\t\t\tif (!providerOption) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.session.modelRuntime.logout(providerOption.id);\n\t\t\t\t\t\tawait this.updateAvailableProviderCount();\n\t\t\t\t\t\tconst message =\n\t\t\t\t\t\t\tproviderOption.authType === \"oauth\"\n\t\t\t\t\t\t\t\t? `Logged out of ${providerOption.name}`\n\t\t\t\t\t\t\t\t: `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;\n\t\t\t\t\t\tthis.showStatus(message);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tthis.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async completeProviderAuthentication(\n\t\tproviderId: string,\n\t\tproviderName: string,\n\t\tauthType: \"oauth\" | \"api_key\",\n\t\tpreviousModel: Model | undefined,\n\t): Promise {\n\t\tawait this.session.modelRuntime.getAvailable();\n\n\t\tconst actionLabel = authType === \"oauth\" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;\n\n\t\tlet selectedModel: Model | undefined;\n\t\tlet selectionError: string | undefined;\n\t\tif (isUnknownModel(previousModel)) {\n\t\t\tconst availableModels = await this.session.modelRuntime.getAvailable();\n\t\t\tconst providerModels = availableModels.filter((model) => model.provider === providerId);\n\t\t\tif (!hasDefaultModelProvider(providerId)) {\n\t\t\t\tselectionError = `${actionLabel}, but no default model is configured for provider \"${providerId}\". Use /model to select a model.`;\n\t\t\t} else if (providerModels.length === 0) {\n\t\t\t\tselectionError = `${actionLabel}, but no models are available for that provider. Use /model to select a model.`;\n\t\t\t} else {\n\t\t\t\tconst defaultModelId = defaultModelPerProvider[providerId];\n\t\t\t\tselectedModel = providerModels.find((model) => model.id === defaultModelId);\n\t\t\t\tif (!selectedModel) {\n\t\t\t\t\tselectionError = `${actionLabel}, but its default model \"${defaultModelId}\" is not available. Use /model to select a model.`;\n\t\t\t\t} else {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.session.setModel(selectedModel);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tselectedModel = undefined;\n\t\t\t\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tselectionError = `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tawait this.updateAvailableProviderCount();\n\t\tthis.footer.invalidate();\n\t\tthis.updateEditorBorderColor();\n\t\tif (selectedModel) {\n\t\t\tthis.showStatus(`${actionLabel}. Selected ${selectedModel.id}. Credentials saved to ${getAuthPath()}`);\n\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel);\n\t\t\tthis.checkDaxnutsEasterEgg(selectedModel);\n\t\t} else {\n\t\t\tthis.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`);\n\t\t\tif (selectionError) {\n\t\t\t\tthis.showError(selectionError);\n\t\t\t} else {\n\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate showAmbientAuthDialog(providerOption: AuthSelectorProvider): void {\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui,\n\t\t\tproviderOption.id,\n\t\t\t() => restoreEditor(),\n\t\t\tproviderOption.name,\n\t\t\t`${providerOption.name} setup`,\n\t\t);\n\t\tdialog.showInfo(`${providerOption.method?.name ?? \"Authentication\"} is configured outside pi.`, [], true);\n\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(dialog);\n\t\tthis.ui.setFocus(dialog);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async showApiKeyLoginDialog(providerId: string, providerName: string): Promise {\n\t\tconst previousModel = this.session.model;\n\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui,\n\t\t\tproviderId,\n\t\t\t(_success, _message) => {\n\t\t\t\t// Completion handled below\n\t\t\t},\n\t\t\tproviderName,\n\t\t);\n\n\t\tif (providerId === \"amazon-bedrock\") {\n\t\t\tdialog.showDetails([\n\t\t\t\ttheme.fg(\"text\", \"You can also use an AWS profile, IAM keys, or role-based credentials.\"),\n\t\t\t\ttheme.fg(\"muted\", \"See:\"),\n\t\t\t\ttheme.fg(\"accent\", ` ${path.join(getDocsPath(), \"providers.md\")}`),\n\t\t\t]);\n\t\t}\n\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(dialog);\n\t\tthis.ui.setFocus(dialog);\n\t\tthis.ui.requestRender();\n\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\ttry {\n\t\t\tawait this.loginProvider(dialog, providerId, \"api_key\");\n\t\t\trestoreEditor();\n\t\t\tawait this.completeProviderAuthentication(providerId, providerName, \"api_key\", previousModel);\n\t\t} catch (error: unknown) {\n\t\t\trestoreEditor();\n\t\t\tconst errorMsg = error instanceof Error ? error.message : String(error);\n\t\t\tif (errorMsg !== \"Login cancelled\") {\n\t\t\t\tthis.showError(`Failed to save API key for ${providerName}: ${errorMsg}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate showAuthSelect(\n\t\tdialog: LoginDialogComponent,\n\t\tprompt: Extract,\n\t): Promise {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst restoreDialog = () => {\n\t\t\t\tthis.editorContainer.clear();\n\t\t\t\tthis.editorContainer.addChild(dialog);\n\t\t\t\tthis.ui.setFocus(dialog);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t};\n\t\t\tconst labels = prompt.options.map((option) => option.label);\n\t\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\t\tprompt.message,\n\t\t\t\tlabels,\n\t\t\t\t(optionLabel) => {\n\t\t\t\t\trestoreDialog();\n\t\t\t\t\tconst id = prompt.options.find((option) => option.label === optionLabel)?.id;\n\t\t\t\t\tif (id) resolve(id);\n\t\t\t\t\telse reject(new Error(\"Login cancelled\"));\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\trestoreDialog();\n\t\t\t\t\treject(new Error(\"Login cancelled\"));\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(selector);\n\t\t\tthis.ui.setFocus(selector);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\tprivate async showAuthPrompt(dialog: LoginDialogComponent, prompt: AuthPrompt): Promise {\n\t\tlet response: Promise;\n\t\tif (prompt.type === \"select\") {\n\t\t\tresponse = this.showAuthSelect(dialog, prompt);\n\t\t} else if (prompt.type === \"manual_code\") {\n\t\t\tresponse = dialog.showManualInput(prompt.message);\n\t\t} else {\n\t\t\tresponse = dialog.showPrompt(prompt.message, prompt.placeholder);\n\t\t}\n\t\tif (!prompt.signal) return response;\n\t\tif (prompt.signal.aborted) throw new Error(\"Login cancelled\");\n\t\tconst signal = prompt.signal;\n\t\tlet onAbort: (() => void) | undefined;\n\t\tconst aborted = new Promise((_resolve, reject) => {\n\t\t\tonAbort = () => reject(new Error(\"Login cancelled\"));\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t});\n\t\ttry {\n\t\t\treturn await Promise.race([response, aborted]);\n\t\t} finally {\n\t\t\tif (onAbort) signal.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t}\n\n\tprivate notifyAuthDialog(dialog: LoginDialogComponent, event: AuthEvent): void {\n\t\tif (event.type === \"auth_url\") {\n\t\t\tdialog.showAuth(event.url, event.instructions);\n\t\t} else if (event.type === \"device_code\") {\n\t\t\tdialog.showDeviceCode(event);\n\t\t\tdialog.showWaiting(\"Waiting for authentication...\");\n\t\t} else if (event.type === \"info\") {\n\t\t\tdialog.showInfo(event.message, event.links);\n\t\t} else {\n\t\t\tdialog.showProgress(event.message);\n\t\t}\n\t}\n\n\tprivate async loginProvider(\n\t\tdialog: LoginDialogComponent,\n\t\tproviderId: string,\n\t\tmethod: \"api_key\" | \"oauth\",\n\t): Promise {\n\t\tawait this.session.modelRuntime.login(providerId, method, {\n\t\t\tsignal: dialog.signal,\n\t\t\tprompt: (prompt) => this.showAuthPrompt(dialog, prompt),\n\t\t\tnotify: (event) => this.notifyAuthDialog(dialog, event),\n\t\t});\n\t}\n\n\tprivate async showLoginDialog(providerId: string, providerName: string): Promise {\n\t\tconst previousModel = this.session.model;\n\t\tconst dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => {}, providerName);\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(dialog);\n\t\tthis.ui.setFocus(dialog);\n\t\tthis.ui.requestRender();\n\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\ttry {\n\t\t\tawait this.loginProvider(dialog, providerId, \"oauth\");\n\t\t\trestoreEditor();\n\t\t\tawait this.completeProviderAuthentication(providerId, providerName, \"oauth\", previousModel);\n\t\t} catch (error: unknown) {\n\t\t\trestoreEditor();\n\t\t\tconst errorMsg = error instanceof Error ? error.message : String(error);\n\t\t\tif (errorMsg !== \"Login cancelled\") {\n\t\t\t\tthis.showError(`Failed to login to ${providerName}: ${errorMsg}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Command handlers\n\t// =========================================================================\n\n\tprivate async handleReloadCommand(): Promise {\n\t\tif (this.session.isStreaming) {\n\t\t\tthis.showWarning(\"Wait for the current response to finish before reloading.\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.session.isCompacting) {\n\t\t\tthis.showWarning(\"Wait for compaction to finish before reloading.\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.resetExtensionUI();\n\n\t\tconst reloadBox = new Container();\n\t\tconst borderColor = (s: string) => theme.fg(\"border\", s);\n\t\treloadBox.addChild(new DynamicBorder(borderColor));\n\t\treloadBox.addChild(new Spacer(1));\n\t\treloadBox.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.fg(\"muted\", \"Reloading keybindings, extensions, skills, prompts, themes, and context files...\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\treloadBox.addChild(new Spacer(1));\n\t\treloadBox.addChild(new DynamicBorder(borderColor));\n\n\t\tconst previousEditor = this.editor;\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(reloadBox);\n\t\tthis.ui.setFocus(reloadBox);\n\t\tthis.ui.requestRender(true);\n\t\tawait new Promise((resolve) => process.nextTick(resolve));\n\n\t\tconst dismissReloadBox = (editor: Component) => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(editor);\n\t\t\tthis.ui.setFocus(editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\tlet chatRestoredBeforeSessionStart = false;\n\t\tlet reloadBoxDismissed = false;\n\t\tconst restoreChatBeforeSessionStart = () => {\n\t\t\tif (chatRestoredBeforeSessionStart) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\t\t\tthis.rebuildChatFromMessages();\n\t\t\tchatRestoredBeforeSessionStart = true;\n\t\t};\n\n\t\ttry {\n\t\t\tawait this.session.reload({ beforeSessionStart: restoreChatBeforeSessionStart });\n\t\t\trestoreChatBeforeSessionStart();\n\t\t\tconfigureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs());\n\t\t\tthis.keybindings.reload();\n\t\t\tconst activeHeader = this.customHeader ?? this.builtInHeader;\n\t\t\tif (isExpandable(activeHeader)) {\n\t\t\t\tactiveHeader.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\t\tawait this.themeController.applyFromSettings();\n\t\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\t\tthis.defaultEditor.setPaddingX(editorPaddingX);\n\t\t\tthis.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);\n\t\t\tif (this.editor !== this.defaultEditor) {\n\t\t\t\tthis.editor.setPaddingX?.(editorPaddingX);\n\t\t\t\tthis.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);\n\t\t\t}\n\t\t\tthis.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());\n\t\t\tconst clearOnShrink = this.settingsManager.getClearOnShrink();\n\t\t\tthis.ui.setClearOnShrink(clearOnShrink);\n\t\t\tif (!clearOnShrink && !this.activeStatusIndicator) {\n\t\t\t\tthis.statusContainer.clear();\n\t\t\t}\n\t\t\tthis.setupAutocompleteProvider();\n\t\t\tconst runner = this.session.extensionRunner;\n\t\t\tthis.setupExtensionShortcuts(runner);\n\t\t\tthis.showLoadedResources({\n\t\t\t\tforce: false,\n\t\t\t\tshowDiagnosticsWhenQuiet: true,\n\t\t\t});\n\t\t\tconst savedImplicitProjectTrust = this.maybeSaveImplicitProjectTrustAfterReload();\n\t\t\tconst modelsJsonError = this.session.modelRuntime.getError();\n\t\t\tif (modelsJsonError) {\n\t\t\t\tthis.showError(`models.json error: ${modelsJsonError}`);\n\t\t\t}\n\t\t\tthis.showStatus(\n\t\t\t\tsavedImplicitProjectTrust\n\t\t\t\t\t? \"Reloaded keybindings, extensions, skills, prompts, themes, and context files; saved project trust\"\n\t\t\t\t\t: \"Reloaded keybindings, extensions, skills, prompts, themes, and context files\",\n\t\t\t);\n\t\t\tdismissReloadBox(this.editor as Component);\n\t\t\treloadBoxDismissed = true;\n\t\t} catch (error) {\n\t\t\tif (!reloadBoxDismissed) {\n\t\t\t\tdismissReloadBox(previousEditor as Component);\n\t\t\t}\n\t\t\tthis.showError(`Reload failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\n\tprivate async handleExportCommand(text: string): Promise {\n\t\tconst outputPath = this.getPathCommandArgument(text, \"/export\");\n\n\t\ttry {\n\t\t\tif (outputPath?.endsWith(\".jsonl\")) {\n\t\t\t\tconst filePath = this.session.exportToJsonl(outputPath);\n\t\t\t\tthis.showStatus(`Session exported to: ${filePath}`);\n\t\t\t} else {\n\t\t\t\tconst filePath = await this.session.exportToHtml(outputPath);\n\t\t\t\tthis.showStatus(`Session exported to: ${filePath}`);\n\t\t\t}\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(`Failed to export session: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t}\n\t}\n\n\tprivate getPathCommandArgument(text: string, command: \"/export\" | \"/import\"): string | undefined {\n\t\tif (text === command) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!text.startsWith(`${command} `)) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst argsString = text.slice(command.length + 1).trimStart();\n\t\tif (!argsString) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst firstChar = argsString[0];\n\t\tif (firstChar === '\"' || firstChar === \"'\") {\n\t\t\tconst closingQuoteIndex = argsString.indexOf(firstChar, 1);\n\t\t\tif (closingQuoteIndex < 0) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn argsString.slice(1, closingQuoteIndex);\n\t\t}\n\n\t\tconst firstWhitespaceIndex = argsString.search(/\\s/);\n\t\tif (firstWhitespaceIndex < 0) {\n\t\t\treturn argsString;\n\t\t}\n\t\treturn argsString.slice(0, firstWhitespaceIndex);\n\t}\n\n\tprivate async handleImportCommand(text: string): Promise {\n\t\tconst inputPath = this.getPathCommandArgument(text, \"/import\");\n\t\tif (!inputPath) {\n\t\t\tthis.showError(\"Usage: /import \");\n\t\t\treturn;\n\t\t}\n\n\t\tconst confirmed = await this.showExtensionConfirm(\"Import session\", `Replace current session with ${inputPath}?`);\n\t\tif (!confirmed) {\n\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.clearStatusIndicator();\n\t\t\tconst result = await this.runtimeHost.importFromJsonl(inputPath);\n\t\t\tif (result.cancelled) {\n\t\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.showStatus(`Session imported from: ${inputPath}`);\n\t\t} catch (error: unknown) {\n\t\t\tif (error instanceof MissingSessionCwdError) {\n\t\t\t\tconst selectedCwd = await this.promptForMissingSessionCwd(error);\n\t\t\t\tif (!selectedCwd) {\n\t\t\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst result = await this.runtimeHost.importFromJsonl(inputPath, selectedCwd);\n\t\t\t\tif (result.cancelled) {\n\t\t\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.showStatus(`Session imported from: ${inputPath}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (error instanceof SessionImportFileNotFoundError) {\n\t\t\t\tthis.showError(`Failed to import session: ${error.message}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.handleFatalRuntimeError(\"Failed to import session\", error);\n\t\t}\n\t}\n\n\tprivate async handleShareCommand(): Promise {\n\t\t// Check if gh is available and logged in\n\t\ttry {\n\t\t\tconst authResult = spawnSync(\"gh\", [\"auth\", \"status\"], { encoding: \"utf-8\" });\n\t\t\tif (authResult.status !== 0) {\n\t\t\t\tthis.showError(\"GitHub CLI is not logged in. Run 'gh auth login' first.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.showError(\"GitHub CLI (gh) is not installed. Install it from https://cli.github.com/\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Export to a temp file\n\t\tconst tmpFile = path.join(os.tmpdir(), \"session.html\");\n\t\ttry {\n\t\t\tawait this.session.exportToHtml(tmpFile);\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(`Failed to export session: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Show cancellable loader, replacing the editor\n\t\tconst loader = new BorderedLoader(this.ui, theme, \"Creating gist...\");\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(loader);\n\t\tthis.ui.setFocus(loader);\n\t\tthis.ui.requestRender();\n\n\t\tconst restoreEditor = () => {\n\t\t\tloader.dispose();\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\ttry {\n\t\t\t\tfs.unlinkSync(tmpFile);\n\t\t\t} catch {\n\t\t\t\t// Ignore cleanup errors\n\t\t\t}\n\t\t};\n\n\t\t// Create a secret gist asynchronously\n\t\tlet proc: ReturnType | null = null;\n\n\t\tloader.onAbort = () => {\n\t\t\tproc?.kill();\n\t\t\trestoreEditor();\n\t\t\tthis.showStatus(\"Share cancelled\");\n\t\t};\n\n\t\ttry {\n\t\t\tconst result = await new Promise<{ stdout: string; stderr: string; code: number | null }>((resolve) => {\n\t\t\t\tproc = spawn(\"gh\", [\"gist\", \"create\", \"--public=false\", tmpFile]);\n\t\t\t\tlet stdout = \"\";\n\t\t\t\tlet stderr = \"\";\n\t\t\t\tproc.stdout?.on(\"data\", (data) => {\n\t\t\t\t\tstdout += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.stderr?.on(\"data\", (data) => {\n\t\t\t\t\tstderr += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.on(\"close\", (code) => resolve({ stdout, stderr, code }));\n\t\t\t});\n\n\t\t\tif (loader.signal.aborted) return;\n\n\t\t\trestoreEditor();\n\n\t\t\tif (result.code !== 0) {\n\t\t\t\tconst errorMsg = result.stderr?.trim() || \"Unknown error\";\n\t\t\t\tthis.showError(`Failed to create gist: ${errorMsg}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Extract gist ID from the URL returned by gh\n\t\t\t// gh returns something like: https://gist.github.com/username/GIST_ID\n\t\t\tconst gistUrl = result.stdout?.trim();\n\t\t\tconst gistId = gistUrl?.split(\"/\").pop();\n\t\t\tif (!gistId) {\n\t\t\t\tthis.showError(\"Failed to parse gist ID from gh output\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Create the preview URL\n\t\t\tconst previewUrl = getShareViewerUrl(gistId);\n\t\t\tthis.showStatus(`Share URL: ${previewUrl}\\nGist: ${gistUrl}`);\n\t\t} catch (error: unknown) {\n\t\t\tif (!loader.signal.aborted) {\n\t\t\t\trestoreEditor();\n\t\t\t\tthis.showError(`Failed to create gist: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async handleCopyCommand(): Promise {\n\t\tconst text = this.session.getLastAssistantText();\n\t\tif (!text) {\n\t\t\tthis.showError(\"No agent messages to copy yet.\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tawait copyToClipboard(text);\n\t\t\tthis.showStatus(\"Copied last agent message to clipboard\");\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate handleNameCommand(text: string): void {\n\t\tconst name = text.replace(/^\\/name\\s*/, \"\").trim();\n\t\tif (!name) {\n\t\t\tconst currentName = this.sessionManager.getSessionName();\n\t\t\tif (currentName) {\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"dim\", `Session name: ${currentName}`), 1, 0));\n\t\t\t} else {\n\t\t\t\tthis.showWarning(\"Usage: /name \");\n\t\t\t}\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.session.setSessionName(name);\n\t\tconst sessionName = this.sessionManager.getSessionName();\n\t\tif (sessionName !== name) {\n\t\t\tthis.showWarning(`Session name was normalized from ${JSON.stringify(name)} to ${JSON.stringify(sessionName)}`);\n\t\t}\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"dim\", `Session name set: ${sessionName ?? name}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleSessionCommand(): void {\n\t\tconst stats = this.session.getSessionStats();\n\t\tconst sessionName = this.sessionManager.getSessionName();\n\t\tconst entries = this.sessionManager.getEntries();\n\t\tconst cacheWaste = computeCacheWaste(entries, this.session.modelRuntime);\n\n\t\t// Cost/token totals per provider/model actually used (e.g. OpenRouter `auto`\n\t\t// resolves to a concrete responseModel). Usage without model attribution is\n\t\t// grouped separately so the breakdown reconciles with the session total.\n\t\tconst usageBreakdown = getUsageCostBreakdown(entries);\n\n\t\tlet info = `${theme.bold(\"Session Info\")}\\n\\n`;\n\t\tif (sessionName) {\n\t\t\tinfo += `${theme.fg(\"dim\", \"Name:\")} ${sessionName}\\n`;\n\t\t}\n\t\tinfo += `${theme.fg(\"dim\", \"File:\")} ${stats.sessionFile ?? \"In-memory\"}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"ID:\")} ${stats.sessionId}\\n\\n`;\n\t\tinfo += `${theme.bold(\"Messages\")}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.totalMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"User:\")} ${stats.userMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Assistant:\")} ${stats.assistantMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Tools:\")} ${stats.toolCalls} calls, ${stats.toolResults} results\\n\\n`;\n\t\tinfo += `${theme.bold(\"Tokens\")}\\n`;\n\t\t// \"Input\" is the full prompt volume. With cache activity, split it into\n\t\t// cached (served from cache) vs uncached (everything else) - the only\n\t\t// provider-independent split. Cache writes, where reported, are a detail\n\t\t// of the uncached portion.\n\t\tconst { input, cacheRead, cacheWrite } = stats.tokens;\n\t\tconst promptTokens = input + cacheRead + cacheWrite;\n\t\tinfo += `${theme.fg(\"dim\", \"Input:\")} ${promptTokens.toLocaleString()}\\n`;\n\t\tif (promptTokens > 0 && (cacheRead > 0 || cacheWrite > 0)) {\n\t\t\tconst hitRate = theme.fg(\"dim\", `(${((cacheRead / promptTokens) * 100).toFixed(1)}%)`);\n\t\t\tinfo += ` ${theme.fg(\"dim\", \"Cached:\")} ${cacheRead.toLocaleString()} ${hitRate}\\n`;\n\t\t\tconst written =\n\t\t\t\tcacheWrite > 0 ? ` ${theme.fg(\"dim\", `(${cacheWrite.toLocaleString()} written to cache)`)}` : \"\";\n\t\t\tinfo += ` ${theme.fg(\"dim\", \"Uncached:\")} ${(input + cacheWrite).toLocaleString()}${written}\\n`;\n\t\t}\n\t\tinfo += `${theme.fg(\"dim\", \"Output:\")} ${stats.tokens.output.toLocaleString()}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.tokens.total.toLocaleString()}\\n`;\n\n\t\tif (stats.cost > 0 || cacheWaste.missedTokens > 0) {\n\t\t\tinfo += `\\n${theme.bold(\"Cost\")}\\n`;\n\t\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} $${stats.cost.toFixed(3)}`;\n\t\t\tif (usageBreakdown.length > 1) {\n\t\t\t\tfor (const entry of usageBreakdown) {\n\t\t\t\t\tinfo += `\\n ${theme.fg(\"dim\", `${entry.key}:`)} $${entry.cost.toFixed(3)} ${theme.fg(\"dim\", `(${formatTokens(entry.tokens)} tokens)`)}`;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (cacheWaste.missedTokens > 0) {\n\t\t\t\tconst missLabel = cacheWaste.missCount === 1 ? \"1 miss\" : `${cacheWaste.missCount} misses`;\n\t\t\t\tconst detail = `${cacheWaste.missedTokens.toLocaleString()} tokens, ${missLabel}`;\n\t\t\t\tinfo +=\n\t\t\t\t\tcacheWaste.missedCost >= 0.0001\n\t\t\t\t\t\t? `\\n${theme.fg(\"dim\", \"Cache Re-billed:\")} $${cacheWaste.missedCost.toFixed(3)} ${theme.fg(\"dim\", `(${detail})`)}`\n\t\t\t\t\t\t: `\\n${theme.fg(\"dim\", \"Cache Re-billed:\")} ${detail}`;\n\t\t\t}\n\t\t}\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(info, 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleChangelogCommand(): void {\n\t\tconst changelogPath = getChangelogPath();\n\t\tconst allEntries = parseChangelog(changelogPath);\n\n\t\tconst changelogMarkdown =\n\t\t\tallEntries.length > 0\n\t\t\t\t? allEntries\n\t\t\t\t\t\t.reverse()\n\t\t\t\t\t\t.map((e) => normalizeChangelogLinks(e.content, e))\n\t\t\t\t\t\t.join(\"\\n\\n\")\n\t\t\t\t: \"No changelog entries found.\";\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, this.getMarkdownThemeWithSettings()));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Get capitalized display string for an app keybinding action.\n\t */\n\tprivate getAppKeyDisplay(action: AppKeybinding): string {\n\t\treturn keyDisplayText(action);\n\t}\n\n\t/**\n\t * Get capitalized display string for an editor keybinding action.\n\t */\n\tprivate getEditorKeyDisplay(action: Keybinding): string {\n\t\treturn keyDisplayText(action);\n\t}\n\n\tprivate handleHotkeysCommand(): void {\n\t\t// Navigation keybindings\n\t\tconst cursorUp = this.getEditorKeyDisplay(\"tui.editor.cursorUp\");\n\t\tconst cursorDown = this.getEditorKeyDisplay(\"tui.editor.cursorDown\");\n\t\tconst cursorLeft = this.getEditorKeyDisplay(\"tui.editor.cursorLeft\");\n\t\tconst cursorRight = this.getEditorKeyDisplay(\"tui.editor.cursorRight\");\n\t\tconst cursorWordLeft = this.getEditorKeyDisplay(\"tui.editor.cursorWordLeft\");\n\t\tconst cursorWordRight = this.getEditorKeyDisplay(\"tui.editor.cursorWordRight\");\n\t\tconst cursorLineStart = this.getEditorKeyDisplay(\"tui.editor.cursorLineStart\");\n\t\tconst cursorLineEnd = this.getEditorKeyDisplay(\"tui.editor.cursorLineEnd\");\n\t\tconst jumpForward = this.getEditorKeyDisplay(\"tui.editor.jumpForward\");\n\t\tconst jumpBackward = this.getEditorKeyDisplay(\"tui.editor.jumpBackward\");\n\t\tconst pageUp = this.getEditorKeyDisplay(\"tui.editor.pageUp\");\n\t\tconst pageDown = this.getEditorKeyDisplay(\"tui.editor.pageDown\");\n\n\t\t// Editing keybindings\n\t\tconst submit = this.getEditorKeyDisplay(\"tui.input.submit\");\n\t\tconst newLine = this.getEditorKeyDisplay(\"tui.input.newLine\");\n\t\tconst deleteWordBackward = this.getEditorKeyDisplay(\"tui.editor.deleteWordBackward\");\n\t\tconst deleteWordForward = this.getEditorKeyDisplay(\"tui.editor.deleteWordForward\");\n\t\tconst deleteToLineStart = this.getEditorKeyDisplay(\"tui.editor.deleteToLineStart\");\n\t\tconst deleteToLineEnd = this.getEditorKeyDisplay(\"tui.editor.deleteToLineEnd\");\n\t\tconst yank = this.getEditorKeyDisplay(\"tui.editor.yank\");\n\t\tconst yankPop = this.getEditorKeyDisplay(\"tui.editor.yankPop\");\n\t\tconst undo = this.getEditorKeyDisplay(\"tui.editor.undo\");\n\t\tconst tab = this.getEditorKeyDisplay(\"tui.input.tab\");\n\n\t\t// App keybindings\n\t\tconst interrupt = this.getAppKeyDisplay(\"app.interrupt\");\n\t\tconst clear = this.getAppKeyDisplay(\"app.clear\");\n\t\tconst exit = this.getAppKeyDisplay(\"app.exit\");\n\t\tconst suspend = this.getAppKeyDisplay(\"app.suspend\");\n\t\tconst cycleThinkingLevel = this.getAppKeyDisplay(\"app.thinking.cycle\");\n\t\tconst cycleModelForward = this.getAppKeyDisplay(\"app.model.cycleForward\");\n\t\tconst selectModel = this.getAppKeyDisplay(\"app.model.select\");\n\t\tconst expandTools = this.getAppKeyDisplay(\"app.tools.expand\");\n\t\tconst toggleThinking = this.getAppKeyDisplay(\"app.thinking.toggle\");\n\t\tconst externalEditor = this.getAppKeyDisplay(\"app.editor.external\");\n\t\tconst cycleModelBackward = this.getAppKeyDisplay(\"app.model.cycleBackward\");\n\t\tconst copyMessage = this.getAppKeyDisplay(\"app.message.copy\");\n\t\tconst followUp = this.getAppKeyDisplay(\"app.message.followUp\");\n\t\tconst dequeue = this.getAppKeyDisplay(\"app.message.dequeue\");\n\t\tconst pasteImage = this.getAppKeyDisplay(\"app.clipboard.pasteImage\");\n\n\t\tlet hotkeys = `\n**Navigation**\n| Key | Action |\n|-----|--------|\n| \\`${cursorUp}\\` / \\`${cursorDown}\\` / \\`${cursorLeft}\\` / \\`${cursorRight}\\` | Move cursor / browse history |\n| \\`${cursorWordLeft}\\` / \\`${cursorWordRight}\\` | Move by word |\n| \\`${cursorLineStart}\\` | Start of line |\n| \\`${cursorLineEnd}\\` | End of line |\n| \\`${jumpForward}\\` | Jump forward to character |\n| \\`${jumpBackward}\\` | Jump backward to character |\n| \\`${pageUp}\\` / \\`${pageDown}\\` | Scroll by page |\n\n**Editing**\n| Key | Action |\n|-----|--------|\n| \\`${submit}\\` | Send message |\n| \\`${newLine}\\` | New line${process.platform === \"win32\" ? \" (Ctrl+Enter on Windows Terminal)\" : \"\"} |\n| \\`${deleteWordBackward}\\` | Delete word backwards |\n| \\`${deleteWordForward}\\` | Delete word forwards |\n| \\`${deleteToLineStart}\\` | Delete to start of line |\n| \\`${deleteToLineEnd}\\` | Delete to end of line |\n| \\`${yank}\\` | Paste the most-recently-deleted text |\n| \\`${yankPop}\\` | Cycle through the deleted text after pasting |\n| \\`${undo}\\` | Undo |\n\n**Other**\n| Key | Action |\n|-----|--------|\n| \\`${tab}\\` | Path completion / accept autocomplete |\n| \\`${interrupt}\\` | Cancel autocomplete / abort streaming |\n| \\`${clear}\\` | Clear editor (first) / exit (second) |\n| \\`${exit}\\` | Exit (when editor is empty) |\n| \\`${suspend}\\` | Suspend to background |\n| \\`${cycleThinkingLevel}\\` | Cycle thinking level |\n| \\`${cycleModelForward}\\` / \\`${cycleModelBackward}\\` | Cycle models |\n| \\`${selectModel}\\` | Open model selector |\n| \\`${expandTools}\\` | Toggle tool output expansion |\n| \\`${toggleThinking}\\` | Toggle thinking block visibility |\n| \\`${externalEditor}\\` | Edit message in external editor |\n| \\`${copyMessage}\\` | Copy last assistant message |\n| \\`${followUp}\\` | Queue follow-up message |\n| \\`${dequeue}\\` | Restore queued messages |\n| \\`${pasteImage}\\` | Paste image or text from clipboard |\n| \\`/\\` | Slash commands |\n| \\`!\\` | Run bash command |\n| \\`!!\\` | Run bash command (excluded from context) |\n`;\n\n\t\t// Add extension-registered shortcuts\n\t\tconst extensionRunner = this.session.extensionRunner;\n\t\tconst shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());\n\t\tif (shortcuts.size > 0) {\n\t\t\thotkeys += `\n**Extensions**\n| Key | Action |\n|-----|--------|\n`;\n\t\t\tfor (const [key, shortcut] of shortcuts) {\n\t\t\t\tconst description = shortcut.description ?? shortcut.extensionPath;\n\t\t\t\tconst keyDisplay = formatKeyText(key, { capitalize: true });\n\t\t\t\thotkeys += `| \\`${keyDisplay}\\` | ${description} |\\n`;\n\t\t\t}\n\t\t}\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"Keyboard Shortcuts\")), 1, 0));\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Markdown(hotkeys.trim(), 1, 1, this.getMarkdownThemeWithSettings()));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleClearCommand(): Promise {\n\t\tthis.clearStatusIndicator();\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.newSession();\n\t\t\tif (result.cancelled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(new Text(`${theme.fg(\"accent\", \"✓ New session started\")}`, 1, 1));\n\t\t\tthis.ui.requestRender();\n\t\t} catch (error: unknown) {\n\t\t\tawait this.handleFatalRuntimeError(\"Failed to create session\", error);\n\t\t}\n\t}\n\n\tprivate handleDebugCommand(): void {\n\t\tconst width = this.ui.terminal.columns;\n\t\tconst height = this.ui.terminal.rows;\n\t\tconst allLines = this.ui.render(width);\n\n\t\tconst debugLogPath = getDebugLogPath();\n\t\tconst debugData = [\n\t\t\t`Debug output at ${new Date().toISOString()}`,\n\t\t\t`Terminal: ${width}x${height}`,\n\t\t\t`Total lines: ${allLines.length}`,\n\t\t\t\"\",\n\t\t\t\"=== All rendered lines with visible widths ===\",\n\t\t\t...allLines.map((line, idx) => {\n\t\t\t\tconst vw = visibleWidth(line);\n\t\t\t\tconst escaped = JSON.stringify(line);\n\t\t\t\treturn `[${idx}] (w=${vw}) ${escaped}`;\n\t\t\t}),\n\t\t\t\"\",\n\t\t\t\"=== Agent messages (JSONL) ===\",\n\t\t\t...this.session.messages.map((msg) => JSON.stringify(msg)),\n\t\t\t\"\",\n\t\t].join(\"\\n\");\n\n\t\tfs.mkdirSync(path.dirname(debugLogPath), { recursive: true });\n\t\tfs.writeFileSync(debugLogPath, debugData);\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(`${theme.fg(\"accent\", \"✓ Debug log written\")}\\n${theme.fg(\"muted\", debugLogPath)}`, 1, 1),\n\t\t);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleArminSaysHi(): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new ArminComponent(this.ui));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleDementedDelves(): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new EarendilAnnouncementComponent());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleDaxnuts(): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DaxnutsComponent(this.ui));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate checkDaxnutsEasterEgg(model: { provider: string; id: string }): void {\n\t\tif (model.provider === \"opencode\" && model.id.toLowerCase().includes(\"kimi-k2.5\")) {\n\t\t\tthis.handleDaxnuts();\n\t\t}\n\t}\n\n\tprivate async handleBashCommand(command: string, excludeFromContext = false): Promise {\n\t\tconst extensionRunner = this.session.extensionRunner;\n\n\t\t// Emit user_bash event to let extensions intercept\n\t\tconst eventResult = await extensionRunner.emitUserBash({\n\t\t\ttype: \"user_bash\",\n\t\t\tcommand,\n\t\t\texcludeFromContext,\n\t\t\tcwd: this.sessionManager.getCwd(),\n\t\t});\n\n\t\t// If extension returned a full result, use it directly\n\t\tif (eventResult?.result) {\n\t\t\tconst result = eventResult.result;\n\n\t\t\t// Create UI component for display\n\t\t\tthis.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);\n\t\t\tif (this.session.isStreaming) {\n\t\t\t\tthis.pendingMessagesContainer.addChild(this.bashComponent);\n\t\t\t\tthis.pendingBashComponents.push(this.bashComponent);\n\t\t\t} else {\n\t\t\t\tthis.chatContainer.addChild(this.bashComponent);\n\t\t\t}\n\n\t\t\t// Show output and complete\n\t\t\tif (result.output) {\n\t\t\t\tthis.bashComponent.appendOutput(result.output);\n\t\t\t}\n\t\t\tthis.bashComponent.setComplete(\n\t\t\t\tresult.exitCode,\n\t\t\t\tresult.cancelled,\n\t\t\t\tresult.truncated ? ({ truncated: true, content: result.output } as TruncationResult) : undefined,\n\t\t\t\tresult.fullOutputPath,\n\t\t\t);\n\n\t\t\t// Record the result in session\n\t\t\tthis.session.recordBashResult(command, result, { excludeFromContext });\n\t\t\tthis.bashComponent = undefined;\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\t// Normal execution path (possibly with custom operations)\n\t\tconst isDeferred = this.session.isStreaming;\n\t\tthis.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);\n\n\t\tif (isDeferred) {\n\t\t\t// Show in pending area when agent is streaming\n\t\t\tthis.pendingMessagesContainer.addChild(this.bashComponent);\n\t\t\tthis.pendingBashComponents.push(this.bashComponent);\n\t\t} else {\n\t\t\t// Show in chat immediately when agent is idle\n\t\t\tthis.chatContainer.addChild(this.bashComponent);\n\t\t}\n\t\tthis.ui.requestRender();\n\n\t\ttry {\n\t\t\tconst result = await this.session.executeBash(\n\t\t\t\tcommand,\n\t\t\t\t(chunk) => {\n\t\t\t\t\tif (this.bashComponent) {\n\t\t\t\t\t\tthis.bashComponent.appendOutput(chunk);\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ excludeFromContext, operations: eventResult?.operations },\n\t\t\t);\n\n\t\t\tif (this.bashComponent) {\n\t\t\t\tthis.bashComponent.setComplete(\n\t\t\t\t\tresult.exitCode,\n\t\t\t\t\tresult.cancelled,\n\t\t\t\t\tresult.truncated ? ({ truncated: true, content: result.output } as TruncationResult) : undefined,\n\t\t\t\t\tresult.fullOutputPath,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (this.bashComponent) {\n\t\t\t\tthis.bashComponent.setComplete(undefined, false);\n\t\t\t}\n\t\t\tthis.showError(`Bash command failed: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t}\n\n\t\tthis.bashComponent = undefined;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleCompactCommand(customInstructions?: string): Promise {\n\t\tthis.clearStatusIndicator();\n\n\t\ttry {\n\t\t\tawait this.session.compact(customInstructions);\n\t\t} catch {\n\t\t\t// Ignore, will be emitted as an event\n\t\t}\n\t}\n\n\tstop(): void {\n\t\tif (this.settingsManager.getShowTerminalProgress()) {\n\t\t\tthis.ui.terminal.setProgress(false);\n\t\t}\n\t\tthis.clearStatusIndicator();\n\t\tthis.themeController.disableAutoSync();\n\t\tthis.clearExtensionTerminalInputListeners();\n\t\tthis.footer.dispose();\n\t\tthis.footerDataProvider.dispose();\n\t\tif (this.unsubscribe) {\n\t\t\tthis.unsubscribe();\n\t\t}\n\t\tif (this.isInitialized) {\n\t\t\tthis.ui.stop();\n\t\t\tthis.isInitialized = false;\n\t\t}\n\t\tthis.unregisterSignalHandlers();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/model-search.d.ts b/dist/modes/interactive/model-search.d.ts new file mode 100644 index 0000000..cd1a6fa --- /dev/null +++ b/dist/modes/interactive/model-search.d.ts @@ -0,0 +1,12 @@ +export interface ModelSearchItem { + id: string; + provider: string; + name?: string; +} +export declare function getModelSearchText(item: ModelSearchItem): string; +/** + * The /model selector search should rank exact provider-prefixed queries before proxy-provider IDs + * like openrouter/openai/gpt-5, so keep the bare model ID out of the leading position. + */ +export declare function getModelSelectorSearchText(item: ModelSearchItem): string; +//# sourceMappingURL=model-search.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/model-search.d.ts.map b/dist/modes/interactive/model-search.d.ts.map new file mode 100644 index 0000000..d8ae57f --- /dev/null +++ b/dist/modes/interactive/model-search.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"model-search.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/model-search.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,eAAe;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,eAAe,GAAG,MAAM,CAIhE;AAED;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,eAAe,GAAG,MAAM,CAIxE","sourcesContent":["export interface ModelSearchItem {\n\tid: string;\n\tprovider: string;\n\tname?: string;\n}\n\nexport function getModelSearchText(item: ModelSearchItem): string {\n\tconst { id, provider } = item;\n\tconst name = item.name ? ` ${item.name}` : \"\";\n\treturn `${id} ${provider} ${provider}/${id} ${provider} ${id}${name}`;\n}\n\n/**\n * The /model selector search should rank exact provider-prefixed queries before proxy-provider IDs\n * like openrouter/openai/gpt-5, so keep the bare model ID out of the leading position.\n */\nexport function getModelSelectorSearchText(item: ModelSearchItem): string {\n\tconst { id, provider } = item;\n\tconst name = item.name ? ` ${item.name}` : \"\";\n\treturn `${provider} ${provider}/${id} ${provider} ${id}${name}`;\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/model-search.js b/dist/modes/interactive/model-search.js new file mode 100644 index 0000000..4abd35b --- /dev/null +++ b/dist/modes/interactive/model-search.js @@ -0,0 +1,15 @@ +export function getModelSearchText(item) { + const { id, provider } = item; + const name = item.name ? ` ${item.name}` : ""; + return `${id} ${provider} ${provider}/${id} ${provider} ${id}${name}`; +} +/** + * The /model selector search should rank exact provider-prefixed queries before proxy-provider IDs + * like openrouter/openai/gpt-5, so keep the bare model ID out of the leading position. + */ +export function getModelSelectorSearchText(item) { + const { id, provider } = item; + const name = item.name ? ` ${item.name}` : ""; + return `${provider} ${provider}/${id} ${provider} ${id}${name}`; +} +//# sourceMappingURL=model-search.js.map \ No newline at end of file diff --git a/dist/modes/interactive/model-search.js.map b/dist/modes/interactive/model-search.js.map new file mode 100644 index 0000000..de7caeb --- /dev/null +++ b/dist/modes/interactive/model-search.js.map @@ -0,0 +1 @@ +{"version":3,"file":"model-search.js","sourceRoot":"","sources":["../../../src/modes/interactive/model-search.ts"],"names":[],"mappings":"AAMA,MAAM,UAAU,kBAAkB,CAAC,IAAqB,EAAU;IACjE,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;IAC9B,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAC9C,OAAO,GAAG,EAAE,IAAI,QAAQ,IAAI,QAAQ,IAAI,EAAE,IAAI,QAAQ,IAAI,EAAE,GAAG,IAAI,EAAE,CAAC;AAAA,CACtE;AAED;;;GAGG;AACH,MAAM,UAAU,0BAA0B,CAAC,IAAqB,EAAU;IACzE,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;IAC9B,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAC9C,OAAO,GAAG,QAAQ,IAAI,QAAQ,IAAI,EAAE,IAAI,QAAQ,IAAI,EAAE,GAAG,IAAI,EAAE,CAAC;AAAA,CAChE","sourcesContent":["export interface ModelSearchItem {\n\tid: string;\n\tprovider: string;\n\tname?: string;\n}\n\nexport function getModelSearchText(item: ModelSearchItem): string {\n\tconst { id, provider } = item;\n\tconst name = item.name ? ` ${item.name}` : \"\";\n\treturn `${id} ${provider} ${provider}/${id} ${provider} ${id}${name}`;\n}\n\n/**\n * The /model selector search should rank exact provider-prefixed queries before proxy-provider IDs\n * like openrouter/openai/gpt-5, so keep the bare model ID out of the leading position.\n */\nexport function getModelSelectorSearchText(item: ModelSearchItem): string {\n\tconst { id, provider } = item;\n\tconst name = item.name ? ` ${item.name}` : \"\";\n\treturn `${provider} ${provider}/${id} ${provider} ${id}${name}`;\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/theme/dark.json b/dist/modes/interactive/theme/dark.json new file mode 100644 index 0000000..d4d5041 --- /dev/null +++ b/dist/modes/interactive/theme/dark.json @@ -0,0 +1,87 @@ +{ + "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "name": "dark", + "vars": { + "cyan": "#00d7ff", + "blue": "#5f87ff", + "green": "#b5bd68", + "red": "#cc6666", + "yellow": "#ffff00", + "text": "#d4d4d4", + "gray": "#808080", + "dimGray": "#666666", + "darkGray": "#505050", + "accent": "#8abeb7", + "selectedBg": "#3a3a4a", + "userMsgBg": "#343541", + "toolPendingBg": "#282832", + "toolSuccessBg": "#283228", + "toolErrorBg": "#3c2828", + "customMsgBg": "#2d2838" + }, + "colors": { + "accent": "accent", + "border": "blue", + "borderAccent": "cyan", + "borderMuted": "darkGray", + "success": "green", + "error": "red", + "warning": "yellow", + "muted": "gray", + "dim": "dimGray", + "text": "text", + "thinkingText": "gray", + + "selectedBg": "selectedBg", + "userMessageBg": "userMsgBg", + "userMessageText": "text", + "customMessageBg": "customMsgBg", + "customMessageText": "text", + "customMessageLabel": "#9575cd", + "toolPendingBg": "toolPendingBg", + "toolSuccessBg": "toolSuccessBg", + "toolErrorBg": "toolErrorBg", + "toolTitle": "text", + "toolOutput": "gray", + + "mdHeading": "#f0c674", + "mdLink": "#81a2be", + "mdLinkUrl": "dimGray", + "mdCode": "accent", + "mdCodeBlock": "green", + "mdCodeBlockBorder": "gray", + "mdQuote": "gray", + "mdQuoteBorder": "gray", + "mdHr": "gray", + "mdListBullet": "accent", + + "toolDiffAdded": "green", + "toolDiffRemoved": "red", + "toolDiffContext": "gray", + + "syntaxComment": "#6A9955", + "syntaxKeyword": "#569CD6", + "syntaxFunction": "#DCDCAA", + "syntaxVariable": "#9CDCFE", + "syntaxString": "#CE9178", + "syntaxNumber": "#B5CEA8", + "syntaxType": "#4EC9B0", + "syntaxOperator": "#D4D4D4", + "syntaxPunctuation": "#D4D4D4", + + "thinkingOff": "darkGray", + "thinkingMinimal": "#6e6e6e", + "thinkingLow": "#5f87af", + "thinkingMedium": "#81a2be", + "thinkingHigh": "#b294bb", + "thinkingXhigh": "#d183e8", + "thinkingMax": "#ff5fff", + + "bashMode": "green" + }, + "export": { + "pageBg": "#18181e", + "cardBg": "#1e1e24", + "infoBg": "#3c3728" + } +} diff --git a/dist/modes/interactive/theme/light.json b/dist/modes/interactive/theme/light.json new file mode 100644 index 0000000..ef0d5c3 --- /dev/null +++ b/dist/modes/interactive/theme/light.json @@ -0,0 +1,86 @@ +{ + "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "name": "light", + "vars": { + "teal": "#5a8080", + "blue": "#547da7", + "green": "#588458", + "red": "#aa5555", + "yellow": "#9a7326", + "text": "#1f2328", + "mediumGray": "#6c6c6c", + "dimGray": "#767676", + "lightGray": "#b0b0b0", + "selectedBg": "#d0d0e0", + "userMsgBg": "#e8e8e8", + "toolPendingBg": "#e8e8f0", + "toolSuccessBg": "#e8f0e8", + "toolErrorBg": "#f0e8e8", + "customMsgBg": "#ede7f6" + }, + "colors": { + "accent": "teal", + "border": "blue", + "borderAccent": "teal", + "borderMuted": "lightGray", + "success": "green", + "error": "red", + "warning": "yellow", + "muted": "mediumGray", + "dim": "dimGray", + "text": "text", + "thinkingText": "mediumGray", + + "selectedBg": "selectedBg", + "userMessageBg": "userMsgBg", + "userMessageText": "text", + "customMessageBg": "customMsgBg", + "customMessageText": "text", + "customMessageLabel": "#7e57c2", + "toolPendingBg": "toolPendingBg", + "toolSuccessBg": "toolSuccessBg", + "toolErrorBg": "toolErrorBg", + "toolTitle": "text", + "toolOutput": "mediumGray", + + "mdHeading": "yellow", + "mdLink": "blue", + "mdLinkUrl": "dimGray", + "mdCode": "teal", + "mdCodeBlock": "green", + "mdCodeBlockBorder": "mediumGray", + "mdQuote": "mediumGray", + "mdQuoteBorder": "mediumGray", + "mdHr": "mediumGray", + "mdListBullet": "green", + + "toolDiffAdded": "green", + "toolDiffRemoved": "red", + "toolDiffContext": "mediumGray", + + "syntaxComment": "#008000", + "syntaxKeyword": "#0000FF", + "syntaxFunction": "#795E26", + "syntaxVariable": "#001080", + "syntaxString": "#A31515", + "syntaxNumber": "#098658", + "syntaxType": "#267F99", + "syntaxOperator": "#000000", + "syntaxPunctuation": "#000000", + + "thinkingOff": "lightGray", + "thinkingMinimal": "#767676", + "thinkingLow": "blue", + "thinkingMedium": "teal", + "thinkingHigh": "#875f87", + "thinkingXhigh": "#8b008b", + "thinkingMax": "#af005f", + + "bashMode": "green" + }, + "export": { + "pageBg": "#f8f8f8", + "cardBg": "#ffffff", + "infoBg": "#fffae6" + } +} diff --git a/dist/modes/interactive/theme/theme-controller.d.ts b/dist/modes/interactive/theme/theme-controller.d.ts new file mode 100644 index 0000000..a318fa6 --- /dev/null +++ b/dist/modes/interactive/theme/theme-controller.d.ts @@ -0,0 +1,29 @@ +import type { TUI } from "@earendil-works/pi-tui"; +import type { SettingsManager } from "../../../core/settings-manager.ts"; +import { type TerminalTheme, type Theme } from "./theme.ts"; +type ThemeResult = { + success: boolean; + error?: string; +}; +export declare class InteractiveThemeController { + private readonly ui; + private readonly settingsManager; + private readonly showError; + private readonly onChanged; + private terminalTheme; + private activeThemeName; + private autoSyncEnabled; + constructor(ui: TUI, settingsManager: SettingsManager, showError: (message: string) => void, onChanged: () => void); + applyFromSettings(): Promise; + setThemeName(themeName: string, showError?: boolean): ThemeResult; + setThemeInstance(themeInstance: Theme): ThemeResult; + preview(themeSettingOrName: string): void; + disableAutoSync(): void; + getTerminalTheme(): TerminalTheme; + private applyThemeName; + private notifyChanged; + private setAutoSync; + private applyTerminalTheme; +} +export {}; +//# sourceMappingURL=theme-controller.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/theme/theme-controller.d.ts.map b/dist/modes/interactive/theme/theme-controller.d.ts.map new file mode 100644 index 0000000..e5c12ec --- /dev/null +++ b/dist/modes/interactive/theme/theme-controller.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"theme-controller.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/theme/theme-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAClD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EASN,KAAK,aAAa,EAClB,KAAK,KAAK,EACV,MAAM,YAAY,CAAC;AAEpB,KAAK,WAAW,GAAG;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAExD,qBAAa,0BAA0B;IACtC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAM;IACzB,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAkB;IAClD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA4B;IACtD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAa;IACvC,OAAO,CAAC,aAAa,CAA0D;IAC/E,OAAO,CAAC,eAAe,CAAqB;IAC5C,OAAO,CAAC,eAAe,CAAS;IAEhC,YAAY,EAAE,EAAE,GAAG,EAAE,eAAe,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,EAAE,SAAS,EAAE,MAAM,IAAI,EAQjH;IAEK,iBAAiB,IAAI,OAAO,CAAC,IAAI,CAAC,CAuBvC;IAED,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,UAAQ,GAAG,WAAW,CAG9D;IAED,gBAAgB,CAAC,aAAa,EAAE,KAAK,GAAG,WAAW,CAMlD;IAED,OAAO,CAAC,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAOxC;IAED,eAAe,IAAI,IAAI,CAEtB;IAED,gBAAgB,IAAI,aAAa,CAEhC;IAED,OAAO,CAAC,cAAc;IAUtB,OAAO,CAAC,aAAa;IAKrB,OAAO,CAAC,WAAW;IAMnB,OAAO,CAAC,kBAAkB;CAa1B","sourcesContent":["import type { TUI } from \"@earendil-works/pi-tui\";\nimport type { SettingsManager } from \"../../../core/settings-manager.ts\";\nimport {\n\tdetectTerminalBackgroundFromEnv,\n\tdetectTerminalBackgroundTheme,\n\tdetectTerminalThemeForAuto,\n\tinitTheme,\n\tparseAutoThemeSetting,\n\tresolveThemeSetting,\n\tsetTheme,\n\tsetThemeInstance,\n\ttype TerminalTheme,\n\ttype Theme,\n} from \"./theme.ts\";\n\ntype ThemeResult = { success: boolean; error?: string };\n\nexport class InteractiveThemeController {\n\tprivate readonly ui: TUI;\n\tprivate readonly settingsManager: SettingsManager;\n\tprivate readonly showError: (message: string) => void;\n\tprivate readonly onChanged: () => void;\n\tprivate terminalTheme: TerminalTheme = detectTerminalBackgroundFromEnv().theme;\n\tprivate activeThemeName: string | undefined;\n\tprivate autoSyncEnabled = false;\n\n\tconstructor(ui: TUI, settingsManager: SettingsManager, showError: (message: string) => void, onChanged: () => void) {\n\t\tthis.ui = ui;\n\t\tthis.settingsManager = settingsManager;\n\t\tthis.showError = showError;\n\t\tthis.onChanged = onChanged;\n\t\tthis.activeThemeName = resolveThemeSetting(this.settingsManager.getThemeSetting(), this.terminalTheme);\n\t\tinitTheme(this.activeThemeName, true);\n\t\tthis.ui.onTerminalColorSchemeChange((terminalTheme) => this.applyTerminalTheme(terminalTheme));\n\t}\n\n\tasync applyFromSettings(): Promise {\n\t\tconst themeSetting = this.settingsManager.getThemeSetting();\n\t\tconst autoTheme = parseAutoThemeSetting(themeSetting);\n\t\tif (autoTheme) {\n\t\t\tthis.terminalTheme = await detectTerminalThemeForAuto({ ui: this.ui, timeoutMs: 100 });\n\t\t\tthis.setAutoSync(true);\n\t\t\tthis.applyThemeName(this.terminalTheme === \"light\" ? autoTheme.lightTheme : autoTheme.darkTheme, true);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.setAutoSync(false);\n\t\tif (themeSetting !== undefined) {\n\t\t\tthis.applyThemeName(themeSetting, true);\n\t\t\treturn;\n\t\t}\n\n\t\tconst detection = await detectTerminalBackgroundTheme({ ui: this.ui, timeoutMs: 100 });\n\t\tthis.terminalTheme = detection.theme;\n\t\tif (!this.applyThemeName(detection.theme).success) return;\n\t\tif (detection.confidence === \"high\") {\n\t\t\tthis.settingsManager.setTheme(detection.theme);\n\t\t\tawait this.settingsManager.flush();\n\t\t}\n\t}\n\n\tsetThemeName(themeName: string, showError = false): ThemeResult {\n\t\tthis.setAutoSync(false);\n\t\treturn this.applyThemeName(themeName, showError);\n\t}\n\n\tsetThemeInstance(themeInstance: Theme): ThemeResult {\n\t\tthis.setAutoSync(false);\n\t\tsetThemeInstance(themeInstance);\n\t\tthis.activeThemeName = \"\";\n\t\tthis.notifyChanged();\n\t\treturn { success: true };\n\t}\n\n\tpreview(themeSettingOrName: string): void {\n\t\tconst themeName = resolveThemeSetting(themeSettingOrName, this.terminalTheme) ?? this.activeThemeName;\n\t\tif (!themeName) return;\n\t\tif (setTheme(themeName, true).success) {\n\t\t\tthis.ui.invalidate();\n\t\t\tthis.ui.requestRender();\n\t\t}\n\t}\n\n\tdisableAutoSync(): void {\n\t\tthis.setAutoSync(false);\n\t}\n\n\tgetTerminalTheme(): TerminalTheme {\n\t\treturn this.terminalTheme;\n\t}\n\n\tprivate applyThemeName(themeName: string, showError = false): ThemeResult {\n\t\tconst result = setTheme(themeName, true);\n\t\tthis.activeThemeName = result.success ? themeName : \"dark\";\n\t\tthis.notifyChanged();\n\t\tif (!result.success && showError) {\n\t\t\tthis.showError(`Failed to load theme \"${themeName}\": ${result.error}\\nFell back to dark theme.`);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate notifyChanged(): void {\n\t\tthis.ui.invalidate();\n\t\tthis.onChanged();\n\t}\n\n\tprivate setAutoSync(enabled: boolean): void {\n\t\tif (this.autoSyncEnabled === enabled) return;\n\t\tthis.autoSyncEnabled = enabled;\n\t\tthis.ui.setTerminalColorSchemeNotifications(enabled);\n\t}\n\n\tprivate applyTerminalTheme(terminalTheme: TerminalTheme): void {\n\t\tif (!this.autoSyncEnabled) return;\n\t\tthis.terminalTheme = terminalTheme;\n\t\tconst autoTheme = parseAutoThemeSetting(this.settingsManager.getThemeSetting());\n\t\tif (!autoTheme) {\n\t\t\tthis.setAutoSync(false);\n\t\t\treturn;\n\t\t}\n\t\tconst themeName = terminalTheme === \"light\" ? autoTheme.lightTheme : autoTheme.darkTheme;\n\t\tif (themeName !== this.activeThemeName) {\n\t\t\tthis.applyThemeName(themeName);\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/theme/theme-controller.js b/dist/modes/interactive/theme/theme-controller.js new file mode 100644 index 0000000..40b8002 --- /dev/null +++ b/dist/modes/interactive/theme/theme-controller.js @@ -0,0 +1,102 @@ +import { detectTerminalBackgroundFromEnv, detectTerminalBackgroundTheme, detectTerminalThemeForAuto, initTheme, parseAutoThemeSetting, resolveThemeSetting, setTheme, setThemeInstance, } from "./theme.js"; +export class InteractiveThemeController { + ui; + settingsManager; + showError; + onChanged; + terminalTheme = detectTerminalBackgroundFromEnv().theme; + activeThemeName; + autoSyncEnabled = false; + constructor(ui, settingsManager, showError, onChanged) { + this.ui = ui; + this.settingsManager = settingsManager; + this.showError = showError; + this.onChanged = onChanged; + this.activeThemeName = resolveThemeSetting(this.settingsManager.getThemeSetting(), this.terminalTheme); + initTheme(this.activeThemeName, true); + this.ui.onTerminalColorSchemeChange((terminalTheme) => this.applyTerminalTheme(terminalTheme)); + } + async applyFromSettings() { + const themeSetting = this.settingsManager.getThemeSetting(); + const autoTheme = parseAutoThemeSetting(themeSetting); + if (autoTheme) { + this.terminalTheme = await detectTerminalThemeForAuto({ ui: this.ui, timeoutMs: 100 }); + this.setAutoSync(true); + this.applyThemeName(this.terminalTheme === "light" ? autoTheme.lightTheme : autoTheme.darkTheme, true); + return; + } + this.setAutoSync(false); + if (themeSetting !== undefined) { + this.applyThemeName(themeSetting, true); + return; + } + const detection = await detectTerminalBackgroundTheme({ ui: this.ui, timeoutMs: 100 }); + this.terminalTheme = detection.theme; + if (!this.applyThemeName(detection.theme).success) + return; + if (detection.confidence === "high") { + this.settingsManager.setTheme(detection.theme); + await this.settingsManager.flush(); + } + } + setThemeName(themeName, showError = false) { + this.setAutoSync(false); + return this.applyThemeName(themeName, showError); + } + setThemeInstance(themeInstance) { + this.setAutoSync(false); + setThemeInstance(themeInstance); + this.activeThemeName = ""; + this.notifyChanged(); + return { success: true }; + } + preview(themeSettingOrName) { + const themeName = resolveThemeSetting(themeSettingOrName, this.terminalTheme) ?? this.activeThemeName; + if (!themeName) + return; + if (setTheme(themeName, true).success) { + this.ui.invalidate(); + this.ui.requestRender(); + } + } + disableAutoSync() { + this.setAutoSync(false); + } + getTerminalTheme() { + return this.terminalTheme; + } + applyThemeName(themeName, showError = false) { + const result = setTheme(themeName, true); + this.activeThemeName = result.success ? themeName : "dark"; + this.notifyChanged(); + if (!result.success && showError) { + this.showError(`Failed to load theme "${themeName}": ${result.error}\nFell back to dark theme.`); + } + return result; + } + notifyChanged() { + this.ui.invalidate(); + this.onChanged(); + } + setAutoSync(enabled) { + if (this.autoSyncEnabled === enabled) + return; + this.autoSyncEnabled = enabled; + this.ui.setTerminalColorSchemeNotifications(enabled); + } + applyTerminalTheme(terminalTheme) { + if (!this.autoSyncEnabled) + return; + this.terminalTheme = terminalTheme; + const autoTheme = parseAutoThemeSetting(this.settingsManager.getThemeSetting()); + if (!autoTheme) { + this.setAutoSync(false); + return; + } + const themeName = terminalTheme === "light" ? autoTheme.lightTheme : autoTheme.darkTheme; + if (themeName !== this.activeThemeName) { + this.applyThemeName(themeName); + } + } +} +//# sourceMappingURL=theme-controller.js.map \ No newline at end of file diff --git a/dist/modes/interactive/theme/theme-controller.js.map b/dist/modes/interactive/theme/theme-controller.js.map new file mode 100644 index 0000000..5d8eca3 --- /dev/null +++ b/dist/modes/interactive/theme/theme-controller.js.map @@ -0,0 +1 @@ +{"version":3,"file":"theme-controller.js","sourceRoot":"","sources":["../../../../src/modes/interactive/theme/theme-controller.ts"],"names":[],"mappings":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E,OAAO;QAC7C,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC;QAC/B,IAAI,CAAC,EAAE,CAAC,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAAA,CACrD;IAEO,kBAAkB,CAAC,aAA4B,EAAQ;QAC9D,IAAI,CAAC,IAAI,CAAC,eAAe;YAAE,OAAO;QAClC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,MAAM,SAAS,GAAG,qBAAqB,CAAC,IAAI,CAAC,eAAe,CAAC,eAAe,EAAE,CAAC,CAAC;QAChF,IAAI,CAAC,SAAS,EAAE,CAAC;YAChB,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;YACxB,OAAO;QACR,CAAC;QACD,MAAM,SAAS,GAAG,aAAa,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC;QACzF,IAAI,SAAS,KAAK,IAAI,CAAC,eAAe,EAAE,CAAC;YACxC,IAAI,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;QAChC,CAAC;IAAA,CACD;CACD","sourcesContent":["import type { TUI } from \"@earendil-works/pi-tui\";\nimport type { SettingsManager } from \"../../../core/settings-manager.ts\";\nimport {\n\tdetectTerminalBackgroundFromEnv,\n\tdetectTerminalBackgroundTheme,\n\tdetectTerminalThemeForAuto,\n\tinitTheme,\n\tparseAutoThemeSetting,\n\tresolveThemeSetting,\n\tsetTheme,\n\tsetThemeInstance,\n\ttype TerminalTheme,\n\ttype Theme,\n} from \"./theme.ts\";\n\ntype ThemeResult = { success: boolean; error?: string };\n\nexport class InteractiveThemeController {\n\tprivate readonly ui: TUI;\n\tprivate readonly settingsManager: SettingsManager;\n\tprivate readonly showError: (message: string) => void;\n\tprivate readonly onChanged: () => void;\n\tprivate terminalTheme: TerminalTheme = detectTerminalBackgroundFromEnv().theme;\n\tprivate activeThemeName: string | undefined;\n\tprivate autoSyncEnabled = false;\n\n\tconstructor(ui: TUI, settingsManager: SettingsManager, showError: (message: string) => void, onChanged: () => void) {\n\t\tthis.ui = ui;\n\t\tthis.settingsManager = settingsManager;\n\t\tthis.showError = showError;\n\t\tthis.onChanged = onChanged;\n\t\tthis.activeThemeName = resolveThemeSetting(this.settingsManager.getThemeSetting(), this.terminalTheme);\n\t\tinitTheme(this.activeThemeName, true);\n\t\tthis.ui.onTerminalColorSchemeChange((terminalTheme) => this.applyTerminalTheme(terminalTheme));\n\t}\n\n\tasync applyFromSettings(): Promise {\n\t\tconst themeSetting = this.settingsManager.getThemeSetting();\n\t\tconst autoTheme = parseAutoThemeSetting(themeSetting);\n\t\tif (autoTheme) {\n\t\t\tthis.terminalTheme = await detectTerminalThemeForAuto({ ui: this.ui, timeoutMs: 100 });\n\t\t\tthis.setAutoSync(true);\n\t\t\tthis.applyThemeName(this.terminalTheme === \"light\" ? autoTheme.lightTheme : autoTheme.darkTheme, true);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.setAutoSync(false);\n\t\tif (themeSetting !== undefined) {\n\t\t\tthis.applyThemeName(themeSetting, true);\n\t\t\treturn;\n\t\t}\n\n\t\tconst detection = await detectTerminalBackgroundTheme({ ui: this.ui, timeoutMs: 100 });\n\t\tthis.terminalTheme = detection.theme;\n\t\tif (!this.applyThemeName(detection.theme).success) return;\n\t\tif (detection.confidence === \"high\") {\n\t\t\tthis.settingsManager.setTheme(detection.theme);\n\t\t\tawait this.settingsManager.flush();\n\t\t}\n\t}\n\n\tsetThemeName(themeName: string, showError = false): ThemeResult {\n\t\tthis.setAutoSync(false);\n\t\treturn this.applyThemeName(themeName, showError);\n\t}\n\n\tsetThemeInstance(themeInstance: Theme): ThemeResult {\n\t\tthis.setAutoSync(false);\n\t\tsetThemeInstance(themeInstance);\n\t\tthis.activeThemeName = \"\";\n\t\tthis.notifyChanged();\n\t\treturn { success: true };\n\t}\n\n\tpreview(themeSettingOrName: string): void {\n\t\tconst themeName = resolveThemeSetting(themeSettingOrName, this.terminalTheme) ?? this.activeThemeName;\n\t\tif (!themeName) return;\n\t\tif (setTheme(themeName, true).success) {\n\t\t\tthis.ui.invalidate();\n\t\t\tthis.ui.requestRender();\n\t\t}\n\t}\n\n\tdisableAutoSync(): void {\n\t\tthis.setAutoSync(false);\n\t}\n\n\tgetTerminalTheme(): TerminalTheme {\n\t\treturn this.terminalTheme;\n\t}\n\n\tprivate applyThemeName(themeName: string, showError = false): ThemeResult {\n\t\tconst result = setTheme(themeName, true);\n\t\tthis.activeThemeName = result.success ? themeName : \"dark\";\n\t\tthis.notifyChanged();\n\t\tif (!result.success && showError) {\n\t\t\tthis.showError(`Failed to load theme \"${themeName}\": ${result.error}\\nFell back to dark theme.`);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate notifyChanged(): void {\n\t\tthis.ui.invalidate();\n\t\tthis.onChanged();\n\t}\n\n\tprivate setAutoSync(enabled: boolean): void {\n\t\tif (this.autoSyncEnabled === enabled) return;\n\t\tthis.autoSyncEnabled = enabled;\n\t\tthis.ui.setTerminalColorSchemeNotifications(enabled);\n\t}\n\n\tprivate applyTerminalTheme(terminalTheme: TerminalTheme): void {\n\t\tif (!this.autoSyncEnabled) return;\n\t\tthis.terminalTheme = terminalTheme;\n\t\tconst autoTheme = parseAutoThemeSetting(this.settingsManager.getThemeSetting());\n\t\tif (!autoTheme) {\n\t\t\tthis.setAutoSync(false);\n\t\t\treturn;\n\t\t}\n\t\tconst themeName = terminalTheme === \"light\" ? autoTheme.lightTheme : autoTheme.darkTheme;\n\t\tif (themeName !== this.activeThemeName) {\n\t\t\tthis.applyThemeName(themeName);\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/theme/theme-schema.json b/dist/modes/interactive/theme/theme-schema.json new file mode 100644 index 0000000..4ab36a7 --- /dev/null +++ b/dist/modes/interactive/theme/theme-schema.json @@ -0,0 +1,340 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Pi Coding Agent Theme", + "description": "Theme schema for Pi coding agent", + "type": "object", + "required": ["name", "colors"], + "properties": { + "$schema": { + "type": "string", + "description": "JSON schema reference" + }, + "name": { + "type": "string", + "pattern": "^[^/]+$", + "description": "Theme name. Must not contain '/' because it is reserved for automatic light/dark theme settings." + }, + "vars": { + "type": "object", + "description": "Reusable color variables", + "additionalProperties": { + "oneOf": [ + { + "type": "string", + "description": "Hex color (#RRGGBB), variable reference, or empty string for terminal default" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255, + "description": "256-color palette index (0-255)" + } + ] + } + }, + "colors": { + "type": "object", + "description": "Theme color definitions (thinkingMax is optional and falls back to thinkingXhigh)", + "required": [ + "accent", + "border", + "borderAccent", + "borderMuted", + "success", + "error", + "warning", + "muted", + "dim", + "text", + "thinkingText", + "selectedBg", + "userMessageBg", + "userMessageText", + "customMessageBg", + "customMessageText", + "customMessageLabel", + "toolPendingBg", + "toolSuccessBg", + "toolErrorBg", + "toolTitle", + "toolOutput", + "mdHeading", + "mdLink", + "mdLinkUrl", + "mdCode", + "mdCodeBlock", + "mdCodeBlockBorder", + "mdQuote", + "mdQuoteBorder", + "mdHr", + "mdListBullet", + "toolDiffAdded", + "toolDiffRemoved", + "toolDiffContext", + "syntaxComment", + "syntaxKeyword", + "syntaxFunction", + "syntaxVariable", + "syntaxString", + "syntaxNumber", + "syntaxType", + "syntaxOperator", + "syntaxPunctuation", + "thinkingOff", + "thinkingMinimal", + "thinkingLow", + "thinkingMedium", + "thinkingHigh", + "thinkingXhigh", + "bashMode" + ], + "properties": { + "accent": { + "$ref": "#/$defs/colorValue", + "description": "Primary accent color (logo, selected items, cursor)" + }, + "border": { + "$ref": "#/$defs/colorValue", + "description": "Normal borders" + }, + "borderAccent": { + "$ref": "#/$defs/colorValue", + "description": "Highlighted borders" + }, + "borderMuted": { + "$ref": "#/$defs/colorValue", + "description": "Subtle borders" + }, + "success": { + "$ref": "#/$defs/colorValue", + "description": "Success states" + }, + "error": { + "$ref": "#/$defs/colorValue", + "description": "Error states" + }, + "warning": { + "$ref": "#/$defs/colorValue", + "description": "Warning states" + }, + "muted": { + "$ref": "#/$defs/colorValue", + "description": "Secondary/dimmed text" + }, + "dim": { + "$ref": "#/$defs/colorValue", + "description": "Very dimmed text (more subtle than muted)" + }, + "text": { + "$ref": "#/$defs/colorValue", + "description": "Default text color (usually empty string)" + }, + "thinkingText": { + "$ref": "#/$defs/colorValue", + "description": "Thinking block text color" + }, + "selectedBg": { + "$ref": "#/$defs/colorValue", + "description": "Selected item background" + }, + "userMessageBg": { + "$ref": "#/$defs/colorValue", + "description": "User message background" + }, + "userMessageText": { + "$ref": "#/$defs/colorValue", + "description": "User message text color" + }, + "customMessageBg": { + "$ref": "#/$defs/colorValue", + "description": "Custom message background (hook-injected messages)" + }, + "customMessageText": { + "$ref": "#/$defs/colorValue", + "description": "Custom message text color" + }, + "customMessageLabel": { + "$ref": "#/$defs/colorValue", + "description": "Custom message type label color" + }, + "toolPendingBg": { + "$ref": "#/$defs/colorValue", + "description": "Tool execution box (pending state)" + }, + "toolSuccessBg": { + "$ref": "#/$defs/colorValue", + "description": "Tool execution box (success state)" + }, + "toolErrorBg": { + "$ref": "#/$defs/colorValue", + "description": "Tool execution box (error state)" + }, + "toolTitle": { + "$ref": "#/$defs/colorValue", + "description": "Tool execution box title color" + }, + "toolOutput": { + "$ref": "#/$defs/colorValue", + "description": "Tool execution box output text color" + }, + "mdHeading": { + "$ref": "#/$defs/colorValue", + "description": "Markdown heading text" + }, + "mdLink": { + "$ref": "#/$defs/colorValue", + "description": "Markdown link text" + }, + "mdLinkUrl": { + "$ref": "#/$defs/colorValue", + "description": "Markdown link URL" + }, + "mdCode": { + "$ref": "#/$defs/colorValue", + "description": "Markdown inline code" + }, + "mdCodeBlock": { + "$ref": "#/$defs/colorValue", + "description": "Markdown code block content" + }, + "mdCodeBlockBorder": { + "$ref": "#/$defs/colorValue", + "description": "Markdown code block fences" + }, + "mdQuote": { + "$ref": "#/$defs/colorValue", + "description": "Markdown blockquote text" + }, + "mdQuoteBorder": { + "$ref": "#/$defs/colorValue", + "description": "Markdown blockquote border" + }, + "mdHr": { + "$ref": "#/$defs/colorValue", + "description": "Markdown horizontal rule" + }, + "mdListBullet": { + "$ref": "#/$defs/colorValue", + "description": "Markdown list bullets/numbers" + }, + "toolDiffAdded": { + "$ref": "#/$defs/colorValue", + "description": "Added lines in tool diffs" + }, + "toolDiffRemoved": { + "$ref": "#/$defs/colorValue", + "description": "Removed lines in tool diffs" + }, + "toolDiffContext": { + "$ref": "#/$defs/colorValue", + "description": "Context lines in tool diffs" + }, + "syntaxComment": { + "$ref": "#/$defs/colorValue", + "description": "Syntax highlighting: comments" + }, + "syntaxKeyword": { + "$ref": "#/$defs/colorValue", + "description": "Syntax highlighting: keywords" + }, + "syntaxFunction": { + "$ref": "#/$defs/colorValue", + "description": "Syntax highlighting: function names" + }, + "syntaxVariable": { + "$ref": "#/$defs/colorValue", + "description": "Syntax highlighting: variable names" + }, + "syntaxString": { + "$ref": "#/$defs/colorValue", + "description": "Syntax highlighting: string literals" + }, + "syntaxNumber": { + "$ref": "#/$defs/colorValue", + "description": "Syntax highlighting: number literals" + }, + "syntaxType": { + "$ref": "#/$defs/colorValue", + "description": "Syntax highlighting: type names" + }, + "syntaxOperator": { + "$ref": "#/$defs/colorValue", + "description": "Syntax highlighting: operators" + }, + "syntaxPunctuation": { + "$ref": "#/$defs/colorValue", + "description": "Syntax highlighting: punctuation" + }, + "thinkingOff": { + "$ref": "#/$defs/colorValue", + "description": "Thinking level border: off" + }, + "thinkingMinimal": { + "$ref": "#/$defs/colorValue", + "description": "Thinking level border: minimal" + }, + "thinkingLow": { + "$ref": "#/$defs/colorValue", + "description": "Thinking level border: low" + }, + "thinkingMedium": { + "$ref": "#/$defs/colorValue", + "description": "Thinking level border: medium" + }, + "thinkingHigh": { + "$ref": "#/$defs/colorValue", + "description": "Thinking level border: high" + }, + "thinkingXhigh": { + "$ref": "#/$defs/colorValue", + "description": "Thinking level border: xhigh" + }, + "thinkingMax": { + "$ref": "#/$defs/colorValue", + "description": "Thinking level border: max (falls back to thinkingXhigh when omitted)" + }, + "bashMode": { + "$ref": "#/$defs/colorValue", + "description": "Editor border color in bash mode" + } + }, + "additionalProperties": false + }, + "export": { + "type": "object", + "description": "Optional colors for HTML export (defaults derived from userMessageBg if not specified)", + "properties": { + "pageBg": { + "$ref": "#/$defs/colorValue", + "description": "Page background color" + }, + "cardBg": { + "$ref": "#/$defs/colorValue", + "description": "Card/container background color" + }, + "infoBg": { + "$ref": "#/$defs/colorValue", + "description": "Info sections background (system prompt, notices)" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false, + "$defs": { + "colorValue": { + "oneOf": [ + { + "type": "string", + "description": "Hex color (#RRGGBB), variable reference, or empty string for terminal default" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 255, + "description": "256-color palette index (0-255)" + } + ] + } + } +} diff --git a/dist/modes/interactive/theme/theme.d.ts b/dist/modes/interactive/theme/theme.d.ts new file mode 100644 index 0000000..71372be --- /dev/null +++ b/dist/modes/interactive/theme/theme.d.ts @@ -0,0 +1,120 @@ +import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; +import { type EditorTheme, type MarkdownTheme, type RgbColor, type SelectListTheme, type SettingsListTheme } from "@earendil-works/pi-tui"; +import type { SourceInfo } from "../../../core/source-info.ts"; +export type ThemeColor = "accent" | "border" | "borderAccent" | "borderMuted" | "success" | "error" | "warning" | "muted" | "dim" | "text" | "thinkingText" | "userMessageText" | "customMessageText" | "customMessageLabel" | "toolTitle" | "toolOutput" | "mdHeading" | "mdLink" | "mdLinkUrl" | "mdCode" | "mdCodeBlock" | "mdCodeBlockBorder" | "mdQuote" | "mdQuoteBorder" | "mdHr" | "mdListBullet" | "toolDiffAdded" | "toolDiffRemoved" | "toolDiffContext" | "syntaxComment" | "syntaxKeyword" | "syntaxFunction" | "syntaxVariable" | "syntaxString" | "syntaxNumber" | "syntaxType" | "syntaxOperator" | "syntaxPunctuation" | "thinkingOff" | "thinkingMinimal" | "thinkingLow" | "thinkingMedium" | "thinkingHigh" | "thinkingXhigh" | "thinkingMax" | "bashMode"; +export type ThemeBg = "selectedBg" | "userMessageBg" | "customMessageBg" | "toolPendingBg" | "toolSuccessBg" | "toolErrorBg"; +type ColorMode = "truecolor" | "256color"; +export declare class Theme { + readonly name?: string; + readonly sourcePath?: string; + sourceInfo?: SourceInfo; + private fgColors; + private bgColors; + private mode; + constructor(fgColors: Record, bgColors: Record, mode: ColorMode, options?: { + name?: string; + sourcePath?: string; + sourceInfo?: SourceInfo; + }); + fg(color: ThemeColor, text: string): string; + bg(color: ThemeBg, text: string): string; + bold(text: string): string; + italic(text: string): string; + underline(text: string): string; + inverse(text: string): string; + strikethrough(text: string): string; + getFgAnsi(color: ThemeColor): string; + getBgAnsi(color: ThemeBg): string; + getColorMode(): ColorMode; + getThinkingBorderColor(level: ThinkingLevel): (str: string) => string; + getBashModeBorderColor(): (str: string) => string; +} +export declare function getAvailableThemes(): string[]; +export interface ThemeInfo { + name: string; + path: string | undefined; +} +export declare function getAvailableThemesWithPaths(): ThemeInfo[]; +export declare function loadThemeFromPath(themePath: string, mode?: ColorMode): Theme; +export declare function getThemeByName(name: string): Theme | undefined; +export type TerminalTheme = "dark" | "light"; +export declare function parseAutoThemeSetting(themeSetting: string | undefined): { + lightTheme: string; + darkTheme: string; +} | undefined; +export declare function resolveThemeSetting(themeSetting: string | undefined, terminalTheme: TerminalTheme): string | undefined; +export interface TerminalThemeDetection { + theme: TerminalTheme; + source: "terminal background" | "COLORFGBG" | "fallback"; + detail: string; + confidence: "high" | "low"; +} +export interface TerminalThemeDetectionOptions { + env?: NodeJS.ProcessEnv; +} +export interface TerminalBackgroundThemeDetector { + queryTerminalBackgroundColor({ timeoutMs }: { + timeoutMs: number; + }): Promise; +} +export interface TerminalAutoThemeDetector extends TerminalBackgroundThemeDetector { + queryTerminalColorScheme?({ timeoutMs }: { + timeoutMs: number; + }): Promise; +} +export interface TerminalBackgroundThemeDetectionOptions extends TerminalThemeDetectionOptions { + ui: TerminalBackgroundThemeDetector; + timeoutMs: number; +} +export interface TerminalAutoThemeDetectionOptions extends TerminalThemeDetectionOptions { + ui: TerminalAutoThemeDetector; + timeoutMs: number; +} +export declare function getThemeForRgbColor(rgb: RgbColor): TerminalTheme; +export declare function detectTerminalBackgroundFromEnv(options?: TerminalThemeDetectionOptions): TerminalThemeDetection; +export declare function detectTerminalBackgroundTheme({ ui, timeoutMs, env }: TerminalBackgroundThemeDetectionOptions): Promise; +export declare function detectTerminalThemeForAuto({ ui, timeoutMs, env }: TerminalAutoThemeDetectionOptions): Promise; +export declare function getDefaultTheme(): string; +export declare const theme: Theme; +export declare function setRegisteredThemes(themes: Theme[]): void; +export declare function initTheme(themeName?: string, enableWatcher?: boolean): void; +export declare function setTheme(name: string, enableWatcher?: boolean): { + success: boolean; + error?: string; +}; +export declare function setThemeInstance(themeInstance: Theme): void; +export declare function onThemeChange(callback: () => void): void; +export declare function stopThemeWatcher(): void; +/** + * Get resolved theme colors as CSS-compatible hex strings. + * Used by HTML export to generate CSS custom properties. + */ +export declare function getResolvedThemeColors(themeName?: string): Record; +/** + * Check if a theme is a "light" theme (for CSS that needs light/dark variants). + */ +export declare function isLightTheme(themeName?: string): boolean; +/** + * Get explicit export colors from theme JSON, if specified. + * Returns undefined for each color that isn't explicitly set. + */ +export declare function getThemeExportColors(themeName?: string): { + pageBg?: string; + cardBg?: string; + infoBg?: string; +}; +/** + * Highlight code with syntax coloring based on file extension or language. + * Returns array of highlighted lines. + */ +export declare function highlightCode(code: string, lang?: string): string[]; +/** + * Get language identifier from file path extension. + */ +export declare function getLanguageFromPath(filePath: string): string | undefined; +export declare function getMarkdownTheme(): MarkdownTheme; +export declare function getSelectListTheme(): SelectListTheme; +export declare function getEditorTheme(): EditorTheme; +export declare function getSettingsListTheme(): SettingsListTheme; +export {}; +//# sourceMappingURL=theme.d.ts.map \ No newline at end of file diff --git a/dist/modes/interactive/theme/theme.d.ts.map b/dist/modes/interactive/theme/theme.d.ts.map new file mode 100644 index 0000000..f588ad0 --- /dev/null +++ b/dist/modes/interactive/theme/theme.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"theme.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/theme/theme.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EACN,KAAK,WAAW,EAEhB,KAAK,aAAa,EAClB,KAAK,QAAQ,EACb,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACtB,MAAM,wBAAwB,CAAC;AAKhC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AA6F/D,MAAM,MAAM,UAAU,GACnB,QAAQ,GACR,QAAQ,GACR,cAAc,GACd,aAAa,GACb,SAAS,GACT,OAAO,GACP,SAAS,GACT,OAAO,GACP,KAAK,GACL,MAAM,GACN,cAAc,GACd,iBAAiB,GACjB,mBAAmB,GACnB,oBAAoB,GACpB,WAAW,GACX,YAAY,GACZ,WAAW,GACX,QAAQ,GACR,WAAW,GACX,QAAQ,GACR,aAAa,GACb,mBAAmB,GACnB,SAAS,GACT,eAAe,GACf,MAAM,GACN,cAAc,GACd,eAAe,GACf,iBAAiB,GACjB,iBAAiB,GACjB,eAAe,GACf,eAAe,GACf,gBAAgB,GAChB,gBAAgB,GAChB,cAAc,GACd,cAAc,GACd,YAAY,GACZ,gBAAgB,GAChB,mBAAmB,GACnB,aAAa,GACb,iBAAiB,GACjB,aAAa,GACb,gBAAgB,GAChB,cAAc,GACd,eAAe,GACf,aAAa,GACb,UAAU,CAAC;AAEd,MAAM,MAAM,OAAO,GAChB,YAAY,GACZ,eAAe,GACf,iBAAiB,GACjB,eAAe,GACf,eAAe,GACf,aAAa,CAAC;AAEjB,KAAK,SAAS,GAAG,WAAW,GAAG,UAAU,CAAC;AAqK1C,qBAAa,KAAK;IACjB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ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AAgB,sBAAsB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAqBjF;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAGxD;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG;IACzD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB,CAwBA;AAiDD;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAmBnE;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAkExE;AAED,wBAAgB,gBAAgB,IAAI,aAAa,CAqChD;AAED,wBAAgB,kBAAkB,IAAI,eAAe,CAQpD;AAED,wBAAgB,cAAc,IAAI,WAAW,CAK5C;AAED,wBAAgB,oBAAoB,IAAI,iBAAiB,CAQxD","sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype EditorTheme,\n\tgetCapabilities,\n\ttype MarkdownTheme,\n\ttype RgbColor,\n\ttype SelectListTheme,\n\ttype SettingsListTheme,\n} from \"@earendil-works/pi-tui\";\nimport chalk from \"chalk\";\nimport { type Static, Type } from \"typebox\";\nimport { Compile } from \"typebox/compile\";\nimport { getCustomThemesDir, getThemesDir } from \"../../../config.ts\";\nimport type { SourceInfo } from \"../../../core/source-info.ts\";\nimport { closeWatcher, watchWithErrorHandler } from \"../../../utils/fs-watch.ts\";\nimport { highlight, supportsLanguage } from \"../../../utils/syntax-highlight.ts\";\n\n// ============================================================================\n// Types & Schema\n// ============================================================================\n\nconst ColorValueSchema = Type.Union([\n\tType.String(), // hex \"#ff0000\", var ref \"primary\", or empty \"\"\n\tType.Integer({ minimum: 0, maximum: 255 }), // 256-color index\n]);\n\ntype ColorValue = Static;\n\nconst ThemeJsonSchema = Type.Object({\n\t$schema: Type.Optional(Type.String()),\n\tname: Type.String(),\n\tvars: Type.Optional(Type.Record(Type.String(), ColorValueSchema)),\n\tcolors: Type.Object({\n\t\t// Core UI (10 colors)\n\t\taccent: ColorValueSchema,\n\t\tborder: ColorValueSchema,\n\t\tborderAccent: ColorValueSchema,\n\t\tborderMuted: ColorValueSchema,\n\t\tsuccess: ColorValueSchema,\n\t\terror: ColorValueSchema,\n\t\twarning: ColorValueSchema,\n\t\tmuted: ColorValueSchema,\n\t\tdim: ColorValueSchema,\n\t\ttext: ColorValueSchema,\n\t\tthinkingText: ColorValueSchema,\n\t\t// Backgrounds & Content Text (11 colors)\n\t\tselectedBg: ColorValueSchema,\n\t\tuserMessageBg: ColorValueSchema,\n\t\tuserMessageText: ColorValueSchema,\n\t\tcustomMessageBg: ColorValueSchema,\n\t\tcustomMessageText: ColorValueSchema,\n\t\tcustomMessageLabel: ColorValueSchema,\n\t\ttoolPendingBg: ColorValueSchema,\n\t\ttoolSuccessBg: ColorValueSchema,\n\t\ttoolErrorBg: ColorValueSchema,\n\t\ttoolTitle: ColorValueSchema,\n\t\ttoolOutput: ColorValueSchema,\n\t\t// Markdown (10 colors)\n\t\tmdHeading: ColorValueSchema,\n\t\tmdLink: ColorValueSchema,\n\t\tmdLinkUrl: ColorValueSchema,\n\t\tmdCode: ColorValueSchema,\n\t\tmdCodeBlock: ColorValueSchema,\n\t\tmdCodeBlockBorder: ColorValueSchema,\n\t\tmdQuote: ColorValueSchema,\n\t\tmdQuoteBorder: ColorValueSchema,\n\t\tmdHr: ColorValueSchema,\n\t\tmdListBullet: ColorValueSchema,\n\t\t// Tool Diffs (3 colors)\n\t\ttoolDiffAdded: ColorValueSchema,\n\t\ttoolDiffRemoved: ColorValueSchema,\n\t\ttoolDiffContext: ColorValueSchema,\n\t\t// Syntax Highlighting (9 colors)\n\t\tsyntaxComment: ColorValueSchema,\n\t\tsyntaxKeyword: ColorValueSchema,\n\t\tsyntaxFunction: ColorValueSchema,\n\t\tsyntaxVariable: ColorValueSchema,\n\t\tsyntaxString: ColorValueSchema,\n\t\tsyntaxNumber: ColorValueSchema,\n\t\tsyntaxType: ColorValueSchema,\n\t\tsyntaxOperator: ColorValueSchema,\n\t\tsyntaxPunctuation: ColorValueSchema,\n\t\t// Thinking Level Borders (6 colors)\n\t\tthinkingOff: ColorValueSchema,\n\t\tthinkingMinimal: ColorValueSchema,\n\t\tthinkingLow: ColorValueSchema,\n\t\tthinkingMedium: ColorValueSchema,\n\t\tthinkingHigh: ColorValueSchema,\n\t\tthinkingXhigh: ColorValueSchema,\n\t\tthinkingMax: Type.Optional(ColorValueSchema),\n\t\t// Bash Mode (1 color)\n\t\tbashMode: ColorValueSchema,\n\t}),\n\texport: Type.Optional(\n\t\tType.Object({\n\t\t\tpageBg: Type.Optional(ColorValueSchema),\n\t\t\tcardBg: Type.Optional(ColorValueSchema),\n\t\t\tinfoBg: Type.Optional(ColorValueSchema),\n\t\t}),\n\t),\n});\n\ntype ThemeJson = Static;\n\nconst validateThemeJson = Compile(ThemeJsonSchema);\n\nexport type ThemeColor =\n\t| \"accent\"\n\t| \"border\"\n\t| \"borderAccent\"\n\t| \"borderMuted\"\n\t| \"success\"\n\t| \"error\"\n\t| \"warning\"\n\t| \"muted\"\n\t| \"dim\"\n\t| \"text\"\n\t| \"thinkingText\"\n\t| \"userMessageText\"\n\t| \"customMessageText\"\n\t| \"customMessageLabel\"\n\t| \"toolTitle\"\n\t| \"toolOutput\"\n\t| \"mdHeading\"\n\t| \"mdLink\"\n\t| \"mdLinkUrl\"\n\t| \"mdCode\"\n\t| \"mdCodeBlock\"\n\t| \"mdCodeBlockBorder\"\n\t| \"mdQuote\"\n\t| \"mdQuoteBorder\"\n\t| \"mdHr\"\n\t| \"mdListBullet\"\n\t| \"toolDiffAdded\"\n\t| \"toolDiffRemoved\"\n\t| \"toolDiffContext\"\n\t| \"syntaxComment\"\n\t| \"syntaxKeyword\"\n\t| \"syntaxFunction\"\n\t| \"syntaxVariable\"\n\t| \"syntaxString\"\n\t| \"syntaxNumber\"\n\t| \"syntaxType\"\n\t| \"syntaxOperator\"\n\t| \"syntaxPunctuation\"\n\t| \"thinkingOff\"\n\t| \"thinkingMinimal\"\n\t| \"thinkingLow\"\n\t| \"thinkingMedium\"\n\t| \"thinkingHigh\"\n\t| \"thinkingXhigh\"\n\t| \"thinkingMax\"\n\t| \"bashMode\";\n\nexport type ThemeBg =\n\t| \"selectedBg\"\n\t| \"userMessageBg\"\n\t| \"customMessageBg\"\n\t| \"toolPendingBg\"\n\t| \"toolSuccessBg\"\n\t| \"toolErrorBg\";\n\ntype ColorMode = \"truecolor\" | \"256color\";\n\n// ============================================================================\n// Color Utilities\n// ============================================================================\n\nfunction hexToRgb(hex: string): { r: number; g: number; b: number } {\n\tconst cleaned = hex.replace(\"#\", \"\");\n\tif (cleaned.length !== 6) {\n\t\tthrow new Error(`Invalid hex color: ${hex}`);\n\t}\n\tconst r = parseInt(cleaned.substring(0, 2), 16);\n\tconst g = parseInt(cleaned.substring(2, 4), 16);\n\tconst b = parseInt(cleaned.substring(4, 6), 16);\n\tif (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) {\n\t\tthrow new Error(`Invalid hex color: ${hex}`);\n\t}\n\treturn { r, g, b };\n}\n\n// The 6x6x6 color cube channel values (indices 0-5)\nconst CUBE_VALUES = [0, 95, 135, 175, 215, 255];\n\n// Grayscale ramp values (indices 232-255, 24 grays from 8 to 238)\nconst GRAY_VALUES = Array.from({ length: 24 }, (_, i) => 8 + i * 10);\n\nfunction findClosestCubeIndex(value: number): number {\n\tlet minDist = Infinity;\n\tlet minIdx = 0;\n\tfor (let i = 0; i < CUBE_VALUES.length; i++) {\n\t\tconst dist = Math.abs(value - CUBE_VALUES[i]);\n\t\tif (dist < minDist) {\n\t\t\tminDist = dist;\n\t\t\tminIdx = i;\n\t\t}\n\t}\n\treturn minIdx;\n}\n\nfunction findClosestGrayIndex(gray: number): number {\n\tlet minDist = Infinity;\n\tlet minIdx = 0;\n\tfor (let i = 0; i < GRAY_VALUES.length; i++) {\n\t\tconst dist = Math.abs(gray - GRAY_VALUES[i]);\n\t\tif (dist < minDist) {\n\t\t\tminDist = dist;\n\t\t\tminIdx = i;\n\t\t}\n\t}\n\treturn minIdx;\n}\n\nfunction colorDistance(r1: number, g1: number, b1: number, r2: number, g2: number, b2: number): number {\n\t// Weighted Euclidean distance (human eye is more sensitive to green)\n\tconst dr = r1 - r2;\n\tconst dg = g1 - g2;\n\tconst db = b1 - b2;\n\treturn dr * dr * 0.299 + dg * dg * 0.587 + db * db * 0.114;\n}\n\nfunction rgbTo256(r: number, g: number, b: number): number {\n\t// Find closest color in the 6x6x6 cube\n\tconst rIdx = findClosestCubeIndex(r);\n\tconst gIdx = findClosestCubeIndex(g);\n\tconst bIdx = findClosestCubeIndex(b);\n\tconst cubeR = CUBE_VALUES[rIdx];\n\tconst cubeG = CUBE_VALUES[gIdx];\n\tconst cubeB = CUBE_VALUES[bIdx];\n\tconst cubeIndex = 16 + 36 * rIdx + 6 * gIdx + bIdx;\n\tconst cubeDist = colorDistance(r, g, b, cubeR, cubeG, cubeB);\n\n\t// Find closest grayscale\n\tconst gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);\n\tconst grayIdx = findClosestGrayIndex(gray);\n\tconst grayValue = GRAY_VALUES[grayIdx];\n\tconst grayIndex = 232 + grayIdx;\n\tconst grayDist = colorDistance(r, g, b, grayValue, grayValue, grayValue);\n\n\t// Check if color has noticeable saturation (hue matters)\n\t// If max-min spread is significant, prefer cube to preserve tint\n\tconst maxC = Math.max(r, g, b);\n\tconst minC = Math.min(r, g, b);\n\tconst spread = maxC - minC;\n\n\t// Only consider grayscale if color is nearly neutral (spread < 10)\n\t// AND grayscale is actually closer\n\tif (spread < 10 && grayDist < cubeDist) {\n\t\treturn grayIndex;\n\t}\n\n\treturn cubeIndex;\n}\n\nfunction hexTo256(hex: string): number {\n\tconst { r, g, b } = hexToRgb(hex);\n\treturn rgbTo256(r, g, b);\n}\n\nfunction fgAnsi(color: string | number, mode: ColorMode): string {\n\tif (color === \"\") return \"\\x1b[39m\";\n\tif (typeof color === \"number\") return `\\x1b[38;5;${color}m`;\n\tif (color.startsWith(\"#\")) {\n\t\tif (mode === \"truecolor\") {\n\t\t\tconst { r, g, b } = hexToRgb(color);\n\t\t\treturn `\\x1b[38;2;${r};${g};${b}m`;\n\t\t} else {\n\t\t\tconst index = hexTo256(color);\n\t\t\treturn `\\x1b[38;5;${index}m`;\n\t\t}\n\t}\n\tthrow new Error(`Invalid color value: ${color}`);\n}\n\nfunction bgAnsi(color: string | number, mode: ColorMode): string {\n\tif (color === \"\") return \"\\x1b[49m\";\n\tif (typeof color === \"number\") return `\\x1b[48;5;${color}m`;\n\tif (color.startsWith(\"#\")) {\n\t\tif (mode === \"truecolor\") {\n\t\t\tconst { r, g, b } = hexToRgb(color);\n\t\t\treturn `\\x1b[48;2;${r};${g};${b}m`;\n\t\t} else {\n\t\t\tconst index = hexTo256(color);\n\t\t\treturn `\\x1b[48;5;${index}m`;\n\t\t}\n\t}\n\tthrow new Error(`Invalid color value: ${color}`);\n}\n\nfunction resolveVarRefs(\n\tvalue: ColorValue,\n\tvars: Record,\n\tvisited = new Set(),\n): string | number {\n\tif (typeof value === \"number\" || value === \"\" || value.startsWith(\"#\")) {\n\t\treturn value;\n\t}\n\tif (visited.has(value)) {\n\t\tthrow new Error(`Circular variable reference detected: ${value}`);\n\t}\n\tif (!(value in vars)) {\n\t\tthrow new Error(`Variable reference not found: ${value}`);\n\t}\n\tvisited.add(value);\n\treturn resolveVarRefs(vars[value], vars, visited);\n}\n\nfunction resolveThemeColors>(\n\tcolors: T,\n\tvars: Record = {},\n): Record {\n\tconst resolved: Record = {};\n\tfor (const [key, value] of Object.entries(colors)) {\n\t\tresolved[key] = resolveVarRefs(value, vars);\n\t}\n\treturn resolved as Record;\n}\n\nfunction withThemeColorFallbacks(colors: ThemeJson[\"colors\"]): ThemeJson[\"colors\"] & { thinkingMax: ColorValue } {\n\treturn { ...colors, thinkingMax: colors.thinkingMax ?? colors.thinkingXhigh };\n}\n\n// ============================================================================\n// Theme Class\n// ============================================================================\n\nexport class Theme {\n\treadonly name?: string;\n\treadonly sourcePath?: string;\n\tsourceInfo?: SourceInfo;\n\tprivate fgColors: Map;\n\tprivate bgColors: Map;\n\tprivate mode: ColorMode;\n\n\tconstructor(\n\t\tfgColors: Record,\n\t\tbgColors: Record,\n\t\tmode: ColorMode,\n\t\toptions: { name?: string; sourcePath?: string; sourceInfo?: SourceInfo } = {},\n\t) {\n\t\tthis.name = options.name;\n\t\tthis.sourcePath = options.sourcePath;\n\t\tthis.sourceInfo = options.sourceInfo;\n\t\tthis.mode = mode;\n\t\tthis.fgColors = new Map();\n\t\tconst colors = { ...fgColors, thinkingMax: fgColors.thinkingMax ?? fgColors.thinkingXhigh };\n\t\tfor (const [key, value] of Object.entries(colors) as [ThemeColor, string | number][]) {\n\t\t\tthis.fgColors.set(key, fgAnsi(value, mode));\n\t\t}\n\t\tthis.bgColors = new Map();\n\t\tfor (const [key, value] of Object.entries(bgColors) as [ThemeBg, string | number][]) {\n\t\t\tthis.bgColors.set(key, bgAnsi(value, mode));\n\t\t}\n\t}\n\n\tfg(color: ThemeColor, text: string): string {\n\t\tconst ansi = this.fgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme color: ${color}`);\n\t\treturn `${ansi}${text}\\x1b[39m`; // Reset only foreground color\n\t}\n\n\tbg(color: ThemeBg, text: string): string {\n\t\tconst ansi = this.bgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme background color: ${color}`);\n\t\treturn `${ansi}${text}\\x1b[49m`; // Reset only background color\n\t}\n\n\tbold(text: string): string {\n\t\treturn chalk.bold(text);\n\t}\n\n\titalic(text: string): string {\n\t\treturn chalk.italic(text);\n\t}\n\n\tunderline(text: string): string {\n\t\treturn chalk.underline(text);\n\t}\n\n\tinverse(text: string): string {\n\t\treturn chalk.inverse(text);\n\t}\n\n\tstrikethrough(text: string): string {\n\t\treturn chalk.strikethrough(text);\n\t}\n\n\tgetFgAnsi(color: ThemeColor): string {\n\t\tconst ansi = this.fgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme color: ${color}`);\n\t\treturn ansi;\n\t}\n\n\tgetBgAnsi(color: ThemeBg): string {\n\t\tconst ansi = this.bgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme background color: ${color}`);\n\t\treturn ansi;\n\t}\n\n\tgetColorMode(): ColorMode {\n\t\treturn this.mode;\n\t}\n\n\tgetThinkingBorderColor(level: ThinkingLevel): (str: string) => string {\n\t\t// Map thinking levels to dedicated theme colors\n\t\tswitch (level) {\n\t\t\tcase \"off\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingOff\", str);\n\t\t\tcase \"minimal\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingMinimal\", str);\n\t\t\tcase \"low\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingLow\", str);\n\t\t\tcase \"medium\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingMedium\", str);\n\t\t\tcase \"high\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingHigh\", str);\n\t\t\tcase \"xhigh\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingXhigh\", str);\n\t\t\tcase \"max\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingMax\", str);\n\t\t\tdefault:\n\t\t\t\treturn (str: string) => this.fg(\"thinkingOff\", str);\n\t\t}\n\t}\n\n\tgetBashModeBorderColor(): (str: string) => string {\n\t\treturn (str: string) => this.fg(\"bashMode\", str);\n\t}\n}\n\n// ============================================================================\n// Theme Loading\n// ============================================================================\n\nlet BUILTIN_THEMES: Record | undefined;\n\nfunction getBuiltinThemes(): Record {\n\tif (!BUILTIN_THEMES) {\n\t\tconst themesDir = getThemesDir();\n\t\tconst darkPath = path.join(themesDir, \"dark.json\");\n\t\tconst lightPath = path.join(themesDir, \"light.json\");\n\t\tBUILTIN_THEMES = {\n\t\t\tdark: JSON.parse(fs.readFileSync(darkPath, \"utf-8\")) as ThemeJson,\n\t\t\tlight: JSON.parse(fs.readFileSync(lightPath, \"utf-8\")) as ThemeJson,\n\t\t};\n\t}\n\treturn BUILTIN_THEMES;\n}\n\nexport function getAvailableThemes(): string[] {\n\treturn getAvailableThemesWithPaths().map(({ name }) => name);\n}\n\nexport interface ThemeInfo {\n\tname: string;\n\tpath: string | undefined;\n}\n\nexport function getAvailableThemesWithPaths(): ThemeInfo[] {\n\tconst themesDir = getThemesDir();\n\tconst result: ThemeInfo[] = [];\n\tconst seen = new Set();\n\tconst addTheme = (themeInfo: ThemeInfo) => {\n\t\tif (seen.has(themeInfo.name)) {\n\t\t\treturn;\n\t\t}\n\t\tseen.add(themeInfo.name);\n\t\tresult.push(themeInfo);\n\t};\n\n\t// Built-in themes\n\tfor (const name of Object.keys(getBuiltinThemes())) {\n\t\taddTheme({ name, path: path.join(themesDir, `${name}.json`) });\n\t}\n\n\t// Custom themes\n\tfor (const themeInfo of getCustomThemeInfos()) {\n\t\taddTheme(themeInfo);\n\t}\n\n\tfor (const [name, theme] of registeredThemes.entries()) {\n\t\taddTheme({ name, path: theme.sourcePath });\n\t}\n\n\treturn result.sort((a, b) => a.name.localeCompare(b.name));\n}\n\nfunction getCustomThemeInfos(): ThemeInfo[] {\n\tconst customThemesDir = getCustomThemesDir();\n\tconst result: ThemeInfo[] = [];\n\tif (!fs.existsSync(customThemesDir)) {\n\t\treturn result;\n\t}\n\n\tfor (const file of fs.readdirSync(customThemesDir)) {\n\t\tif (!file.endsWith(\".json\")) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst themePath = path.join(customThemesDir, file);\n\t\ttry {\n\t\t\tconst customTheme = loadThemeFromPath(themePath);\n\t\t\tif (customTheme.name) {\n\t\t\t\tresult.push({ name: customTheme.name, path: themePath });\n\t\t\t}\n\t\t} catch {\n\t\t\t// Invalid themes are ignored here; the resource loader reports them\n\t\t\t// during normal startup/reload.\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction assertThemeNameIsValid(name: string): void {\n\tif (name.includes(\"/\")) {\n\t\tthrow new Error(\n\t\t\t`Invalid theme name \"${name}\": theme names cannot contain \"/\" because it is reserved for automatic light/dark theme settings.`,\n\t\t);\n\t}\n}\n\nfunction parseThemeJson(label: string, json: unknown): ThemeJson {\n\tif (!validateThemeJson.Check(json)) {\n\t\tconst errors = Array.from(validateThemeJson.Errors(json));\n\t\tconst missingColors = new Set();\n\t\tconst otherErrors: string[] = [];\n\n\t\tfor (const error of errors) {\n\t\t\tif (error.keyword === \"required\" && error.instancePath === \"/colors\") {\n\t\t\t\tconst requiredProperties = (error.params as { requiredProperties?: string[] }).requiredProperties;\n\t\t\t\tfor (const requiredProperty of requiredProperties ?? []) {\n\t\t\t\t\tmissingColors.add(requiredProperty);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst path = error.instancePath || \"/\";\n\t\t\totherErrors.push(` - ${path}: ${error.message}`);\n\t\t}\n\n\t\tlet errorMessage = `Invalid theme \"${label}\":\\n`;\n\t\tif (missingColors.size > 0) {\n\t\t\terrorMessage += \"\\nMissing required color tokens:\\n\";\n\t\t\terrorMessage += Array.from(missingColors)\n\t\t\t\t.sort()\n\t\t\t\t.map((color) => ` - ${color}`)\n\t\t\t\t.join(\"\\n\");\n\t\t\terrorMessage += '\\n\\nPlease add these colors to your theme\\'s \"colors\" object.';\n\t\t\terrorMessage += \"\\nSee the built-in themes (dark.json, light.json) for reference values.\";\n\t\t}\n\t\tif (otherErrors.length > 0) {\n\t\t\terrorMessage += `\\n\\nOther errors:\\n${otherErrors.join(\"\\n\")}`;\n\t\t}\n\n\t\tthrow new Error(errorMessage);\n\t}\n\n\tconst themeJson = json as ThemeJson;\n\tassertThemeNameIsValid(themeJson.name);\n\treturn themeJson;\n}\n\nfunction parseThemeJsonContent(label: string, content: string): ThemeJson {\n\tlet json: unknown;\n\ttry {\n\t\tjson = JSON.parse(content);\n\t} catch (error) {\n\t\tthrow new Error(`Failed to parse theme ${label}: ${error}`);\n\t}\n\treturn parseThemeJson(label, json);\n}\n\nfunction loadThemeJson(name: string): ThemeJson {\n\tconst builtinThemes = getBuiltinThemes();\n\tif (name in builtinThemes) {\n\t\treturn builtinThemes[name];\n\t}\n\tconst registeredTheme = registeredThemes.get(name);\n\tif (registeredTheme?.sourcePath) {\n\t\tconst content = fs.readFileSync(registeredTheme.sourcePath, \"utf-8\");\n\t\treturn parseThemeJsonContent(registeredTheme.sourcePath, content);\n\t}\n\tif (registeredTheme) {\n\t\tthrow new Error(`Theme \"${name}\" does not have a source path for export`);\n\t}\n\tconst customThemesDir = getCustomThemesDir();\n\tconst themePath = path.join(customThemesDir, `${name}.json`);\n\tif (!fs.existsSync(themePath)) {\n\t\tthrow new Error(`Theme not found: ${name}`);\n\t}\n\tconst content = fs.readFileSync(themePath, \"utf-8\");\n\treturn parseThemeJsonContent(name, content);\n}\n\nfunction createTheme(themeJson: ThemeJson, mode?: ColorMode, sourcePath?: string): Theme {\n\tconst colorMode = mode ?? (getCapabilities().trueColor ? \"truecolor\" : \"256color\");\n\tconst resolvedColors = resolveThemeColors(withThemeColorFallbacks(themeJson.colors), themeJson.vars);\n\tconst fgColors: Record = {} as Record;\n\tconst bgColors: Record = {} as Record;\n\tconst bgColorKeys: Set = new Set([\n\t\t\"selectedBg\",\n\t\t\"userMessageBg\",\n\t\t\"customMessageBg\",\n\t\t\"toolPendingBg\",\n\t\t\"toolSuccessBg\",\n\t\t\"toolErrorBg\",\n\t]);\n\tfor (const [key, value] of Object.entries(resolvedColors)) {\n\t\tif (bgColorKeys.has(key)) {\n\t\t\tbgColors[key as ThemeBg] = value;\n\t\t} else {\n\t\t\tfgColors[key as ThemeColor] = value;\n\t\t}\n\t}\n\treturn new Theme(fgColors, bgColors, colorMode, {\n\t\tname: themeJson.name,\n\t\tsourcePath,\n\t});\n}\n\nexport function loadThemeFromPath(themePath: string, mode?: ColorMode): Theme {\n\tconst content = fs.readFileSync(themePath, \"utf-8\");\n\tconst themeJson = parseThemeJsonContent(themePath, content);\n\treturn createTheme(themeJson, mode, themePath);\n}\n\nfunction loadTheme(name: string, mode?: ColorMode): Theme {\n\tconst registeredTheme = registeredThemes.get(name);\n\tif (registeredTheme) {\n\t\treturn registeredTheme;\n\t}\n\tconst themeJson = loadThemeJson(name);\n\treturn createTheme(themeJson, mode);\n}\n\nexport function getThemeByName(name: string): Theme | undefined {\n\ttry {\n\t\treturn loadTheme(name);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport type TerminalTheme = \"dark\" | \"light\";\n\nexport function parseAutoThemeSetting(\n\tthemeSetting: string | undefined,\n): { lightTheme: string; darkTheme: string } | undefined {\n\tif (!themeSetting) return undefined;\n\tconst slashIndex = themeSetting.indexOf(\"/\");\n\tif (slashIndex === -1 || themeSetting.indexOf(\"/\", slashIndex + 1) !== -1) {\n\t\treturn undefined;\n\t}\n\n\tconst lightTheme = themeSetting.slice(0, slashIndex).trim();\n\tconst darkTheme = themeSetting.slice(slashIndex + 1).trim();\n\tif (!lightTheme || !darkTheme) {\n\t\treturn undefined;\n\t}\n\treturn { lightTheme, darkTheme };\n}\n\nexport function resolveThemeSetting(\n\tthemeSetting: string | undefined,\n\tterminalTheme: TerminalTheme,\n): string | undefined {\n\tconst autoTheme = parseAutoThemeSetting(themeSetting);\n\tif (autoTheme) {\n\t\treturn terminalTheme === \"light\" ? autoTheme.lightTheme : autoTheme.darkTheme;\n\t}\n\tif (themeSetting?.includes(\"/\")) return undefined;\n\tif (typeof themeSetting === \"string\") return themeSetting;\n\treturn undefined;\n}\n\nexport interface TerminalThemeDetection {\n\ttheme: TerminalTheme;\n\tsource: \"terminal background\" | \"COLORFGBG\" | \"fallback\";\n\tdetail: string;\n\tconfidence: \"high\" | \"low\";\n}\n\nexport interface TerminalThemeDetectionOptions {\n\tenv?: NodeJS.ProcessEnv;\n}\n\nexport interface TerminalBackgroundThemeDetector {\n\tqueryTerminalBackgroundColor({ timeoutMs }: { timeoutMs: number }): Promise;\n}\n\nexport interface TerminalAutoThemeDetector extends TerminalBackgroundThemeDetector {\n\tqueryTerminalColorScheme?({ timeoutMs }: { timeoutMs: number }): Promise;\n}\n\nexport interface TerminalBackgroundThemeDetectionOptions extends TerminalThemeDetectionOptions {\n\tui: TerminalBackgroundThemeDetector;\n\ttimeoutMs: number;\n}\n\nexport interface TerminalAutoThemeDetectionOptions extends TerminalThemeDetectionOptions {\n\tui: TerminalAutoThemeDetector;\n\ttimeoutMs: number;\n}\n\nfunction getColorFgBgBackgroundIndex(colorfgbg: string): number | undefined {\n\tconst parts = colorfgbg.split(\";\");\n\tfor (let i = parts.length - 1; i >= 0; i--) {\n\t\tconst bg = parseInt(parts[i].trim(), 10);\n\t\tif (Number.isInteger(bg) && bg >= 0 && bg <= 255) {\n\t\t\treturn bg;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction getRgbColorLuminance({ r, g, b }: RgbColor): number {\n\tconst toLinear = (channel: number) => {\n\t\tconst value = channel / 255;\n\t\treturn value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;\n\t};\n\treturn 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b);\n}\n\nfunction getAnsiColorLuminance(index: number): number {\n\treturn getRgbColorLuminance(hexToRgb(ansi256ToHex(index)));\n}\n\nexport function getThemeForRgbColor(rgb: RgbColor): TerminalTheme {\n\treturn getRgbColorLuminance(rgb) >= 0.5 ? \"light\" : \"dark\";\n}\n\nexport function detectTerminalBackgroundFromEnv(options: TerminalThemeDetectionOptions = {}): TerminalThemeDetection {\n\tconst env = options.env ?? process.env;\n\tconst colorfgbg = env.COLORFGBG || \"\";\n\tconst bg = getColorFgBgBackgroundIndex(colorfgbg);\n\tif (bg !== undefined) {\n\t\treturn {\n\t\t\ttheme: getAnsiColorLuminance(bg) >= 0.5 ? \"light\" : \"dark\",\n\t\t\tsource: \"COLORFGBG\",\n\t\t\tdetail: `background color index ${bg}`,\n\t\t\tconfidence: \"high\",\n\t\t};\n\t}\n\n\treturn {\n\t\ttheme: \"dark\",\n\t\tsource: \"fallback\",\n\t\tdetail: \"no terminal background hint found\",\n\t\tconfidence: \"low\",\n\t};\n}\n\nexport async function detectTerminalBackgroundTheme({\n\tui,\n\ttimeoutMs,\n\tenv,\n}: TerminalBackgroundThemeDetectionOptions): Promise {\n\ttry {\n\t\tconst rgb = await ui.queryTerminalBackgroundColor({ timeoutMs });\n\t\tif (rgb) {\n\t\t\treturn {\n\t\t\t\ttheme: getThemeForRgbColor(rgb),\n\t\t\t\tsource: \"terminal background\",\n\t\t\t\tdetail: `OSC 11 background rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`,\n\t\t\t\tconfidence: \"high\",\n\t\t\t};\n\t\t}\n\t} catch {\n\t\t// Fall back to environment-based detection when the terminal query fails.\n\t}\n\n\treturn detectTerminalBackgroundFromEnv({ env });\n}\n\nexport async function detectTerminalThemeForAuto({\n\tui,\n\ttimeoutMs,\n\tenv,\n}: TerminalAutoThemeDetectionOptions): Promise {\n\ttry {\n\t\tconst colorScheme = await ui.queryTerminalColorScheme?.({ timeoutMs });\n\t\tif (colorScheme) return colorScheme;\n\t} catch {\n\t\t// Fall back to OSC 11 / COLORFGBG detection when color-scheme DSR is unsupported.\n\t}\n\treturn (await detectTerminalBackgroundTheme({ ui, timeoutMs, env })).theme;\n}\n\nexport function getDefaultTheme(): string {\n\treturn detectTerminalBackgroundFromEnv().theme;\n}\n\n// ============================================================================\n// Global Theme Instance\n// ============================================================================\n\n// Use globalThis to share theme across module loaders (tsx + jiti in dev mode)\nconst THEME_KEY = Symbol.for(\"@earendil-works/pi-coding-agent:theme\");\nconst THEME_KEY_OLD = Symbol.for(\"@mariozechner/pi-coding-agent:theme\");\n\n// Export theme as a getter that reads from globalThis\n// This ensures all module instances (tsx, jiti) see the same theme\nexport const theme: Theme = new Proxy({} as Theme, {\n\tget(_target, prop) {\n\t\tconst t = (globalThis as Record)[THEME_KEY];\n\t\tif (!t) throw new Error(\"Theme not initialized. Call initTheme() first.\");\n\t\treturn (t as unknown as Record)[prop];\n\t},\n});\n\nfunction setGlobalTheme(t: Theme): void {\n\t(globalThis as Record)[THEME_KEY] = t;\n\t(globalThis as Record)[THEME_KEY_OLD] = t;\n}\n\nlet currentThemeName: string | undefined;\nlet themeWatcher: fs.FSWatcher | undefined;\nlet themeReloadTimer: NodeJS.Timeout | undefined;\nlet onThemeChangeCallback: (() => void) | undefined;\nconst registeredThemes = new Map();\n\nexport function setRegisteredThemes(themes: Theme[]): void {\n\tregisteredThemes.clear();\n\tfor (const theme of themes) {\n\t\tif (theme.name) {\n\t\t\tassertThemeNameIsValid(theme.name);\n\t\t\tregisteredThemes.set(theme.name, theme);\n\t\t}\n\t}\n}\n\nexport function initTheme(themeName?: string, enableWatcher: boolean = false): void {\n\tconst name = themeName ?? getDefaultTheme();\n\tcurrentThemeName = name;\n\ttry {\n\t\tsetGlobalTheme(loadTheme(name));\n\t\tif (enableWatcher) {\n\t\t\tstartThemeWatcher();\n\t\t}\n\t} catch (_error) {\n\t\t// Theme is invalid - fall back to dark theme silently\n\t\tcurrentThemeName = \"dark\";\n\t\tsetGlobalTheme(loadTheme(\"dark\"));\n\t\t// Don't start watcher for fallback theme\n\t}\n}\n\nexport function setTheme(name: string, enableWatcher: boolean = false): { success: boolean; error?: string } {\n\tcurrentThemeName = name;\n\ttry {\n\t\tsetGlobalTheme(loadTheme(name));\n\t\tif (enableWatcher) {\n\t\t\tstartThemeWatcher();\n\t\t}\n\t\tif (onThemeChangeCallback) {\n\t\t\tonThemeChangeCallback();\n\t\t}\n\t\treturn { success: true };\n\t} catch (error) {\n\t\t// Theme is invalid - fall back to dark theme\n\t\tcurrentThemeName = \"dark\";\n\t\tsetGlobalTheme(loadTheme(\"dark\"));\n\t\t// Don't start watcher for fallback theme\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t};\n\t}\n}\n\nexport function setThemeInstance(themeInstance: Theme): void {\n\tsetGlobalTheme(themeInstance);\n\tcurrentThemeName = \"\";\n\tstopThemeWatcher(); // Can't watch a direct instance\n\tif (onThemeChangeCallback) {\n\t\tonThemeChangeCallback();\n\t}\n}\n\nexport function onThemeChange(callback: () => void): void {\n\tonThemeChangeCallback = callback;\n}\n\nfunction startThemeWatcher(): void {\n\tstopThemeWatcher();\n\n\t// Only watch if it's a custom theme (not built-in)\n\tif (!currentThemeName || currentThemeName === \"dark\" || currentThemeName === \"light\") {\n\t\treturn;\n\t}\n\n\tconst customThemesDir = getCustomThemesDir();\n\tconst watchedThemeName = currentThemeName;\n\tconst watchedFileName = `${watchedThemeName}.json`;\n\tconst themeFile = path.join(customThemesDir, watchedFileName);\n\n\t// Only watch if the file exists\n\tif (!fs.existsSync(themeFile)) {\n\t\treturn;\n\t}\n\n\tconst scheduleReload = () => {\n\t\tif (themeReloadTimer) {\n\t\t\tclearTimeout(themeReloadTimer);\n\t\t}\n\t\tthemeReloadTimer = setTimeout(() => {\n\t\t\tthemeReloadTimer = undefined;\n\n\t\t\t// Ignore stale timers after switching themes or stopping the watcher\n\t\t\tif (currentThemeName !== watchedThemeName) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Keep the last successfully loaded theme active if the file is temporarily missing\n\t\t\tif (!fs.existsSync(themeFile)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Reload the theme from disk and refresh the registry cache\n\t\t\t\tconst reloadedTheme = loadThemeFromPath(themeFile);\n\t\t\t\tregisteredThemes.set(watchedThemeName, reloadedTheme);\n\t\t\t\tsetGlobalTheme(reloadedTheme);\n\t\t\t\t// Notify callback (to invalidate UI)\n\t\t\t\tif (onThemeChangeCallback) {\n\t\t\t\t\tonThemeChangeCallback();\n\t\t\t\t}\n\t\t\t} catch (_error) {\n\t\t\t\t// Ignore errors (file might be in invalid state while being edited)\n\t\t\t}\n\t\t}, 100);\n\t};\n\n\tthemeWatcher =\n\t\twatchWithErrorHandler(\n\t\t\tcustomThemesDir,\n\t\t\t(_eventType, filename) => {\n\t\t\t\tif (currentThemeName !== watchedThemeName) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!filename) {\n\t\t\t\t\tscheduleReload();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (filename !== watchedFileName) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tscheduleReload();\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tcloseWatcher(themeWatcher);\n\t\t\t\tthemeWatcher = undefined;\n\t\t\t},\n\t\t) ?? undefined;\n}\n\nexport function stopThemeWatcher(): void {\n\tif (themeReloadTimer) {\n\t\tclearTimeout(themeReloadTimer);\n\t\tthemeReloadTimer = undefined;\n\t}\n\tcloseWatcher(themeWatcher);\n\tthemeWatcher = undefined;\n}\n\n// ============================================================================\n// HTML Export Helpers\n// ============================================================================\n\n/**\n * Convert a 256-color index to hex string.\n * Indices 0-15: basic colors (approximate)\n * Indices 16-231: 6x6x6 color cube\n * Indices 232-255: grayscale ramp\n */\nfunction ansi256ToHex(index: number): string {\n\t// Basic colors (0-15) - approximate common terminal values\n\tconst basicColors = [\n\t\t\"#000000\",\n\t\t\"#800000\",\n\t\t\"#008000\",\n\t\t\"#808000\",\n\t\t\"#000080\",\n\t\t\"#800080\",\n\t\t\"#008080\",\n\t\t\"#c0c0c0\",\n\t\t\"#808080\",\n\t\t\"#ff0000\",\n\t\t\"#00ff00\",\n\t\t\"#ffff00\",\n\t\t\"#0000ff\",\n\t\t\"#ff00ff\",\n\t\t\"#00ffff\",\n\t\t\"#ffffff\",\n\t];\n\tif (index < 16) {\n\t\treturn basicColors[index];\n\t}\n\n\t// Color cube (16-231): 6x6x6 = 216 colors\n\tif (index < 232) {\n\t\tconst cubeIndex = index - 16;\n\t\tconst r = Math.floor(cubeIndex / 36);\n\t\tconst g = Math.floor((cubeIndex % 36) / 6);\n\t\tconst b = cubeIndex % 6;\n\t\tconst toHex = (n: number) => (n === 0 ? 0 : 55 + n * 40).toString(16).padStart(2, \"0\");\n\t\treturn `#${toHex(r)}${toHex(g)}${toHex(b)}`;\n\t}\n\n\t// Grayscale (232-255): 24 shades\n\tconst gray = 8 + (index - 232) * 10;\n\tconst grayHex = gray.toString(16).padStart(2, \"0\");\n\treturn `#${grayHex}${grayHex}${grayHex}`;\n}\n\n/**\n * Get resolved theme colors as CSS-compatible hex strings.\n * Used by HTML export to generate CSS custom properties.\n */\nexport function getResolvedThemeColors(themeName?: string): Record {\n\tconst name = themeName ?? currentThemeName ?? getDefaultTheme();\n\tconst isLight = name === \"light\";\n\tconst themeJson = loadThemeJson(name);\n\tconst resolved = resolveThemeColors(withThemeColorFallbacks(themeJson.colors), themeJson.vars);\n\n\t// Default text color for empty values (terminal uses default fg color)\n\tconst defaultText = isLight ? \"#000000\" : \"#e5e5e7\";\n\n\tconst cssColors: Record = {};\n\tfor (const [key, value] of Object.entries(resolved)) {\n\t\tif (typeof value === \"number\") {\n\t\t\tcssColors[key] = ansi256ToHex(value);\n\t\t} else if (value === \"\") {\n\t\t\t// Empty means default terminal color - use sensible fallback for HTML\n\t\t\tcssColors[key] = defaultText;\n\t\t} else {\n\t\t\tcssColors[key] = value;\n\t\t}\n\t}\n\treturn cssColors;\n}\n\n/**\n * Check if a theme is a \"light\" theme (for CSS that needs light/dark variants).\n */\nexport function isLightTheme(themeName?: string): boolean {\n\t// Currently just check the name - could be extended to analyze colors\n\treturn themeName === \"light\";\n}\n\n/**\n * Get explicit export colors from theme JSON, if specified.\n * Returns undefined for each color that isn't explicitly set.\n */\nexport function getThemeExportColors(themeName?: string): {\n\tpageBg?: string;\n\tcardBg?: string;\n\tinfoBg?: string;\n} {\n\tconst name = themeName ?? currentThemeName ?? getDefaultTheme();\n\ttry {\n\t\tconst themeJson = loadThemeJson(name);\n\t\tconst exportSection = themeJson.export;\n\t\tif (!exportSection) return {};\n\n\t\tconst vars = themeJson.vars ?? {};\n\t\tconst resolve = (value: ColorValue | undefined): string | undefined => {\n\t\t\tif (value === undefined) return undefined;\n\t\t\tconst resolved = resolveVarRefs(value, vars);\n\t\t\tif (typeof resolved === \"number\") return ansi256ToHex(resolved);\n\t\t\tif (resolved === \"\") return undefined;\n\t\t\treturn resolved;\n\t\t};\n\n\t\treturn {\n\t\t\tpageBg: resolve(exportSection.pageBg),\n\t\t\tcardBg: resolve(exportSection.cardBg),\n\t\t\tinfoBg: resolve(exportSection.infoBg),\n\t\t};\n\t} catch {\n\t\treturn {};\n\t}\n}\n\n// ============================================================================\n// TUI Helpers\n// ============================================================================\n\ntype CliHighlightTheme = Record string>;\n\nlet cachedHighlightThemeFor: Theme | undefined;\nlet cachedCliHighlightTheme: CliHighlightTheme | undefined;\n\nfunction buildCliHighlightTheme(t: Theme): CliHighlightTheme {\n\treturn {\n\t\tkeyword: (s: string) => t.fg(\"syntaxKeyword\", s),\n\t\tbuilt_in: (s: string) => t.fg(\"syntaxType\", s),\n\t\tliteral: (s: string) => t.fg(\"syntaxNumber\", s),\n\t\tnumber: (s: string) => t.fg(\"syntaxNumber\", s),\n\t\tregexp: (s: string) => t.fg(\"syntaxString\", s),\n\t\tstring: (s: string) => t.fg(\"syntaxString\", s),\n\t\tcomment: (s: string) => t.fg(\"syntaxComment\", s),\n\t\tdoctag: (s: string) => t.fg(\"syntaxComment\", s),\n\t\tmeta: (s: string) => t.fg(\"muted\", s),\n\t\tfunction: (s: string) => t.fg(\"syntaxFunction\", s),\n\t\ttitle: (s: string) => t.fg(\"syntaxFunction\", s),\n\t\tclass: (s: string) => t.fg(\"syntaxType\", s),\n\t\ttype: (s: string) => t.fg(\"syntaxType\", s),\n\t\ttag: (s: string) => t.fg(\"syntaxPunctuation\", s),\n\t\tname: (s: string) => t.fg(\"syntaxKeyword\", s),\n\t\tattr: (s: string) => t.fg(\"syntaxVariable\", s),\n\t\tvariable: (s: string) => t.fg(\"syntaxVariable\", s),\n\t\tparams: (s: string) => t.fg(\"syntaxVariable\", s),\n\t\toperator: (s: string) => t.fg(\"syntaxOperator\", s),\n\t\tpunctuation: (s: string) => t.fg(\"syntaxPunctuation\", s),\n\t\temphasis: (s: string) => t.italic(s),\n\t\tstrong: (s: string) => t.bold(s),\n\t\tlink: (s: string) => t.underline(s),\n\t\taddition: (s: string) => t.fg(\"toolDiffAdded\", s),\n\t\tdeletion: (s: string) => t.fg(\"toolDiffRemoved\", s),\n\t};\n}\n\nfunction getCliHighlightTheme(t: Theme): CliHighlightTheme {\n\tif (cachedHighlightThemeFor !== t || !cachedCliHighlightTheme) {\n\t\tcachedHighlightThemeFor = t;\n\t\tcachedCliHighlightTheme = buildCliHighlightTheme(t);\n\t}\n\treturn cachedCliHighlightTheme;\n}\n\n/**\n * Highlight code with syntax coloring based on file extension or language.\n * Returns array of highlighted lines.\n */\nexport function highlightCode(code: string, lang?: string): string[] {\n\t// Validate language before highlighting to avoid stderr spam from cli-highlight\n\tconst validLang = lang && supportsLanguage(lang) ? lang : undefined;\n\t// Skip highlighting when no valid language is specified. cli-highlight's\n\t// auto-detection is unreliable and can misidentify prose as AppleScript,\n\t// LiveCodeServer, etc., coloring random English words as keywords.\n\tif (!validLang) {\n\t\treturn code.split(\"\\n\").map((line) => theme.fg(\"mdCodeBlock\", line));\n\t}\n\tconst opts = {\n\t\tlanguage: validLang,\n\t\tignoreIllegals: true,\n\t\ttheme: getCliHighlightTheme(theme),\n\t};\n\ttry {\n\t\treturn highlight(code, opts).split(\"\\n\");\n\t} catch {\n\t\treturn code.split(\"\\n\");\n\t}\n}\n\n/**\n * Get language identifier from file path extension.\n */\nexport function getLanguageFromPath(filePath: string): string | undefined {\n\tconst ext = filePath.split(\".\").pop()?.toLowerCase();\n\tif (!ext) return undefined;\n\n\tconst extToLang: Record = {\n\t\tts: \"typescript\",\n\t\ttsx: \"typescript\",\n\t\tjs: \"javascript\",\n\t\tjsx: \"javascript\",\n\t\tmjs: \"javascript\",\n\t\tcjs: \"javascript\",\n\t\tpy: \"python\",\n\t\trb: \"ruby\",\n\t\trs: \"rust\",\n\t\tgo: \"go\",\n\t\tjava: \"java\",\n\t\tkt: \"kotlin\",\n\t\tswift: \"swift\",\n\t\tc: \"c\",\n\t\th: \"c\",\n\t\tcpp: \"cpp\",\n\t\tcc: \"cpp\",\n\t\tcxx: \"cpp\",\n\t\thpp: \"cpp\",\n\t\tcs: \"csharp\",\n\t\tphp: \"php\",\n\t\tsh: \"bash\",\n\t\tbash: \"bash\",\n\t\tzsh: \"bash\",\n\t\tfish: \"fish\",\n\t\tps1: \"powershell\",\n\t\tsql: \"sql\",\n\t\thtml: \"html\",\n\t\thtm: \"html\",\n\t\tcss: \"css\",\n\t\tscss: \"scss\",\n\t\tsass: \"sass\",\n\t\tless: \"less\",\n\t\tjson: \"json\",\n\t\tyaml: \"yaml\",\n\t\tyml: \"yaml\",\n\t\ttoml: \"toml\",\n\t\txml: \"xml\",\n\t\tmd: \"markdown\",\n\t\tmarkdown: \"markdown\",\n\t\tdockerfile: \"dockerfile\",\n\t\tmakefile: \"makefile\",\n\t\tcmake: \"cmake\",\n\t\tlua: \"lua\",\n\t\tperl: \"perl\",\n\t\tr: \"r\",\n\t\tscala: \"scala\",\n\t\tclj: \"clojure\",\n\t\tex: \"elixir\",\n\t\texs: \"elixir\",\n\t\terl: \"erlang\",\n\t\ths: \"haskell\",\n\t\tml: \"ocaml\",\n\t\tvim: \"vim\",\n\t\tgraphql: \"graphql\",\n\t\tproto: \"protobuf\",\n\t\ttf: \"hcl\",\n\t\thcl: \"hcl\",\n\t};\n\n\treturn extToLang[ext];\n}\n\nexport function getMarkdownTheme(): MarkdownTheme {\n\treturn {\n\t\theading: (text: string) => theme.fg(\"mdHeading\", text),\n\t\tlink: (text: string) => theme.fg(\"mdLink\", text),\n\t\tlinkUrl: (text: string) => theme.fg(\"mdLinkUrl\", text),\n\t\tcode: (text: string) => theme.fg(\"mdCode\", text),\n\t\tcodeBlock: (text: string) => theme.fg(\"mdCodeBlock\", text),\n\t\tcodeBlockBorder: (text: string) => theme.fg(\"mdCodeBlockBorder\", text),\n\t\tquote: (text: string) => theme.fg(\"mdQuote\", text),\n\t\tquoteBorder: (text: string) => theme.fg(\"mdQuoteBorder\", text),\n\t\thr: (text: string) => theme.fg(\"mdHr\", text),\n\t\tlistBullet: (text: string) => theme.fg(\"mdListBullet\", text),\n\t\tbold: (text: string) => theme.bold(text),\n\t\titalic: (text: string) => theme.italic(text),\n\t\tunderline: (text: string) => theme.underline(text),\n\t\tstrikethrough: (text: string) => chalk.strikethrough(text),\n\t\thighlightCode: (code: string, lang?: string): string[] => {\n\t\t\t// Validate language before highlighting to avoid stderr spam from cli-highlight\n\t\t\tconst validLang = lang && supportsLanguage(lang) ? lang : undefined;\n\t\t\t// Skip highlighting when no valid language is specified. cli-highlight's\n\t\t\t// auto-detection is unreliable and can misidentify prose as AppleScript,\n\t\t\t// LiveCodeServer, etc., coloring random English words as keywords.\n\t\t\tif (!validLang) {\n\t\t\t\treturn code.split(\"\\n\").map((line) => theme.fg(\"mdCodeBlock\", line));\n\t\t\t}\n\t\t\tconst opts = {\n\t\t\t\tlanguage: validLang,\n\t\t\t\tignoreIllegals: true,\n\t\t\t\ttheme: getCliHighlightTheme(theme),\n\t\t\t};\n\t\t\ttry {\n\t\t\t\treturn highlight(code, opts).split(\"\\n\");\n\t\t\t} catch {\n\t\t\t\treturn code.split(\"\\n\").map((line) => theme.fg(\"mdCodeBlock\", line));\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport function getSelectListTheme(): SelectListTheme {\n\treturn {\n\t\tselectedPrefix: (text: string) => theme.fg(\"accent\", text),\n\t\tselectedText: (text: string) => theme.fg(\"accent\", text),\n\t\tdescription: (text: string) => theme.fg(\"muted\", text),\n\t\tscrollInfo: (text: string) => theme.fg(\"muted\", text),\n\t\tnoMatch: (text: string) => theme.fg(\"muted\", text),\n\t};\n}\n\nexport function getEditorTheme(): EditorTheme {\n\treturn {\n\t\tborderColor: (text: string) => theme.fg(\"borderMuted\", text),\n\t\tselectList: getSelectListTheme(),\n\t};\n}\n\nexport function getSettingsListTheme(): SettingsListTheme {\n\treturn {\n\t\tlabel: (text: string, selected: boolean) => (selected ? theme.fg(\"accent\", text) : text),\n\t\tvalue: (text: string, selected: boolean) => (selected ? theme.fg(\"accent\", text) : theme.fg(\"muted\", text)),\n\t\tdescription: (text: string) => theme.fg(\"dim\", text),\n\t\tcursor: theme.fg(\"accent\", \"→ \"),\n\t\thint: (text: string) => theme.fg(\"dim\", text),\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/modes/interactive/theme/theme.js b/dist/modes/interactive/theme/theme.js new file mode 100644 index 0000000..c4b7a40 --- /dev/null +++ b/dist/modes/interactive/theme/theme.js @@ -0,0 +1,1063 @@ +import * as fs from "node:fs"; +import * as path from "node:path"; +import { getCapabilities, } from "@earendil-works/pi-tui"; +import chalk from "chalk"; +import { Type } from "typebox"; +import { Compile } from "typebox/compile"; +import { getCustomThemesDir, getThemesDir } from "../../../config.js"; +import { closeWatcher, watchWithErrorHandler } from "../../../utils/fs-watch.js"; +import { highlight, supportsLanguage } from "../../../utils/syntax-highlight.js"; +// ============================================================================ +// Types & Schema +// ============================================================================ +const ColorValueSchema = Type.Union([ + Type.String(), // hex "#ff0000", var ref "primary", or empty "" + Type.Integer({ minimum: 0, maximum: 255 }), // 256-color index +]); +const ThemeJsonSchema = Type.Object({ + $schema: Type.Optional(Type.String()), + name: Type.String(), + vars: Type.Optional(Type.Record(Type.String(), ColorValueSchema)), + colors: Type.Object({ + // Core UI (10 colors) + accent: ColorValueSchema, + border: ColorValueSchema, + borderAccent: ColorValueSchema, + borderMuted: ColorValueSchema, + success: ColorValueSchema, + error: ColorValueSchema, + warning: ColorValueSchema, + muted: ColorValueSchema, + dim: ColorValueSchema, + text: ColorValueSchema, + thinkingText: ColorValueSchema, + // Backgrounds & Content Text (11 colors) + selectedBg: ColorValueSchema, + userMessageBg: ColorValueSchema, + userMessageText: ColorValueSchema, + customMessageBg: ColorValueSchema, + customMessageText: ColorValueSchema, + customMessageLabel: ColorValueSchema, + toolPendingBg: ColorValueSchema, + toolSuccessBg: ColorValueSchema, + toolErrorBg: ColorValueSchema, + toolTitle: ColorValueSchema, + toolOutput: ColorValueSchema, + // Markdown (10 colors) + mdHeading: ColorValueSchema, + mdLink: ColorValueSchema, + mdLinkUrl: ColorValueSchema, + mdCode: ColorValueSchema, + mdCodeBlock: ColorValueSchema, + mdCodeBlockBorder: ColorValueSchema, + mdQuote: ColorValueSchema, + mdQuoteBorder: ColorValueSchema, + mdHr: ColorValueSchema, + mdListBullet: ColorValueSchema, + // Tool Diffs (3 colors) + toolDiffAdded: ColorValueSchema, + toolDiffRemoved: ColorValueSchema, + toolDiffContext: ColorValueSchema, + // Syntax Highlighting (9 colors) + syntaxComment: ColorValueSchema, + syntaxKeyword: ColorValueSchema, + syntaxFunction: ColorValueSchema, + syntaxVariable: ColorValueSchema, + syntaxString: ColorValueSchema, + syntaxNumber: ColorValueSchema, + syntaxType: ColorValueSchema, + syntaxOperator: ColorValueSchema, + syntaxPunctuation: ColorValueSchema, + // Thinking Level Borders (6 colors) + thinkingOff: ColorValueSchema, + thinkingMinimal: ColorValueSchema, + thinkingLow: ColorValueSchema, + thinkingMedium: ColorValueSchema, + thinkingHigh: ColorValueSchema, + thinkingXhigh: ColorValueSchema, + thinkingMax: Type.Optional(ColorValueSchema), + // Bash Mode (1 color) + bashMode: ColorValueSchema, + }), + export: Type.Optional(Type.Object({ + pageBg: Type.Optional(ColorValueSchema), + cardBg: Type.Optional(ColorValueSchema), + infoBg: Type.Optional(ColorValueSchema), + })), +}); +const validateThemeJson = Compile(ThemeJsonSchema); +// ============================================================================ +// Color Utilities +// ============================================================================ +function hexToRgb(hex) { + const cleaned = hex.replace("#", ""); + if (cleaned.length !== 6) { + throw new Error(`Invalid hex color: ${hex}`); + } + const r = parseInt(cleaned.substring(0, 2), 16); + const g = parseInt(cleaned.substring(2, 4), 16); + const b = parseInt(cleaned.substring(4, 6), 16); + if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) { + throw new Error(`Invalid hex color: ${hex}`); + } + return { r, g, b }; +} +// The 6x6x6 color cube channel values (indices 0-5) +const CUBE_VALUES = [0, 95, 135, 175, 215, 255]; +// Grayscale ramp values (indices 232-255, 24 grays from 8 to 238) +const GRAY_VALUES = Array.from({ length: 24 }, (_, i) => 8 + i * 10); +function findClosestCubeIndex(value) { + let minDist = Infinity; + let minIdx = 0; + for (let i = 0; i < CUBE_VALUES.length; i++) { + const dist = Math.abs(value - CUBE_VALUES[i]); + if (dist < minDist) { + minDist = dist; + minIdx = i; + } + } + return minIdx; +} +function findClosestGrayIndex(gray) { + let minDist = Infinity; + let minIdx = 0; + for (let i = 0; i < GRAY_VALUES.length; i++) { + const dist = Math.abs(gray - GRAY_VALUES[i]); + if (dist < minDist) { + minDist = dist; + minIdx = i; + } + } + return minIdx; +} +function colorDistance(r1, g1, b1, r2, g2, b2) { + // Weighted Euclidean distance (human eye is more sensitive to green) + const dr = r1 - r2; + const dg = g1 - g2; + const db = b1 - b2; + return dr * dr * 0.299 + dg * dg * 0.587 + db * db * 0.114; +} +function rgbTo256(r, g, b) { + // Find closest color in the 6x6x6 cube + const rIdx = findClosestCubeIndex(r); + const gIdx = findClosestCubeIndex(g); + const bIdx = findClosestCubeIndex(b); + const cubeR = CUBE_VALUES[rIdx]; + const cubeG = CUBE_VALUES[gIdx]; + const cubeB = CUBE_VALUES[bIdx]; + const cubeIndex = 16 + 36 * rIdx + 6 * gIdx + bIdx; + const cubeDist = colorDistance(r, g, b, cubeR, cubeG, cubeB); + // Find closest grayscale + const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b); + const grayIdx = findClosestGrayIndex(gray); + const grayValue = GRAY_VALUES[grayIdx]; + const grayIndex = 232 + grayIdx; + const grayDist = colorDistance(r, g, b, grayValue, grayValue, grayValue); + // Check if color has noticeable saturation (hue matters) + // If max-min spread is significant, prefer cube to preserve tint + const maxC = Math.max(r, g, b); + const minC = Math.min(r, g, b); + const spread = maxC - minC; + // Only consider grayscale if color is nearly neutral (spread < 10) + // AND grayscale is actually closer + if (spread < 10 && grayDist < cubeDist) { + return grayIndex; + } + return cubeIndex; +} +function hexTo256(hex) { + const { r, g, b } = hexToRgb(hex); + return rgbTo256(r, g, b); +} +function fgAnsi(color, mode) { + if (color === "") + return "\x1b[39m"; + if (typeof color === "number") + return `\x1b[38;5;${color}m`; + if (color.startsWith("#")) { + if (mode === "truecolor") { + const { r, g, b } = hexToRgb(color); + return `\x1b[38;2;${r};${g};${b}m`; + } + else { + const index = hexTo256(color); + return `\x1b[38;5;${index}m`; + } + } + throw new Error(`Invalid color value: ${color}`); +} +function bgAnsi(color, mode) { + if (color === "") + return "\x1b[49m"; + if (typeof color === "number") + return `\x1b[48;5;${color}m`; + if (color.startsWith("#")) { + if (mode === "truecolor") { + const { r, g, b } = hexToRgb(color); + return `\x1b[48;2;${r};${g};${b}m`; + } + else { + const index = hexTo256(color); + return `\x1b[48;5;${index}m`; + } + } + throw new Error(`Invalid color value: ${color}`); +} +function resolveVarRefs(value, vars, visited = new Set()) { + if (typeof value === "number" || value === "" || value.startsWith("#")) { + return value; + } + if (visited.has(value)) { + throw new Error(`Circular variable reference detected: ${value}`); + } + if (!(value in vars)) { + throw new Error(`Variable reference not found: ${value}`); + } + visited.add(value); + return resolveVarRefs(vars[value], vars, visited); +} +function resolveThemeColors(colors, vars = {}) { + const resolved = {}; + for (const [key, value] of Object.entries(colors)) { + resolved[key] = resolveVarRefs(value, vars); + } + return resolved; +} +function withThemeColorFallbacks(colors) { + return { ...colors, thinkingMax: colors.thinkingMax ?? colors.thinkingXhigh }; +} +// ============================================================================ +// Theme Class +// ============================================================================ +export class Theme { + name; + sourcePath; + sourceInfo; + fgColors; + bgColors; + mode; + constructor(fgColors, bgColors, mode, options = {}) { + this.name = options.name; + this.sourcePath = options.sourcePath; + this.sourceInfo = options.sourceInfo; + this.mode = mode; + this.fgColors = new Map(); + const colors = { ...fgColors, thinkingMax: fgColors.thinkingMax ?? fgColors.thinkingXhigh }; + for (const [key, value] of Object.entries(colors)) { + this.fgColors.set(key, fgAnsi(value, mode)); + } + this.bgColors = new Map(); + for (const [key, value] of Object.entries(bgColors)) { + this.bgColors.set(key, bgAnsi(value, mode)); + } + } + fg(color, text) { + const ansi = this.fgColors.get(color); + if (!ansi) + throw new Error(`Unknown theme color: ${color}`); + return `${ansi}${text}\x1b[39m`; // Reset only foreground color + } + bg(color, text) { + const ansi = this.bgColors.get(color); + if (!ansi) + throw new Error(`Unknown theme background color: ${color}`); + return `${ansi}${text}\x1b[49m`; // Reset only background color + } + bold(text) { + return chalk.bold(text); + } + italic(text) { + return chalk.italic(text); + } + underline(text) { + return chalk.underline(text); + } + inverse(text) { + return chalk.inverse(text); + } + strikethrough(text) { + return chalk.strikethrough(text); + } + getFgAnsi(color) { + const ansi = this.fgColors.get(color); + if (!ansi) + throw new Error(`Unknown theme color: ${color}`); + return ansi; + } + getBgAnsi(color) { + const ansi = this.bgColors.get(color); + if (!ansi) + throw new Error(`Unknown theme background color: ${color}`); + return ansi; + } + getColorMode() { + return this.mode; + } + getThinkingBorderColor(level) { + // Map thinking levels to dedicated theme colors + switch (level) { + case "off": + return (str) => this.fg("thinkingOff", str); + case "minimal": + return (str) => this.fg("thinkingMinimal", str); + case "low": + return (str) => this.fg("thinkingLow", str); + case "medium": + return (str) => this.fg("thinkingMedium", str); + case "high": + return (str) => this.fg("thinkingHigh", str); + case "xhigh": + return (str) => this.fg("thinkingXhigh", str); + case "max": + return (str) => this.fg("thinkingMax", str); + default: + return (str) => this.fg("thinkingOff", str); + } + } + getBashModeBorderColor() { + return (str) => this.fg("bashMode", str); + } +} +// ============================================================================ +// Theme Loading +// ============================================================================ +let BUILTIN_THEMES; +function getBuiltinThemes() { + if (!BUILTIN_THEMES) { + const themesDir = getThemesDir(); + const darkPath = path.join(themesDir, "dark.json"); + const lightPath = path.join(themesDir, "light.json"); + BUILTIN_THEMES = { + dark: JSON.parse(fs.readFileSync(darkPath, "utf-8")), + light: JSON.parse(fs.readFileSync(lightPath, "utf-8")), + }; + } + return BUILTIN_THEMES; +} +export function getAvailableThemes() { + return getAvailableThemesWithPaths().map(({ name }) => name); +} +export function getAvailableThemesWithPaths() { + const themesDir = getThemesDir(); + const result = []; + const seen = new Set(); + const addTheme = (themeInfo) => { + if (seen.has(themeInfo.name)) { + return; + } + seen.add(themeInfo.name); + result.push(themeInfo); + }; + // Built-in themes + for (const name of Object.keys(getBuiltinThemes())) { + addTheme({ name, path: path.join(themesDir, `${name}.json`) }); + } + // Custom themes + for (const themeInfo of getCustomThemeInfos()) { + addTheme(themeInfo); + } + for (const [name, theme] of registeredThemes.entries()) { + addTheme({ name, path: theme.sourcePath }); + } + return result.sort((a, b) => a.name.localeCompare(b.name)); +} +function getCustomThemeInfos() { + const customThemesDir = getCustomThemesDir(); + const result = []; + if (!fs.existsSync(customThemesDir)) { + return result; + } + for (const file of fs.readdirSync(customThemesDir)) { + if (!file.endsWith(".json")) { + continue; + } + const themePath = path.join(customThemesDir, file); + try { + const customTheme = loadThemeFromPath(themePath); + if (customTheme.name) { + result.push({ name: customTheme.name, path: themePath }); + } + } + catch { + // Invalid themes are ignored here; the resource loader reports them + // during normal startup/reload. + } + } + return result; +} +function assertThemeNameIsValid(name) { + if (name.includes("/")) { + throw new Error(`Invalid theme name "${name}": theme names cannot contain "/" because it is reserved for automatic light/dark theme settings.`); + } +} +function parseThemeJson(label, json) { + if (!validateThemeJson.Check(json)) { + const errors = Array.from(validateThemeJson.Errors(json)); + const missingColors = new Set(); + const otherErrors = []; + for (const error of errors) { + if (error.keyword === "required" && error.instancePath === "/colors") { + const requiredProperties = error.params.requiredProperties; + for (const requiredProperty of requiredProperties ?? []) { + missingColors.add(requiredProperty); + } + continue; + } + const path = error.instancePath || "/"; + otherErrors.push(` - ${path}: ${error.message}`); + } + let errorMessage = `Invalid theme "${label}":\n`; + if (missingColors.size > 0) { + errorMessage += "\nMissing required color tokens:\n"; + errorMessage += Array.from(missingColors) + .sort() + .map((color) => ` - ${color}`) + .join("\n"); + errorMessage += '\n\nPlease add these colors to your theme\'s "colors" object.'; + errorMessage += "\nSee the built-in themes (dark.json, light.json) for reference values."; + } + if (otherErrors.length > 0) { + errorMessage += `\n\nOther errors:\n${otherErrors.join("\n")}`; + } + throw new Error(errorMessage); + } + const themeJson = json; + assertThemeNameIsValid(themeJson.name); + return themeJson; +} +function parseThemeJsonContent(label, content) { + let json; + try { + json = JSON.parse(content); + } + catch (error) { + throw new Error(`Failed to parse theme ${label}: ${error}`); + } + return parseThemeJson(label, json); +} +function loadThemeJson(name) { + const builtinThemes = getBuiltinThemes(); + if (name in builtinThemes) { + return builtinThemes[name]; + } + const registeredTheme = registeredThemes.get(name); + if (registeredTheme?.sourcePath) { + const content = fs.readFileSync(registeredTheme.sourcePath, "utf-8"); + return parseThemeJsonContent(registeredTheme.sourcePath, content); + } + if (registeredTheme) { + throw new Error(`Theme "${name}" does not have a source path for export`); + } + const customThemesDir = getCustomThemesDir(); + const themePath = path.join(customThemesDir, `${name}.json`); + if (!fs.existsSync(themePath)) { + throw new Error(`Theme not found: ${name}`); + } + const content = fs.readFileSync(themePath, "utf-8"); + return parseThemeJsonContent(name, content); +} +function createTheme(themeJson, mode, sourcePath) { + const colorMode = mode ?? (getCapabilities().trueColor ? "truecolor" : "256color"); + const resolvedColors = resolveThemeColors(withThemeColorFallbacks(themeJson.colors), themeJson.vars); + const fgColors = {}; + const bgColors = {}; + const bgColorKeys = new Set([ + "selectedBg", + "userMessageBg", + "customMessageBg", + "toolPendingBg", + "toolSuccessBg", + "toolErrorBg", + ]); + for (const [key, value] of Object.entries(resolvedColors)) { + if (bgColorKeys.has(key)) { + bgColors[key] = value; + } + else { + fgColors[key] = value; + } + } + return new Theme(fgColors, bgColors, colorMode, { + name: themeJson.name, + sourcePath, + }); +} +export function loadThemeFromPath(themePath, mode) { + const content = fs.readFileSync(themePath, "utf-8"); + const themeJson = parseThemeJsonContent(themePath, content); + return createTheme(themeJson, mode, themePath); +} +function loadTheme(name, mode) { + const registeredTheme = registeredThemes.get(name); + if (registeredTheme) { + return registeredTheme; + } + const themeJson = loadThemeJson(name); + return createTheme(themeJson, mode); +} +export function getThemeByName(name) { + try { + return loadTheme(name); + } + catch { + return undefined; + } +} +export function parseAutoThemeSetting(themeSetting) { + if (!themeSetting) + return undefined; + const slashIndex = themeSetting.indexOf("/"); + if (slashIndex === -1 || themeSetting.indexOf("/", slashIndex + 1) !== -1) { + return undefined; + } + const lightTheme = themeSetting.slice(0, slashIndex).trim(); + const darkTheme = themeSetting.slice(slashIndex + 1).trim(); + if (!lightTheme || !darkTheme) { + return undefined; + } + return { lightTheme, darkTheme }; +} +export function resolveThemeSetting(themeSetting, terminalTheme) { + const autoTheme = parseAutoThemeSetting(themeSetting); + if (autoTheme) { + return terminalTheme === "light" ? autoTheme.lightTheme : autoTheme.darkTheme; + } + if (themeSetting?.includes("/")) + return undefined; + if (typeof themeSetting === "string") + return themeSetting; + return undefined; +} +function getColorFgBgBackgroundIndex(colorfgbg) { + const parts = colorfgbg.split(";"); + for (let i = parts.length - 1; i >= 0; i--) { + const bg = parseInt(parts[i].trim(), 10); + if (Number.isInteger(bg) && bg >= 0 && bg <= 255) { + return bg; + } + } + return undefined; +} +function getRgbColorLuminance({ r, g, b }) { + const toLinear = (channel) => { + const value = channel / 255; + return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4; + }; + return 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b); +} +function getAnsiColorLuminance(index) { + return getRgbColorLuminance(hexToRgb(ansi256ToHex(index))); +} +export function getThemeForRgbColor(rgb) { + return getRgbColorLuminance(rgb) >= 0.5 ? "light" : "dark"; +} +export function detectTerminalBackgroundFromEnv(options = {}) { + const env = options.env ?? process.env; + const colorfgbg = env.COLORFGBG || ""; + const bg = getColorFgBgBackgroundIndex(colorfgbg); + if (bg !== undefined) { + return { + theme: getAnsiColorLuminance(bg) >= 0.5 ? "light" : "dark", + source: "COLORFGBG", + detail: `background color index ${bg}`, + confidence: "high", + }; + } + return { + theme: "dark", + source: "fallback", + detail: "no terminal background hint found", + confidence: "low", + }; +} +export async function detectTerminalBackgroundTheme({ ui, timeoutMs, env, }) { + try { + const rgb = await ui.queryTerminalBackgroundColor({ timeoutMs }); + if (rgb) { + return { + theme: getThemeForRgbColor(rgb), + source: "terminal background", + detail: `OSC 11 background rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`, + confidence: "high", + }; + } + } + catch { + // Fall back to environment-based detection when the terminal query fails. + } + return detectTerminalBackgroundFromEnv({ env }); +} +export async function detectTerminalThemeForAuto({ ui, timeoutMs, env, }) { + try { + const colorScheme = await ui.queryTerminalColorScheme?.({ timeoutMs }); + if (colorScheme) + return colorScheme; + } + catch { + // Fall back to OSC 11 / COLORFGBG detection when color-scheme DSR is unsupported. + } + return (await detectTerminalBackgroundTheme({ ui, timeoutMs, env })).theme; +} +export function getDefaultTheme() { + return detectTerminalBackgroundFromEnv().theme; +} +// ============================================================================ +// Global Theme Instance +// ============================================================================ +// Use globalThis to share theme across module loaders (tsx + jiti in dev mode) +const THEME_KEY = Symbol.for("@earendil-works/pi-coding-agent:theme"); +const THEME_KEY_OLD = Symbol.for("@mariozechner/pi-coding-agent:theme"); +// Export theme as a getter that reads from globalThis +// This ensures all module instances (tsx, jiti) see the same theme +export const theme = new Proxy({}, { + get(_target, prop) { + const t = globalThis[THEME_KEY]; + if (!t) + throw new Error("Theme not initialized. Call initTheme() first."); + return t[prop]; + }, +}); +function setGlobalTheme(t) { + globalThis[THEME_KEY] = t; + globalThis[THEME_KEY_OLD] = t; +} +let currentThemeName; +let themeWatcher; +let themeReloadTimer; +let onThemeChangeCallback; +const registeredThemes = new Map(); +export function setRegisteredThemes(themes) { + registeredThemes.clear(); + for (const theme of themes) { + if (theme.name) { + assertThemeNameIsValid(theme.name); + registeredThemes.set(theme.name, theme); + } + } +} +export function initTheme(themeName, enableWatcher = false) { + const name = themeName ?? getDefaultTheme(); + currentThemeName = name; + try { + setGlobalTheme(loadTheme(name)); + if (enableWatcher) { + startThemeWatcher(); + } + } + catch (_error) { + // Theme is invalid - fall back to dark theme silently + currentThemeName = "dark"; + setGlobalTheme(loadTheme("dark")); + // Don't start watcher for fallback theme + } +} +export function setTheme(name, enableWatcher = false) { + currentThemeName = name; + try { + setGlobalTheme(loadTheme(name)); + if (enableWatcher) { + startThemeWatcher(); + } + if (onThemeChangeCallback) { + onThemeChangeCallback(); + } + return { success: true }; + } + catch (error) { + // Theme is invalid - fall back to dark theme + currentThemeName = "dark"; + setGlobalTheme(loadTheme("dark")); + // Don't start watcher for fallback theme + return { + success: false, + error: error instanceof Error ? error.message : String(error), + }; + } +} +export function setThemeInstance(themeInstance) { + setGlobalTheme(themeInstance); + currentThemeName = ""; + stopThemeWatcher(); // Can't watch a direct instance + if (onThemeChangeCallback) { + onThemeChangeCallback(); + } +} +export function onThemeChange(callback) { + onThemeChangeCallback = callback; +} +function startThemeWatcher() { + stopThemeWatcher(); + // Only watch if it's a custom theme (not built-in) + if (!currentThemeName || currentThemeName === "dark" || currentThemeName === "light") { + return; + } + const customThemesDir = getCustomThemesDir(); + const watchedThemeName = currentThemeName; + const watchedFileName = `${watchedThemeName}.json`; + const themeFile = path.join(customThemesDir, watchedFileName); + // Only watch if the file exists + if (!fs.existsSync(themeFile)) { + return; + } + const scheduleReload = () => { + if (themeReloadTimer) { + clearTimeout(themeReloadTimer); + } + themeReloadTimer = setTimeout(() => { + themeReloadTimer = undefined; + // Ignore stale timers after switching themes or stopping the watcher + if (currentThemeName !== watchedThemeName) { + return; + } + // Keep the last successfully loaded theme active if the file is temporarily missing + if (!fs.existsSync(themeFile)) { + return; + } + try { + // Reload the theme from disk and refresh the registry cache + const reloadedTheme = loadThemeFromPath(themeFile); + registeredThemes.set(watchedThemeName, reloadedTheme); + setGlobalTheme(reloadedTheme); + // Notify callback (to invalidate UI) + if (onThemeChangeCallback) { + onThemeChangeCallback(); + } + } + catch (_error) { + // Ignore errors (file might be in invalid state while being edited) + } + }, 100); + }; + themeWatcher = + watchWithErrorHandler(customThemesDir, (_eventType, filename) => { + if (currentThemeName !== watchedThemeName) { + return; + } + if (!filename) { + scheduleReload(); + return; + } + if (filename !== watchedFileName) { + return; + } + scheduleReload(); + }, () => { + closeWatcher(themeWatcher); + themeWatcher = undefined; + }) ?? undefined; +} +export function stopThemeWatcher() { + if (themeReloadTimer) { + clearTimeout(themeReloadTimer); + themeReloadTimer = undefined; + } + closeWatcher(themeWatcher); + themeWatcher = undefined; +} +// ============================================================================ +// HTML Export Helpers +// ============================================================================ +/** + * Convert a 256-color index to hex string. + * Indices 0-15: basic colors (approximate) + * Indices 16-231: 6x6x6 color cube + * Indices 232-255: grayscale ramp + */ +function ansi256ToHex(index) { + // Basic colors (0-15) - approximate common terminal values + const basicColors = [ + "#000000", + "#800000", + "#008000", + "#808000", + "#000080", + "#800080", + "#008080", + "#c0c0c0", + "#808080", + "#ff0000", + "#00ff00", + "#ffff00", + "#0000ff", + "#ff00ff", + "#00ffff", + "#ffffff", + ]; + if (index < 16) { + return basicColors[index]; + } + // Color cube (16-231): 6x6x6 = 216 colors + if (index < 232) { + const cubeIndex = index - 16; + const r = Math.floor(cubeIndex / 36); + const g = Math.floor((cubeIndex % 36) / 6); + const b = cubeIndex % 6; + const toHex = (n) => (n === 0 ? 0 : 55 + n * 40).toString(16).padStart(2, "0"); + return `#${toHex(r)}${toHex(g)}${toHex(b)}`; + } + // Grayscale (232-255): 24 shades + const gray = 8 + (index - 232) * 10; + const grayHex = gray.toString(16).padStart(2, "0"); + return `#${grayHex}${grayHex}${grayHex}`; +} +/** + * Get resolved theme colors as CSS-compatible hex strings. + * Used by HTML export to generate CSS custom properties. + */ +export function getResolvedThemeColors(themeName) { + const name = themeName ?? currentThemeName ?? getDefaultTheme(); + const isLight = name === "light"; + const themeJson = loadThemeJson(name); + const resolved = resolveThemeColors(withThemeColorFallbacks(themeJson.colors), themeJson.vars); + // Default text color for empty values (terminal uses default fg color) + const defaultText = isLight ? "#000000" : "#e5e5e7"; + const cssColors = {}; + for (const [key, value] of Object.entries(resolved)) { + if (typeof value === "number") { + cssColors[key] = ansi256ToHex(value); + } + else if (value === "") { + // Empty means default terminal color - use sensible fallback for HTML + cssColors[key] = defaultText; + } + else { + cssColors[key] = value; + } + } + return cssColors; +} +/** + * Check if a theme is a "light" theme (for CSS that needs light/dark variants). + */ +export function isLightTheme(themeName) { + // Currently just check the name - could be extended to analyze colors + return themeName === "light"; +} +/** + * Get explicit export colors from theme JSON, if specified. + * Returns undefined for each color that isn't explicitly set. + */ +export function getThemeExportColors(themeName) { + const name = themeName ?? currentThemeName ?? getDefaultTheme(); + try { + const themeJson = loadThemeJson(name); + const exportSection = themeJson.export; + if (!exportSection) + return {}; + const vars = themeJson.vars ?? {}; + const resolve = (value) => { + if (value === undefined) + return undefined; + const resolved = resolveVarRefs(value, vars); + if (typeof resolved === "number") + return ansi256ToHex(resolved); + if (resolved === "") + return undefined; + return resolved; + }; + return { + pageBg: resolve(exportSection.pageBg), + cardBg: resolve(exportSection.cardBg), + infoBg: resolve(exportSection.infoBg), + }; + } + catch { + return {}; + } +} +let cachedHighlightThemeFor; +let cachedCliHighlightTheme; +function buildCliHighlightTheme(t) { + return { + keyword: (s) => t.fg("syntaxKeyword", s), + built_in: (s) => t.fg("syntaxType", s), + literal: (s) => t.fg("syntaxNumber", s), + number: (s) => t.fg("syntaxNumber", s), + regexp: (s) => t.fg("syntaxString", s), + string: (s) => t.fg("syntaxString", s), + comment: (s) => t.fg("syntaxComment", s), + doctag: (s) => t.fg("syntaxComment", s), + meta: (s) => t.fg("muted", s), + function: (s) => t.fg("syntaxFunction", s), + title: (s) => t.fg("syntaxFunction", s), + class: (s) => t.fg("syntaxType", s), + type: (s) => t.fg("syntaxType", s), + tag: (s) => t.fg("syntaxPunctuation", s), + name: (s) => t.fg("syntaxKeyword", s), + attr: (s) => t.fg("syntaxVariable", s), + variable: (s) => t.fg("syntaxVariable", s), + params: (s) => t.fg("syntaxVariable", s), + operator: (s) => t.fg("syntaxOperator", s), + punctuation: (s) => t.fg("syntaxPunctuation", s), + emphasis: (s) => t.italic(s), + strong: (s) => t.bold(s), + link: (s) => t.underline(s), + addition: (s) => t.fg("toolDiffAdded", s), + deletion: (s) => t.fg("toolDiffRemoved", s), + }; +} +function getCliHighlightTheme(t) { + if (cachedHighlightThemeFor !== t || !cachedCliHighlightTheme) { + cachedHighlightThemeFor = t; + cachedCliHighlightTheme = buildCliHighlightTheme(t); + } + return cachedCliHighlightTheme; +} +/** + * Highlight code with syntax coloring based on file extension or language. + * Returns array of highlighted lines. + */ +export function highlightCode(code, lang) { + // Validate language before highlighting to avoid stderr spam from cli-highlight + const validLang = lang && supportsLanguage(lang) ? lang : undefined; + // Skip highlighting when no valid language is specified. cli-highlight's + // auto-detection is unreliable and can misidentify prose as AppleScript, + // LiveCodeServer, etc., coloring random English words as keywords. + if (!validLang) { + return code.split("\n").map((line) => theme.fg("mdCodeBlock", line)); + } + const opts = { + language: validLang, + ignoreIllegals: true, + theme: getCliHighlightTheme(theme), + }; + try { + return highlight(code, opts).split("\n"); + } + catch { + return code.split("\n"); + } +} +/** + * Get language identifier from file path extension. + */ +export function getLanguageFromPath(filePath) { + const ext = filePath.split(".").pop()?.toLowerCase(); + if (!ext) + return undefined; + const extToLang = { + ts: "typescript", + tsx: "typescript", + js: "javascript", + jsx: "javascript", + mjs: "javascript", + cjs: "javascript", + py: "python", + rb: "ruby", + rs: "rust", + go: "go", + java: "java", + kt: "kotlin", + swift: "swift", + c: "c", + h: "c", + cpp: "cpp", + cc: "cpp", + cxx: "cpp", + hpp: "cpp", + cs: "csharp", + php: "php", + sh: "bash", + bash: "bash", + zsh: "bash", + fish: "fish", + ps1: "powershell", + sql: "sql", + html: "html", + htm: "html", + css: "css", + scss: "scss", + sass: "sass", + less: "less", + json: "json", + yaml: "yaml", + yml: "yaml", + toml: "toml", + xml: "xml", + md: "markdown", + markdown: "markdown", + dockerfile: "dockerfile", + makefile: "makefile", + cmake: "cmake", + lua: "lua", + perl: "perl", + r: "r", + scala: "scala", + clj: "clojure", + ex: "elixir", + exs: "elixir", + erl: "erlang", + hs: "haskell", + ml: "ocaml", + vim: "vim", + graphql: "graphql", + proto: "protobuf", + tf: "hcl", + hcl: "hcl", + }; + return extToLang[ext]; +} +export function getMarkdownTheme() { + return { + heading: (text) => theme.fg("mdHeading", text), + link: (text) => theme.fg("mdLink", text), + linkUrl: (text) => theme.fg("mdLinkUrl", text), + code: (text) => theme.fg("mdCode", text), + codeBlock: (text) => theme.fg("mdCodeBlock", text), + codeBlockBorder: (text) => theme.fg("mdCodeBlockBorder", text), + quote: (text) => theme.fg("mdQuote", text), + quoteBorder: (text) => theme.fg("mdQuoteBorder", text), + hr: (text) => theme.fg("mdHr", text), + listBullet: (text) => theme.fg("mdListBullet", text), + bold: (text) => theme.bold(text), + italic: (text) => theme.italic(text), + underline: (text) => theme.underline(text), + strikethrough: (text) => chalk.strikethrough(text), + highlightCode: (code, lang) => { + // Validate language before highlighting to avoid stderr spam from cli-highlight + const validLang = lang && supportsLanguage(lang) ? lang : undefined; + // Skip highlighting when no valid language is specified. cli-highlight's + // auto-detection is unreliable and can misidentify prose as AppleScript, + // LiveCodeServer, etc., coloring random English words as keywords. + if (!validLang) { + return code.split("\n").map((line) => theme.fg("mdCodeBlock", line)); + } + const opts = { + language: validLang, + ignoreIllegals: true, + theme: getCliHighlightTheme(theme), + }; + try { + return highlight(code, opts).split("\n"); + } + catch { + return code.split("\n").map((line) => theme.fg("mdCodeBlock", line)); + } + }, + }; +} +export function getSelectListTheme() { + return { + selectedPrefix: (text) => theme.fg("accent", text), + selectedText: (text) => theme.fg("accent", text), + description: (text) => theme.fg("muted", text), + scrollInfo: (text) => theme.fg("muted", text), + noMatch: (text) => theme.fg("muted", text), + }; +} +export function getEditorTheme() { + return { + borderColor: (text) => theme.fg("borderMuted", text), + selectList: getSelectListTheme(), + }; +} +export function getSettingsListTheme() { + return { + label: (text, selected) => (selected ? theme.fg("accent", text) : text), + value: (text, selected) => (selected ? theme.fg("accent", text) : theme.fg("muted", text)), + description: (text) => theme.fg("dim", text), + cursor: theme.fg("accent", "→ "), + hint: (text) => theme.fg("dim", text), + }; +} +//# sourceMappingURL=theme.js.map \ No newline at end of file diff --git a/dist/modes/interactive/theme/theme.js.map b/dist/modes/interactive/theme/theme.js.map new file mode 100644 index 0000000..52b366d --- /dev/null +++ b/dist/modes/interactive/theme/theme.js.map @@ -0,0 +1 @@ +{"version":3,"file":"theme.js","sourceRoot":"","sources":["../../../../src/modes/interactive/theme/theme.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAEN,eAAe,GAKf,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAEtE,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AAEjF,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E,MAAM,gBAAgB,GAAG,IAAI,CAAC,KAAK,CAAC;IACnC,IAAI,CAAC,MAAM,EAAE,EAAE,gDAAgD;IAC/D,IAAI,CAAC,OAAO,CAAC,EAAE,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,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC;KAClD,CAAC;AAAA,CACF;AAED,MAAM,UAAU,cAAc,GAAgB;IAC7C,OAAO;QACN,WAAW,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,aAAa,EAAE,IAAI,CAAC;QAC5D,UAAU,EAAE,kBAAkB,EAAE;KAChC,CAAC;AAAA,CACF;AAED,MAAM,UAAU,oBAAoB,GAAsB;IACzD,OAAO;QACN,KAAK,EAAE,CAAC,IAAY,EAAE,QAAiB,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QACxF,KAAK,EAAE,CAAC,IAAY,EAAE,QAAiB,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QAC3G,WAAW,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC;QACpD,MAAM,EAAE,KAAK,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAI,CAAC;QAChC,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC;KAC7C,CAAC;AAAA,CACF","sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype EditorTheme,\n\tgetCapabilities,\n\ttype MarkdownTheme,\n\ttype RgbColor,\n\ttype SelectListTheme,\n\ttype SettingsListTheme,\n} from \"@earendil-works/pi-tui\";\nimport chalk from \"chalk\";\nimport { type Static, Type } from \"typebox\";\nimport { Compile } from \"typebox/compile\";\nimport { getCustomThemesDir, getThemesDir } from \"../../../config.ts\";\nimport type { SourceInfo } from \"../../../core/source-info.ts\";\nimport { closeWatcher, watchWithErrorHandler } from \"../../../utils/fs-watch.ts\";\nimport { highlight, supportsLanguage } from \"../../../utils/syntax-highlight.ts\";\n\n// ============================================================================\n// Types & Schema\n// ============================================================================\n\nconst ColorValueSchema = Type.Union([\n\tType.String(), // hex \"#ff0000\", var ref \"primary\", or empty \"\"\n\tType.Integer({ minimum: 0, maximum: 255 }), // 256-color index\n]);\n\ntype ColorValue = Static;\n\nconst ThemeJsonSchema = Type.Object({\n\t$schema: Type.Optional(Type.String()),\n\tname: Type.String(),\n\tvars: Type.Optional(Type.Record(Type.String(), ColorValueSchema)),\n\tcolors: Type.Object({\n\t\t// Core UI (10 colors)\n\t\taccent: ColorValueSchema,\n\t\tborder: ColorValueSchema,\n\t\tborderAccent: ColorValueSchema,\n\t\tborderMuted: ColorValueSchema,\n\t\tsuccess: ColorValueSchema,\n\t\terror: ColorValueSchema,\n\t\twarning: ColorValueSchema,\n\t\tmuted: ColorValueSchema,\n\t\tdim: ColorValueSchema,\n\t\ttext: ColorValueSchema,\n\t\tthinkingText: ColorValueSchema,\n\t\t// Backgrounds & Content Text (11 colors)\n\t\tselectedBg: ColorValueSchema,\n\t\tuserMessageBg: ColorValueSchema,\n\t\tuserMessageText: ColorValueSchema,\n\t\tcustomMessageBg: ColorValueSchema,\n\t\tcustomMessageText: ColorValueSchema,\n\t\tcustomMessageLabel: ColorValueSchema,\n\t\ttoolPendingBg: ColorValueSchema,\n\t\ttoolSuccessBg: ColorValueSchema,\n\t\ttoolErrorBg: ColorValueSchema,\n\t\ttoolTitle: ColorValueSchema,\n\t\ttoolOutput: ColorValueSchema,\n\t\t// Markdown (10 colors)\n\t\tmdHeading: ColorValueSchema,\n\t\tmdLink: ColorValueSchema,\n\t\tmdLinkUrl: ColorValueSchema,\n\t\tmdCode: ColorValueSchema,\n\t\tmdCodeBlock: ColorValueSchema,\n\t\tmdCodeBlockBorder: ColorValueSchema,\n\t\tmdQuote: ColorValueSchema,\n\t\tmdQuoteBorder: ColorValueSchema,\n\t\tmdHr: ColorValueSchema,\n\t\tmdListBullet: ColorValueSchema,\n\t\t// Tool Diffs (3 colors)\n\t\ttoolDiffAdded: ColorValueSchema,\n\t\ttoolDiffRemoved: ColorValueSchema,\n\t\ttoolDiffContext: ColorValueSchema,\n\t\t// Syntax Highlighting (9 colors)\n\t\tsyntaxComment: ColorValueSchema,\n\t\tsyntaxKeyword: ColorValueSchema,\n\t\tsyntaxFunction: ColorValueSchema,\n\t\tsyntaxVariable: ColorValueSchema,\n\t\tsyntaxString: ColorValueSchema,\n\t\tsyntaxNumber: ColorValueSchema,\n\t\tsyntaxType: ColorValueSchema,\n\t\tsyntaxOperator: ColorValueSchema,\n\t\tsyntaxPunctuation: ColorValueSchema,\n\t\t// Thinking Level Borders (6 colors)\n\t\tthinkingOff: ColorValueSchema,\n\t\tthinkingMinimal: ColorValueSchema,\n\t\tthinkingLow: ColorValueSchema,\n\t\tthinkingMedium: ColorValueSchema,\n\t\tthinkingHigh: ColorValueSchema,\n\t\tthinkingXhigh: ColorValueSchema,\n\t\tthinkingMax: Type.Optional(ColorValueSchema),\n\t\t// Bash Mode (1 color)\n\t\tbashMode: ColorValueSchema,\n\t}),\n\texport: Type.Optional(\n\t\tType.Object({\n\t\t\tpageBg: Type.Optional(ColorValueSchema),\n\t\t\tcardBg: Type.Optional(ColorValueSchema),\n\t\t\tinfoBg: Type.Optional(ColorValueSchema),\n\t\t}),\n\t),\n});\n\ntype ThemeJson = Static;\n\nconst validateThemeJson = Compile(ThemeJsonSchema);\n\nexport type ThemeColor =\n\t| \"accent\"\n\t| \"border\"\n\t| \"borderAccent\"\n\t| \"borderMuted\"\n\t| \"success\"\n\t| \"error\"\n\t| \"warning\"\n\t| \"muted\"\n\t| \"dim\"\n\t| \"text\"\n\t| \"thinkingText\"\n\t| \"userMessageText\"\n\t| \"customMessageText\"\n\t| \"customMessageLabel\"\n\t| \"toolTitle\"\n\t| \"toolOutput\"\n\t| \"mdHeading\"\n\t| \"mdLink\"\n\t| \"mdLinkUrl\"\n\t| \"mdCode\"\n\t| \"mdCodeBlock\"\n\t| \"mdCodeBlockBorder\"\n\t| \"mdQuote\"\n\t| \"mdQuoteBorder\"\n\t| \"mdHr\"\n\t| \"mdListBullet\"\n\t| \"toolDiffAdded\"\n\t| \"toolDiffRemoved\"\n\t| \"toolDiffContext\"\n\t| \"syntaxComment\"\n\t| \"syntaxKeyword\"\n\t| \"syntaxFunction\"\n\t| \"syntaxVariable\"\n\t| \"syntaxString\"\n\t| \"syntaxNumber\"\n\t| \"syntaxType\"\n\t| \"syntaxOperator\"\n\t| \"syntaxPunctuation\"\n\t| \"thinkingOff\"\n\t| \"thinkingMinimal\"\n\t| \"thinkingLow\"\n\t| \"thinkingMedium\"\n\t| \"thinkingHigh\"\n\t| \"thinkingXhigh\"\n\t| \"thinkingMax\"\n\t| \"bashMode\";\n\nexport type ThemeBg =\n\t| \"selectedBg\"\n\t| \"userMessageBg\"\n\t| \"customMessageBg\"\n\t| \"toolPendingBg\"\n\t| \"toolSuccessBg\"\n\t| \"toolErrorBg\";\n\ntype ColorMode = \"truecolor\" | \"256color\";\n\n// ============================================================================\n// Color Utilities\n// ============================================================================\n\nfunction hexToRgb(hex: string): { r: number; g: number; b: number } {\n\tconst cleaned = hex.replace(\"#\", \"\");\n\tif (cleaned.length !== 6) {\n\t\tthrow new Error(`Invalid hex color: ${hex}`);\n\t}\n\tconst r = parseInt(cleaned.substring(0, 2), 16);\n\tconst g = parseInt(cleaned.substring(2, 4), 16);\n\tconst b = parseInt(cleaned.substring(4, 6), 16);\n\tif (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) {\n\t\tthrow new Error(`Invalid hex color: ${hex}`);\n\t}\n\treturn { r, g, b };\n}\n\n// The 6x6x6 color cube channel values (indices 0-5)\nconst CUBE_VALUES = [0, 95, 135, 175, 215, 255];\n\n// Grayscale ramp values (indices 232-255, 24 grays from 8 to 238)\nconst GRAY_VALUES = Array.from({ length: 24 }, (_, i) => 8 + i * 10);\n\nfunction findClosestCubeIndex(value: number): number {\n\tlet minDist = Infinity;\n\tlet minIdx = 0;\n\tfor (let i = 0; i < CUBE_VALUES.length; i++) {\n\t\tconst dist = Math.abs(value - CUBE_VALUES[i]);\n\t\tif (dist < minDist) {\n\t\t\tminDist = dist;\n\t\t\tminIdx = i;\n\t\t}\n\t}\n\treturn minIdx;\n}\n\nfunction findClosestGrayIndex(gray: number): number {\n\tlet minDist = Infinity;\n\tlet minIdx = 0;\n\tfor (let i = 0; i < GRAY_VALUES.length; i++) {\n\t\tconst dist = Math.abs(gray - GRAY_VALUES[i]);\n\t\tif (dist < minDist) {\n\t\t\tminDist = dist;\n\t\t\tminIdx = i;\n\t\t}\n\t}\n\treturn minIdx;\n}\n\nfunction colorDistance(r1: number, g1: number, b1: number, r2: number, g2: number, b2: number): number {\n\t// Weighted Euclidean distance (human eye is more sensitive to green)\n\tconst dr = r1 - r2;\n\tconst dg = g1 - g2;\n\tconst db = b1 - b2;\n\treturn dr * dr * 0.299 + dg * dg * 0.587 + db * db * 0.114;\n}\n\nfunction rgbTo256(r: number, g: number, b: number): number {\n\t// Find closest color in the 6x6x6 cube\n\tconst rIdx = findClosestCubeIndex(r);\n\tconst gIdx = findClosestCubeIndex(g);\n\tconst bIdx = findClosestCubeIndex(b);\n\tconst cubeR = CUBE_VALUES[rIdx];\n\tconst cubeG = CUBE_VALUES[gIdx];\n\tconst cubeB = CUBE_VALUES[bIdx];\n\tconst cubeIndex = 16 + 36 * rIdx + 6 * gIdx + bIdx;\n\tconst cubeDist = colorDistance(r, g, b, cubeR, cubeG, cubeB);\n\n\t// Find closest grayscale\n\tconst gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);\n\tconst grayIdx = findClosestGrayIndex(gray);\n\tconst grayValue = GRAY_VALUES[grayIdx];\n\tconst grayIndex = 232 + grayIdx;\n\tconst grayDist = colorDistance(r, g, b, grayValue, grayValue, grayValue);\n\n\t// Check if color has noticeable saturation (hue matters)\n\t// If max-min spread is significant, prefer cube to preserve tint\n\tconst maxC = Math.max(r, g, b);\n\tconst minC = Math.min(r, g, b);\n\tconst spread = maxC - minC;\n\n\t// Only consider grayscale if color is nearly neutral (spread < 10)\n\t// AND grayscale is actually closer\n\tif (spread < 10 && grayDist < cubeDist) {\n\t\treturn grayIndex;\n\t}\n\n\treturn cubeIndex;\n}\n\nfunction hexTo256(hex: string): number {\n\tconst { r, g, b } = hexToRgb(hex);\n\treturn rgbTo256(r, g, b);\n}\n\nfunction fgAnsi(color: string | number, mode: ColorMode): string {\n\tif (color === \"\") return \"\\x1b[39m\";\n\tif (typeof color === \"number\") return `\\x1b[38;5;${color}m`;\n\tif (color.startsWith(\"#\")) {\n\t\tif (mode === \"truecolor\") {\n\t\t\tconst { r, g, b } = hexToRgb(color);\n\t\t\treturn `\\x1b[38;2;${r};${g};${b}m`;\n\t\t} else {\n\t\t\tconst index = hexTo256(color);\n\t\t\treturn `\\x1b[38;5;${index}m`;\n\t\t}\n\t}\n\tthrow new Error(`Invalid color value: ${color}`);\n}\n\nfunction bgAnsi(color: string | number, mode: ColorMode): string {\n\tif (color === \"\") return \"\\x1b[49m\";\n\tif (typeof color === \"number\") return `\\x1b[48;5;${color}m`;\n\tif (color.startsWith(\"#\")) {\n\t\tif (mode === \"truecolor\") {\n\t\t\tconst { r, g, b } = hexToRgb(color);\n\t\t\treturn `\\x1b[48;2;${r};${g};${b}m`;\n\t\t} else {\n\t\t\tconst index = hexTo256(color);\n\t\t\treturn `\\x1b[48;5;${index}m`;\n\t\t}\n\t}\n\tthrow new Error(`Invalid color value: ${color}`);\n}\n\nfunction resolveVarRefs(\n\tvalue: ColorValue,\n\tvars: Record,\n\tvisited = new Set(),\n): string | number {\n\tif (typeof value === \"number\" || value === \"\" || value.startsWith(\"#\")) {\n\t\treturn value;\n\t}\n\tif (visited.has(value)) {\n\t\tthrow new Error(`Circular variable reference detected: ${value}`);\n\t}\n\tif (!(value in vars)) {\n\t\tthrow new Error(`Variable reference not found: ${value}`);\n\t}\n\tvisited.add(value);\n\treturn resolveVarRefs(vars[value], vars, visited);\n}\n\nfunction resolveThemeColors>(\n\tcolors: T,\n\tvars: Record = {},\n): Record {\n\tconst resolved: Record = {};\n\tfor (const [key, value] of Object.entries(colors)) {\n\t\tresolved[key] = resolveVarRefs(value, vars);\n\t}\n\treturn resolved as Record;\n}\n\nfunction withThemeColorFallbacks(colors: ThemeJson[\"colors\"]): ThemeJson[\"colors\"] & { thinkingMax: ColorValue } {\n\treturn { ...colors, thinkingMax: colors.thinkingMax ?? colors.thinkingXhigh };\n}\n\n// ============================================================================\n// Theme Class\n// ============================================================================\n\nexport class Theme {\n\treadonly name?: string;\n\treadonly sourcePath?: string;\n\tsourceInfo?: SourceInfo;\n\tprivate fgColors: Map;\n\tprivate bgColors: Map;\n\tprivate mode: ColorMode;\n\n\tconstructor(\n\t\tfgColors: Record,\n\t\tbgColors: Record,\n\t\tmode: ColorMode,\n\t\toptions: { name?: string; sourcePath?: string; sourceInfo?: SourceInfo } = {},\n\t) {\n\t\tthis.name = options.name;\n\t\tthis.sourcePath = options.sourcePath;\n\t\tthis.sourceInfo = options.sourceInfo;\n\t\tthis.mode = mode;\n\t\tthis.fgColors = new Map();\n\t\tconst colors = { ...fgColors, thinkingMax: fgColors.thinkingMax ?? fgColors.thinkingXhigh };\n\t\tfor (const [key, value] of Object.entries(colors) as [ThemeColor, string | number][]) {\n\t\t\tthis.fgColors.set(key, fgAnsi(value, mode));\n\t\t}\n\t\tthis.bgColors = new Map();\n\t\tfor (const [key, value] of Object.entries(bgColors) as [ThemeBg, string | number][]) {\n\t\t\tthis.bgColors.set(key, bgAnsi(value, mode));\n\t\t}\n\t}\n\n\tfg(color: ThemeColor, text: string): string {\n\t\tconst ansi = this.fgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme color: ${color}`);\n\t\treturn `${ansi}${text}\\x1b[39m`; // Reset only foreground color\n\t}\n\n\tbg(color: ThemeBg, text: string): string {\n\t\tconst ansi = this.bgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme background color: ${color}`);\n\t\treturn `${ansi}${text}\\x1b[49m`; // Reset only background color\n\t}\n\n\tbold(text: string): string {\n\t\treturn chalk.bold(text);\n\t}\n\n\titalic(text: string): string {\n\t\treturn chalk.italic(text);\n\t}\n\n\tunderline(text: string): string {\n\t\treturn chalk.underline(text);\n\t}\n\n\tinverse(text: string): string {\n\t\treturn chalk.inverse(text);\n\t}\n\n\tstrikethrough(text: string): string {\n\t\treturn chalk.strikethrough(text);\n\t}\n\n\tgetFgAnsi(color: ThemeColor): string {\n\t\tconst ansi = this.fgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme color: ${color}`);\n\t\treturn ansi;\n\t}\n\n\tgetBgAnsi(color: ThemeBg): string {\n\t\tconst ansi = this.bgColors.get(color);\n\t\tif (!ansi) throw new Error(`Unknown theme background color: ${color}`);\n\t\treturn ansi;\n\t}\n\n\tgetColorMode(): ColorMode {\n\t\treturn this.mode;\n\t}\n\n\tgetThinkingBorderColor(level: ThinkingLevel): (str: string) => string {\n\t\t// Map thinking levels to dedicated theme colors\n\t\tswitch (level) {\n\t\t\tcase \"off\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingOff\", str);\n\t\t\tcase \"minimal\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingMinimal\", str);\n\t\t\tcase \"low\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingLow\", str);\n\t\t\tcase \"medium\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingMedium\", str);\n\t\t\tcase \"high\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingHigh\", str);\n\t\t\tcase \"xhigh\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingXhigh\", str);\n\t\t\tcase \"max\":\n\t\t\t\treturn (str: string) => this.fg(\"thinkingMax\", str);\n\t\t\tdefault:\n\t\t\t\treturn (str: string) => this.fg(\"thinkingOff\", str);\n\t\t}\n\t}\n\n\tgetBashModeBorderColor(): (str: string) => string {\n\t\treturn (str: string) => this.fg(\"bashMode\", str);\n\t}\n}\n\n// ============================================================================\n// Theme Loading\n// ============================================================================\n\nlet BUILTIN_THEMES: Record | undefined;\n\nfunction getBuiltinThemes(): Record {\n\tif (!BUILTIN_THEMES) {\n\t\tconst themesDir = getThemesDir();\n\t\tconst darkPath = path.join(themesDir, \"dark.json\");\n\t\tconst lightPath = path.join(themesDir, \"light.json\");\n\t\tBUILTIN_THEMES = {\n\t\t\tdark: JSON.parse(fs.readFileSync(darkPath, \"utf-8\")) as ThemeJson,\n\t\t\tlight: JSON.parse(fs.readFileSync(lightPath, \"utf-8\")) as ThemeJson,\n\t\t};\n\t}\n\treturn BUILTIN_THEMES;\n}\n\nexport function getAvailableThemes(): string[] {\n\treturn getAvailableThemesWithPaths().map(({ name }) => name);\n}\n\nexport interface ThemeInfo {\n\tname: string;\n\tpath: string | undefined;\n}\n\nexport function getAvailableThemesWithPaths(): ThemeInfo[] {\n\tconst themesDir = getThemesDir();\n\tconst result: ThemeInfo[] = [];\n\tconst seen = new Set();\n\tconst addTheme = (themeInfo: ThemeInfo) => {\n\t\tif (seen.has(themeInfo.name)) {\n\t\t\treturn;\n\t\t}\n\t\tseen.add(themeInfo.name);\n\t\tresult.push(themeInfo);\n\t};\n\n\t// Built-in themes\n\tfor (const name of Object.keys(getBuiltinThemes())) {\n\t\taddTheme({ name, path: path.join(themesDir, `${name}.json`) });\n\t}\n\n\t// Custom themes\n\tfor (const themeInfo of getCustomThemeInfos()) {\n\t\taddTheme(themeInfo);\n\t}\n\n\tfor (const [name, theme] of registeredThemes.entries()) {\n\t\taddTheme({ name, path: theme.sourcePath });\n\t}\n\n\treturn result.sort((a, b) => a.name.localeCompare(b.name));\n}\n\nfunction getCustomThemeInfos(): ThemeInfo[] {\n\tconst customThemesDir = getCustomThemesDir();\n\tconst result: ThemeInfo[] = [];\n\tif (!fs.existsSync(customThemesDir)) {\n\t\treturn result;\n\t}\n\n\tfor (const file of fs.readdirSync(customThemesDir)) {\n\t\tif (!file.endsWith(\".json\")) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst themePath = path.join(customThemesDir, file);\n\t\ttry {\n\t\t\tconst customTheme = loadThemeFromPath(themePath);\n\t\t\tif (customTheme.name) {\n\t\t\t\tresult.push({ name: customTheme.name, path: themePath });\n\t\t\t}\n\t\t} catch {\n\t\t\t// Invalid themes are ignored here; the resource loader reports them\n\t\t\t// during normal startup/reload.\n\t\t}\n\t}\n\treturn result;\n}\n\nfunction assertThemeNameIsValid(name: string): void {\n\tif (name.includes(\"/\")) {\n\t\tthrow new Error(\n\t\t\t`Invalid theme name \"${name}\": theme names cannot contain \"/\" because it is reserved for automatic light/dark theme settings.`,\n\t\t);\n\t}\n}\n\nfunction parseThemeJson(label: string, json: unknown): ThemeJson {\n\tif (!validateThemeJson.Check(json)) {\n\t\tconst errors = Array.from(validateThemeJson.Errors(json));\n\t\tconst missingColors = new Set();\n\t\tconst otherErrors: string[] = [];\n\n\t\tfor (const error of errors) {\n\t\t\tif (error.keyword === \"required\" && error.instancePath === \"/colors\") {\n\t\t\t\tconst requiredProperties = (error.params as { requiredProperties?: string[] }).requiredProperties;\n\t\t\t\tfor (const requiredProperty of requiredProperties ?? []) {\n\t\t\t\t\tmissingColors.add(requiredProperty);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst path = error.instancePath || \"/\";\n\t\t\totherErrors.push(` - ${path}: ${error.message}`);\n\t\t}\n\n\t\tlet errorMessage = `Invalid theme \"${label}\":\\n`;\n\t\tif (missingColors.size > 0) {\n\t\t\terrorMessage += \"\\nMissing required color tokens:\\n\";\n\t\t\terrorMessage += Array.from(missingColors)\n\t\t\t\t.sort()\n\t\t\t\t.map((color) => ` - ${color}`)\n\t\t\t\t.join(\"\\n\");\n\t\t\terrorMessage += '\\n\\nPlease add these colors to your theme\\'s \"colors\" object.';\n\t\t\terrorMessage += \"\\nSee the built-in themes (dark.json, light.json) for reference values.\";\n\t\t}\n\t\tif (otherErrors.length > 0) {\n\t\t\terrorMessage += `\\n\\nOther errors:\\n${otherErrors.join(\"\\n\")}`;\n\t\t}\n\n\t\tthrow new Error(errorMessage);\n\t}\n\n\tconst themeJson = json as ThemeJson;\n\tassertThemeNameIsValid(themeJson.name);\n\treturn themeJson;\n}\n\nfunction parseThemeJsonContent(label: string, content: string): ThemeJson {\n\tlet json: unknown;\n\ttry {\n\t\tjson = JSON.parse(content);\n\t} catch (error) {\n\t\tthrow new Error(`Failed to parse theme ${label}: ${error}`);\n\t}\n\treturn parseThemeJson(label, json);\n}\n\nfunction loadThemeJson(name: string): ThemeJson {\n\tconst builtinThemes = getBuiltinThemes();\n\tif (name in builtinThemes) {\n\t\treturn builtinThemes[name];\n\t}\n\tconst registeredTheme = registeredThemes.get(name);\n\tif (registeredTheme?.sourcePath) {\n\t\tconst content = fs.readFileSync(registeredTheme.sourcePath, \"utf-8\");\n\t\treturn parseThemeJsonContent(registeredTheme.sourcePath, content);\n\t}\n\tif (registeredTheme) {\n\t\tthrow new Error(`Theme \"${name}\" does not have a source path for export`);\n\t}\n\tconst customThemesDir = getCustomThemesDir();\n\tconst themePath = path.join(customThemesDir, `${name}.json`);\n\tif (!fs.existsSync(themePath)) {\n\t\tthrow new Error(`Theme not found: ${name}`);\n\t}\n\tconst content = fs.readFileSync(themePath, \"utf-8\");\n\treturn parseThemeJsonContent(name, content);\n}\n\nfunction createTheme(themeJson: ThemeJson, mode?: ColorMode, sourcePath?: string): Theme {\n\tconst colorMode = mode ?? (getCapabilities().trueColor ? \"truecolor\" : \"256color\");\n\tconst resolvedColors = resolveThemeColors(withThemeColorFallbacks(themeJson.colors), themeJson.vars);\n\tconst fgColors: Record = {} as Record;\n\tconst bgColors: Record = {} as Record;\n\tconst bgColorKeys: Set = new Set([\n\t\t\"selectedBg\",\n\t\t\"userMessageBg\",\n\t\t\"customMessageBg\",\n\t\t\"toolPendingBg\",\n\t\t\"toolSuccessBg\",\n\t\t\"toolErrorBg\",\n\t]);\n\tfor (const [key, value] of Object.entries(resolvedColors)) {\n\t\tif (bgColorKeys.has(key)) {\n\t\t\tbgColors[key as ThemeBg] = value;\n\t\t} else {\n\t\t\tfgColors[key as ThemeColor] = value;\n\t\t}\n\t}\n\treturn new Theme(fgColors, bgColors, colorMode, {\n\t\tname: themeJson.name,\n\t\tsourcePath,\n\t});\n}\n\nexport function loadThemeFromPath(themePath: string, mode?: ColorMode): Theme {\n\tconst content = fs.readFileSync(themePath, \"utf-8\");\n\tconst themeJson = parseThemeJsonContent(themePath, content);\n\treturn createTheme(themeJson, mode, themePath);\n}\n\nfunction loadTheme(name: string, mode?: ColorMode): Theme {\n\tconst registeredTheme = registeredThemes.get(name);\n\tif (registeredTheme) {\n\t\treturn registeredTheme;\n\t}\n\tconst themeJson = loadThemeJson(name);\n\treturn createTheme(themeJson, mode);\n}\n\nexport function getThemeByName(name: string): Theme | undefined {\n\ttry {\n\t\treturn loadTheme(name);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport type TerminalTheme = \"dark\" | \"light\";\n\nexport function parseAutoThemeSetting(\n\tthemeSetting: string | undefined,\n): { lightTheme: string; darkTheme: string } | undefined {\n\tif (!themeSetting) return undefined;\n\tconst slashIndex = themeSetting.indexOf(\"/\");\n\tif (slashIndex === -1 || themeSetting.indexOf(\"/\", slashIndex + 1) !== -1) {\n\t\treturn undefined;\n\t}\n\n\tconst lightTheme = themeSetting.slice(0, slashIndex).trim();\n\tconst darkTheme = themeSetting.slice(slashIndex + 1).trim();\n\tif (!lightTheme || !darkTheme) {\n\t\treturn undefined;\n\t}\n\treturn { lightTheme, darkTheme };\n}\n\nexport function resolveThemeSetting(\n\tthemeSetting: string | undefined,\n\tterminalTheme: TerminalTheme,\n): string | undefined {\n\tconst autoTheme = parseAutoThemeSetting(themeSetting);\n\tif (autoTheme) {\n\t\treturn terminalTheme === \"light\" ? autoTheme.lightTheme : autoTheme.darkTheme;\n\t}\n\tif (themeSetting?.includes(\"/\")) return undefined;\n\tif (typeof themeSetting === \"string\") return themeSetting;\n\treturn undefined;\n}\n\nexport interface TerminalThemeDetection {\n\ttheme: TerminalTheme;\n\tsource: \"terminal background\" | \"COLORFGBG\" | \"fallback\";\n\tdetail: string;\n\tconfidence: \"high\" | \"low\";\n}\n\nexport interface TerminalThemeDetectionOptions {\n\tenv?: NodeJS.ProcessEnv;\n}\n\nexport interface TerminalBackgroundThemeDetector {\n\tqueryTerminalBackgroundColor({ timeoutMs }: { timeoutMs: number }): Promise;\n}\n\nexport interface TerminalAutoThemeDetector extends TerminalBackgroundThemeDetector {\n\tqueryTerminalColorScheme?({ timeoutMs }: { timeoutMs: number }): Promise;\n}\n\nexport interface TerminalBackgroundThemeDetectionOptions extends TerminalThemeDetectionOptions {\n\tui: TerminalBackgroundThemeDetector;\n\ttimeoutMs: number;\n}\n\nexport interface TerminalAutoThemeDetectionOptions extends TerminalThemeDetectionOptions {\n\tui: TerminalAutoThemeDetector;\n\ttimeoutMs: number;\n}\n\nfunction getColorFgBgBackgroundIndex(colorfgbg: string): number | undefined {\n\tconst parts = colorfgbg.split(\";\");\n\tfor (let i = parts.length - 1; i >= 0; i--) {\n\t\tconst bg = parseInt(parts[i].trim(), 10);\n\t\tif (Number.isInteger(bg) && bg >= 0 && bg <= 255) {\n\t\t\treturn bg;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction getRgbColorLuminance({ r, g, b }: RgbColor): number {\n\tconst toLinear = (channel: number) => {\n\t\tconst value = channel / 255;\n\t\treturn value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;\n\t};\n\treturn 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b);\n}\n\nfunction getAnsiColorLuminance(index: number): number {\n\treturn getRgbColorLuminance(hexToRgb(ansi256ToHex(index)));\n}\n\nexport function getThemeForRgbColor(rgb: RgbColor): TerminalTheme {\n\treturn getRgbColorLuminance(rgb) >= 0.5 ? \"light\" : \"dark\";\n}\n\nexport function detectTerminalBackgroundFromEnv(options: TerminalThemeDetectionOptions = {}): TerminalThemeDetection {\n\tconst env = options.env ?? process.env;\n\tconst colorfgbg = env.COLORFGBG || \"\";\n\tconst bg = getColorFgBgBackgroundIndex(colorfgbg);\n\tif (bg !== undefined) {\n\t\treturn {\n\t\t\ttheme: getAnsiColorLuminance(bg) >= 0.5 ? \"light\" : \"dark\",\n\t\t\tsource: \"COLORFGBG\",\n\t\t\tdetail: `background color index ${bg}`,\n\t\t\tconfidence: \"high\",\n\t\t};\n\t}\n\n\treturn {\n\t\ttheme: \"dark\",\n\t\tsource: \"fallback\",\n\t\tdetail: \"no terminal background hint found\",\n\t\tconfidence: \"low\",\n\t};\n}\n\nexport async function detectTerminalBackgroundTheme({\n\tui,\n\ttimeoutMs,\n\tenv,\n}: TerminalBackgroundThemeDetectionOptions): Promise {\n\ttry {\n\t\tconst rgb = await ui.queryTerminalBackgroundColor({ timeoutMs });\n\t\tif (rgb) {\n\t\t\treturn {\n\t\t\t\ttheme: getThemeForRgbColor(rgb),\n\t\t\t\tsource: \"terminal background\",\n\t\t\t\tdetail: `OSC 11 background rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`,\n\t\t\t\tconfidence: \"high\",\n\t\t\t};\n\t\t}\n\t} catch {\n\t\t// Fall back to environment-based detection when the terminal query fails.\n\t}\n\n\treturn detectTerminalBackgroundFromEnv({ env });\n}\n\nexport async function detectTerminalThemeForAuto({\n\tui,\n\ttimeoutMs,\n\tenv,\n}: TerminalAutoThemeDetectionOptions): Promise {\n\ttry {\n\t\tconst colorScheme = await ui.queryTerminalColorScheme?.({ timeoutMs });\n\t\tif (colorScheme) return colorScheme;\n\t} catch {\n\t\t// Fall back to OSC 11 / COLORFGBG detection when color-scheme DSR is unsupported.\n\t}\n\treturn (await detectTerminalBackgroundTheme({ ui, timeoutMs, env })).theme;\n}\n\nexport function getDefaultTheme(): string {\n\treturn detectTerminalBackgroundFromEnv().theme;\n}\n\n// ============================================================================\n// Global Theme Instance\n// ============================================================================\n\n// Use globalThis to share theme across module loaders (tsx + jiti in dev mode)\nconst THEME_KEY = Symbol.for(\"@earendil-works/pi-coding-agent:theme\");\nconst THEME_KEY_OLD = Symbol.for(\"@mariozechner/pi-coding-agent:theme\");\n\n// Export theme as a getter that reads from globalThis\n// This ensures all module instances (tsx, jiti) see the same theme\nexport const theme: Theme = new Proxy({} as Theme, {\n\tget(_target, prop) {\n\t\tconst t = (globalThis as Record)[THEME_KEY];\n\t\tif (!t) throw new Error(\"Theme not initialized. Call initTheme() first.\");\n\t\treturn (t as unknown as Record)[prop];\n\t},\n});\n\nfunction setGlobalTheme(t: Theme): void {\n\t(globalThis as Record)[THEME_KEY] = t;\n\t(globalThis as Record)[THEME_KEY_OLD] = t;\n}\n\nlet currentThemeName: string | undefined;\nlet themeWatcher: fs.FSWatcher | undefined;\nlet themeReloadTimer: NodeJS.Timeout | undefined;\nlet onThemeChangeCallback: (() => void) | undefined;\nconst registeredThemes = new Map();\n\nexport function setRegisteredThemes(themes: Theme[]): void {\n\tregisteredThemes.clear();\n\tfor (const theme of themes) {\n\t\tif (theme.name) {\n\t\t\tassertThemeNameIsValid(theme.name);\n\t\t\tregisteredThemes.set(theme.name, theme);\n\t\t}\n\t}\n}\n\nexport function initTheme(themeName?: string, enableWatcher: boolean = false): void {\n\tconst name = themeName ?? getDefaultTheme();\n\tcurrentThemeName = name;\n\ttry {\n\t\tsetGlobalTheme(loadTheme(name));\n\t\tif (enableWatcher) {\n\t\t\tstartThemeWatcher();\n\t\t}\n\t} catch (_error) {\n\t\t// Theme is invalid - fall back to dark theme silently\n\t\tcurrentThemeName = \"dark\";\n\t\tsetGlobalTheme(loadTheme(\"dark\"));\n\t\t// Don't start watcher for fallback theme\n\t}\n}\n\nexport function setTheme(name: string, enableWatcher: boolean = false): { success: boolean; error?: string } {\n\tcurrentThemeName = name;\n\ttry {\n\t\tsetGlobalTheme(loadTheme(name));\n\t\tif (enableWatcher) {\n\t\t\tstartThemeWatcher();\n\t\t}\n\t\tif (onThemeChangeCallback) {\n\t\t\tonThemeChangeCallback();\n\t\t}\n\t\treturn { success: true };\n\t} catch (error) {\n\t\t// Theme is invalid - fall back to dark theme\n\t\tcurrentThemeName = \"dark\";\n\t\tsetGlobalTheme(loadTheme(\"dark\"));\n\t\t// Don't start watcher for fallback theme\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t};\n\t}\n}\n\nexport function setThemeInstance(themeInstance: Theme): void {\n\tsetGlobalTheme(themeInstance);\n\tcurrentThemeName = \"\";\n\tstopThemeWatcher(); // Can't watch a direct instance\n\tif (onThemeChangeCallback) {\n\t\tonThemeChangeCallback();\n\t}\n}\n\nexport function onThemeChange(callback: () => void): void {\n\tonThemeChangeCallback = callback;\n}\n\nfunction startThemeWatcher(): void {\n\tstopThemeWatcher();\n\n\t// Only watch if it's a custom theme (not built-in)\n\tif (!currentThemeName || currentThemeName === \"dark\" || currentThemeName === \"light\") {\n\t\treturn;\n\t}\n\n\tconst customThemesDir = getCustomThemesDir();\n\tconst watchedThemeName = currentThemeName;\n\tconst watchedFileName = `${watchedThemeName}.json`;\n\tconst themeFile = path.join(customThemesDir, watchedFileName);\n\n\t// Only watch if the file exists\n\tif (!fs.existsSync(themeFile)) {\n\t\treturn;\n\t}\n\n\tconst scheduleReload = () => {\n\t\tif (themeReloadTimer) {\n\t\t\tclearTimeout(themeReloadTimer);\n\t\t}\n\t\tthemeReloadTimer = setTimeout(() => {\n\t\t\tthemeReloadTimer = undefined;\n\n\t\t\t// Ignore stale timers after switching themes or stopping the watcher\n\t\t\tif (currentThemeName !== watchedThemeName) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Keep the last successfully loaded theme active if the file is temporarily missing\n\t\t\tif (!fs.existsSync(themeFile)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Reload the theme from disk and refresh the registry cache\n\t\t\t\tconst reloadedTheme = loadThemeFromPath(themeFile);\n\t\t\t\tregisteredThemes.set(watchedThemeName, reloadedTheme);\n\t\t\t\tsetGlobalTheme(reloadedTheme);\n\t\t\t\t// Notify callback (to invalidate UI)\n\t\t\t\tif (onThemeChangeCallback) {\n\t\t\t\t\tonThemeChangeCallback();\n\t\t\t\t}\n\t\t\t} catch (_error) {\n\t\t\t\t// Ignore errors (file might be in invalid state while being edited)\n\t\t\t}\n\t\t}, 100);\n\t};\n\n\tthemeWatcher =\n\t\twatchWithErrorHandler(\n\t\t\tcustomThemesDir,\n\t\t\t(_eventType, filename) => {\n\t\t\t\tif (currentThemeName !== watchedThemeName) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!filename) {\n\t\t\t\t\tscheduleReload();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (filename !== watchedFileName) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tscheduleReload();\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tcloseWatcher(themeWatcher);\n\t\t\t\tthemeWatcher = undefined;\n\t\t\t},\n\t\t) ?? undefined;\n}\n\nexport function stopThemeWatcher(): void {\n\tif (themeReloadTimer) {\n\t\tclearTimeout(themeReloadTimer);\n\t\tthemeReloadTimer = undefined;\n\t}\n\tcloseWatcher(themeWatcher);\n\tthemeWatcher = undefined;\n}\n\n// ============================================================================\n// HTML Export Helpers\n// ============================================================================\n\n/**\n * Convert a 256-color index to hex string.\n * Indices 0-15: basic colors (approximate)\n * Indices 16-231: 6x6x6 color cube\n * Indices 232-255: grayscale ramp\n */\nfunction ansi256ToHex(index: number): string {\n\t// Basic colors (0-15) - approximate common terminal values\n\tconst basicColors = [\n\t\t\"#000000\",\n\t\t\"#800000\",\n\t\t\"#008000\",\n\t\t\"#808000\",\n\t\t\"#000080\",\n\t\t\"#800080\",\n\t\t\"#008080\",\n\t\t\"#c0c0c0\",\n\t\t\"#808080\",\n\t\t\"#ff0000\",\n\t\t\"#00ff00\",\n\t\t\"#ffff00\",\n\t\t\"#0000ff\",\n\t\t\"#ff00ff\",\n\t\t\"#00ffff\",\n\t\t\"#ffffff\",\n\t];\n\tif (index < 16) {\n\t\treturn basicColors[index];\n\t}\n\n\t// Color cube (16-231): 6x6x6 = 216 colors\n\tif (index < 232) {\n\t\tconst cubeIndex = index - 16;\n\t\tconst r = Math.floor(cubeIndex / 36);\n\t\tconst g = Math.floor((cubeIndex % 36) / 6);\n\t\tconst b = cubeIndex % 6;\n\t\tconst toHex = (n: number) => (n === 0 ? 0 : 55 + n * 40).toString(16).padStart(2, \"0\");\n\t\treturn `#${toHex(r)}${toHex(g)}${toHex(b)}`;\n\t}\n\n\t// Grayscale (232-255): 24 shades\n\tconst gray = 8 + (index - 232) * 10;\n\tconst grayHex = gray.toString(16).padStart(2, \"0\");\n\treturn `#${grayHex}${grayHex}${grayHex}`;\n}\n\n/**\n * Get resolved theme colors as CSS-compatible hex strings.\n * Used by HTML export to generate CSS custom properties.\n */\nexport function getResolvedThemeColors(themeName?: string): Record {\n\tconst name = themeName ?? currentThemeName ?? getDefaultTheme();\n\tconst isLight = name === \"light\";\n\tconst themeJson = loadThemeJson(name);\n\tconst resolved = resolveThemeColors(withThemeColorFallbacks(themeJson.colors), themeJson.vars);\n\n\t// Default text color for empty values (terminal uses default fg color)\n\tconst defaultText = isLight ? \"#000000\" : \"#e5e5e7\";\n\n\tconst cssColors: Record = {};\n\tfor (const [key, value] of Object.entries(resolved)) {\n\t\tif (typeof value === \"number\") {\n\t\t\tcssColors[key] = ansi256ToHex(value);\n\t\t} else if (value === \"\") {\n\t\t\t// Empty means default terminal color - use sensible fallback for HTML\n\t\t\tcssColors[key] = defaultText;\n\t\t} else {\n\t\t\tcssColors[key] = value;\n\t\t}\n\t}\n\treturn cssColors;\n}\n\n/**\n * Check if a theme is a \"light\" theme (for CSS that needs light/dark variants).\n */\nexport function isLightTheme(themeName?: string): boolean {\n\t// Currently just check the name - could be extended to analyze colors\n\treturn themeName === \"light\";\n}\n\n/**\n * Get explicit export colors from theme JSON, if specified.\n * Returns undefined for each color that isn't explicitly set.\n */\nexport function getThemeExportColors(themeName?: string): {\n\tpageBg?: string;\n\tcardBg?: string;\n\tinfoBg?: string;\n} {\n\tconst name = themeName ?? currentThemeName ?? getDefaultTheme();\n\ttry {\n\t\tconst themeJson = loadThemeJson(name);\n\t\tconst exportSection = themeJson.export;\n\t\tif (!exportSection) return {};\n\n\t\tconst vars = themeJson.vars ?? {};\n\t\tconst resolve = (value: ColorValue | undefined): string | undefined => {\n\t\t\tif (value === undefined) return undefined;\n\t\t\tconst resolved = resolveVarRefs(value, vars);\n\t\t\tif (typeof resolved === \"number\") return ansi256ToHex(resolved);\n\t\t\tif (resolved === \"\") return undefined;\n\t\t\treturn resolved;\n\t\t};\n\n\t\treturn {\n\t\t\tpageBg: resolve(exportSection.pageBg),\n\t\t\tcardBg: resolve(exportSection.cardBg),\n\t\t\tinfoBg: resolve(exportSection.infoBg),\n\t\t};\n\t} catch {\n\t\treturn {};\n\t}\n}\n\n// ============================================================================\n// TUI Helpers\n// ============================================================================\n\ntype CliHighlightTheme = Record string>;\n\nlet cachedHighlightThemeFor: Theme | undefined;\nlet cachedCliHighlightTheme: CliHighlightTheme | undefined;\n\nfunction buildCliHighlightTheme(t: Theme): CliHighlightTheme {\n\treturn {\n\t\tkeyword: (s: string) => t.fg(\"syntaxKeyword\", s),\n\t\tbuilt_in: (s: string) => t.fg(\"syntaxType\", s),\n\t\tliteral: (s: string) => t.fg(\"syntaxNumber\", s),\n\t\tnumber: (s: string) => t.fg(\"syntaxNumber\", s),\n\t\tregexp: (s: string) => t.fg(\"syntaxString\", s),\n\t\tstring: (s: string) => t.fg(\"syntaxString\", s),\n\t\tcomment: (s: string) => t.fg(\"syntaxComment\", s),\n\t\tdoctag: (s: string) => t.fg(\"syntaxComment\", s),\n\t\tmeta: (s: string) => t.fg(\"muted\", s),\n\t\tfunction: (s: string) => t.fg(\"syntaxFunction\", s),\n\t\ttitle: (s: string) => t.fg(\"syntaxFunction\", s),\n\t\tclass: (s: string) => t.fg(\"syntaxType\", s),\n\t\ttype: (s: string) => t.fg(\"syntaxType\", s),\n\t\ttag: (s: string) => t.fg(\"syntaxPunctuation\", s),\n\t\tname: (s: string) => t.fg(\"syntaxKeyword\", s),\n\t\tattr: (s: string) => t.fg(\"syntaxVariable\", s),\n\t\tvariable: (s: string) => t.fg(\"syntaxVariable\", s),\n\t\tparams: (s: string) => t.fg(\"syntaxVariable\", s),\n\t\toperator: (s: string) => t.fg(\"syntaxOperator\", s),\n\t\tpunctuation: (s: string) => t.fg(\"syntaxPunctuation\", s),\n\t\temphasis: (s: string) => t.italic(s),\n\t\tstrong: (s: string) => t.bold(s),\n\t\tlink: (s: string) => t.underline(s),\n\t\taddition: (s: string) => t.fg(\"toolDiffAdded\", s),\n\t\tdeletion: (s: string) => t.fg(\"toolDiffRemoved\", s),\n\t};\n}\n\nfunction getCliHighlightTheme(t: Theme): CliHighlightTheme {\n\tif (cachedHighlightThemeFor !== t || !cachedCliHighlightTheme) {\n\t\tcachedHighlightThemeFor = t;\n\t\tcachedCliHighlightTheme = buildCliHighlightTheme(t);\n\t}\n\treturn cachedCliHighlightTheme;\n}\n\n/**\n * Highlight code with syntax coloring based on file extension or language.\n * Returns array of highlighted lines.\n */\nexport function highlightCode(code: string, lang?: string): string[] {\n\t// Validate language before highlighting to avoid stderr spam from cli-highlight\n\tconst validLang = lang && supportsLanguage(lang) ? lang : undefined;\n\t// Skip highlighting when no valid language is specified. cli-highlight's\n\t// auto-detection is unreliable and can misidentify prose as AppleScript,\n\t// LiveCodeServer, etc., coloring random English words as keywords.\n\tif (!validLang) {\n\t\treturn code.split(\"\\n\").map((line) => theme.fg(\"mdCodeBlock\", line));\n\t}\n\tconst opts = {\n\t\tlanguage: validLang,\n\t\tignoreIllegals: true,\n\t\ttheme: getCliHighlightTheme(theme),\n\t};\n\ttry {\n\t\treturn highlight(code, opts).split(\"\\n\");\n\t} catch {\n\t\treturn code.split(\"\\n\");\n\t}\n}\n\n/**\n * Get language identifier from file path extension.\n */\nexport function getLanguageFromPath(filePath: string): string | undefined {\n\tconst ext = filePath.split(\".\").pop()?.toLowerCase();\n\tif (!ext) return undefined;\n\n\tconst extToLang: Record = {\n\t\tts: \"typescript\",\n\t\ttsx: \"typescript\",\n\t\tjs: \"javascript\",\n\t\tjsx: \"javascript\",\n\t\tmjs: \"javascript\",\n\t\tcjs: \"javascript\",\n\t\tpy: \"python\",\n\t\trb: \"ruby\",\n\t\trs: \"rust\",\n\t\tgo: \"go\",\n\t\tjava: \"java\",\n\t\tkt: \"kotlin\",\n\t\tswift: \"swift\",\n\t\tc: \"c\",\n\t\th: \"c\",\n\t\tcpp: \"cpp\",\n\t\tcc: \"cpp\",\n\t\tcxx: \"cpp\",\n\t\thpp: \"cpp\",\n\t\tcs: \"csharp\",\n\t\tphp: \"php\",\n\t\tsh: \"bash\",\n\t\tbash: \"bash\",\n\t\tzsh: \"bash\",\n\t\tfish: \"fish\",\n\t\tps1: \"powershell\",\n\t\tsql: \"sql\",\n\t\thtml: \"html\",\n\t\thtm: \"html\",\n\t\tcss: \"css\",\n\t\tscss: \"scss\",\n\t\tsass: \"sass\",\n\t\tless: \"less\",\n\t\tjson: \"json\",\n\t\tyaml: \"yaml\",\n\t\tyml: \"yaml\",\n\t\ttoml: \"toml\",\n\t\txml: \"xml\",\n\t\tmd: \"markdown\",\n\t\tmarkdown: \"markdown\",\n\t\tdockerfile: \"dockerfile\",\n\t\tmakefile: \"makefile\",\n\t\tcmake: \"cmake\",\n\t\tlua: \"lua\",\n\t\tperl: \"perl\",\n\t\tr: \"r\",\n\t\tscala: \"scala\",\n\t\tclj: \"clojure\",\n\t\tex: \"elixir\",\n\t\texs: \"elixir\",\n\t\terl: \"erlang\",\n\t\ths: \"haskell\",\n\t\tml: \"ocaml\",\n\t\tvim: \"vim\",\n\t\tgraphql: \"graphql\",\n\t\tproto: \"protobuf\",\n\t\ttf: \"hcl\",\n\t\thcl: \"hcl\",\n\t};\n\n\treturn extToLang[ext];\n}\n\nexport function getMarkdownTheme(): MarkdownTheme {\n\treturn {\n\t\theading: (text: string) => theme.fg(\"mdHeading\", text),\n\t\tlink: (text: string) => theme.fg(\"mdLink\", text),\n\t\tlinkUrl: (text: string) => theme.fg(\"mdLinkUrl\", text),\n\t\tcode: (text: string) => theme.fg(\"mdCode\", text),\n\t\tcodeBlock: (text: string) => theme.fg(\"mdCodeBlock\", text),\n\t\tcodeBlockBorder: (text: string) => theme.fg(\"mdCodeBlockBorder\", text),\n\t\tquote: (text: string) => theme.fg(\"mdQuote\", text),\n\t\tquoteBorder: (text: string) => theme.fg(\"mdQuoteBorder\", text),\n\t\thr: (text: string) => theme.fg(\"mdHr\", text),\n\t\tlistBullet: (text: string) => theme.fg(\"mdListBullet\", text),\n\t\tbold: (text: string) => theme.bold(text),\n\t\titalic: (text: string) => theme.italic(text),\n\t\tunderline: (text: string) => theme.underline(text),\n\t\tstrikethrough: (text: string) => chalk.strikethrough(text),\n\t\thighlightCode: (code: string, lang?: string): string[] => {\n\t\t\t// Validate language before highlighting to avoid stderr spam from cli-highlight\n\t\t\tconst validLang = lang && supportsLanguage(lang) ? lang : undefined;\n\t\t\t// Skip highlighting when no valid language is specified. cli-highlight's\n\t\t\t// auto-detection is unreliable and can misidentify prose as AppleScript,\n\t\t\t// LiveCodeServer, etc., coloring random English words as keywords.\n\t\t\tif (!validLang) {\n\t\t\t\treturn code.split(\"\\n\").map((line) => theme.fg(\"mdCodeBlock\", line));\n\t\t\t}\n\t\t\tconst opts = {\n\t\t\t\tlanguage: validLang,\n\t\t\t\tignoreIllegals: true,\n\t\t\t\ttheme: getCliHighlightTheme(theme),\n\t\t\t};\n\t\t\ttry {\n\t\t\t\treturn highlight(code, opts).split(\"\\n\");\n\t\t\t} catch {\n\t\t\t\treturn code.split(\"\\n\").map((line) => theme.fg(\"mdCodeBlock\", line));\n\t\t\t}\n\t\t},\n\t};\n}\n\nexport function getSelectListTheme(): SelectListTheme {\n\treturn {\n\t\tselectedPrefix: (text: string) => theme.fg(\"accent\", text),\n\t\tselectedText: (text: string) => theme.fg(\"accent\", text),\n\t\tdescription: (text: string) => theme.fg(\"muted\", text),\n\t\tscrollInfo: (text: string) => theme.fg(\"muted\", text),\n\t\tnoMatch: (text: string) => theme.fg(\"muted\", text),\n\t};\n}\n\nexport function getEditorTheme(): EditorTheme {\n\treturn {\n\t\tborderColor: (text: string) => theme.fg(\"borderMuted\", text),\n\t\tselectList: getSelectListTheme(),\n\t};\n}\n\nexport function getSettingsListTheme(): SettingsListTheme {\n\treturn {\n\t\tlabel: (text: string, selected: boolean) => (selected ? theme.fg(\"accent\", text) : text),\n\t\tvalue: (text: string, selected: boolean) => (selected ? theme.fg(\"accent\", text) : theme.fg(\"muted\", text)),\n\t\tdescription: (text: string) => theme.fg(\"dim\", text),\n\t\tcursor: theme.fg(\"accent\", \"→ \"),\n\t\thint: (text: string) => theme.fg(\"dim\", text),\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/modes/print-mode.d.ts b/dist/modes/print-mode.d.ts new file mode 100644 index 0000000..154075a --- /dev/null +++ b/dist/modes/print-mode.d.ts @@ -0,0 +1,28 @@ +/** + * Print mode (single-shot): Send prompts, output result, exit. + * + * Used for: + * - `pi -p "prompt"` - text output + * - `pi --mode json "prompt"` - JSON event stream + */ +import type { ImageContent } from "@earendil-works/pi-ai"; +import type { AgentSessionRuntime } from "../core/agent-session-runtime.ts"; +/** + * Options for print mode. + */ +export interface PrintModeOptions { + /** Output mode: "text" for final response only, "json" for all events */ + mode: "text" | "json"; + /** Array of additional prompts to send after initialMessage */ + messages?: string[]; + /** First message to send (may contain @file content) */ + initialMessage?: string; + /** Images to attach to the initial message */ + initialImages?: ImageContent[]; +} +/** + * Run in print (single-shot) mode. + * Sends prompts to the agent and outputs the result. + */ +export declare function runPrintMode(runtimeHost: AgentSessionRuntime, options: PrintModeOptions): Promise; +//# sourceMappingURL=print-mode.d.ts.map \ No newline at end of file diff --git a/dist/modes/print-mode.d.ts.map b/dist/modes/print-mode.d.ts.map new file mode 100644 index 0000000..95f59a8 --- /dev/null +++ b/dist/modes/print-mode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"print-mode.d.ts","sourceRoot":"","sources":["../../src/modes/print-mode.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAoB,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC5E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAI5E;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAChC,yEAAyE;IACzE,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IACtB,+DAA+D;IAC/D,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,wDAAwD;IACxD,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,8CAA8C;IAC9C,aAAa,CAAC,EAAE,YAAY,EAAE,CAAC;CAC/B;AAED;;;GAGG;AACH,wBAAsB,YAAY,CAAC,WAAW,EAAE,mBAAmB,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,MAAM,CAAC,CA+H/G","sourcesContent":["/**\n * Print mode (single-shot): Send prompts, output result, exit.\n *\n * Used for:\n * - `pi -p \"prompt\"` - text output\n * - `pi --mode json \"prompt\"` - JSON event stream\n */\n\nimport type { AssistantMessage, ImageContent } from \"@earendil-works/pi-ai\";\nimport type { AgentSessionRuntime } from \"../core/agent-session-runtime.ts\";\nimport { flushRawStdout, writeRawStdout } from \"../core/output-guard.ts\";\nimport { killTrackedDetachedChildren } from \"../utils/shell.ts\";\n\n/**\n * Options for print mode.\n */\nexport interface PrintModeOptions {\n\t/** Output mode: \"text\" for final response only, \"json\" for all events */\n\tmode: \"text\" | \"json\";\n\t/** Array of additional prompts to send after initialMessage */\n\tmessages?: string[];\n\t/** First message to send (may contain @file content) */\n\tinitialMessage?: string;\n\t/** Images to attach to the initial message */\n\tinitialImages?: ImageContent[];\n}\n\n/**\n * Run in print (single-shot) mode.\n * Sends prompts to the agent and outputs the result.\n */\nexport async function runPrintMode(runtimeHost: AgentSessionRuntime, options: PrintModeOptions): Promise {\n\tconst { mode, messages = [], initialMessage, initialImages } = options;\n\tlet exitCode = 0;\n\tlet session = runtimeHost.session;\n\tlet unsubscribe: (() => void) | undefined;\n\tlet disposed = false;\n\tconst signalCleanupHandlers: Array<() => void> = [];\n\n\tconst disposeRuntime = async (): Promise => {\n\t\tif (disposed) return;\n\t\tdisposed = true;\n\t\tunsubscribe?.();\n\t\tawait runtimeHost.dispose();\n\t};\n\n\tconst registerSignalHandlers = (): void => {\n\t\tconst signals: NodeJS.Signals[] = [\"SIGTERM\"];\n\t\tif (process.platform !== \"win32\") {\n\t\t\tsignals.push(\"SIGHUP\");\n\t\t}\n\n\t\tfor (const signal of signals) {\n\t\t\tconst handler = () => {\n\t\t\t\tkillTrackedDetachedChildren();\n\t\t\t\tvoid disposeRuntime().finally(() => {\n\t\t\t\t\tprocess.exit(signal === \"SIGHUP\" ? 129 : 143);\n\t\t\t\t});\n\t\t\t};\n\t\t\tprocess.on(signal, handler);\n\t\t\tsignalCleanupHandlers.push(() => process.off(signal, handler));\n\t\t}\n\t};\n\n\tregisterSignalHandlers();\n\n\truntimeHost.setRebindSession(async () => {\n\t\tawait rebindSession();\n\t});\n\n\tconst rebindSession = async (): Promise => {\n\t\tsession = runtimeHost.session;\n\t\tawait session.bindExtensions({\n\t\t\tmode: mode === \"json\" ? \"json\" : \"print\",\n\t\t\tcommandContextActions: {\n\t\t\t\twaitForIdle: () => session.waitForIdle(),\n\t\t\t\tnewSession: async (newSessionOptions) => runtimeHost.newSession(newSessionOptions),\n\t\t\t\tfork: async (entryId, forkOptions) => {\n\t\t\t\t\tconst result = await runtimeHost.fork(entryId, forkOptions);\n\t\t\t\t\treturn { cancelled: result.cancelled };\n\t\t\t\t},\n\t\t\t\tnavigateTree: async (targetId, navigateOptions) => {\n\t\t\t\t\tconst result = await session.navigateTree(targetId, {\n\t\t\t\t\t\tsummarize: navigateOptions?.summarize,\n\t\t\t\t\t\tcustomInstructions: navigateOptions?.customInstructions,\n\t\t\t\t\t\treplaceInstructions: navigateOptions?.replaceInstructions,\n\t\t\t\t\t\tlabel: navigateOptions?.label,\n\t\t\t\t\t});\n\t\t\t\t\treturn { cancelled: result.cancelled };\n\t\t\t\t},\n\t\t\t\tswitchSession: async (sessionPath, switchOptions) => {\n\t\t\t\t\treturn runtimeHost.switchSession(sessionPath, switchOptions);\n\t\t\t\t},\n\t\t\t\treload: async () => {\n\t\t\t\t\tawait session.reload();\n\t\t\t\t},\n\t\t\t},\n\t\t\tonError: (err) => {\n\t\t\t\tconsole.error(`Extension error (${err.extensionPath}): ${err.error}`);\n\t\t\t},\n\t\t});\n\n\t\tunsubscribe?.();\n\t\tunsubscribe = session.subscribe((event) => {\n\t\t\tif (mode === \"json\") {\n\t\t\t\twriteRawStdout(`${JSON.stringify(event)}\\n`);\n\t\t\t}\n\t\t});\n\t};\n\n\ttry {\n\t\tif (mode === \"json\") {\n\t\t\tconst header = session.sessionManager.getHeader();\n\t\t\tif (header) {\n\t\t\t\twriteRawStdout(`${JSON.stringify(header)}\\n`);\n\t\t\t}\n\t\t}\n\n\t\tawait rebindSession();\n\n\t\tif (initialMessage) {\n\t\t\tawait session.prompt(initialMessage, { images: initialImages });\n\t\t}\n\n\t\tfor (const message of messages) {\n\t\t\tawait session.prompt(message);\n\t\t}\n\n\t\tif (mode === \"text\") {\n\t\t\tconst state = session.state;\n\t\t\tconst lastMessage = state.messages[state.messages.length - 1];\n\n\t\t\tif (lastMessage?.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = lastMessage as AssistantMessage;\n\t\t\t\tif (assistantMsg.stopReason === \"error\" || assistantMsg.stopReason === \"aborted\") {\n\t\t\t\t\tconsole.error(assistantMsg.errorMessage || `Request ${assistantMsg.stopReason}`);\n\t\t\t\t\texitCode = 1;\n\t\t\t\t} else {\n\t\t\t\t\tfor (const content of assistantMsg.content) {\n\t\t\t\t\t\tif (content.type === \"text\") {\n\t\t\t\t\t\t\twriteRawStdout(`${content.text}\\n`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn exitCode;\n\t} catch (error: unknown) {\n\t\tconsole.error(error instanceof Error ? error.message : String(error));\n\t\treturn 1;\n\t} finally {\n\t\tfor (const cleanup of signalCleanupHandlers) {\n\t\t\tcleanup();\n\t\t}\n\t\tawait disposeRuntime();\n\t\tawait flushRawStdout();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/print-mode.js b/dist/modes/print-mode.js new file mode 100644 index 0000000..0497bd5 --- /dev/null +++ b/dist/modes/print-mode.js @@ -0,0 +1,132 @@ +/** + * Print mode (single-shot): Send prompts, output result, exit. + * + * Used for: + * - `pi -p "prompt"` - text output + * - `pi --mode json "prompt"` - JSON event stream + */ +import { flushRawStdout, writeRawStdout } from "../core/output-guard.js"; +import { killTrackedDetachedChildren } from "../utils/shell.js"; +/** + * Run in print (single-shot) mode. + * Sends prompts to the agent and outputs the result. + */ +export async function runPrintMode(runtimeHost, options) { + const { mode, messages = [], initialMessage, initialImages } = options; + let exitCode = 0; + let session = runtimeHost.session; + let unsubscribe; + let disposed = false; + const signalCleanupHandlers = []; + const disposeRuntime = async () => { + if (disposed) + return; + disposed = true; + unsubscribe?.(); + await runtimeHost.dispose(); + }; + const registerSignalHandlers = () => { + const signals = ["SIGTERM"]; + if (process.platform !== "win32") { + signals.push("SIGHUP"); + } + for (const signal of signals) { + const handler = () => { + killTrackedDetachedChildren(); + void disposeRuntime().finally(() => { + process.exit(signal === "SIGHUP" ? 129 : 143); + }); + }; + process.on(signal, handler); + signalCleanupHandlers.push(() => process.off(signal, handler)); + } + }; + registerSignalHandlers(); + runtimeHost.setRebindSession(async () => { + await rebindSession(); + }); + const rebindSession = async () => { + session = runtimeHost.session; + await session.bindExtensions({ + mode: mode === "json" ? "json" : "print", + commandContextActions: { + waitForIdle: () => session.waitForIdle(), + newSession: async (newSessionOptions) => runtimeHost.newSession(newSessionOptions), + fork: async (entryId, forkOptions) => { + const result = await runtimeHost.fork(entryId, forkOptions); + return { cancelled: result.cancelled }; + }, + navigateTree: async (targetId, navigateOptions) => { + const result = await session.navigateTree(targetId, { + summarize: navigateOptions?.summarize, + customInstructions: navigateOptions?.customInstructions, + replaceInstructions: navigateOptions?.replaceInstructions, + label: navigateOptions?.label, + }); + return { cancelled: result.cancelled }; + }, + switchSession: async (sessionPath, switchOptions) => { + return runtimeHost.switchSession(sessionPath, switchOptions); + }, + reload: async () => { + await session.reload(); + }, + }, + onError: (err) => { + console.error(`Extension error (${err.extensionPath}): ${err.error}`); + }, + }); + unsubscribe?.(); + unsubscribe = session.subscribe((event) => { + if (mode === "json") { + writeRawStdout(`${JSON.stringify(event)}\n`); + } + }); + }; + try { + if (mode === "json") { + const header = session.sessionManager.getHeader(); + if (header) { + writeRawStdout(`${JSON.stringify(header)}\n`); + } + } + await rebindSession(); + if (initialMessage) { + await session.prompt(initialMessage, { images: initialImages }); + } + for (const message of messages) { + await session.prompt(message); + } + if (mode === "text") { + const state = session.state; + const lastMessage = state.messages[state.messages.length - 1]; + if (lastMessage?.role === "assistant") { + const assistantMsg = lastMessage; + if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") { + console.error(assistantMsg.errorMessage || `Request ${assistantMsg.stopReason}`); + exitCode = 1; + } + else { + for (const content of assistantMsg.content) { + if (content.type === "text") { + writeRawStdout(`${content.text}\n`); + } + } + } + } + } + return exitCode; + } + catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + return 1; + } + finally { + for (const cleanup of signalCleanupHandlers) { + cleanup(); + } + await disposeRuntime(); + await flushRawStdout(); + } +} +//# sourceMappingURL=print-mode.js.map \ No newline at end of file diff --git a/dist/modes/print-mode.js.map b/dist/modes/print-mode.js.map new file mode 100644 index 0000000..ee8ef4f --- /dev/null +++ b/dist/modes/print-mode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"print-mode.js","sourceRoot":"","sources":["../../src/modes/print-mode.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACzE,OAAO,EAAE,2BAA2B,EAAE,MAAM,mBAAmB,CAAC;AAgBhE;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,WAAgC,EAAE,OAAyB,EAAmB;IAChH,MAAM,EAAE,IAAI,EAAE,QAAQ,GAAG,EAAE,EAAE,cAAc,EAAE,aAAa,EAAE,GAAG,OAAO,CAAC;IACvE,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,IAAI,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC;IAClC,IAAI,WAAqC,CAAC;IAC1C,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,MAAM,qBAAqB,GAAsB,EAAE,CAAC;IAEpD,MAAM,cAAc,GAAG,KAAK,IAAmB,EAAE,CAAC;QACjD,IAAI,QAAQ;YAAE,OAAO;QACrB,QAAQ,GAAG,IAAI,CAAC;QAChB,WAAW,EAAE,EAAE,CAAC;QAChB,MAAM,WAAW,CAAC,OAAO,EAAE,CAAC;IAAA,CAC5B,CAAC;IAEF,MAAM,sBAAsB,GAAG,GAAS,EAAE,CAAC;QAC1C,MAAM,OAAO,GAAqB,CAAC,SAAS,CAAC,CAAC;QAC9C,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;YAClC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACxB,CAAC;QAED,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC9B,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC;gBACrB,2BAA2B,EAAE,CAAC;gBAC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CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QACtE,OAAO,CAAC,CAAC;IACV,CAAC;YAAS,CAAC;QACV,KAAK,MAAM,OAAO,IAAI,qBAAqB,EAAE,CAAC;YAC7C,OAAO,EAAE,CAAC;QACX,CAAC;QACD,MAAM,cAAc,EAAE,CAAC;QACvB,MAAM,cAAc,EAAE,CAAC;IACxB,CAAC;AAAA,CACD","sourcesContent":["/**\n * Print mode (single-shot): Send prompts, output result, exit.\n *\n * Used for:\n * - `pi -p \"prompt\"` - text output\n * - `pi --mode json \"prompt\"` - JSON event stream\n */\n\nimport type { AssistantMessage, ImageContent } from \"@earendil-works/pi-ai\";\nimport type { AgentSessionRuntime } from \"../core/agent-session-runtime.ts\";\nimport { flushRawStdout, writeRawStdout } from \"../core/output-guard.ts\";\nimport { killTrackedDetachedChildren } from \"../utils/shell.ts\";\n\n/**\n * Options for print mode.\n */\nexport interface PrintModeOptions {\n\t/** Output mode: \"text\" for final response only, \"json\" for all events */\n\tmode: \"text\" | \"json\";\n\t/** Array of additional prompts to send after initialMessage */\n\tmessages?: string[];\n\t/** First message to send (may contain @file content) */\n\tinitialMessage?: string;\n\t/** Images to attach to the initial message */\n\tinitialImages?: ImageContent[];\n}\n\n/**\n * Run in print (single-shot) mode.\n * Sends prompts to the agent and outputs the result.\n */\nexport async function runPrintMode(runtimeHost: AgentSessionRuntime, options: PrintModeOptions): Promise {\n\tconst { mode, messages = [], initialMessage, initialImages } = options;\n\tlet exitCode = 0;\n\tlet session = runtimeHost.session;\n\tlet unsubscribe: (() => void) | undefined;\n\tlet disposed = false;\n\tconst signalCleanupHandlers: Array<() => void> = [];\n\n\tconst disposeRuntime = async (): Promise => {\n\t\tif (disposed) return;\n\t\tdisposed = true;\n\t\tunsubscribe?.();\n\t\tawait runtimeHost.dispose();\n\t};\n\n\tconst registerSignalHandlers = (): void => {\n\t\tconst signals: NodeJS.Signals[] = [\"SIGTERM\"];\n\t\tif (process.platform !== \"win32\") {\n\t\t\tsignals.push(\"SIGHUP\");\n\t\t}\n\n\t\tfor (const signal of signals) {\n\t\t\tconst handler = () => {\n\t\t\t\tkillTrackedDetachedChildren();\n\t\t\t\tvoid disposeRuntime().finally(() => {\n\t\t\t\t\tprocess.exit(signal === \"SIGHUP\" ? 129 : 143);\n\t\t\t\t});\n\t\t\t};\n\t\t\tprocess.on(signal, handler);\n\t\t\tsignalCleanupHandlers.push(() => process.off(signal, handler));\n\t\t}\n\t};\n\n\tregisterSignalHandlers();\n\n\truntimeHost.setRebindSession(async () => {\n\t\tawait rebindSession();\n\t});\n\n\tconst rebindSession = async (): Promise => {\n\t\tsession = runtimeHost.session;\n\t\tawait session.bindExtensions({\n\t\t\tmode: mode === \"json\" ? \"json\" : \"print\",\n\t\t\tcommandContextActions: {\n\t\t\t\twaitForIdle: () => session.waitForIdle(),\n\t\t\t\tnewSession: async (newSessionOptions) => runtimeHost.newSession(newSessionOptions),\n\t\t\t\tfork: async (entryId, forkOptions) => {\n\t\t\t\t\tconst result = await runtimeHost.fork(entryId, forkOptions);\n\t\t\t\t\treturn { cancelled: result.cancelled };\n\t\t\t\t},\n\t\t\t\tnavigateTree: async (targetId, navigateOptions) => {\n\t\t\t\t\tconst result = await session.navigateTree(targetId, {\n\t\t\t\t\t\tsummarize: navigateOptions?.summarize,\n\t\t\t\t\t\tcustomInstructions: navigateOptions?.customInstructions,\n\t\t\t\t\t\treplaceInstructions: navigateOptions?.replaceInstructions,\n\t\t\t\t\t\tlabel: navigateOptions?.label,\n\t\t\t\t\t});\n\t\t\t\t\treturn { cancelled: result.cancelled };\n\t\t\t\t},\n\t\t\t\tswitchSession: async (sessionPath, switchOptions) => {\n\t\t\t\t\treturn runtimeHost.switchSession(sessionPath, switchOptions);\n\t\t\t\t},\n\t\t\t\treload: async () => {\n\t\t\t\t\tawait session.reload();\n\t\t\t\t},\n\t\t\t},\n\t\t\tonError: (err) => {\n\t\t\t\tconsole.error(`Extension error (${err.extensionPath}): ${err.error}`);\n\t\t\t},\n\t\t});\n\n\t\tunsubscribe?.();\n\t\tunsubscribe = session.subscribe((event) => {\n\t\t\tif (mode === \"json\") {\n\t\t\t\twriteRawStdout(`${JSON.stringify(event)}\\n`);\n\t\t\t}\n\t\t});\n\t};\n\n\ttry {\n\t\tif (mode === \"json\") {\n\t\t\tconst header = session.sessionManager.getHeader();\n\t\t\tif (header) {\n\t\t\t\twriteRawStdout(`${JSON.stringify(header)}\\n`);\n\t\t\t}\n\t\t}\n\n\t\tawait rebindSession();\n\n\t\tif (initialMessage) {\n\t\t\tawait session.prompt(initialMessage, { images: initialImages });\n\t\t}\n\n\t\tfor (const message of messages) {\n\t\t\tawait session.prompt(message);\n\t\t}\n\n\t\tif (mode === \"text\") {\n\t\t\tconst state = session.state;\n\t\t\tconst lastMessage = state.messages[state.messages.length - 1];\n\n\t\t\tif (lastMessage?.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = lastMessage as AssistantMessage;\n\t\t\t\tif (assistantMsg.stopReason === \"error\" || assistantMsg.stopReason === \"aborted\") {\n\t\t\t\t\tconsole.error(assistantMsg.errorMessage || `Request ${assistantMsg.stopReason}`);\n\t\t\t\t\texitCode = 1;\n\t\t\t\t} else {\n\t\t\t\t\tfor (const content of assistantMsg.content) {\n\t\t\t\t\t\tif (content.type === \"text\") {\n\t\t\t\t\t\t\twriteRawStdout(`${content.text}\\n`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn exitCode;\n\t} catch (error: unknown) {\n\t\tconsole.error(error instanceof Error ? error.message : String(error));\n\t\treturn 1;\n\t} finally {\n\t\tfor (const cleanup of signalCleanupHandlers) {\n\t\t\tcleanup();\n\t\t}\n\t\tawait disposeRuntime();\n\t\tawait flushRawStdout();\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/rpc/jsonl.d.ts b/dist/modes/rpc/jsonl.d.ts new file mode 100644 index 0000000..43d33b1 --- /dev/null +++ b/dist/modes/rpc/jsonl.d.ts @@ -0,0 +1,17 @@ +import type { Readable } from "node:stream"; +/** + * Serialize a single strict JSONL record. + * + * Framing is LF-only. Payload strings may contain other Unicode separators such as + * U+2028 and U+2029. Clients must split records on `\n` only. + */ +export declare function serializeJsonLine(value: unknown): string; +/** + * Attach an LF-only JSONL reader to a stream. + * + * This intentionally does not use Node readline. Readline splits on additional + * Unicode separators that are valid inside JSON strings and therefore does not + * implement strict JSONL framing. + */ +export declare function attachJsonlLineReader(stream: Readable, onLine: (line: string) => void): () => void; +//# sourceMappingURL=jsonl.d.ts.map \ No newline at end of file diff --git a/dist/modes/rpc/jsonl.d.ts.map b/dist/modes/rpc/jsonl.d.ts.map new file mode 100644 index 0000000..197de27 --- /dev/null +++ b/dist/modes/rpc/jsonl.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonl.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/jsonl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAG5C;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAExD;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,GAAG,MAAM,IAAI,CAqClG","sourcesContent":["import type { Readable } from \"node:stream\";\nimport { StringDecoder } from \"node:string_decoder\";\n\n/**\n * Serialize a single strict JSONL record.\n *\n * Framing is LF-only. Payload strings may contain other Unicode separators such as\n * U+2028 and U+2029. Clients must split records on `\\n` only.\n */\nexport function serializeJsonLine(value: unknown): string {\n\treturn `${JSON.stringify(value)}\\n`;\n}\n\n/**\n * Attach an LF-only JSONL reader to a stream.\n *\n * This intentionally does not use Node readline. Readline splits on additional\n * Unicode separators that are valid inside JSON strings and therefore does not\n * implement strict JSONL framing.\n */\nexport function attachJsonlLineReader(stream: Readable, onLine: (line: string) => void): () => void {\n\tconst decoder = new StringDecoder(\"utf8\");\n\tlet buffer = \"\";\n\n\tconst emitLine = (line: string) => {\n\t\tonLine(line.endsWith(\"\\r\") ? line.slice(0, -1) : line);\n\t};\n\n\tconst onData = (chunk: string | Buffer) => {\n\t\tbuffer += typeof chunk === \"string\" ? chunk : decoder.write(chunk);\n\n\t\twhile (true) {\n\t\t\tconst newlineIndex = buffer.indexOf(\"\\n\");\n\t\t\tif (newlineIndex === -1) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\temitLine(buffer.slice(0, newlineIndex));\n\t\t\tbuffer = buffer.slice(newlineIndex + 1);\n\t\t}\n\t};\n\n\tconst onEnd = () => {\n\t\tbuffer += decoder.end();\n\t\tif (buffer.length > 0) {\n\t\t\temitLine(buffer);\n\t\t\tbuffer = \"\";\n\t\t}\n\t};\n\n\tstream.on(\"data\", onData);\n\tstream.on(\"end\", onEnd);\n\n\treturn () => {\n\t\tstream.off(\"data\", onData);\n\t\tstream.off(\"end\", onEnd);\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/modes/rpc/jsonl.js b/dist/modes/rpc/jsonl.js new file mode 100644 index 0000000..a8d1d80 --- /dev/null +++ b/dist/modes/rpc/jsonl.js @@ -0,0 +1,49 @@ +import { StringDecoder } from "node:string_decoder"; +/** + * Serialize a single strict JSONL record. + * + * Framing is LF-only. Payload strings may contain other Unicode separators such as + * U+2028 and U+2029. Clients must split records on `\n` only. + */ +export function serializeJsonLine(value) { + return `${JSON.stringify(value)}\n`; +} +/** + * Attach an LF-only JSONL reader to a stream. + * + * This intentionally does not use Node readline. Readline splits on additional + * Unicode separators that are valid inside JSON strings and therefore does not + * implement strict JSONL framing. + */ +export function attachJsonlLineReader(stream, onLine) { + const decoder = new StringDecoder("utf8"); + let buffer = ""; + const emitLine = (line) => { + onLine(line.endsWith("\r") ? line.slice(0, -1) : line); + }; + const onData = (chunk) => { + buffer += typeof chunk === "string" ? chunk : decoder.write(chunk); + while (true) { + const newlineIndex = buffer.indexOf("\n"); + if (newlineIndex === -1) { + return; + } + emitLine(buffer.slice(0, newlineIndex)); + buffer = buffer.slice(newlineIndex + 1); + } + }; + const onEnd = () => { + buffer += decoder.end(); + if (buffer.length > 0) { + emitLine(buffer); + buffer = ""; + } + }; + stream.on("data", onData); + stream.on("end", onEnd); + return () => { + stream.off("data", onData); + stream.off("end", onEnd); + }; +} +//# sourceMappingURL=jsonl.js.map \ No newline at end of file diff --git a/dist/modes/rpc/jsonl.js.map b/dist/modes/rpc/jsonl.js.map new file mode 100644 index 0000000..c16d725 --- /dev/null +++ b/dist/modes/rpc/jsonl.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonl.js","sourceRoot":"","sources":["../../../src/modes/rpc/jsonl.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAc,EAAU;IACzD,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC;AAAA,CACpC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,qBAAqB,CAAC,MAAgB,EAAE,MAA8B,EAAc;IACnG,MAAM,OAAO,GAAG,IAAI,aAAa,CAAC,MAAM,CAAC,CAAC;IAC1C,IAAI,MAAM,GAAG,EAAE,CAAC;IAEhB,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC;QAClC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAAA,CACvD,CAAC;IAEF,MAAM,MAAM,GAAG,CAAC,KAAsB,EAAE,EAAE,CAAC;QAC1C,MAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAEnE,OAAO,IAAI,EAAE,CAAC;YACb,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;YAC1C,IAAI,YAAY,KAAK,CAAC,CAAC,EAAE,CAAC;gBACzB,OAAO;YACR,CAAC;YAED,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC;YACxC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,YAAY,GAAG,CAAC,CAAC,CAAC;QACzC,CAAC;IAAA,CACD,CAAC;IAEF,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC;QACnB,MAAM,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;QACxB,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACvB,QAAQ,CAAC,MAAM,CAAC,CAAC;YACjB,MAAM,GAAG,EAAE,CAAC;QACb,CAAC;IAAA,CACD,CAAC;IAEF,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC1B,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAExB,OAAO,GAAG,EAAE,CAAC;QACZ,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC3B,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAAA,CACzB,CAAC;AAAA,CACF","sourcesContent":["import type { Readable } from \"node:stream\";\nimport { StringDecoder } from \"node:string_decoder\";\n\n/**\n * Serialize a single strict JSONL record.\n *\n * Framing is LF-only. Payload strings may contain other Unicode separators such as\n * U+2028 and U+2029. Clients must split records on `\\n` only.\n */\nexport function serializeJsonLine(value: unknown): string {\n\treturn `${JSON.stringify(value)}\\n`;\n}\n\n/**\n * Attach an LF-only JSONL reader to a stream.\n *\n * This intentionally does not use Node readline. Readline splits on additional\n * Unicode separators that are valid inside JSON strings and therefore does not\n * implement strict JSONL framing.\n */\nexport function attachJsonlLineReader(stream: Readable, onLine: (line: string) => void): () => void {\n\tconst decoder = new StringDecoder(\"utf8\");\n\tlet buffer = \"\";\n\n\tconst emitLine = (line: string) => {\n\t\tonLine(line.endsWith(\"\\r\") ? line.slice(0, -1) : line);\n\t};\n\n\tconst onData = (chunk: string | Buffer) => {\n\t\tbuffer += typeof chunk === \"string\" ? chunk : decoder.write(chunk);\n\n\t\twhile (true) {\n\t\t\tconst newlineIndex = buffer.indexOf(\"\\n\");\n\t\t\tif (newlineIndex === -1) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\temitLine(buffer.slice(0, newlineIndex));\n\t\t\tbuffer = buffer.slice(newlineIndex + 1);\n\t\t}\n\t};\n\n\tconst onEnd = () => {\n\t\tbuffer += decoder.end();\n\t\tif (buffer.length > 0) {\n\t\t\temitLine(buffer);\n\t\t\tbuffer = \"\";\n\t\t}\n\t};\n\n\tstream.on(\"data\", onData);\n\tstream.on(\"end\", onEnd);\n\n\treturn () => {\n\t\tstream.off(\"data\", onData);\n\t\tstream.off(\"end\", onEnd);\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/modes/rpc/rpc-client.d.ts b/dist/modes/rpc/rpc-client.d.ts new file mode 100644 index 0000000..9263bde --- /dev/null +++ b/dist/modes/rpc/rpc-client.d.ts @@ -0,0 +1,246 @@ +/** + * RPC Client for programmatic access to the coding agent. + * + * Spawns the agent in RPC mode and provides a typed API for all operations. + */ +import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core"; +import type { ImageContent } from "@earendil-works/pi-ai"; +import type { AgentSessionEvent, SessionStats } from "../../core/agent-session.ts"; +import type { BashResult } from "../../core/bash-executor.ts"; +import type { CompactionResult } from "../../core/compaction/index.ts"; +import type { SessionEntry, SessionTreeNode } from "../../core/session-manager.ts"; +import type { RpcSessionState, RpcSlashCommand } from "./rpc-types.ts"; +export interface RpcClientOptions { + /** Path to the CLI entry point (default: searches for dist/cli.js) */ + cliPath?: string; + /** Working directory for the agent */ + cwd?: string; + /** Environment variables */ + env?: Record; + /** Provider to use */ + provider?: string; + /** Model ID to use */ + model?: string; + /** Additional CLI arguments */ + args?: string[]; +} +export interface ModelInfo { + provider: string; + id: string; + contextWindow: number; + reasoning: boolean; +} +export type RpcEventListener = (event: AgentSessionEvent) => void; +export declare class RpcClient { + private process; + private stopReadingStdout; + private eventListeners; + private pendingRequests; + private requestId; + private stderr; + private exitError; + private options; + constructor(options?: RpcClientOptions); + /** + * Start the RPC agent process. + */ + start(): Promise; + /** + * Stop the RPC agent process. + */ + stop(): Promise; + /** + * Subscribe to agent events. + */ + onEvent(listener: RpcEventListener): () => void; + /** + * Get collected stderr output (useful for debugging). + */ + getStderr(): string; + /** + * Send a prompt to the agent. + * Returns immediately after sending; use onEvent() to receive streaming events. + * Use waitForIdle() to wait for completion. + */ + prompt(message: string, images?: ImageContent[]): Promise; + /** + * Queue a steering message to interrupt the agent mid-run. + */ + steer(message: string, images?: ImageContent[]): Promise; + /** + * Queue a follow-up message to be processed after the agent finishes. + */ + followUp(message: string, images?: ImageContent[]): Promise; + /** + * Abort current operation. + */ + abort(): Promise; + /** + * Start a new session, optionally with parent tracking. + * @param parentSession - Optional parent session path for lineage tracking + * @returns Object with `cancelled: true` if an extension cancelled the new session + */ + newSession(parentSession?: string): Promise<{ + cancelled: boolean; + }>; + /** + * Get current session state. + */ + getState(): Promise; + /** + * Set model by provider and ID. + */ + setModel(provider: string, modelId: string): Promise<{ + provider: string; + id: string; + }>; + /** + * Cycle to next model. + */ + cycleModel(): Promise<{ + model: { + provider: string; + id: string; + }; + thinkingLevel: ThinkingLevel; + isScoped: boolean; + } | null>; + /** + * Get list of available models. + */ + getAvailableModels(): Promise; + /** + * Set thinking level. + */ + setThinkingLevel(level: ThinkingLevel): Promise; + /** + * Cycle thinking level. + */ + cycleThinkingLevel(): Promise<{ + level: ThinkingLevel; + } | null>; + /** + * Get list of available thinking levels for the current model. + */ + getAvailableThinkingLevels(): Promise; + /** + * Set steering mode. + */ + setSteeringMode(mode: "all" | "one-at-a-time"): Promise; + /** + * Set follow-up mode. + */ + setFollowUpMode(mode: "all" | "one-at-a-time"): Promise; + /** + * Compact session context. + */ + compact(customInstructions?: string): Promise; + /** + * Set auto-compaction enabled/disabled. + */ + setAutoCompaction(enabled: boolean): Promise; + /** + * Set auto-retry enabled/disabled. + */ + setAutoRetry(enabled: boolean): Promise; + /** + * Abort in-progress retry. + */ + abortRetry(): Promise; + /** + * Execute a bash command. + */ + bash(command: string): Promise; + /** + * Abort running bash command. + */ + abortBash(): Promise; + /** + * Get session statistics. + */ + getSessionStats(): Promise; + /** + * Export session to HTML. + */ + exportHtml(outputPath?: string): Promise<{ + path: string; + }>; + /** + * Switch to a different session file. + * @returns Object with `cancelled: true` if an extension cancelled the switch + */ + switchSession(sessionPath: string): Promise<{ + cancelled: boolean; + }>; + /** + * Fork from a specific message. + * @returns Object with `text` (the message text) and `cancelled` (if extension cancelled) + */ + fork(entryId: string): Promise<{ + text: string; + cancelled: boolean; + }>; + /** + * Clone the current active branch into a new session. + * @returns Object with `cancelled: true` if an extension cancelled the clone + */ + clone(): Promise<{ + cancelled: boolean; + }>; + /** + * Get messages available for forking. + */ + getForkMessages(): Promise>; + /** + * Get session entries in append order, optionally only those after the `since` entry id. + */ + getEntries(since?: string): Promise<{ + entries: SessionEntry[]; + leafId: string | null; + }>; + /** + * Get the session entry tree. + */ + getTree(): Promise<{ + tree: SessionTreeNode[]; + leafId: string | null; + }>; + /** + * Get text of last assistant message. + */ + getLastAssistantText(): Promise; + /** + * Set the session display name. + */ + setSessionName(name: string): Promise; + /** + * Get all messages in the session. + */ + getMessages(): Promise; + /** + * Get available commands (extension commands, prompt templates, skills). + */ + getCommands(): Promise; + /** + * Wait for agent to become idle (no streaming). + * Resolves when agent_settled event is received. + */ + waitForIdle(timeout?: number): Promise; + /** + * Collect events until agent becomes idle. + */ + collectEvents(timeout?: number): Promise; + /** + * Send prompt and wait for completion, returning all events. + */ + promptAndWait(message: string, images?: ImageContent[], timeout?: number): Promise; + private handleLine; + private createProcessExitError; + private rejectPendingRequests; + private send; + private getData; +} +//# sourceMappingURL=rpc-client.d.ts.map \ No newline at end of file diff --git a/dist/modes/rpc/rpc-client.d.ts.map b/dist/modes/rpc/rpc-client.d.ts.map new file mode 100644 index 0000000..b8b7c1f --- /dev/null +++ b/dist/modes/rpc/rpc-client.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc-client.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AACnF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAEnF,OAAO,KAAK,EAA2B,eAAe,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAYhG,MAAM,WAAW,gBAAgB;IAChC,sEAAsE;IACtE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,sCAAsC;IACtC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,4BAA4B;IAC5B,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,sBAAsB;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sBAAsB;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+BAA+B;IAC/B,IAAI,CA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,EAAE,eAAe,EAAE,CAAC;QAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC,CAG3E;IAED;;OAEG;IACG,oBAAoB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAGnD;IAED;;OAEG;IACG,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhD;IAED;;OAEG;IACG,WAAW,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC,CAG3C;IAED;;OAEG;IACG,WAAW,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC,CAG9C;IAMD;;;OAGG;IACH,WAAW,CAAC,OAAO,SAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAe1C;IAED;;OAEG;IACH,aAAa,CAAC,OAAO,SAAQ,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAiB3D;IAED;;OAEG;IACG,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,EAAE,OAAO,SAAQ,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAI3G;IAMD,OAAO,CAAC,UAAU;IAqBlB,OAAO,CAAC,sBAAsB;IAI9B,OAAO,CAAC,qBAAqB;YAOf,IAAI;IAmDlB,OAAO,CAAC,OAAO;CAUf","sourcesContent":["/**\n * RPC Client for programmatic access to the coding agent.\n *\n * Spawns the agent in RPC mode and provides a typed API for all operations.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent } from \"@earendil-works/pi-ai\";\nimport type { AgentSessionEvent, SessionStats } from \"../../core/agent-session.ts\";\nimport type { BashResult } from \"../../core/bash-executor.ts\";\nimport type { CompactionResult } from \"../../core/compaction/index.ts\";\nimport type { SessionEntry, SessionTreeNode } from \"../../core/session-manager.ts\";\nimport { attachJsonlLineReader, serializeJsonLine } from \"./jsonl.ts\";\nimport type { RpcCommand, RpcResponse, RpcSessionState, RpcSlashCommand } from \"./rpc-types.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Distributive Omit that works with union types */\ntype DistributiveOmit = T extends unknown ? Omit : never;\n\n/** RpcCommand without the id field (for internal send) */\ntype RpcCommandBody = DistributiveOmit;\n\nexport interface RpcClientOptions {\n\t/** Path to the CLI entry point (default: searches for dist/cli.js) */\n\tcliPath?: string;\n\t/** Working directory for the agent */\n\tcwd?: string;\n\t/** Environment variables */\n\tenv?: Record;\n\t/** Provider to use */\n\tprovider?: string;\n\t/** Model ID to use */\n\tmodel?: string;\n\t/** Additional CLI arguments */\n\targs?: string[];\n}\n\nexport interface ModelInfo {\n\tprovider: string;\n\tid: string;\n\tcontextWindow: number;\n\treasoning: boolean;\n}\n\nexport type RpcEventListener = (event: AgentSessionEvent) => void;\n\n// ============================================================================\n// RPC Client\n// ============================================================================\n\nexport class RpcClient {\n\tprivate process: ChildProcess | null = null;\n\tprivate stopReadingStdout: (() => void) | null = null;\n\tprivate eventListeners: RpcEventListener[] = [];\n\tprivate pendingRequests: Map void; reject: (error: Error) => void }> =\n\t\tnew Map();\n\tprivate requestId = 0;\n\tprivate stderr = \"\";\n\tprivate exitError: Error | null = null;\n\tprivate options: RpcClientOptions;\n\n\tconstructor(options: RpcClientOptions = {}) {\n\t\tthis.options = options;\n\t}\n\n\t/**\n\t * Start the RPC agent process.\n\t */\n\tasync start(): Promise {\n\t\tif (this.process) {\n\t\t\tthrow new Error(\"Client already started\");\n\t\t}\n\n\t\tthis.exitError = null;\n\n\t\tconst cliPath = this.options.cliPath ?? \"dist/cli.js\";\n\t\tconst args = [\"--mode\", \"rpc\"];\n\n\t\tif (this.options.provider) {\n\t\t\targs.push(\"--provider\", this.options.provider);\n\t\t}\n\t\tif (this.options.model) {\n\t\t\targs.push(\"--model\", this.options.model);\n\t\t}\n\t\tif (this.options.args) {\n\t\t\targs.push(...this.options.args);\n\t\t}\n\n\t\tconst childProcess = spawn(\"node\", [cliPath, ...args], {\n\t\t\tcwd: this.options.cwd,\n\t\t\tenv: { ...process.env, ...this.options.env },\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tthis.process = childProcess;\n\n\t\t// Collect stderr for debugging\n\t\tchildProcess.stderr?.on(\"data\", (data) => {\n\t\t\tthis.stderr += data.toString();\n\t\t\tprocess.stderr.write(data);\n\t\t});\n\n\t\tchildProcess.once(\"exit\", (code, signal) => {\n\t\t\tif (this.process !== childProcess) return;\n\t\t\tconst error = this.createProcessExitError(code, signal);\n\t\t\tthis.exitError = error;\n\t\t\tthis.rejectPendingRequests(error);\n\t\t});\n\t\tchildProcess.once(\"error\", (error) => {\n\t\t\tif (this.process !== childProcess) return;\n\t\t\tconst processError = new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`);\n\t\t\tthis.exitError = processError;\n\t\t\tthis.rejectPendingRequests(processError);\n\t\t});\n\t\tchildProcess.stdin?.on(\"error\", (error) => {\n\t\t\tif (this.process !== childProcess) return;\n\t\t\tconst stdinError =\n\t\t\t\tthis.exitError ?? new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`);\n\t\t\tthis.exitError = stdinError;\n\t\t\tthis.rejectPendingRequests(stdinError);\n\t\t});\n\n\t\t// Set up strict JSONL reader for stdout.\n\t\tthis.stopReadingStdout = attachJsonlLineReader(childProcess.stdout!, (line) => {\n\t\t\tthis.handleLine(line);\n\t\t});\n\n\t\t// Wait a moment for process to initialize\n\t\tawait new Promise((resolve) => setTimeout(resolve, 100));\n\n\t\tif (this.process.exitCode !== null) {\n\t\t\tconst error = this.exitError ?? this.createProcessExitError(this.process.exitCode, this.process.signalCode);\n\t\t\tthis.exitError = error;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Stop the RPC agent process.\n\t */\n\tasync stop(): Promise {\n\t\tif (!this.process) return;\n\n\t\tthis.stopReadingStdout?.();\n\t\tthis.stopReadingStdout = null;\n\t\tthis.process.kill(\"SIGTERM\");\n\n\t\t// Wait for process to exit\n\t\tawait new Promise((resolve) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tthis.process?.kill(\"SIGKILL\");\n\t\t\t\tresolve();\n\t\t\t}, 1000);\n\n\t\t\tthis.process?.on(\"exit\", () => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\n\t\tthis.process = null;\n\t\tthis.pendingRequests.clear();\n\t}\n\n\t/**\n\t * Subscribe to agent events.\n\t */\n\tonEvent(listener: RpcEventListener): () => void {\n\t\tthis.eventListeners.push(listener);\n\t\treturn () => {\n\t\t\tconst index = this.eventListeners.indexOf(listener);\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.eventListeners.splice(index, 1);\n\t\t\t}\n\t\t};\n\t}\n\n\t/**\n\t * Get collected stderr output (useful for debugging).\n\t */\n\tgetStderr(): string {\n\t\treturn this.stderr;\n\t}\n\n\t// =========================================================================\n\t// Command Methods\n\t// =========================================================================\n\n\t/**\n\t * Send a prompt to the agent.\n\t * Returns immediately after sending; use onEvent() to receive streaming events.\n\t * Use waitForIdle() to wait for completion.\n\t */\n\tasync prompt(message: string, images?: ImageContent[]): Promise {\n\t\tawait this.send({ type: \"prompt\", message, images });\n\t}\n\n\t/**\n\t * Queue a steering message to interrupt the agent mid-run.\n\t */\n\tasync steer(message: string, images?: ImageContent[]): Promise {\n\t\tawait this.send({ type: \"steer\", message, images });\n\t}\n\n\t/**\n\t * Queue a follow-up message to be processed after the agent finishes.\n\t */\n\tasync followUp(message: string, images?: ImageContent[]): Promise {\n\t\tawait this.send({ type: \"follow_up\", message, images });\n\t}\n\n\t/**\n\t * Abort current operation.\n\t */\n\tasync abort(): Promise {\n\t\tawait this.send({ type: \"abort\" });\n\t}\n\n\t/**\n\t * Start a new session, optionally with parent tracking.\n\t * @param parentSession - Optional parent session path for lineage tracking\n\t * @returns Object with `cancelled: true` if an extension cancelled the new session\n\t */\n\tasync newSession(parentSession?: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"new_session\", parentSession });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get current session state.\n\t */\n\tasync getState(): Promise {\n\t\tconst response = await this.send({ type: \"get_state\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Set model by provider and ID.\n\t */\n\tasync setModel(provider: string, modelId: string): Promise<{ provider: string; id: string }> {\n\t\tconst response = await this.send({ type: \"set_model\", provider, modelId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Cycle to next model.\n\t */\n\tasync cycleModel(): Promise<{\n\t\tmodel: { provider: string; id: string };\n\t\tthinkingLevel: ThinkingLevel;\n\t\tisScoped: boolean;\n\t} | null> {\n\t\tconst response = await this.send({ type: \"cycle_model\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get list of available models.\n\t */\n\tasync getAvailableModels(): Promise {\n\t\tconst response = await this.send({ type: \"get_available_models\" });\n\t\treturn this.getData<{ models: ModelInfo[] }>(response).models;\n\t}\n\n\t/**\n\t * Set thinking level.\n\t */\n\tasync setThinkingLevel(level: ThinkingLevel): Promise {\n\t\tawait this.send({ type: \"set_thinking_level\", level });\n\t}\n\n\t/**\n\t * Cycle thinking level.\n\t */\n\tasync cycleThinkingLevel(): Promise<{ level: ThinkingLevel } | null> {\n\t\tconst response = await this.send({ type: \"cycle_thinking_level\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get list of available thinking levels for the current model.\n\t */\n\tasync getAvailableThinkingLevels(): Promise {\n\t\tconst response = await this.send({ type: \"get_available_thinking_levels\" });\n\t\treturn this.getData<{ levels: ThinkingLevel[] }>(response).levels;\n\t}\n\n\t/**\n\t * Set steering mode.\n\t */\n\tasync setSteeringMode(mode: \"all\" | \"one-at-a-time\"): Promise {\n\t\tawait this.send({ type: \"set_steering_mode\", mode });\n\t}\n\n\t/**\n\t * Set follow-up mode.\n\t */\n\tasync setFollowUpMode(mode: \"all\" | \"one-at-a-time\"): Promise {\n\t\tawait this.send({ type: \"set_follow_up_mode\", mode });\n\t}\n\n\t/**\n\t * Compact session context.\n\t */\n\tasync compact(customInstructions?: string): Promise {\n\t\tconst response = await this.send({ type: \"compact\", customInstructions });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Set auto-compaction enabled/disabled.\n\t */\n\tasync setAutoCompaction(enabled: boolean): Promise {\n\t\tawait this.send({ type: \"set_auto_compaction\", enabled });\n\t}\n\n\t/**\n\t * Set auto-retry enabled/disabled.\n\t */\n\tasync setAutoRetry(enabled: boolean): Promise {\n\t\tawait this.send({ type: \"set_auto_retry\", enabled });\n\t}\n\n\t/**\n\t * Abort in-progress retry.\n\t */\n\tasync abortRetry(): Promise {\n\t\tawait this.send({ type: \"abort_retry\" });\n\t}\n\n\t/**\n\t * Execute a bash command.\n\t */\n\tasync bash(command: string): Promise {\n\t\tconst response = await this.send({ type: \"bash\", command });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Abort running bash command.\n\t */\n\tasync abortBash(): Promise {\n\t\tawait this.send({ type: \"abort_bash\" });\n\t}\n\n\t/**\n\t * Get session statistics.\n\t */\n\tasync getSessionStats(): Promise {\n\t\tconst response = await this.send({ type: \"get_session_stats\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Export session to HTML.\n\t */\n\tasync exportHtml(outputPath?: string): Promise<{ path: string }> {\n\t\tconst response = await this.send({ type: \"export_html\", outputPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Switch to a different session file.\n\t * @returns Object with `cancelled: true` if an extension cancelled the switch\n\t */\n\tasync switchSession(sessionPath: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"switch_session\", sessionPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Fork from a specific message.\n\t * @returns Object with `text` (the message text) and `cancelled` (if extension cancelled)\n\t */\n\tasync fork(entryId: string): Promise<{ text: string; cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"fork\", entryId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Clone the current active branch into a new session.\n\t * @returns Object with `cancelled: true` if an extension cancelled the clone\n\t */\n\tasync clone(): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"clone\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get messages available for forking.\n\t */\n\tasync getForkMessages(): Promise> {\n\t\tconst response = await this.send({ type: \"get_fork_messages\" });\n\t\treturn this.getData<{ messages: Array<{ entryId: string; text: string }> }>(response).messages;\n\t}\n\n\t/**\n\t * Get session entries in append order, optionally only those after the `since` entry id.\n\t */\n\tasync getEntries(since?: string): Promise<{ entries: SessionEntry[]; leafId: string | null }> {\n\t\tconst response = await this.send({ type: \"get_entries\", since });\n\t\treturn this.getData<{ entries: SessionEntry[]; leafId: string | null }>(response);\n\t}\n\n\t/**\n\t * Get the session entry tree.\n\t */\n\tasync getTree(): Promise<{ tree: SessionTreeNode[]; leafId: string | null }> {\n\t\tconst response = await this.send({ type: \"get_tree\" });\n\t\treturn this.getData<{ tree: SessionTreeNode[]; leafId: string | null }>(response);\n\t}\n\n\t/**\n\t * Get text of last assistant message.\n\t */\n\tasync getLastAssistantText(): Promise {\n\t\tconst response = await this.send({ type: \"get_last_assistant_text\" });\n\t\treturn this.getData<{ text: string | null }>(response).text;\n\t}\n\n\t/**\n\t * Set the session display name.\n\t */\n\tasync setSessionName(name: string): Promise {\n\t\tawait this.send({ type: \"set_session_name\", name });\n\t}\n\n\t/**\n\t * Get all messages in the session.\n\t */\n\tasync getMessages(): Promise {\n\t\tconst response = await this.send({ type: \"get_messages\" });\n\t\treturn this.getData<{ messages: AgentMessage[] }>(response).messages;\n\t}\n\n\t/**\n\t * Get available commands (extension commands, prompt templates, skills).\n\t */\n\tasync getCommands(): Promise {\n\t\tconst response = await this.send({ type: \"get_commands\" });\n\t\treturn this.getData<{ commands: RpcSlashCommand[] }>(response).commands;\n\t}\n\n\t// =========================================================================\n\t// Helpers\n\t// =========================================================================\n\n\t/**\n\t * Wait for agent to become idle (no streaming).\n\t * Resolves when agent_settled event is received.\n\t */\n\twaitForIdle(timeout = 60000): Promise {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tunsubscribe();\n\t\t\t\treject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`));\n\t\t\t}, timeout);\n\n\t\t\tconst unsubscribe = this.onEvent((event) => {\n\t\t\t\tif (event.type === \"agent_settled\") {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Collect events until agent becomes idle.\n\t */\n\tcollectEvents(timeout = 60000): Promise {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst events: AgentSessionEvent[] = [];\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tunsubscribe();\n\t\t\t\treject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`));\n\t\t\t}, timeout);\n\n\t\t\tconst unsubscribe = this.onEvent((event) => {\n\t\t\t\tevents.push(event);\n\t\t\t\tif (event.type === \"agent_settled\") {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tresolve(events);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Send prompt and wait for completion, returning all events.\n\t */\n\tasync promptAndWait(message: string, images?: ImageContent[], timeout = 60000): Promise {\n\t\tconst eventsPromise = this.collectEvents(timeout);\n\t\tawait this.prompt(message, images);\n\t\treturn eventsPromise;\n\t}\n\n\t// =========================================================================\n\t// Internal\n\t// =========================================================================\n\n\tprivate handleLine(line: string): void {\n\t\ttry {\n\t\t\tconst data = JSON.parse(line);\n\n\t\t\t// Check if it's a response to a pending request\n\t\t\tif (data.type === \"response\" && data.id && this.pendingRequests.has(data.id)) {\n\t\t\t\tconst pending = this.pendingRequests.get(data.id)!;\n\t\t\t\tthis.pendingRequests.delete(data.id);\n\t\t\t\tpending.resolve(data as RpcResponse);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Otherwise it's an event\n\t\t\tfor (const listener of this.eventListeners) {\n\t\t\t\tlistener(data as AgentSessionEvent);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore non-JSON lines\n\t\t}\n\t}\n\n\tprivate createProcessExitError(code: number | null, signal: NodeJS.Signals | null): Error {\n\t\treturn new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`);\n\t}\n\n\tprivate rejectPendingRequests(error: Error): void {\n\t\tfor (const pending of this.pendingRequests.values()) {\n\t\t\tpending.reject(error);\n\t\t}\n\t\tthis.pendingRequests.clear();\n\t}\n\n\tprivate async send(command: RpcCommandBody): Promise {\n\t\tconst childProcess = this.process;\n\t\tconst stdin = childProcess?.stdin;\n\t\tif (!childProcess || !stdin) {\n\t\t\tthrow new Error(\"Client not started\");\n\t\t}\n\t\tif (this.exitError) {\n\t\t\tthrow this.exitError;\n\t\t}\n\t\tif (childProcess.exitCode !== null) {\n\t\t\tconst error = this.createProcessExitError(childProcess.exitCode, childProcess.signalCode);\n\t\t\tthis.exitError = error;\n\t\t\tthrow error;\n\t\t}\n\t\tif (stdin.destroyed || !stdin.writable) {\n\t\t\tconst error = new Error(`Agent process stdin is not writable. Stderr: ${this.stderr}`);\n\t\t\tthis.exitError = error;\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst id = `req_${++this.requestId}`;\n\t\tconst fullCommand = { ...command, id } as RpcCommand;\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tthis.pendingRequests.delete(id);\n\t\t\t\treject(new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`));\n\t\t\t}, 30000);\n\n\t\t\tthis.pendingRequests.set(id, {\n\t\t\t\tresolve: (response) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tresolve(response);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\tstdin.write(serializeJsonLine(fullCommand));\n\t\t\t} catch (error: unknown) {\n\t\t\t\tconst writeError = error instanceof Error ? error : new Error(String(error));\n\t\t\t\tconst pending = this.pendingRequests.get(id);\n\t\t\t\tthis.pendingRequests.delete(id);\n\t\t\t\tpending?.reject(writeError);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate getData(response: RpcResponse): T {\n\t\tif (!response.success) {\n\t\t\tconst errorResponse = response as Extract;\n\t\t\tthrow new Error(errorResponse.error);\n\t\t}\n\t\t// Type assertion: we trust response.data matches T based on the command sent.\n\t\t// This is safe because each public method specifies the correct T for its command.\n\t\tconst successResponse = response as Extract;\n\t\treturn successResponse.data as T;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/rpc/rpc-client.js b/dist/modes/rpc/rpc-client.js new file mode 100644 index 0000000..8683f01 --- /dev/null +++ b/dist/modes/rpc/rpc-client.js @@ -0,0 +1,488 @@ +/** + * RPC Client for programmatic access to the coding agent. + * + * Spawns the agent in RPC mode and provides a typed API for all operations. + */ +import { spawn } from "node:child_process"; +import { attachJsonlLineReader, serializeJsonLine } from "./jsonl.js"; +// ============================================================================ +// RPC Client +// ============================================================================ +export class RpcClient { + process = null; + stopReadingStdout = null; + eventListeners = []; + pendingRequests = new Map(); + requestId = 0; + stderr = ""; + exitError = null; + options; + constructor(options = {}) { + this.options = options; + } + /** + * Start the RPC agent process. + */ + async start() { + if (this.process) { + throw new Error("Client already started"); + } + this.exitError = null; + const cliPath = this.options.cliPath ?? "dist/cli.js"; + const args = ["--mode", "rpc"]; + if (this.options.provider) { + args.push("--provider", this.options.provider); + } + if (this.options.model) { + args.push("--model", this.options.model); + } + if (this.options.args) { + args.push(...this.options.args); + } + const childProcess = spawn("node", [cliPath, ...args], { + cwd: this.options.cwd, + env: { ...process.env, ...this.options.env }, + stdio: ["pipe", "pipe", "pipe"], + }); + this.process = childProcess; + // Collect stderr for debugging + childProcess.stderr?.on("data", (data) => { + this.stderr += data.toString(); + process.stderr.write(data); + }); + childProcess.once("exit", (code, signal) => { + if (this.process !== childProcess) + return; + const error = this.createProcessExitError(code, signal); + this.exitError = error; + this.rejectPendingRequests(error); + }); + childProcess.once("error", (error) => { + if (this.process !== childProcess) + return; + const processError = new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`); + this.exitError = processError; + this.rejectPendingRequests(processError); + }); + childProcess.stdin?.on("error", (error) => { + if (this.process !== childProcess) + return; + const stdinError = this.exitError ?? new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`); + this.exitError = stdinError; + this.rejectPendingRequests(stdinError); + }); + // Set up strict JSONL reader for stdout. + this.stopReadingStdout = attachJsonlLineReader(childProcess.stdout, (line) => { + this.handleLine(line); + }); + // Wait a moment for process to initialize + await new Promise((resolve) => setTimeout(resolve, 100)); + if (this.process.exitCode !== null) { + const error = this.exitError ?? this.createProcessExitError(this.process.exitCode, this.process.signalCode); + this.exitError = error; + throw error; + } + } + /** + * Stop the RPC agent process. + */ + async stop() { + if (!this.process) + return; + this.stopReadingStdout?.(); + this.stopReadingStdout = null; + this.process.kill("SIGTERM"); + // Wait for process to exit + await new Promise((resolve) => { + const timeout = setTimeout(() => { + this.process?.kill("SIGKILL"); + resolve(); + }, 1000); + this.process?.on("exit", () => { + clearTimeout(timeout); + resolve(); + }); + }); + this.process = null; + this.pendingRequests.clear(); + } + /** + * Subscribe to agent events. + */ + onEvent(listener) { + this.eventListeners.push(listener); + return () => { + const index = this.eventListeners.indexOf(listener); + if (index !== -1) { + this.eventListeners.splice(index, 1); + } + }; + } + /** + * Get collected stderr output (useful for debugging). + */ + getStderr() { + return this.stderr; + } + // ========================================================================= + // Command Methods + // ========================================================================= + /** + * Send a prompt to the agent. + * Returns immediately after sending; use onEvent() to receive streaming events. + * Use waitForIdle() to wait for completion. + */ + async prompt(message, images) { + await this.send({ type: "prompt", message, images }); + } + /** + * Queue a steering message to interrupt the agent mid-run. + */ + async steer(message, images) { + await this.send({ type: "steer", message, images }); + } + /** + * Queue a follow-up message to be processed after the agent finishes. + */ + async followUp(message, images) { + await this.send({ type: "follow_up", message, images }); + } + /** + * Abort current operation. + */ + async abort() { + await this.send({ type: "abort" }); + } + /** + * Start a new session, optionally with parent tracking. + * @param parentSession - Optional parent session path for lineage tracking + * @returns Object with `cancelled: true` if an extension cancelled the new session + */ + async newSession(parentSession) { + const response = await this.send({ type: "new_session", parentSession }); + return this.getData(response); + } + /** + * Get current session state. + */ + async getState() { + const response = await this.send({ type: "get_state" }); + return this.getData(response); + } + /** + * Set model by provider and ID. + */ + async setModel(provider, modelId) { + const response = await this.send({ type: "set_model", provider, modelId }); + return this.getData(response); + } + /** + * Cycle to next model. + */ + async cycleModel() { + const response = await this.send({ type: "cycle_model" }); + return this.getData(response); + } + /** + * Get list of available models. + */ + async getAvailableModels() { + const response = await this.send({ type: "get_available_models" }); + return this.getData(response).models; + } + /** + * Set thinking level. + */ + async setThinkingLevel(level) { + await this.send({ type: "set_thinking_level", level }); + } + /** + * Cycle thinking level. + */ + async cycleThinkingLevel() { + const response = await this.send({ type: "cycle_thinking_level" }); + return this.getData(response); + } + /** + * Get list of available thinking levels for the current model. + */ + async getAvailableThinkingLevels() { + const response = await this.send({ type: "get_available_thinking_levels" }); + return this.getData(response).levels; + } + /** + * Set steering mode. + */ + async setSteeringMode(mode) { + await this.send({ type: "set_steering_mode", mode }); + } + /** + * Set follow-up mode. + */ + async setFollowUpMode(mode) { + await this.send({ type: "set_follow_up_mode", mode }); + } + /** + * Compact session context. + */ + async compact(customInstructions) { + const response = await this.send({ type: "compact", customInstructions }); + return this.getData(response); + } + /** + * Set auto-compaction enabled/disabled. + */ + async setAutoCompaction(enabled) { + await this.send({ type: "set_auto_compaction", enabled }); + } + /** + * Set auto-retry enabled/disabled. + */ + async setAutoRetry(enabled) { + await this.send({ type: "set_auto_retry", enabled }); + } + /** + * Abort in-progress retry. + */ + async abortRetry() { + await this.send({ type: "abort_retry" }); + } + /** + * Execute a bash command. + */ + async bash(command) { + const response = await this.send({ type: "bash", command }); + return this.getData(response); + } + /** + * Abort running bash command. + */ + async abortBash() { + await this.send({ type: "abort_bash" }); + } + /** + * Get session statistics. + */ + async getSessionStats() { + const response = await this.send({ type: "get_session_stats" }); + return this.getData(response); + } + /** + * Export session to HTML. + */ + async exportHtml(outputPath) { + const response = await this.send({ type: "export_html", outputPath }); + return this.getData(response); + } + /** + * Switch to a different session file. + * @returns Object with `cancelled: true` if an extension cancelled the switch + */ + async switchSession(sessionPath) { + const response = await this.send({ type: "switch_session", sessionPath }); + return this.getData(response); + } + /** + * Fork from a specific message. + * @returns Object with `text` (the message text) and `cancelled` (if extension cancelled) + */ + async fork(entryId) { + const response = await this.send({ type: "fork", entryId }); + return this.getData(response); + } + /** + * Clone the current active branch into a new session. + * @returns Object with `cancelled: true` if an extension cancelled the clone + */ + async clone() { + const response = await this.send({ type: "clone" }); + return this.getData(response); + } + /** + * Get messages available for forking. + */ + async getForkMessages() { + const response = await this.send({ type: "get_fork_messages" }); + return this.getData(response).messages; + } + /** + * Get session entries in append order, optionally only those after the `since` entry id. + */ + async getEntries(since) { + const response = await this.send({ type: "get_entries", since }); + return this.getData(response); + } + /** + * Get the session entry tree. + */ + async getTree() { + const response = await this.send({ type: "get_tree" }); + return this.getData(response); + } + /** + * Get text of last assistant message. + */ + async getLastAssistantText() { + const response = await this.send({ type: "get_last_assistant_text" }); + return this.getData(response).text; + } + /** + * Set the session display name. + */ + async setSessionName(name) { + await this.send({ type: "set_session_name", name }); + } + /** + * Get all messages in the session. + */ + async getMessages() { + const response = await this.send({ type: "get_messages" }); + return this.getData(response).messages; + } + /** + * Get available commands (extension commands, prompt templates, skills). + */ + async getCommands() { + const response = await this.send({ type: "get_commands" }); + return this.getData(response).commands; + } + // ========================================================================= + // Helpers + // ========================================================================= + /** + * Wait for agent to become idle (no streaming). + * Resolves when agent_settled event is received. + */ + waitForIdle(timeout = 60000) { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + unsubscribe(); + reject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`)); + }, timeout); + const unsubscribe = this.onEvent((event) => { + if (event.type === "agent_settled") { + clearTimeout(timer); + unsubscribe(); + resolve(); + } + }); + }); + } + /** + * Collect events until agent becomes idle. + */ + collectEvents(timeout = 60000) { + return new Promise((resolve, reject) => { + const events = []; + const timer = setTimeout(() => { + unsubscribe(); + reject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`)); + }, timeout); + const unsubscribe = this.onEvent((event) => { + events.push(event); + if (event.type === "agent_settled") { + clearTimeout(timer); + unsubscribe(); + resolve(events); + } + }); + }); + } + /** + * Send prompt and wait for completion, returning all events. + */ + async promptAndWait(message, images, timeout = 60000) { + const eventsPromise = this.collectEvents(timeout); + await this.prompt(message, images); + return eventsPromise; + } + // ========================================================================= + // Internal + // ========================================================================= + handleLine(line) { + try { + const data = JSON.parse(line); + // Check if it's a response to a pending request + if (data.type === "response" && data.id && this.pendingRequests.has(data.id)) { + const pending = this.pendingRequests.get(data.id); + this.pendingRequests.delete(data.id); + pending.resolve(data); + return; + } + // Otherwise it's an event + for (const listener of this.eventListeners) { + listener(data); + } + } + catch { + // Ignore non-JSON lines + } + } + createProcessExitError(code, signal) { + return new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`); + } + rejectPendingRequests(error) { + for (const pending of this.pendingRequests.values()) { + pending.reject(error); + } + this.pendingRequests.clear(); + } + async send(command) { + const childProcess = this.process; + const stdin = childProcess?.stdin; + if (!childProcess || !stdin) { + throw new Error("Client not started"); + } + if (this.exitError) { + throw this.exitError; + } + if (childProcess.exitCode !== null) { + const error = this.createProcessExitError(childProcess.exitCode, childProcess.signalCode); + this.exitError = error; + throw error; + } + if (stdin.destroyed || !stdin.writable) { + const error = new Error(`Agent process stdin is not writable. Stderr: ${this.stderr}`); + this.exitError = error; + throw error; + } + const id = `req_${++this.requestId}`; + const fullCommand = { ...command, id }; + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + this.pendingRequests.delete(id); + reject(new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`)); + }, 30000); + this.pendingRequests.set(id, { + resolve: (response) => { + clearTimeout(timeout); + resolve(response); + }, + reject: (error) => { + clearTimeout(timeout); + reject(error); + }, + }); + try { + stdin.write(serializeJsonLine(fullCommand)); + } + catch (error) { + const writeError = error instanceof Error ? error : new Error(String(error)); + const pending = this.pendingRequests.get(id); + this.pendingRequests.delete(id); + pending?.reject(writeError); + } + }); + } + getData(response) { + if (!response.success) { + const errorResponse = response; + throw new Error(errorResponse.error); + } + // Type assertion: we trust response.data matches T based on the command sent. + // This is safe because each public method specifies the correct T for its command. + const successResponse = response; + return successResponse.data; + } +} +//# sourceMappingURL=rpc-client.js.map \ No newline at end of file diff --git a/dist/modes/rpc/rpc-client.js.map b/dist/modes/rpc/rpc-client.js.map new file mode 100644 index 0000000..a60ba27 --- /dev/null +++ b/dist/modes/rpc/rpc-client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc-client.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAO9D,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAqCtE,+EAA+E;AAC/E,aAAa;AACb,+EAA+E;AAE/E,MAAM,OAAO,SAAS;IACb,OAAO,GAAwB,IAAI,CAAC;IACpC,iBAAiB,GAAwB,IAAI,CAAC;IAC9C,cAAc,GAAuB,EAAE,CAAC;IACxC,eAAe,GACtB,IAAI,GAAG,EAAE,CAAC;IACH,SAAS,GAAG,CAAC,CAAC;IACd,MAAM,GAA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D,CAAC;YAC3E,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;QACtC,CAAC;QACD,8EAA8E;QAC9E,mFAAmF;QACnF,MAAM,eAAe,GAAG,QAAkE,CAAC;QAC3F,OAAO,eAAe,CAAC,IAAS,CAAC;IAAA,CACjC;CACD","sourcesContent":["/**\n * RPC Client for programmatic access to the coding agent.\n *\n * Spawns the agent in RPC mode and provides a typed API for all operations.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent } from \"@earendil-works/pi-ai\";\nimport type { AgentSessionEvent, SessionStats } from \"../../core/agent-session.ts\";\nimport type { BashResult } from \"../../core/bash-executor.ts\";\nimport type { CompactionResult } from \"../../core/compaction/index.ts\";\nimport type { SessionEntry, SessionTreeNode } from \"../../core/session-manager.ts\";\nimport { attachJsonlLineReader, serializeJsonLine } from \"./jsonl.ts\";\nimport type { RpcCommand, RpcResponse, RpcSessionState, RpcSlashCommand } from \"./rpc-types.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/** Distributive Omit that works with union types */\ntype DistributiveOmit = T extends unknown ? Omit : never;\n\n/** RpcCommand without the id field (for internal send) */\ntype RpcCommandBody = DistributiveOmit;\n\nexport interface RpcClientOptions {\n\t/** Path to the CLI entry point (default: searches for dist/cli.js) */\n\tcliPath?: string;\n\t/** Working directory for the agent */\n\tcwd?: string;\n\t/** Environment variables */\n\tenv?: Record;\n\t/** Provider to use */\n\tprovider?: string;\n\t/** Model ID to use */\n\tmodel?: string;\n\t/** Additional CLI arguments */\n\targs?: string[];\n}\n\nexport interface ModelInfo {\n\tprovider: string;\n\tid: string;\n\tcontextWindow: number;\n\treasoning: boolean;\n}\n\nexport type RpcEventListener = (event: AgentSessionEvent) => void;\n\n// ============================================================================\n// RPC Client\n// ============================================================================\n\nexport class RpcClient {\n\tprivate process: ChildProcess | null = null;\n\tprivate stopReadingStdout: (() => void) | null = null;\n\tprivate eventListeners: RpcEventListener[] = [];\n\tprivate pendingRequests: Map void; reject: (error: Error) => void }> =\n\t\tnew Map();\n\tprivate requestId = 0;\n\tprivate stderr = \"\";\n\tprivate exitError: Error | null = null;\n\tprivate options: RpcClientOptions;\n\n\tconstructor(options: RpcClientOptions = {}) {\n\t\tthis.options = options;\n\t}\n\n\t/**\n\t * Start the RPC agent process.\n\t */\n\tasync start(): Promise {\n\t\tif (this.process) {\n\t\t\tthrow new Error(\"Client already started\");\n\t\t}\n\n\t\tthis.exitError = null;\n\n\t\tconst cliPath = this.options.cliPath ?? \"dist/cli.js\";\n\t\tconst args = [\"--mode\", \"rpc\"];\n\n\t\tif (this.options.provider) {\n\t\t\targs.push(\"--provider\", this.options.provider);\n\t\t}\n\t\tif (this.options.model) {\n\t\t\targs.push(\"--model\", this.options.model);\n\t\t}\n\t\tif (this.options.args) {\n\t\t\targs.push(...this.options.args);\n\t\t}\n\n\t\tconst childProcess = spawn(\"node\", [cliPath, ...args], {\n\t\t\tcwd: this.options.cwd,\n\t\t\tenv: { ...process.env, ...this.options.env },\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tthis.process = childProcess;\n\n\t\t// Collect stderr for debugging\n\t\tchildProcess.stderr?.on(\"data\", (data) => {\n\t\t\tthis.stderr += data.toString();\n\t\t\tprocess.stderr.write(data);\n\t\t});\n\n\t\tchildProcess.once(\"exit\", (code, signal) => {\n\t\t\tif (this.process !== childProcess) return;\n\t\t\tconst error = this.createProcessExitError(code, signal);\n\t\t\tthis.exitError = error;\n\t\t\tthis.rejectPendingRequests(error);\n\t\t});\n\t\tchildProcess.once(\"error\", (error) => {\n\t\t\tif (this.process !== childProcess) return;\n\t\t\tconst processError = new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`);\n\t\t\tthis.exitError = processError;\n\t\t\tthis.rejectPendingRequests(processError);\n\t\t});\n\t\tchildProcess.stdin?.on(\"error\", (error) => {\n\t\t\tif (this.process !== childProcess) return;\n\t\t\tconst stdinError =\n\t\t\t\tthis.exitError ?? new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`);\n\t\t\tthis.exitError = stdinError;\n\t\t\tthis.rejectPendingRequests(stdinError);\n\t\t});\n\n\t\t// Set up strict JSONL reader for stdout.\n\t\tthis.stopReadingStdout = attachJsonlLineReader(childProcess.stdout!, (line) => {\n\t\t\tthis.handleLine(line);\n\t\t});\n\n\t\t// Wait a moment for process to initialize\n\t\tawait new Promise((resolve) => setTimeout(resolve, 100));\n\n\t\tif (this.process.exitCode !== null) {\n\t\t\tconst error = this.exitError ?? this.createProcessExitError(this.process.exitCode, this.process.signalCode);\n\t\t\tthis.exitError = error;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Stop the RPC agent process.\n\t */\n\tasync stop(): Promise {\n\t\tif (!this.process) return;\n\n\t\tthis.stopReadingStdout?.();\n\t\tthis.stopReadingStdout = null;\n\t\tthis.process.kill(\"SIGTERM\");\n\n\t\t// Wait for process to exit\n\t\tawait new Promise((resolve) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tthis.process?.kill(\"SIGKILL\");\n\t\t\t\tresolve();\n\t\t\t}, 1000);\n\n\t\t\tthis.process?.on(\"exit\", () => {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\n\t\tthis.process = null;\n\t\tthis.pendingRequests.clear();\n\t}\n\n\t/**\n\t * Subscribe to agent events.\n\t */\n\tonEvent(listener: RpcEventListener): () => void {\n\t\tthis.eventListeners.push(listener);\n\t\treturn () => {\n\t\t\tconst index = this.eventListeners.indexOf(listener);\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.eventListeners.splice(index, 1);\n\t\t\t}\n\t\t};\n\t}\n\n\t/**\n\t * Get collected stderr output (useful for debugging).\n\t */\n\tgetStderr(): string {\n\t\treturn this.stderr;\n\t}\n\n\t// =========================================================================\n\t// Command Methods\n\t// =========================================================================\n\n\t/**\n\t * Send a prompt to the agent.\n\t * Returns immediately after sending; use onEvent() to receive streaming events.\n\t * Use waitForIdle() to wait for completion.\n\t */\n\tasync prompt(message: string, images?: ImageContent[]): Promise {\n\t\tawait this.send({ type: \"prompt\", message, images });\n\t}\n\n\t/**\n\t * Queue a steering message to interrupt the agent mid-run.\n\t */\n\tasync steer(message: string, images?: ImageContent[]): Promise {\n\t\tawait this.send({ type: \"steer\", message, images });\n\t}\n\n\t/**\n\t * Queue a follow-up message to be processed after the agent finishes.\n\t */\n\tasync followUp(message: string, images?: ImageContent[]): Promise {\n\t\tawait this.send({ type: \"follow_up\", message, images });\n\t}\n\n\t/**\n\t * Abort current operation.\n\t */\n\tasync abort(): Promise {\n\t\tawait this.send({ type: \"abort\" });\n\t}\n\n\t/**\n\t * Start a new session, optionally with parent tracking.\n\t * @param parentSession - Optional parent session path for lineage tracking\n\t * @returns Object with `cancelled: true` if an extension cancelled the new session\n\t */\n\tasync newSession(parentSession?: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"new_session\", parentSession });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get current session state.\n\t */\n\tasync getState(): Promise {\n\t\tconst response = await this.send({ type: \"get_state\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Set model by provider and ID.\n\t */\n\tasync setModel(provider: string, modelId: string): Promise<{ provider: string; id: string }> {\n\t\tconst response = await this.send({ type: \"set_model\", provider, modelId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Cycle to next model.\n\t */\n\tasync cycleModel(): Promise<{\n\t\tmodel: { provider: string; id: string };\n\t\tthinkingLevel: ThinkingLevel;\n\t\tisScoped: boolean;\n\t} | null> {\n\t\tconst response = await this.send({ type: \"cycle_model\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get list of available models.\n\t */\n\tasync getAvailableModels(): Promise {\n\t\tconst response = await this.send({ type: \"get_available_models\" });\n\t\treturn this.getData<{ models: ModelInfo[] }>(response).models;\n\t}\n\n\t/**\n\t * Set thinking level.\n\t */\n\tasync setThinkingLevel(level: ThinkingLevel): Promise {\n\t\tawait this.send({ type: \"set_thinking_level\", level });\n\t}\n\n\t/**\n\t * Cycle thinking level.\n\t */\n\tasync cycleThinkingLevel(): Promise<{ level: ThinkingLevel } | null> {\n\t\tconst response = await this.send({ type: \"cycle_thinking_level\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get list of available thinking levels for the current model.\n\t */\n\tasync getAvailableThinkingLevels(): Promise {\n\t\tconst response = await this.send({ type: \"get_available_thinking_levels\" });\n\t\treturn this.getData<{ levels: ThinkingLevel[] }>(response).levels;\n\t}\n\n\t/**\n\t * Set steering mode.\n\t */\n\tasync setSteeringMode(mode: \"all\" | \"one-at-a-time\"): Promise {\n\t\tawait this.send({ type: \"set_steering_mode\", mode });\n\t}\n\n\t/**\n\t * Set follow-up mode.\n\t */\n\tasync setFollowUpMode(mode: \"all\" | \"one-at-a-time\"): Promise {\n\t\tawait this.send({ type: \"set_follow_up_mode\", mode });\n\t}\n\n\t/**\n\t * Compact session context.\n\t */\n\tasync compact(customInstructions?: string): Promise {\n\t\tconst response = await this.send({ type: \"compact\", customInstructions });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Set auto-compaction enabled/disabled.\n\t */\n\tasync setAutoCompaction(enabled: boolean): Promise {\n\t\tawait this.send({ type: \"set_auto_compaction\", enabled });\n\t}\n\n\t/**\n\t * Set auto-retry enabled/disabled.\n\t */\n\tasync setAutoRetry(enabled: boolean): Promise {\n\t\tawait this.send({ type: \"set_auto_retry\", enabled });\n\t}\n\n\t/**\n\t * Abort in-progress retry.\n\t */\n\tasync abortRetry(): Promise {\n\t\tawait this.send({ type: \"abort_retry\" });\n\t}\n\n\t/**\n\t * Execute a bash command.\n\t */\n\tasync bash(command: string): Promise {\n\t\tconst response = await this.send({ type: \"bash\", command });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Abort running bash command.\n\t */\n\tasync abortBash(): Promise {\n\t\tawait this.send({ type: \"abort_bash\" });\n\t}\n\n\t/**\n\t * Get session statistics.\n\t */\n\tasync getSessionStats(): Promise {\n\t\tconst response = await this.send({ type: \"get_session_stats\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Export session to HTML.\n\t */\n\tasync exportHtml(outputPath?: string): Promise<{ path: string }> {\n\t\tconst response = await this.send({ type: \"export_html\", outputPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Switch to a different session file.\n\t * @returns Object with `cancelled: true` if an extension cancelled the switch\n\t */\n\tasync switchSession(sessionPath: string): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"switch_session\", sessionPath });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Fork from a specific message.\n\t * @returns Object with `text` (the message text) and `cancelled` (if extension cancelled)\n\t */\n\tasync fork(entryId: string): Promise<{ text: string; cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"fork\", entryId });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Clone the current active branch into a new session.\n\t * @returns Object with `cancelled: true` if an extension cancelled the clone\n\t */\n\tasync clone(): Promise<{ cancelled: boolean }> {\n\t\tconst response = await this.send({ type: \"clone\" });\n\t\treturn this.getData(response);\n\t}\n\n\t/**\n\t * Get messages available for forking.\n\t */\n\tasync getForkMessages(): Promise> {\n\t\tconst response = await this.send({ type: \"get_fork_messages\" });\n\t\treturn this.getData<{ messages: Array<{ entryId: string; text: string }> }>(response).messages;\n\t}\n\n\t/**\n\t * Get session entries in append order, optionally only those after the `since` entry id.\n\t */\n\tasync getEntries(since?: string): Promise<{ entries: SessionEntry[]; leafId: string | null }> {\n\t\tconst response = await this.send({ type: \"get_entries\", since });\n\t\treturn this.getData<{ entries: SessionEntry[]; leafId: string | null }>(response);\n\t}\n\n\t/**\n\t * Get the session entry tree.\n\t */\n\tasync getTree(): Promise<{ tree: SessionTreeNode[]; leafId: string | null }> {\n\t\tconst response = await this.send({ type: \"get_tree\" });\n\t\treturn this.getData<{ tree: SessionTreeNode[]; leafId: string | null }>(response);\n\t}\n\n\t/**\n\t * Get text of last assistant message.\n\t */\n\tasync getLastAssistantText(): Promise {\n\t\tconst response = await this.send({ type: \"get_last_assistant_text\" });\n\t\treturn this.getData<{ text: string | null }>(response).text;\n\t}\n\n\t/**\n\t * Set the session display name.\n\t */\n\tasync setSessionName(name: string): Promise {\n\t\tawait this.send({ type: \"set_session_name\", name });\n\t}\n\n\t/**\n\t * Get all messages in the session.\n\t */\n\tasync getMessages(): Promise {\n\t\tconst response = await this.send({ type: \"get_messages\" });\n\t\treturn this.getData<{ messages: AgentMessage[] }>(response).messages;\n\t}\n\n\t/**\n\t * Get available commands (extension commands, prompt templates, skills).\n\t */\n\tasync getCommands(): Promise {\n\t\tconst response = await this.send({ type: \"get_commands\" });\n\t\treturn this.getData<{ commands: RpcSlashCommand[] }>(response).commands;\n\t}\n\n\t// =========================================================================\n\t// Helpers\n\t// =========================================================================\n\n\t/**\n\t * Wait for agent to become idle (no streaming).\n\t * Resolves when agent_settled event is received.\n\t */\n\twaitForIdle(timeout = 60000): Promise {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tunsubscribe();\n\t\t\t\treject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`));\n\t\t\t}, timeout);\n\n\t\t\tconst unsubscribe = this.onEvent((event) => {\n\t\t\t\tif (event.type === \"agent_settled\") {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Collect events until agent becomes idle.\n\t */\n\tcollectEvents(timeout = 60000): Promise {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst events: AgentSessionEvent[] = [];\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tunsubscribe();\n\t\t\t\treject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`));\n\t\t\t}, timeout);\n\n\t\t\tconst unsubscribe = this.onEvent((event) => {\n\t\t\t\tevents.push(event);\n\t\t\t\tif (event.type === \"agent_settled\") {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tunsubscribe();\n\t\t\t\t\tresolve(events);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Send prompt and wait for completion, returning all events.\n\t */\n\tasync promptAndWait(message: string, images?: ImageContent[], timeout = 60000): Promise {\n\t\tconst eventsPromise = this.collectEvents(timeout);\n\t\tawait this.prompt(message, images);\n\t\treturn eventsPromise;\n\t}\n\n\t// =========================================================================\n\t// Internal\n\t// =========================================================================\n\n\tprivate handleLine(line: string): void {\n\t\ttry {\n\t\t\tconst data = JSON.parse(line);\n\n\t\t\t// Check if it's a response to a pending request\n\t\t\tif (data.type === \"response\" && data.id && this.pendingRequests.has(data.id)) {\n\t\t\t\tconst pending = this.pendingRequests.get(data.id)!;\n\t\t\t\tthis.pendingRequests.delete(data.id);\n\t\t\t\tpending.resolve(data as RpcResponse);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Otherwise it's an event\n\t\t\tfor (const listener of this.eventListeners) {\n\t\t\t\tlistener(data as AgentSessionEvent);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore non-JSON lines\n\t\t}\n\t}\n\n\tprivate createProcessExitError(code: number | null, signal: NodeJS.Signals | null): Error {\n\t\treturn new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`);\n\t}\n\n\tprivate rejectPendingRequests(error: Error): void {\n\t\tfor (const pending of this.pendingRequests.values()) {\n\t\t\tpending.reject(error);\n\t\t}\n\t\tthis.pendingRequests.clear();\n\t}\n\n\tprivate async send(command: RpcCommandBody): Promise {\n\t\tconst childProcess = this.process;\n\t\tconst stdin = childProcess?.stdin;\n\t\tif (!childProcess || !stdin) {\n\t\t\tthrow new Error(\"Client not started\");\n\t\t}\n\t\tif (this.exitError) {\n\t\t\tthrow this.exitError;\n\t\t}\n\t\tif (childProcess.exitCode !== null) {\n\t\t\tconst error = this.createProcessExitError(childProcess.exitCode, childProcess.signalCode);\n\t\t\tthis.exitError = error;\n\t\t\tthrow error;\n\t\t}\n\t\tif (stdin.destroyed || !stdin.writable) {\n\t\t\tconst error = new Error(`Agent process stdin is not writable. Stderr: ${this.stderr}`);\n\t\t\tthis.exitError = error;\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst id = `req_${++this.requestId}`;\n\t\tconst fullCommand = { ...command, id } as RpcCommand;\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tthis.pendingRequests.delete(id);\n\t\t\t\treject(new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`));\n\t\t\t}, 30000);\n\n\t\t\tthis.pendingRequests.set(id, {\n\t\t\t\tresolve: (response) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tresolve(response);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\tstdin.write(serializeJsonLine(fullCommand));\n\t\t\t} catch (error: unknown) {\n\t\t\t\tconst writeError = error instanceof Error ? error : new Error(String(error));\n\t\t\t\tconst pending = this.pendingRequests.get(id);\n\t\t\t\tthis.pendingRequests.delete(id);\n\t\t\t\tpending?.reject(writeError);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate getData(response: RpcResponse): T {\n\t\tif (!response.success) {\n\t\t\tconst errorResponse = response as Extract;\n\t\t\tthrow new Error(errorResponse.error);\n\t\t}\n\t\t// Type assertion: we trust response.data matches T based on the command sent.\n\t\t// This is safe because each public method specifies the correct T for its command.\n\t\tconst successResponse = response as Extract;\n\t\treturn successResponse.data as T;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/modes/rpc/rpc-mode.d.ts b/dist/modes/rpc/rpc-mode.d.ts new file mode 100644 index 0000000..b37ddc5 --- /dev/null +++ b/dist/modes/rpc/rpc-mode.d.ts @@ -0,0 +1,20 @@ +/** + * RPC mode: Headless operation with JSON stdin/stdout protocol. + * + * Used for embedding the agent in other applications. + * Receives commands as JSON on stdin, outputs events and responses as JSON on stdout. + * + * Protocol: + * - Commands: JSON objects with `type` field, optional `id` for correlation + * - Responses: JSON objects with `type: "response"`, `command`, `success`, and optional `data`/`error` + * - Events: AgentSessionEvent objects streamed as they occur + * - Extension UI: Extension UI requests are emitted, client responds with extension_ui_response + */ +import type { AgentSessionRuntime } from "../../core/agent-session-runtime.ts"; +export type { RpcCommand, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcResponse, RpcSessionState, } from "./rpc-types.ts"; +/** + * Run in RPC mode. + * Listens for JSON commands on stdin, outputs events and responses on stdout. + */ +export declare function runRpcMode(runtimeHost: AgentSessionRuntime): Promise; +//# sourceMappingURL=rpc-mode.d.ts.map \ No newline at end of file diff --git a/dist/modes/rpc/rpc-mode.d.ts.map b/dist/modes/rpc/rpc-mode.d.ts.map new file mode 100644 index 0000000..06af14b --- /dev/null +++ b/dist/modes/rpc/rpc-mode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc-mode.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-mode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AA0B/E,YAAY,EACX,UAAU,EACV,qBAAqB,EACrB,sBAAsB,EACtB,WAAW,EACX,eAAe,GACf,MAAM,gBAAgB,CAAC;AAExB;;;GAGG;AACH,wBAAsB,UAAU,CAAC,WAAW,EAAE,mBAAmB,GAAG,OAAO,CAAC,KAAK,CAAC,CA2vBjF","sourcesContent":["/**\n * RPC mode: Headless operation with JSON stdin/stdout protocol.\n *\n * Used for embedding the agent in other applications.\n * Receives commands as JSON on stdin, outputs events and responses as JSON on stdout.\n *\n * Protocol:\n * - Commands: JSON objects with `type` field, optional `id` for correlation\n * - Responses: JSON objects with `type: \"response\"`, `command`, `success`, and optional `data`/`error`\n * - Events: AgentSessionEvent objects streamed as they occur\n * - Extension UI: Extension UI requests are emitted, client responds with extension_ui_response\n */\n\nimport * as crypto from \"node:crypto\";\nimport type { AgentSessionRuntime } from \"../../core/agent-session-runtime.ts\";\nimport type {\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tWorkingIndicatorOptions,\n} from \"../../core/extensions/index.ts\";\nimport {\n\tflushRawStdout,\n\ttakeOverStdout,\n\twaitForRawStdoutBackpressure,\n\twriteRawStdout,\n} from \"../../core/output-guard.ts\";\nimport { killTrackedDetachedChildren } from \"../../utils/shell.ts\";\nimport { type Theme, theme } from \"../interactive/theme/theme.ts\";\nimport { attachJsonlLineReader, serializeJsonLine } from \"./jsonl.ts\";\nimport type {\n\tRpcCommand,\n\tRpcExtensionUIRequest,\n\tRpcExtensionUIResponse,\n\tRpcResponse,\n\tRpcSessionState,\n\tRpcSlashCommand,\n} from \"./rpc-types.ts\";\n\n// Re-export types for consumers\nexport type {\n\tRpcCommand,\n\tRpcExtensionUIRequest,\n\tRpcExtensionUIResponse,\n\tRpcResponse,\n\tRpcSessionState,\n} from \"./rpc-types.ts\";\n\n/**\n * Run in RPC mode.\n * Listens for JSON commands on stdin, outputs events and responses on stdout.\n */\nexport async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise {\n\ttakeOverStdout();\n\tlet session = runtimeHost.session;\n\tlet unsubscribe: (() => void) | undefined;\n\tlet unsubscribeBackpressure: (() => void) | undefined;\n\n\tconst output = (obj: RpcResponse | RpcExtensionUIRequest | object) => {\n\t\twriteRawStdout(serializeJsonLine(obj));\n\t};\n\n\tconst success = (\n\t\tid: string | undefined,\n\t\tcommand: T,\n\t\tdata?: object | null,\n\t): RpcResponse => {\n\t\tif (data === undefined) {\n\t\t\treturn { id, type: \"response\", command, success: true } as RpcResponse;\n\t\t}\n\t\treturn { id, type: \"response\", command, success: true, data } as RpcResponse;\n\t};\n\n\tconst error = (id: string | undefined, command: string, message: string): RpcResponse => {\n\t\treturn { id, type: \"response\", command, success: false, error: message };\n\t};\n\n\t// Pending extension UI requests waiting for response\n\tconst pendingExtensionRequests = new Map<\n\t\tstring,\n\t\t{ resolve: (value: any) => void; reject: (error: Error) => void }\n\t>();\n\n\t// Shutdown request flag\n\tlet shutdownRequested = false;\n\tlet shuttingDown = false;\n\tconst signalCleanupHandlers: Array<() => void> = [];\n\n\t/** Helper for dialog methods with signal/timeout support */\n\tfunction createDialogPromise(\n\t\topts: ExtensionUIDialogOptions | undefined,\n\t\tdefaultValue: T,\n\t\trequest: Record,\n\t\tparseResponse: (response: RpcExtensionUIResponse) => T,\n\t): Promise {\n\t\tif (opts?.signal?.aborted) return Promise.resolve(defaultValue);\n\n\t\tconst id = crypto.randomUUID();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet timeoutId: ReturnType | undefined;\n\n\t\t\tconst cleanup = () => {\n\t\t\t\tif (timeoutId) clearTimeout(timeoutId);\n\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tpendingExtensionRequests.delete(id);\n\t\t\t};\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(defaultValue);\n\t\t\t};\n\t\t\topts?.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\tif (opts?.timeout) {\n\t\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(defaultValue);\n\t\t\t\t}, opts.timeout);\n\t\t\t}\n\n\t\t\tpendingExtensionRequests.set(id, {\n\t\t\t\tresolve: (response: RpcExtensionUIResponse) => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(parseResponse(response));\n\t\t\t\t},\n\t\t\t\treject,\n\t\t\t});\n\t\t\toutput({ type: \"extension_ui_request\", id, ...request } as RpcExtensionUIRequest);\n\t\t});\n\t}\n\n\t/**\n\t * Create an extension UI context that uses the RPC protocol.\n\t */\n\tconst createExtensionUIContext = (): ExtensionUIContext => ({\n\t\tselect: (title, options, opts) =>\n\t\t\tcreateDialogPromise(opts, undefined, { method: \"select\", title, options, timeout: opts?.timeout }, (r) =>\n\t\t\t\t\"cancelled\" in r && r.cancelled ? undefined : \"value\" in r ? r.value : undefined,\n\t\t\t),\n\n\t\tconfirm: (title, message, opts) =>\n\t\t\tcreateDialogPromise(opts, false, { method: \"confirm\", title, message, timeout: opts?.timeout }, (r) =>\n\t\t\t\t\"cancelled\" in r && r.cancelled ? false : \"confirmed\" in r ? r.confirmed : false,\n\t\t\t),\n\n\t\tinput: (title, placeholder, opts) =>\n\t\t\tcreateDialogPromise(opts, undefined, { method: \"input\", title, placeholder, timeout: opts?.timeout }, (r) =>\n\t\t\t\t\"cancelled\" in r && r.cancelled ? undefined : \"value\" in r ? r.value : undefined,\n\t\t\t),\n\n\t\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void {\n\t\t\t// Fire and forget - no response needed\n\t\t\toutput({\n\t\t\t\ttype: \"extension_ui_request\",\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\tmethod: \"notify\",\n\t\t\t\tmessage,\n\t\t\t\tnotifyType: type,\n\t\t\t} as RpcExtensionUIRequest);\n\t\t},\n\n\t\tonTerminalInput(): () => void {\n\t\t\t// Raw terminal input not supported in RPC mode\n\t\t\treturn () => {};\n\t\t},\n\n\t\tsetStatus(key: string, text: string | undefined): void {\n\t\t\t// Fire and forget - no response needed\n\t\t\toutput({\n\t\t\t\ttype: \"extension_ui_request\",\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\tmethod: \"setStatus\",\n\t\t\t\tstatusKey: key,\n\t\t\t\tstatusText: text,\n\t\t\t} as RpcExtensionUIRequest);\n\t\t},\n\n\t\tsetWorkingMessage(_message?: string): void {\n\t\t\t// Working message not supported in RPC mode - requires TUI loader access\n\t\t},\n\n\t\tsetWorkingVisible(_visible: boolean): void {\n\t\t\t// Working visibility not supported in RPC mode - requires TUI loader access\n\t\t},\n\n\t\tsetWorkingIndicator(_options?: WorkingIndicatorOptions): void {\n\t\t\t// Working indicator customization not supported in RPC mode - requires TUI loader access\n\t\t},\n\n\t\tsetHiddenThinkingLabel(_label?: string): void {\n\t\t\t// Hidden thinking label not supported in RPC mode - requires TUI message rendering access\n\t\t},\n\n\t\tsetWidget(key: string, content: unknown, options?: ExtensionWidgetOptions): void {\n\t\t\t// Only support string arrays in RPC mode - factory functions are ignored\n\t\t\tif (content === undefined || Array.isArray(content)) {\n\t\t\t\toutput({\n\t\t\t\t\ttype: \"extension_ui_request\",\n\t\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\t\tmethod: \"setWidget\",\n\t\t\t\t\twidgetKey: key,\n\t\t\t\t\twidgetLines: content as string[] | undefined,\n\t\t\t\t\twidgetPlacement: options?.placement,\n\t\t\t\t} as RpcExtensionUIRequest);\n\t\t\t}\n\t\t\t// Component factories are not supported in RPC mode - would need TUI access\n\t\t},\n\n\t\tsetFooter(_factory: unknown): void {\n\t\t\t// Custom footer not supported in RPC mode - requires TUI access\n\t\t},\n\n\t\tsetHeader(_factory: unknown): void {\n\t\t\t// Custom header not supported in RPC mode - requires TUI access\n\t\t},\n\n\t\tsetTitle(title: string): void {\n\t\t\t// Fire and forget - host can implement terminal title control\n\t\t\toutput({\n\t\t\t\ttype: \"extension_ui_request\",\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\tmethod: \"setTitle\",\n\t\t\t\ttitle,\n\t\t\t} as RpcExtensionUIRequest);\n\t\t},\n\n\t\tasync custom() {\n\t\t\t// Custom UI not supported in RPC mode\n\t\t\treturn undefined as never;\n\t\t},\n\n\t\tpasteToEditor(text: string): void {\n\t\t\t// Paste handling not supported in RPC mode - falls back to setEditorText\n\t\t\tthis.setEditorText(text);\n\t\t},\n\n\t\tsetEditorText(text: string): void {\n\t\t\t// Fire and forget - host can implement editor control\n\t\t\toutput({\n\t\t\t\ttype: \"extension_ui_request\",\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\tmethod: \"set_editor_text\",\n\t\t\t\ttext,\n\t\t\t} as RpcExtensionUIRequest);\n\t\t},\n\n\t\tgetEditorText(): string {\n\t\t\t// Synchronous method can't wait for RPC response\n\t\t\t// Host should track editor state locally if needed\n\t\t\treturn \"\";\n\t\t},\n\n\t\tasync editor(title: string, prefill?: string): Promise {\n\t\t\tconst id = crypto.randomUUID();\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tpendingExtensionRequests.set(id, {\n\t\t\t\t\tresolve: (response: RpcExtensionUIResponse) => {\n\t\t\t\t\t\tif (\"cancelled\" in response && response.cancelled) {\n\t\t\t\t\t\t\tresolve(undefined);\n\t\t\t\t\t\t} else if (\"value\" in response) {\n\t\t\t\t\t\t\tresolve(response.value);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresolve(undefined);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\treject,\n\t\t\t\t});\n\t\t\t\toutput({ type: \"extension_ui_request\", id, method: \"editor\", title, prefill } as RpcExtensionUIRequest);\n\t\t\t});\n\t\t},\n\n\t\taddAutocompleteProvider(): void {\n\t\t\t// Autocomplete provider composition is not supported in RPC mode\n\t\t},\n\n\t\tsetEditorComponent(): void {\n\t\t\t// Custom editor components not supported in RPC mode\n\t\t},\n\n\t\tgetEditorComponent() {\n\t\t\t// Custom editor components not supported in RPC mode\n\t\t\treturn undefined;\n\t\t},\n\n\t\tget theme() {\n\t\t\treturn theme;\n\t\t},\n\n\t\tgetAllThemes() {\n\t\t\treturn [];\n\t\t},\n\n\t\tgetTheme(_name: string) {\n\t\t\treturn undefined;\n\t\t},\n\n\t\tsetTheme(_theme: string | Theme) {\n\t\t\t// Theme switching not supported in RPC mode\n\t\t\treturn { success: false, error: \"Theme switching not supported in RPC mode\" };\n\t\t},\n\n\t\tgetToolsExpanded() {\n\t\t\t// Tool expansion not supported in RPC mode - no TUI\n\t\t\treturn false;\n\t\t},\n\n\t\tsetToolsExpanded(_expanded: boolean) {\n\t\t\t// Tool expansion not supported in RPC mode - no TUI\n\t\t},\n\t});\n\n\truntimeHost.setRebindSession(async () => {\n\t\tawait rebindSession();\n\t});\n\n\tconst rebindSession = async (): Promise => {\n\t\tsession = runtimeHost.session;\n\t\tawait session.bindExtensions({\n\t\t\tuiContext: createExtensionUIContext(),\n\t\t\tmode: \"rpc\",\n\t\t\tcommandContextActions: {\n\t\t\t\twaitForIdle: () => session.waitForIdle(),\n\t\t\t\tnewSession: async (options) => runtimeHost.newSession(options),\n\t\t\t\tfork: async (entryId, forkOptions) => {\n\t\t\t\t\tconst result = await runtimeHost.fork(entryId, forkOptions);\n\t\t\t\t\treturn { cancelled: result.cancelled };\n\t\t\t\t},\n\t\t\t\tnavigateTree: async (targetId, options) => {\n\t\t\t\t\tconst result = await session.navigateTree(targetId, {\n\t\t\t\t\t\tsummarize: options?.summarize,\n\t\t\t\t\t\tcustomInstructions: options?.customInstructions,\n\t\t\t\t\t\treplaceInstructions: options?.replaceInstructions,\n\t\t\t\t\t\tlabel: options?.label,\n\t\t\t\t\t});\n\t\t\t\t\treturn { cancelled: result.cancelled };\n\t\t\t\t},\n\t\t\t\tswitchSession: async (sessionPath, options) => {\n\t\t\t\t\treturn runtimeHost.switchSession(sessionPath, options);\n\t\t\t\t},\n\t\t\t\treload: async () => {\n\t\t\t\t\tawait session.reload();\n\t\t\t\t},\n\t\t\t},\n\t\t\tshutdownHandler: () => {\n\t\t\t\tshutdownRequested = true;\n\t\t\t},\n\t\t\tonError: (err) => {\n\t\t\t\toutput({ type: \"extension_error\", extensionPath: err.extensionPath, event: err.event, error: err.error });\n\t\t\t},\n\t\t});\n\n\t\tunsubscribe?.();\n\t\tunsubscribeBackpressure?.();\n\t\tunsubscribe = session.subscribe((event) => {\n\t\t\toutput(event);\n\t\t\tif (event.type === \"agent_settled\") {\n\t\t\t\tvoid checkShutdownRequested();\n\t\t\t}\n\t\t});\n\t\tunsubscribeBackpressure = session.agent.subscribe(async () => {\n\t\t\tawait waitForRawStdoutBackpressure();\n\t\t});\n\t};\n\n\tconst registerSignalHandlers = (): void => {\n\t\tconst signals: NodeJS.Signals[] = [\"SIGTERM\"];\n\t\tif (process.platform !== \"win32\") {\n\t\t\tsignals.push(\"SIGHUP\");\n\t\t}\n\n\t\tfor (const signal of signals) {\n\t\t\tconst handler = () => {\n\t\t\t\tkillTrackedDetachedChildren();\n\t\t\t\tvoid shutdown(signal === \"SIGHUP\" ? 129 : 143, signal);\n\t\t\t};\n\t\t\tprocess.on(signal, handler);\n\t\t\tsignalCleanupHandlers.push(() => process.off(signal, handler));\n\t\t}\n\t};\n\n\tawait rebindSession();\n\tregisterSignalHandlers();\n\n\t// Handle a single command\n\tconst handleCommand = async (command: RpcCommand): Promise => {\n\t\tconst id = command.id;\n\n\t\tswitch (command.type) {\n\t\t\t// =================================================================\n\t\t\t// Prompting\n\t\t\t// =================================================================\n\n\t\t\tcase \"prompt\": {\n\t\t\t\t// Start prompt handling immediately, but emit the authoritative response only after\n\t\t\t\t// prompt preflight succeeds. Queued and immediately handled prompts also count as success.\n\t\t\t\tlet preflightSucceeded = false;\n\t\t\t\tvoid session\n\t\t\t\t\t.prompt(command.message, {\n\t\t\t\t\t\timages: command.images,\n\t\t\t\t\t\tstreamingBehavior: command.streamingBehavior,\n\t\t\t\t\t\tsource: \"rpc\",\n\t\t\t\t\t\tpreflightResult: (didSucceed) => {\n\t\t\t\t\t\t\tif (didSucceed) {\n\t\t\t\t\t\t\t\tpreflightSucceeded = true;\n\t\t\t\t\t\t\t\toutput(success(id, \"prompt\"));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t\t.catch((e) => {\n\t\t\t\t\t\tif (!preflightSucceeded) {\n\t\t\t\t\t\t\toutput(error(id, \"prompt\", e.message));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\tcase \"steer\": {\n\t\t\t\tawait session.steer(command.message, command.images);\n\t\t\t\treturn success(id, \"steer\");\n\t\t\t}\n\n\t\t\tcase \"follow_up\": {\n\t\t\t\tawait session.followUp(command.message, command.images);\n\t\t\t\treturn success(id, \"follow_up\");\n\t\t\t}\n\n\t\t\tcase \"abort\": {\n\t\t\t\tawait session.abort();\n\t\t\t\treturn success(id, \"abort\");\n\t\t\t}\n\n\t\t\tcase \"new_session\": {\n\t\t\t\tconst options = command.parentSession ? { parentSession: command.parentSession } : undefined;\n\t\t\t\tconst result = await runtimeHost.newSession(options);\n\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\tawait rebindSession();\n\t\t\t\t}\n\t\t\t\treturn success(id, \"new_session\", result);\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// State\n\t\t\t// =================================================================\n\n\t\t\tcase \"get_state\": {\n\t\t\t\tconst state: RpcSessionState = {\n\t\t\t\t\tmodel: session.model,\n\t\t\t\t\tthinkingLevel: session.thinkingLevel,\n\t\t\t\t\tisStreaming: session.isStreaming,\n\t\t\t\t\tisCompacting: session.isCompacting,\n\t\t\t\t\tsteeringMode: session.steeringMode,\n\t\t\t\t\tfollowUpMode: session.followUpMode,\n\t\t\t\t\tsessionFile: session.sessionFile,\n\t\t\t\t\tsessionId: session.sessionId,\n\t\t\t\t\tsessionName: session.sessionName,\n\t\t\t\t\tautoCompactionEnabled: session.autoCompactionEnabled,\n\t\t\t\t\tmessageCount: session.messages.length,\n\t\t\t\t\tpendingMessageCount: session.pendingMessageCount,\n\t\t\t\t};\n\t\t\t\treturn success(id, \"get_state\", state);\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Model\n\t\t\t// =================================================================\n\n\t\t\tcase \"set_model\": {\n\t\t\t\tconst models = await session.modelRuntime.getAvailable();\n\t\t\t\tconst model = models.find((m) => m.provider === command.provider && m.id === command.modelId);\n\t\t\t\tif (!model) {\n\t\t\t\t\treturn error(id, \"set_model\", `Model not found: ${command.provider}/${command.modelId}`);\n\t\t\t\t}\n\t\t\t\tawait session.setModel(model);\n\t\t\t\treturn success(id, \"set_model\", model);\n\t\t\t}\n\n\t\t\tcase \"cycle_model\": {\n\t\t\t\tconst result = await session.cycleModel();\n\t\t\t\tif (!result) {\n\t\t\t\t\treturn success(id, \"cycle_model\", null);\n\t\t\t\t}\n\t\t\t\treturn success(id, \"cycle_model\", result);\n\t\t\t}\n\n\t\t\tcase \"get_available_models\": {\n\t\t\t\tconst models = await session.modelRuntime.getAvailable();\n\t\t\t\treturn success(id, \"get_available_models\", { models });\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Thinking\n\t\t\t// =================================================================\n\n\t\t\tcase \"set_thinking_level\": {\n\t\t\t\tsession.setThinkingLevel(command.level);\n\t\t\t\treturn success(id, \"set_thinking_level\");\n\t\t\t}\n\n\t\t\tcase \"cycle_thinking_level\": {\n\t\t\t\tconst level = session.cycleThinkingLevel();\n\t\t\t\tif (!level) {\n\t\t\t\t\treturn success(id, \"cycle_thinking_level\", null);\n\t\t\t\t}\n\t\t\t\treturn success(id, \"cycle_thinking_level\", { level });\n\t\t\t}\n\n\t\t\tcase \"get_available_thinking_levels\": {\n\t\t\t\tconst levels = session.getAvailableThinkingLevels();\n\t\t\t\treturn success(id, \"get_available_thinking_levels\", { levels });\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Queue Modes\n\t\t\t// =================================================================\n\n\t\t\tcase \"set_steering_mode\": {\n\t\t\t\tsession.setSteeringMode(command.mode);\n\t\t\t\treturn success(id, \"set_steering_mode\");\n\t\t\t}\n\n\t\t\tcase \"set_follow_up_mode\": {\n\t\t\t\tsession.setFollowUpMode(command.mode);\n\t\t\t\treturn success(id, \"set_follow_up_mode\");\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Compaction\n\t\t\t// =================================================================\n\n\t\t\tcase \"compact\": {\n\t\t\t\tconst result = await session.compact(command.customInstructions);\n\t\t\t\treturn success(id, \"compact\", result);\n\t\t\t}\n\n\t\t\tcase \"set_auto_compaction\": {\n\t\t\t\tsession.setAutoCompactionEnabled(command.enabled);\n\t\t\t\treturn success(id, \"set_auto_compaction\");\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Retry\n\t\t\t// =================================================================\n\n\t\t\tcase \"set_auto_retry\": {\n\t\t\t\tsession.setAutoRetryEnabled(command.enabled);\n\t\t\t\treturn success(id, \"set_auto_retry\");\n\t\t\t}\n\n\t\t\tcase \"abort_retry\": {\n\t\t\t\tsession.abortRetry();\n\t\t\t\treturn success(id, \"abort_retry\");\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Bash\n\t\t\t// =================================================================\n\n\t\t\tcase \"bash\": {\n\t\t\t\tconst eventResult = await session.extensionRunner.emitUserBash({\n\t\t\t\t\ttype: \"user_bash\",\n\t\t\t\t\tcommand: command.command,\n\t\t\t\t\texcludeFromContext: command.excludeFromContext ?? false,\n\t\t\t\t\tcwd: session.sessionManager.getCwd(),\n\t\t\t\t});\n\n\t\t\t\tif (eventResult?.result) {\n\t\t\t\t\tsession.recordBashResult(command.command, eventResult.result, {\n\t\t\t\t\t\texcludeFromContext: command.excludeFromContext,\n\t\t\t\t\t});\n\t\t\t\t\treturn success(id, \"bash\", eventResult.result);\n\t\t\t\t}\n\n\t\t\t\tconst result = await session.executeBash(command.command, undefined, {\n\t\t\t\t\texcludeFromContext: command.excludeFromContext,\n\t\t\t\t\tid,\n\t\t\t\t\toperations: eventResult?.operations,\n\t\t\t\t});\n\t\t\t\treturn success(id, \"bash\", result);\n\t\t\t}\n\n\t\t\tcase \"abort_bash\": {\n\t\t\t\tsession.abortBash();\n\t\t\t\treturn success(id, \"abort_bash\");\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Session\n\t\t\t// =================================================================\n\n\t\t\tcase \"get_session_stats\": {\n\t\t\t\tconst stats = session.getSessionStats();\n\t\t\t\treturn success(id, \"get_session_stats\", stats);\n\t\t\t}\n\n\t\t\tcase \"export_html\": {\n\t\t\t\tconst path = await session.exportToHtml(command.outputPath);\n\t\t\t\treturn success(id, \"export_html\", { path });\n\t\t\t}\n\n\t\t\tcase \"switch_session\": {\n\t\t\t\tconst result = await runtimeHost.switchSession(command.sessionPath);\n\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\tawait rebindSession();\n\t\t\t\t}\n\t\t\t\treturn success(id, \"switch_session\", result);\n\t\t\t}\n\n\t\t\tcase \"fork\": {\n\t\t\t\tconst result = await runtimeHost.fork(command.entryId);\n\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\tawait rebindSession();\n\t\t\t\t}\n\t\t\t\treturn success(id, \"fork\", { text: result.selectedText, cancelled: result.cancelled });\n\t\t\t}\n\n\t\t\tcase \"clone\": {\n\t\t\t\tconst leafId = session.sessionManager.getLeafId();\n\t\t\t\tif (!leafId) {\n\t\t\t\t\treturn error(id, \"clone\", \"Cannot clone session: no current entry selected\");\n\t\t\t\t}\n\t\t\t\tconst result = await runtimeHost.fork(leafId, { position: \"at\" });\n\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\tawait rebindSession();\n\t\t\t\t}\n\t\t\t\treturn success(id, \"clone\", { cancelled: result.cancelled });\n\t\t\t}\n\n\t\t\tcase \"get_fork_messages\": {\n\t\t\t\tconst messages = session.getUserMessagesForForking();\n\t\t\t\treturn success(id, \"get_fork_messages\", { messages });\n\t\t\t}\n\n\t\t\tcase \"get_entries\": {\n\t\t\t\tconst sessionManager = session.sessionManager;\n\t\t\t\tlet entries = sessionManager.getEntries();\n\t\t\t\tif (command.since !== undefined) {\n\t\t\t\t\tconst sinceIndex = entries.findIndex((e) => e.id === command.since);\n\t\t\t\t\tif (sinceIndex === -1) {\n\t\t\t\t\t\treturn error(id, \"get_entries\", `Entry not found: ${command.since}`);\n\t\t\t\t\t}\n\t\t\t\t\tentries = entries.slice(sinceIndex + 1);\n\t\t\t\t}\n\t\t\t\treturn success(id, \"get_entries\", { entries, leafId: sessionManager.getLeafId() });\n\t\t\t}\n\n\t\t\tcase \"get_tree\": {\n\t\t\t\tconst sessionManager = session.sessionManager;\n\t\t\t\treturn success(id, \"get_tree\", { tree: sessionManager.getTree(), leafId: sessionManager.getLeafId() });\n\t\t\t}\n\n\t\t\tcase \"get_last_assistant_text\": {\n\t\t\t\tconst text = session.getLastAssistantText();\n\t\t\t\treturn success(id, \"get_last_assistant_text\", { text });\n\t\t\t}\n\n\t\t\tcase \"set_session_name\": {\n\t\t\t\tconst name = command.name.trim();\n\t\t\t\tif (!name) {\n\t\t\t\t\treturn error(id, \"set_session_name\", \"Session name cannot be empty\");\n\t\t\t\t}\n\t\t\t\tsession.setSessionName(name);\n\t\t\t\treturn success(id, \"set_session_name\");\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Messages\n\t\t\t// =================================================================\n\n\t\t\tcase \"get_messages\": {\n\t\t\t\treturn success(id, \"get_messages\", { messages: session.messages });\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Commands (available for invocation via prompt)\n\t\t\t// =================================================================\n\n\t\t\tcase \"get_commands\": {\n\t\t\t\tconst commands: RpcSlashCommand[] = [];\n\n\t\t\t\tfor (const command of session.extensionRunner.getRegisteredCommands()) {\n\t\t\t\t\tcommands.push({\n\t\t\t\t\t\tname: command.invocationName,\n\t\t\t\t\t\tdescription: command.description,\n\t\t\t\t\t\tsource: \"extension\",\n\t\t\t\t\t\tsourceInfo: command.sourceInfo,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tfor (const template of session.promptTemplates) {\n\t\t\t\t\tcommands.push({\n\t\t\t\t\t\tname: template.name,\n\t\t\t\t\t\tdescription: template.description,\n\t\t\t\t\t\tsource: \"prompt\",\n\t\t\t\t\t\tsourceInfo: template.sourceInfo,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tfor (const skill of session.resourceLoader.getSkills().skills) {\n\t\t\t\t\tcommands.push({\n\t\t\t\t\t\tname: `skill:${skill.name}`,\n\t\t\t\t\t\tdescription: skill.description,\n\t\t\t\t\t\tsource: \"skill\",\n\t\t\t\t\t\tsourceInfo: skill.sourceInfo,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn success(id, \"get_commands\", { commands });\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tconst unknownCommand = command as { type: string };\n\t\t\t\treturn error(id, unknownCommand.type, `Unknown command: ${unknownCommand.type}`);\n\t\t\t}\n\t\t}\n\t};\n\n\t/**\n\t * Check if shutdown was requested and perform shutdown if so.\n\t * Called after handling each command when waiting for the next command.\n\t */\n\tlet detachInput = () => {};\n\n\tasync function shutdown(exitCode = 0, signal?: NodeJS.Signals): Promise {\n\t\tif (shuttingDown) {\n\t\t\tprocess.exit(exitCode);\n\t\t}\n\t\tshuttingDown = true;\n\t\tfor (const cleanup of signalCleanupHandlers) {\n\t\t\tcleanup();\n\t\t}\n\t\tunsubscribe?.();\n\t\tunsubscribeBackpressure?.();\n\t\tawait runtimeHost.dispose();\n\t\tdetachInput();\n\t\tprocess.stdin.pause();\n\t\tif (signal !== \"SIGTERM\") {\n\t\t\tawait flushRawStdout();\n\t\t}\n\t\tprocess.exit(exitCode);\n\t}\n\n\tasync function checkShutdownRequested(): Promise {\n\t\tif (!shutdownRequested) return;\n\t\tawait shutdown();\n\t}\n\n\tconst handleInputLine = async (line: string) => {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(line);\n\t\t} catch (parseError: unknown) {\n\t\t\toutput(\n\t\t\t\terror(\n\t\t\t\t\tundefined,\n\t\t\t\t\t\"parse\",\n\t\t\t\t\t`Failed to parse command: ${parseError instanceof Error ? parseError.message : String(parseError)}`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tawait waitForRawStdoutBackpressure();\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle extension UI responses\n\t\tif (\n\t\t\ttypeof parsed === \"object\" &&\n\t\t\tparsed !== null &&\n\t\t\t\"type\" in parsed &&\n\t\t\tparsed.type === \"extension_ui_response\"\n\t\t) {\n\t\t\tconst response = parsed as RpcExtensionUIResponse;\n\t\t\tconst pending = pendingExtensionRequests.get(response.id);\n\t\t\tif (pending) {\n\t\t\t\tpendingExtensionRequests.delete(response.id);\n\t\t\t\tpending.resolve(response);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst command = parsed as RpcCommand;\n\t\ttry {\n\t\t\tconst response = await handleCommand(command);\n\t\t\tif (response) {\n\t\t\t\toutput(response);\n\t\t\t\tawait waitForRawStdoutBackpressure();\n\t\t\t}\n\t\t\tawait checkShutdownRequested();\n\t\t} catch (commandError: unknown) {\n\t\t\toutput(\n\t\t\t\terror(\n\t\t\t\t\tcommand.id,\n\t\t\t\t\tcommand.type,\n\t\t\t\t\tcommandError instanceof Error ? commandError.message : String(commandError),\n\t\t\t\t),\n\t\t\t);\n\t\t\tawait waitForRawStdoutBackpressure();\n\t\t}\n\t};\n\n\tconst onInputEnd = () => {\n\t\tvoid shutdown();\n\t};\n\tprocess.stdin.on(\"end\", onInputEnd);\n\n\tdetachInput = (() => {\n\t\tconst detachJsonl = attachJsonlLineReader(process.stdin, (line) => {\n\t\t\tvoid handleInputLine(line);\n\t\t});\n\t\treturn () => {\n\t\t\tdetachJsonl();\n\t\t\tprocess.stdin.off(\"end\", onInputEnd);\n\t\t};\n\t})();\n\n\t// Keep process alive forever\n\treturn new Promise(() => {});\n}\n"]} \ No newline at end of file diff --git a/dist/modes/rpc/rpc-mode.js b/dist/modes/rpc/rpc-mode.js new file mode 100644 index 0000000..8567321 --- /dev/null +++ b/dist/modes/rpc/rpc-mode.js @@ -0,0 +1,653 @@ +/** + * RPC mode: Headless operation with JSON stdin/stdout protocol. + * + * Used for embedding the agent in other applications. + * Receives commands as JSON on stdin, outputs events and responses as JSON on stdout. + * + * Protocol: + * - Commands: JSON objects with `type` field, optional `id` for correlation + * - Responses: JSON objects with `type: "response"`, `command`, `success`, and optional `data`/`error` + * - Events: AgentSessionEvent objects streamed as they occur + * - Extension UI: Extension UI requests are emitted, client responds with extension_ui_response + */ +import * as crypto from "node:crypto"; +import { flushRawStdout, takeOverStdout, waitForRawStdoutBackpressure, writeRawStdout, } from "../../core/output-guard.js"; +import { killTrackedDetachedChildren } from "../../utils/shell.js"; +import { theme } from "../interactive/theme/theme.js"; +import { attachJsonlLineReader, serializeJsonLine } from "./jsonl.js"; +/** + * Run in RPC mode. + * Listens for JSON commands on stdin, outputs events and responses on stdout. + */ +export async function runRpcMode(runtimeHost) { + takeOverStdout(); + let session = runtimeHost.session; + let unsubscribe; + let unsubscribeBackpressure; + const output = (obj) => { + writeRawStdout(serializeJsonLine(obj)); + }; + const success = (id, command, data) => { + if (data === undefined) { + return { id, type: "response", command, success: true }; + } + return { id, type: "response", command, success: true, data }; + }; + const error = (id, command, message) => { + return { id, type: "response", command, success: false, error: message }; + }; + // Pending extension UI requests waiting for response + const pendingExtensionRequests = new Map(); + // Shutdown request flag + let shutdownRequested = false; + let shuttingDown = false; + const signalCleanupHandlers = []; + /** Helper for dialog methods with signal/timeout support */ + function createDialogPromise(opts, defaultValue, request, parseResponse) { + if (opts?.signal?.aborted) + return Promise.resolve(defaultValue); + const id = crypto.randomUUID(); + return new Promise((resolve, reject) => { + let timeoutId; + const cleanup = () => { + if (timeoutId) + clearTimeout(timeoutId); + opts?.signal?.removeEventListener("abort", onAbort); + pendingExtensionRequests.delete(id); + }; + const onAbort = () => { + cleanup(); + resolve(defaultValue); + }; + opts?.signal?.addEventListener("abort", onAbort, { once: true }); + if (opts?.timeout) { + timeoutId = setTimeout(() => { + cleanup(); + resolve(defaultValue); + }, opts.timeout); + } + pendingExtensionRequests.set(id, { + resolve: (response) => { + cleanup(); + resolve(parseResponse(response)); + }, + reject, + }); + output({ type: "extension_ui_request", id, ...request }); + }); + } + /** + * Create an extension UI context that uses the RPC protocol. + */ + const createExtensionUIContext = () => ({ + select: (title, options, opts) => createDialogPromise(opts, undefined, { method: "select", title, options, timeout: opts?.timeout }, (r) => "cancelled" in r && r.cancelled ? undefined : "value" in r ? r.value : undefined), + confirm: (title, message, opts) => createDialogPromise(opts, false, { method: "confirm", title, message, timeout: opts?.timeout }, (r) => "cancelled" in r && r.cancelled ? false : "confirmed" in r ? r.confirmed : false), + input: (title, placeholder, opts) => createDialogPromise(opts, undefined, { method: "input", title, placeholder, timeout: opts?.timeout }, (r) => "cancelled" in r && r.cancelled ? undefined : "value" in r ? r.value : undefined), + notify(message, type) { + // Fire and forget - no response needed + output({ + type: "extension_ui_request", + id: crypto.randomUUID(), + method: "notify", + message, + notifyType: type, + }); + }, + onTerminalInput() { + // Raw terminal input not supported in RPC mode + return () => { }; + }, + setStatus(key, text) { + // Fire and forget - no response needed + output({ + type: "extension_ui_request", + id: crypto.randomUUID(), + method: "setStatus", + statusKey: key, + statusText: text, + }); + }, + setWorkingMessage(_message) { + // Working message not supported in RPC mode - requires TUI loader access + }, + setWorkingVisible(_visible) { + // Working visibility not supported in RPC mode - requires TUI loader access + }, + setWorkingIndicator(_options) { + // Working indicator customization not supported in RPC mode - requires TUI loader access + }, + setHiddenThinkingLabel(_label) { + // Hidden thinking label not supported in RPC mode - requires TUI message rendering access + }, + setWidget(key, content, options) { + // Only support string arrays in RPC mode - factory functions are ignored + if (content === undefined || Array.isArray(content)) { + output({ + type: "extension_ui_request", + id: crypto.randomUUID(), + method: "setWidget", + widgetKey: key, + widgetLines: content, + widgetPlacement: options?.placement, + }); + } + // Component factories are not supported in RPC mode - would need TUI access + }, + setFooter(_factory) { + // Custom footer not supported in RPC mode - requires TUI access + }, + setHeader(_factory) { + // Custom header not supported in RPC mode - requires TUI access + }, + setTitle(title) { + // Fire and forget - host can implement terminal title control + output({ + type: "extension_ui_request", + id: crypto.randomUUID(), + method: "setTitle", + title, + }); + }, + async custom() { + // Custom UI not supported in RPC mode + return undefined; + }, + pasteToEditor(text) { + // Paste handling not supported in RPC mode - falls back to setEditorText + this.setEditorText(text); + }, + setEditorText(text) { + // Fire and forget - host can implement editor control + output({ + type: "extension_ui_request", + id: crypto.randomUUID(), + method: "set_editor_text", + text, + }); + }, + getEditorText() { + // Synchronous method can't wait for RPC response + // Host should track editor state locally if needed + return ""; + }, + async editor(title, prefill) { + const id = crypto.randomUUID(); + return new Promise((resolve, reject) => { + pendingExtensionRequests.set(id, { + resolve: (response) => { + if ("cancelled" in response && response.cancelled) { + resolve(undefined); + } + else if ("value" in response) { + resolve(response.value); + } + else { + resolve(undefined); + } + }, + reject, + }); + output({ type: "extension_ui_request", id, method: "editor", title, prefill }); + }); + }, + addAutocompleteProvider() { + // Autocomplete provider composition is not supported in RPC mode + }, + setEditorComponent() { + // Custom editor components not supported in RPC mode + }, + getEditorComponent() { + // Custom editor components not supported in RPC mode + return undefined; + }, + get theme() { + return theme; + }, + getAllThemes() { + return []; + }, + getTheme(_name) { + return undefined; + }, + setTheme(_theme) { + // Theme switching not supported in RPC mode + return { success: false, error: "Theme switching not supported in RPC mode" }; + }, + getToolsExpanded() { + // Tool expansion not supported in RPC mode - no TUI + return false; + }, + setToolsExpanded(_expanded) { + // Tool expansion not supported in RPC mode - no TUI + }, + }); + runtimeHost.setRebindSession(async () => { + await rebindSession(); + }); + const rebindSession = async () => { + session = runtimeHost.session; + await session.bindExtensions({ + uiContext: createExtensionUIContext(), + mode: "rpc", + commandContextActions: { + waitForIdle: () => session.waitForIdle(), + newSession: async (options) => runtimeHost.newSession(options), + fork: async (entryId, forkOptions) => { + const result = await runtimeHost.fork(entryId, forkOptions); + return { cancelled: result.cancelled }; + }, + navigateTree: async (targetId, options) => { + const result = await session.navigateTree(targetId, { + summarize: options?.summarize, + customInstructions: options?.customInstructions, + replaceInstructions: options?.replaceInstructions, + label: options?.label, + }); + return { cancelled: result.cancelled }; + }, + switchSession: async (sessionPath, options) => { + return runtimeHost.switchSession(sessionPath, options); + }, + reload: async () => { + await session.reload(); + }, + }, + shutdownHandler: () => { + shutdownRequested = true; + }, + onError: (err) => { + output({ type: "extension_error", extensionPath: err.extensionPath, event: err.event, error: err.error }); + }, + }); + unsubscribe?.(); + unsubscribeBackpressure?.(); + unsubscribe = session.subscribe((event) => { + output(event); + if (event.type === "agent_settled") { + void checkShutdownRequested(); + } + }); + unsubscribeBackpressure = session.agent.subscribe(async () => { + await waitForRawStdoutBackpressure(); + }); + }; + const registerSignalHandlers = () => { + const signals = ["SIGTERM"]; + if (process.platform !== "win32") { + signals.push("SIGHUP"); + } + for (const signal of signals) { + const handler = () => { + killTrackedDetachedChildren(); + void shutdown(signal === "SIGHUP" ? 129 : 143, signal); + }; + process.on(signal, handler); + signalCleanupHandlers.push(() => process.off(signal, handler)); + } + }; + await rebindSession(); + registerSignalHandlers(); + // Handle a single command + const handleCommand = async (command) => { + const id = command.id; + switch (command.type) { + // ================================================================= + // Prompting + // ================================================================= + case "prompt": { + // Start prompt handling immediately, but emit the authoritative response only after + // prompt preflight succeeds. Queued and immediately handled prompts also count as success. + let preflightSucceeded = false; + void session + .prompt(command.message, { + images: command.images, + streamingBehavior: command.streamingBehavior, + source: "rpc", + preflightResult: (didSucceed) => { + if (didSucceed) { + preflightSucceeded = true; + output(success(id, "prompt")); + } + }, + }) + .catch((e) => { + if (!preflightSucceeded) { + output(error(id, "prompt", e.message)); + } + }); + return undefined; + } + case "steer": { + await session.steer(command.message, command.images); + return success(id, "steer"); + } + case "follow_up": { + await session.followUp(command.message, command.images); + return success(id, "follow_up"); + } + case "abort": { + await session.abort(); + return success(id, "abort"); + } + case "new_session": { + const options = command.parentSession ? { parentSession: command.parentSession } : undefined; + const result = await runtimeHost.newSession(options); + if (!result.cancelled) { + await rebindSession(); + } + return success(id, "new_session", result); + } + // ================================================================= + // State + // ================================================================= + case "get_state": { + const state = { + model: session.model, + thinkingLevel: session.thinkingLevel, + isStreaming: session.isStreaming, + isCompacting: session.isCompacting, + steeringMode: session.steeringMode, + followUpMode: session.followUpMode, + sessionFile: session.sessionFile, + sessionId: session.sessionId, + sessionName: session.sessionName, + autoCompactionEnabled: session.autoCompactionEnabled, + messageCount: session.messages.length, + pendingMessageCount: session.pendingMessageCount, + }; + return success(id, "get_state", state); + } + // ================================================================= + // Model + // ================================================================= + case "set_model": { + const models = await session.modelRuntime.getAvailable(); + const model = models.find((m) => m.provider === command.provider && m.id === command.modelId); + if (!model) { + return error(id, "set_model", `Model not found: ${command.provider}/${command.modelId}`); + } + await session.setModel(model); + return success(id, "set_model", model); + } + case "cycle_model": { + const result = await session.cycleModel(); + if (!result) { + return success(id, "cycle_model", null); + } + return success(id, "cycle_model", result); + } + case "get_available_models": { + const models = await session.modelRuntime.getAvailable(); + return success(id, "get_available_models", { models }); + } + // ================================================================= + // Thinking + // ================================================================= + case "set_thinking_level": { + session.setThinkingLevel(command.level); + return success(id, "set_thinking_level"); + } + case "cycle_thinking_level": { + const level = session.cycleThinkingLevel(); + if (!level) { + return success(id, "cycle_thinking_level", null); + } + return success(id, "cycle_thinking_level", { level }); + } + case "get_available_thinking_levels": { + const levels = session.getAvailableThinkingLevels(); + return success(id, "get_available_thinking_levels", { levels }); + } + // ================================================================= + // Queue Modes + // ================================================================= + case "set_steering_mode": { + session.setSteeringMode(command.mode); + return success(id, "set_steering_mode"); + } + case "set_follow_up_mode": { + session.setFollowUpMode(command.mode); + return success(id, "set_follow_up_mode"); + } + // ================================================================= + // Compaction + // ================================================================= + case "compact": { + const result = await session.compact(command.customInstructions); + return success(id, "compact", result); + } + case "set_auto_compaction": { + session.setAutoCompactionEnabled(command.enabled); + return success(id, "set_auto_compaction"); + } + // ================================================================= + // Retry + // ================================================================= + case "set_auto_retry": { + session.setAutoRetryEnabled(command.enabled); + return success(id, "set_auto_retry"); + } + case "abort_retry": { + session.abortRetry(); + return success(id, "abort_retry"); + } + // ================================================================= + // Bash + // ================================================================= + case "bash": { + const eventResult = await session.extensionRunner.emitUserBash({ + type: "user_bash", + command: command.command, + excludeFromContext: command.excludeFromContext ?? false, + cwd: session.sessionManager.getCwd(), + }); + if (eventResult?.result) { + session.recordBashResult(command.command, eventResult.result, { + excludeFromContext: command.excludeFromContext, + }); + return success(id, "bash", eventResult.result); + } + const result = await session.executeBash(command.command, undefined, { + excludeFromContext: command.excludeFromContext, + id, + operations: eventResult?.operations, + }); + return success(id, "bash", result); + } + case "abort_bash": { + session.abortBash(); + return success(id, "abort_bash"); + } + // ================================================================= + // Session + // ================================================================= + case "get_session_stats": { + const stats = session.getSessionStats(); + return success(id, "get_session_stats", stats); + } + case "export_html": { + const path = await session.exportToHtml(command.outputPath); + return success(id, "export_html", { path }); + } + case "switch_session": { + const result = await runtimeHost.switchSession(command.sessionPath); + if (!result.cancelled) { + await rebindSession(); + } + return success(id, "switch_session", result); + } + case "fork": { + const result = await runtimeHost.fork(command.entryId); + if (!result.cancelled) { + await rebindSession(); + } + return success(id, "fork", { text: result.selectedText, cancelled: result.cancelled }); + } + case "clone": { + const leafId = session.sessionManager.getLeafId(); + if (!leafId) { + return error(id, "clone", "Cannot clone session: no current entry selected"); + } + const result = await runtimeHost.fork(leafId, { position: "at" }); + if (!result.cancelled) { + await rebindSession(); + } + return success(id, "clone", { cancelled: result.cancelled }); + } + case "get_fork_messages": { + const messages = session.getUserMessagesForForking(); + return success(id, "get_fork_messages", { messages }); + } + case "get_entries": { + const sessionManager = session.sessionManager; + let entries = sessionManager.getEntries(); + if (command.since !== undefined) { + const sinceIndex = entries.findIndex((e) => e.id === command.since); + if (sinceIndex === -1) { + return error(id, "get_entries", `Entry not found: ${command.since}`); + } + entries = entries.slice(sinceIndex + 1); + } + return success(id, "get_entries", { entries, leafId: sessionManager.getLeafId() }); + } + case "get_tree": { + const sessionManager = session.sessionManager; + return success(id, "get_tree", { tree: sessionManager.getTree(), leafId: sessionManager.getLeafId() }); + } + case "get_last_assistant_text": { + const text = session.getLastAssistantText(); + return success(id, "get_last_assistant_text", { text }); + } + case "set_session_name": { + const name = command.name.trim(); + if (!name) { + return error(id, "set_session_name", "Session name cannot be empty"); + } + session.setSessionName(name); + return success(id, "set_session_name"); + } + // ================================================================= + // Messages + // ================================================================= + case "get_messages": { + return success(id, "get_messages", { messages: session.messages }); + } + // ================================================================= + // Commands (available for invocation via prompt) + // ================================================================= + case "get_commands": { + const commands = []; + for (const command of session.extensionRunner.getRegisteredCommands()) { + commands.push({ + name: command.invocationName, + description: command.description, + source: "extension", + sourceInfo: command.sourceInfo, + }); + } + for (const template of session.promptTemplates) { + commands.push({ + name: template.name, + description: template.description, + source: "prompt", + sourceInfo: template.sourceInfo, + }); + } + for (const skill of session.resourceLoader.getSkills().skills) { + commands.push({ + name: `skill:${skill.name}`, + description: skill.description, + source: "skill", + sourceInfo: skill.sourceInfo, + }); + } + return success(id, "get_commands", { commands }); + } + default: { + const unknownCommand = command; + return error(id, unknownCommand.type, `Unknown command: ${unknownCommand.type}`); + } + } + }; + /** + * Check if shutdown was requested and perform shutdown if so. + * Called after handling each command when waiting for the next command. + */ + let detachInput = () => { }; + async function shutdown(exitCode = 0, signal) { + if (shuttingDown) { + process.exit(exitCode); + } + shuttingDown = true; + for (const cleanup of signalCleanupHandlers) { + cleanup(); + } + unsubscribe?.(); + unsubscribeBackpressure?.(); + await runtimeHost.dispose(); + detachInput(); + process.stdin.pause(); + if (signal !== "SIGTERM") { + await flushRawStdout(); + } + process.exit(exitCode); + } + async function checkShutdownRequested() { + if (!shutdownRequested) + return; + await shutdown(); + } + const handleInputLine = async (line) => { + let parsed; + try { + parsed = JSON.parse(line); + } + catch (parseError) { + output(error(undefined, "parse", `Failed to parse command: ${parseError instanceof Error ? parseError.message : String(parseError)}`)); + await waitForRawStdoutBackpressure(); + return; + } + // Handle extension UI responses + if (typeof parsed === "object" && + parsed !== null && + "type" in parsed && + parsed.type === "extension_ui_response") { + const response = parsed; + const pending = pendingExtensionRequests.get(response.id); + if (pending) { + pendingExtensionRequests.delete(response.id); + pending.resolve(response); + } + return; + } + const command = parsed; + try { + const response = await handleCommand(command); + if (response) { + output(response); + await waitForRawStdoutBackpressure(); + } + await checkShutdownRequested(); + } + catch (commandError) { + output(error(command.id, command.type, commandError instanceof Error ? commandError.message : String(commandError))); + await waitForRawStdoutBackpressure(); + } + }; + const onInputEnd = () => { + void shutdown(); + }; + process.stdin.on("end", onInputEnd); + detachInput = (() => { + const detachJsonl = attachJsonlLineReader(process.stdin, (line) => { + void handleInputLine(line); + }); + return () => { + detachJsonl(); + process.stdin.off("end", onInputEnd); + }; + })(); + // Keep process alive forever + return new Promise(() => { }); +} +//# sourceMappingURL=rpc-mode.js.map \ No newline at end of file diff --git a/dist/modes/rpc/rpc-mode.js.map b/dist/modes/rpc/rpc-mode.js.map new file mode 100644 index 0000000..e5d21a6 --- /dev/null +++ b/dist/modes/rpc/rpc-mode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc-mode.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-mode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AAQtC,OAAO,EACN,cAAc,EACd,cAAc,EACd,4BAA4B,EAC5B,cAAc,GACd,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,2BAA2B,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAc,KAAK,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAmBtE;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,WAAgC,EAAkB;IAClF,cAAc,EAAE,CAAC;IACjB,IAAI,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC;IAClC,IAAI,WAAqC,CAAC;IAC1C,IAAI,uBAAiD,CAAC;IAEtD,MAAM,MAAM,GAAG,CAAC,GAAiD,EAAE,EAAE,CAAC;QACrE,cAAc,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAC;IAAA,CACvC,CAAC;IAEF,MAAM,OAAO,GAAG,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AAC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC;YAClE,KAAK,eAAe,CAAC,IAAI,CAAC,CAAC;QAAA,CAC3B,CAAC,CAAC;QACH,OAAO,GAAG,EAAE,CAAC;YACZ,WAAW,EAAE,CAAC;YACd,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;QAAA,CACrC,CAAC;IAAA,CACF,CAAC,EAAE,CAAC;IAEL,6BAA6B;IAC7B,OAAO,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC,EAAC,CAAC,CAAC,CAAC;AAAA,CAC7B","sourcesContent":["/**\n * RPC mode: Headless operation with JSON stdin/stdout protocol.\n *\n * Used for embedding the agent in other applications.\n * Receives commands as JSON on stdin, outputs events and responses as JSON on stdout.\n *\n * Protocol:\n * - Commands: JSON objects with `type` field, optional `id` for correlation\n * - Responses: JSON objects with `type: \"response\"`, `command`, `success`, and optional `data`/`error`\n * - Events: AgentSessionEvent objects streamed as they occur\n * - Extension UI: Extension UI requests are emitted, client responds with extension_ui_response\n */\n\nimport * as crypto from \"node:crypto\";\nimport type { AgentSessionRuntime } from \"../../core/agent-session-runtime.ts\";\nimport type {\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tWorkingIndicatorOptions,\n} from \"../../core/extensions/index.ts\";\nimport {\n\tflushRawStdout,\n\ttakeOverStdout,\n\twaitForRawStdoutBackpressure,\n\twriteRawStdout,\n} from \"../../core/output-guard.ts\";\nimport { killTrackedDetachedChildren } from \"../../utils/shell.ts\";\nimport { type Theme, theme } from \"../interactive/theme/theme.ts\";\nimport { attachJsonlLineReader, serializeJsonLine } from \"./jsonl.ts\";\nimport type {\n\tRpcCommand,\n\tRpcExtensionUIRequest,\n\tRpcExtensionUIResponse,\n\tRpcResponse,\n\tRpcSessionState,\n\tRpcSlashCommand,\n} from \"./rpc-types.ts\";\n\n// Re-export types for consumers\nexport type {\n\tRpcCommand,\n\tRpcExtensionUIRequest,\n\tRpcExtensionUIResponse,\n\tRpcResponse,\n\tRpcSessionState,\n} from \"./rpc-types.ts\";\n\n/**\n * Run in RPC mode.\n * Listens for JSON commands on stdin, outputs events and responses on stdout.\n */\nexport async function runRpcMode(runtimeHost: AgentSessionRuntime): Promise {\n\ttakeOverStdout();\n\tlet session = runtimeHost.session;\n\tlet unsubscribe: (() => void) | undefined;\n\tlet unsubscribeBackpressure: (() => void) | undefined;\n\n\tconst output = (obj: RpcResponse | RpcExtensionUIRequest | object) => {\n\t\twriteRawStdout(serializeJsonLine(obj));\n\t};\n\n\tconst success = (\n\t\tid: string | undefined,\n\t\tcommand: T,\n\t\tdata?: object | null,\n\t): RpcResponse => {\n\t\tif (data === undefined) {\n\t\t\treturn { id, type: \"response\", command, success: true } as RpcResponse;\n\t\t}\n\t\treturn { id, type: \"response\", command, success: true, data } as RpcResponse;\n\t};\n\n\tconst error = (id: string | undefined, command: string, message: string): RpcResponse => {\n\t\treturn { id, type: \"response\", command, success: false, error: message };\n\t};\n\n\t// Pending extension UI requests waiting for response\n\tconst pendingExtensionRequests = new Map<\n\t\tstring,\n\t\t{ resolve: (value: any) => void; reject: (error: Error) => void }\n\t>();\n\n\t// Shutdown request flag\n\tlet shutdownRequested = false;\n\tlet shuttingDown = false;\n\tconst signalCleanupHandlers: Array<() => void> = [];\n\n\t/** Helper for dialog methods with signal/timeout support */\n\tfunction createDialogPromise(\n\t\topts: ExtensionUIDialogOptions | undefined,\n\t\tdefaultValue: T,\n\t\trequest: Record,\n\t\tparseResponse: (response: RpcExtensionUIResponse) => T,\n\t): Promise {\n\t\tif (opts?.signal?.aborted) return Promise.resolve(defaultValue);\n\n\t\tconst id = crypto.randomUUID();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet timeoutId: ReturnType | undefined;\n\n\t\t\tconst cleanup = () => {\n\t\t\t\tif (timeoutId) clearTimeout(timeoutId);\n\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tpendingExtensionRequests.delete(id);\n\t\t\t};\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(defaultValue);\n\t\t\t};\n\t\t\topts?.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\tif (opts?.timeout) {\n\t\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(defaultValue);\n\t\t\t\t}, opts.timeout);\n\t\t\t}\n\n\t\t\tpendingExtensionRequests.set(id, {\n\t\t\t\tresolve: (response: RpcExtensionUIResponse) => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(parseResponse(response));\n\t\t\t\t},\n\t\t\t\treject,\n\t\t\t});\n\t\t\toutput({ type: \"extension_ui_request\", id, ...request } as RpcExtensionUIRequest);\n\t\t});\n\t}\n\n\t/**\n\t * Create an extension UI context that uses the RPC protocol.\n\t */\n\tconst createExtensionUIContext = (): ExtensionUIContext => ({\n\t\tselect: (title, options, opts) =>\n\t\t\tcreateDialogPromise(opts, undefined, { method: \"select\", title, options, timeout: opts?.timeout }, (r) =>\n\t\t\t\t\"cancelled\" in r && r.cancelled ? undefined : \"value\" in r ? r.value : undefined,\n\t\t\t),\n\n\t\tconfirm: (title, message, opts) =>\n\t\t\tcreateDialogPromise(opts, false, { method: \"confirm\", title, message, timeout: opts?.timeout }, (r) =>\n\t\t\t\t\"cancelled\" in r && r.cancelled ? false : \"confirmed\" in r ? r.confirmed : false,\n\t\t\t),\n\n\t\tinput: (title, placeholder, opts) =>\n\t\t\tcreateDialogPromise(opts, undefined, { method: \"input\", title, placeholder, timeout: opts?.timeout }, (r) =>\n\t\t\t\t\"cancelled\" in r && r.cancelled ? undefined : \"value\" in r ? r.value : undefined,\n\t\t\t),\n\n\t\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void {\n\t\t\t// Fire and forget - no response needed\n\t\t\toutput({\n\t\t\t\ttype: \"extension_ui_request\",\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\tmethod: \"notify\",\n\t\t\t\tmessage,\n\t\t\t\tnotifyType: type,\n\t\t\t} as RpcExtensionUIRequest);\n\t\t},\n\n\t\tonTerminalInput(): () => void {\n\t\t\t// Raw terminal input not supported in RPC mode\n\t\t\treturn () => {};\n\t\t},\n\n\t\tsetStatus(key: string, text: string | undefined): void {\n\t\t\t// Fire and forget - no response needed\n\t\t\toutput({\n\t\t\t\ttype: \"extension_ui_request\",\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\tmethod: \"setStatus\",\n\t\t\t\tstatusKey: key,\n\t\t\t\tstatusText: text,\n\t\t\t} as RpcExtensionUIRequest);\n\t\t},\n\n\t\tsetWorkingMessage(_message?: string): void {\n\t\t\t// Working message not supported in RPC mode - requires TUI loader access\n\t\t},\n\n\t\tsetWorkingVisible(_visible: boolean): void {\n\t\t\t// Working visibility not supported in RPC mode - requires TUI loader access\n\t\t},\n\n\t\tsetWorkingIndicator(_options?: WorkingIndicatorOptions): void {\n\t\t\t// Working indicator customization not supported in RPC mode - requires TUI loader access\n\t\t},\n\n\t\tsetHiddenThinkingLabel(_label?: string): void {\n\t\t\t// Hidden thinking label not supported in RPC mode - requires TUI message rendering access\n\t\t},\n\n\t\tsetWidget(key: string, content: unknown, options?: ExtensionWidgetOptions): void {\n\t\t\t// Only support string arrays in RPC mode - factory functions are ignored\n\t\t\tif (content === undefined || Array.isArray(content)) {\n\t\t\t\toutput({\n\t\t\t\t\ttype: \"extension_ui_request\",\n\t\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\t\tmethod: \"setWidget\",\n\t\t\t\t\twidgetKey: key,\n\t\t\t\t\twidgetLines: content as string[] | undefined,\n\t\t\t\t\twidgetPlacement: options?.placement,\n\t\t\t\t} as RpcExtensionUIRequest);\n\t\t\t}\n\t\t\t// Component factories are not supported in RPC mode - would need TUI access\n\t\t},\n\n\t\tsetFooter(_factory: unknown): void {\n\t\t\t// Custom footer not supported in RPC mode - requires TUI access\n\t\t},\n\n\t\tsetHeader(_factory: unknown): void {\n\t\t\t// Custom header not supported in RPC mode - requires TUI access\n\t\t},\n\n\t\tsetTitle(title: string): void {\n\t\t\t// Fire and forget - host can implement terminal title control\n\t\t\toutput({\n\t\t\t\ttype: \"extension_ui_request\",\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\tmethod: \"setTitle\",\n\t\t\t\ttitle,\n\t\t\t} as RpcExtensionUIRequest);\n\t\t},\n\n\t\tasync custom() {\n\t\t\t// Custom UI not supported in RPC mode\n\t\t\treturn undefined as never;\n\t\t},\n\n\t\tpasteToEditor(text: string): void {\n\t\t\t// Paste handling not supported in RPC mode - falls back to setEditorText\n\t\t\tthis.setEditorText(text);\n\t\t},\n\n\t\tsetEditorText(text: string): void {\n\t\t\t// Fire and forget - host can implement editor control\n\t\t\toutput({\n\t\t\t\ttype: \"extension_ui_request\",\n\t\t\t\tid: crypto.randomUUID(),\n\t\t\t\tmethod: \"set_editor_text\",\n\t\t\t\ttext,\n\t\t\t} as RpcExtensionUIRequest);\n\t\t},\n\n\t\tgetEditorText(): string {\n\t\t\t// Synchronous method can't wait for RPC response\n\t\t\t// Host should track editor state locally if needed\n\t\t\treturn \"\";\n\t\t},\n\n\t\tasync editor(title: string, prefill?: string): Promise {\n\t\t\tconst id = crypto.randomUUID();\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tpendingExtensionRequests.set(id, {\n\t\t\t\t\tresolve: (response: RpcExtensionUIResponse) => {\n\t\t\t\t\t\tif (\"cancelled\" in response && response.cancelled) {\n\t\t\t\t\t\t\tresolve(undefined);\n\t\t\t\t\t\t} else if (\"value\" in response) {\n\t\t\t\t\t\t\tresolve(response.value);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresolve(undefined);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\treject,\n\t\t\t\t});\n\t\t\t\toutput({ type: \"extension_ui_request\", id, method: \"editor\", title, prefill } as RpcExtensionUIRequest);\n\t\t\t});\n\t\t},\n\n\t\taddAutocompleteProvider(): void {\n\t\t\t// Autocomplete provider composition is not supported in RPC mode\n\t\t},\n\n\t\tsetEditorComponent(): void {\n\t\t\t// Custom editor components not supported in RPC mode\n\t\t},\n\n\t\tgetEditorComponent() {\n\t\t\t// Custom editor components not supported in RPC mode\n\t\t\treturn undefined;\n\t\t},\n\n\t\tget theme() {\n\t\t\treturn theme;\n\t\t},\n\n\t\tgetAllThemes() {\n\t\t\treturn [];\n\t\t},\n\n\t\tgetTheme(_name: string) {\n\t\t\treturn undefined;\n\t\t},\n\n\t\tsetTheme(_theme: string | Theme) {\n\t\t\t// Theme switching not supported in RPC mode\n\t\t\treturn { success: false, error: \"Theme switching not supported in RPC mode\" };\n\t\t},\n\n\t\tgetToolsExpanded() {\n\t\t\t// Tool expansion not supported in RPC mode - no TUI\n\t\t\treturn false;\n\t\t},\n\n\t\tsetToolsExpanded(_expanded: boolean) {\n\t\t\t// Tool expansion not supported in RPC mode - no TUI\n\t\t},\n\t});\n\n\truntimeHost.setRebindSession(async () => {\n\t\tawait rebindSession();\n\t});\n\n\tconst rebindSession = async (): Promise => {\n\t\tsession = runtimeHost.session;\n\t\tawait session.bindExtensions({\n\t\t\tuiContext: createExtensionUIContext(),\n\t\t\tmode: \"rpc\",\n\t\t\tcommandContextActions: {\n\t\t\t\twaitForIdle: () => session.waitForIdle(),\n\t\t\t\tnewSession: async (options) => runtimeHost.newSession(options),\n\t\t\t\tfork: async (entryId, forkOptions) => {\n\t\t\t\t\tconst result = await runtimeHost.fork(entryId, forkOptions);\n\t\t\t\t\treturn { cancelled: result.cancelled };\n\t\t\t\t},\n\t\t\t\tnavigateTree: async (targetId, options) => {\n\t\t\t\t\tconst result = await session.navigateTree(targetId, {\n\t\t\t\t\t\tsummarize: options?.summarize,\n\t\t\t\t\t\tcustomInstructions: options?.customInstructions,\n\t\t\t\t\t\treplaceInstructions: options?.replaceInstructions,\n\t\t\t\t\t\tlabel: options?.label,\n\t\t\t\t\t});\n\t\t\t\t\treturn { cancelled: result.cancelled };\n\t\t\t\t},\n\t\t\t\tswitchSession: async (sessionPath, options) => {\n\t\t\t\t\treturn runtimeHost.switchSession(sessionPath, options);\n\t\t\t\t},\n\t\t\t\treload: async () => {\n\t\t\t\t\tawait session.reload();\n\t\t\t\t},\n\t\t\t},\n\t\t\tshutdownHandler: () => {\n\t\t\t\tshutdownRequested = true;\n\t\t\t},\n\t\t\tonError: (err) => {\n\t\t\t\toutput({ type: \"extension_error\", extensionPath: err.extensionPath, event: err.event, error: err.error });\n\t\t\t},\n\t\t});\n\n\t\tunsubscribe?.();\n\t\tunsubscribeBackpressure?.();\n\t\tunsubscribe = session.subscribe((event) => {\n\t\t\toutput(event);\n\t\t\tif (event.type === \"agent_settled\") {\n\t\t\t\tvoid checkShutdownRequested();\n\t\t\t}\n\t\t});\n\t\tunsubscribeBackpressure = session.agent.subscribe(async () => {\n\t\t\tawait waitForRawStdoutBackpressure();\n\t\t});\n\t};\n\n\tconst registerSignalHandlers = (): void => {\n\t\tconst signals: NodeJS.Signals[] = [\"SIGTERM\"];\n\t\tif (process.platform !== \"win32\") {\n\t\t\tsignals.push(\"SIGHUP\");\n\t\t}\n\n\t\tfor (const signal of signals) {\n\t\t\tconst handler = () => {\n\t\t\t\tkillTrackedDetachedChildren();\n\t\t\t\tvoid shutdown(signal === \"SIGHUP\" ? 129 : 143, signal);\n\t\t\t};\n\t\t\tprocess.on(signal, handler);\n\t\t\tsignalCleanupHandlers.push(() => process.off(signal, handler));\n\t\t}\n\t};\n\n\tawait rebindSession();\n\tregisterSignalHandlers();\n\n\t// Handle a single command\n\tconst handleCommand = async (command: RpcCommand): Promise => {\n\t\tconst id = command.id;\n\n\t\tswitch (command.type) {\n\t\t\t// =================================================================\n\t\t\t// Prompting\n\t\t\t// =================================================================\n\n\t\t\tcase \"prompt\": {\n\t\t\t\t// Start prompt handling immediately, but emit the authoritative response only after\n\t\t\t\t// prompt preflight succeeds. Queued and immediately handled prompts also count as success.\n\t\t\t\tlet preflightSucceeded = false;\n\t\t\t\tvoid session\n\t\t\t\t\t.prompt(command.message, {\n\t\t\t\t\t\timages: command.images,\n\t\t\t\t\t\tstreamingBehavior: command.streamingBehavior,\n\t\t\t\t\t\tsource: \"rpc\",\n\t\t\t\t\t\tpreflightResult: (didSucceed) => {\n\t\t\t\t\t\t\tif (didSucceed) {\n\t\t\t\t\t\t\t\tpreflightSucceeded = true;\n\t\t\t\t\t\t\t\toutput(success(id, \"prompt\"));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t\t.catch((e) => {\n\t\t\t\t\t\tif (!preflightSucceeded) {\n\t\t\t\t\t\t\toutput(error(id, \"prompt\", e.message));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\tcase \"steer\": {\n\t\t\t\tawait session.steer(command.message, command.images);\n\t\t\t\treturn success(id, \"steer\");\n\t\t\t}\n\n\t\t\tcase \"follow_up\": {\n\t\t\t\tawait session.followUp(command.message, command.images);\n\t\t\t\treturn success(id, \"follow_up\");\n\t\t\t}\n\n\t\t\tcase \"abort\": {\n\t\t\t\tawait session.abort();\n\t\t\t\treturn success(id, \"abort\");\n\t\t\t}\n\n\t\t\tcase \"new_session\": {\n\t\t\t\tconst options = command.parentSession ? { parentSession: command.parentSession } : undefined;\n\t\t\t\tconst result = await runtimeHost.newSession(options);\n\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\tawait rebindSession();\n\t\t\t\t}\n\t\t\t\treturn success(id, \"new_session\", result);\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// State\n\t\t\t// =================================================================\n\n\t\t\tcase \"get_state\": {\n\t\t\t\tconst state: RpcSessionState = {\n\t\t\t\t\tmodel: session.model,\n\t\t\t\t\tthinkingLevel: session.thinkingLevel,\n\t\t\t\t\tisStreaming: session.isStreaming,\n\t\t\t\t\tisCompacting: session.isCompacting,\n\t\t\t\t\tsteeringMode: session.steeringMode,\n\t\t\t\t\tfollowUpMode: session.followUpMode,\n\t\t\t\t\tsessionFile: session.sessionFile,\n\t\t\t\t\tsessionId: session.sessionId,\n\t\t\t\t\tsessionName: session.sessionName,\n\t\t\t\t\tautoCompactionEnabled: session.autoCompactionEnabled,\n\t\t\t\t\tmessageCount: session.messages.length,\n\t\t\t\t\tpendingMessageCount: session.pendingMessageCount,\n\t\t\t\t};\n\t\t\t\treturn success(id, \"get_state\", state);\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Model\n\t\t\t// =================================================================\n\n\t\t\tcase \"set_model\": {\n\t\t\t\tconst models = await session.modelRuntime.getAvailable();\n\t\t\t\tconst model = models.find((m) => m.provider === command.provider && m.id === command.modelId);\n\t\t\t\tif (!model) {\n\t\t\t\t\treturn error(id, \"set_model\", `Model not found: ${command.provider}/${command.modelId}`);\n\t\t\t\t}\n\t\t\t\tawait session.setModel(model);\n\t\t\t\treturn success(id, \"set_model\", model);\n\t\t\t}\n\n\t\t\tcase \"cycle_model\": {\n\t\t\t\tconst result = await session.cycleModel();\n\t\t\t\tif (!result) {\n\t\t\t\t\treturn success(id, \"cycle_model\", null);\n\t\t\t\t}\n\t\t\t\treturn success(id, \"cycle_model\", result);\n\t\t\t}\n\n\t\t\tcase \"get_available_models\": {\n\t\t\t\tconst models = await session.modelRuntime.getAvailable();\n\t\t\t\treturn success(id, \"get_available_models\", { models });\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Thinking\n\t\t\t// =================================================================\n\n\t\t\tcase \"set_thinking_level\": {\n\t\t\t\tsession.setThinkingLevel(command.level);\n\t\t\t\treturn success(id, \"set_thinking_level\");\n\t\t\t}\n\n\t\t\tcase \"cycle_thinking_level\": {\n\t\t\t\tconst level = session.cycleThinkingLevel();\n\t\t\t\tif (!level) {\n\t\t\t\t\treturn success(id, \"cycle_thinking_level\", null);\n\t\t\t\t}\n\t\t\t\treturn success(id, \"cycle_thinking_level\", { level });\n\t\t\t}\n\n\t\t\tcase \"get_available_thinking_levels\": {\n\t\t\t\tconst levels = session.getAvailableThinkingLevels();\n\t\t\t\treturn success(id, \"get_available_thinking_levels\", { levels });\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Queue Modes\n\t\t\t// =================================================================\n\n\t\t\tcase \"set_steering_mode\": {\n\t\t\t\tsession.setSteeringMode(command.mode);\n\t\t\t\treturn success(id, \"set_steering_mode\");\n\t\t\t}\n\n\t\t\tcase \"set_follow_up_mode\": {\n\t\t\t\tsession.setFollowUpMode(command.mode);\n\t\t\t\treturn success(id, \"set_follow_up_mode\");\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Compaction\n\t\t\t// =================================================================\n\n\t\t\tcase \"compact\": {\n\t\t\t\tconst result = await session.compact(command.customInstructions);\n\t\t\t\treturn success(id, \"compact\", result);\n\t\t\t}\n\n\t\t\tcase \"set_auto_compaction\": {\n\t\t\t\tsession.setAutoCompactionEnabled(command.enabled);\n\t\t\t\treturn success(id, \"set_auto_compaction\");\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Retry\n\t\t\t// =================================================================\n\n\t\t\tcase \"set_auto_retry\": {\n\t\t\t\tsession.setAutoRetryEnabled(command.enabled);\n\t\t\t\treturn success(id, \"set_auto_retry\");\n\t\t\t}\n\n\t\t\tcase \"abort_retry\": {\n\t\t\t\tsession.abortRetry();\n\t\t\t\treturn success(id, \"abort_retry\");\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Bash\n\t\t\t// =================================================================\n\n\t\t\tcase \"bash\": {\n\t\t\t\tconst eventResult = await session.extensionRunner.emitUserBash({\n\t\t\t\t\ttype: \"user_bash\",\n\t\t\t\t\tcommand: command.command,\n\t\t\t\t\texcludeFromContext: command.excludeFromContext ?? false,\n\t\t\t\t\tcwd: session.sessionManager.getCwd(),\n\t\t\t\t});\n\n\t\t\t\tif (eventResult?.result) {\n\t\t\t\t\tsession.recordBashResult(command.command, eventResult.result, {\n\t\t\t\t\t\texcludeFromContext: command.excludeFromContext,\n\t\t\t\t\t});\n\t\t\t\t\treturn success(id, \"bash\", eventResult.result);\n\t\t\t\t}\n\n\t\t\t\tconst result = await session.executeBash(command.command, undefined, {\n\t\t\t\t\texcludeFromContext: command.excludeFromContext,\n\t\t\t\t\tid,\n\t\t\t\t\toperations: eventResult?.operations,\n\t\t\t\t});\n\t\t\t\treturn success(id, \"bash\", result);\n\t\t\t}\n\n\t\t\tcase \"abort_bash\": {\n\t\t\t\tsession.abortBash();\n\t\t\t\treturn success(id, \"abort_bash\");\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Session\n\t\t\t// =================================================================\n\n\t\t\tcase \"get_session_stats\": {\n\t\t\t\tconst stats = session.getSessionStats();\n\t\t\t\treturn success(id, \"get_session_stats\", stats);\n\t\t\t}\n\n\t\t\tcase \"export_html\": {\n\t\t\t\tconst path = await session.exportToHtml(command.outputPath);\n\t\t\t\treturn success(id, \"export_html\", { path });\n\t\t\t}\n\n\t\t\tcase \"switch_session\": {\n\t\t\t\tconst result = await runtimeHost.switchSession(command.sessionPath);\n\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\tawait rebindSession();\n\t\t\t\t}\n\t\t\t\treturn success(id, \"switch_session\", result);\n\t\t\t}\n\n\t\t\tcase \"fork\": {\n\t\t\t\tconst result = await runtimeHost.fork(command.entryId);\n\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\tawait rebindSession();\n\t\t\t\t}\n\t\t\t\treturn success(id, \"fork\", { text: result.selectedText, cancelled: result.cancelled });\n\t\t\t}\n\n\t\t\tcase \"clone\": {\n\t\t\t\tconst leafId = session.sessionManager.getLeafId();\n\t\t\t\tif (!leafId) {\n\t\t\t\t\treturn error(id, \"clone\", \"Cannot clone session: no current entry selected\");\n\t\t\t\t}\n\t\t\t\tconst result = await runtimeHost.fork(leafId, { position: \"at\" });\n\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\tawait rebindSession();\n\t\t\t\t}\n\t\t\t\treturn success(id, \"clone\", { cancelled: result.cancelled });\n\t\t\t}\n\n\t\t\tcase \"get_fork_messages\": {\n\t\t\t\tconst messages = session.getUserMessagesForForking();\n\t\t\t\treturn success(id, \"get_fork_messages\", { messages });\n\t\t\t}\n\n\t\t\tcase \"get_entries\": {\n\t\t\t\tconst sessionManager = session.sessionManager;\n\t\t\t\tlet entries = sessionManager.getEntries();\n\t\t\t\tif (command.since !== undefined) {\n\t\t\t\t\tconst sinceIndex = entries.findIndex((e) => e.id === command.since);\n\t\t\t\t\tif (sinceIndex === -1) {\n\t\t\t\t\t\treturn error(id, \"get_entries\", `Entry not found: ${command.since}`);\n\t\t\t\t\t}\n\t\t\t\t\tentries = entries.slice(sinceIndex + 1);\n\t\t\t\t}\n\t\t\t\treturn success(id, \"get_entries\", { entries, leafId: sessionManager.getLeafId() });\n\t\t\t}\n\n\t\t\tcase \"get_tree\": {\n\t\t\t\tconst sessionManager = session.sessionManager;\n\t\t\t\treturn success(id, \"get_tree\", { tree: sessionManager.getTree(), leafId: sessionManager.getLeafId() });\n\t\t\t}\n\n\t\t\tcase \"get_last_assistant_text\": {\n\t\t\t\tconst text = session.getLastAssistantText();\n\t\t\t\treturn success(id, \"get_last_assistant_text\", { text });\n\t\t\t}\n\n\t\t\tcase \"set_session_name\": {\n\t\t\t\tconst name = command.name.trim();\n\t\t\t\tif (!name) {\n\t\t\t\t\treturn error(id, \"set_session_name\", \"Session name cannot be empty\");\n\t\t\t\t}\n\t\t\t\tsession.setSessionName(name);\n\t\t\t\treturn success(id, \"set_session_name\");\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Messages\n\t\t\t// =================================================================\n\n\t\t\tcase \"get_messages\": {\n\t\t\t\treturn success(id, \"get_messages\", { messages: session.messages });\n\t\t\t}\n\n\t\t\t// =================================================================\n\t\t\t// Commands (available for invocation via prompt)\n\t\t\t// =================================================================\n\n\t\t\tcase \"get_commands\": {\n\t\t\t\tconst commands: RpcSlashCommand[] = [];\n\n\t\t\t\tfor (const command of session.extensionRunner.getRegisteredCommands()) {\n\t\t\t\t\tcommands.push({\n\t\t\t\t\t\tname: command.invocationName,\n\t\t\t\t\t\tdescription: command.description,\n\t\t\t\t\t\tsource: \"extension\",\n\t\t\t\t\t\tsourceInfo: command.sourceInfo,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tfor (const template of session.promptTemplates) {\n\t\t\t\t\tcommands.push({\n\t\t\t\t\t\tname: template.name,\n\t\t\t\t\t\tdescription: template.description,\n\t\t\t\t\t\tsource: \"prompt\",\n\t\t\t\t\t\tsourceInfo: template.sourceInfo,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tfor (const skill of session.resourceLoader.getSkills().skills) {\n\t\t\t\t\tcommands.push({\n\t\t\t\t\t\tname: `skill:${skill.name}`,\n\t\t\t\t\t\tdescription: skill.description,\n\t\t\t\t\t\tsource: \"skill\",\n\t\t\t\t\t\tsourceInfo: skill.sourceInfo,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn success(id, \"get_commands\", { commands });\n\t\t\t}\n\n\t\t\tdefault: {\n\t\t\t\tconst unknownCommand = command as { type: string };\n\t\t\t\treturn error(id, unknownCommand.type, `Unknown command: ${unknownCommand.type}`);\n\t\t\t}\n\t\t}\n\t};\n\n\t/**\n\t * Check if shutdown was requested and perform shutdown if so.\n\t * Called after handling each command when waiting for the next command.\n\t */\n\tlet detachInput = () => {};\n\n\tasync function shutdown(exitCode = 0, signal?: NodeJS.Signals): Promise {\n\t\tif (shuttingDown) {\n\t\t\tprocess.exit(exitCode);\n\t\t}\n\t\tshuttingDown = true;\n\t\tfor (const cleanup of signalCleanupHandlers) {\n\t\t\tcleanup();\n\t\t}\n\t\tunsubscribe?.();\n\t\tunsubscribeBackpressure?.();\n\t\tawait runtimeHost.dispose();\n\t\tdetachInput();\n\t\tprocess.stdin.pause();\n\t\tif (signal !== \"SIGTERM\") {\n\t\t\tawait flushRawStdout();\n\t\t}\n\t\tprocess.exit(exitCode);\n\t}\n\n\tasync function checkShutdownRequested(): Promise {\n\t\tif (!shutdownRequested) return;\n\t\tawait shutdown();\n\t}\n\n\tconst handleInputLine = async (line: string) => {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(line);\n\t\t} catch (parseError: unknown) {\n\t\t\toutput(\n\t\t\t\terror(\n\t\t\t\t\tundefined,\n\t\t\t\t\t\"parse\",\n\t\t\t\t\t`Failed to parse command: ${parseError instanceof Error ? parseError.message : String(parseError)}`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tawait waitForRawStdoutBackpressure();\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle extension UI responses\n\t\tif (\n\t\t\ttypeof parsed === \"object\" &&\n\t\t\tparsed !== null &&\n\t\t\t\"type\" in parsed &&\n\t\t\tparsed.type === \"extension_ui_response\"\n\t\t) {\n\t\t\tconst response = parsed as RpcExtensionUIResponse;\n\t\t\tconst pending = pendingExtensionRequests.get(response.id);\n\t\t\tif (pending) {\n\t\t\t\tpendingExtensionRequests.delete(response.id);\n\t\t\t\tpending.resolve(response);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst command = parsed as RpcCommand;\n\t\ttry {\n\t\t\tconst response = await handleCommand(command);\n\t\t\tif (response) {\n\t\t\t\toutput(response);\n\t\t\t\tawait waitForRawStdoutBackpressure();\n\t\t\t}\n\t\t\tawait checkShutdownRequested();\n\t\t} catch (commandError: unknown) {\n\t\t\toutput(\n\t\t\t\terror(\n\t\t\t\t\tcommand.id,\n\t\t\t\t\tcommand.type,\n\t\t\t\t\tcommandError instanceof Error ? commandError.message : String(commandError),\n\t\t\t\t),\n\t\t\t);\n\t\t\tawait waitForRawStdoutBackpressure();\n\t\t}\n\t};\n\n\tconst onInputEnd = () => {\n\t\tvoid shutdown();\n\t};\n\tprocess.stdin.on(\"end\", onInputEnd);\n\n\tdetachInput = (() => {\n\t\tconst detachJsonl = attachJsonlLineReader(process.stdin, (line) => {\n\t\t\tvoid handleInputLine(line);\n\t\t});\n\t\treturn () => {\n\t\t\tdetachJsonl();\n\t\t\tprocess.stdin.off(\"end\", onInputEnd);\n\t\t};\n\t})();\n\n\t// Keep process alive forever\n\treturn new Promise(() => {});\n}\n"]} \ No newline at end of file diff --git a/dist/modes/rpc/rpc-types.d.ts b/dist/modes/rpc/rpc-types.d.ts new file mode 100644 index 0000000..b772bc7 --- /dev/null +++ b/dist/modes/rpc/rpc-types.d.ts @@ -0,0 +1,457 @@ +/** + * RPC protocol types for headless operation. + * + * Commands are sent as JSON lines on stdin. + * Responses and events are emitted as JSON lines on stdout. + */ +import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core"; +import type { ImageContent, Model } from "@earendil-works/pi-ai"; +import type { SessionStats } from "../../core/agent-session.ts"; +import type { BashResult } from "../../core/bash-executor.ts"; +import type { CompactionResult } from "../../core/compaction/index.ts"; +import type { SessionEntry, SessionTreeNode } from "../../core/session-manager.ts"; +import type { SourceInfo } from "../../core/source-info.ts"; +export type RpcCommand = { + id?: string; + type: "prompt"; + message: string; + images?: ImageContent[]; + streamingBehavior?: "steer" | "followUp"; +} | { + id?: string; + type: "steer"; + message: string; + images?: ImageContent[]; +} | { + id?: string; + type: "follow_up"; + message: string; + images?: ImageContent[]; +} | { + id?: string; + type: "abort"; +} | { + id?: string; + type: "new_session"; + parentSession?: string; +} | { + id?: string; + type: "get_state"; +} | { + id?: string; + type: "set_model"; + provider: string; + modelId: string; +} | { + id?: string; + type: "cycle_model"; +} | { + id?: string; + type: "get_available_models"; +} | { + id?: string; + type: "set_thinking_level"; + level: ThinkingLevel; +} | { + id?: string; + type: "cycle_thinking_level"; +} | { + id?: string; + type: "get_available_thinking_levels"; +} | { + id?: string; + type: "set_steering_mode"; + mode: "all" | "one-at-a-time"; +} | { + id?: string; + type: "set_follow_up_mode"; + mode: "all" | "one-at-a-time"; +} | { + id?: string; + type: "compact"; + customInstructions?: string; +} | { + id?: string; + type: "set_auto_compaction"; + enabled: boolean; +} | { + id?: string; + type: "set_auto_retry"; + enabled: boolean; +} | { + id?: string; + type: "abort_retry"; +} | { + id?: string; + type: "bash"; + command: string; + excludeFromContext?: boolean; +} | { + id?: string; + type: "abort_bash"; +} | { + id?: string; + type: "get_session_stats"; +} | { + id?: string; + type: "export_html"; + outputPath?: string; +} | { + id?: string; + type: "switch_session"; + sessionPath: string; +} | { + id?: string; + type: "fork"; + entryId: string; +} | { + id?: string; + type: "clone"; +} | { + id?: string; + type: "get_fork_messages"; +} | { + id?: string; + type: "get_entries"; + since?: string; +} | { + id?: string; + type: "get_tree"; +} | { + id?: string; + type: "get_last_assistant_text"; +} | { + id?: string; + type: "set_session_name"; + name: string; +} | { + id?: string; + type: "get_messages"; +} | { + id?: string; + type: "get_commands"; +}; +/** A command available for invocation via prompt */ +export interface RpcSlashCommand { + /** Command name (without leading slash) */ + name: string; + /** Human-readable description */ + description?: string; + /** What kind of command this is */ + source: "extension" | "prompt" | "skill"; + /** Source metadata for the owning resource */ + sourceInfo: SourceInfo; +} +export interface RpcSessionState { + model?: Model; + thinkingLevel: ThinkingLevel; + isStreaming: boolean; + isCompacting: boolean; + steeringMode: "all" | "one-at-a-time"; + followUpMode: "all" | "one-at-a-time"; + sessionFile?: string; + sessionId: string; + sessionName?: string; + autoCompactionEnabled: boolean; + messageCount: number; + pendingMessageCount: number; +} +export type RpcResponse = { + id?: string; + type: "response"; + command: "prompt"; + success: true; +} | { + id?: string; + type: "response"; + command: "steer"; + success: true; +} | { + id?: string; + type: "response"; + command: "follow_up"; + success: true; +} | { + id?: string; + type: "response"; + command: "abort"; + success: true; +} | { + id?: string; + type: "response"; + command: "new_session"; + success: true; + data: { + cancelled: boolean; + }; +} | { + id?: string; + type: "response"; + command: "get_state"; + success: true; + data: RpcSessionState; +} | { + id?: string; + type: "response"; + command: "set_model"; + success: true; + data: Model; +} | { + id?: string; + type: "response"; + command: "cycle_model"; + success: true; + data: { + model: Model; + thinkingLevel: ThinkingLevel; + isScoped: boolean; + } | null; +} | { + id?: string; + type: "response"; + command: "get_available_models"; + success: true; + data: { + models: Model[]; + }; +} | { + id?: string; + type: "response"; + command: "set_thinking_level"; + success: true; +} | { + id?: string; + type: "response"; + command: "cycle_thinking_level"; + success: true; + data: { + level: ThinkingLevel; + } | null; +} | { + id?: string; + type: "response"; + command: "get_available_thinking_levels"; + success: true; + data: { + levels: ThinkingLevel[]; + }; +} | { + id?: string; + type: "response"; + command: "set_steering_mode"; + success: true; +} | { + id?: string; + type: "response"; + command: "set_follow_up_mode"; + success: true; +} | { + id?: string; + type: "response"; + command: "compact"; + success: true; + data: CompactionResult; +} | { + id?: string; + type: "response"; + command: "set_auto_compaction"; + success: true; +} | { + id?: string; + type: "response"; + command: "set_auto_retry"; + success: true; +} | { + id?: string; + type: "response"; + command: "abort_retry"; + success: true; +} | { + id?: string; + type: "response"; + command: "bash"; + success: true; + data: BashResult; +} | { + id?: string; + type: "response"; + command: "abort_bash"; + success: true; +} | { + id?: string; + type: "response"; + command: "get_session_stats"; + success: true; + data: SessionStats; +} | { + id?: string; + type: "response"; + command: "export_html"; + success: true; + data: { + path: string; + }; +} | { + id?: string; + type: "response"; + command: "switch_session"; + success: true; + data: { + cancelled: boolean; + }; +} | { + id?: string; + type: "response"; + command: "fork"; + success: true; + data: { + text: string; + cancelled: boolean; + }; +} | { + id?: string; + type: "response"; + command: "clone"; + success: true; + data: { + cancelled: boolean; + }; +} | { + id?: string; + type: "response"; + command: "get_fork_messages"; + success: true; + data: { + messages: Array<{ + entryId: string; + text: string; + }>; + }; +} | { + id?: string; + type: "response"; + command: "get_entries"; + success: true; + data: { + entries: SessionEntry[]; + leafId: string | null; + }; +} | { + id?: string; + type: "response"; + command: "get_tree"; + success: true; + data: { + tree: SessionTreeNode[]; + leafId: string | null; + }; +} | { + id?: string; + type: "response"; + command: "get_last_assistant_text"; + success: true; + data: { + text: string | null; + }; +} | { + id?: string; + type: "response"; + command: "set_session_name"; + success: true; +} | { + id?: string; + type: "response"; + command: "get_messages"; + success: true; + data: { + messages: AgentMessage[]; + }; +} | { + id?: string; + type: "response"; + command: "get_commands"; + success: true; + data: { + commands: RpcSlashCommand[]; + }; +} | { + id?: string; + type: "response"; + command: string; + success: false; + error: string; +}; +/** Emitted when an extension needs user input */ +export type RpcExtensionUIRequest = { + type: "extension_ui_request"; + id: string; + method: "select"; + title: string; + options: string[]; + timeout?: number; +} | { + type: "extension_ui_request"; + id: string; + method: "confirm"; + title: string; + message: string; + timeout?: number; +} | { + type: "extension_ui_request"; + id: string; + method: "input"; + title: string; + placeholder?: string; + timeout?: number; +} | { + type: "extension_ui_request"; + id: string; + method: "editor"; + title: string; + prefill?: string; +} | { + type: "extension_ui_request"; + id: string; + method: "notify"; + message: string; + notifyType?: "info" | "warning" | "error"; +} | { + type: "extension_ui_request"; + id: string; + method: "setStatus"; + statusKey: string; + statusText: string | undefined; +} | { + type: "extension_ui_request"; + id: string; + method: "setWidget"; + widgetKey: string; + widgetLines: string[] | undefined; + widgetPlacement?: "aboveEditor" | "belowEditor"; +} | { + type: "extension_ui_request"; + id: string; + method: "setTitle"; + title: string; +} | { + type: "extension_ui_request"; + id: string; + method: "set_editor_text"; + text: string; +}; +/** Response to an extension UI request */ +export type RpcExtensionUIResponse = { + type: "extension_ui_response"; + id: string; + value: string; +} | { + type: "extension_ui_response"; + id: string; + confirmed: boolean; +} | { + type: "extension_ui_response"; + id: string; + cancelled: true; +}; +export type RpcCommandType = RpcCommand["type"]; +//# sourceMappingURL=rpc-types.d.ts.map \ No newline at end of file diff --git a/dist/modes/rpc/rpc-types.d.ts.map b/dist/modes/rpc/rpc-types.d.ts.map new file mode 100644 index 0000000..ce3c12f --- /dev/null +++ b/dist/modes/rpc/rpc-types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc-types.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,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MzF,0CAA0C;AAC1C,MAAM,MAAM,sBAAsB,GAC/B;IAAE,IAAI,EAAE,uBAAuB,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC5D;IAAE,IAAI,EAAE,uBAAuB,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE,GACjE;IAAE,IAAI,EAAE,uBAAuB,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,IAAI,CAAA;CAAE,CAAC;AAMlE,MAAM,MAAM,cAAc,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC","sourcesContent":["/**\n * RPC protocol types for headless operation.\n *\n * Commands are sent as JSON lines on stdin.\n * Responses and events are emitted as JSON lines on stdout.\n */\n\nimport type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, Model } from \"@earendil-works/pi-ai\";\nimport type { SessionStats } from \"../../core/agent-session.ts\";\nimport type { BashResult } from \"../../core/bash-executor.ts\";\nimport type { CompactionResult } from \"../../core/compaction/index.ts\";\nimport type { SessionEntry, SessionTreeNode } from \"../../core/session-manager.ts\";\nimport type { SourceInfo } from \"../../core/source-info.ts\";\n\n// ============================================================================\n// RPC Commands (stdin)\n// ============================================================================\n\nexport type RpcCommand =\n\t// Prompting\n\t| { id?: string; type: \"prompt\"; message: string; images?: ImageContent[]; streamingBehavior?: \"steer\" | \"followUp\" }\n\t| { id?: string; type: \"steer\"; message: string; images?: ImageContent[] }\n\t| { id?: string; type: \"follow_up\"; message: string; images?: ImageContent[] }\n\t| { id?: string; type: \"abort\" }\n\t| { id?: string; type: \"new_session\"; parentSession?: string }\n\n\t// State\n\t| { id?: string; type: \"get_state\" }\n\n\t// Model\n\t| { id?: string; type: \"set_model\"; provider: string; modelId: string }\n\t| { id?: string; type: \"cycle_model\" }\n\t| { id?: string; type: \"get_available_models\" }\n\n\t// Thinking\n\t| { id?: string; type: \"set_thinking_level\"; level: ThinkingLevel }\n\t| { id?: string; type: \"cycle_thinking_level\" }\n\t| { id?: string; type: \"get_available_thinking_levels\" }\n\n\t// Queue modes\n\t| { id?: string; type: \"set_steering_mode\"; mode: \"all\" | \"one-at-a-time\" }\n\t| { id?: string; type: \"set_follow_up_mode\"; mode: \"all\" | \"one-at-a-time\" }\n\n\t// Compaction\n\t| { id?: string; type: \"compact\"; customInstructions?: string }\n\t| { id?: string; type: \"set_auto_compaction\"; enabled: boolean }\n\n\t// Retry\n\t| { id?: string; type: \"set_auto_retry\"; enabled: boolean }\n\t| { id?: string; type: \"abort_retry\" }\n\n\t// Bash\n\t| { id?: string; type: \"bash\"; command: string; excludeFromContext?: boolean }\n\t| { id?: string; type: \"abort_bash\" }\n\n\t// Session\n\t| { id?: string; type: \"get_session_stats\" }\n\t| { id?: string; type: \"export_html\"; outputPath?: string }\n\t| { id?: string; type: \"switch_session\"; sessionPath: string }\n\t| { id?: string; type: \"fork\"; entryId: string }\n\t| { id?: string; type: \"clone\" }\n\t| { id?: string; type: \"get_fork_messages\" }\n\t| { id?: string; type: \"get_entries\"; since?: string }\n\t| { id?: string; type: \"get_tree\" }\n\t| { id?: string; type: \"get_last_assistant_text\" }\n\t| { id?: string; type: \"set_session_name\"; name: string }\n\n\t// Messages\n\t| { id?: string; type: \"get_messages\" }\n\n\t// Commands (available for invocation via prompt)\n\t| { id?: string; type: \"get_commands\" };\n\n// ============================================================================\n// RPC Slash Command (for get_commands response)\n// ============================================================================\n\n/** A command available for invocation via prompt */\nexport interface RpcSlashCommand {\n\t/** Command name (without leading slash) */\n\tname: string;\n\t/** Human-readable description */\n\tdescription?: string;\n\t/** What kind of command this is */\n\tsource: \"extension\" | \"prompt\" | \"skill\";\n\t/** Source metadata for the owning resource */\n\tsourceInfo: SourceInfo;\n}\n\n// ============================================================================\n// RPC State\n// ============================================================================\n\nexport interface RpcSessionState {\n\tmodel?: Model;\n\tthinkingLevel: ThinkingLevel;\n\tisStreaming: boolean;\n\tisCompacting: boolean;\n\tsteeringMode: \"all\" | \"one-at-a-time\";\n\tfollowUpMode: \"all\" | \"one-at-a-time\";\n\tsessionFile?: string;\n\tsessionId: string;\n\tsessionName?: string;\n\tautoCompactionEnabled: boolean;\n\tmessageCount: number;\n\tpendingMessageCount: number;\n}\n\n// ============================================================================\n// RPC Responses (stdout)\n// ============================================================================\n\n// Success responses with data\nexport type RpcResponse =\n\t// Prompting (async - events follow)\n\t| { id?: string; type: \"response\"; command: \"prompt\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"steer\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"follow_up\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"abort\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"new_session\"; success: true; data: { cancelled: boolean } }\n\n\t// State\n\t| { id?: string; type: \"response\"; command: \"get_state\"; success: true; data: RpcSessionState }\n\n\t// Model\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"set_model\";\n\t\t\tsuccess: true;\n\t\t\tdata: Model;\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"cycle_model\";\n\t\t\tsuccess: true;\n\t\t\tdata: { model: Model; thinkingLevel: ThinkingLevel; isScoped: boolean } | null;\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_available_models\";\n\t\t\tsuccess: true;\n\t\t\tdata: { models: Model[] };\n\t }\n\n\t// Thinking\n\t| { id?: string; type: \"response\"; command: \"set_thinking_level\"; success: true }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"cycle_thinking_level\";\n\t\t\tsuccess: true;\n\t\t\tdata: { level: ThinkingLevel } | null;\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_available_thinking_levels\";\n\t\t\tsuccess: true;\n\t\t\tdata: { levels: ThinkingLevel[] };\n\t }\n\n\t// Queue modes\n\t| { id?: string; type: \"response\"; command: \"set_steering_mode\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"set_follow_up_mode\"; success: true }\n\n\t// Compaction\n\t| { id?: string; type: \"response\"; command: \"compact\"; success: true; data: CompactionResult }\n\t| { id?: string; type: \"response\"; command: \"set_auto_compaction\"; success: true }\n\n\t// Retry\n\t| { id?: string; type: \"response\"; command: \"set_auto_retry\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"abort_retry\"; success: true }\n\n\t// Bash\n\t| { id?: string; type: \"response\"; command: \"bash\"; success: true; data: BashResult }\n\t| { id?: string; type: \"response\"; command: \"abort_bash\"; success: true }\n\n\t// Session\n\t| { id?: string; type: \"response\"; command: \"get_session_stats\"; success: true; data: SessionStats }\n\t| { id?: string; type: \"response\"; command: \"export_html\"; success: true; data: { path: string } }\n\t| { id?: string; type: \"response\"; command: \"switch_session\"; success: true; data: { cancelled: boolean } }\n\t| { id?: string; type: \"response\"; command: \"fork\"; success: true; data: { text: string; cancelled: boolean } }\n\t| { id?: string; type: \"response\"; command: \"clone\"; success: true; data: { cancelled: boolean } }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_fork_messages\";\n\t\t\tsuccess: true;\n\t\t\tdata: { messages: Array<{ entryId: string; text: string }> };\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_entries\";\n\t\t\tsuccess: true;\n\t\t\tdata: { entries: SessionEntry[]; leafId: string | null };\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_tree\";\n\t\t\tsuccess: true;\n\t\t\tdata: { tree: SessionTreeNode[]; leafId: string | null };\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_last_assistant_text\";\n\t\t\tsuccess: true;\n\t\t\tdata: { text: string | null };\n\t }\n\t| { id?: string; type: \"response\"; command: \"set_session_name\"; success: true }\n\n\t// Messages\n\t| { id?: string; type: \"response\"; command: \"get_messages\"; success: true; data: { messages: AgentMessage[] } }\n\n\t// Commands\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_commands\";\n\t\t\tsuccess: true;\n\t\t\tdata: { commands: RpcSlashCommand[] };\n\t }\n\n\t// Error response (any command can fail)\n\t| { id?: string; type: \"response\"; command: string; success: false; error: string };\n\n// ============================================================================\n// Extension UI Events (stdout)\n// ============================================================================\n\n/** Emitted when an extension needs user input */\nexport type RpcExtensionUIRequest =\n\t| { type: \"extension_ui_request\"; id: string; method: \"select\"; title: string; options: string[]; timeout?: number }\n\t| { type: \"extension_ui_request\"; id: string; method: \"confirm\"; title: string; message: string; timeout?: number }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"input\";\n\t\t\ttitle: string;\n\t\t\tplaceholder?: string;\n\t\t\ttimeout?: number;\n\t }\n\t| { type: \"extension_ui_request\"; id: string; method: \"editor\"; title: string; prefill?: string }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"notify\";\n\t\t\tmessage: string;\n\t\t\tnotifyType?: \"info\" | \"warning\" | \"error\";\n\t }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"setStatus\";\n\t\t\tstatusKey: string;\n\t\t\tstatusText: string | undefined;\n\t }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"setWidget\";\n\t\t\twidgetKey: string;\n\t\t\twidgetLines: string[] | undefined;\n\t\t\twidgetPlacement?: \"aboveEditor\" | \"belowEditor\";\n\t }\n\t| { type: \"extension_ui_request\"; id: string; method: \"setTitle\"; title: string }\n\t| { type: \"extension_ui_request\"; id: string; method: \"set_editor_text\"; text: string };\n\n// ============================================================================\n// Extension UI Commands (stdin)\n// ============================================================================\n\n/** Response to an extension UI request */\nexport type RpcExtensionUIResponse =\n\t| { type: \"extension_ui_response\"; id: string; value: string }\n\t| { type: \"extension_ui_response\"; id: string; confirmed: boolean }\n\t| { type: \"extension_ui_response\"; id: string; cancelled: true };\n\n// ============================================================================\n// Helper type for extracting command types\n// ============================================================================\n\nexport type RpcCommandType = RpcCommand[\"type\"];\n"]} \ No newline at end of file diff --git a/dist/modes/rpc/rpc-types.js b/dist/modes/rpc/rpc-types.js new file mode 100644 index 0000000..1aa7336 --- /dev/null +++ b/dist/modes/rpc/rpc-types.js @@ -0,0 +1,8 @@ +/** + * RPC protocol types for headless operation. + * + * Commands are sent as JSON lines on stdin. + * Responses and events are emitted as JSON lines on stdout. + */ +export {}; +//# sourceMappingURL=rpc-types.js.map \ No newline at end of file diff --git a/dist/modes/rpc/rpc-types.js.map b/dist/modes/rpc/rpc-types.js.map new file mode 100644 index 0000000..1ab8936 --- /dev/null +++ b/dist/modes/rpc/rpc-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc-types.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG","sourcesContent":["/**\n * RPC protocol types for headless operation.\n *\n * Commands are sent as JSON lines on stdin.\n * Responses and events are emitted as JSON lines on stdout.\n */\n\nimport type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, Model } from \"@earendil-works/pi-ai\";\nimport type { SessionStats } from \"../../core/agent-session.ts\";\nimport type { BashResult } from \"../../core/bash-executor.ts\";\nimport type { CompactionResult } from \"../../core/compaction/index.ts\";\nimport type { SessionEntry, SessionTreeNode } from \"../../core/session-manager.ts\";\nimport type { SourceInfo } from \"../../core/source-info.ts\";\n\n// ============================================================================\n// RPC Commands (stdin)\n// ============================================================================\n\nexport type RpcCommand =\n\t// Prompting\n\t| { id?: string; type: \"prompt\"; message: string; images?: ImageContent[]; streamingBehavior?: \"steer\" | \"followUp\" }\n\t| { id?: string; type: \"steer\"; message: string; images?: ImageContent[] }\n\t| { id?: string; type: \"follow_up\"; message: string; images?: ImageContent[] }\n\t| { id?: string; type: \"abort\" }\n\t| { id?: string; type: \"new_session\"; parentSession?: string }\n\n\t// State\n\t| { id?: string; type: \"get_state\" }\n\n\t// Model\n\t| { id?: string; type: \"set_model\"; provider: string; modelId: string }\n\t| { id?: string; type: \"cycle_model\" }\n\t| { id?: string; type: \"get_available_models\" }\n\n\t// Thinking\n\t| { id?: string; type: \"set_thinking_level\"; level: ThinkingLevel }\n\t| { id?: string; type: \"cycle_thinking_level\" }\n\t| { id?: string; type: \"get_available_thinking_levels\" }\n\n\t// Queue modes\n\t| { id?: string; type: \"set_steering_mode\"; mode: \"all\" | \"one-at-a-time\" }\n\t| { id?: string; type: \"set_follow_up_mode\"; mode: \"all\" | \"one-at-a-time\" }\n\n\t// Compaction\n\t| { id?: string; type: \"compact\"; customInstructions?: string }\n\t| { id?: string; type: \"set_auto_compaction\"; enabled: boolean }\n\n\t// Retry\n\t| { id?: string; type: \"set_auto_retry\"; enabled: boolean }\n\t| { id?: string; type: \"abort_retry\" }\n\n\t// Bash\n\t| { id?: string; type: \"bash\"; command: string; excludeFromContext?: boolean }\n\t| { id?: string; type: \"abort_bash\" }\n\n\t// Session\n\t| { id?: string; type: \"get_session_stats\" }\n\t| { id?: string; type: \"export_html\"; outputPath?: string }\n\t| { id?: string; type: \"switch_session\"; sessionPath: string }\n\t| { id?: string; type: \"fork\"; entryId: string }\n\t| { id?: string; type: \"clone\" }\n\t| { id?: string; type: \"get_fork_messages\" }\n\t| { id?: string; type: \"get_entries\"; since?: string }\n\t| { id?: string; type: \"get_tree\" }\n\t| { id?: string; type: \"get_last_assistant_text\" }\n\t| { id?: string; type: \"set_session_name\"; name: string }\n\n\t// Messages\n\t| { id?: string; type: \"get_messages\" }\n\n\t// Commands (available for invocation via prompt)\n\t| { id?: string; type: \"get_commands\" };\n\n// ============================================================================\n// RPC Slash Command (for get_commands response)\n// ============================================================================\n\n/** A command available for invocation via prompt */\nexport interface RpcSlashCommand {\n\t/** Command name (without leading slash) */\n\tname: string;\n\t/** Human-readable description */\n\tdescription?: string;\n\t/** What kind of command this is */\n\tsource: \"extension\" | \"prompt\" | \"skill\";\n\t/** Source metadata for the owning resource */\n\tsourceInfo: SourceInfo;\n}\n\n// ============================================================================\n// RPC State\n// ============================================================================\n\nexport interface RpcSessionState {\n\tmodel?: Model;\n\tthinkingLevel: ThinkingLevel;\n\tisStreaming: boolean;\n\tisCompacting: boolean;\n\tsteeringMode: \"all\" | \"one-at-a-time\";\n\tfollowUpMode: \"all\" | \"one-at-a-time\";\n\tsessionFile?: string;\n\tsessionId: string;\n\tsessionName?: string;\n\tautoCompactionEnabled: boolean;\n\tmessageCount: number;\n\tpendingMessageCount: number;\n}\n\n// ============================================================================\n// RPC Responses (stdout)\n// ============================================================================\n\n// Success responses with data\nexport type RpcResponse =\n\t// Prompting (async - events follow)\n\t| { id?: string; type: \"response\"; command: \"prompt\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"steer\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"follow_up\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"abort\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"new_session\"; success: true; data: { cancelled: boolean } }\n\n\t// State\n\t| { id?: string; type: \"response\"; command: \"get_state\"; success: true; data: RpcSessionState }\n\n\t// Model\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"set_model\";\n\t\t\tsuccess: true;\n\t\t\tdata: Model;\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"cycle_model\";\n\t\t\tsuccess: true;\n\t\t\tdata: { model: Model; thinkingLevel: ThinkingLevel; isScoped: boolean } | null;\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_available_models\";\n\t\t\tsuccess: true;\n\t\t\tdata: { models: Model[] };\n\t }\n\n\t// Thinking\n\t| { id?: string; type: \"response\"; command: \"set_thinking_level\"; success: true }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"cycle_thinking_level\";\n\t\t\tsuccess: true;\n\t\t\tdata: { level: ThinkingLevel } | null;\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_available_thinking_levels\";\n\t\t\tsuccess: true;\n\t\t\tdata: { levels: ThinkingLevel[] };\n\t }\n\n\t// Queue modes\n\t| { id?: string; type: \"response\"; command: \"set_steering_mode\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"set_follow_up_mode\"; success: true }\n\n\t// Compaction\n\t| { id?: string; type: \"response\"; command: \"compact\"; success: true; data: CompactionResult }\n\t| { id?: string; type: \"response\"; command: \"set_auto_compaction\"; success: true }\n\n\t// Retry\n\t| { id?: string; type: \"response\"; command: \"set_auto_retry\"; success: true }\n\t| { id?: string; type: \"response\"; command: \"abort_retry\"; success: true }\n\n\t// Bash\n\t| { id?: string; type: \"response\"; command: \"bash\"; success: true; data: BashResult }\n\t| { id?: string; type: \"response\"; command: \"abort_bash\"; success: true }\n\n\t// Session\n\t| { id?: string; type: \"response\"; command: \"get_session_stats\"; success: true; data: SessionStats }\n\t| { id?: string; type: \"response\"; command: \"export_html\"; success: true; data: { path: string } }\n\t| { id?: string; type: \"response\"; command: \"switch_session\"; success: true; data: { cancelled: boolean } }\n\t| { id?: string; type: \"response\"; command: \"fork\"; success: true; data: { text: string; cancelled: boolean } }\n\t| { id?: string; type: \"response\"; command: \"clone\"; success: true; data: { cancelled: boolean } }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_fork_messages\";\n\t\t\tsuccess: true;\n\t\t\tdata: { messages: Array<{ entryId: string; text: string }> };\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_entries\";\n\t\t\tsuccess: true;\n\t\t\tdata: { entries: SessionEntry[]; leafId: string | null };\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_tree\";\n\t\t\tsuccess: true;\n\t\t\tdata: { tree: SessionTreeNode[]; leafId: string | null };\n\t }\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_last_assistant_text\";\n\t\t\tsuccess: true;\n\t\t\tdata: { text: string | null };\n\t }\n\t| { id?: string; type: \"response\"; command: \"set_session_name\"; success: true }\n\n\t// Messages\n\t| { id?: string; type: \"response\"; command: \"get_messages\"; success: true; data: { messages: AgentMessage[] } }\n\n\t// Commands\n\t| {\n\t\t\tid?: string;\n\t\t\ttype: \"response\";\n\t\t\tcommand: \"get_commands\";\n\t\t\tsuccess: true;\n\t\t\tdata: { commands: RpcSlashCommand[] };\n\t }\n\n\t// Error response (any command can fail)\n\t| { id?: string; type: \"response\"; command: string; success: false; error: string };\n\n// ============================================================================\n// Extension UI Events (stdout)\n// ============================================================================\n\n/** Emitted when an extension needs user input */\nexport type RpcExtensionUIRequest =\n\t| { type: \"extension_ui_request\"; id: string; method: \"select\"; title: string; options: string[]; timeout?: number }\n\t| { type: \"extension_ui_request\"; id: string; method: \"confirm\"; title: string; message: string; timeout?: number }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"input\";\n\t\t\ttitle: string;\n\t\t\tplaceholder?: string;\n\t\t\ttimeout?: number;\n\t }\n\t| { type: \"extension_ui_request\"; id: string; method: \"editor\"; title: string; prefill?: string }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"notify\";\n\t\t\tmessage: string;\n\t\t\tnotifyType?: \"info\" | \"warning\" | \"error\";\n\t }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"setStatus\";\n\t\t\tstatusKey: string;\n\t\t\tstatusText: string | undefined;\n\t }\n\t| {\n\t\t\ttype: \"extension_ui_request\";\n\t\t\tid: string;\n\t\t\tmethod: \"setWidget\";\n\t\t\twidgetKey: string;\n\t\t\twidgetLines: string[] | undefined;\n\t\t\twidgetPlacement?: \"aboveEditor\" | \"belowEditor\";\n\t }\n\t| { type: \"extension_ui_request\"; id: string; method: \"setTitle\"; title: string }\n\t| { type: \"extension_ui_request\"; id: string; method: \"set_editor_text\"; text: string };\n\n// ============================================================================\n// Extension UI Commands (stdin)\n// ============================================================================\n\n/** Response to an extension UI request */\nexport type RpcExtensionUIResponse =\n\t| { type: \"extension_ui_response\"; id: string; value: string }\n\t| { type: \"extension_ui_response\"; id: string; confirmed: boolean }\n\t| { type: \"extension_ui_response\"; id: string; cancelled: true };\n\n// ============================================================================\n// Helper type for extracting command types\n// ============================================================================\n\nexport type RpcCommandType = RpcCommand[\"type\"];\n"]} \ No newline at end of file diff --git a/dist/package-manager-cli.d.ts b/dist/package-manager-cli.d.ts new file mode 100644 index 0000000..05dfb6b --- /dev/null +++ b/dist/package-manager-cli.d.ts @@ -0,0 +1,8 @@ +import type { InlineExtension } from "./core/extensions/types.ts"; +export type PackageCommand = "install" | "remove" | "update" | "list"; +export interface PackageCommandRuntimeOptions { + extensionFactories?: InlineExtension[]; +} +export declare function handleConfigCommand(args: string[], runtimeOptions?: PackageCommandRuntimeOptions): Promise; +export declare function handlePackageCommand(args: string[], runtimeOptions?: PackageCommandRuntimeOptions): Promise; +//# sourceMappingURL=package-manager-cli.d.ts.map \ No newline at end of file diff --git a/dist/package-manager-cli.d.ts.map b/dist/package-manager-cli.d.ts.map new file mode 100644 index 0000000..4265562 --- /dev/null +++ b/dist/package-manager-cli.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"package-manager-cli.d.ts","sourceRoot":"","sources":["../src/package-manager-cli.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAclE,MAAM,MAAM,cAAc,GAAG,SAAS,GAAG,QAAQ,GAAG,QAAQ,GAAG,MAAM,CAAC;AAuftE,MAAM,WAAW,4BAA4B;IAC5C,kBAAkB,CAAC,EAAE,eAAe,EAAE,CAAC;CACvC;AAiED,wBAAsB,mBAAmB,CACxC,IAAI,EAAE,MAAM,EAAE,EACd,cAAc,GAAE,4BAAiC,GAC/C,OAAO,CAAC,OAAO,CAAC,CAoElB;AAED,wBAAsB,oBAAoB,CACzC,IAAI,EAAE,MAAM,EAAE,EACd,cAAc,GAAE,4BAAiC,GAC/C,OAAO,CAAC,OAAO,CAAC,CAgNlB","sourcesContent":["import { join } from \"node:path\";\nimport { Markdown, type MarkdownTheme } from \"@earendil-works/pi-tui\";\nimport chalk from \"chalk\";\nimport { selectConfig } from \"./cli/config-selector.ts\";\nimport { createProjectTrustContext } from \"./cli/project-trust.ts\";\nimport {\n\tAPP_NAME,\n\tCONFIG_DIR_NAME,\n\tdetectInstallMethod,\n\tgetAgentDir,\n\tgetPackageDir,\n\tgetSelfUpdateCommand,\n\tgetSelfUpdateUnavailableInstruction,\n\tPACKAGE_NAME,\n\ttype SelfUpdateCommand,\n\ttype SelfUpdatePackageTarget,\n\tVERSION,\n} from \"./config.ts\";\nimport type { InlineExtension } from \"./core/extensions/types.ts\";\nimport { ModelRuntime } from \"./core/model-runtime.ts\";\nimport { DefaultPackageManager } from \"./core/package-manager.ts\";\nimport { type AppMode, resolveProjectTrusted } from \"./core/project-trust.ts\";\nimport { DefaultResourceLoader } from \"./core/resource-loader.ts\";\nimport { SettingsManager } from \"./core/settings-manager.ts\";\nimport { hasTrustRequiringProjectResources, ProjectTrustStore } from \"./core/trust-manager.ts\";\nimport { spawnProcess } from \"./utils/child-process.ts\";\nimport { getLatestPiRelease, isNewerPackageVersion } from \"./utils/version-check.ts\";\nimport {\n\tcleanupWindowsSelfUpdateQuarantine,\n\tquarantineWindowsNativeDependencies,\n} from \"./utils/windows-self-update.ts\";\n\nexport type PackageCommand = \"install\" | \"remove\" | \"update\" | \"list\";\n\ntype UpdateTarget = { type: \"all\" } | { type: \"self\" } | { type: \"extensions\"; source?: string } | { type: \"models\" };\n\nconst SELF_UPDATE_NOTE_MARKDOWN_THEME: MarkdownTheme = {\n\theading: (text) => chalk.bold(chalk.yellow(text)),\n\tlink: (text) => chalk.cyan(text),\n\tlinkUrl: (text) => chalk.dim(text),\n\tcode: (text) => chalk.yellow(text),\n\tcodeBlock: (text) => chalk.dim(text),\n\tcodeBlockBorder: (text) => chalk.dim(text),\n\tquote: (text) => chalk.dim(text),\n\tquoteBorder: (text) => chalk.dim(text),\n\thr: (text) => chalk.dim(text),\n\tlistBullet: (text) => chalk.yellow(text),\n\tbold: (text) => chalk.bold(text),\n\titalic: (text) => chalk.italic(text),\n\tstrikethrough: (text) => chalk.strikethrough(text),\n\tunderline: (text) => chalk.underline(text),\n};\n\ninterface PackageCommandOptions {\n\tcommand: PackageCommand;\n\tsource?: string;\n\tupdateTarget?: UpdateTarget;\n\tshowExtensionsSkippedNote: boolean;\n\tlocal: boolean;\n\tforce: boolean;\n\tprojectTrustOverride?: boolean;\n\thelp: boolean;\n\tinvalidOption?: string;\n\tinvalidArgument?: string;\n\tmissingOptionValue?: string;\n\tconflictingOptions?: string;\n}\n\nfunction reportSettingsErrors(settingsManager: SettingsManager, context: string): void {\n\tconst errors = settingsManager.drainErrors();\n\tfor (const { scope, error } of errors) {\n\t\tconsole.error(chalk.yellow(`Warning (${context}, ${scope} settings): ${error.message}`));\n\t\tif (error.stack) {\n\t\t\tconsole.error(chalk.dim(error.stack));\n\t\t}\n\t}\n}\n\nfunction getPackageCommandUsage(command: PackageCommand): string {\n\tswitch (command) {\n\t\tcase \"install\":\n\t\t\treturn `${APP_NAME} install [-l] [--approve|--no-approve]`;\n\t\tcase \"remove\":\n\t\t\treturn `${APP_NAME} remove [-l] [--approve|--no-approve]`;\n\t\tcase \"update\":\n\t\t\treturn `${APP_NAME} update [source|self|pi] [--self|--extensions|--models|--all] [--extension ] [--approve|--no-approve] [--force]`;\n\t\tcase \"list\":\n\t\t\treturn `${APP_NAME} list [--approve|--no-approve]`;\n\t}\n}\n\nconst CONFIG_COMMAND_USAGE = `${APP_NAME} config [-l] [--approve|--no-approve]`;\n\nfunction printConfigCommandHelp(): void {\n\tconsole.log(`${chalk.bold(\"Usage:\")}\n ${CONFIG_COMMAND_USAGE}\n\nOpen the resource configuration TUI to enable or disable package resources.\nWithout -l, starts in global settings (~/${CONFIG_DIR_NAME}/agent/settings.json).\nPress Tab in the TUI to switch between global and project-local modes.\n\nOptions:\n -l, --local Edit project overrides (${CONFIG_DIR_NAME}/settings.json)\n -a, --approve Trust project-local files for this command with -l\n -na, --no-approve Ignore project-local files for this command with -l\n`);\n}\n\nfunction printPackageCommandHelp(command: PackageCommand): void {\n\tswitch (command) {\n\t\tcase \"install\":\n\t\t\tconsole.log(`${chalk.bold(\"Usage:\")}\n ${getPackageCommandUsage(\"install\")}\n\nInstall a package and add it to settings.\n\nOptions:\n -l, --local Install project-locally (${CONFIG_DIR_NAME}/settings.json)\n -a, --approve Trust project-local files for this command\n -na, --no-approve Ignore project-local files for this command\n\nExamples:\n ${APP_NAME} install npm:@foo/bar\n ${APP_NAME} install git:github.com/user/repo\n ${APP_NAME} install git:git@github.com:user/repo\n ${APP_NAME} install https://github.com/user/repo\n ${APP_NAME} install ssh://git@github.com/user/repo\n ${APP_NAME} install ./local/path\n`);\n\t\t\treturn;\n\n\t\tcase \"remove\":\n\t\t\tconsole.log(`${chalk.bold(\"Usage:\")}\n ${getPackageCommandUsage(\"remove\")}\n\nRemove a package and its source from settings.\nAlias: ${APP_NAME} uninstall [-l]\n\nOptions:\n -l, --local Remove from project settings (${CONFIG_DIR_NAME}/settings.json)\n -a, --approve Trust project-local files for this command\n -na, --no-approve Ignore project-local files for this command\n\nExamples:\n ${APP_NAME} remove npm:@foo/bar\n ${APP_NAME} uninstall npm:@foo/bar\n`);\n\t\t\treturn;\n\n\t\tcase \"update\":\n\t\t\tconsole.log(`${chalk.bold(\"Usage:\")}\n ${getPackageCommandUsage(\"update\")}\n\nUpdate pi, installed packages, or model catalogs.\n\nOptions:\n --self Update pi only (default when no target is given)\n --extensions Update installed packages only\n --models Refresh model catalogs only\n --all Update pi and installed packages\n --extension Update one package only\n -a, --approve Trust project-local files for this command\n -na, --no-approve Ignore project-local files for this command\n --force Reinstall pi even if the current version is latest\n\nShort forms:\n ${APP_NAME} update Update pi only\n ${APP_NAME} update --all Update pi and all extensions\n ${APP_NAME} update --models Refresh model catalogs only\n ${APP_NAME} update Update one package\n ${APP_NAME} update pi Update pi only (self works as alias to pi)\n`);\n\t\t\treturn;\n\n\t\tcase \"list\":\n\t\t\tconsole.log(`${chalk.bold(\"Usage:\")}\n ${getPackageCommandUsage(\"list\")}\n\nList installed packages from user and project settings.\n\nOptions:\n -a, --approve Trust project-local files for this command\n -na, --no-approve Ignore project-local files for this command\n`);\n\t\t\treturn;\n\t}\n}\n\nfunction parsePackageCommand(args: string[]): PackageCommandOptions | undefined {\n\tconst [rawCommand, ...rest] = args;\n\tlet command: PackageCommand | undefined;\n\tif (rawCommand === \"uninstall\") {\n\t\tcommand = \"remove\";\n\t} else if (rawCommand === \"install\" || rawCommand === \"remove\" || rawCommand === \"update\" || rawCommand === \"list\") {\n\t\tcommand = rawCommand;\n\t}\n\tif (!command) {\n\t\treturn undefined;\n\t}\n\n\tlet local = false;\n\tlet force = false;\n\tlet projectTrustOverride: boolean | undefined;\n\tlet help = false;\n\tlet invalidOption: string | undefined;\n\tlet invalidArgument: string | undefined;\n\tlet missingOptionValue: string | undefined;\n\tlet conflictingOptions: string | undefined;\n\tlet source: string | undefined;\n\tlet selfFlag = false;\n\tlet extensionsFlag = false;\n\tlet modelsFlag = false;\n\tlet allFlag = false;\n\tlet extensionFlagSource: string | undefined;\n\n\tfor (let index = 0; index < rest.length; index++) {\n\t\tconst arg = rest[index];\n\t\tif (arg === \"-h\" || arg === \"--help\") {\n\t\t\thelp = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"-l\" || arg === \"--local\") {\n\t\t\tif (command === \"install\" || command === \"remove\") {\n\t\t\t\tlocal = true;\n\t\t\t} else {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--self\") {\n\t\t\tif (command === \"update\") {\n\t\t\t\tselfFlag = true;\n\t\t\t} else {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--extensions\") {\n\t\t\tif (command === \"update\") {\n\t\t\t\textensionsFlag = true;\n\t\t\t} else {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--models\") {\n\t\t\tif (command === \"update\") {\n\t\t\t\tmodelsFlag = true;\n\t\t\t} else {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--all\") {\n\t\t\tif (command === \"update\") {\n\t\t\t\tallFlag = true;\n\t\t\t} else {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--approve\" || arg === \"-a\") {\n\t\t\tprojectTrustOverride = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--no-approve\" || arg === \"-na\") {\n\t\t\tprojectTrustOverride = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--force\") {\n\t\t\tif (command === \"update\") {\n\t\t\t\tforce = true;\n\t\t\t} else {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--extension\") {\n\t\t\tif (command !== \"update\") {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst value = rest[index + 1];\n\t\t\tif (!value || value.startsWith(\"-\")) {\n\t\t\t\tmissingOptionValue = missingOptionValue ?? arg;\n\t\t\t} else if (extensionFlagSource) {\n\t\t\t\tconflictingOptions = conflictingOptions ?? \"--extension can only be provided once\";\n\t\t\t\tindex++;\n\t\t\t} else {\n\t\t\t\textensionFlagSource = value;\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg.startsWith(\"-\")) {\n\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!source) {\n\t\t\tsource = arg;\n\t\t} else {\n\t\t\tinvalidArgument = invalidArgument ?? arg;\n\t\t}\n\t}\n\n\tlet updateTarget: UpdateTarget | undefined;\n\tlet showExtensionsSkippedNote = false;\n\tif (command === \"update\") {\n\t\tif (allFlag && (selfFlag || extensionsFlag || modelsFlag || extensionFlagSource)) {\n\t\t\tconflictingOptions =\n\t\t\t\tconflictingOptions ?? \"--all cannot be combined with --self, --extensions, --models, or --extension\";\n\t\t}\n\t\tif (allFlag && source) {\n\t\t\tconflictingOptions = conflictingOptions ?? \"--all cannot be combined with a positional source\";\n\t\t}\n\n\t\tif (modelsFlag) {\n\t\t\tif (selfFlag || extensionsFlag || allFlag || extensionFlagSource) {\n\t\t\t\tconflictingOptions =\n\t\t\t\t\tconflictingOptions ?? \"--models cannot be combined with --self, --extensions, --all, or --extension\";\n\t\t\t}\n\t\t\tif (source) {\n\t\t\t\tconflictingOptions = conflictingOptions ?? \"--models cannot be combined with a positional source\";\n\t\t\t}\n\t\t\tupdateTarget = { type: \"models\" };\n\t\t} else if (extensionFlagSource) {\n\t\t\tif (selfFlag || extensionsFlag || allFlag) {\n\t\t\t\tconflictingOptions =\n\t\t\t\t\tconflictingOptions ?? \"--extension cannot be combined with --self, --extensions, or --all\";\n\t\t\t}\n\t\t\tif (source) {\n\t\t\t\tconflictingOptions = conflictingOptions ?? \"--extension cannot be combined with a positional source\";\n\t\t\t}\n\t\t\tupdateTarget = { type: \"extensions\", source: extensionFlagSource };\n\t\t} else if (source) {\n\t\t\tconst sourceIsSelf = source === \"self\" || source === \"pi\";\n\t\t\tif (sourceIsSelf) {\n\t\t\t\tupdateTarget = extensionsFlag ? { type: \"all\" } : { type: \"self\" };\n\t\t\t} else {\n\t\t\t\tif (extensionsFlag || selfFlag || allFlag) {\n\t\t\t\t\tconflictingOptions =\n\t\t\t\t\t\tconflictingOptions ??\n\t\t\t\t\t\t\"positional update targets cannot be combined with --self, --extensions, or --all\";\n\t\t\t\t}\n\t\t\t\tupdateTarget = { type: \"extensions\", source };\n\t\t\t}\n\t\t} else if (allFlag) {\n\t\t\tupdateTarget = { type: \"all\" };\n\t\t} else if (selfFlag && extensionsFlag) {\n\t\t\tupdateTarget = { type: \"all\" };\n\t\t} else if (selfFlag) {\n\t\t\tupdateTarget = { type: \"self\" };\n\t\t} else if (extensionsFlag) {\n\t\t\tupdateTarget = { type: \"extensions\" };\n\t\t} else {\n\t\t\tupdateTarget = { type: \"self\" };\n\t\t\tshowExtensionsSkippedNote = true;\n\t\t}\n\t}\n\n\treturn {\n\t\tcommand,\n\t\tsource,\n\t\tupdateTarget,\n\t\tshowExtensionsSkippedNote,\n\t\tlocal,\n\t\tforce,\n\t\tprojectTrustOverride,\n\t\thelp,\n\t\tinvalidOption,\n\t\tinvalidArgument,\n\t\tmissingOptionValue,\n\t\tconflictingOptions,\n\t};\n}\n\nfunction updateTargetIncludesSelf(target: UpdateTarget): boolean {\n\treturn target.type === \"all\" || target.type === \"self\";\n}\n\nfunction updateTargetIncludesExtensions(target: UpdateTarget): boolean {\n\treturn target.type === \"all\" || target.type === \"extensions\";\n}\n\nasync function refreshModelCatalogs(agentDir: string): Promise {\n\tconst modelRuntime = await ModelRuntime.create({\n\t\tauthPath: join(agentDir, \"auth.json\"),\n\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\tallowModelNetwork: false,\n\t});\n\tconst controller = new AbortController();\n\tconst timeout = setTimeout(() => controller.abort(), 15_000);\n\ttry {\n\t\tconst result = await modelRuntime.refresh({\n\t\t\tallowNetwork: true,\n\t\t\tforce: true,\n\t\t\tsignal: controller.signal,\n\t\t});\n\t\tif (result.aborted) {\n\t\t\tthrow new Error(\"Model catalog refresh timed out.\");\n\t\t}\n\t\tif (result.errors.size > 0) {\n\t\t\tconst details = Array.from(result.errors, ([provider, error]) => `${provider}: ${error.message}`).join(\"; \");\n\t\t\tthrow new Error(`Could not refresh model catalogs: ${details}`);\n\t\t}\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n\tconsole.log(chalk.green(\"Model catalogs refreshed\"));\n}\n\nfunction printSelfUpdateUnavailable(\n\tnpmCommand?: string[],\n\tupdatePackageTarget: SelfUpdatePackageTarget = PACKAGE_NAME,\n): void {\n\tconsole.error(`error: ${APP_NAME} cannot self-update this installation.`);\n\tconsole.error(getSelfUpdateUnavailableInstruction(PACKAGE_NAME, npmCommand, updatePackageTarget));\n\n\tconst entrypoint = process.argv[1];\n\tif (entrypoint) {\n\t\tconsole.error(\"\");\n\t\tconsole.error(`Location of pi executable: ${entrypoint}`);\n\t}\n}\n\nfunction printSelfUpdateFallback(command: SelfUpdateCommand): void {\n\tconsole.error(chalk.dim(`If this keeps failing, run this command yourself: ${command.display}`));\n}\n\nfunction printPnpmSelfUpdateMetadataHint(): void {\n\tconsole.error(chalk.yellow(\"If pnpm reports missing package versions, its cached registry metadata may be stale.\"));\n\tconsole.error(chalk.yellow(`Run \\`pnpm store prune\\` and retry \\`${APP_NAME} update --self\\`.`));\n}\n\nfunction printSelfUpdateNote(note: string): void {\n\tconst trimmedNote = note.trim();\n\tif (!trimmedNote) {\n\t\treturn;\n\t}\n\n\tconsole.log();\n\tconsole.log(chalk.bold(chalk.yellow(\"Update note\")));\n\ttry {\n\t\tconst width = Math.max(20, process.stdout.columns ?? 80);\n\t\tconst renderedLines = new Markdown(trimmedNote, 0, 0, SELF_UPDATE_NOTE_MARKDOWN_THEME)\n\t\t\t.render(width)\n\t\t\t.map((line) => line.trimEnd());\n\t\tconsole.log(renderedLines.join(\"\\n\"));\n\t} catch {\n\t\tconsole.log(trimmedNote);\n\t}\n\tconsole.log();\n}\n\ninterface SelfUpdatePlan {\n\tpackageName: string;\n\tinstallSpec: string;\n\tversion: string;\n\tshouldRun: boolean;\n\tnote?: string;\n}\n\nasync function getSelfUpdatePlan(force: boolean): Promise {\n\tlet latestRelease: Awaited>;\n\ttry {\n\t\tlatestRelease = await getLatestPiRelease(VERSION);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`Could not determine latest ${APP_NAME} version: ${message}`);\n\t}\n\tif (!latestRelease) {\n\t\tthrow new Error(`Could not determine latest ${APP_NAME} version.`);\n\t}\n\n\tconst packageName = latestRelease.packageName ?? PACKAGE_NAME;\n\tconst installSpec = `${packageName}@${latestRelease.version}`;\n\tif (force || packageName !== PACKAGE_NAME || isNewerPackageVersion(latestRelease.version, VERSION)) {\n\t\treturn {\n\t\t\tpackageName,\n\t\t\tinstallSpec,\n\t\t\tversion: latestRelease.version,\n\t\t\t...(latestRelease.note ? { note: latestRelease.note } : {}),\n\t\t\tshouldRun: true,\n\t\t};\n\t}\n\n\tconsole.log(chalk.green(`${APP_NAME} is already up to date (v${VERSION})`));\n\treturn { packageName, installSpec, version: latestRelease.version, shouldRun: false };\n}\n\nasync function runSelfUpdate(command: SelfUpdateCommand): Promise {\n\tconsole.log(chalk.dim(`Updating ${APP_NAME} with ${command.display}...`));\n\tfor (const step of command.steps ?? [command]) {\n\t\tawait new Promise((resolve, reject) => {\n\t\t\tconst child = spawnProcess(step.command, step.args, {\n\t\t\t\tstdio: \"inherit\",\n\t\t\t});\n\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\treject(error);\n\t\t\t});\n\t\t\tchild.on(\"close\", (code, signal) => {\n\t\t\t\tif (code === 0) {\n\t\t\t\t\tresolve();\n\t\t\t\t} else if (signal) {\n\t\t\t\t\treject(new Error(`${step.display} terminated by signal ${signal}`));\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(`${step.display} exited with code ${code ?? \"unknown\"}`));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n}\n\nfunction prepareWindowsNpmSelfUpdate(): void {\n\tif (process.platform !== \"win32\") {\n\t\treturn;\n\t}\n\n\tconst packageDir = getPackageDir();\n\tcleanupWindowsSelfUpdateQuarantine(packageDir);\n\tquarantineWindowsNativeDependencies(packageDir);\n}\n\nexport interface PackageCommandRuntimeOptions {\n\textensionFactories?: InlineExtension[];\n}\n\ninterface CommandSettingsResult {\n\tsettingsManager: SettingsManager;\n\tprojectTrustWarnings: string[];\n}\n\nfunction getCommandAppMode(): AppMode {\n\treturn process.stdin.isTTY && process.stdout.isTTY ? \"interactive\" : \"print\";\n}\n\nfunction reportProjectTrustWarnings(warnings: readonly string[]): void {\n\tfor (const warning of warnings) {\n\t\tconsole.error(chalk.yellow(`Warning: ${warning}`));\n\t}\n}\n\nasync function createCommandSettingsManager(options: {\n\tcwd: string;\n\tagentDir: string;\n\tprojectTrustOverride?: boolean;\n\tuseSavedProjectTrustOnly?: boolean;\n\textensionFactories?: InlineExtension[];\n}): Promise {\n\tconst settingsManager = SettingsManager.create(options.cwd, options.agentDir, { projectTrusted: false });\n\tconst projectTrustWarnings: string[] = [];\n\tconst trustStore = new ProjectTrustStore(options.agentDir);\n\tif (options.useSavedProjectTrustOnly) {\n\t\tconst savedProjectTrusted = trustStore.get(options.cwd) === true;\n\t\tsettingsManager.setProjectTrusted(options.projectTrustOverride ?? savedProjectTrusted);\n\t\treturn { settingsManager, projectTrustWarnings };\n\t}\n\n\tconst appMode = getCommandAppMode();\n\tconst extensionsResult =\n\t\toptions.projectTrustOverride === undefined && hasTrustRequiringProjectResources(options.cwd)\n\t\t\t? await new DefaultResourceLoader({\n\t\t\t\t\tcwd: options.cwd,\n\t\t\t\t\tagentDir: options.agentDir,\n\t\t\t\t\tsettingsManager,\n\t\t\t\t\textensionFactories: options.extensionFactories,\n\t\t\t\t}).loadProjectTrustExtensions()\n\t\t\t: undefined;\n\tfor (const error of extensionsResult?.errors ?? []) {\n\t\tprojectTrustWarnings.push(`Failed to load extension \"${error.path}\": ${error.error}`);\n\t}\n\n\tconst projectTrusted = await resolveProjectTrusted({\n\t\tcwd: options.cwd,\n\t\ttrustStore,\n\t\ttrustOverride: options.projectTrustOverride,\n\t\tdefaultProjectTrust: settingsManager.getDefaultProjectTrust(),\n\t\textensionsResult,\n\t\tprojectTrustContext: createProjectTrustContext({\n\t\t\tcwd: options.cwd,\n\t\t\tmode: appMode,\n\t\t\tsettingsManager,\n\t\t\thasUI: appMode === \"interactive\",\n\t\t}),\n\t\tonExtensionError: (message) => projectTrustWarnings.push(message),\n\t});\n\tsettingsManager.setProjectTrusted(projectTrusted);\n\treturn { settingsManager, projectTrustWarnings };\n}\n\nexport async function handleConfigCommand(\n\targs: string[],\n\truntimeOptions: PackageCommandRuntimeOptions = {},\n): Promise {\n\tconst [command, ...rest] = args;\n\tif (command !== \"config\") {\n\t\treturn false;\n\t}\n\n\tif (rest.includes(\"-h\") || rest.includes(\"--help\")) {\n\t\tprintConfigCommandHelp();\n\t\treturn true;\n\t}\n\n\tlet local = false;\n\tlet projectTrustOverride: boolean | undefined;\n\tfor (const arg of rest) {\n\t\tif (arg === \"-l\" || arg === \"--local\") {\n\t\t\tlocal = true;\n\t\t} else if (arg === \"-a\" || arg === \"--approve\") {\n\t\t\tprojectTrustOverride = true;\n\t\t} else if (arg === \"-na\" || arg === \"--no-approve\") {\n\t\t\tprojectTrustOverride = false;\n\t\t} else if (arg.startsWith(\"-\")) {\n\t\t\tconsole.error(chalk.red(`Unknown option ${arg} for \"config\".`));\n\t\t\tconsole.error(chalk.dim(`Use \"${APP_NAME} --help\" or \"${CONFIG_COMMAND_USAGE}\".`));\n\t\t\tprocess.exitCode = 1;\n\t\t\treturn true;\n\t\t} else {\n\t\t\tconsole.error(chalk.red(`Unexpected argument ${arg}.`));\n\t\t\tconsole.error(chalk.dim(`Usage: ${CONFIG_COMMAND_USAGE}`));\n\t\t\tprocess.exitCode = 1;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst { settingsManager, projectTrustWarnings } = await createCommandSettingsManager({\n\t\tcwd,\n\t\tagentDir,\n\t\tprojectTrustOverride,\n\t\textensionFactories: runtimeOptions.extensionFactories,\n\t});\n\treportProjectTrustWarnings(projectTrustWarnings);\n\tif (local && !settingsManager.isProjectTrusted()) {\n\t\tconsole.error(chalk.red(\"Project is not trusted. Use --approve to modify local resource config.\"));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\treportSettingsErrors(settingsManager, \"config command\");\n\tconst globalSettingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\tconst globalResolvedPaths = await new DefaultPackageManager({\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager: globalSettingsManager,\n\t}).resolve();\n\tconst projectResolvedPaths = settingsManager.isProjectTrusted()\n\t\t? await new DefaultPackageManager({ cwd, agentDir, settingsManager }).resolve()\n\t\t: globalResolvedPaths;\n\n\tawait selectConfig({\n\t\tresolvedPaths: { global: globalResolvedPaths, project: projectResolvedPaths },\n\t\tsettingsManager,\n\t\tcwd,\n\t\tagentDir,\n\t\twriteScope: local ? \"project\" : \"global\",\n\t\tprojectModeAvailable: settingsManager.isProjectTrusted(),\n\t});\n\n\tprocess.exit(0);\n}\n\nexport async function handlePackageCommand(\n\targs: string[],\n\truntimeOptions: PackageCommandRuntimeOptions = {},\n): Promise {\n\tconst options = parsePackageCommand(args);\n\tif (!options) {\n\t\treturn false;\n\t}\n\n\tif (options.help) {\n\t\tprintPackageCommandHelp(options.command);\n\t\treturn true;\n\t}\n\n\tif (options.invalidOption) {\n\t\tconsole.error(chalk.red(`Unknown option ${options.invalidOption} for \"${options.command}\".`));\n\t\tconsole.error(chalk.dim(`Use \"${APP_NAME} --help\" or \"${getPackageCommandUsage(options.command)}\".`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\n\tif (options.missingOptionValue) {\n\t\tconsole.error(chalk.red(`Missing value for ${options.missingOptionValue}.`));\n\t\tconsole.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\n\tif (options.invalidArgument) {\n\t\tconsole.error(chalk.red(`Unexpected argument ${options.invalidArgument}.`));\n\t\tconsole.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\n\tif (options.conflictingOptions) {\n\t\tconsole.error(chalk.red(options.conflictingOptions));\n\t\tconsole.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\n\tconst source = options.source;\n\tif ((options.command === \"install\" || options.command === \"remove\") && !source) {\n\t\tconsole.error(chalk.red(`Missing ${options.command} source.`));\n\t\tconsole.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\n\tif (options.command === \"update\" && options.updateTarget?.type === \"models\") {\n\t\ttry {\n\t\t\tawait refreshModelCatalogs(getAgentDir());\n\t\t} catch (error: unknown) {\n\t\t\tconst message = error instanceof Error ? error.message : \"Unknown model catalog refresh error\";\n\t\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\t\tprocess.exitCode = 1;\n\t\t}\n\t\treturn true;\n\t}\n\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst writesProjectPackageConfig = (options.command === \"install\" || options.command === \"remove\") && options.local;\n\tconst { settingsManager, projectTrustWarnings } = await createCommandSettingsManager({\n\t\tcwd,\n\t\tagentDir,\n\t\tprojectTrustOverride: options.projectTrustOverride,\n\t\tuseSavedProjectTrustOnly: options.command === \"update\",\n\t\textensionFactories: runtimeOptions.extensionFactories,\n\t});\n\treportProjectTrustWarnings(projectTrustWarnings);\n\tif (!settingsManager.isProjectTrusted() && writesProjectPackageConfig) {\n\t\tconsole.error(chalk.red(\"Project is not trusted. Use --approve to modify local package config.\"));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\treportSettingsErrors(settingsManager, \"package command\");\n\tconst selfUpdateNpmCommand = settingsManager.getGlobalSettings().npmCommand;\n\n\tconst packageManager = new DefaultPackageManager({ cwd, agentDir, settingsManager });\n\n\tpackageManager.setProgressCallback((event) => {\n\t\tif (event.type === \"start\") {\n\t\t\tprocess.stdout.write(chalk.dim(`${event.message}\\n`));\n\t\t}\n\t});\n\n\ttry {\n\t\tswitch (options.command) {\n\t\t\tcase \"install\":\n\t\t\t\tawait packageManager.installAndPersist(source!, { local: options.local });\n\t\t\t\tconsole.log(chalk.green(`Installed ${source}`));\n\t\t\t\treturn true;\n\n\t\t\tcase \"remove\": {\n\t\t\t\tconst removed = await packageManager.removeAndPersist(source!, { local: options.local });\n\t\t\t\tif (!removed) {\n\t\t\t\t\tconsole.error(chalk.red(`No matching package found for ${source}`));\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tconsole.log(chalk.green(`Removed ${source}`));\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tcase \"list\": {\n\t\t\t\tconst configuredPackages = packageManager.listConfiguredPackages();\n\t\t\t\tconst userPackages = configuredPackages.filter((pkg) => pkg.scope === \"user\");\n\t\t\t\tconst projectPackages = configuredPackages.filter((pkg) => pkg.scope === \"project\");\n\n\t\t\t\tif (configuredPackages.length === 0) {\n\t\t\t\t\tconsole.log(chalk.dim(\"No packages installed.\"));\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\tconst formatPackage = (pkg: (typeof configuredPackages)[number]) => {\n\t\t\t\t\tconst display = pkg.filtered ? `${pkg.source} (filtered)` : pkg.source;\n\t\t\t\t\tconsole.log(` ${display}`);\n\t\t\t\t\tif (pkg.installedPath) {\n\t\t\t\t\t\tconsole.log(chalk.dim(` ${pkg.installedPath}`));\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tif (userPackages.length > 0) {\n\t\t\t\t\tconsole.log(chalk.bold(\"User packages:\"));\n\t\t\t\t\tfor (const pkg of userPackages) {\n\t\t\t\t\t\tformatPackage(pkg);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (projectPackages.length > 0) {\n\t\t\t\t\tif (userPackages.length > 0) console.log();\n\t\t\t\t\tconsole.log(chalk.bold(\"Project packages:\"));\n\t\t\t\t\tfor (const pkg of projectPackages) {\n\t\t\t\t\t\tformatPackage(pkg);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tcase \"update\": {\n\t\t\t\tconst target = options.updateTarget ?? { type: \"self\" };\n\t\t\t\tif (options.showExtensionsSkippedNote) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.dim(`Extensions are skipped. Run ${APP_NAME} update --extensions to update extensions.`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (updateTargetIncludesExtensions(target)) {\n\t\t\t\t\tconst updateSource = target.type === \"extensions\" ? target.source : undefined;\n\t\t\t\t\tawait packageManager.update(updateSource);\n\t\t\t\t\tif (updateSource) {\n\t\t\t\t\t\tconsole.log(chalk.green(`Updated ${updateSource}`));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(chalk.green(\"Updated packages\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (updateTargetIncludesSelf(target)) {\n\t\t\t\t\tconst selfUpdatePlan = await getSelfUpdatePlan(options.force);\n\t\t\t\t\tif (!selfUpdatePlan.shouldRun) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tconst installMethod = detectInstallMethod();\n\t\t\t\t\tif (process.platform === \"win32\" && installMethod !== \"npm\" && installMethod !== \"pnpm\") {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(`${APP_NAME} self-update on Windows is only supported for npm and pnpm installs.`),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.error(chalk.dim(`Detected install method: ${installMethod}. Update ${APP_NAME} manually.`));\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tconst selfUpdateTarget = {\n\t\t\t\t\t\tpackageName: selfUpdatePlan.packageName,\n\t\t\t\t\t\tinstallSpec: selfUpdatePlan.installSpec,\n\t\t\t\t\t};\n\t\t\t\t\tconst selfUpdateCommand = getSelfUpdateCommand(PACKAGE_NAME, selfUpdateNpmCommand, selfUpdateTarget);\n\t\t\t\t\tif (!selfUpdateCommand) {\n\t\t\t\t\t\tprintSelfUpdateUnavailable(selfUpdateNpmCommand, selfUpdateTarget);\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tif (selfUpdatePlan.note) {\n\t\t\t\t\t\tprintSelfUpdateNote(selfUpdatePlan.note);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (installMethod === \"npm\") {\n\t\t\t\t\t\t\tprepareWindowsNpmSelfUpdate();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait runSelfUpdate(selfUpdateCommand);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tconst message = error instanceof Error ? error.message : \"Unknown package command error\";\n\t\t\t\t\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\t\t\t\t\tif (installMethod === \"pnpm\") {\n\t\t\t\t\t\t\tprintPnpmSelfUpdateMetadataHint();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprintSelfUpdateFallback(selfUpdateCommand);\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(chalk.green(`Updated ${APP_NAME} from ${VERSION} to ${selfUpdatePlan.version}`));\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : \"Unknown package command error\";\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/package-manager-cli.js b/dist/package-manager-cli.js new file mode 100644 index 0000000..290341f --- /dev/null +++ b/dist/package-manager-cli.js @@ -0,0 +1,775 @@ +import { join } from "node:path"; +import { Markdown } from "@earendil-works/pi-tui"; +import chalk from "chalk"; +import { selectConfig } from "./cli/config-selector.js"; +import { createProjectTrustContext } from "./cli/project-trust.js"; +import { APP_NAME, CONFIG_DIR_NAME, detectInstallMethod, getAgentDir, getPackageDir, getSelfUpdateCommand, getSelfUpdateUnavailableInstruction, PACKAGE_NAME, VERSION, } from "./config.js"; +import { ModelRuntime } from "./core/model-runtime.js"; +import { DefaultPackageManager } from "./core/package-manager.js"; +import { resolveProjectTrusted } from "./core/project-trust.js"; +import { DefaultResourceLoader } from "./core/resource-loader.js"; +import { SettingsManager } from "./core/settings-manager.js"; +import { hasTrustRequiringProjectResources, ProjectTrustStore } from "./core/trust-manager.js"; +import { spawnProcess } from "./utils/child-process.js"; +import { getLatestPiRelease, isNewerPackageVersion } from "./utils/version-check.js"; +import { cleanupWindowsSelfUpdateQuarantine, quarantineWindowsNativeDependencies, } from "./utils/windows-self-update.js"; +const SELF_UPDATE_NOTE_MARKDOWN_THEME = { + heading: (text) => chalk.bold(chalk.yellow(text)), + link: (text) => chalk.cyan(text), + linkUrl: (text) => chalk.dim(text), + code: (text) => chalk.yellow(text), + codeBlock: (text) => chalk.dim(text), + codeBlockBorder: (text) => chalk.dim(text), + quote: (text) => chalk.dim(text), + quoteBorder: (text) => chalk.dim(text), + hr: (text) => chalk.dim(text), + listBullet: (text) => chalk.yellow(text), + bold: (text) => chalk.bold(text), + italic: (text) => chalk.italic(text), + strikethrough: (text) => chalk.strikethrough(text), + underline: (text) => chalk.underline(text), +}; +function reportSettingsErrors(settingsManager, context) { + const errors = settingsManager.drainErrors(); + for (const { scope, error } of errors) { + console.error(chalk.yellow(`Warning (${context}, ${scope} settings): ${error.message}`)); + if (error.stack) { + console.error(chalk.dim(error.stack)); + } + } +} +function getPackageCommandUsage(command) { + switch (command) { + case "install": + return `${APP_NAME} install [-l] [--approve|--no-approve]`; + case "remove": + return `${APP_NAME} remove [-l] [--approve|--no-approve]`; + case "update": + return `${APP_NAME} update [source|self|pi] [--self|--extensions|--models|--all] [--extension ] [--approve|--no-approve] [--force]`; + case "list": + return `${APP_NAME} list [--approve|--no-approve]`; + } +} +const CONFIG_COMMAND_USAGE = `${APP_NAME} config [-l] [--approve|--no-approve]`; +function printConfigCommandHelp() { + console.log(`${chalk.bold("Usage:")} + ${CONFIG_COMMAND_USAGE} + +Open the resource configuration TUI to enable or disable package resources. +Without -l, starts in global settings (~/${CONFIG_DIR_NAME}/agent/settings.json). +Press Tab in the TUI to switch between global and project-local modes. + +Options: + -l, --local Edit project overrides (${CONFIG_DIR_NAME}/settings.json) + -a, --approve Trust project-local files for this command with -l + -na, --no-approve Ignore project-local files for this command with -l +`); +} +function printPackageCommandHelp(command) { + switch (command) { + case "install": + console.log(`${chalk.bold("Usage:")} + ${getPackageCommandUsage("install")} + +Install a package and add it to settings. + +Options: + -l, --local Install project-locally (${CONFIG_DIR_NAME}/settings.json) + -a, --approve Trust project-local files for this command + -na, --no-approve Ignore project-local files for this command + +Examples: + ${APP_NAME} install npm:@foo/bar + ${APP_NAME} install git:github.com/user/repo + ${APP_NAME} install git:git@github.com:user/repo + ${APP_NAME} install https://github.com/user/repo + ${APP_NAME} install ssh://git@github.com/user/repo + ${APP_NAME} install ./local/path +`); + return; + case "remove": + console.log(`${chalk.bold("Usage:")} + ${getPackageCommandUsage("remove")} + +Remove a package and its source from settings. +Alias: ${APP_NAME} uninstall [-l] + +Options: + -l, --local Remove from project settings (${CONFIG_DIR_NAME}/settings.json) + -a, --approve Trust project-local files for this command + -na, --no-approve Ignore project-local files for this command + +Examples: + ${APP_NAME} remove npm:@foo/bar + ${APP_NAME} uninstall npm:@foo/bar +`); + return; + case "update": + console.log(`${chalk.bold("Usage:")} + ${getPackageCommandUsage("update")} + +Update pi, installed packages, or model catalogs. + +Options: + --self Update pi only (default when no target is given) + --extensions Update installed packages only + --models Refresh model catalogs only + --all Update pi and installed packages + --extension Update one package only + -a, --approve Trust project-local files for this command + -na, --no-approve Ignore project-local files for this command + --force Reinstall pi even if the current version is latest + +Short forms: + ${APP_NAME} update Update pi only + ${APP_NAME} update --all Update pi and all extensions + ${APP_NAME} update --models Refresh model catalogs only + ${APP_NAME} update Update one package + ${APP_NAME} update pi Update pi only (self works as alias to pi) +`); + return; + case "list": + console.log(`${chalk.bold("Usage:")} + ${getPackageCommandUsage("list")} + +List installed packages from user and project settings. + +Options: + -a, --approve Trust project-local files for this command + -na, --no-approve Ignore project-local files for this command +`); + return; + } +} +function parsePackageCommand(args) { + const [rawCommand, ...rest] = args; + let command; + if (rawCommand === "uninstall") { + command = "remove"; + } + else if (rawCommand === "install" || rawCommand === "remove" || rawCommand === "update" || rawCommand === "list") { + command = rawCommand; + } + if (!command) { + return undefined; + } + let local = false; + let force = false; + let projectTrustOverride; + let help = false; + let invalidOption; + let invalidArgument; + let missingOptionValue; + let conflictingOptions; + let source; + let selfFlag = false; + let extensionsFlag = false; + let modelsFlag = false; + let allFlag = false; + let extensionFlagSource; + for (let index = 0; index < rest.length; index++) { + const arg = rest[index]; + if (arg === "-h" || arg === "--help") { + help = true; + continue; + } + if (arg === "-l" || arg === "--local") { + if (command === "install" || command === "remove") { + local = true; + } + else { + invalidOption = invalidOption ?? arg; + } + continue; + } + if (arg === "--self") { + if (command === "update") { + selfFlag = true; + } + else { + invalidOption = invalidOption ?? arg; + } + continue; + } + if (arg === "--extensions") { + if (command === "update") { + extensionsFlag = true; + } + else { + invalidOption = invalidOption ?? arg; + } + continue; + } + if (arg === "--models") { + if (command === "update") { + modelsFlag = true; + } + else { + invalidOption = invalidOption ?? arg; + } + continue; + } + if (arg === "--all") { + if (command === "update") { + allFlag = true; + } + else { + invalidOption = invalidOption ?? arg; + } + continue; + } + if (arg === "--approve" || arg === "-a") { + projectTrustOverride = true; + continue; + } + if (arg === "--no-approve" || arg === "-na") { + projectTrustOverride = false; + continue; + } + if (arg === "--force") { + if (command === "update") { + force = true; + } + else { + invalidOption = invalidOption ?? arg; + } + continue; + } + if (arg === "--extension") { + if (command !== "update") { + invalidOption = invalidOption ?? arg; + continue; + } + const value = rest[index + 1]; + if (!value || value.startsWith("-")) { + missingOptionValue = missingOptionValue ?? arg; + } + else if (extensionFlagSource) { + conflictingOptions = conflictingOptions ?? "--extension can only be provided once"; + index++; + } + else { + extensionFlagSource = value; + index++; + } + continue; + } + if (arg.startsWith("-")) { + invalidOption = invalidOption ?? arg; + continue; + } + if (!source) { + source = arg; + } + else { + invalidArgument = invalidArgument ?? arg; + } + } + let updateTarget; + let showExtensionsSkippedNote = false; + if (command === "update") { + if (allFlag && (selfFlag || extensionsFlag || modelsFlag || extensionFlagSource)) { + conflictingOptions = + conflictingOptions ?? "--all cannot be combined with --self, --extensions, --models, or --extension"; + } + if (allFlag && source) { + conflictingOptions = conflictingOptions ?? "--all cannot be combined with a positional source"; + } + if (modelsFlag) { + if (selfFlag || extensionsFlag || allFlag || extensionFlagSource) { + conflictingOptions = + conflictingOptions ?? "--models cannot be combined with --self, --extensions, --all, or --extension"; + } + if (source) { + conflictingOptions = conflictingOptions ?? "--models cannot be combined with a positional source"; + } + updateTarget = { type: "models" }; + } + else if (extensionFlagSource) { + if (selfFlag || extensionsFlag || allFlag) { + conflictingOptions = + conflictingOptions ?? "--extension cannot be combined with --self, --extensions, or --all"; + } + if (source) { + conflictingOptions = conflictingOptions ?? "--extension cannot be combined with a positional source"; + } + updateTarget = { type: "extensions", source: extensionFlagSource }; + } + else if (source) { + const sourceIsSelf = source === "self" || source === "pi"; + if (sourceIsSelf) { + updateTarget = extensionsFlag ? { type: "all" } : { type: "self" }; + } + else { + if (extensionsFlag || selfFlag || allFlag) { + conflictingOptions = + conflictingOptions ?? + "positional update targets cannot be combined with --self, --extensions, or --all"; + } + updateTarget = { type: "extensions", source }; + } + } + else if (allFlag) { + updateTarget = { type: "all" }; + } + else if (selfFlag && extensionsFlag) { + updateTarget = { type: "all" }; + } + else if (selfFlag) { + updateTarget = { type: "self" }; + } + else if (extensionsFlag) { + updateTarget = { type: "extensions" }; + } + else { + updateTarget = { type: "self" }; + showExtensionsSkippedNote = true; + } + } + return { + command, + source, + updateTarget, + showExtensionsSkippedNote, + local, + force, + projectTrustOverride, + help, + invalidOption, + invalidArgument, + missingOptionValue, + conflictingOptions, + }; +} +function updateTargetIncludesSelf(target) { + return target.type === "all" || target.type === "self"; +} +function updateTargetIncludesExtensions(target) { + return target.type === "all" || target.type === "extensions"; +} +async function refreshModelCatalogs(agentDir) { + const modelRuntime = await ModelRuntime.create({ + authPath: join(agentDir, "auth.json"), + modelsPath: join(agentDir, "models.json"), + allowModelNetwork: false, + }); + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 15_000); + try { + const result = await modelRuntime.refresh({ + allowNetwork: true, + force: true, + signal: controller.signal, + }); + if (result.aborted) { + throw new Error("Model catalog refresh timed out."); + } + if (result.errors.size > 0) { + const details = Array.from(result.errors, ([provider, error]) => `${provider}: ${error.message}`).join("; "); + throw new Error(`Could not refresh model catalogs: ${details}`); + } + } + finally { + clearTimeout(timeout); + } + console.log(chalk.green("Model catalogs refreshed")); +} +function printSelfUpdateUnavailable(npmCommand, updatePackageTarget = PACKAGE_NAME) { + console.error(`error: ${APP_NAME} cannot self-update this installation.`); + console.error(getSelfUpdateUnavailableInstruction(PACKAGE_NAME, npmCommand, updatePackageTarget)); + const entrypoint = process.argv[1]; + if (entrypoint) { + console.error(""); + console.error(`Location of pi executable: ${entrypoint}`); + } +} +function printSelfUpdateFallback(command) { + console.error(chalk.dim(`If this keeps failing, run this command yourself: ${command.display}`)); +} +function printPnpmSelfUpdateMetadataHint() { + console.error(chalk.yellow("If pnpm reports missing package versions, its cached registry metadata may be stale.")); + console.error(chalk.yellow(`Run \`pnpm store prune\` and retry \`${APP_NAME} update --self\`.`)); +} +function printSelfUpdateNote(note) { + const trimmedNote = note.trim(); + if (!trimmedNote) { + return; + } + console.log(); + console.log(chalk.bold(chalk.yellow("Update note"))); + try { + const width = Math.max(20, process.stdout.columns ?? 80); + const renderedLines = new Markdown(trimmedNote, 0, 0, SELF_UPDATE_NOTE_MARKDOWN_THEME) + .render(width) + .map((line) => line.trimEnd()); + console.log(renderedLines.join("\n")); + } + catch { + console.log(trimmedNote); + } + console.log(); +} +async function getSelfUpdatePlan(force) { + let latestRelease; + try { + latestRelease = await getLatestPiRelease(VERSION); + } + catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`Could not determine latest ${APP_NAME} version: ${message}`); + } + if (!latestRelease) { + throw new Error(`Could not determine latest ${APP_NAME} version.`); + } + const packageName = latestRelease.packageName ?? PACKAGE_NAME; + const installSpec = `${packageName}@${latestRelease.version}`; + if (force || packageName !== PACKAGE_NAME || isNewerPackageVersion(latestRelease.version, VERSION)) { + return { + packageName, + installSpec, + version: latestRelease.version, + ...(latestRelease.note ? { note: latestRelease.note } : {}), + shouldRun: true, + }; + } + console.log(chalk.green(`${APP_NAME} is already up to date (v${VERSION})`)); + return { packageName, installSpec, version: latestRelease.version, shouldRun: false }; +} +async function runSelfUpdate(command) { + console.log(chalk.dim(`Updating ${APP_NAME} with ${command.display}...`)); + for (const step of command.steps ?? [command]) { + await new Promise((resolve, reject) => { + const child = spawnProcess(step.command, step.args, { + stdio: "inherit", + }); + child.on("error", (error) => { + reject(error); + }); + child.on("close", (code, signal) => { + if (code === 0) { + resolve(); + } + else if (signal) { + reject(new Error(`${step.display} terminated by signal ${signal}`)); + } + else { + reject(new Error(`${step.display} exited with code ${code ?? "unknown"}`)); + } + }); + }); + } +} +function prepareWindowsNpmSelfUpdate() { + if (process.platform !== "win32") { + return; + } + const packageDir = getPackageDir(); + cleanupWindowsSelfUpdateQuarantine(packageDir); + quarantineWindowsNativeDependencies(packageDir); +} +function getCommandAppMode() { + return process.stdin.isTTY && process.stdout.isTTY ? "interactive" : "print"; +} +function reportProjectTrustWarnings(warnings) { + for (const warning of warnings) { + console.error(chalk.yellow(`Warning: ${warning}`)); + } +} +async function createCommandSettingsManager(options) { + const settingsManager = SettingsManager.create(options.cwd, options.agentDir, { projectTrusted: false }); + const projectTrustWarnings = []; + const trustStore = new ProjectTrustStore(options.agentDir); + if (options.useSavedProjectTrustOnly) { + const savedProjectTrusted = trustStore.get(options.cwd) === true; + settingsManager.setProjectTrusted(options.projectTrustOverride ?? savedProjectTrusted); + return { settingsManager, projectTrustWarnings }; + } + const appMode = getCommandAppMode(); + const extensionsResult = options.projectTrustOverride === undefined && hasTrustRequiringProjectResources(options.cwd) + ? await new DefaultResourceLoader({ + cwd: options.cwd, + agentDir: options.agentDir, + settingsManager, + extensionFactories: options.extensionFactories, + }).loadProjectTrustExtensions() + : undefined; + for (const error of extensionsResult?.errors ?? []) { + projectTrustWarnings.push(`Failed to load extension "${error.path}": ${error.error}`); + } + const projectTrusted = await resolveProjectTrusted({ + cwd: options.cwd, + trustStore, + trustOverride: options.projectTrustOverride, + defaultProjectTrust: settingsManager.getDefaultProjectTrust(), + extensionsResult, + projectTrustContext: createProjectTrustContext({ + cwd: options.cwd, + mode: appMode, + settingsManager, + hasUI: appMode === "interactive", + }), + onExtensionError: (message) => projectTrustWarnings.push(message), + }); + settingsManager.setProjectTrusted(projectTrusted); + return { settingsManager, projectTrustWarnings }; +} +export async function handleConfigCommand(args, runtimeOptions = {}) { + const [command, ...rest] = args; + if (command !== "config") { + return false; + } + if (rest.includes("-h") || rest.includes("--help")) { + printConfigCommandHelp(); + return true; + } + let local = false; + let projectTrustOverride; + for (const arg of rest) { + if (arg === "-l" || arg === "--local") { + local = true; + } + else if (arg === "-a" || arg === "--approve") { + projectTrustOverride = true; + } + else if (arg === "-na" || arg === "--no-approve") { + projectTrustOverride = false; + } + else if (arg.startsWith("-")) { + console.error(chalk.red(`Unknown option ${arg} for "config".`)); + console.error(chalk.dim(`Use "${APP_NAME} --help" or "${CONFIG_COMMAND_USAGE}".`)); + process.exitCode = 1; + return true; + } + else { + console.error(chalk.red(`Unexpected argument ${arg}.`)); + console.error(chalk.dim(`Usage: ${CONFIG_COMMAND_USAGE}`)); + process.exitCode = 1; + return true; + } + } + const cwd = process.cwd(); + const agentDir = getAgentDir(); + const { settingsManager, projectTrustWarnings } = await createCommandSettingsManager({ + cwd, + agentDir, + projectTrustOverride, + extensionFactories: runtimeOptions.extensionFactories, + }); + reportProjectTrustWarnings(projectTrustWarnings); + if (local && !settingsManager.isProjectTrusted()) { + console.error(chalk.red("Project is not trusted. Use --approve to modify local resource config.")); + process.exitCode = 1; + return true; + } + reportSettingsErrors(settingsManager, "config command"); + const globalSettingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false }); + const globalResolvedPaths = await new DefaultPackageManager({ + cwd, + agentDir, + settingsManager: globalSettingsManager, + }).resolve(); + const projectResolvedPaths = settingsManager.isProjectTrusted() + ? await new DefaultPackageManager({ cwd, agentDir, settingsManager }).resolve() + : globalResolvedPaths; + await selectConfig({ + resolvedPaths: { global: globalResolvedPaths, project: projectResolvedPaths }, + settingsManager, + cwd, + agentDir, + writeScope: local ? "project" : "global", + projectModeAvailable: settingsManager.isProjectTrusted(), + }); + process.exit(0); +} +export async function handlePackageCommand(args, runtimeOptions = {}) { + const options = parsePackageCommand(args); + if (!options) { + return false; + } + if (options.help) { + printPackageCommandHelp(options.command); + return true; + } + if (options.invalidOption) { + console.error(chalk.red(`Unknown option ${options.invalidOption} for "${options.command}".`)); + console.error(chalk.dim(`Use "${APP_NAME} --help" or "${getPackageCommandUsage(options.command)}".`)); + process.exitCode = 1; + return true; + } + if (options.missingOptionValue) { + console.error(chalk.red(`Missing value for ${options.missingOptionValue}.`)); + console.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`)); + process.exitCode = 1; + return true; + } + if (options.invalidArgument) { + console.error(chalk.red(`Unexpected argument ${options.invalidArgument}.`)); + console.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`)); + process.exitCode = 1; + return true; + } + if (options.conflictingOptions) { + console.error(chalk.red(options.conflictingOptions)); + console.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`)); + process.exitCode = 1; + return true; + } + const source = options.source; + if ((options.command === "install" || options.command === "remove") && !source) { + console.error(chalk.red(`Missing ${options.command} source.`)); + console.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`)); + process.exitCode = 1; + return true; + } + if (options.command === "update" && options.updateTarget?.type === "models") { + try { + await refreshModelCatalogs(getAgentDir()); + } + catch (error) { + const message = error instanceof Error ? error.message : "Unknown model catalog refresh error"; + console.error(chalk.red(`Error: ${message}`)); + process.exitCode = 1; + } + return true; + } + const cwd = process.cwd(); + const agentDir = getAgentDir(); + const writesProjectPackageConfig = (options.command === "install" || options.command === "remove") && options.local; + const { settingsManager, projectTrustWarnings } = await createCommandSettingsManager({ + cwd, + agentDir, + projectTrustOverride: options.projectTrustOverride, + useSavedProjectTrustOnly: options.command === "update", + extensionFactories: runtimeOptions.extensionFactories, + }); + reportProjectTrustWarnings(projectTrustWarnings); + if (!settingsManager.isProjectTrusted() && writesProjectPackageConfig) { + console.error(chalk.red("Project is not trusted. Use --approve to modify local package config.")); + process.exitCode = 1; + return true; + } + reportSettingsErrors(settingsManager, "package command"); + const selfUpdateNpmCommand = settingsManager.getGlobalSettings().npmCommand; + const packageManager = new DefaultPackageManager({ cwd, agentDir, settingsManager }); + packageManager.setProgressCallback((event) => { + if (event.type === "start") { + process.stdout.write(chalk.dim(`${event.message}\n`)); + } + }); + try { + switch (options.command) { + case "install": + await packageManager.installAndPersist(source, { local: options.local }); + console.log(chalk.green(`Installed ${source}`)); + return true; + case "remove": { + const removed = await packageManager.removeAndPersist(source, { local: options.local }); + if (!removed) { + console.error(chalk.red(`No matching package found for ${source}`)); + process.exitCode = 1; + return true; + } + console.log(chalk.green(`Removed ${source}`)); + return true; + } + case "list": { + const configuredPackages = packageManager.listConfiguredPackages(); + const userPackages = configuredPackages.filter((pkg) => pkg.scope === "user"); + const projectPackages = configuredPackages.filter((pkg) => pkg.scope === "project"); + if (configuredPackages.length === 0) { + console.log(chalk.dim("No packages installed.")); + return true; + } + const formatPackage = (pkg) => { + const display = pkg.filtered ? `${pkg.source} (filtered)` : pkg.source; + console.log(` ${display}`); + if (pkg.installedPath) { + console.log(chalk.dim(` ${pkg.installedPath}`)); + } + }; + if (userPackages.length > 0) { + console.log(chalk.bold("User packages:")); + for (const pkg of userPackages) { + formatPackage(pkg); + } + } + if (projectPackages.length > 0) { + if (userPackages.length > 0) + console.log(); + console.log(chalk.bold("Project packages:")); + for (const pkg of projectPackages) { + formatPackage(pkg); + } + } + return true; + } + case "update": { + const target = options.updateTarget ?? { type: "self" }; + if (options.showExtensionsSkippedNote) { + console.log(chalk.dim(`Extensions are skipped. Run ${APP_NAME} update --extensions to update extensions.`)); + } + if (updateTargetIncludesExtensions(target)) { + const updateSource = target.type === "extensions" ? target.source : undefined; + await packageManager.update(updateSource); + if (updateSource) { + console.log(chalk.green(`Updated ${updateSource}`)); + } + else { + console.log(chalk.green("Updated packages")); + } + } + if (updateTargetIncludesSelf(target)) { + const selfUpdatePlan = await getSelfUpdatePlan(options.force); + if (!selfUpdatePlan.shouldRun) { + return true; + } + const installMethod = detectInstallMethod(); + if (process.platform === "win32" && installMethod !== "npm" && installMethod !== "pnpm") { + console.error(chalk.red(`${APP_NAME} self-update on Windows is only supported for npm and pnpm installs.`)); + console.error(chalk.dim(`Detected install method: ${installMethod}. Update ${APP_NAME} manually.`)); + process.exitCode = 1; + return true; + } + const selfUpdateTarget = { + packageName: selfUpdatePlan.packageName, + installSpec: selfUpdatePlan.installSpec, + }; + const selfUpdateCommand = getSelfUpdateCommand(PACKAGE_NAME, selfUpdateNpmCommand, selfUpdateTarget); + if (!selfUpdateCommand) { + printSelfUpdateUnavailable(selfUpdateNpmCommand, selfUpdateTarget); + process.exitCode = 1; + return true; + } + if (selfUpdatePlan.note) { + printSelfUpdateNote(selfUpdatePlan.note); + } + try { + if (installMethod === "npm") { + prepareWindowsNpmSelfUpdate(); + } + await runSelfUpdate(selfUpdateCommand); + } + catch (error) { + const message = error instanceof Error ? error.message : "Unknown package command error"; + console.error(chalk.red(`Error: ${message}`)); + if (installMethod === "pnpm") { + printPnpmSelfUpdateMetadataHint(); + } + printSelfUpdateFallback(selfUpdateCommand); + process.exitCode = 1; + return true; + } + console.log(chalk.green(`Updated ${APP_NAME} from ${VERSION} to ${selfUpdatePlan.version}`)); + } + return true; + } + } + } + catch (error) { + const message = error instanceof Error ? error.message : "Unknown package command error"; + console.error(chalk.red(`Error: ${message}`)); + process.exitCode = 1; + return true; + } +} +//# sourceMappingURL=package-manager-cli.js.map \ No newline at end of file diff --git a/dist/package-manager-cli.js.map b/dist/package-manager-cli.js.map new file mode 100644 index 0000000..d0434d5 --- /dev/null +++ b/dist/package-manager-cli.js.map @@ -0,0 +1 @@ +{"version":3,"file":"package-manager-cli.js","sourceRoot":"","sources":["../src/package-manager-cli.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAsB,MAAM,wBAAwB,CAAC;AACtE,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EACN,QAAQ,EACR,eAAe,EACf,mBAAmB,EACnB,WAAW,EACX,aAAa,EACb,oBAAoB,EACpB,mCAAmC,EACnC,YAAY,EAGZ,OAAO,GACP,MAAM,aAA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rB,OAAO,IAAI,CAAC;IACb,CAAC;AAAA,CACD","sourcesContent":["import { join } from \"node:path\";\nimport { Markdown, type MarkdownTheme } from \"@earendil-works/pi-tui\";\nimport chalk from \"chalk\";\nimport { selectConfig } from \"./cli/config-selector.ts\";\nimport { createProjectTrustContext } from \"./cli/project-trust.ts\";\nimport {\n\tAPP_NAME,\n\tCONFIG_DIR_NAME,\n\tdetectInstallMethod,\n\tgetAgentDir,\n\tgetPackageDir,\n\tgetSelfUpdateCommand,\n\tgetSelfUpdateUnavailableInstruction,\n\tPACKAGE_NAME,\n\ttype SelfUpdateCommand,\n\ttype SelfUpdatePackageTarget,\n\tVERSION,\n} from \"./config.ts\";\nimport type { InlineExtension } from \"./core/extensions/types.ts\";\nimport { ModelRuntime } from \"./core/model-runtime.ts\";\nimport { DefaultPackageManager } from \"./core/package-manager.ts\";\nimport { type AppMode, resolveProjectTrusted } from \"./core/project-trust.ts\";\nimport { DefaultResourceLoader } from \"./core/resource-loader.ts\";\nimport { SettingsManager } from \"./core/settings-manager.ts\";\nimport { hasTrustRequiringProjectResources, ProjectTrustStore } from \"./core/trust-manager.ts\";\nimport { spawnProcess } from \"./utils/child-process.ts\";\nimport { getLatestPiRelease, isNewerPackageVersion } from \"./utils/version-check.ts\";\nimport {\n\tcleanupWindowsSelfUpdateQuarantine,\n\tquarantineWindowsNativeDependencies,\n} from \"./utils/windows-self-update.ts\";\n\nexport type PackageCommand = \"install\" | \"remove\" | \"update\" | \"list\";\n\ntype UpdateTarget = { type: \"all\" } | { type: \"self\" } | { type: \"extensions\"; source?: string } | { type: \"models\" };\n\nconst SELF_UPDATE_NOTE_MARKDOWN_THEME: MarkdownTheme = {\n\theading: (text) => chalk.bold(chalk.yellow(text)),\n\tlink: (text) => chalk.cyan(text),\n\tlinkUrl: (text) => chalk.dim(text),\n\tcode: (text) => chalk.yellow(text),\n\tcodeBlock: (text) => chalk.dim(text),\n\tcodeBlockBorder: (text) => chalk.dim(text),\n\tquote: (text) => chalk.dim(text),\n\tquoteBorder: (text) => chalk.dim(text),\n\thr: (text) => chalk.dim(text),\n\tlistBullet: (text) => chalk.yellow(text),\n\tbold: (text) => chalk.bold(text),\n\titalic: (text) => chalk.italic(text),\n\tstrikethrough: (text) => chalk.strikethrough(text),\n\tunderline: (text) => chalk.underline(text),\n};\n\ninterface PackageCommandOptions {\n\tcommand: PackageCommand;\n\tsource?: string;\n\tupdateTarget?: UpdateTarget;\n\tshowExtensionsSkippedNote: boolean;\n\tlocal: boolean;\n\tforce: boolean;\n\tprojectTrustOverride?: boolean;\n\thelp: boolean;\n\tinvalidOption?: string;\n\tinvalidArgument?: string;\n\tmissingOptionValue?: string;\n\tconflictingOptions?: string;\n}\n\nfunction reportSettingsErrors(settingsManager: SettingsManager, context: string): void {\n\tconst errors = settingsManager.drainErrors();\n\tfor (const { scope, error } of errors) {\n\t\tconsole.error(chalk.yellow(`Warning (${context}, ${scope} settings): ${error.message}`));\n\t\tif (error.stack) {\n\t\t\tconsole.error(chalk.dim(error.stack));\n\t\t}\n\t}\n}\n\nfunction getPackageCommandUsage(command: PackageCommand): string {\n\tswitch (command) {\n\t\tcase \"install\":\n\t\t\treturn `${APP_NAME} install [-l] [--approve|--no-approve]`;\n\t\tcase \"remove\":\n\t\t\treturn `${APP_NAME} remove [-l] [--approve|--no-approve]`;\n\t\tcase \"update\":\n\t\t\treturn `${APP_NAME} update [source|self|pi] [--self|--extensions|--models|--all] [--extension ] [--approve|--no-approve] [--force]`;\n\t\tcase \"list\":\n\t\t\treturn `${APP_NAME} list [--approve|--no-approve]`;\n\t}\n}\n\nconst CONFIG_COMMAND_USAGE = `${APP_NAME} config [-l] [--approve|--no-approve]`;\n\nfunction printConfigCommandHelp(): void {\n\tconsole.log(`${chalk.bold(\"Usage:\")}\n ${CONFIG_COMMAND_USAGE}\n\nOpen the resource configuration TUI to enable or disable package resources.\nWithout -l, starts in global settings (~/${CONFIG_DIR_NAME}/agent/settings.json).\nPress Tab in the TUI to switch between global and project-local modes.\n\nOptions:\n -l, --local Edit project overrides (${CONFIG_DIR_NAME}/settings.json)\n -a, --approve Trust project-local files for this command with -l\n -na, --no-approve Ignore project-local files for this command with -l\n`);\n}\n\nfunction printPackageCommandHelp(command: PackageCommand): void {\n\tswitch (command) {\n\t\tcase \"install\":\n\t\t\tconsole.log(`${chalk.bold(\"Usage:\")}\n ${getPackageCommandUsage(\"install\")}\n\nInstall a package and add it to settings.\n\nOptions:\n -l, --local Install project-locally (${CONFIG_DIR_NAME}/settings.json)\n -a, --approve Trust project-local files for this command\n -na, --no-approve Ignore project-local files for this command\n\nExamples:\n ${APP_NAME} install npm:@foo/bar\n ${APP_NAME} install git:github.com/user/repo\n ${APP_NAME} install git:git@github.com:user/repo\n ${APP_NAME} install https://github.com/user/repo\n ${APP_NAME} install ssh://git@github.com/user/repo\n ${APP_NAME} install ./local/path\n`);\n\t\t\treturn;\n\n\t\tcase \"remove\":\n\t\t\tconsole.log(`${chalk.bold(\"Usage:\")}\n ${getPackageCommandUsage(\"remove\")}\n\nRemove a package and its source from settings.\nAlias: ${APP_NAME} uninstall [-l]\n\nOptions:\n -l, --local Remove from project settings (${CONFIG_DIR_NAME}/settings.json)\n -a, --approve Trust project-local files for this command\n -na, --no-approve Ignore project-local files for this command\n\nExamples:\n ${APP_NAME} remove npm:@foo/bar\n ${APP_NAME} uninstall npm:@foo/bar\n`);\n\t\t\treturn;\n\n\t\tcase \"update\":\n\t\t\tconsole.log(`${chalk.bold(\"Usage:\")}\n ${getPackageCommandUsage(\"update\")}\n\nUpdate pi, installed packages, or model catalogs.\n\nOptions:\n --self Update pi only (default when no target is given)\n --extensions Update installed packages only\n --models Refresh model catalogs only\n --all Update pi and installed packages\n --extension Update one package only\n -a, --approve Trust project-local files for this command\n -na, --no-approve Ignore project-local files for this command\n --force Reinstall pi even if the current version is latest\n\nShort forms:\n ${APP_NAME} update Update pi only\n ${APP_NAME} update --all Update pi and all extensions\n ${APP_NAME} update --models Refresh model catalogs only\n ${APP_NAME} update Update one package\n ${APP_NAME} update pi Update pi only (self works as alias to pi)\n`);\n\t\t\treturn;\n\n\t\tcase \"list\":\n\t\t\tconsole.log(`${chalk.bold(\"Usage:\")}\n ${getPackageCommandUsage(\"list\")}\n\nList installed packages from user and project settings.\n\nOptions:\n -a, --approve Trust project-local files for this command\n -na, --no-approve Ignore project-local files for this command\n`);\n\t\t\treturn;\n\t}\n}\n\nfunction parsePackageCommand(args: string[]): PackageCommandOptions | undefined {\n\tconst [rawCommand, ...rest] = args;\n\tlet command: PackageCommand | undefined;\n\tif (rawCommand === \"uninstall\") {\n\t\tcommand = \"remove\";\n\t} else if (rawCommand === \"install\" || rawCommand === \"remove\" || rawCommand === \"update\" || rawCommand === \"list\") {\n\t\tcommand = rawCommand;\n\t}\n\tif (!command) {\n\t\treturn undefined;\n\t}\n\n\tlet local = false;\n\tlet force = false;\n\tlet projectTrustOverride: boolean | undefined;\n\tlet help = false;\n\tlet invalidOption: string | undefined;\n\tlet invalidArgument: string | undefined;\n\tlet missingOptionValue: string | undefined;\n\tlet conflictingOptions: string | undefined;\n\tlet source: string | undefined;\n\tlet selfFlag = false;\n\tlet extensionsFlag = false;\n\tlet modelsFlag = false;\n\tlet allFlag = false;\n\tlet extensionFlagSource: string | undefined;\n\n\tfor (let index = 0; index < rest.length; index++) {\n\t\tconst arg = rest[index];\n\t\tif (arg === \"-h\" || arg === \"--help\") {\n\t\t\thelp = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"-l\" || arg === \"--local\") {\n\t\t\tif (command === \"install\" || command === \"remove\") {\n\t\t\t\tlocal = true;\n\t\t\t} else {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--self\") {\n\t\t\tif (command === \"update\") {\n\t\t\t\tselfFlag = true;\n\t\t\t} else {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--extensions\") {\n\t\t\tif (command === \"update\") {\n\t\t\t\textensionsFlag = true;\n\t\t\t} else {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--models\") {\n\t\t\tif (command === \"update\") {\n\t\t\t\tmodelsFlag = true;\n\t\t\t} else {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--all\") {\n\t\t\tif (command === \"update\") {\n\t\t\t\tallFlag = true;\n\t\t\t} else {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--approve\" || arg === \"-a\") {\n\t\t\tprojectTrustOverride = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--no-approve\" || arg === \"-na\") {\n\t\t\tprojectTrustOverride = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--force\") {\n\t\t\tif (command === \"update\") {\n\t\t\t\tforce = true;\n\t\t\t} else {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg === \"--extension\") {\n\t\t\tif (command !== \"update\") {\n\t\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst value = rest[index + 1];\n\t\t\tif (!value || value.startsWith(\"-\")) {\n\t\t\t\tmissingOptionValue = missingOptionValue ?? arg;\n\t\t\t} else if (extensionFlagSource) {\n\t\t\t\tconflictingOptions = conflictingOptions ?? \"--extension can only be provided once\";\n\t\t\t\tindex++;\n\t\t\t} else {\n\t\t\t\textensionFlagSource = value;\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (arg.startsWith(\"-\")) {\n\t\t\tinvalidOption = invalidOption ?? arg;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!source) {\n\t\t\tsource = arg;\n\t\t} else {\n\t\t\tinvalidArgument = invalidArgument ?? arg;\n\t\t}\n\t}\n\n\tlet updateTarget: UpdateTarget | undefined;\n\tlet showExtensionsSkippedNote = false;\n\tif (command === \"update\") {\n\t\tif (allFlag && (selfFlag || extensionsFlag || modelsFlag || extensionFlagSource)) {\n\t\t\tconflictingOptions =\n\t\t\t\tconflictingOptions ?? \"--all cannot be combined with --self, --extensions, --models, or --extension\";\n\t\t}\n\t\tif (allFlag && source) {\n\t\t\tconflictingOptions = conflictingOptions ?? \"--all cannot be combined with a positional source\";\n\t\t}\n\n\t\tif (modelsFlag) {\n\t\t\tif (selfFlag || extensionsFlag || allFlag || extensionFlagSource) {\n\t\t\t\tconflictingOptions =\n\t\t\t\t\tconflictingOptions ?? \"--models cannot be combined with --self, --extensions, --all, or --extension\";\n\t\t\t}\n\t\t\tif (source) {\n\t\t\t\tconflictingOptions = conflictingOptions ?? \"--models cannot be combined with a positional source\";\n\t\t\t}\n\t\t\tupdateTarget = { type: \"models\" };\n\t\t} else if (extensionFlagSource) {\n\t\t\tif (selfFlag || extensionsFlag || allFlag) {\n\t\t\t\tconflictingOptions =\n\t\t\t\t\tconflictingOptions ?? \"--extension cannot be combined with --self, --extensions, or --all\";\n\t\t\t}\n\t\t\tif (source) {\n\t\t\t\tconflictingOptions = conflictingOptions ?? \"--extension cannot be combined with a positional source\";\n\t\t\t}\n\t\t\tupdateTarget = { type: \"extensions\", source: extensionFlagSource };\n\t\t} else if (source) {\n\t\t\tconst sourceIsSelf = source === \"self\" || source === \"pi\";\n\t\t\tif (sourceIsSelf) {\n\t\t\t\tupdateTarget = extensionsFlag ? { type: \"all\" } : { type: \"self\" };\n\t\t\t} else {\n\t\t\t\tif (extensionsFlag || selfFlag || allFlag) {\n\t\t\t\t\tconflictingOptions =\n\t\t\t\t\t\tconflictingOptions ??\n\t\t\t\t\t\t\"positional update targets cannot be combined with --self, --extensions, or --all\";\n\t\t\t\t}\n\t\t\t\tupdateTarget = { type: \"extensions\", source };\n\t\t\t}\n\t\t} else if (allFlag) {\n\t\t\tupdateTarget = { type: \"all\" };\n\t\t} else if (selfFlag && extensionsFlag) {\n\t\t\tupdateTarget = { type: \"all\" };\n\t\t} else if (selfFlag) {\n\t\t\tupdateTarget = { type: \"self\" };\n\t\t} else if (extensionsFlag) {\n\t\t\tupdateTarget = { type: \"extensions\" };\n\t\t} else {\n\t\t\tupdateTarget = { type: \"self\" };\n\t\t\tshowExtensionsSkippedNote = true;\n\t\t}\n\t}\n\n\treturn {\n\t\tcommand,\n\t\tsource,\n\t\tupdateTarget,\n\t\tshowExtensionsSkippedNote,\n\t\tlocal,\n\t\tforce,\n\t\tprojectTrustOverride,\n\t\thelp,\n\t\tinvalidOption,\n\t\tinvalidArgument,\n\t\tmissingOptionValue,\n\t\tconflictingOptions,\n\t};\n}\n\nfunction updateTargetIncludesSelf(target: UpdateTarget): boolean {\n\treturn target.type === \"all\" || target.type === \"self\";\n}\n\nfunction updateTargetIncludesExtensions(target: UpdateTarget): boolean {\n\treturn target.type === \"all\" || target.type === \"extensions\";\n}\n\nasync function refreshModelCatalogs(agentDir: string): Promise {\n\tconst modelRuntime = await ModelRuntime.create({\n\t\tauthPath: join(agentDir, \"auth.json\"),\n\t\tmodelsPath: join(agentDir, \"models.json\"),\n\t\tallowModelNetwork: false,\n\t});\n\tconst controller = new AbortController();\n\tconst timeout = setTimeout(() => controller.abort(), 15_000);\n\ttry {\n\t\tconst result = await modelRuntime.refresh({\n\t\t\tallowNetwork: true,\n\t\t\tforce: true,\n\t\t\tsignal: controller.signal,\n\t\t});\n\t\tif (result.aborted) {\n\t\t\tthrow new Error(\"Model catalog refresh timed out.\");\n\t\t}\n\t\tif (result.errors.size > 0) {\n\t\t\tconst details = Array.from(result.errors, ([provider, error]) => `${provider}: ${error.message}`).join(\"; \");\n\t\t\tthrow new Error(`Could not refresh model catalogs: ${details}`);\n\t\t}\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n\tconsole.log(chalk.green(\"Model catalogs refreshed\"));\n}\n\nfunction printSelfUpdateUnavailable(\n\tnpmCommand?: string[],\n\tupdatePackageTarget: SelfUpdatePackageTarget = PACKAGE_NAME,\n): void {\n\tconsole.error(`error: ${APP_NAME} cannot self-update this installation.`);\n\tconsole.error(getSelfUpdateUnavailableInstruction(PACKAGE_NAME, npmCommand, updatePackageTarget));\n\n\tconst entrypoint = process.argv[1];\n\tif (entrypoint) {\n\t\tconsole.error(\"\");\n\t\tconsole.error(`Location of pi executable: ${entrypoint}`);\n\t}\n}\n\nfunction printSelfUpdateFallback(command: SelfUpdateCommand): void {\n\tconsole.error(chalk.dim(`If this keeps failing, run this command yourself: ${command.display}`));\n}\n\nfunction printPnpmSelfUpdateMetadataHint(): void {\n\tconsole.error(chalk.yellow(\"If pnpm reports missing package versions, its cached registry metadata may be stale.\"));\n\tconsole.error(chalk.yellow(`Run \\`pnpm store prune\\` and retry \\`${APP_NAME} update --self\\`.`));\n}\n\nfunction printSelfUpdateNote(note: string): void {\n\tconst trimmedNote = note.trim();\n\tif (!trimmedNote) {\n\t\treturn;\n\t}\n\n\tconsole.log();\n\tconsole.log(chalk.bold(chalk.yellow(\"Update note\")));\n\ttry {\n\t\tconst width = Math.max(20, process.stdout.columns ?? 80);\n\t\tconst renderedLines = new Markdown(trimmedNote, 0, 0, SELF_UPDATE_NOTE_MARKDOWN_THEME)\n\t\t\t.render(width)\n\t\t\t.map((line) => line.trimEnd());\n\t\tconsole.log(renderedLines.join(\"\\n\"));\n\t} catch {\n\t\tconsole.log(trimmedNote);\n\t}\n\tconsole.log();\n}\n\ninterface SelfUpdatePlan {\n\tpackageName: string;\n\tinstallSpec: string;\n\tversion: string;\n\tshouldRun: boolean;\n\tnote?: string;\n}\n\nasync function getSelfUpdatePlan(force: boolean): Promise {\n\tlet latestRelease: Awaited>;\n\ttry {\n\t\tlatestRelease = await getLatestPiRelease(VERSION);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`Could not determine latest ${APP_NAME} version: ${message}`);\n\t}\n\tif (!latestRelease) {\n\t\tthrow new Error(`Could not determine latest ${APP_NAME} version.`);\n\t}\n\n\tconst packageName = latestRelease.packageName ?? PACKAGE_NAME;\n\tconst installSpec = `${packageName}@${latestRelease.version}`;\n\tif (force || packageName !== PACKAGE_NAME || isNewerPackageVersion(latestRelease.version, VERSION)) {\n\t\treturn {\n\t\t\tpackageName,\n\t\t\tinstallSpec,\n\t\t\tversion: latestRelease.version,\n\t\t\t...(latestRelease.note ? { note: latestRelease.note } : {}),\n\t\t\tshouldRun: true,\n\t\t};\n\t}\n\n\tconsole.log(chalk.green(`${APP_NAME} is already up to date (v${VERSION})`));\n\treturn { packageName, installSpec, version: latestRelease.version, shouldRun: false };\n}\n\nasync function runSelfUpdate(command: SelfUpdateCommand): Promise {\n\tconsole.log(chalk.dim(`Updating ${APP_NAME} with ${command.display}...`));\n\tfor (const step of command.steps ?? [command]) {\n\t\tawait new Promise((resolve, reject) => {\n\t\t\tconst child = spawnProcess(step.command, step.args, {\n\t\t\t\tstdio: \"inherit\",\n\t\t\t});\n\t\t\tchild.on(\"error\", (error) => {\n\t\t\t\treject(error);\n\t\t\t});\n\t\t\tchild.on(\"close\", (code, signal) => {\n\t\t\t\tif (code === 0) {\n\t\t\t\t\tresolve();\n\t\t\t\t} else if (signal) {\n\t\t\t\t\treject(new Error(`${step.display} terminated by signal ${signal}`));\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(`${step.display} exited with code ${code ?? \"unknown\"}`));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n}\n\nfunction prepareWindowsNpmSelfUpdate(): void {\n\tif (process.platform !== \"win32\") {\n\t\treturn;\n\t}\n\n\tconst packageDir = getPackageDir();\n\tcleanupWindowsSelfUpdateQuarantine(packageDir);\n\tquarantineWindowsNativeDependencies(packageDir);\n}\n\nexport interface PackageCommandRuntimeOptions {\n\textensionFactories?: InlineExtension[];\n}\n\ninterface CommandSettingsResult {\n\tsettingsManager: SettingsManager;\n\tprojectTrustWarnings: string[];\n}\n\nfunction getCommandAppMode(): AppMode {\n\treturn process.stdin.isTTY && process.stdout.isTTY ? \"interactive\" : \"print\";\n}\n\nfunction reportProjectTrustWarnings(warnings: readonly string[]): void {\n\tfor (const warning of warnings) {\n\t\tconsole.error(chalk.yellow(`Warning: ${warning}`));\n\t}\n}\n\nasync function createCommandSettingsManager(options: {\n\tcwd: string;\n\tagentDir: string;\n\tprojectTrustOverride?: boolean;\n\tuseSavedProjectTrustOnly?: boolean;\n\textensionFactories?: InlineExtension[];\n}): Promise {\n\tconst settingsManager = SettingsManager.create(options.cwd, options.agentDir, { projectTrusted: false });\n\tconst projectTrustWarnings: string[] = [];\n\tconst trustStore = new ProjectTrustStore(options.agentDir);\n\tif (options.useSavedProjectTrustOnly) {\n\t\tconst savedProjectTrusted = trustStore.get(options.cwd) === true;\n\t\tsettingsManager.setProjectTrusted(options.projectTrustOverride ?? savedProjectTrusted);\n\t\treturn { settingsManager, projectTrustWarnings };\n\t}\n\n\tconst appMode = getCommandAppMode();\n\tconst extensionsResult =\n\t\toptions.projectTrustOverride === undefined && hasTrustRequiringProjectResources(options.cwd)\n\t\t\t? await new DefaultResourceLoader({\n\t\t\t\t\tcwd: options.cwd,\n\t\t\t\t\tagentDir: options.agentDir,\n\t\t\t\t\tsettingsManager,\n\t\t\t\t\textensionFactories: options.extensionFactories,\n\t\t\t\t}).loadProjectTrustExtensions()\n\t\t\t: undefined;\n\tfor (const error of extensionsResult?.errors ?? []) {\n\t\tprojectTrustWarnings.push(`Failed to load extension \"${error.path}\": ${error.error}`);\n\t}\n\n\tconst projectTrusted = await resolveProjectTrusted({\n\t\tcwd: options.cwd,\n\t\ttrustStore,\n\t\ttrustOverride: options.projectTrustOverride,\n\t\tdefaultProjectTrust: settingsManager.getDefaultProjectTrust(),\n\t\textensionsResult,\n\t\tprojectTrustContext: createProjectTrustContext({\n\t\t\tcwd: options.cwd,\n\t\t\tmode: appMode,\n\t\t\tsettingsManager,\n\t\t\thasUI: appMode === \"interactive\",\n\t\t}),\n\t\tonExtensionError: (message) => projectTrustWarnings.push(message),\n\t});\n\tsettingsManager.setProjectTrusted(projectTrusted);\n\treturn { settingsManager, projectTrustWarnings };\n}\n\nexport async function handleConfigCommand(\n\targs: string[],\n\truntimeOptions: PackageCommandRuntimeOptions = {},\n): Promise {\n\tconst [command, ...rest] = args;\n\tif (command !== \"config\") {\n\t\treturn false;\n\t}\n\n\tif (rest.includes(\"-h\") || rest.includes(\"--help\")) {\n\t\tprintConfigCommandHelp();\n\t\treturn true;\n\t}\n\n\tlet local = false;\n\tlet projectTrustOverride: boolean | undefined;\n\tfor (const arg of rest) {\n\t\tif (arg === \"-l\" || arg === \"--local\") {\n\t\t\tlocal = true;\n\t\t} else if (arg === \"-a\" || arg === \"--approve\") {\n\t\t\tprojectTrustOverride = true;\n\t\t} else if (arg === \"-na\" || arg === \"--no-approve\") {\n\t\t\tprojectTrustOverride = false;\n\t\t} else if (arg.startsWith(\"-\")) {\n\t\t\tconsole.error(chalk.red(`Unknown option ${arg} for \"config\".`));\n\t\t\tconsole.error(chalk.dim(`Use \"${APP_NAME} --help\" or \"${CONFIG_COMMAND_USAGE}\".`));\n\t\t\tprocess.exitCode = 1;\n\t\t\treturn true;\n\t\t} else {\n\t\t\tconsole.error(chalk.red(`Unexpected argument ${arg}.`));\n\t\t\tconsole.error(chalk.dim(`Usage: ${CONFIG_COMMAND_USAGE}`));\n\t\t\tprocess.exitCode = 1;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst { settingsManager, projectTrustWarnings } = await createCommandSettingsManager({\n\t\tcwd,\n\t\tagentDir,\n\t\tprojectTrustOverride,\n\t\textensionFactories: runtimeOptions.extensionFactories,\n\t});\n\treportProjectTrustWarnings(projectTrustWarnings);\n\tif (local && !settingsManager.isProjectTrusted()) {\n\t\tconsole.error(chalk.red(\"Project is not trusted. Use --approve to modify local resource config.\"));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\treportSettingsErrors(settingsManager, \"config command\");\n\tconst globalSettingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\tconst globalResolvedPaths = await new DefaultPackageManager({\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager: globalSettingsManager,\n\t}).resolve();\n\tconst projectResolvedPaths = settingsManager.isProjectTrusted()\n\t\t? await new DefaultPackageManager({ cwd, agentDir, settingsManager }).resolve()\n\t\t: globalResolvedPaths;\n\n\tawait selectConfig({\n\t\tresolvedPaths: { global: globalResolvedPaths, project: projectResolvedPaths },\n\t\tsettingsManager,\n\t\tcwd,\n\t\tagentDir,\n\t\twriteScope: local ? \"project\" : \"global\",\n\t\tprojectModeAvailable: settingsManager.isProjectTrusted(),\n\t});\n\n\tprocess.exit(0);\n}\n\nexport async function handlePackageCommand(\n\targs: string[],\n\truntimeOptions: PackageCommandRuntimeOptions = {},\n): Promise {\n\tconst options = parsePackageCommand(args);\n\tif (!options) {\n\t\treturn false;\n\t}\n\n\tif (options.help) {\n\t\tprintPackageCommandHelp(options.command);\n\t\treturn true;\n\t}\n\n\tif (options.invalidOption) {\n\t\tconsole.error(chalk.red(`Unknown option ${options.invalidOption} for \"${options.command}\".`));\n\t\tconsole.error(chalk.dim(`Use \"${APP_NAME} --help\" or \"${getPackageCommandUsage(options.command)}\".`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\n\tif (options.missingOptionValue) {\n\t\tconsole.error(chalk.red(`Missing value for ${options.missingOptionValue}.`));\n\t\tconsole.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\n\tif (options.invalidArgument) {\n\t\tconsole.error(chalk.red(`Unexpected argument ${options.invalidArgument}.`));\n\t\tconsole.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\n\tif (options.conflictingOptions) {\n\t\tconsole.error(chalk.red(options.conflictingOptions));\n\t\tconsole.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\n\tconst source = options.source;\n\tif ((options.command === \"install\" || options.command === \"remove\") && !source) {\n\t\tconsole.error(chalk.red(`Missing ${options.command} source.`));\n\t\tconsole.error(chalk.dim(`Usage: ${getPackageCommandUsage(options.command)}`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\n\tif (options.command === \"update\" && options.updateTarget?.type === \"models\") {\n\t\ttry {\n\t\t\tawait refreshModelCatalogs(getAgentDir());\n\t\t} catch (error: unknown) {\n\t\t\tconst message = error instanceof Error ? error.message : \"Unknown model catalog refresh error\";\n\t\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\t\tprocess.exitCode = 1;\n\t\t}\n\t\treturn true;\n\t}\n\n\tconst cwd = process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst writesProjectPackageConfig = (options.command === \"install\" || options.command === \"remove\") && options.local;\n\tconst { settingsManager, projectTrustWarnings } = await createCommandSettingsManager({\n\t\tcwd,\n\t\tagentDir,\n\t\tprojectTrustOverride: options.projectTrustOverride,\n\t\tuseSavedProjectTrustOnly: options.command === \"update\",\n\t\textensionFactories: runtimeOptions.extensionFactories,\n\t});\n\treportProjectTrustWarnings(projectTrustWarnings);\n\tif (!settingsManager.isProjectTrusted() && writesProjectPackageConfig) {\n\t\tconsole.error(chalk.red(\"Project is not trusted. Use --approve to modify local package config.\"));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n\treportSettingsErrors(settingsManager, \"package command\");\n\tconst selfUpdateNpmCommand = settingsManager.getGlobalSettings().npmCommand;\n\n\tconst packageManager = new DefaultPackageManager({ cwd, agentDir, settingsManager });\n\n\tpackageManager.setProgressCallback((event) => {\n\t\tif (event.type === \"start\") {\n\t\t\tprocess.stdout.write(chalk.dim(`${event.message}\\n`));\n\t\t}\n\t});\n\n\ttry {\n\t\tswitch (options.command) {\n\t\t\tcase \"install\":\n\t\t\t\tawait packageManager.installAndPersist(source!, { local: options.local });\n\t\t\t\tconsole.log(chalk.green(`Installed ${source}`));\n\t\t\t\treturn true;\n\n\t\t\tcase \"remove\": {\n\t\t\t\tconst removed = await packageManager.removeAndPersist(source!, { local: options.local });\n\t\t\t\tif (!removed) {\n\t\t\t\t\tconsole.error(chalk.red(`No matching package found for ${source}`));\n\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tconsole.log(chalk.green(`Removed ${source}`));\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tcase \"list\": {\n\t\t\t\tconst configuredPackages = packageManager.listConfiguredPackages();\n\t\t\t\tconst userPackages = configuredPackages.filter((pkg) => pkg.scope === \"user\");\n\t\t\t\tconst projectPackages = configuredPackages.filter((pkg) => pkg.scope === \"project\");\n\n\t\t\t\tif (configuredPackages.length === 0) {\n\t\t\t\t\tconsole.log(chalk.dim(\"No packages installed.\"));\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\tconst formatPackage = (pkg: (typeof configuredPackages)[number]) => {\n\t\t\t\t\tconst display = pkg.filtered ? `${pkg.source} (filtered)` : pkg.source;\n\t\t\t\t\tconsole.log(` ${display}`);\n\t\t\t\t\tif (pkg.installedPath) {\n\t\t\t\t\t\tconsole.log(chalk.dim(` ${pkg.installedPath}`));\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tif (userPackages.length > 0) {\n\t\t\t\t\tconsole.log(chalk.bold(\"User packages:\"));\n\t\t\t\t\tfor (const pkg of userPackages) {\n\t\t\t\t\t\tformatPackage(pkg);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (projectPackages.length > 0) {\n\t\t\t\t\tif (userPackages.length > 0) console.log();\n\t\t\t\t\tconsole.log(chalk.bold(\"Project packages:\"));\n\t\t\t\t\tfor (const pkg of projectPackages) {\n\t\t\t\t\t\tformatPackage(pkg);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tcase \"update\": {\n\t\t\t\tconst target = options.updateTarget ?? { type: \"self\" };\n\t\t\t\tif (options.showExtensionsSkippedNote) {\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\tchalk.dim(`Extensions are skipped. Run ${APP_NAME} update --extensions to update extensions.`),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (updateTargetIncludesExtensions(target)) {\n\t\t\t\t\tconst updateSource = target.type === \"extensions\" ? target.source : undefined;\n\t\t\t\t\tawait packageManager.update(updateSource);\n\t\t\t\t\tif (updateSource) {\n\t\t\t\t\t\tconsole.log(chalk.green(`Updated ${updateSource}`));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(chalk.green(\"Updated packages\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (updateTargetIncludesSelf(target)) {\n\t\t\t\t\tconst selfUpdatePlan = await getSelfUpdatePlan(options.force);\n\t\t\t\t\tif (!selfUpdatePlan.shouldRun) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tconst installMethod = detectInstallMethod();\n\t\t\t\t\tif (process.platform === \"win32\" && installMethod !== \"npm\" && installMethod !== \"pnpm\") {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\tchalk.red(`${APP_NAME} self-update on Windows is only supported for npm and pnpm installs.`),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconsole.error(chalk.dim(`Detected install method: ${installMethod}. Update ${APP_NAME} manually.`));\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tconst selfUpdateTarget = {\n\t\t\t\t\t\tpackageName: selfUpdatePlan.packageName,\n\t\t\t\t\t\tinstallSpec: selfUpdatePlan.installSpec,\n\t\t\t\t\t};\n\t\t\t\t\tconst selfUpdateCommand = getSelfUpdateCommand(PACKAGE_NAME, selfUpdateNpmCommand, selfUpdateTarget);\n\t\t\t\t\tif (!selfUpdateCommand) {\n\t\t\t\t\t\tprintSelfUpdateUnavailable(selfUpdateNpmCommand, selfUpdateTarget);\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tif (selfUpdatePlan.note) {\n\t\t\t\t\t\tprintSelfUpdateNote(selfUpdatePlan.note);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (installMethod === \"npm\") {\n\t\t\t\t\t\t\tprepareWindowsNpmSelfUpdate();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait runSelfUpdate(selfUpdateCommand);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tconst message = error instanceof Error ? error.message : \"Unknown package command error\";\n\t\t\t\t\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\t\t\t\t\tif (installMethod === \"pnpm\") {\n\t\t\t\t\t\t\tprintPnpmSelfUpdateMetadataHint();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprintSelfUpdateFallback(selfUpdateCommand);\n\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tconsole.log(chalk.green(`Updated ${APP_NAME} from ${VERSION} to ${selfUpdatePlan.version}`));\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : \"Unknown package command error\";\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exitCode = 1;\n\t\treturn true;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/rpc-entry.d.ts b/dist/rpc-entry.d.ts new file mode 100644 index 0000000..294079a --- /dev/null +++ b/dist/rpc-entry.d.ts @@ -0,0 +1,3 @@ +#!/usr/bin/env node +export {}; +//# sourceMappingURL=rpc-entry.d.ts.map \ No newline at end of file diff --git a/dist/rpc-entry.d.ts.map b/dist/rpc-entry.d.ts.map new file mode 100644 index 0000000..7a64c18 --- /dev/null +++ b/dist/rpc-entry.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc-entry.d.ts","sourceRoot":"","sources":["../src/rpc-entry.ts"],"names":[],"mappings":"","sourcesContent":["#!/usr/bin/env node\nimport { APP_NAME } from \"./config.ts\";\nimport { configureHttpDispatcher } from \"./core/http-dispatcher.ts\";\nimport { main } from \"./main.ts\";\n\nprocess.title = `${APP_NAME}-rpc`;\nprocess.env.PI_CODING_AGENT = \"true\";\nprocess.emitWarning = (() => {}) as typeof process.emitWarning;\n\nconfigureHttpDispatcher();\n\nmain([\"--mode\", \"rpc\", ...process.argv.slice(2)]);\n"]} \ No newline at end of file diff --git a/dist/rpc-entry.js b/dist/rpc-entry.js new file mode 100755 index 0000000..3e07567 --- /dev/null +++ b/dist/rpc-entry.js @@ -0,0 +1,10 @@ +#!/usr/bin/env node +import { APP_NAME } from "./config.js"; +import { configureHttpDispatcher } from "./core/http-dispatcher.js"; +import { main } from "./main.js"; +process.title = `${APP_NAME}-rpc`; +process.env.PI_CODING_AGENT = "true"; +process.emitWarning = (() => { }); +configureHttpDispatcher(); +main(["--mode", "rpc", ...process.argv.slice(2)]); +//# sourceMappingURL=rpc-entry.js.map \ No newline at end of file diff --git a/dist/rpc-entry.js.map b/dist/rpc-entry.js.map new file mode 100644 index 0000000..92c1a0a --- /dev/null +++ b/dist/rpc-entry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rpc-entry.js","sourceRoot":"","sources":["../src/rpc-entry.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,CAAC,KAAK,GAAG,GAAG,QAAQ,MAAM,CAAC;AAClC,OAAO,CAAC,GAAG,CAAC,eAAe,GAAG,MAAM,CAAC;AACrC,OAAO,CAAC,WAAW,GAAG,CAAC,GAAG,EAAE,CAAC,EAAC,CAAC,CAA+B,CAAC;AAE/D,uBAAuB,EAAE,CAAC;AAE1B,IAAI,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { APP_NAME } from \"./config.ts\";\nimport { configureHttpDispatcher } from \"./core/http-dispatcher.ts\";\nimport { main } from \"./main.ts\";\n\nprocess.title = `${APP_NAME}-rpc`;\nprocess.env.PI_CODING_AGENT = \"true\";\nprocess.emitWarning = (() => {}) as typeof process.emitWarning;\n\nconfigureHttpDispatcher();\n\nmain([\"--mode\", \"rpc\", ...process.argv.slice(2)]);\n"]} \ No newline at end of file diff --git a/dist/utils/ansi.d.ts b/dist/utils/ansi.d.ts new file mode 100644 index 0000000..285b8b6 --- /dev/null +++ b/dist/utils/ansi.d.ts @@ -0,0 +1,2 @@ +export declare function stripAnsi(value: string): string; +//# sourceMappingURL=ansi.d.ts.map \ No newline at end of file diff --git a/dist/utils/ansi.d.ts.map b/dist/utils/ansi.d.ts.map new file mode 100644 index 0000000..8129ce1 --- /dev/null +++ b/dist/utils/ansi.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ansi.d.ts","sourceRoot":"","sources":["../../src/utils/ansi.ts"],"names":[],"mappings":"AA6CA,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAc/C","sourcesContent":["/*\n * Portions of this file are derived from:\n * - ansi-regex (https://github.com/chalk/ansi-regex)\n * - strip-ansi (https://github.com/chalk/strip-ansi)\n *\n * MIT License\n *\n * Copyright (c) Sindre Sorhus (https://sindresorhus.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nfunction ansiRegex({ onlyFirst = false }: { onlyFirst?: boolean } = {}): RegExp {\n\t// Valid string terminator sequences are BEL, ESC\\, and 0x9c\n\tconst ST = \"(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)\";\n\n\t// OSC sequences only: ESC ] ... ST (non-greedy until the first ST)\n\tconst osc = `(?:\\\\u001B\\\\][\\\\s\\\\S]*?${ST})`;\n\n\t// CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte\n\tconst csi = \"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:\\\\d{1,4}(?:[;:]\\\\d{0,4})*)?[\\\\dA-PR-TZcf-nq-uy=><~]\";\n\n\tconst pattern = `${osc}|${csi}`;\n\n\treturn new RegExp(pattern, onlyFirst ? undefined : \"g\");\n}\n\nconst regex = ansiRegex();\n\nexport function stripAnsi(value: string): string {\n\tif (typeof value !== \"string\") {\n\t\tthrow new TypeError(`Expected a \\`string\\`, got \\`${typeof value}\\``);\n\t}\n\n\t// Fast path: ANSI codes require ESC (7-bit) or CSI (8-bit) introducer\n\tif (!value.includes(\"\\u001B\") && !value.includes(\"\\u009B\")) {\n\t\treturn value;\n\t}\n\n\t// Even though the regex is global, we don't need to reset the `.lastIndex`\n\t// because unlike `.exec()` and `.test()`, `.replace()` does it automatically\n\t// and doing it manually has a performance penalty.\n\treturn value.replace(regex, \"\");\n}\n"]} \ No newline at end of file diff --git a/dist/utils/ansi.js b/dist/utils/ansi.js new file mode 100644 index 0000000..91ec3b4 --- /dev/null +++ b/dist/utils/ansi.js @@ -0,0 +1,52 @@ +/* + * Portions of this file are derived from: + * - ansi-regex (https://github.com/chalk/ansi-regex) + * - strip-ansi (https://github.com/chalk/strip-ansi) + * + * MIT License + * + * Copyright (c) Sindre Sorhus (https://sindresorhus.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +function ansiRegex({ onlyFirst = false } = {}) { + // Valid string terminator sequences are BEL, ESC\, and 0x9c + const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)"; + // OSC sequences only: ESC ] ... ST (non-greedy until the first ST) + const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`; + // CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte + const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]"; + const pattern = `${osc}|${csi}`; + return new RegExp(pattern, onlyFirst ? undefined : "g"); +} +const regex = ansiRegex(); +export function stripAnsi(value) { + if (typeof value !== "string") { + throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``); + } + // Fast path: ANSI codes require ESC (7-bit) or CSI (8-bit) introducer + if (!value.includes("\u001B") && !value.includes("\u009B")) { + return value; + } + // Even though the regex is global, we don't need to reset the `.lastIndex` + // because unlike `.exec()` and `.test()`, `.replace()` does it automatically + // and doing it manually has a performance penalty. + return value.replace(regex, ""); +} +//# sourceMappingURL=ansi.js.map \ No newline at end of file diff --git a/dist/utils/ansi.js.map b/dist/utils/ansi.js.map new file mode 100644 index 0000000..321a82c --- /dev/null +++ b/dist/utils/ansi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ansi.js","sourceRoot":"","sources":["../../src/utils/ansi.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,SAAS,SAAS,CAAC,EAAE,SAAS,GAAG,KAAK,EAAE,GAA4B,EAAE,EAAU;IAC/E,4DAA4D;IAC5D,MAAM,EAAE,GAAG,oCAAoC,CAAC;IAEhD,mEAAmE;IACnE,MAAM,GAAG,GAAG,0BAA0B,EAAE,GAAG,CAAC;IAE5C,sGAAsG;IACtG,MAAM,GAAG,GAAG,oFAAoF,CAAC;IAEjG,MAAM,OAAO,GAAG,GAAG,GAAG,IAAI,GAAG,EAAE,CAAC;IAEhC,OAAO,IAAI,MAAM,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAAA,CACxD;AAED,MAAM,KAAK,GAAG,SAAS,EAAE,CAAC;AAE1B,MAAM,UAAU,SAAS,CAAC,KAAa,EAAU;IAChD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC/B,MAAM,IAAI,SAAS,CAAC,gCAAgC,OAAO,KAAK,IAAI,CAAC,CAAC;IACvE,CAAC;IAED,sEAAsE;IACtE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAC;IACd,CAAC;IAED,2EAA2E;IAC3E,6EAA6E;IAC7E,mDAAmD;IACnD,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AAAA,CAChC","sourcesContent":["/*\n * Portions of this file are derived from:\n * - ansi-regex (https://github.com/chalk/ansi-regex)\n * - strip-ansi (https://github.com/chalk/strip-ansi)\n *\n * MIT License\n *\n * Copyright (c) Sindre Sorhus (https://sindresorhus.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nfunction ansiRegex({ onlyFirst = false }: { onlyFirst?: boolean } = {}): RegExp {\n\t// Valid string terminator sequences are BEL, ESC\\, and 0x9c\n\tconst ST = \"(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)\";\n\n\t// OSC sequences only: ESC ] ... ST (non-greedy until the first ST)\n\tconst osc = `(?:\\\\u001B\\\\][\\\\s\\\\S]*?${ST})`;\n\n\t// CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte\n\tconst csi = \"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:\\\\d{1,4}(?:[;:]\\\\d{0,4})*)?[\\\\dA-PR-TZcf-nq-uy=><~]\";\n\n\tconst pattern = `${osc}|${csi}`;\n\n\treturn new RegExp(pattern, onlyFirst ? undefined : \"g\");\n}\n\nconst regex = ansiRegex();\n\nexport function stripAnsi(value: string): string {\n\tif (typeof value !== \"string\") {\n\t\tthrow new TypeError(`Expected a \\`string\\`, got \\`${typeof value}\\``);\n\t}\n\n\t// Fast path: ANSI codes require ESC (7-bit) or CSI (8-bit) introducer\n\tif (!value.includes(\"\\u001B\") && !value.includes(\"\\u009B\")) {\n\t\treturn value;\n\t}\n\n\t// Even though the regex is global, we don't need to reset the `.lastIndex`\n\t// because unlike `.exec()` and `.test()`, `.replace()` does it automatically\n\t// and doing it manually has a performance penalty.\n\treturn value.replace(regex, \"\");\n}\n"]} \ No newline at end of file diff --git a/dist/utils/changelog.d.ts b/dist/utils/changelog.d.ts new file mode 100644 index 0000000..74fd5d3 --- /dev/null +++ b/dist/utils/changelog.d.ts @@ -0,0 +1,22 @@ +export interface ChangelogEntry { + major: number; + minor: number; + patch: number; + content: string; +} +export declare function normalizeChangelogLinks(markdown: string, version: string | ChangelogEntry): string; +/** + * Parse changelog entries from CHANGELOG.md + * Scans for ## lines and collects content until next ## or EOF + */ +export declare function parseChangelog(changelogPath: string): ChangelogEntry[]; +/** + * Compare versions. Returns: -1 if v1 < v2, 0 if v1 === v2, 1 if v1 > v2 + */ +export declare function compareVersions(v1: ChangelogEntry, v2: ChangelogEntry): number; +/** + * Get entries newer than lastVersion + */ +export declare function getNewEntries(entries: ChangelogEntry[], lastVersion: string): ChangelogEntry[]; +export { getChangelogPath } from "../config.ts"; +//# sourceMappingURL=changelog.d.ts.map \ No newline at end of file diff --git a/dist/utils/changelog.d.ts.map b/dist/utils/changelog.d.ts.map new file mode 100644 index 0000000..6258eda --- /dev/null +++ b/dist/utils/changelog.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"changelog.d.ts","sourceRoot":"","sources":["../../src/utils/changelog.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,cAAc;IAC9B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;CAChB;AA2FD,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,cAAc,GAAG,MAAM,CAKlG;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,aAAa,EAAE,MAAM,GAAG,cAAc,EAAE,CAyDtE;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,EAAE,EAAE,cAAc,EAAE,EAAE,EAAE,cAAc,GAAG,MAAM,CAI9E;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,cAAc,EAAE,EAAE,WAAW,EAAE,MAAM,GAAG,cAAc,EAAE,CAW9F;AAGD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["import path from \"node:path\";\nimport { existsSync, readFileSync } from \"fs\";\n\nexport interface ChangelogEntry {\n\tmajor: number;\n\tminor: number;\n\tpatch: number;\n\tcontent: string;\n}\n\nconst GITHUB_REPO = \"earendil-works/pi\";\nconst CHANGELOG_LINK_BASE_PATH = \"packages/coding-agent\";\nconst LEGACY_REPO_RE = /^https:\\/\\/github\\.com\\/(?:badlogic|earendil-works)\\/pi-mono(?=\\/|$)/;\nconst URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;\nconst INLINE_MARKDOWN_LINK_RE = /(!?\\[[^\\]\\n]+\\]\\()([^\\s)]+)((?:\\s+[^)]*)?\\))/g;\n\nfunction entryVersion(entry: ChangelogEntry): string {\n\treturn `${entry.major}.${entry.minor}.${entry.patch}`;\n}\n\nfunction normalizeTag(version: string | ChangelogEntry): string {\n\tconst versionString = typeof version === \"string\" ? version : entryVersion(version);\n\treturn versionString.startsWith(\"v\") ? versionString : `v${versionString}`;\n}\n\nfunction splitLocalTarget(target: string): { fragment: string; pathPart: string; query: string } {\n\tconst hashIndex = target.indexOf(\"#\");\n\tconst beforeHash = hashIndex === -1 ? target : target.slice(0, hashIndex);\n\tconst fragment = hashIndex === -1 ? \"\" : target.slice(hashIndex);\n\tconst queryIndex = beforeHash.indexOf(\"?\");\n\n\tif (queryIndex === -1) {\n\t\treturn { fragment, pathPart: beforeHash, query: \"\" };\n\t}\n\n\treturn {\n\t\tfragment,\n\t\tpathPart: beforeHash.slice(0, queryIndex),\n\t\tquery: beforeHash.slice(queryIndex),\n\t};\n}\n\nfunction normalizePathPart(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"/\");\n}\n\nfunction resolveRepositoryPath(targetPath: string): string | undefined {\n\tconst normalizedTarget = normalizePathPart(targetPath);\n\tconst joined = normalizedTarget.startsWith(\"/\")\n\t\t? path.posix.normalize(normalizedTarget.replace(/^\\/+/, \"\"))\n\t\t: path.posix.normalize(path.posix.join(CHANGELOG_LINK_BASE_PATH, normalizedTarget));\n\n\tif (joined === \".\" || joined.startsWith(\"../\") || joined === \"..\") {\n\t\treturn undefined;\n\t}\n\n\treturn joined;\n}\n\nfunction isDirectoryTarget(originalPath: string, repositoryPath: string): boolean {\n\tif (originalPath.endsWith(\"/\")) {\n\t\treturn true;\n\t}\n\n\tconst basename = path.posix.basename(repositoryPath);\n\treturn !basename.includes(\".\");\n}\n\nfunction normalizeChangelogLinkTarget(target: string, tag: string): string {\n\tlet canonicalTarget = target.replace(LEGACY_REPO_RE, `https://github.com/${GITHUB_REPO}`);\n\tconst repoUrl = `https://github.com/${GITHUB_REPO}`;\n\n\tfor (const route of [\"blob\", \"tree\"]) {\n\t\tfor (const branch of [\"main\", \"master\"]) {\n\t\t\tconst floatingRefPrefix = `${repoUrl}/${route}/${branch}/`;\n\t\t\tif (canonicalTarget.startsWith(floatingRefPrefix)) {\n\t\t\t\tcanonicalTarget = `${repoUrl}/${route}/${tag}/${canonicalTarget.slice(floatingRefPrefix.length)}`;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (canonicalTarget.startsWith(\"#\") || canonicalTarget.startsWith(\"//\") || URL_SCHEME_RE.test(canonicalTarget)) {\n\t\treturn canonicalTarget;\n\t}\n\n\tconst { fragment, pathPart, query } = splitLocalTarget(canonicalTarget);\n\tif (!pathPart) {\n\t\treturn canonicalTarget;\n\t}\n\n\tconst repositoryPath = resolveRepositoryPath(pathPart);\n\tif (!repositoryPath) {\n\t\treturn canonicalTarget;\n\t}\n\n\tconst route = isDirectoryTarget(pathPart, repositoryPath) ? \"tree\" : \"blob\";\n\treturn `https://github.com/${GITHUB_REPO}/${route}/${tag}/${encodeURI(repositoryPath)}${query}${fragment}`;\n}\n\nexport function normalizeChangelogLinks(markdown: string, version: string | ChangelogEntry): string {\n\tconst tag = normalizeTag(version);\n\treturn markdown.replace(INLINE_MARKDOWN_LINK_RE, (_match, prefix, target, suffix) => {\n\t\treturn `${prefix}${normalizeChangelogLinkTarget(target, tag)}${suffix}`;\n\t});\n}\n\n/**\n * Parse changelog entries from CHANGELOG.md\n * Scans for ## lines and collects content until next ## or EOF\n */\nexport function parseChangelog(changelogPath: string): ChangelogEntry[] {\n\tif (!existsSync(changelogPath)) {\n\t\treturn [];\n\t}\n\n\ttry {\n\t\tconst content = readFileSync(changelogPath, \"utf-8\");\n\t\tconst lines = content.split(\"\\n\");\n\t\tconst entries: ChangelogEntry[] = [];\n\n\t\tlet currentLines: string[] = [];\n\t\tlet currentVersion: { major: number; minor: number; patch: number } | null = null;\n\n\t\tfor (const line of lines) {\n\t\t\t// Check if this is a version header (## [x.y.z] ...)\n\t\t\tif (line.startsWith(\"## \")) {\n\t\t\t\t// Save previous entry if exists\n\t\t\t\tif (currentVersion && currentLines.length > 0) {\n\t\t\t\t\tentries.push({\n\t\t\t\t\t\t...currentVersion,\n\t\t\t\t\t\tcontent: currentLines.join(\"\\n\").trim(),\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Try to parse version from this line\n\t\t\t\tconst versionMatch = line.match(/##\\s+\\[?(\\d+)\\.(\\d+)\\.(\\d+)\\]?/);\n\t\t\t\tif (versionMatch) {\n\t\t\t\t\tcurrentVersion = {\n\t\t\t\t\t\tmajor: Number.parseInt(versionMatch[1], 10),\n\t\t\t\t\t\tminor: Number.parseInt(versionMatch[2], 10),\n\t\t\t\t\t\tpatch: Number.parseInt(versionMatch[3], 10),\n\t\t\t\t\t};\n\t\t\t\t\tcurrentLines = [line];\n\t\t\t\t} else {\n\t\t\t\t\t// Reset if we can't parse version\n\t\t\t\t\tcurrentVersion = null;\n\t\t\t\t\tcurrentLines = [];\n\t\t\t\t}\n\t\t\t} else if (currentVersion) {\n\t\t\t\t// Collect lines for current version\n\t\t\t\tcurrentLines.push(line);\n\t\t\t}\n\t\t}\n\n\t\t// Save last entry\n\t\tif (currentVersion && currentLines.length > 0) {\n\t\t\tentries.push({\n\t\t\t\t...currentVersion,\n\t\t\t\tcontent: currentLines.join(\"\\n\").trim(),\n\t\t\t});\n\t\t}\n\n\t\treturn entries;\n\t} catch (error) {\n\t\tconsole.error(`Warning: Could not parse changelog: ${error}`);\n\t\treturn [];\n\t}\n}\n\n/**\n * Compare versions. Returns: -1 if v1 < v2, 0 if v1 === v2, 1 if v1 > v2\n */\nexport function compareVersions(v1: ChangelogEntry, v2: ChangelogEntry): number {\n\tif (v1.major !== v2.major) return v1.major - v2.major;\n\tif (v1.minor !== v2.minor) return v1.minor - v2.minor;\n\treturn v1.patch - v2.patch;\n}\n\n/**\n * Get entries newer than lastVersion\n */\nexport function getNewEntries(entries: ChangelogEntry[], lastVersion: string): ChangelogEntry[] {\n\t// Parse lastVersion\n\tconst parts = lastVersion.split(\".\").map(Number);\n\tconst last: ChangelogEntry = {\n\t\tmajor: parts[0] || 0,\n\t\tminor: parts[1] || 0,\n\t\tpatch: parts[2] || 0,\n\t\tcontent: \"\",\n\t};\n\n\treturn entries.filter((entry) => compareVersions(entry, last) > 0);\n}\n\n// Re-export getChangelogPath from paths.ts for convenience\nexport { getChangelogPath } from \"../config.ts\";\n"]} \ No newline at end of file diff --git a/dist/utils/changelog.js b/dist/utils/changelog.js new file mode 100644 index 0000000..6bb1e3d --- /dev/null +++ b/dist/utils/changelog.js @@ -0,0 +1,165 @@ +import path from "node:path"; +import { existsSync, readFileSync } from "fs"; +const GITHUB_REPO = "earendil-works/pi"; +const CHANGELOG_LINK_BASE_PATH = "packages/coding-agent"; +const LEGACY_REPO_RE = /^https:\/\/github\.com\/(?:badlogic|earendil-works)\/pi-mono(?=\/|$)/; +const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i; +const INLINE_MARKDOWN_LINK_RE = /(!?\[[^\]\n]+\]\()([^\s)]+)((?:\s+[^)]*)?\))/g; +function entryVersion(entry) { + return `${entry.major}.${entry.minor}.${entry.patch}`; +} +function normalizeTag(version) { + const versionString = typeof version === "string" ? version : entryVersion(version); + return versionString.startsWith("v") ? versionString : `v${versionString}`; +} +function splitLocalTarget(target) { + const hashIndex = target.indexOf("#"); + const beforeHash = hashIndex === -1 ? target : target.slice(0, hashIndex); + const fragment = hashIndex === -1 ? "" : target.slice(hashIndex); + const queryIndex = beforeHash.indexOf("?"); + if (queryIndex === -1) { + return { fragment, pathPart: beforeHash, query: "" }; + } + return { + fragment, + pathPart: beforeHash.slice(0, queryIndex), + query: beforeHash.slice(queryIndex), + }; +} +function normalizePathPart(value) { + return value.replaceAll("\\", "/"); +} +function resolveRepositoryPath(targetPath) { + const normalizedTarget = normalizePathPart(targetPath); + const joined = normalizedTarget.startsWith("/") + ? path.posix.normalize(normalizedTarget.replace(/^\/+/, "")) + : path.posix.normalize(path.posix.join(CHANGELOG_LINK_BASE_PATH, normalizedTarget)); + if (joined === "." || joined.startsWith("../") || joined === "..") { + return undefined; + } + return joined; +} +function isDirectoryTarget(originalPath, repositoryPath) { + if (originalPath.endsWith("/")) { + return true; + } + const basename = path.posix.basename(repositoryPath); + return !basename.includes("."); +} +function normalizeChangelogLinkTarget(target, tag) { + let canonicalTarget = target.replace(LEGACY_REPO_RE, `https://github.com/${GITHUB_REPO}`); + const repoUrl = `https://github.com/${GITHUB_REPO}`; + for (const route of ["blob", "tree"]) { + for (const branch of ["main", "master"]) { + const floatingRefPrefix = `${repoUrl}/${route}/${branch}/`; + if (canonicalTarget.startsWith(floatingRefPrefix)) { + canonicalTarget = `${repoUrl}/${route}/${tag}/${canonicalTarget.slice(floatingRefPrefix.length)}`; + } + } + } + if (canonicalTarget.startsWith("#") || canonicalTarget.startsWith("//") || URL_SCHEME_RE.test(canonicalTarget)) { + return canonicalTarget; + } + const { fragment, pathPart, query } = splitLocalTarget(canonicalTarget); + if (!pathPart) { + return canonicalTarget; + } + const repositoryPath = resolveRepositoryPath(pathPart); + if (!repositoryPath) { + return canonicalTarget; + } + const route = isDirectoryTarget(pathPart, repositoryPath) ? "tree" : "blob"; + return `https://github.com/${GITHUB_REPO}/${route}/${tag}/${encodeURI(repositoryPath)}${query}${fragment}`; +} +export function normalizeChangelogLinks(markdown, version) { + const tag = normalizeTag(version); + return markdown.replace(INLINE_MARKDOWN_LINK_RE, (_match, prefix, target, suffix) => { + return `${prefix}${normalizeChangelogLinkTarget(target, tag)}${suffix}`; + }); +} +/** + * Parse changelog entries from CHANGELOG.md + * Scans for ## lines and collects content until next ## or EOF + */ +export function parseChangelog(changelogPath) { + if (!existsSync(changelogPath)) { + return []; + } + try { + const content = readFileSync(changelogPath, "utf-8"); + const lines = content.split("\n"); + const entries = []; + let currentLines = []; + let currentVersion = null; + for (const line of lines) { + // Check if this is a version header (## [x.y.z] ...) + if (line.startsWith("## ")) { + // Save previous entry if exists + if (currentVersion && currentLines.length > 0) { + entries.push({ + ...currentVersion, + content: currentLines.join("\n").trim(), + }); + } + // Try to parse version from this line + const versionMatch = line.match(/##\s+\[?(\d+)\.(\d+)\.(\d+)\]?/); + if (versionMatch) { + currentVersion = { + major: Number.parseInt(versionMatch[1], 10), + minor: Number.parseInt(versionMatch[2], 10), + patch: Number.parseInt(versionMatch[3], 10), + }; + currentLines = [line]; + } + else { + // Reset if we can't parse version + currentVersion = null; + currentLines = []; + } + } + else if (currentVersion) { + // Collect lines for current version + currentLines.push(line); + } + } + // Save last entry + if (currentVersion && currentLines.length > 0) { + entries.push({ + ...currentVersion, + content: currentLines.join("\n").trim(), + }); + } + return entries; + } + catch (error) { + console.error(`Warning: Could not parse changelog: ${error}`); + return []; + } +} +/** + * Compare versions. Returns: -1 if v1 < v2, 0 if v1 === v2, 1 if v1 > v2 + */ +export function compareVersions(v1, v2) { + if (v1.major !== v2.major) + return v1.major - v2.major; + if (v1.minor !== v2.minor) + return v1.minor - v2.minor; + return v1.patch - v2.patch; +} +/** + * Get entries newer than lastVersion + */ +export function getNewEntries(entries, lastVersion) { + // Parse lastVersion + const parts = lastVersion.split(".").map(Number); + const last = { + major: parts[0] || 0, + minor: parts[1] || 0, + patch: parts[2] || 0, + content: "", + }; + return entries.filter((entry) => compareVersions(entry, last) > 0); +} +// Re-export getChangelogPath from paths.ts for convenience +export { getChangelogPath } from "../config.js"; +//# sourceMappingURL=changelog.js.map \ No newline at end of file diff --git a/dist/utils/changelog.js.map b/dist/utils/changelog.js.map new file mode 100644 index 0000000..c57c9ee --- /dev/null +++ b/dist/utils/changelog.js.map @@ -0,0 +1 @@ +{"version":3,"file":"changelog.js","s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AAM,UAAU,eAAe,CAAC,EAAkB,EAAE,EAAkB,EAAU;IAC/E,IAAI,EAAE,CAAC,KAAK,KAAK,EAAE,CAAC,KAAK;QAAE,OAAO,EAAE,CAAC,KAAK,GAAG,EAAE,CAAC,KAAK,CAAC;IACtD,IAAI,EAAE,CAAC,KAAK,KAAK,EAAE,CAAC,KAAK;QAAE,OAAO,EAAE,CAAC,KAAK,GAAG,EAAE,CAAC,KAAK,CAAC;IACtD,OAAO,EAAE,CAAC,KAAK,GAAG,EAAE,CAAC,KAAK,CAAC;AAAA,CAC3B;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,OAAyB,EAAE,WAAmB,EAAoB;IAC/F,oBAAoB;IACpB,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACjD,MAAM,IAAI,GAAmB;QAC5B,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;QACpB,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;QACpB,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;QACpB,OAAO,EAAE,EAAE;KACX,CAAC;IAEF,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAAA,CACnE;AAED,2DAA2D;AAC3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["import path from \"node:path\";\nimport { existsSync, readFileSync } from \"fs\";\n\nexport interface ChangelogEntry {\n\tmajor: number;\n\tminor: number;\n\tpatch: number;\n\tcontent: string;\n}\n\nconst GITHUB_REPO = \"earendil-works/pi\";\nconst CHANGELOG_LINK_BASE_PATH = \"packages/coding-agent\";\nconst LEGACY_REPO_RE = /^https:\\/\\/github\\.com\\/(?:badlogic|earendil-works)\\/pi-mono(?=\\/|$)/;\nconst URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;\nconst INLINE_MARKDOWN_LINK_RE = /(!?\\[[^\\]\\n]+\\]\\()([^\\s)]+)((?:\\s+[^)]*)?\\))/g;\n\nfunction entryVersion(entry: ChangelogEntry): string {\n\treturn `${entry.major}.${entry.minor}.${entry.patch}`;\n}\n\nfunction normalizeTag(version: string | ChangelogEntry): string {\n\tconst versionString = typeof version === \"string\" ? version : entryVersion(version);\n\treturn versionString.startsWith(\"v\") ? versionString : `v${versionString}`;\n}\n\nfunction splitLocalTarget(target: string): { fragment: string; pathPart: string; query: string } {\n\tconst hashIndex = target.indexOf(\"#\");\n\tconst beforeHash = hashIndex === -1 ? target : target.slice(0, hashIndex);\n\tconst fragment = hashIndex === -1 ? \"\" : target.slice(hashIndex);\n\tconst queryIndex = beforeHash.indexOf(\"?\");\n\n\tif (queryIndex === -1) {\n\t\treturn { fragment, pathPart: beforeHash, query: \"\" };\n\t}\n\n\treturn {\n\t\tfragment,\n\t\tpathPart: beforeHash.slice(0, queryIndex),\n\t\tquery: beforeHash.slice(queryIndex),\n\t};\n}\n\nfunction normalizePathPart(value: string): string {\n\treturn value.replaceAll(\"\\\\\", \"/\");\n}\n\nfunction resolveRepositoryPath(targetPath: string): string | undefined {\n\tconst normalizedTarget = normalizePathPart(targetPath);\n\tconst joined = normalizedTarget.startsWith(\"/\")\n\t\t? path.posix.normalize(normalizedTarget.replace(/^\\/+/, \"\"))\n\t\t: path.posix.normalize(path.posix.join(CHANGELOG_LINK_BASE_PATH, normalizedTarget));\n\n\tif (joined === \".\" || joined.startsWith(\"../\") || joined === \"..\") {\n\t\treturn undefined;\n\t}\n\n\treturn joined;\n}\n\nfunction isDirectoryTarget(originalPath: string, repositoryPath: string): boolean {\n\tif (originalPath.endsWith(\"/\")) {\n\t\treturn true;\n\t}\n\n\tconst basename = path.posix.basename(repositoryPath);\n\treturn !basename.includes(\".\");\n}\n\nfunction normalizeChangelogLinkTarget(target: string, tag: string): string {\n\tlet canonicalTarget = target.replace(LEGACY_REPO_RE, `https://github.com/${GITHUB_REPO}`);\n\tconst repoUrl = `https://github.com/${GITHUB_REPO}`;\n\n\tfor (const route of [\"blob\", \"tree\"]) {\n\t\tfor (const branch of [\"main\", \"master\"]) {\n\t\t\tconst floatingRefPrefix = `${repoUrl}/${route}/${branch}/`;\n\t\t\tif (canonicalTarget.startsWith(floatingRefPrefix)) {\n\t\t\t\tcanonicalTarget = `${repoUrl}/${route}/${tag}/${canonicalTarget.slice(floatingRefPrefix.length)}`;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (canonicalTarget.startsWith(\"#\") || canonicalTarget.startsWith(\"//\") || URL_SCHEME_RE.test(canonicalTarget)) {\n\t\treturn canonicalTarget;\n\t}\n\n\tconst { fragment, pathPart, query } = splitLocalTarget(canonicalTarget);\n\tif (!pathPart) {\n\t\treturn canonicalTarget;\n\t}\n\n\tconst repositoryPath = resolveRepositoryPath(pathPart);\n\tif (!repositoryPath) {\n\t\treturn canonicalTarget;\n\t}\n\n\tconst route = isDirectoryTarget(pathPart, repositoryPath) ? \"tree\" : \"blob\";\n\treturn `https://github.com/${GITHUB_REPO}/${route}/${tag}/${encodeURI(repositoryPath)}${query}${fragment}`;\n}\n\nexport function normalizeChangelogLinks(markdown: string, version: string | ChangelogEntry): string {\n\tconst tag = normalizeTag(version);\n\treturn markdown.replace(INLINE_MARKDOWN_LINK_RE, (_match, prefix, target, suffix) => {\n\t\treturn `${prefix}${normalizeChangelogLinkTarget(target, tag)}${suffix}`;\n\t});\n}\n\n/**\n * Parse changelog entries from CHANGELOG.md\n * Scans for ## lines and collects content until next ## or EOF\n */\nexport function parseChangelog(changelogPath: string): ChangelogEntry[] {\n\tif (!existsSync(changelogPath)) {\n\t\treturn [];\n\t}\n\n\ttry {\n\t\tconst content = readFileSync(changelogPath, \"utf-8\");\n\t\tconst lines = content.split(\"\\n\");\n\t\tconst entries: ChangelogEntry[] = [];\n\n\t\tlet currentLines: string[] = [];\n\t\tlet currentVersion: { major: number; minor: number; patch: number } | null = null;\n\n\t\tfor (const line of lines) {\n\t\t\t// Check if this is a version header (## [x.y.z] ...)\n\t\t\tif (line.startsWith(\"## \")) {\n\t\t\t\t// Save previous entry if exists\n\t\t\t\tif (currentVersion && currentLines.length > 0) {\n\t\t\t\t\tentries.push({\n\t\t\t\t\t\t...currentVersion,\n\t\t\t\t\t\tcontent: currentLines.join(\"\\n\").trim(),\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Try to parse version from this line\n\t\t\t\tconst versionMatch = line.match(/##\\s+\\[?(\\d+)\\.(\\d+)\\.(\\d+)\\]?/);\n\t\t\t\tif (versionMatch) {\n\t\t\t\t\tcurrentVersion = {\n\t\t\t\t\t\tmajor: Number.parseInt(versionMatch[1], 10),\n\t\t\t\t\t\tminor: Number.parseInt(versionMatch[2], 10),\n\t\t\t\t\t\tpatch: Number.parseInt(versionMatch[3], 10),\n\t\t\t\t\t};\n\t\t\t\t\tcurrentLines = [line];\n\t\t\t\t} else {\n\t\t\t\t\t// Reset if we can't parse version\n\t\t\t\t\tcurrentVersion = null;\n\t\t\t\t\tcurrentLines = [];\n\t\t\t\t}\n\t\t\t} else if (currentVersion) {\n\t\t\t\t// Collect lines for current version\n\t\t\t\tcurrentLines.push(line);\n\t\t\t}\n\t\t}\n\n\t\t// Save last entry\n\t\tif (currentVersion && currentLines.length > 0) {\n\t\t\tentries.push({\n\t\t\t\t...currentVersion,\n\t\t\t\tcontent: currentLines.join(\"\\n\").trim(),\n\t\t\t});\n\t\t}\n\n\t\treturn entries;\n\t} catch (error) {\n\t\tconsole.error(`Warning: Could not parse changelog: ${error}`);\n\t\treturn [];\n\t}\n}\n\n/**\n * Compare versions. Returns: -1 if v1 < v2, 0 if v1 === v2, 1 if v1 > v2\n */\nexport function compareVersions(v1: ChangelogEntry, v2: ChangelogEntry): number {\n\tif (v1.major !== v2.major) return v1.major - v2.major;\n\tif (v1.minor !== v2.minor) return v1.minor - v2.minor;\n\treturn v1.patch - v2.patch;\n}\n\n/**\n * Get entries newer than lastVersion\n */\nexport function getNewEntries(entries: ChangelogEntry[], lastVersion: string): ChangelogEntry[] {\n\t// Parse lastVersion\n\tconst parts = lastVersion.split(\".\").map(Number);\n\tconst last: ChangelogEntry = {\n\t\tmajor: parts[0] || 0,\n\t\tminor: parts[1] || 0,\n\t\tpatch: parts[2] || 0,\n\t\tcontent: \"\",\n\t};\n\n\treturn entries.filter((entry) => compareVersions(entry, last) > 0);\n}\n\n// Re-export getChangelogPath from paths.ts for convenience\nexport { getChangelogPath } from \"../config.ts\";\n"]} \ No newline at end of file diff --git a/dist/utils/child-process.d.ts b/dist/utils/child-process.d.ts new file mode 100644 index 0000000..c75b42d --- /dev/null +++ b/dist/utils/child-process.d.ts @@ -0,0 +1,18 @@ +import { type ChildProcess, type ChildProcessByStdio, type SpawnOptions, type SpawnOptionsWithStdioTuple, type SpawnSyncOptionsWithStringEncoding, type SpawnSyncReturns, type StdioNull, type StdioPipe } from "node:child_process"; +import type { Readable } from "node:stream"; +export declare function spawnProcess(command: string, args: string[], options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; +export declare function spawnProcess(command: string, args: string[], options: SpawnOptions): ChildProcess; +export declare function spawnProcessSync(command: string, args: string[], options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; +/** + * Wait for a child process to terminate without hanging on inherited stdio handles. + * + * A short-lived child can `exit` while a detached descendant keeps its stdout/stderr + * pipe open. We must not resolve and destroy the streams on a fixed deadline measured + * from `exit`, or output still being written past that deadline is silently lost + * (earendil-works/pi#5303). Instead, after `exit` we wait for the pipes to fall idle: + * the grace timer is re-armed on every chunk, so an actively writing descendant keeps + * us reading, while a quiet inherited handle (e.g. a Windows daemonized descendant + * that never lets `close` fire) still releases us after the grace elapses. + */ +export declare function waitForChildProcess(child: ChildProcess): Promise; +//# sourceMappingURL=child-process.d.ts.map \ No newline at end of file diff --git a/dist/utils/child-process.d.ts.map b/dist/utils/child-process.d.ts.map new file mode 100644 index 0000000..3ad5948 --- /dev/null +++ b/dist/utils/child-process.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"child-process.d.ts","sourceRoot":"","sources":["../../src/utils/child-process.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,mBAAmB,EAGxB,KAAK,YAAY,EACjB,KAAK,0BAA0B,EAC/B,KAAK,kCAAkC,EACvC,KAAK,gBAAgB,EACrB,KAAK,SAAS,EACd,KAAK,SAAS,EACd,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAK5C,wBAAgB,YAAY,CAC3B,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,EAAE,0BAA0B,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC,GAClE,mBAAmB,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;AACjD,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,YAAY,GAAG,YAAY,CAAC;AAKnG,wBAAgB,gBAAgB,CAC/B,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,EAAE,kCAAkC,GACzC,gBAAgB,CAAC,MAAM,CAAC,CAI1B;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAwF/E","sourcesContent":["import {\n\ttype ChildProcess,\n\ttype ChildProcessByStdio,\n\tspawn as nodeSpawn,\n\tspawnSync as nodeSpawnSync,\n\ttype SpawnOptions,\n\ttype SpawnOptionsWithStdioTuple,\n\ttype SpawnSyncOptionsWithStringEncoding,\n\ttype SpawnSyncReturns,\n\ttype StdioNull,\n\ttype StdioPipe,\n} from \"node:child_process\";\nimport type { Readable } from \"node:stream\";\nimport crossSpawn from \"cross-spawn\";\n\nconst EXIT_STDIO_GRACE_MS = 100;\n\nexport function spawnProcess(\n\tcommand: string,\n\targs: string[],\n\toptions: SpawnOptionsWithStdioTuple,\n): ChildProcessByStdio;\nexport function spawnProcess(command: string, args: string[], options: SpawnOptions): ChildProcess;\nexport function spawnProcess(command: string, args: string[], options: SpawnOptions): ChildProcess {\n\treturn process.platform === \"win32\" ? crossSpawn(command, args, options) : nodeSpawn(command, args, options);\n}\n\nexport function spawnProcessSync(\n\tcommand: string,\n\targs: string[],\n\toptions: SpawnSyncOptionsWithStringEncoding,\n): SpawnSyncReturns {\n\treturn process.platform === \"win32\"\n\t\t? crossSpawn.sync(command, args, options)\n\t\t: nodeSpawnSync(command, args, options);\n}\n\n/**\n * Wait for a child process to terminate without hanging on inherited stdio handles.\n *\n * A short-lived child can `exit` while a detached descendant keeps its stdout/stderr\n * pipe open. We must not resolve and destroy the streams on a fixed deadline measured\n * from `exit`, or output still being written past that deadline is silently lost\n * (earendil-works/pi#5303). Instead, after `exit` we wait for the pipes to fall idle:\n * the grace timer is re-armed on every chunk, so an actively writing descendant keeps\n * us reading, while a quiet inherited handle (e.g. a Windows daemonized descendant\n * that never lets `close` fire) still releases us after the grace elapses.\n */\nexport function waitForChildProcess(child: ChildProcess): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet exited = false;\n\t\tlet exitCode: number | null = null;\n\t\tlet postExitTimer: NodeJS.Timeout | undefined;\n\t\tlet stdoutEnded = child.stdout === null;\n\t\tlet stderrEnded = child.stderr === null;\n\n\t\tconst cleanup = () => {\n\t\t\tif (postExitTimer) {\n\t\t\t\tclearTimeout(postExitTimer);\n\t\t\t\tpostExitTimer = undefined;\n\t\t\t}\n\t\t\tchild.removeListener(\"error\", onError);\n\t\t\tchild.removeListener(\"exit\", onExit);\n\t\t\tchild.removeListener(\"close\", onClose);\n\t\t\tchild.stdout?.removeListener(\"end\", onStdoutEnd);\n\t\t\tchild.stderr?.removeListener(\"end\", onStderrEnd);\n\t\t\tchild.stdout?.removeListener(\"data\", onData);\n\t\t\tchild.stderr?.removeListener(\"data\", onData);\n\t\t};\n\n\t\tconst finalize = (code: number | null) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tchild.stdout?.destroy();\n\t\t\tchild.stderr?.destroy();\n\t\t\tresolve(code);\n\t\t};\n\n\t\tconst maybeFinalizeAfterExit = () => {\n\t\t\tif (!exited || settled) return;\n\t\t\tif (stdoutEnded && stderrEnded) {\n\t\t\t\tfinalize(exitCode);\n\t\t\t}\n\t\t};\n\n\t\tconst armIdleTimer = () => {\n\t\t\tif (postExitTimer) clearTimeout(postExitTimer);\n\t\t\tpostExitTimer = setTimeout(() => finalize(exitCode), EXIT_STDIO_GRACE_MS);\n\t\t};\n\n\t\tconst onData = () => {\n\t\t\t// Output is still arriving after exit; defer finalizing so we don't\n\t\t\t// destroy the stream mid-write and truncate the tail.\n\t\t\tif (exited && !settled) armIdleTimer();\n\t\t};\n\n\t\tconst onStdoutEnd = () => {\n\t\t\tstdoutEnded = true;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t};\n\n\t\tconst onStderrEnd = () => {\n\t\t\tstderrEnded = true;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t};\n\n\t\tconst onError = (err: Error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(err);\n\t\t};\n\n\t\tconst onExit = (code: number | null) => {\n\t\t\texited = true;\n\t\t\texitCode = code;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t\tif (!settled) {\n\t\t\t\tarmIdleTimer();\n\t\t\t}\n\t\t};\n\n\t\tconst onClose = (code: number | null) => {\n\t\t\tfinalize(code);\n\t\t};\n\n\t\tchild.stdout?.once(\"end\", onStdoutEnd);\n\t\tchild.stderr?.once(\"end\", onStderrEnd);\n\t\tchild.stdout?.on(\"data\", onData);\n\t\tchild.stderr?.on(\"data\", onData);\n\t\tchild.once(\"error\", onError);\n\t\tchild.once(\"exit\", onExit);\n\t\tchild.once(\"close\", onClose);\n\t});\n}\n"]} \ No newline at end of file diff --git a/dist/utils/child-process.js b/dist/utils/child-process.js new file mode 100644 index 0000000..48e5724 --- /dev/null +++ b/dist/utils/child-process.js @@ -0,0 +1,106 @@ +import { spawn as nodeSpawn, spawnSync as nodeSpawnSync, } from "node:child_process"; +import crossSpawn from "cross-spawn"; +const EXIT_STDIO_GRACE_MS = 100; +export function spawnProcess(command, args, options) { + return process.platform === "win32" ? crossSpawn(command, args, options) : nodeSpawn(command, args, options); +} +export function spawnProcessSync(command, args, options) { + return process.platform === "win32" + ? crossSpawn.sync(command, args, options) + : nodeSpawnSync(command, args, options); +} +/** + * Wait for a child process to terminate without hanging on inherited stdio handles. + * + * A short-lived child can `exit` while a detached descendant keeps its stdout/stderr + * pipe open. We must not resolve and destroy the streams on a fixed deadline measured + * from `exit`, or output still being written past that deadline is silently lost + * (earendil-works/pi#5303). Instead, after `exit` we wait for the pipes to fall idle: + * the grace timer is re-armed on every chunk, so an actively writing descendant keeps + * us reading, while a quiet inherited handle (e.g. a Windows daemonized descendant + * that never lets `close` fire) still releases us after the grace elapses. + */ +export function waitForChildProcess(child) { + return new Promise((resolve, reject) => { + let settled = false; + let exited = false; + let exitCode = null; + let postExitTimer; + let stdoutEnded = child.stdout === null; + let stderrEnded = child.stderr === null; + const cleanup = () => { + if (postExitTimer) { + clearTimeout(postExitTimer); + postExitTimer = undefined; + } + child.removeListener("error", onError); + child.removeListener("exit", onExit); + child.removeListener("close", onClose); + child.stdout?.removeListener("end", onStdoutEnd); + child.stderr?.removeListener("end", onStderrEnd); + child.stdout?.removeListener("data", onData); + child.stderr?.removeListener("data", onData); + }; + const finalize = (code) => { + if (settled) + return; + settled = true; + cleanup(); + child.stdout?.destroy(); + child.stderr?.destroy(); + resolve(code); + }; + const maybeFinalizeAfterExit = () => { + if (!exited || settled) + return; + if (stdoutEnded && stderrEnded) { + finalize(exitCode); + } + }; + const armIdleTimer = () => { + if (postExitTimer) + clearTimeout(postExitTimer); + postExitTimer = setTimeout(() => finalize(exitCode), EXIT_STDIO_GRACE_MS); + }; + const onData = () => { + // Output is still arriving after exit; defer finalizing so we don't + // destroy the stream mid-write and truncate the tail. + if (exited && !settled) + armIdleTimer(); + }; + const onStdoutEnd = () => { + stdoutEnded = true; + maybeFinalizeAfterExit(); + }; + const onStderrEnd = () => { + stderrEnded = true; + maybeFinalizeAfterExit(); + }; + const onError = (err) => { + if (settled) + return; + settled = true; + cleanup(); + reject(err); + }; + const onExit = (code) => { + exited = true; + exitCode = code; + maybeFinalizeAfterExit(); + if (!settled) { + armIdleTimer(); + } + }; + const onClose = (code) => { + finalize(code); + }; + child.stdout?.once("end", onStdoutEnd); + child.stderr?.once("end", onStderrEnd); + child.stdout?.on("data", onData); + child.stderr?.on("data", onData); + child.once("error", onError); + child.once("exit", onExit); + child.once("close", onClose); + }); +} +//# sourceMappingURL=child-process.js.map \ No newline at end of file diff --git a/dist/utils/child-process.js.map b/dist/utils/child-process.js.map new file mode 100644 index 0000000..71c8bc0 --- /dev/null +++ b/dist/utils/child-process.js.map @@ -0,0 +1 @@ +{"version":3,"file":"child-process.js","sourceRoot":"","sources":["../../src/utils/child-process.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,IAAI,SAAS,EAClB,SAAS,IAAI,aAAa,GAO1B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,UAAU,MAAM,aAAa,CAAC;AAErC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAQhC,MAAM,UAAU,YAAY,CAAC,OAAe,EAAE,IAAc,EAAE,OAAqB,EAAgB;IAClG,OAAO,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,OAAO,C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AC,GAAU,EAAE,EAAE,CAAC;YAC/B,IAAI,OAAO;gBAAE,OAAO;YACpB,OAAO,GAAG,IAAI,CAAC;YACf,OAAO,EAAE,CAAC;YACV,MAAM,CAAC,GAAG,CAAC,CAAC;QAAA,CACZ,CAAC;QAEF,MAAM,MAAM,GAAG,CAAC,IAAmB,EAAE,EAAE,CAAC;YACvC,MAAM,GAAG,IAAI,CAAC;YACd,QAAQ,GAAG,IAAI,CAAC;YAChB,sBAAsB,EAAE,CAAC;YACzB,IAAI,CAAC,OAAO,EAAE,CAAC;gBACd,YAAY,EAAE,CAAC;YAChB,CAAC;QAAA,CACD,CAAC;QAEF,MAAM,OAAO,GAAG,CAAC,IAAmB,EAAE,EAAE,CAAC;YACxC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAAA,CACf,CAAC;QAEF,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;QACvC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;QACvC,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjC,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC7B,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC3B,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAAA,CAC7B,CAAC,CAAC;AAAA,CACH","sourcesContent":["import {\n\ttype ChildProcess,\n\ttype ChildProcessByStdio,\n\tspawn as nodeSpawn,\n\tspawnSync as nodeSpawnSync,\n\ttype SpawnOptions,\n\ttype SpawnOptionsWithStdioTuple,\n\ttype SpawnSyncOptionsWithStringEncoding,\n\ttype SpawnSyncReturns,\n\ttype StdioNull,\n\ttype StdioPipe,\n} from \"node:child_process\";\nimport type { Readable } from \"node:stream\";\nimport crossSpawn from \"cross-spawn\";\n\nconst EXIT_STDIO_GRACE_MS = 100;\n\nexport function spawnProcess(\n\tcommand: string,\n\targs: string[],\n\toptions: SpawnOptionsWithStdioTuple,\n): ChildProcessByStdio;\nexport function spawnProcess(command: string, args: string[], options: SpawnOptions): ChildProcess;\nexport function spawnProcess(command: string, args: string[], options: SpawnOptions): ChildProcess {\n\treturn process.platform === \"win32\" ? crossSpawn(command, args, options) : nodeSpawn(command, args, options);\n}\n\nexport function spawnProcessSync(\n\tcommand: string,\n\targs: string[],\n\toptions: SpawnSyncOptionsWithStringEncoding,\n): SpawnSyncReturns {\n\treturn process.platform === \"win32\"\n\t\t? crossSpawn.sync(command, args, options)\n\t\t: nodeSpawnSync(command, args, options);\n}\n\n/**\n * Wait for a child process to terminate without hanging on inherited stdio handles.\n *\n * A short-lived child can `exit` while a detached descendant keeps its stdout/stderr\n * pipe open. We must not resolve and destroy the streams on a fixed deadline measured\n * from `exit`, or output still being written past that deadline is silently lost\n * (earendil-works/pi#5303). Instead, after `exit` we wait for the pipes to fall idle:\n * the grace timer is re-armed on every chunk, so an actively writing descendant keeps\n * us reading, while a quiet inherited handle (e.g. a Windows daemonized descendant\n * that never lets `close` fire) still releases us after the grace elapses.\n */\nexport function waitForChildProcess(child: ChildProcess): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet exited = false;\n\t\tlet exitCode: number | null = null;\n\t\tlet postExitTimer: NodeJS.Timeout | undefined;\n\t\tlet stdoutEnded = child.stdout === null;\n\t\tlet stderrEnded = child.stderr === null;\n\n\t\tconst cleanup = () => {\n\t\t\tif (postExitTimer) {\n\t\t\t\tclearTimeout(postExitTimer);\n\t\t\t\tpostExitTimer = undefined;\n\t\t\t}\n\t\t\tchild.removeListener(\"error\", onError);\n\t\t\tchild.removeListener(\"exit\", onExit);\n\t\t\tchild.removeListener(\"close\", onClose);\n\t\t\tchild.stdout?.removeListener(\"end\", onStdoutEnd);\n\t\t\tchild.stderr?.removeListener(\"end\", onStderrEnd);\n\t\t\tchild.stdout?.removeListener(\"data\", onData);\n\t\t\tchild.stderr?.removeListener(\"data\", onData);\n\t\t};\n\n\t\tconst finalize = (code: number | null) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tchild.stdout?.destroy();\n\t\t\tchild.stderr?.destroy();\n\t\t\tresolve(code);\n\t\t};\n\n\t\tconst maybeFinalizeAfterExit = () => {\n\t\t\tif (!exited || settled) return;\n\t\t\tif (stdoutEnded && stderrEnded) {\n\t\t\t\tfinalize(exitCode);\n\t\t\t}\n\t\t};\n\n\t\tconst armIdleTimer = () => {\n\t\t\tif (postExitTimer) clearTimeout(postExitTimer);\n\t\t\tpostExitTimer = setTimeout(() => finalize(exitCode), EXIT_STDIO_GRACE_MS);\n\t\t};\n\n\t\tconst onData = () => {\n\t\t\t// Output is still arriving after exit; defer finalizing so we don't\n\t\t\t// destroy the stream mid-write and truncate the tail.\n\t\t\tif (exited && !settled) armIdleTimer();\n\t\t};\n\n\t\tconst onStdoutEnd = () => {\n\t\t\tstdoutEnded = true;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t};\n\n\t\tconst onStderrEnd = () => {\n\t\t\tstderrEnded = true;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t};\n\n\t\tconst onError = (err: Error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(err);\n\t\t};\n\n\t\tconst onExit = (code: number | null) => {\n\t\t\texited = true;\n\t\t\texitCode = code;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t\tif (!settled) {\n\t\t\t\tarmIdleTimer();\n\t\t\t}\n\t\t};\n\n\t\tconst onClose = (code: number | null) => {\n\t\t\tfinalize(code);\n\t\t};\n\n\t\tchild.stdout?.once(\"end\", onStdoutEnd);\n\t\tchild.stderr?.once(\"end\", onStderrEnd);\n\t\tchild.stdout?.on(\"data\", onData);\n\t\tchild.stderr?.on(\"data\", onData);\n\t\tchild.once(\"error\", onError);\n\t\tchild.once(\"exit\", onExit);\n\t\tchild.once(\"close\", onClose);\n\t});\n}\n"]} \ No newline at end of file diff --git a/dist/utils/clipboard-image.d.ts b/dist/utils/clipboard-image.d.ts new file mode 100644 index 0000000..5ad7dbc --- /dev/null +++ b/dist/utils/clipboard-image.d.ts @@ -0,0 +1,11 @@ +export type ClipboardImage = { + bytes: Uint8Array; + mimeType: string; +}; +export declare function isWaylandSession(env?: NodeJS.ProcessEnv): boolean; +export declare function extensionForImageMimeType(mimeType: string): string | null; +export declare function readClipboardImage(options?: { + env?: NodeJS.ProcessEnv; + platform?: NodeJS.Platform; +}): Promise; +//# sourceMappingURL=clipboard-image.d.ts.map \ No newline at end of file diff --git a/dist/utils/clipboard-image.d.ts.map b/dist/utils/clipboard-image.d.ts.map new file mode 100644 index 0000000..478a80c --- /dev/null +++ b/dist/utils/clipboard-image.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clipboard-image.d.ts","sourceRoot":"","sources":["../../src/utils/clipboard-image.ts"],"names":[],"mappings":"AASA,MAAM,MAAM,cAAc,GAAG;IAC5B,KAAK,EAAE,UAAU,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;CACjB,CAAC;AASF,wBAAgB,gBAAgB,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,OAAO,CAE9E;AAMD,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAazE;AAmND,wBAAsB,kBAAkB,CAAC,OAAO,CAAC,EAAE;IAClD,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC;CAC3B,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CA2CjC","sourcesContent":["import { spawnSync } from \"child_process\";\nimport { randomUUID } from \"crypto\";\nimport { readFileSync, unlinkSync } from \"fs\";\nimport { tmpdir } from \"os\";\nimport { join } from \"path\";\n\nimport { clipboard } from \"./clipboard-native.ts\";\nimport { loadPhoton } from \"./photon.ts\";\n\nexport type ClipboardImage = {\n\tbytes: Uint8Array;\n\tmimeType: string;\n};\n\nconst SUPPORTED_IMAGE_MIME_TYPES = [\"image/png\", \"image/jpeg\", \"image/webp\", \"image/gif\"] as const;\n\nconst DEFAULT_LIST_TIMEOUT_MS = 1000;\nconst DEFAULT_READ_TIMEOUT_MS = 3000;\nconst DEFAULT_POWERSHELL_TIMEOUT_MS = 5000;\nconst DEFAULT_MAX_BUFFER_BYTES = 50 * 1024 * 1024;\n\nexport function isWaylandSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn Boolean(env.WAYLAND_DISPLAY) || env.XDG_SESSION_TYPE === \"wayland\";\n}\n\nfunction baseMimeType(mimeType: string): string {\n\treturn mimeType.split(\";\")[0]?.trim().toLowerCase() ?? mimeType.toLowerCase();\n}\n\nexport function extensionForImageMimeType(mimeType: string): string | null {\n\tswitch (baseMimeType(mimeType)) {\n\t\tcase \"image/png\":\n\t\t\treturn \"png\";\n\t\tcase \"image/jpeg\":\n\t\t\treturn \"jpg\";\n\t\tcase \"image/webp\":\n\t\t\treturn \"webp\";\n\t\tcase \"image/gif\":\n\t\t\treturn \"gif\";\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nfunction selectPreferredImageMimeType(mimeTypes: string[]): string | null {\n\tconst normalized = mimeTypes\n\t\t.map((t) => t.trim())\n\t\t.filter(Boolean)\n\t\t.map((t) => ({ raw: t, base: baseMimeType(t) }));\n\n\tfor (const preferred of SUPPORTED_IMAGE_MIME_TYPES) {\n\t\tconst match = normalized.find((t) => t.base === preferred);\n\t\tif (match) {\n\t\t\treturn match.raw;\n\t\t}\n\t}\n\n\tconst anyImage = normalized.find((t) => t.base.startsWith(\"image/\"));\n\treturn anyImage?.raw ?? null;\n}\n\nfunction isSupportedImageMimeType(mimeType: string): boolean {\n\tconst base = baseMimeType(mimeType);\n\treturn SUPPORTED_IMAGE_MIME_TYPES.some((t) => t === base);\n}\n\n/**\n * Convert unsupported image formats to PNG using Photon.\n * Returns null if conversion is unavailable or fails.\n */\nasync function convertToPng(bytes: Uint8Array): Promise {\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\treturn null;\n\t}\n\n\ttry {\n\t\tconst image = photon.PhotonImage.new_from_byteslice(bytes);\n\t\ttry {\n\t\t\treturn image.get_bytes();\n\t\t} finally {\n\t\t\timage.free();\n\t\t}\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction runCommand(\n\tcommand: string,\n\targs: string[],\n\toptions?: { timeoutMs?: number; maxBufferBytes?: number; env?: NodeJS.ProcessEnv },\n): { stdout: Buffer; ok: boolean } {\n\tconst timeoutMs = options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS;\n\tconst maxBufferBytes = options?.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;\n\n\tconst result = spawnSync(command, args, {\n\t\ttimeout: timeoutMs,\n\t\tmaxBuffer: maxBufferBytes,\n\t\tenv: options?.env,\n\t});\n\n\tif (result.error) {\n\t\treturn { ok: false, stdout: Buffer.alloc(0) };\n\t}\n\n\tif (result.status !== 0) {\n\t\treturn { ok: false, stdout: Buffer.alloc(0) };\n\t}\n\n\tconst stdout = Buffer.isBuffer(result.stdout)\n\t\t? result.stdout\n\t\t: Buffer.from(result.stdout ?? \"\", typeof result.stdout === \"string\" ? \"utf-8\" : undefined);\n\n\treturn { ok: true, stdout };\n}\n\nfunction readClipboardImageViaWlPaste(): ClipboardImage | null {\n\tconst list = runCommand(\"wl-paste\", [\"--list-types\"], { timeoutMs: DEFAULT_LIST_TIMEOUT_MS });\n\tif (!list.ok) {\n\t\treturn null;\n\t}\n\n\tconst types = list.stdout\n\t\t.toString(\"utf-8\")\n\t\t.split(/\\r?\\n/)\n\t\t.map((t) => t.trim())\n\t\t.filter(Boolean);\n\n\tconst selectedType = selectPreferredImageMimeType(types);\n\tif (!selectedType) {\n\t\treturn null;\n\t}\n\n\tconst data = runCommand(\"wl-paste\", [\"--type\", selectedType, \"--no-newline\"]);\n\tif (!data.ok || data.stdout.length === 0) {\n\t\treturn null;\n\t}\n\n\treturn { bytes: data.stdout, mimeType: baseMimeType(selectedType) };\n}\n\nfunction isWSL(env: NodeJS.ProcessEnv = process.env): boolean {\n\tif (env.WSL_DISTRO_NAME || env.WSLENV) {\n\t\treturn true;\n\t}\n\n\ttry {\n\t\tconst release = readFileSync(\"/proc/version\", \"utf-8\");\n\t\treturn /microsoft|wsl/i.test(release);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * On WSL, the Linux clipboard (Wayland/X11) does not receive image data from\n * Windows screenshots (Win+Shift+S). PowerShell can access the Windows clipboard\n * directly, so we use it as a fallback.\n */\nfunction readClipboardImageViaPowerShell(): ClipboardImage | null {\n\tconst tmpFile = join(tmpdir(), `pi-wsl-clip-${randomUUID()}.png`);\n\n\ttry {\n\t\tconst winPathResult = runCommand(\"wslpath\", [\"-w\", tmpFile], { timeoutMs: DEFAULT_LIST_TIMEOUT_MS });\n\t\tif (!winPathResult.ok) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst winPath = winPathResult.stdout.toString(\"utf-8\").trim();\n\t\tif (!winPath) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst psQuotedWinPath = winPath.replaceAll(\"'\", \"''\");\n\t\tconst psScript = [\n\t\t\t\"Add-Type -AssemblyName System.Windows.Forms\",\n\t\t\t\"Add-Type -AssemblyName System.Drawing\",\n\t\t\t`$path = '${psQuotedWinPath}'`,\n\t\t\t\"$img = [System.Windows.Forms.Clipboard]::GetImage()\",\n\t\t\t\"if ($img) { $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' } else { Write-Output 'empty' }\",\n\t\t].join(\"; \");\n\n\t\tconst result = runCommand(\"powershell.exe\", [\"-NoProfile\", \"-Command\", psScript], {\n\t\t\ttimeoutMs: DEFAULT_POWERSHELL_TIMEOUT_MS,\n\t\t});\n\t\tif (!result.ok) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst output = result.stdout.toString(\"utf-8\").trim();\n\t\tif (output !== \"ok\") {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst bytes = readFileSync(tmpFile);\n\t\tif (bytes.length === 0) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn { bytes: new Uint8Array(bytes), mimeType: \"image/png\" };\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\ttry {\n\t\t\tunlinkSync(tmpFile);\n\t\t} catch {\n\t\t\t// Ignore cleanup errors.\n\t\t}\n\t}\n}\n\nfunction readClipboardImageViaXclip(): ClipboardImage | null {\n\tconst targets = runCommand(\"xclip\", [\"-selection\", \"clipboard\", \"-t\", \"TARGETS\", \"-o\"], {\n\t\ttimeoutMs: DEFAULT_LIST_TIMEOUT_MS,\n\t});\n\n\tlet candidateTypes: string[] = [];\n\tif (targets.ok) {\n\t\tcandidateTypes = targets.stdout\n\t\t\t.toString(\"utf-8\")\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t}\n\n\tconst preferred = candidateTypes.length > 0 ? selectPreferredImageMimeType(candidateTypes) : null;\n\tconst tryTypes = preferred ? [preferred, ...SUPPORTED_IMAGE_MIME_TYPES] : [...SUPPORTED_IMAGE_MIME_TYPES];\n\n\tfor (const mimeType of tryTypes) {\n\t\tconst data = runCommand(\"xclip\", [\"-selection\", \"clipboard\", \"-t\", mimeType, \"-o\"]);\n\t\tif (data.ok && data.stdout.length > 0) {\n\t\t\treturn { bytes: data.stdout, mimeType: baseMimeType(mimeType) };\n\t\t}\n\t}\n\n\treturn null;\n}\n\nasync function readClipboardImageViaNativeClipboard(): Promise {\n\tif (!clipboard || !clipboard.hasImage()) {\n\t\treturn null;\n\t}\n\n\tconst imageData = await clipboard.getImageBinary();\n\tif (!imageData || imageData.length === 0) {\n\t\treturn null;\n\t}\n\n\tconst bytes = imageData instanceof Uint8Array ? imageData : Uint8Array.from(imageData);\n\treturn { bytes, mimeType: \"image/png\" };\n}\n\nexport async function readClipboardImage(options?: {\n\tenv?: NodeJS.ProcessEnv;\n\tplatform?: NodeJS.Platform;\n}): Promise {\n\tconst env = options?.env ?? process.env;\n\tconst platform = options?.platform ?? process.platform;\n\n\tif (env.TERMUX_VERSION) {\n\t\treturn null;\n\t}\n\n\tlet image: ClipboardImage | null = null;\n\n\tif (platform === \"linux\") {\n\t\tconst wsl = isWSL(env);\n\t\tconst wayland = isWaylandSession(env);\n\n\t\tif (wayland || wsl) {\n\t\t\timage = readClipboardImageViaWlPaste() ?? readClipboardImageViaXclip();\n\t\t}\n\n\t\tif (!image && wsl) {\n\t\t\timage = readClipboardImageViaPowerShell();\n\t\t}\n\n\t\tif (!image && !wayland) {\n\t\t\timage = (await readClipboardImageViaNativeClipboard()) ?? readClipboardImageViaXclip();\n\t\t}\n\t} else {\n\t\timage = await readClipboardImageViaNativeClipboard();\n\t}\n\n\tif (!image) {\n\t\treturn null;\n\t}\n\n\t// Convert unsupported formats (e.g., BMP from WSLg) to PNG\n\tif (!isSupportedImageMimeType(image.mimeType)) {\n\t\tconst pngBytes = await convertToPng(image.bytes);\n\t\tif (!pngBytes) {\n\t\t\treturn null;\n\t\t}\n\t\treturn { bytes: pngBytes, mimeType: \"image/png\" };\n\t}\n\n\treturn image;\n}\n"]} \ No newline at end of file diff --git a/dist/utils/clipboard-image.js b/dist/utils/clipboard-image.js new file mode 100644 index 0000000..f6aca25 --- /dev/null +++ b/dist/utils/clipboard-image.js @@ -0,0 +1,245 @@ +import { spawnSync } from "child_process"; +import { randomUUID } from "crypto"; +import { readFileSync, unlinkSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; +import { clipboard } from "./clipboard-native.js"; +import { loadPhoton } from "./photon.js"; +const SUPPORTED_IMAGE_MIME_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"]; +const DEFAULT_LIST_TIMEOUT_MS = 1000; +const DEFAULT_READ_TIMEOUT_MS = 3000; +const DEFAULT_POWERSHELL_TIMEOUT_MS = 5000; +const DEFAULT_MAX_BUFFER_BYTES = 50 * 1024 * 1024; +export function isWaylandSession(env = process.env) { + return Boolean(env.WAYLAND_DISPLAY) || env.XDG_SESSION_TYPE === "wayland"; +} +function baseMimeType(mimeType) { + return mimeType.split(";")[0]?.trim().toLowerCase() ?? mimeType.toLowerCase(); +} +export function extensionForImageMimeType(mimeType) { + switch (baseMimeType(mimeType)) { + case "image/png": + return "png"; + case "image/jpeg": + return "jpg"; + case "image/webp": + return "webp"; + case "image/gif": + return "gif"; + default: + return null; + } +} +function selectPreferredImageMimeType(mimeTypes) { + const normalized = mimeTypes + .map((t) => t.trim()) + .filter(Boolean) + .map((t) => ({ raw: t, base: baseMimeType(t) })); + for (const preferred of SUPPORTED_IMAGE_MIME_TYPES) { + const match = normalized.find((t) => t.base === preferred); + if (match) { + return match.raw; + } + } + const anyImage = normalized.find((t) => t.base.startsWith("image/")); + return anyImage?.raw ?? null; +} +function isSupportedImageMimeType(mimeType) { + const base = baseMimeType(mimeType); + return SUPPORTED_IMAGE_MIME_TYPES.some((t) => t === base); +} +/** + * Convert unsupported image formats to PNG using Photon. + * Returns null if conversion is unavailable or fails. + */ +async function convertToPng(bytes) { + const photon = await loadPhoton(); + if (!photon) { + return null; + } + try { + const image = photon.PhotonImage.new_from_byteslice(bytes); + try { + return image.get_bytes(); + } + finally { + image.free(); + } + } + catch { + return null; + } +} +function runCommand(command, args, options) { + const timeoutMs = options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS; + const maxBufferBytes = options?.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES; + const result = spawnSync(command, args, { + timeout: timeoutMs, + maxBuffer: maxBufferBytes, + env: options?.env, + }); + if (result.error) { + return { ok: false, stdout: Buffer.alloc(0) }; + } + if (result.status !== 0) { + return { ok: false, stdout: Buffer.alloc(0) }; + } + const stdout = Buffer.isBuffer(result.stdout) + ? result.stdout + : Buffer.from(result.stdout ?? "", typeof result.stdout === "string" ? "utf-8" : undefined); + return { ok: true, stdout }; +} +function readClipboardImageViaWlPaste() { + const list = runCommand("wl-paste", ["--list-types"], { timeoutMs: DEFAULT_LIST_TIMEOUT_MS }); + if (!list.ok) { + return null; + } + const types = list.stdout + .toString("utf-8") + .split(/\r?\n/) + .map((t) => t.trim()) + .filter(Boolean); + const selectedType = selectPreferredImageMimeType(types); + if (!selectedType) { + return null; + } + const data = runCommand("wl-paste", ["--type", selectedType, "--no-newline"]); + if (!data.ok || data.stdout.length === 0) { + return null; + } + return { bytes: data.stdout, mimeType: baseMimeType(selectedType) }; +} +function isWSL(env = process.env) { + if (env.WSL_DISTRO_NAME || env.WSLENV) { + return true; + } + try { + const release = readFileSync("/proc/version", "utf-8"); + return /microsoft|wsl/i.test(release); + } + catch { + return false; + } +} +/** + * On WSL, the Linux clipboard (Wayland/X11) does not receive image data from + * Windows screenshots (Win+Shift+S). PowerShell can access the Windows clipboard + * directly, so we use it as a fallback. + */ +function readClipboardImageViaPowerShell() { + const tmpFile = join(tmpdir(), `pi-wsl-clip-${randomUUID()}.png`); + try { + const winPathResult = runCommand("wslpath", ["-w", tmpFile], { timeoutMs: DEFAULT_LIST_TIMEOUT_MS }); + if (!winPathResult.ok) { + return null; + } + const winPath = winPathResult.stdout.toString("utf-8").trim(); + if (!winPath) { + return null; + } + const psQuotedWinPath = winPath.replaceAll("'", "''"); + const psScript = [ + "Add-Type -AssemblyName System.Windows.Forms", + "Add-Type -AssemblyName System.Drawing", + `$path = '${psQuotedWinPath}'`, + "$img = [System.Windows.Forms.Clipboard]::GetImage()", + "if ($img) { $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' } else { Write-Output 'empty' }", + ].join("; "); + const result = runCommand("powershell.exe", ["-NoProfile", "-Command", psScript], { + timeoutMs: DEFAULT_POWERSHELL_TIMEOUT_MS, + }); + if (!result.ok) { + return null; + } + const output = result.stdout.toString("utf-8").trim(); + if (output !== "ok") { + return null; + } + const bytes = readFileSync(tmpFile); + if (bytes.length === 0) { + return null; + } + return { bytes: new Uint8Array(bytes), mimeType: "image/png" }; + } + catch { + return null; + } + finally { + try { + unlinkSync(tmpFile); + } + catch { + // Ignore cleanup errors. + } + } +} +function readClipboardImageViaXclip() { + const targets = runCommand("xclip", ["-selection", "clipboard", "-t", "TARGETS", "-o"], { + timeoutMs: DEFAULT_LIST_TIMEOUT_MS, + }); + let candidateTypes = []; + if (targets.ok) { + candidateTypes = targets.stdout + .toString("utf-8") + .split(/\r?\n/) + .map((t) => t.trim()) + .filter(Boolean); + } + const preferred = candidateTypes.length > 0 ? selectPreferredImageMimeType(candidateTypes) : null; + const tryTypes = preferred ? [preferred, ...SUPPORTED_IMAGE_MIME_TYPES] : [...SUPPORTED_IMAGE_MIME_TYPES]; + for (const mimeType of tryTypes) { + const data = runCommand("xclip", ["-selection", "clipboard", "-t", mimeType, "-o"]); + if (data.ok && data.stdout.length > 0) { + return { bytes: data.stdout, mimeType: baseMimeType(mimeType) }; + } + } + return null; +} +async function readClipboardImageViaNativeClipboard() { + if (!clipboard || !clipboard.hasImage()) { + return null; + } + const imageData = await clipboard.getImageBinary(); + if (!imageData || imageData.length === 0) { + return null; + } + const bytes = imageData instanceof Uint8Array ? imageData : Uint8Array.from(imageData); + return { bytes, mimeType: "image/png" }; +} +export async function readClipboardImage(options) { + const env = options?.env ?? process.env; + const platform = options?.platform ?? process.platform; + if (env.TERMUX_VERSION) { + return null; + } + let image = null; + if (platform === "linux") { + const wsl = isWSL(env); + const wayland = isWaylandSession(env); + if (wayland || wsl) { + image = readClipboardImageViaWlPaste() ?? readClipboardImageViaXclip(); + } + if (!image && wsl) { + image = readClipboardImageViaPowerShell(); + } + if (!image && !wayland) { + image = (await readClipboardImageViaNativeClipboard()) ?? readClipboardImageViaXclip(); + } + } + else { + image = await readClipboardImageViaNativeClipboard(); + } + if (!image) { + return null; + } + // Convert unsupported formats (e.g., BMP from WSLg) to PNG + if (!isSupportedImageMimeType(image.mimeType)) { + const pngBytes = await convertToPng(image.bytes); + if (!pngBytes) { + return null; + } + return { bytes: pngBytes, mimeType: "image/png" }; + } + return image; +} +//# sourceMappingURL=clipboard-image.js.map \ No newline at end of file diff --git a/dist/utils/clipboard-image.js.map b/dist/utils/clipboard-image.js.map new file mode 100644 index 0000000..ba27e73 --- /dev/null +++ b/dist/utils/clipboard-image.js.map @@ -0,0 +1 @@ +{"version":3,"file":"clipboard-image.js","sourceRoot":"","sources":["../../src/utils/clipboard-image.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAC5B,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAOzC,MAAM,0BAA0B,GAAG,CAAC,WAAW,EAAE,YAAY,EAAE,YAAY,EAAE,WAAW,CAAU,CAAC;AAEnG,MAAM,uBAAuB,GAAG,IAAI,CAAC;AACrC,MAAM,uBAAuB,GAAG,IAAI,CAAC;AACrC,MAAM,6BAA6B,GAAG,IAAI,CAAC;AAC3C,MAAM,wBAAwB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAElD,MAAM,UAAU,gBAAgB,CAAC,GAAG,GAAsB,OAAO,CAAC,GAAG,EAAW;IAC/E,OAAO,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,GAAG,CAAC,gBAAgB,KAAK,SAAS,CAAC;AAAA,CAC1E;AAED,SAAS,YAAY,CAAC,QAAgB,EAAU;IAC/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AC/C,MAAM,QAAQ,GAAG,MAAM,YAAY,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACjD,IAAI,CAAC,QAAQ,EAAE,CAAC;YACf,OAAO,IAAI,CAAC;QACb,CAAC;QACD,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC;IACnD,CAAC;IAED,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["import { spawnSync } from \"child_process\";\nimport { randomUUID } from \"crypto\";\nimport { readFileSync, unlinkSync } from \"fs\";\nimport { tmpdir } from \"os\";\nimport { join } from \"path\";\n\nimport { clipboard } from \"./clipboard-native.ts\";\nimport { loadPhoton } from \"./photon.ts\";\n\nexport type ClipboardImage = {\n\tbytes: Uint8Array;\n\tmimeType: string;\n};\n\nconst SUPPORTED_IMAGE_MIME_TYPES = [\"image/png\", \"image/jpeg\", \"image/webp\", \"image/gif\"] as const;\n\nconst DEFAULT_LIST_TIMEOUT_MS = 1000;\nconst DEFAULT_READ_TIMEOUT_MS = 3000;\nconst DEFAULT_POWERSHELL_TIMEOUT_MS = 5000;\nconst DEFAULT_MAX_BUFFER_BYTES = 50 * 1024 * 1024;\n\nexport function isWaylandSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn Boolean(env.WAYLAND_DISPLAY) || env.XDG_SESSION_TYPE === \"wayland\";\n}\n\nfunction baseMimeType(mimeType: string): string {\n\treturn mimeType.split(\";\")[0]?.trim().toLowerCase() ?? mimeType.toLowerCase();\n}\n\nexport function extensionForImageMimeType(mimeType: string): string | null {\n\tswitch (baseMimeType(mimeType)) {\n\t\tcase \"image/png\":\n\t\t\treturn \"png\";\n\t\tcase \"image/jpeg\":\n\t\t\treturn \"jpg\";\n\t\tcase \"image/webp\":\n\t\t\treturn \"webp\";\n\t\tcase \"image/gif\":\n\t\t\treturn \"gif\";\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nfunction selectPreferredImageMimeType(mimeTypes: string[]): string | null {\n\tconst normalized = mimeTypes\n\t\t.map((t) => t.trim())\n\t\t.filter(Boolean)\n\t\t.map((t) => ({ raw: t, base: baseMimeType(t) }));\n\n\tfor (const preferred of SUPPORTED_IMAGE_MIME_TYPES) {\n\t\tconst match = normalized.find((t) => t.base === preferred);\n\t\tif (match) {\n\t\t\treturn match.raw;\n\t\t}\n\t}\n\n\tconst anyImage = normalized.find((t) => t.base.startsWith(\"image/\"));\n\treturn anyImage?.raw ?? null;\n}\n\nfunction isSupportedImageMimeType(mimeType: string): boolean {\n\tconst base = baseMimeType(mimeType);\n\treturn SUPPORTED_IMAGE_MIME_TYPES.some((t) => t === base);\n}\n\n/**\n * Convert unsupported image formats to PNG using Photon.\n * Returns null if conversion is unavailable or fails.\n */\nasync function convertToPng(bytes: Uint8Array): Promise {\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\treturn null;\n\t}\n\n\ttry {\n\t\tconst image = photon.PhotonImage.new_from_byteslice(bytes);\n\t\ttry {\n\t\t\treturn image.get_bytes();\n\t\t} finally {\n\t\t\timage.free();\n\t\t}\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction runCommand(\n\tcommand: string,\n\targs: string[],\n\toptions?: { timeoutMs?: number; maxBufferBytes?: number; env?: NodeJS.ProcessEnv },\n): { stdout: Buffer; ok: boolean } {\n\tconst timeoutMs = options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS;\n\tconst maxBufferBytes = options?.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;\n\n\tconst result = spawnSync(command, args, {\n\t\ttimeout: timeoutMs,\n\t\tmaxBuffer: maxBufferBytes,\n\t\tenv: options?.env,\n\t});\n\n\tif (result.error) {\n\t\treturn { ok: false, stdout: Buffer.alloc(0) };\n\t}\n\n\tif (result.status !== 0) {\n\t\treturn { ok: false, stdout: Buffer.alloc(0) };\n\t}\n\n\tconst stdout = Buffer.isBuffer(result.stdout)\n\t\t? result.stdout\n\t\t: Buffer.from(result.stdout ?? \"\", typeof result.stdout === \"string\" ? \"utf-8\" : undefined);\n\n\treturn { ok: true, stdout };\n}\n\nfunction readClipboardImageViaWlPaste(): ClipboardImage | null {\n\tconst list = runCommand(\"wl-paste\", [\"--list-types\"], { timeoutMs: DEFAULT_LIST_TIMEOUT_MS });\n\tif (!list.ok) {\n\t\treturn null;\n\t}\n\n\tconst types = list.stdout\n\t\t.toString(\"utf-8\")\n\t\t.split(/\\r?\\n/)\n\t\t.map((t) => t.trim())\n\t\t.filter(Boolean);\n\n\tconst selectedType = selectPreferredImageMimeType(types);\n\tif (!selectedType) {\n\t\treturn null;\n\t}\n\n\tconst data = runCommand(\"wl-paste\", [\"--type\", selectedType, \"--no-newline\"]);\n\tif (!data.ok || data.stdout.length === 0) {\n\t\treturn null;\n\t}\n\n\treturn { bytes: data.stdout, mimeType: baseMimeType(selectedType) };\n}\n\nfunction isWSL(env: NodeJS.ProcessEnv = process.env): boolean {\n\tif (env.WSL_DISTRO_NAME || env.WSLENV) {\n\t\treturn true;\n\t}\n\n\ttry {\n\t\tconst release = readFileSync(\"/proc/version\", \"utf-8\");\n\t\treturn /microsoft|wsl/i.test(release);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * On WSL, the Linux clipboard (Wayland/X11) does not receive image data from\n * Windows screenshots (Win+Shift+S). PowerShell can access the Windows clipboard\n * directly, so we use it as a fallback.\n */\nfunction readClipboardImageViaPowerShell(): ClipboardImage | null {\n\tconst tmpFile = join(tmpdir(), `pi-wsl-clip-${randomUUID()}.png`);\n\n\ttry {\n\t\tconst winPathResult = runCommand(\"wslpath\", [\"-w\", tmpFile], { timeoutMs: DEFAULT_LIST_TIMEOUT_MS });\n\t\tif (!winPathResult.ok) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst winPath = winPathResult.stdout.toString(\"utf-8\").trim();\n\t\tif (!winPath) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst psQuotedWinPath = winPath.replaceAll(\"'\", \"''\");\n\t\tconst psScript = [\n\t\t\t\"Add-Type -AssemblyName System.Windows.Forms\",\n\t\t\t\"Add-Type -AssemblyName System.Drawing\",\n\t\t\t`$path = '${psQuotedWinPath}'`,\n\t\t\t\"$img = [System.Windows.Forms.Clipboard]::GetImage()\",\n\t\t\t\"if ($img) { $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' } else { Write-Output 'empty' }\",\n\t\t].join(\"; \");\n\n\t\tconst result = runCommand(\"powershell.exe\", [\"-NoProfile\", \"-Command\", psScript], {\n\t\t\ttimeoutMs: DEFAULT_POWERSHELL_TIMEOUT_MS,\n\t\t});\n\t\tif (!result.ok) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst output = result.stdout.toString(\"utf-8\").trim();\n\t\tif (output !== \"ok\") {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst bytes = readFileSync(tmpFile);\n\t\tif (bytes.length === 0) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn { bytes: new Uint8Array(bytes), mimeType: \"image/png\" };\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\ttry {\n\t\t\tunlinkSync(tmpFile);\n\t\t} catch {\n\t\t\t// Ignore cleanup errors.\n\t\t}\n\t}\n}\n\nfunction readClipboardImageViaXclip(): ClipboardImage | null {\n\tconst targets = runCommand(\"xclip\", [\"-selection\", \"clipboard\", \"-t\", \"TARGETS\", \"-o\"], {\n\t\ttimeoutMs: DEFAULT_LIST_TIMEOUT_MS,\n\t});\n\n\tlet candidateTypes: string[] = [];\n\tif (targets.ok) {\n\t\tcandidateTypes = targets.stdout\n\t\t\t.toString(\"utf-8\")\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t}\n\n\tconst preferred = candidateTypes.length > 0 ? selectPreferredImageMimeType(candidateTypes) : null;\n\tconst tryTypes = preferred ? [preferred, ...SUPPORTED_IMAGE_MIME_TYPES] : [...SUPPORTED_IMAGE_MIME_TYPES];\n\n\tfor (const mimeType of tryTypes) {\n\t\tconst data = runCommand(\"xclip\", [\"-selection\", \"clipboard\", \"-t\", mimeType, \"-o\"]);\n\t\tif (data.ok && data.stdout.length > 0) {\n\t\t\treturn { bytes: data.stdout, mimeType: baseMimeType(mimeType) };\n\t\t}\n\t}\n\n\treturn null;\n}\n\nasync function readClipboardImageViaNativeClipboard(): Promise {\n\tif (!clipboard || !clipboard.hasImage()) {\n\t\treturn null;\n\t}\n\n\tconst imageData = await clipboard.getImageBinary();\n\tif (!imageData || imageData.length === 0) {\n\t\treturn null;\n\t}\n\n\tconst bytes = imageData instanceof Uint8Array ? imageData : Uint8Array.from(imageData);\n\treturn { bytes, mimeType: \"image/png\" };\n}\n\nexport async function readClipboardImage(options?: {\n\tenv?: NodeJS.ProcessEnv;\n\tplatform?: NodeJS.Platform;\n}): Promise {\n\tconst env = options?.env ?? process.env;\n\tconst platform = options?.platform ?? process.platform;\n\n\tif (env.TERMUX_VERSION) {\n\t\treturn null;\n\t}\n\n\tlet image: ClipboardImage | null = null;\n\n\tif (platform === \"linux\") {\n\t\tconst wsl = isWSL(env);\n\t\tconst wayland = isWaylandSession(env);\n\n\t\tif (wayland || wsl) {\n\t\t\timage = readClipboardImageViaWlPaste() ?? readClipboardImageViaXclip();\n\t\t}\n\n\t\tif (!image && wsl) {\n\t\t\timage = readClipboardImageViaPowerShell();\n\t\t}\n\n\t\tif (!image && !wayland) {\n\t\t\timage = (await readClipboardImageViaNativeClipboard()) ?? readClipboardImageViaXclip();\n\t\t}\n\t} else {\n\t\timage = await readClipboardImageViaNativeClipboard();\n\t}\n\n\tif (!image) {\n\t\treturn null;\n\t}\n\n\t// Convert unsupported formats (e.g., BMP from WSLg) to PNG\n\tif (!isSupportedImageMimeType(image.mimeType)) {\n\t\tconst pngBytes = await convertToPng(image.bytes);\n\t\tif (!pngBytes) {\n\t\t\treturn null;\n\t\t}\n\t\treturn { bytes: pngBytes, mimeType: \"image/png\" };\n\t}\n\n\treturn image;\n}\n"]} \ No newline at end of file diff --git a/dist/utils/clipboard-native.d.ts b/dist/utils/clipboard-native.d.ts new file mode 100644 index 0000000..04258b2 --- /dev/null +++ b/dist/utils/clipboard-native.d.ts @@ -0,0 +1,11 @@ +export type ClipboardModule = { + getText: () => Promise; + setText: (text: string) => Promise; + hasImage: () => boolean; + getImageBinary: () => Promise>; +}; +type ClipboardRequire = (id: string) => unknown; +export declare function loadClipboardNative(requires?: readonly ClipboardRequire[]): ClipboardModule | null; +declare const clipboard: ClipboardModule | null; +export { clipboard }; +//# sourceMappingURL=clipboard-native.d.ts.map \ No newline at end of file diff --git a/dist/utils/clipboard-native.d.ts.map b/dist/utils/clipboard-native.d.ts.map new file mode 100644 index 0000000..6fbd064 --- /dev/null +++ b/dist/utils/clipboard-native.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clipboard-native.d.ts","sourceRoot":"","sources":["../../src/utils/clipboard-native.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,eAAe,GAAG;IAC7B,OAAO,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/B,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC,QAAQ,EAAE,MAAM,OAAO,CAAC;IACxB,cAAc,EAAE,MAAM,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;CAC7C,CAAC;AAEF,KAAK,gBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC;AAMhD,wBAAgB,mBAAmB,CAClC,QAAQ,GAAE,SAAS,gBAAgB,EAA0C,GAC3E,eAAe,GAAG,IAAI,CASxB;AAED,QAAA,MAAM,SAAS,wBAA2E,CAAC;AAE3F,OAAO,EAAE,SAAS,EAAE,CAAC","sourcesContent":["import { createRequire } from \"module\";\nimport { dirname, join } from \"path\";\nimport { pathToFileURL } from \"url\";\n\nexport type ClipboardModule = {\n\tgetText: () => Promise;\n\tsetText: (text: string) => Promise;\n\thasImage: () => boolean;\n\tgetImageBinary: () => Promise>;\n};\n\ntype ClipboardRequire = (id: string) => unknown;\n\nconst moduleRequire = createRequire(import.meta.url);\nconst executableDirRequire = createRequire(pathToFileURL(join(dirname(process.execPath), \"package.json\")).href);\nconst hasDisplay = process.platform !== \"linux\" || Boolean(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);\n\nexport function loadClipboardNative(\n\trequires: readonly ClipboardRequire[] = [moduleRequire, executableDirRequire],\n): ClipboardModule | null {\n\tfor (const requireClipboard of requires) {\n\t\ttry {\n\t\t\treturn requireClipboard(\"@mariozechner/clipboard\") as ClipboardModule;\n\t\t} catch {\n\t\t\t// Try the next resolution root.\n\t\t}\n\t}\n\treturn null;\n}\n\nconst clipboard = !process.env.TERMUX_VERSION && hasDisplay ? loadClipboardNative() : null;\n\nexport { clipboard };\n"]} \ No newline at end of file diff --git a/dist/utils/clipboard-native.js b/dist/utils/clipboard-native.js new file mode 100644 index 0000000..42647bc --- /dev/null +++ b/dist/utils/clipboard-native.js @@ -0,0 +1,20 @@ +import { createRequire } from "module"; +import { dirname, join } from "path"; +import { pathToFileURL } from "url"; +const moduleRequire = createRequire(import.meta.url); +const executableDirRequire = createRequire(pathToFileURL(join(dirname(process.execPath), "package.json")).href); +const hasDisplay = process.platform !== "linux" || Boolean(process.env.DISPLAY || process.env.WAYLAND_DISPLAY); +export function loadClipboardNative(requires = [moduleRequire, executableDirRequire]) { + for (const requireClipboard of requires) { + try { + return requireClipboard("@mariozechner/clipboard"); + } + catch { + // Try the next resolution root. + } + } + return null; +} +const clipboard = !process.env.TERMUX_VERSION && hasDisplay ? loadClipboardNative() : null; +export { clipboard }; +//# sourceMappingURL=clipboard-native.js.map \ No newline at end of file diff --git a/dist/utils/clipboard-native.js.map b/dist/utils/clipboard-native.js.map new file mode 100644 index 0000000..d75d7f9 --- /dev/null +++ b/dist/utils/clipboard-native.js.map @@ -0,0 +1 @@ +{"version":3,"file":"clipboard-native.js","sourceRoot":"","sources":["../../src/utils/clipboard-native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAWpC,MAAM,aAAa,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AACrD,MAAM,oBAAoB,GAAG,aAAa,CAAC,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;AAChH,MAAM,UAAU,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,IAAI,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;AAE/G,MAAM,UAAU,mBAAmB,CAClC,QAAQ,GAAgC,CAAC,aAAa,EAAE,oBAAoB,CAAC,EACpD;IACzB,KAAK,MAAM,gBAAgB,IAAI,QAAQ,EAAE,CAAC;QACzC,IAAI,CAAC;YACJ,OAAO,gBAAgB,CAAC,yBAAyB,CAAoB,CAAC;QACvE,CAAC;QAAC,MAAM,CAAC;YACR,gCAAgC;QACjC,CAAC;IACF,CAAC;IACD,OAAO,IAAI,CAAC;AAAA,CACZ;AAED,MAAM,SAAS,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,UAAU,CAAC,CAAC,CAAC,mBAAmB,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAE3F,OAAO,EAAE,SAAS,EAAE,CAAC","sourcesContent":["import { createRequire } from \"module\";\nimport { dirname, join } from \"path\";\nimport { pathToFileURL } from \"url\";\n\nexport type ClipboardModule = {\n\tgetText: () => Promise;\n\tsetText: (text: string) => Promise;\n\thasImage: () => boolean;\n\tgetImageBinary: () => Promise>;\n};\n\ntype ClipboardRequire = (id: string) => unknown;\n\nconst moduleRequire = createRequire(import.meta.url);\nconst executableDirRequire = createRequire(pathToFileURL(join(dirname(process.execPath), \"package.json\")).href);\nconst hasDisplay = process.platform !== \"linux\" || Boolean(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);\n\nexport function loadClipboardNative(\n\trequires: readonly ClipboardRequire[] = [moduleRequire, executableDirRequire],\n): ClipboardModule | null {\n\tfor (const requireClipboard of requires) {\n\t\ttry {\n\t\t\treturn requireClipboard(\"@mariozechner/clipboard\") as ClipboardModule;\n\t\t} catch {\n\t\t\t// Try the next resolution root.\n\t\t}\n\t}\n\treturn null;\n}\n\nconst clipboard = !process.env.TERMUX_VERSION && hasDisplay ? loadClipboardNative() : null;\n\nexport { clipboard };\n"]} \ No newline at end of file diff --git a/dist/utils/clipboard.d.ts b/dist/utils/clipboard.d.ts new file mode 100644 index 0000000..fba761d --- /dev/null +++ b/dist/utils/clipboard.d.ts @@ -0,0 +1,4 @@ +/** Read plain text from the system clipboard, if native clipboard access is available. */ +export declare function readClipboardText(): Promise; +export declare function copyToClipboard(text: string): Promise; +//# sourceMappingURL=clipboard.d.ts.map \ No newline at end of file diff --git a/dist/utils/clipboard.d.ts.map b/dist/utils/clipboard.d.ts.map new file mode 100644 index 0000000..6dc2e7b --- /dev/null +++ b/dist/utils/clipboard.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clipboard.d.ts","sourceRoot":"","sources":["../../src/utils/clipboard.ts"],"names":[],"mappings":"AAkCA,0FAA0F;AAC1F,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAWhE;AAED,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAsGjE","sourcesContent":["import { execSync, spawn } from \"child_process\";\nimport { platform } from \"os\";\nimport { isWaylandSession } from \"./clipboard-image.ts\";\nimport { clipboard } from \"./clipboard-native.ts\";\n\ntype NativeClipboardExecOptions = {\n\tinput: string;\n\ttimeout: number;\n\tstdio: [\"pipe\", \"ignore\", \"ignore\"];\n};\n\nfunction copyToX11Clipboard(options: NativeClipboardExecOptions): void {\n\ttry {\n\t\texecSync(\"xclip -selection clipboard\", options);\n\t} catch {\n\t\texecSync(\"xsel --clipboard --input\", options);\n\t}\n}\n\nconst MAX_OSC52_ENCODED_LENGTH = 100_000;\n\nfunction isRemoteSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.MOSH_CONNECTION);\n}\n\nfunction emitOsc52(text: string): boolean {\n\tconst encoded = Buffer.from(text).toString(\"base64\");\n\tif (encoded.length > MAX_OSC52_ENCODED_LENGTH) {\n\t\treturn false;\n\t}\n\tprocess.stdout.write(`\\x1b]52;c;${encoded}\\x07`);\n\treturn true;\n}\n\n/** Read plain text from the system clipboard, if native clipboard access is available. */\nexport async function readClipboardText(): Promise {\n\tif (!clipboard) {\n\t\treturn null;\n\t}\n\n\ttry {\n\t\tconst text = await clipboard.getText();\n\t\treturn text || null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport async function copyToClipboard(text: string): Promise {\n\tlet copied = false;\n\n\tconst p = platform();\n\n\t// Prefer direct clipboard writes. Emitting OSC 52 first can make terminals\n\t// write the same native clipboard concurrently with the addon, and very large\n\t// OSC 52 payloads can desynchronize terminal rendering.\n\t//\n\t// On Linux, skip the native addon. The underlying `clipboard-rs` crate is\n\t// X11-only and does not retain selection ownership after `set_text`\n\t// resolves, so on Wayland-only compositors (Hyprland, Niri, ...) and even\n\t// some X11 sessions the call resolves successfully without populating the\n\t// clipboard. The platform tools below (wl-copy, xclip, xsel) properly\n\t// daemonize and keep ownership.\n\ttry {\n\t\tif (clipboard && p !== \"linux\") {\n\t\t\tawait clipboard.setText(text);\n\t\t\tcopied = true;\n\t\t}\n\t} catch {\n\t\t// Fall through to platform-specific clipboard tools.\n\t}\n\n\tconst remote = isRemoteSession();\n\tif (copied && !remote) {\n\t\treturn;\n\t}\n\n\tconst options: NativeClipboardExecOptions = { input: text, timeout: 5000, stdio: [\"pipe\", \"ignore\", \"ignore\"] };\n\n\tif (!copied) {\n\t\ttry {\n\t\t\tif (p === \"darwin\") {\n\t\t\t\texecSync(\"pbcopy\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else if (p === \"win32\") {\n\t\t\t\texecSync(\"clip\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else {\n\t\t\t\t// Linux. Try Termux, Wayland, or X11 clipboard tools.\n\t\t\t\tif (process.env.TERMUX_VERSION) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\texecSync(\"termux-clipboard-set\", options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Fall back to Wayland or X11 tools.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!copied) {\n\t\t\t\t\tconst hasWaylandDisplay = Boolean(process.env.WAYLAND_DISPLAY);\n\t\t\t\t\tconst hasX11Display = Boolean(process.env.DISPLAY);\n\t\t\t\t\tconst isWayland = isWaylandSession();\n\t\t\t\t\tif (isWayland && hasWaylandDisplay) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// Verify wl-copy exists (spawn errors are async and won't be caught)\n\t\t\t\t\t\t\texecSync(\"which wl-copy\", { stdio: \"ignore\" });\n\t\t\t\t\t\t\t// wl-copy with execSync hangs due to fork behavior; use spawn instead.\n\t\t\t\t\t\t\t// Await the exit code and only claim success on a clean exit, so a\n\t\t\t\t\t\t\t// failed wl-copy falls through to the xclip/OSC 52 fallbacks.\n\t\t\t\t\t\t\tconst wlCopyExit = await new Promise((resolve) => {\n\t\t\t\t\t\t\t\tconst proc = spawn(\"wl-copy\", [], { stdio: [\"pipe\", \"ignore\", \"ignore\"] });\n\t\t\t\t\t\t\t\tproc.on(\"error\", () => resolve(1));\n\t\t\t\t\t\t\t\tproc.on(\"close\", (code) => resolve(code ?? 1));\n\t\t\t\t\t\t\t\tproc.stdin.on(\"error\", () => {\n\t\t\t\t\t\t\t\t\t// Ignore EPIPE errors if wl-copy exits early\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tproc.stdin.write(text);\n\t\t\t\t\t\t\t\tproc.stdin.end();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (wlCopyExit === 0) {\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t} else if (hasX11Display) {\n\t\t\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tif (hasX11Display) {\n\t\t\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (hasX11Display) {\n\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to OSC 52 fallback.\n\t\t}\n\t}\n\n\tif (remote || !copied) {\n\t\tconst osc52Copied = emitOsc52(text);\n\t\tcopied = copied || osc52Copied;\n\t}\n\n\tif (!copied) {\n\t\tthrow new Error(\"Failed to copy to clipboard\");\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/clipboard.js b/dist/utils/clipboard.js new file mode 100644 index 0000000..f4bd4fc --- /dev/null +++ b/dist/utils/clipboard.js @@ -0,0 +1,141 @@ +import { execSync, spawn } from "child_process"; +import { platform } from "os"; +import { isWaylandSession } from "./clipboard-image.js"; +import { clipboard } from "./clipboard-native.js"; +function copyToX11Clipboard(options) { + try { + execSync("xclip -selection clipboard", options); + } + catch { + execSync("xsel --clipboard --input", options); + } +} +const MAX_OSC52_ENCODED_LENGTH = 100_000; +function isRemoteSession(env = process.env) { + return Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.MOSH_CONNECTION); +} +function emitOsc52(text) { + const encoded = Buffer.from(text).toString("base64"); + if (encoded.length > MAX_OSC52_ENCODED_LENGTH) { + return false; + } + process.stdout.write(`\x1b]52;c;${encoded}\x07`); + return true; +} +/** Read plain text from the system clipboard, if native clipboard access is available. */ +export async function readClipboardText() { + if (!clipboard) { + return null; + } + try { + const text = await clipboard.getText(); + return text || null; + } + catch { + return null; + } +} +export async function copyToClipboard(text) { + let copied = false; + const p = platform(); + // Prefer direct clipboard writes. Emitting OSC 52 first can make terminals + // write the same native clipboard concurrently with the addon, and very large + // OSC 52 payloads can desynchronize terminal rendering. + // + // On Linux, skip the native addon. The underlying `clipboard-rs` crate is + // X11-only and does not retain selection ownership after `set_text` + // resolves, so on Wayland-only compositors (Hyprland, Niri, ...) and even + // some X11 sessions the call resolves successfully without populating the + // clipboard. The platform tools below (wl-copy, xclip, xsel) properly + // daemonize and keep ownership. + try { + if (clipboard && p !== "linux") { + await clipboard.setText(text); + copied = true; + } + } + catch { + // Fall through to platform-specific clipboard tools. + } + const remote = isRemoteSession(); + if (copied && !remote) { + return; + } + const options = { input: text, timeout: 5000, stdio: ["pipe", "ignore", "ignore"] }; + if (!copied) { + try { + if (p === "darwin") { + execSync("pbcopy", options); + copied = true; + } + else if (p === "win32") { + execSync("clip", options); + copied = true; + } + else { + // Linux. Try Termux, Wayland, or X11 clipboard tools. + if (process.env.TERMUX_VERSION) { + try { + execSync("termux-clipboard-set", options); + copied = true; + } + catch { + // Fall back to Wayland or X11 tools. + } + } + if (!copied) { + const hasWaylandDisplay = Boolean(process.env.WAYLAND_DISPLAY); + const hasX11Display = Boolean(process.env.DISPLAY); + const isWayland = isWaylandSession(); + if (isWayland && hasWaylandDisplay) { + try { + // Verify wl-copy exists (spawn errors are async and won't be caught) + execSync("which wl-copy", { stdio: "ignore" }); + // wl-copy with execSync hangs due to fork behavior; use spawn instead. + // Await the exit code and only claim success on a clean exit, so a + // failed wl-copy falls through to the xclip/OSC 52 fallbacks. + const wlCopyExit = await new Promise((resolve) => { + const proc = spawn("wl-copy", [], { stdio: ["pipe", "ignore", "ignore"] }); + proc.on("error", () => resolve(1)); + proc.on("close", (code) => resolve(code ?? 1)); + proc.stdin.on("error", () => { + // Ignore EPIPE errors if wl-copy exits early + }); + proc.stdin.write(text); + proc.stdin.end(); + }); + if (wlCopyExit === 0) { + copied = true; + } + else if (hasX11Display) { + copyToX11Clipboard(options); + copied = true; + } + } + catch { + if (hasX11Display) { + copyToX11Clipboard(options); + copied = true; + } + } + } + else if (hasX11Display) { + copyToX11Clipboard(options); + copied = true; + } + } + } + } + catch { + // Fall through to OSC 52 fallback. + } + } + if (remote || !copied) { + const osc52Copied = emitOsc52(text); + copied = copied || osc52Copied; + } + if (!copied) { + throw new Error("Failed to copy to clipboard"); + } +} +//# sourceMappingURL=clipboard.js.map \ No newline at end of file diff --git a/dist/utils/clipboard.js.map b/dist/utils/clipboard.js.map new file mode 100644 index 0000000..d822541 --- /dev/null +++ b/dist/utils/clipboard.js.map @@ -0,0 +1 @@ +{"version":3,"file":"clipboard.js","sourceRoot":"","sources":["../../src/utils/clipboard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAC9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAQlD,SAAS,kBAAkB,CAAC,OAAmC,EAAQ;IACtE,IAAI,CAAC;QACJ,QAAQ,CAAC,4BAA4B,EAAE,OAAO,CAAC,CAAC;IACjD,CAAC;IAAC,MAAM,CAAC;QACR,QAAQ,CAAC,0BAA0B,EAAE,OAAO,CAAC,CAAC;IAC/C,CAAC;AAAA,CACD;AAED,MAAM,wBAAwB,GAAG,OAAO,CAAC;AAEzC,SAAS,eAAe,CAAC,GAAG,GAAsB,OAAO,CAAC,GAAG,EA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O,CAAC,CAAC;wBAC5B,MAAM,GAAG,IAAI,CAAC;oBACf,CAAC;gBACF,CAAC;YACF,CAAC;QACF,CAAC;QAAC,MAAM,CAAC;YACR,mCAAmC;QACpC,CAAC;IACF,CAAC;IAED,IAAI,MAAM,IAAI,CAAC,MAAM,EAAE,CAAC;QACvB,MAAM,WAAW,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;QACpC,MAAM,GAAG,MAAM,IAAI,WAAW,CAAC;IAChC,CAAC;IAED,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IAChD,CAAC;AAAA,CACD","sourcesContent":["import { execSync, spawn } from \"child_process\";\nimport { platform } from \"os\";\nimport { isWaylandSession } from \"./clipboard-image.ts\";\nimport { clipboard } from \"./clipboard-native.ts\";\n\ntype NativeClipboardExecOptions = {\n\tinput: string;\n\ttimeout: number;\n\tstdio: [\"pipe\", \"ignore\", \"ignore\"];\n};\n\nfunction copyToX11Clipboard(options: NativeClipboardExecOptions): void {\n\ttry {\n\t\texecSync(\"xclip -selection clipboard\", options);\n\t} catch {\n\t\texecSync(\"xsel --clipboard --input\", options);\n\t}\n}\n\nconst MAX_OSC52_ENCODED_LENGTH = 100_000;\n\nfunction isRemoteSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.MOSH_CONNECTION);\n}\n\nfunction emitOsc52(text: string): boolean {\n\tconst encoded = Buffer.from(text).toString(\"base64\");\n\tif (encoded.length > MAX_OSC52_ENCODED_LENGTH) {\n\t\treturn false;\n\t}\n\tprocess.stdout.write(`\\x1b]52;c;${encoded}\\x07`);\n\treturn true;\n}\n\n/** Read plain text from the system clipboard, if native clipboard access is available. */\nexport async function readClipboardText(): Promise {\n\tif (!clipboard) {\n\t\treturn null;\n\t}\n\n\ttry {\n\t\tconst text = await clipboard.getText();\n\t\treturn text || null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport async function copyToClipboard(text: string): Promise {\n\tlet copied = false;\n\n\tconst p = platform();\n\n\t// Prefer direct clipboard writes. Emitting OSC 52 first can make terminals\n\t// write the same native clipboard concurrently with the addon, and very large\n\t// OSC 52 payloads can desynchronize terminal rendering.\n\t//\n\t// On Linux, skip the native addon. The underlying `clipboard-rs` crate is\n\t// X11-only and does not retain selection ownership after `set_text`\n\t// resolves, so on Wayland-only compositors (Hyprland, Niri, ...) and even\n\t// some X11 sessions the call resolves successfully without populating the\n\t// clipboard. The platform tools below (wl-copy, xclip, xsel) properly\n\t// daemonize and keep ownership.\n\ttry {\n\t\tif (clipboard && p !== \"linux\") {\n\t\t\tawait clipboard.setText(text);\n\t\t\tcopied = true;\n\t\t}\n\t} catch {\n\t\t// Fall through to platform-specific clipboard tools.\n\t}\n\n\tconst remote = isRemoteSession();\n\tif (copied && !remote) {\n\t\treturn;\n\t}\n\n\tconst options: NativeClipboardExecOptions = { input: text, timeout: 5000, stdio: [\"pipe\", \"ignore\", \"ignore\"] };\n\n\tif (!copied) {\n\t\ttry {\n\t\t\tif (p === \"darwin\") {\n\t\t\t\texecSync(\"pbcopy\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else if (p === \"win32\") {\n\t\t\t\texecSync(\"clip\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else {\n\t\t\t\t// Linux. Try Termux, Wayland, or X11 clipboard tools.\n\t\t\t\tif (process.env.TERMUX_VERSION) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\texecSync(\"termux-clipboard-set\", options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Fall back to Wayland or X11 tools.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!copied) {\n\t\t\t\t\tconst hasWaylandDisplay = Boolean(process.env.WAYLAND_DISPLAY);\n\t\t\t\t\tconst hasX11Display = Boolean(process.env.DISPLAY);\n\t\t\t\t\tconst isWayland = isWaylandSession();\n\t\t\t\t\tif (isWayland && hasWaylandDisplay) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// Verify wl-copy exists (spawn errors are async and won't be caught)\n\t\t\t\t\t\t\texecSync(\"which wl-copy\", { stdio: \"ignore\" });\n\t\t\t\t\t\t\t// wl-copy with execSync hangs due to fork behavior; use spawn instead.\n\t\t\t\t\t\t\t// Await the exit code and only claim success on a clean exit, so a\n\t\t\t\t\t\t\t// failed wl-copy falls through to the xclip/OSC 52 fallbacks.\n\t\t\t\t\t\t\tconst wlCopyExit = await new Promise((resolve) => {\n\t\t\t\t\t\t\t\tconst proc = spawn(\"wl-copy\", [], { stdio: [\"pipe\", \"ignore\", \"ignore\"] });\n\t\t\t\t\t\t\t\tproc.on(\"error\", () => resolve(1));\n\t\t\t\t\t\t\t\tproc.on(\"close\", (code) => resolve(code ?? 1));\n\t\t\t\t\t\t\t\tproc.stdin.on(\"error\", () => {\n\t\t\t\t\t\t\t\t\t// Ignore EPIPE errors if wl-copy exits early\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tproc.stdin.write(text);\n\t\t\t\t\t\t\t\tproc.stdin.end();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (wlCopyExit === 0) {\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t} else if (hasX11Display) {\n\t\t\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tif (hasX11Display) {\n\t\t\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (hasX11Display) {\n\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to OSC 52 fallback.\n\t\t}\n\t}\n\n\tif (remote || !copied) {\n\t\tconst osc52Copied = emitOsc52(text);\n\t\tcopied = copied || osc52Copied;\n\t}\n\n\tif (!copied) {\n\t\tthrow new Error(\"Failed to copy to clipboard\");\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/deprecation.d.ts b/dist/utils/deprecation.d.ts new file mode 100644 index 0000000..1283bcd --- /dev/null +++ b/dist/utils/deprecation.d.ts @@ -0,0 +1,4 @@ +export declare function warnDeprecation(message: string): void; +/** Clear deprecation warning state. Exported for tests. */ +export declare function clearDeprecationWarningsForTests(): void; +//# sourceMappingURL=deprecation.d.ts.map \ No newline at end of file diff --git a/dist/utils/deprecation.d.ts.map b/dist/utils/deprecation.d.ts.map new file mode 100644 index 0000000..ceb1a3d --- /dev/null +++ b/dist/utils/deprecation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"deprecation.d.ts","sourceRoot":"","sources":["../../src/utils/deprecation.ts"],"names":[],"mappings":"AAIA,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAIrD;AAED,2DAA2D;AAC3D,wBAAgB,gCAAgC,IAAI,IAAI,CAEvD","sourcesContent":["import chalk from \"chalk\";\n\nconst emittedDeprecationWarnings = new Set();\n\nexport function warnDeprecation(message: string): void {\n\tif (emittedDeprecationWarnings.has(message)) return;\n\temittedDeprecationWarnings.add(message);\n\tconsole.warn(chalk.yellow(`Deprecation warning: ${message}`));\n}\n\n/** Clear deprecation warning state. Exported for tests. */\nexport function clearDeprecationWarningsForTests(): void {\n\temittedDeprecationWarnings.clear();\n}\n"]} \ No newline at end of file diff --git a/dist/utils/deprecation.js b/dist/utils/deprecation.js new file mode 100644 index 0000000..21078b7 --- /dev/null +++ b/dist/utils/deprecation.js @@ -0,0 +1,13 @@ +import chalk from "chalk"; +const emittedDeprecationWarnings = new Set(); +export function warnDeprecation(message) { + if (emittedDeprecationWarnings.has(message)) + return; + emittedDeprecationWarnings.add(message); + console.warn(chalk.yellow(`Deprecation warning: ${message}`)); +} +/** Clear deprecation warning state. Exported for tests. */ +export function clearDeprecationWarningsForTests() { + emittedDeprecationWarnings.clear(); +} +//# sourceMappingURL=deprecation.js.map \ No newline at end of file diff --git a/dist/utils/deprecation.js.map b/dist/utils/deprecation.js.map new file mode 100644 index 0000000..77fc4d1 --- /dev/null +++ b/dist/utils/deprecation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deprecation.js","sourceRoot":"","sources":["../../src/utils/deprecation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,MAAM,0BAA0B,GAAG,IAAI,GAAG,EAAU,CAAC;AAErD,MAAM,UAAU,eAAe,CAAC,OAAe,EAAQ;IACtD,IAAI,0BAA0B,CAAC,GAAG,CAAC,OAAO,CAAC;QAAE,OAAO;IACpD,0BAA0B,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,wBAAwB,OAAO,EAAE,CAAC,CAAC,CAAC;AAAA,CAC9D;AAED,2DAA2D;AAC3D,MAAM,UAAU,gCAAgC,GAAS;IACxD,0BAA0B,CAAC,KAAK,EAAE,CAAC;AAAA,CACnC","sourcesContent":["import chalk from \"chalk\";\n\nconst emittedDeprecationWarnings = new Set();\n\nexport function warnDeprecation(message: string): void {\n\tif (emittedDeprecationWarnings.has(message)) return;\n\temittedDeprecationWarnings.add(message);\n\tconsole.warn(chalk.yellow(`Deprecation warning: ${message}`));\n}\n\n/** Clear deprecation warning state. Exported for tests. */\nexport function clearDeprecationWarningsForTests(): void {\n\temittedDeprecationWarnings.clear();\n}\n"]} \ No newline at end of file diff --git a/dist/utils/exif-orientation.d.ts b/dist/utils/exif-orientation.d.ts new file mode 100644 index 0000000..40d95bf --- /dev/null +++ b/dist/utils/exif-orientation.d.ts @@ -0,0 +1,5 @@ +import type { PhotonImageType } from "./photon.ts"; +type Photon = typeof import("@silvia-odwyer/photon-node"); +export declare function applyExifOrientation(photon: Photon, image: PhotonImageType, originalBytes: Uint8Array): PhotonImageType; +export {}; +//# sourceMappingURL=exif-orientation.d.ts.map \ No newline at end of file diff --git a/dist/utils/exif-orientation.d.ts.map b/dist/utils/exif-orientation.d.ts.map new file mode 100644 index 0000000..871794f --- /dev/null +++ b/dist/utils/exif-orientation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"exif-orientation.d.ts","sourceRoot":"","sources":["../../src/utils/exif-orientation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,KAAK,MAAM,GAAG,cAAc,4BAA4B,CAAC,CAAC;AAgJ1D,wBAAgB,oBAAoB,CACnC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,eAAe,EACtB,aAAa,EAAE,UAAU,GACvB,eAAe,CAgCjB","sourcesContent":["import type { PhotonImageType } from \"./photon.ts\";\n\ntype Photon = typeof import(\"@silvia-odwyer/photon-node\");\n\nfunction readOrientationFromTiff(bytes: Uint8Array, tiffStart: number): number {\n\tif (tiffStart + 8 > bytes.length) return 1;\n\n\tconst byteOrder = (bytes[tiffStart] << 8) | bytes[tiffStart + 1];\n\tconst le = byteOrder === 0x4949;\n\n\tconst read16 = (pos: number): number => {\n\t\tif (le) return bytes[pos] | (bytes[pos + 1] << 8);\n\t\treturn (bytes[pos] << 8) | bytes[pos + 1];\n\t};\n\n\tconst read32 = (pos: number): number => {\n\t\tif (le) return bytes[pos] | (bytes[pos + 1] << 8) | (bytes[pos + 2] << 16) | (bytes[pos + 3] << 24);\n\t\treturn ((bytes[pos] << 24) | (bytes[pos + 1] << 16) | (bytes[pos + 2] << 8) | bytes[pos + 3]) >>> 0;\n\t};\n\n\tconst ifdOffset = read32(tiffStart + 4);\n\tconst ifdStart = tiffStart + ifdOffset;\n\tif (ifdStart + 2 > bytes.length) return 1;\n\n\tconst entryCount = read16(ifdStart);\n\tfor (let i = 0; i < entryCount; i++) {\n\t\tconst entryPos = ifdStart + 2 + i * 12;\n\t\tif (entryPos + 12 > bytes.length) return 1;\n\n\t\tif (read16(entryPos) === 0x0112) {\n\t\t\tconst value = read16(entryPos + 8);\n\t\t\treturn value >= 1 && value <= 8 ? value : 1;\n\t\t}\n\t}\n\n\treturn 1;\n}\n\nfunction findJpegTiffOffset(bytes: Uint8Array): number {\n\tlet offset = 2;\n\twhile (offset < bytes.length - 1) {\n\t\tif (bytes[offset] !== 0xff) return -1;\n\t\tconst marker = bytes[offset + 1];\n\t\tif (marker === 0xff) {\n\t\t\toffset++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (marker === 0xe1) {\n\t\t\tif (offset + 4 >= bytes.length) return -1;\n\t\t\tconst segmentStart = offset + 4;\n\t\t\tif (segmentStart + 6 > bytes.length) return -1;\n\t\t\tif (!hasExifHeader(bytes, segmentStart)) return -1;\n\t\t\treturn segmentStart + 6;\n\t\t}\n\n\t\tif (offset + 4 > bytes.length) return -1;\n\t\tconst length = (bytes[offset + 2] << 8) | bytes[offset + 3];\n\t\toffset += 2 + length;\n\t}\n\n\treturn -1;\n}\n\nfunction findWebpTiffOffset(bytes: Uint8Array): number {\n\tlet offset = 12;\n\twhile (offset + 8 <= bytes.length) {\n\t\tconst chunkId = String.fromCharCode(bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]);\n\t\tconst chunkSize =\n\t\t\tbytes[offset + 4] | (bytes[offset + 5] << 8) | (bytes[offset + 6] << 16) | (bytes[offset + 7] << 24);\n\t\tconst dataStart = offset + 8;\n\n\t\tif (chunkId === \"EXIF\") {\n\t\t\tif (dataStart + chunkSize > bytes.length) return -1;\n\t\t\t// Some WebP files have \"Exif\\0\\0\" prefix before the TIFF header\n\t\t\tconst tiffStart = chunkSize >= 6 && hasExifHeader(bytes, dataStart) ? dataStart + 6 : dataStart;\n\t\t\treturn tiffStart;\n\t\t}\n\n\t\t// RIFF chunks are padded to even size\n\t\toffset = dataStart + chunkSize + (chunkSize % 2);\n\t}\n\n\treturn -1;\n}\n\nfunction hasExifHeader(bytes: Uint8Array, offset: number): boolean {\n\treturn (\n\t\tbytes[offset] === 0x45 &&\n\t\tbytes[offset + 1] === 0x78 &&\n\t\tbytes[offset + 2] === 0x69 &&\n\t\tbytes[offset + 3] === 0x66 &&\n\t\tbytes[offset + 4] === 0x00 &&\n\t\tbytes[offset + 5] === 0x00\n\t);\n}\n\nfunction getExifOrientation(bytes: Uint8Array): number {\n\tlet tiffOffset = -1;\n\n\t// JPEG: starts with FF D8\n\tif (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xd8) {\n\t\ttiffOffset = findJpegTiffOffset(bytes);\n\t}\n\t// WebP: starts with RIFF....WEBP\n\telse if (\n\t\tbytes.length >= 12 &&\n\t\tbytes[0] === 0x52 &&\n\t\tbytes[1] === 0x49 &&\n\t\tbytes[2] === 0x46 &&\n\t\tbytes[3] === 0x46 &&\n\t\tbytes[8] === 0x57 &&\n\t\tbytes[9] === 0x45 &&\n\t\tbytes[10] === 0x42 &&\n\t\tbytes[11] === 0x50\n\t) {\n\t\ttiffOffset = findWebpTiffOffset(bytes);\n\t}\n\n\tif (tiffOffset === -1) return 1;\n\treturn readOrientationFromTiff(bytes, tiffOffset);\n}\n\ntype DstIndexFn = (x: number, y: number, w: number, h: number) => number;\n\nfunction rotate90(photon: Photon, image: PhotonImageType, dstIndex: DstIndexFn): PhotonImageType {\n\tconst w = image.get_width();\n\tconst h = image.get_height();\n\tconst src = image.get_raw_pixels();\n\tconst dst = new Uint8Array(src.length);\n\n\tfor (let y = 0; y < h; y++) {\n\t\tfor (let x = 0; x < w; x++) {\n\t\t\tconst srcIdx = (y * w + x) * 4;\n\t\t\tconst dstIdx = dstIndex(x, y, w, h) * 4;\n\t\t\tdst[dstIdx] = src[srcIdx];\n\t\t\tdst[dstIdx + 1] = src[srcIdx + 1];\n\t\t\tdst[dstIdx + 2] = src[srcIdx + 2];\n\t\t\tdst[dstIdx + 3] = src[srcIdx + 3];\n\t\t}\n\t}\n\n\treturn new photon.PhotonImage(dst, h, w);\n}\n\n// Flip orientations mutate in-place. Rotations return a new image (caller must free the old one if different).\nexport function applyExifOrientation(\n\tphoton: Photon,\n\timage: PhotonImageType,\n\toriginalBytes: Uint8Array,\n): PhotonImageType {\n\tconst orientation = getExifOrientation(originalBytes);\n\tif (orientation === 1) return image;\n\n\tswitch (orientation) {\n\t\tcase 2:\n\t\t\tphoton.fliph(image);\n\t\t\treturn image;\n\t\tcase 3:\n\t\t\tphoton.fliph(image);\n\t\t\tphoton.flipv(image);\n\t\t\treturn image;\n\t\tcase 4:\n\t\t\tphoton.flipv(image);\n\t\t\treturn image;\n\t\tcase 5: {\n\t\t\tconst rotated = rotate90(photon, image, (x, y, _w, h) => x * h + (h - 1 - y));\n\t\t\tphoton.fliph(rotated);\n\t\t\treturn rotated;\n\t\t}\n\t\tcase 6:\n\t\t\treturn rotate90(photon, image, (x, y, _w, h) => x * h + (h - 1 - y));\n\t\tcase 7: {\n\t\t\tconst rotated = rotate90(photon, image, (x, y, w, h) => (w - 1 - x) * h + y);\n\t\t\tphoton.fliph(rotated);\n\t\t\treturn rotated;\n\t\t}\n\t\tcase 8:\n\t\t\treturn rotate90(photon, image, (x, y, w, h) => (w - 1 - x) * h + y);\n\t\tdefault:\n\t\t\treturn image;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/exif-orientation.js b/dist/utils/exif-orientation.js new file mode 100644 index 0000000..a49332f --- /dev/null +++ b/dist/utils/exif-orientation.js @@ -0,0 +1,158 @@ +function readOrientationFromTiff(bytes, tiffStart) { + if (tiffStart + 8 > bytes.length) + return 1; + const byteOrder = (bytes[tiffStart] << 8) | bytes[tiffStart + 1]; + const le = byteOrder === 0x4949; + const read16 = (pos) => { + if (le) + return bytes[pos] | (bytes[pos + 1] << 8); + return (bytes[pos] << 8) | bytes[pos + 1]; + }; + const read32 = (pos) => { + if (le) + return bytes[pos] | (bytes[pos + 1] << 8) | (bytes[pos + 2] << 16) | (bytes[pos + 3] << 24); + return ((bytes[pos] << 24) | (bytes[pos + 1] << 16) | (bytes[pos + 2] << 8) | bytes[pos + 3]) >>> 0; + }; + const ifdOffset = read32(tiffStart + 4); + const ifdStart = tiffStart + ifdOffset; + if (ifdStart + 2 > bytes.length) + return 1; + const entryCount = read16(ifdStart); + for (let i = 0; i < entryCount; i++) { + const entryPos = ifdStart + 2 + i * 12; + if (entryPos + 12 > bytes.length) + return 1; + if (read16(entryPos) === 0x0112) { + const value = read16(entryPos + 8); + return value >= 1 && value <= 8 ? value : 1; + } + } + return 1; +} +function findJpegTiffOffset(bytes) { + let offset = 2; + while (offset < bytes.length - 1) { + if (bytes[offset] !== 0xff) + return -1; + const marker = bytes[offset + 1]; + if (marker === 0xff) { + offset++; + continue; + } + if (marker === 0xe1) { + if (offset + 4 >= bytes.length) + return -1; + const segmentStart = offset + 4; + if (segmentStart + 6 > bytes.length) + return -1; + if (!hasExifHeader(bytes, segmentStart)) + return -1; + return segmentStart + 6; + } + if (offset + 4 > bytes.length) + return -1; + const length = (bytes[offset + 2] << 8) | bytes[offset + 3]; + offset += 2 + length; + } + return -1; +} +function findWebpTiffOffset(bytes) { + let offset = 12; + while (offset + 8 <= bytes.length) { + const chunkId = String.fromCharCode(bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]); + const chunkSize = bytes[offset + 4] | (bytes[offset + 5] << 8) | (bytes[offset + 6] << 16) | (bytes[offset + 7] << 24); + const dataStart = offset + 8; + if (chunkId === "EXIF") { + if (dataStart + chunkSize > bytes.length) + return -1; + // Some WebP files have "Exif\0\0" prefix before the TIFF header + const tiffStart = chunkSize >= 6 && hasExifHeader(bytes, dataStart) ? dataStart + 6 : dataStart; + return tiffStart; + } + // RIFF chunks are padded to even size + offset = dataStart + chunkSize + (chunkSize % 2); + } + return -1; +} +function hasExifHeader(bytes, offset) { + return (bytes[offset] === 0x45 && + bytes[offset + 1] === 0x78 && + bytes[offset + 2] === 0x69 && + bytes[offset + 3] === 0x66 && + bytes[offset + 4] === 0x00 && + bytes[offset + 5] === 0x00); +} +function getExifOrientation(bytes) { + let tiffOffset = -1; + // JPEG: starts with FF D8 + if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xd8) { + tiffOffset = findJpegTiffOffset(bytes); + } + // WebP: starts with RIFF....WEBP + else if (bytes.length >= 12 && + bytes[0] === 0x52 && + bytes[1] === 0x49 && + bytes[2] === 0x46 && + bytes[3] === 0x46 && + bytes[8] === 0x57 && + bytes[9] === 0x45 && + bytes[10] === 0x42 && + bytes[11] === 0x50) { + tiffOffset = findWebpTiffOffset(bytes); + } + if (tiffOffset === -1) + return 1; + return readOrientationFromTiff(bytes, tiffOffset); +} +function rotate90(photon, image, dstIndex) { + const w = image.get_width(); + const h = image.get_height(); + const src = image.get_raw_pixels(); + const dst = new Uint8Array(src.length); + for (let y = 0; y < h; y++) { + for (let x = 0; x < w; x++) { + const srcIdx = (y * w + x) * 4; + const dstIdx = dstIndex(x, y, w, h) * 4; + dst[dstIdx] = src[srcIdx]; + dst[dstIdx + 1] = src[srcIdx + 1]; + dst[dstIdx + 2] = src[srcIdx + 2]; + dst[dstIdx + 3] = src[srcIdx + 3]; + } + } + return new photon.PhotonImage(dst, h, w); +} +// Flip orientations mutate in-place. Rotations return a new image (caller must free the old one if different). +export function applyExifOrientation(photon, image, originalBytes) { + const orientation = getExifOrientation(originalBytes); + if (orientation === 1) + return image; + switch (orientation) { + case 2: + photon.fliph(image); + return image; + case 3: + photon.fliph(image); + photon.flipv(image); + return image; + case 4: + photon.flipv(image); + return image; + case 5: { + const rotated = rotate90(photon, image, (x, y, _w, h) => x * h + (h - 1 - y)); + photon.fliph(rotated); + return rotated; + } + case 6: + return rotate90(photon, image, (x, y, _w, h) => x * h + (h - 1 - y)); + case 7: { + const rotated = rotate90(photon, image, (x, y, w, h) => (w - 1 - x) * h + y); + photon.fliph(rotated); + return rotated; + } + case 8: + return rotate90(photon, image, (x, y, w, h) => (w - 1 - x) * h + y); + default: + return image; + } +} +//# sourceMappingURL=exif-orientation.js.map \ No newline at end of file diff --git a/dist/utils/exif-orientation.js.map b/dist/utils/exif-orientation.js.map new file mode 100644 index 0000000..a9606ea --- /dev/null +++ b/dist/utils/exif-orientation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"exif-orientation.js","sourceRoot":"","sources":["../../src/utils/exif-orientation.ts"],"names":[],"mappings":"AAIA,SAAS,uBAAuB,CAAC,KAAiB,EAAE,SAAiB,EAAU;IAC9E,IAAI,SAAS,GAAG,CAAC,GAAG,KAAK,CAAC,MAAM;QAAE,OAAO,CAAC,CAAC;IAE3C,MAAM,SAAS,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC;IACjE,MAAM,EAAE,GAAG,SAAS,KAAK,MAAM,CAAC;IAEhC,MAAM,MAAM,GAAG,CAAC,GAAW,EAAU,EAAE,CAAC;QACvC,IAAI,EAAE;YAAE,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;QAClD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;IAAA,CAC1C,CAAC;IAEF,MAAM,MAAM,GAAG,CAAC,GAAW,EAAU,EAAE,CAAC;QACvC,IAAI,EAAE;YAAE,OAAO,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;QACpG,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,CA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n\nfunction readOrientationFromTiff(bytes: Uint8Array, tiffStart: number): number {\n\tif (tiffStart + 8 > bytes.length) return 1;\n\n\tconst byteOrder = (bytes[tiffStart] << 8) | bytes[tiffStart + 1];\n\tconst le = byteOrder === 0x4949;\n\n\tconst read16 = (pos: number): number => {\n\t\tif (le) return bytes[pos] | (bytes[pos + 1] << 8);\n\t\treturn (bytes[pos] << 8) | bytes[pos + 1];\n\t};\n\n\tconst read32 = (pos: number): number => {\n\t\tif (le) return bytes[pos] | (bytes[pos + 1] << 8) | (bytes[pos + 2] << 16) | (bytes[pos + 3] << 24);\n\t\treturn ((bytes[pos] << 24) | (bytes[pos + 1] << 16) | (bytes[pos + 2] << 8) | bytes[pos + 3]) >>> 0;\n\t};\n\n\tconst ifdOffset = read32(tiffStart + 4);\n\tconst ifdStart = tiffStart + ifdOffset;\n\tif (ifdStart + 2 > bytes.length) return 1;\n\n\tconst entryCount = read16(ifdStart);\n\tfor (let i = 0; i < entryCount; i++) {\n\t\tconst entryPos = ifdStart + 2 + i * 12;\n\t\tif (entryPos + 12 > bytes.length) return 1;\n\n\t\tif (read16(entryPos) === 0x0112) {\n\t\t\tconst value = read16(entryPos + 8);\n\t\t\treturn value >= 1 && value <= 8 ? value : 1;\n\t\t}\n\t}\n\n\treturn 1;\n}\n\nfunction findJpegTiffOffset(bytes: Uint8Array): number {\n\tlet offset = 2;\n\twhile (offset < bytes.length - 1) {\n\t\tif (bytes[offset] !== 0xff) return -1;\n\t\tconst marker = bytes[offset + 1];\n\t\tif (marker === 0xff) {\n\t\t\toffset++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (marker === 0xe1) {\n\t\t\tif (offset + 4 >= bytes.length) return -1;\n\t\t\tconst segmentStart = offset + 4;\n\t\t\tif (segmentStart + 6 > bytes.length) return -1;\n\t\t\tif (!hasExifHeader(bytes, segmentStart)) return -1;\n\t\t\treturn segmentStart + 6;\n\t\t}\n\n\t\tif (offset + 4 > bytes.length) return -1;\n\t\tconst length = (bytes[offset + 2] << 8) | bytes[offset + 3];\n\t\toffset += 2 + length;\n\t}\n\n\treturn -1;\n}\n\nfunction findWebpTiffOffset(bytes: Uint8Array): number {\n\tlet offset = 12;\n\twhile (offset + 8 <= bytes.length) {\n\t\tconst chunkId = String.fromCharCode(bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]);\n\t\tconst chunkSize =\n\t\t\tbytes[offset + 4] | (bytes[offset + 5] << 8) | (bytes[offset + 6] << 16) | (bytes[offset + 7] << 24);\n\t\tconst dataStart = offset + 8;\n\n\t\tif (chunkId === \"EXIF\") {\n\t\t\tif (dataStart + chunkSize > bytes.length) return -1;\n\t\t\t// Some WebP files have \"Exif\\0\\0\" prefix before the TIFF header\n\t\t\tconst tiffStart = chunkSize >= 6 && hasExifHeader(bytes, dataStart) ? dataStart + 6 : dataStart;\n\t\t\treturn tiffStart;\n\t\t}\n\n\t\t// RIFF chunks are padded to even size\n\t\toffset = dataStart + chunkSize + (chunkSize % 2);\n\t}\n\n\treturn -1;\n}\n\nfunction hasExifHeader(bytes: Uint8Array, offset: number): boolean {\n\treturn (\n\t\tbytes[offset] === 0x45 &&\n\t\tbytes[offset + 1] === 0x78 &&\n\t\tbytes[offset + 2] === 0x69 &&\n\t\tbytes[offset + 3] === 0x66 &&\n\t\tbytes[offset + 4] === 0x00 &&\n\t\tbytes[offset + 5] === 0x00\n\t);\n}\n\nfunction getExifOrientation(bytes: Uint8Array): number {\n\tlet tiffOffset = -1;\n\n\t// JPEG: starts with FF D8\n\tif (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xd8) {\n\t\ttiffOffset = findJpegTiffOffset(bytes);\n\t}\n\t// WebP: starts with RIFF....WEBP\n\telse if (\n\t\tbytes.length >= 12 &&\n\t\tbytes[0] === 0x52 &&\n\t\tbytes[1] === 0x49 &&\n\t\tbytes[2] === 0x46 &&\n\t\tbytes[3] === 0x46 &&\n\t\tbytes[8] === 0x57 &&\n\t\tbytes[9] === 0x45 &&\n\t\tbytes[10] === 0x42 &&\n\t\tbytes[11] === 0x50\n\t) {\n\t\ttiffOffset = findWebpTiffOffset(bytes);\n\t}\n\n\tif (tiffOffset === -1) return 1;\n\treturn readOrientationFromTiff(bytes, tiffOffset);\n}\n\ntype DstIndexFn = (x: number, y: number, w: number, h: number) => number;\n\nfunction rotate90(photon: Photon, image: PhotonImageType, dstIndex: DstIndexFn): PhotonImageType {\n\tconst w = image.get_width();\n\tconst h = image.get_height();\n\tconst src = image.get_raw_pixels();\n\tconst dst = new Uint8Array(src.length);\n\n\tfor (let y = 0; y < h; y++) {\n\t\tfor (let x = 0; x < w; x++) {\n\t\t\tconst srcIdx = (y * w + x) * 4;\n\t\t\tconst dstIdx = dstIndex(x, y, w, h) * 4;\n\t\t\tdst[dstIdx] = src[srcIdx];\n\t\t\tdst[dstIdx + 1] = src[srcIdx + 1];\n\t\t\tdst[dstIdx + 2] = src[srcIdx + 2];\n\t\t\tdst[dstIdx + 3] = src[srcIdx + 3];\n\t\t}\n\t}\n\n\treturn new photon.PhotonImage(dst, h, w);\n}\n\n// Flip orientations mutate in-place. Rotations return a new image (caller must free the old one if different).\nexport function applyExifOrientation(\n\tphoton: Photon,\n\timage: PhotonImageType,\n\toriginalBytes: Uint8Array,\n): PhotonImageType {\n\tconst orientation = getExifOrientation(originalBytes);\n\tif (orientation === 1) return image;\n\n\tswitch (orientation) {\n\t\tcase 2:\n\t\t\tphoton.fliph(image);\n\t\t\treturn image;\n\t\tcase 3:\n\t\t\tphoton.fliph(image);\n\t\t\tphoton.flipv(image);\n\t\t\treturn image;\n\t\tcase 4:\n\t\t\tphoton.flipv(image);\n\t\t\treturn image;\n\t\tcase 5: {\n\t\t\tconst rotated = rotate90(photon, image, (x, y, _w, h) => x * h + (h - 1 - y));\n\t\t\tphoton.fliph(rotated);\n\t\t\treturn rotated;\n\t\t}\n\t\tcase 6:\n\t\t\treturn rotate90(photon, image, (x, y, _w, h) => x * h + (h - 1 - y));\n\t\tcase 7: {\n\t\t\tconst rotated = rotate90(photon, image, (x, y, w, h) => (w - 1 - x) * h + y);\n\t\t\tphoton.fliph(rotated);\n\t\t\treturn rotated;\n\t\t}\n\t\tcase 8:\n\t\t\treturn rotate90(photon, image, (x, y, w, h) => (w - 1 - x) * h + y);\n\t\tdefault:\n\t\t\treturn image;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/frontmatter.d.ts b/dist/utils/frontmatter.d.ts new file mode 100644 index 0000000..4d63591 --- /dev/null +++ b/dist/utils/frontmatter.d.ts @@ -0,0 +1,8 @@ +type ParsedFrontmatter> = { + frontmatter: T; + body: string; +}; +export declare const parseFrontmatter: = Record>(content: string) => ParsedFrontmatter; +export declare const stripFrontmatter: (content: string) => string; +export {}; +//# sourceMappingURL=frontmatter.d.ts.map \ No newline at end of file diff --git a/dist/utils/frontmatter.d.ts.map b/dist/utils/frontmatter.d.ts.map new file mode 100644 index 0000000..d09628c --- /dev/null +++ b/dist/utils/frontmatter.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"frontmatter.d.ts","sourceRoot":"","sources":["../../src/utils/frontmatter.ts"],"names":[],"mappings":"AAEA,KAAK,iBAAiB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI;IAC3D,WAAW,EAAE,CAAC,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;CACb,CAAC;AAsBF,eAAO,MAAM,gBAAgB,GAAI,CAAC,oGASjC,CAAC;AAEF,eAAO,MAAM,gBAAgB,6BAA8D,CAAC","sourcesContent":["import { parse } from \"yaml\";\n\ntype ParsedFrontmatter> = {\n\tfrontmatter: T;\n\tbody: string;\n};\n\nconst normalizeNewlines = (value: string): string => value.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n\nconst extractFrontmatter = (content: string): { yamlString: string | null; body: string } => {\n\tconst normalized = normalizeNewlines(content);\n\n\tif (!normalized.startsWith(\"---\")) {\n\t\treturn { yamlString: null, body: normalized };\n\t}\n\n\tconst endIndex = normalized.indexOf(\"\\n---\", 3);\n\tif (endIndex === -1) {\n\t\treturn { yamlString: null, body: normalized };\n\t}\n\n\treturn {\n\t\tyamlString: normalized.slice(4, endIndex),\n\t\tbody: normalized.slice(endIndex + 4).trim(),\n\t};\n};\n\nexport const parseFrontmatter = = Record>(\n\tcontent: string,\n): ParsedFrontmatter => {\n\tconst { yamlString, body } = extractFrontmatter(content);\n\tif (!yamlString) {\n\t\treturn { frontmatter: {} as T, body };\n\t}\n\tconst parsed = parse(yamlString);\n\treturn { frontmatter: (parsed ?? {}) as T, body };\n};\n\nexport const stripFrontmatter = (content: string): string => parseFrontmatter(content).body;\n"]} \ No newline at end of file diff --git a/dist/utils/frontmatter.js b/dist/utils/frontmatter.js new file mode 100644 index 0000000..b42a895 --- /dev/null +++ b/dist/utils/frontmatter.js @@ -0,0 +1,26 @@ +import { parse } from "yaml"; +const normalizeNewlines = (value) => value.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); +const extractFrontmatter = (content) => { + const normalized = normalizeNewlines(content); + if (!normalized.startsWith("---")) { + return { yamlString: null, body: normalized }; + } + const endIndex = normalized.indexOf("\n---", 3); + if (endIndex === -1) { + return { yamlString: null, body: normalized }; + } + return { + yamlString: normalized.slice(4, endIndex), + body: normalized.slice(endIndex + 4).trim(), + }; +}; +export const parseFrontmatter = (content) => { + const { yamlString, body } = extractFrontmatter(content); + if (!yamlString) { + return { frontmatter: {}, body }; + } + const parsed = parse(yamlString); + return { frontmatter: (parsed ?? {}), body }; +}; +export const stripFrontmatter = (content) => parseFrontmatter(content).body; +//# sourceMappingURL=frontmatter.js.map \ No newline at end of file diff --git a/dist/utils/frontmatter.js.map b/dist/utils/frontmatter.js.map new file mode 100644 index 0000000..22ea9e6 --- /dev/null +++ b/dist/utils/frontmatter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"frontmatter.js","sourceRoot":"","sources":["../../src/utils/frontmatter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK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,IAAI,EAAE,CAAC;AAAA,CAClD,CAAC;AAEF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,OAAe,EAAU,EAAE,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC","sourcesContent":["import { parse } from \"yaml\";\n\ntype ParsedFrontmatter> = {\n\tfrontmatter: T;\n\tbody: string;\n};\n\nconst normalizeNewlines = (value: string): string => value.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n\nconst extractFrontmatter = (content: string): { yamlString: string | null; body: string } => {\n\tconst normalized = normalizeNewlines(content);\n\n\tif (!normalized.startsWith(\"---\")) {\n\t\treturn { yamlString: null, body: normalized };\n\t}\n\n\tconst endIndex = normalized.indexOf(\"\\n---\", 3);\n\tif (endIndex === -1) {\n\t\treturn { yamlString: null, body: normalized };\n\t}\n\n\treturn {\n\t\tyamlString: normalized.slice(4, endIndex),\n\t\tbody: normalized.slice(endIndex + 4).trim(),\n\t};\n};\n\nexport const parseFrontmatter = = Record>(\n\tcontent: string,\n): ParsedFrontmatter => {\n\tconst { yamlString, body } = extractFrontmatter(content);\n\tif (!yamlString) {\n\t\treturn { frontmatter: {} as T, body };\n\t}\n\tconst parsed = parse(yamlString);\n\treturn { frontmatter: (parsed ?? {}) as T, body };\n};\n\nexport const stripFrontmatter = (content: string): string => parseFrontmatter(content).body;\n"]} \ No newline at end of file diff --git a/dist/utils/fs-watch.d.ts b/dist/utils/fs-watch.d.ts new file mode 100644 index 0000000..ffe0139 --- /dev/null +++ b/dist/utils/fs-watch.d.ts @@ -0,0 +1,5 @@ +import { type FSWatcher, type WatchListener } from "node:fs"; +export declare const FS_WATCH_RETRY_DELAY_MS = 5000; +export declare function closeWatcher(watcher: FSWatcher | null | undefined): void; +export declare function watchWithErrorHandler(path: string, listener: WatchListener, onError: () => void): FSWatcher | null; +//# sourceMappingURL=fs-watch.d.ts.map \ No newline at end of file diff --git a/dist/utils/fs-watch.d.ts.map b/dist/utils/fs-watch.d.ts.map new file mode 100644 index 0000000..586a77f --- /dev/null +++ b/dist/utils/fs-watch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fs-watch.d.ts","sourceRoot":"","sources":["../../src/utils/fs-watch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAE,KAAK,aAAa,EAAS,MAAM,SAAS,CAAC;AAEpE,eAAO,MAAM,uBAAuB,OAAO,CAAC;AAE5C,wBAAgB,YAAY,CAAC,OAAO,EAAE,SAAS,GAAG,IAAI,GAAG,SAAS,GAAG,IAAI,CAUxE;AAED,wBAAgB,qBAAqB,CACpC,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,aAAa,CAAC,MAAM,CAAC,EAC/B,OAAO,EAAE,MAAM,IAAI,GACjB,SAAS,GAAG,IAAI,CASlB","sourcesContent":["import { type FSWatcher, type WatchListener, watch } from \"node:fs\";\n\nexport const FS_WATCH_RETRY_DELAY_MS = 5000;\n\nexport function closeWatcher(watcher: FSWatcher | null | undefined): void {\n\tif (!watcher) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\twatcher.close();\n\t} catch {\n\t\t// Ignore watcher close errors\n\t}\n}\n\nexport function watchWithErrorHandler(\n\tpath: string,\n\tlistener: WatchListener,\n\tonError: () => void,\n): FSWatcher | null {\n\ttry {\n\t\tconst watcher = watch(path, listener);\n\t\twatcher.on(\"error\", onError);\n\t\treturn watcher;\n\t} catch {\n\t\tonError();\n\t\treturn null;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/fs-watch.js b/dist/utils/fs-watch.js new file mode 100644 index 0000000..730ecc2 --- /dev/null +++ b/dist/utils/fs-watch.js @@ -0,0 +1,25 @@ +import { watch } from "node:fs"; +export const FS_WATCH_RETRY_DELAY_MS = 5000; +export function closeWatcher(watcher) { + if (!watcher) { + return; + } + try { + watcher.close(); + } + catch { + // Ignore watcher close errors + } +} +export function watchWithErrorHandler(path, listener, onError) { + try { + const watcher = watch(path, listener); + watcher.on("error", onError); + return watcher; + } + catch { + onError(); + return null; + } +} +//# sourceMappingURL=fs-watch.js.map \ No newline at end of file diff --git a/dist/utils/fs-watch.js.map b/dist/utils/fs-watch.js.map new file mode 100644 index 0000000..7fedbb6 --- /dev/null +++ b/dist/utils/fs-watch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fs-watch.js","sourceRoot":"","sources":["../../src/utils/fs-watch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsC,KAAK,EAAE,MAAM,SAAS,CAAC;AAEpE,MAAM,CAAC,MAAM,uBAAuB,GAAG,IAAI,CAAC;AAE5C,MAAM,UAAU,YAAY,CAAC,OAAqC,EAAQ;IACzE,IAAI,CAAC,OAAO,EAAE,CAAC;QACd,OAAO;IACR,CAAC;IAED,IAAI,CAAC;QACJ,OAAO,CAAC,KAAK,EAAE,CAAC;IACjB,CAAC;IAAC,MAAM,CAAC;QACR,8BAA8B;IAC/B,CAAC;AAAA,CACD;AAED,MAAM,UAAU,qBAAqB,CACpC,IAAY,EACZ,QAA+B,EAC/B,OAAmB,EACA;IACnB,IAAI,CAAC;QACJ,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QACtC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC7B,OAAO,OAAO,CAAC;IAChB,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,EAAE,CAAC;QACV,OAAO,IAAI,CAAC;IACb,CAAC;AAAA,CACD","sourcesContent":["import { type FSWatcher, type WatchListener, watch } from \"node:fs\";\n\nexport const FS_WATCH_RETRY_DELAY_MS = 5000;\n\nexport function closeWatcher(watcher: FSWatcher | null | undefined): void {\n\tif (!watcher) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\twatcher.close();\n\t} catch {\n\t\t// Ignore watcher close errors\n\t}\n}\n\nexport function watchWithErrorHandler(\n\tpath: string,\n\tlistener: WatchListener,\n\tonError: () => void,\n): FSWatcher | null {\n\ttry {\n\t\tconst watcher = watch(path, listener);\n\t\twatcher.on(\"error\", onError);\n\t\treturn watcher;\n\t} catch {\n\t\tonError();\n\t\treturn null;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/git.d.ts b/dist/utils/git.d.ts new file mode 100644 index 0000000..e4885be --- /dev/null +++ b/dist/utils/git.d.ts @@ -0,0 +1,26 @@ +/** + * Parsed git URL information. + */ +export type GitSource = { + /** Always "git" for git sources */ + type: "git"; + /** Clone URL (always valid for git clone, without ref suffix) */ + repo: string; + /** Git host domain (e.g., "github.com") */ + host: string; + /** Repository path (e.g., "user/repo") */ + path: string; + /** Git ref (branch, tag, commit) if specified */ + ref?: string; + /** True if ref was specified (package won't be auto-updated) */ + pinned: boolean; +}; +/** + * Parse git source into a GitSource. + * + * Rules: + * - With git: prefix, accept all historical shorthand forms. + * - Without git: prefix, only accept explicit protocol URLs. + */ +export declare function parseGitUrl(source: string): GitSource | null; +//# sourceMappingURL=git.d.ts.map \ No newline at end of file diff --git a/dist/utils/git.d.ts.map b/dist/utils/git.d.ts.map new file mode 100644 index 0000000..c5d8ab2 --- /dev/null +++ b/dist/utils/git.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"git.d.ts","sourceRoot":"","sources":["../../src/utils/git.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG;IACvB,mCAAmC;IACnC,IAAI,EAAE,KAAK,CAAC;IACZ,iEAAiE;IACjE,IAAI,EAAE,MAAM,CAAC;IACb,2CAA2C;IAC3C,IAAI,EAAE,MAAM,CAAC;IACb,0CAA0C;IAC1C,IAAI,EAAE,MAAM,CAAC;IACb,iDAAiD;IACjD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,gEAAgE;IAChE,MAAM,EAAE,OAAO,CAAC;CAChB,CAAC;AAkJF;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAsD5D","sourcesContent":["import hostedGitInfo from \"hosted-git-info\";\n\n/**\n * Parsed git URL information.\n */\nexport type GitSource = {\n\t/** Always \"git\" for git sources */\n\ttype: \"git\";\n\t/** Clone URL (always valid for git clone, without ref suffix) */\n\trepo: string;\n\t/** Git host domain (e.g., \"github.com\") */\n\thost: string;\n\t/** Repository path (e.g., \"user/repo\") */\n\tpath: string;\n\t/** Git ref (branch, tag, commit) if specified */\n\tref?: string;\n\t/** True if ref was specified (package won't be auto-updated) */\n\tpinned: boolean;\n};\n\nfunction splitRef(url: string): { repo: string; ref?: string } {\n\tconst scpLikeMatch = url.match(/^git@([^:]+):(.+)$/);\n\tif (scpLikeMatch) {\n\t\tconst pathWithMaybeRef = scpLikeMatch[2] ?? \"\";\n\t\tconst refSeparator = pathWithMaybeRef.indexOf(\"@\");\n\t\tif (refSeparator < 0) return { repo: url };\n\t\tconst repoPath = pathWithMaybeRef.slice(0, refSeparator);\n\t\tconst ref = pathWithMaybeRef.slice(refSeparator + 1);\n\t\tif (!repoPath || !ref) return { repo: url };\n\t\treturn {\n\t\t\trepo: `git@${scpLikeMatch[1] ?? \"\"}:${repoPath}`,\n\t\t\tref,\n\t\t};\n\t}\n\n\tif (url.includes(\"://\")) {\n\t\ttry {\n\t\t\tconst parsed = new URL(url);\n\t\t\tconst pathWithMaybeRef = parsed.pathname.replace(/^\\/+/, \"\");\n\t\t\tconst refSeparator = pathWithMaybeRef.indexOf(\"@\");\n\t\t\tif (refSeparator < 0) return { repo: url };\n\t\t\tconst repoPath = pathWithMaybeRef.slice(0, refSeparator);\n\t\t\tconst ref = pathWithMaybeRef.slice(refSeparator + 1);\n\t\t\tif (!repoPath || !ref) return { repo: url };\n\t\t\tparsed.pathname = `/${repoPath}`;\n\t\t\treturn {\n\t\t\t\trepo: parsed.toString().replace(/\\/$/, \"\"),\n\t\t\t\tref,\n\t\t\t};\n\t\t} catch {\n\t\t\treturn { repo: url };\n\t\t}\n\t}\n\n\tconst slashIndex = url.indexOf(\"/\");\n\tif (slashIndex < 0) {\n\t\treturn { repo: url };\n\t}\n\tconst host = url.slice(0, slashIndex);\n\tconst pathWithMaybeRef = url.slice(slashIndex + 1);\n\tconst refSeparator = pathWithMaybeRef.indexOf(\"@\");\n\tif (refSeparator < 0) {\n\t\treturn { repo: url };\n\t}\n\tconst repoPath = pathWithMaybeRef.slice(0, refSeparator);\n\tconst ref = pathWithMaybeRef.slice(refSeparator + 1);\n\tif (!repoPath || !ref) {\n\t\treturn { repo: url };\n\t}\n\treturn {\n\t\trepo: `${host}/${repoPath}`,\n\t\tref,\n\t};\n}\n\nfunction decodeForValidation(value: string): string | null {\n\ttry {\n\t\treturn decodeURIComponent(value);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction hasUnsafeGitInstallPart(value: string, allowSlash: boolean): boolean {\n\tconst decoded = decodeForValidation(value);\n\tif (decoded === null) {\n\t\treturn true;\n\t}\n\tconst candidates = [value, decoded];\n\tfor (const candidate of candidates) {\n\t\tif (candidate.includes(\"\\0\") || candidate.includes(\"\\\\\") || candidate.startsWith(\"/\")) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!allowSlash && candidate.includes(\"/\")) {\n\t\t\treturn true;\n\t\t}\n\t\tif (candidate.split(\"/\").includes(\"..\")) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction buildGitSource(args: { repo: string; host: string; path: string; ref?: string }): GitSource | null {\n\tif (args.path.startsWith(\"/\")) {\n\t\treturn null;\n\t}\n\tconst normalizedPath = args.path.replace(/\\.git$/, \"\").replace(/^\\/+/, \"\");\n\tif (!args.host || !normalizedPath || normalizedPath.split(\"/\").length < 2) {\n\t\treturn null;\n\t}\n\tif (hasUnsafeGitInstallPart(args.host, false) || hasUnsafeGitInstallPart(normalizedPath, true)) {\n\t\treturn null;\n\t}\n\n\treturn {\n\t\ttype: \"git\",\n\t\trepo: args.repo,\n\t\thost: args.host,\n\t\tpath: normalizedPath,\n\t\tref: args.ref,\n\t\tpinned: Boolean(args.ref),\n\t};\n}\n\nfunction parseGenericGitUrl(url: string): GitSource | null {\n\tconst { repo: repoWithoutRef, ref } = splitRef(url);\n\tlet repo = repoWithoutRef;\n\tlet host = \"\";\n\tlet path = \"\";\n\n\tconst scpLikeMatch = repoWithoutRef.match(/^git@([^:]+):(.+)$/);\n\tif (scpLikeMatch) {\n\t\thost = scpLikeMatch[1] ?? \"\";\n\t\tpath = scpLikeMatch[2] ?? \"\";\n\t} else if (\n\t\trepoWithoutRef.startsWith(\"https://\") ||\n\t\trepoWithoutRef.startsWith(\"http://\") ||\n\t\trepoWithoutRef.startsWith(\"ssh://\") ||\n\t\trepoWithoutRef.startsWith(\"git://\")\n\t) {\n\t\ttry {\n\t\t\tconst parsed = new URL(repoWithoutRef);\n\t\t\thost = parsed.hostname;\n\t\t\tpath = parsed.pathname.replace(/^\\/+/, \"\");\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t} else {\n\t\tconst slashIndex = repoWithoutRef.indexOf(\"/\");\n\t\tif (slashIndex < 0) {\n\t\t\treturn null;\n\t\t}\n\t\thost = repoWithoutRef.slice(0, slashIndex);\n\t\tpath = repoWithoutRef.slice(slashIndex + 1);\n\t\tif (!host.includes(\".\") && host !== \"localhost\") {\n\t\t\treturn null;\n\t\t}\n\t\trepo = `https://${repoWithoutRef}`;\n\t}\n\n\treturn buildGitSource({ repo, host, path, ref });\n}\n\n/**\n * Parse git source into a GitSource.\n *\n * Rules:\n * - With git: prefix, accept all historical shorthand forms.\n * - Without git: prefix, only accept explicit protocol URLs.\n */\nexport function parseGitUrl(source: string): GitSource | null {\n\tconst trimmed = source.trim();\n\tconst hasGitPrefix = trimmed.startsWith(\"git:\");\n\tconst url = hasGitPrefix ? trimmed.slice(4).trim() : trimmed;\n\n\tif (!hasGitPrefix && !/^(https?|ssh|git):\\/\\//i.test(url)) {\n\t\treturn null;\n\t}\n\n\tconst split = splitRef(url);\n\n\tconst hostedCandidates = [split.ref ? `${split.repo}#${split.ref}` : undefined, url].filter(\n\t\t(value): value is string => Boolean(value),\n\t);\n\tfor (const candidate of hostedCandidates) {\n\t\tconst info = hostedGitInfo.fromUrl(candidate);\n\t\tif (info) {\n\t\t\tif (split.ref && info.project?.includes(\"@\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst useHttpsPrefix =\n\t\t\t\t!split.repo.startsWith(\"http://\") &&\n\t\t\t\t!split.repo.startsWith(\"https://\") &&\n\t\t\t\t!split.repo.startsWith(\"ssh://\") &&\n\t\t\t\t!split.repo.startsWith(\"git://\") &&\n\t\t\t\t!split.repo.startsWith(\"git@\");\n\t\t\treturn buildGitSource({\n\t\t\t\trepo: useHttpsPrefix ? `https://${split.repo}` : split.repo,\n\t\t\t\thost: info.domain || \"\",\n\t\t\t\tpath: `${info.user}/${info.project}`,\n\t\t\t\tref: info.committish || split.ref || undefined,\n\t\t\t});\n\t\t}\n\t}\n\n\tconst httpsCandidates = [split.ref ? `https://${split.repo}#${split.ref}` : undefined, `https://${url}`].filter(\n\t\t(value): value is string => Boolean(value),\n\t);\n\tfor (const candidate of httpsCandidates) {\n\t\tconst info = hostedGitInfo.fromUrl(candidate);\n\t\tif (info) {\n\t\t\tif (split.ref && info.project?.includes(\"@\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn buildGitSource({\n\t\t\t\trepo: `https://${split.repo}`,\n\t\t\t\thost: info.domain || \"\",\n\t\t\t\tpath: `${info.user}/${info.project}`,\n\t\t\t\tref: info.committish || split.ref || undefined,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn parseGenericGitUrl(url);\n}\n"]} \ No newline at end of file diff --git a/dist/utils/git.js b/dist/utils/git.js new file mode 100644 index 0000000..a4005a9 --- /dev/null +++ b/dist/utils/git.js @@ -0,0 +1,195 @@ +import hostedGitInfo from "hosted-git-info"; +function splitRef(url) { + const scpLikeMatch = url.match(/^git@([^:]+):(.+)$/); + if (scpLikeMatch) { + const pathWithMaybeRef = scpLikeMatch[2] ?? ""; + const refSeparator = pathWithMaybeRef.indexOf("@"); + if (refSeparator < 0) + return { repo: url }; + const repoPath = pathWithMaybeRef.slice(0, refSeparator); + const ref = pathWithMaybeRef.slice(refSeparator + 1); + if (!repoPath || !ref) + return { repo: url }; + return { + repo: `git@${scpLikeMatch[1] ?? ""}:${repoPath}`, + ref, + }; + } + if (url.includes("://")) { + try { + const parsed = new URL(url); + const pathWithMaybeRef = parsed.pathname.replace(/^\/+/, ""); + const refSeparator = pathWithMaybeRef.indexOf("@"); + if (refSeparator < 0) + return { repo: url }; + const repoPath = pathWithMaybeRef.slice(0, refSeparator); + const ref = pathWithMaybeRef.slice(refSeparator + 1); + if (!repoPath || !ref) + return { repo: url }; + parsed.pathname = `/${repoPath}`; + return { + repo: parsed.toString().replace(/\/$/, ""), + ref, + }; + } + catch { + return { repo: url }; + } + } + const slashIndex = url.indexOf("/"); + if (slashIndex < 0) { + return { repo: url }; + } + const host = url.slice(0, slashIndex); + const pathWithMaybeRef = url.slice(slashIndex + 1); + const refSeparator = pathWithMaybeRef.indexOf("@"); + if (refSeparator < 0) { + return { repo: url }; + } + const repoPath = pathWithMaybeRef.slice(0, refSeparator); + const ref = pathWithMaybeRef.slice(refSeparator + 1); + if (!repoPath || !ref) { + return { repo: url }; + } + return { + repo: `${host}/${repoPath}`, + ref, + }; +} +function decodeForValidation(value) { + try { + return decodeURIComponent(value); + } + catch { + return null; + } +} +function hasUnsafeGitInstallPart(value, allowSlash) { + const decoded = decodeForValidation(value); + if (decoded === null) { + return true; + } + const candidates = [value, decoded]; + for (const candidate of candidates) { + if (candidate.includes("\0") || candidate.includes("\\") || candidate.startsWith("/")) { + return true; + } + if (!allowSlash && candidate.includes("/")) { + return true; + } + if (candidate.split("/").includes("..")) { + return true; + } + } + return false; +} +function buildGitSource(args) { + if (args.path.startsWith("/")) { + return null; + } + const normalizedPath = args.path.replace(/\.git$/, "").replace(/^\/+/, ""); + if (!args.host || !normalizedPath || normalizedPath.split("/").length < 2) { + return null; + } + if (hasUnsafeGitInstallPart(args.host, false) || hasUnsafeGitInstallPart(normalizedPath, true)) { + return null; + } + return { + type: "git", + repo: args.repo, + host: args.host, + path: normalizedPath, + ref: args.ref, + pinned: Boolean(args.ref), + }; +} +function parseGenericGitUrl(url) { + const { repo: repoWithoutRef, ref } = splitRef(url); + let repo = repoWithoutRef; + let host = ""; + let path = ""; + const scpLikeMatch = repoWithoutRef.match(/^git@([^:]+):(.+)$/); + if (scpLikeMatch) { + host = scpLikeMatch[1] ?? ""; + path = scpLikeMatch[2] ?? ""; + } + else if (repoWithoutRef.startsWith("https://") || + repoWithoutRef.startsWith("http://") || + repoWithoutRef.startsWith("ssh://") || + repoWithoutRef.startsWith("git://")) { + try { + const parsed = new URL(repoWithoutRef); + host = parsed.hostname; + path = parsed.pathname.replace(/^\/+/, ""); + } + catch { + return null; + } + } + else { + const slashIndex = repoWithoutRef.indexOf("/"); + if (slashIndex < 0) { + return null; + } + host = repoWithoutRef.slice(0, slashIndex); + path = repoWithoutRef.slice(slashIndex + 1); + if (!host.includes(".") && host !== "localhost") { + return null; + } + repo = `https://${repoWithoutRef}`; + } + return buildGitSource({ repo, host, path, ref }); +} +/** + * Parse git source into a GitSource. + * + * Rules: + * - With git: prefix, accept all historical shorthand forms. + * - Without git: prefix, only accept explicit protocol URLs. + */ +export function parseGitUrl(source) { + const trimmed = source.trim(); + const hasGitPrefix = trimmed.startsWith("git:"); + const url = hasGitPrefix ? trimmed.slice(4).trim() : trimmed; + if (!hasGitPrefix && !/^(https?|ssh|git):\/\//i.test(url)) { + return null; + } + const split = splitRef(url); + const hostedCandidates = [split.ref ? `${split.repo}#${split.ref}` : undefined, url].filter((value) => Boolean(value)); + for (const candidate of hostedCandidates) { + const info = hostedGitInfo.fromUrl(candidate); + if (info) { + if (split.ref && info.project?.includes("@")) { + continue; + } + const useHttpsPrefix = !split.repo.startsWith("http://") && + !split.repo.startsWith("https://") && + !split.repo.startsWith("ssh://") && + !split.repo.startsWith("git://") && + !split.repo.startsWith("git@"); + return buildGitSource({ + repo: useHttpsPrefix ? `https://${split.repo}` : split.repo, + host: info.domain || "", + path: `${info.user}/${info.project}`, + ref: info.committish || split.ref || undefined, + }); + } + } + const httpsCandidates = [split.ref ? `https://${split.repo}#${split.ref}` : undefined, `https://${url}`].filter((value) => Boolean(value)); + for (const candidate of httpsCandidates) { + const info = hostedGitInfo.fromUrl(candidate); + if (info) { + if (split.ref && info.project?.includes("@")) { + continue; + } + return buildGitSource({ + repo: `https://${split.repo}`, + host: info.domain || "", + path: `${info.user}/${info.project}`, + ref: info.committish || split.ref || undefined, + }); + } + } + return parseGenericGitUrl(url); +} +//# sourceMappingURL=git.js.map \ No newline at end of file diff --git a/dist/utils/git.js.map b/dist/utils/git.js.map new file mode 100644 index 0000000..fa0db72 --- /dev/null +++ b/dist/utils/git.js.map @@ -0,0 +1 @@ +{"version":3,"file":"git.js","sourceRoot":"","sources":["../../src/utils/git.ts"],"names":[],"mappings":"AAAA,OAAO,aAAa,MAAM,iBAAiB,CAAC;AAoB5C,SAAS,QAAQ,CAAC,GAAW,EAAkC;IAC9D,MAAM,YAAY,GAAG,GAAG,CAAC,KAAK,CAAC,oBAAoB,CAAC,CAAC;IACrD,IAAI,YAAY,EAAE,CAAC;QAClB,MAAM,gBAAgB,GAAG,YAAY,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QAC/C,MAAM,YAAY,GAAG,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QACnD,IAAI,YAAY,GAAG,CAAC;YAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QAC3C,MAAM,QAAQ,GAAG,gBAAgB,CAAC,KAAK,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC;QACzD,MAAM,GAAG,GAAG,gBAAgB,CAAC,KAAK,CAAC,YAAY,GAAG,CAAC,CAAC,CAAC;QACrD,IAAI,CAAC,QAAQ,IAAI,CAAC,GAAG;YAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QA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AQ,CAAC,GAAG,CAAC,EAAE,CAAC;gBAC9C,SAAS;YACV,CAAC;YACD,OAAO,cAAc,CAAC;gBACrB,IAAI,EAAE,WAAW,KAAK,CAAC,IAAI,EAAE;gBAC7B,IAAI,EAAE,IAAI,CAAC,MAAM,IAAI,EAAE;gBACvB,IAAI,EAAE,GAAG,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,OAAO,EAAE;gBACpC,GAAG,EAAE,IAAI,CAAC,UAAU,IAAI,KAAK,CAAC,GAAG,IAAI,SAAS;aAC9C,CAAC,CAAC;QACJ,CAAC;IACF,CAAC;IAED,OAAO,kBAAkB,CAAC,GAAG,CAAC,CAAC;AAAA,CAC/B","sourcesContent":["import hostedGitInfo from \"hosted-git-info\";\n\n/**\n * Parsed git URL information.\n */\nexport type GitSource = {\n\t/** Always \"git\" for git sources */\n\ttype: \"git\";\n\t/** Clone URL (always valid for git clone, without ref suffix) */\n\trepo: string;\n\t/** Git host domain (e.g., \"github.com\") */\n\thost: string;\n\t/** Repository path (e.g., \"user/repo\") */\n\tpath: string;\n\t/** Git ref (branch, tag, commit) if specified */\n\tref?: string;\n\t/** True if ref was specified (package won't be auto-updated) */\n\tpinned: boolean;\n};\n\nfunction splitRef(url: string): { repo: string; ref?: string } {\n\tconst scpLikeMatch = url.match(/^git@([^:]+):(.+)$/);\n\tif (scpLikeMatch) {\n\t\tconst pathWithMaybeRef = scpLikeMatch[2] ?? \"\";\n\t\tconst refSeparator = pathWithMaybeRef.indexOf(\"@\");\n\t\tif (refSeparator < 0) return { repo: url };\n\t\tconst repoPath = pathWithMaybeRef.slice(0, refSeparator);\n\t\tconst ref = pathWithMaybeRef.slice(refSeparator + 1);\n\t\tif (!repoPath || !ref) return { repo: url };\n\t\treturn {\n\t\t\trepo: `git@${scpLikeMatch[1] ?? \"\"}:${repoPath}`,\n\t\t\tref,\n\t\t};\n\t}\n\n\tif (url.includes(\"://\")) {\n\t\ttry {\n\t\t\tconst parsed = new URL(url);\n\t\t\tconst pathWithMaybeRef = parsed.pathname.replace(/^\\/+/, \"\");\n\t\t\tconst refSeparator = pathWithMaybeRef.indexOf(\"@\");\n\t\t\tif (refSeparator < 0) return { repo: url };\n\t\t\tconst repoPath = pathWithMaybeRef.slice(0, refSeparator);\n\t\t\tconst ref = pathWithMaybeRef.slice(refSeparator + 1);\n\t\t\tif (!repoPath || !ref) return { repo: url };\n\t\t\tparsed.pathname = `/${repoPath}`;\n\t\t\treturn {\n\t\t\t\trepo: parsed.toString().replace(/\\/$/, \"\"),\n\t\t\t\tref,\n\t\t\t};\n\t\t} catch {\n\t\t\treturn { repo: url };\n\t\t}\n\t}\n\n\tconst slashIndex = url.indexOf(\"/\");\n\tif (slashIndex < 0) {\n\t\treturn { repo: url };\n\t}\n\tconst host = url.slice(0, slashIndex);\n\tconst pathWithMaybeRef = url.slice(slashIndex + 1);\n\tconst refSeparator = pathWithMaybeRef.indexOf(\"@\");\n\tif (refSeparator < 0) {\n\t\treturn { repo: url };\n\t}\n\tconst repoPath = pathWithMaybeRef.slice(0, refSeparator);\n\tconst ref = pathWithMaybeRef.slice(refSeparator + 1);\n\tif (!repoPath || !ref) {\n\t\treturn { repo: url };\n\t}\n\treturn {\n\t\trepo: `${host}/${repoPath}`,\n\t\tref,\n\t};\n}\n\nfunction decodeForValidation(value: string): string | null {\n\ttry {\n\t\treturn decodeURIComponent(value);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction hasUnsafeGitInstallPart(value: string, allowSlash: boolean): boolean {\n\tconst decoded = decodeForValidation(value);\n\tif (decoded === null) {\n\t\treturn true;\n\t}\n\tconst candidates = [value, decoded];\n\tfor (const candidate of candidates) {\n\t\tif (candidate.includes(\"\\0\") || candidate.includes(\"\\\\\") || candidate.startsWith(\"/\")) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!allowSlash && candidate.includes(\"/\")) {\n\t\t\treturn true;\n\t\t}\n\t\tif (candidate.split(\"/\").includes(\"..\")) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nfunction buildGitSource(args: { repo: string; host: string; path: string; ref?: string }): GitSource | null {\n\tif (args.path.startsWith(\"/\")) {\n\t\treturn null;\n\t}\n\tconst normalizedPath = args.path.replace(/\\.git$/, \"\").replace(/^\\/+/, \"\");\n\tif (!args.host || !normalizedPath || normalizedPath.split(\"/\").length < 2) {\n\t\treturn null;\n\t}\n\tif (hasUnsafeGitInstallPart(args.host, false) || hasUnsafeGitInstallPart(normalizedPath, true)) {\n\t\treturn null;\n\t}\n\n\treturn {\n\t\ttype: \"git\",\n\t\trepo: args.repo,\n\t\thost: args.host,\n\t\tpath: normalizedPath,\n\t\tref: args.ref,\n\t\tpinned: Boolean(args.ref),\n\t};\n}\n\nfunction parseGenericGitUrl(url: string): GitSource | null {\n\tconst { repo: repoWithoutRef, ref } = splitRef(url);\n\tlet repo = repoWithoutRef;\n\tlet host = \"\";\n\tlet path = \"\";\n\n\tconst scpLikeMatch = repoWithoutRef.match(/^git@([^:]+):(.+)$/);\n\tif (scpLikeMatch) {\n\t\thost = scpLikeMatch[1] ?? \"\";\n\t\tpath = scpLikeMatch[2] ?? \"\";\n\t} else if (\n\t\trepoWithoutRef.startsWith(\"https://\") ||\n\t\trepoWithoutRef.startsWith(\"http://\") ||\n\t\trepoWithoutRef.startsWith(\"ssh://\") ||\n\t\trepoWithoutRef.startsWith(\"git://\")\n\t) {\n\t\ttry {\n\t\t\tconst parsed = new URL(repoWithoutRef);\n\t\t\thost = parsed.hostname;\n\t\t\tpath = parsed.pathname.replace(/^\\/+/, \"\");\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t} else {\n\t\tconst slashIndex = repoWithoutRef.indexOf(\"/\");\n\t\tif (slashIndex < 0) {\n\t\t\treturn null;\n\t\t}\n\t\thost = repoWithoutRef.slice(0, slashIndex);\n\t\tpath = repoWithoutRef.slice(slashIndex + 1);\n\t\tif (!host.includes(\".\") && host !== \"localhost\") {\n\t\t\treturn null;\n\t\t}\n\t\trepo = `https://${repoWithoutRef}`;\n\t}\n\n\treturn buildGitSource({ repo, host, path, ref });\n}\n\n/**\n * Parse git source into a GitSource.\n *\n * Rules:\n * - With git: prefix, accept all historical shorthand forms.\n * - Without git: prefix, only accept explicit protocol URLs.\n */\nexport function parseGitUrl(source: string): GitSource | null {\n\tconst trimmed = source.trim();\n\tconst hasGitPrefix = trimmed.startsWith(\"git:\");\n\tconst url = hasGitPrefix ? trimmed.slice(4).trim() : trimmed;\n\n\tif (!hasGitPrefix && !/^(https?|ssh|git):\\/\\//i.test(url)) {\n\t\treturn null;\n\t}\n\n\tconst split = splitRef(url);\n\n\tconst hostedCandidates = [split.ref ? `${split.repo}#${split.ref}` : undefined, url].filter(\n\t\t(value): value is string => Boolean(value),\n\t);\n\tfor (const candidate of hostedCandidates) {\n\t\tconst info = hostedGitInfo.fromUrl(candidate);\n\t\tif (info) {\n\t\t\tif (split.ref && info.project?.includes(\"@\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst useHttpsPrefix =\n\t\t\t\t!split.repo.startsWith(\"http://\") &&\n\t\t\t\t!split.repo.startsWith(\"https://\") &&\n\t\t\t\t!split.repo.startsWith(\"ssh://\") &&\n\t\t\t\t!split.repo.startsWith(\"git://\") &&\n\t\t\t\t!split.repo.startsWith(\"git@\");\n\t\t\treturn buildGitSource({\n\t\t\t\trepo: useHttpsPrefix ? `https://${split.repo}` : split.repo,\n\t\t\t\thost: info.domain || \"\",\n\t\t\t\tpath: `${info.user}/${info.project}`,\n\t\t\t\tref: info.committish || split.ref || undefined,\n\t\t\t});\n\t\t}\n\t}\n\n\tconst httpsCandidates = [split.ref ? `https://${split.repo}#${split.ref}` : undefined, `https://${url}`].filter(\n\t\t(value): value is string => Boolean(value),\n\t);\n\tfor (const candidate of httpsCandidates) {\n\t\tconst info = hostedGitInfo.fromUrl(candidate);\n\t\tif (info) {\n\t\t\tif (split.ref && info.project?.includes(\"@\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn buildGitSource({\n\t\t\t\trepo: `https://${split.repo}`,\n\t\t\t\thost: info.domain || \"\",\n\t\t\t\tpath: `${info.user}/${info.project}`,\n\t\t\t\tref: info.committish || split.ref || undefined,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn parseGenericGitUrl(url);\n}\n"]} \ No newline at end of file diff --git a/dist/utils/html.d.ts b/dist/utils/html.d.ts new file mode 100644 index 0000000..46188b2 --- /dev/null +++ b/dist/utils/html.d.ts @@ -0,0 +1,7 @@ +export interface DecodedHtmlEntity { + text: string; + length: number; +} +export declare function decodeHtmlEntity(entity: string): string | undefined; +export declare function decodeHtmlEntityAt(html: string, index: number): DecodedHtmlEntity | undefined; +//# sourceMappingURL=html.d.ts.map \ No newline at end of file diff --git a/dist/utils/html.d.ts.map b/dist/utils/html.d.ts.map new file mode 100644 index 0000000..a18205d --- /dev/null +++ b/dist/utils/html.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"html.d.ts","sourceRoot":"","sources":["../../src/utils/html.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,iBAAiB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CACf;AASD,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAuBnE;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAa7F","sourcesContent":["export interface DecodedHtmlEntity {\n\ttext: string;\n\tlength: number;\n}\n\nfunction decodeCodePoint(codePoint: number): string | undefined {\n\tif (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {\n\t\treturn undefined;\n\t}\n\treturn String.fromCodePoint(codePoint);\n}\n\nexport function decodeHtmlEntity(entity: string): string | undefined {\n\tswitch (entity) {\n\t\tcase \"amp\":\n\t\t\treturn \"&\";\n\t\tcase \"lt\":\n\t\t\treturn \"<\";\n\t\tcase \"gt\":\n\t\t\treturn \">\";\n\t\tcase \"quot\":\n\t\t\treturn '\"';\n\t\tcase \"apos\":\n\t\t\treturn \"'\";\n\t}\n\n\tif (entity.startsWith(\"#x\") || entity.startsWith(\"#X\")) {\n\t\treturn decodeCodePoint(Number.parseInt(entity.slice(2), 16));\n\t}\n\n\tif (entity.startsWith(\"#\")) {\n\t\treturn decodeCodePoint(Number.parseInt(entity.slice(1), 10));\n\t}\n\n\treturn undefined;\n}\n\nexport function decodeHtmlEntityAt(html: string, index: number): DecodedHtmlEntity | undefined {\n\tconst semicolonIndex = html.indexOf(\";\", index + 1);\n\tif (semicolonIndex === -1 || semicolonIndex - index > 16) {\n\t\treturn undefined;\n\t}\n\n\tconst entity = html.slice(index + 1, semicolonIndex);\n\tconst decoded = decodeHtmlEntity(entity);\n\tif (decoded === undefined) {\n\t\treturn undefined;\n\t}\n\n\treturn { text: decoded, length: semicolonIndex - index + 1 };\n}\n"]} \ No newline at end of file diff --git a/dist/utils/html.js b/dist/utils/html.js new file mode 100644 index 0000000..7fefd82 --- /dev/null +++ b/dist/utils/html.js @@ -0,0 +1,40 @@ +function decodeCodePoint(codePoint) { + if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) { + return undefined; + } + return String.fromCodePoint(codePoint); +} +export function decodeHtmlEntity(entity) { + switch (entity) { + case "amp": + return "&"; + case "lt": + return "<"; + case "gt": + return ">"; + case "quot": + return '"'; + case "apos": + return "'"; + } + if (entity.startsWith("#x") || entity.startsWith("#X")) { + return decodeCodePoint(Number.parseInt(entity.slice(2), 16)); + } + if (entity.startsWith("#")) { + return decodeCodePoint(Number.parseInt(entity.slice(1), 10)); + } + return undefined; +} +export function decodeHtmlEntityAt(html, index) { + const semicolonIndex = html.indexOf(";", index + 1); + if (semicolonIndex === -1 || semicolonIndex - index > 16) { + return undefined; + } + const entity = html.slice(index + 1, semicolonIndex); + const decoded = decodeHtmlEntity(entity); + if (decoded === undefined) { + return undefined; + } + return { text: decoded, length: semicolonIndex - index + 1 }; +} +//# sourceMappingURL=html.js.map \ No newline at end of file diff --git a/dist/utils/html.js.map b/dist/utils/html.js.map new file mode 100644 index 0000000..8a22df4 --- /dev/null +++ b/dist/utils/html.js.map @@ -0,0 +1 @@ +{"version":3,"file":"html.js","sourceRoot":"","sources":["../../src/utils/html.ts"],"names":[],"mappings":"AAKA,SAAS,eAAe,CAAC,SAAiB,EAAsB;IAC/D,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,IAAI,SAAS,GAAG,CAAC,IAAI,SAAS,GAAG,QAAQ,EAAE,CAAC;QAC3E,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,OAAO,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC;AAAA,CACvC;AAED,MAAM,UAAU,gBAAgB,CAAC,MAAc,EAAsB;IACpE,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,KAAK;YACT,OAAO,GAAG,CAAC;QACZ,KAAK,IAAI;YACR,OAAO,GAAG,CAAC;QACZ,KAAK,IAAI;YACR,OAAO,GAAG,CAAC;QACZ,KAAK,MAAM;YACV,OAAO,GAAG,CAAC;QACZ,KAAK,MAAM;YACV,OAAO,GAAG,CAAC;IACb,CAAC;IAED,IAAI,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACxD,OAAO,eAAe,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;IAC9D,CAAC;IAED,IAAI,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QAC5B,OAAO,eAAe,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;IAC9D,CAAC;IAED,OAAO,SAAS,CAAC;AAAA,CACjB;AAED,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAE,KAAa,EAAiC;IAC9F,MAAM,cAAc,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;IACpD,IAAI,cAAc,KAAK,CAAC,CAAC,IAAI,cAAc,GAAG,KAAK,GAAG,EAAE,EAAE,CAAC;QAC1D,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,EAAE,cAAc,CAAC,CAAC;IACrD,MAAM,OAAO,GAAG,gBAAgB,CAAC,MAAM,CAAC,CAAC;IACzC,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC3B,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,cAAc,GAAG,KAAK,GAAG,CAAC,EAAE,CAAC;AAAA,CAC7D","sourcesContent":["export interface DecodedHtmlEntity {\n\ttext: string;\n\tlength: number;\n}\n\nfunction decodeCodePoint(codePoint: number): string | undefined {\n\tif (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {\n\t\treturn undefined;\n\t}\n\treturn String.fromCodePoint(codePoint);\n}\n\nexport function decodeHtmlEntity(entity: string): string | undefined {\n\tswitch (entity) {\n\t\tcase \"amp\":\n\t\t\treturn \"&\";\n\t\tcase \"lt\":\n\t\t\treturn \"<\";\n\t\tcase \"gt\":\n\t\t\treturn \">\";\n\t\tcase \"quot\":\n\t\t\treturn '\"';\n\t\tcase \"apos\":\n\t\t\treturn \"'\";\n\t}\n\n\tif (entity.startsWith(\"#x\") || entity.startsWith(\"#X\")) {\n\t\treturn decodeCodePoint(Number.parseInt(entity.slice(2), 16));\n\t}\n\n\tif (entity.startsWith(\"#\")) {\n\t\treturn decodeCodePoint(Number.parseInt(entity.slice(1), 10));\n\t}\n\n\treturn undefined;\n}\n\nexport function decodeHtmlEntityAt(html: string, index: number): DecodedHtmlEntity | undefined {\n\tconst semicolonIndex = html.indexOf(\";\", index + 1);\n\tif (semicolonIndex === -1 || semicolonIndex - index > 16) {\n\t\treturn undefined;\n\t}\n\n\tconst entity = html.slice(index + 1, semicolonIndex);\n\tconst decoded = decodeHtmlEntity(entity);\n\tif (decoded === undefined) {\n\t\treturn undefined;\n\t}\n\n\treturn { text: decoded, length: semicolonIndex - index + 1 };\n}\n"]} \ No newline at end of file diff --git a/dist/utils/image-convert.d.ts b/dist/utils/image-convert.d.ts new file mode 100644 index 0000000..3d9c73a --- /dev/null +++ b/dist/utils/image-convert.d.ts @@ -0,0 +1,10 @@ +export declare function convertImageBytesToPng(bytes: Uint8Array): Promise; +/** + * Convert image to PNG format for terminal display. + * Kitty graphics protocol requires PNG format (f=100). + */ +export declare function convertToPng(base64Data: string, mimeType: string): Promise<{ + data: string; + mimeType: string; +} | null>; +//# sourceMappingURL=image-convert.d.ts.map \ No newline at end of file diff --git a/dist/utils/image-convert.d.ts.map b/dist/utils/image-convert.d.ts.map new file mode 100644 index 0000000..a70377c --- /dev/null +++ b/dist/utils/image-convert.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"image-convert.d.ts","sourceRoot":"","sources":["../../src/utils/image-convert.ts"],"names":[],"mappings":"AAGA,wBAAsB,sBAAsB,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAoB1F;AAED;;;GAGG;AACH,wBAAsB,YAAY,CACjC,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,GACd,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC,CAgBpD","sourcesContent":["import { applyExifOrientation } from \"./exif-orientation.ts\";\nimport { loadPhoton } from \"./photon.ts\";\n\nexport async function convertImageBytesToPng(bytes: Uint8Array): Promise {\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\t// Photon not available, can't convert\n\t\treturn null;\n\t}\n\n\ttry {\n\t\tconst rawImage = photon.PhotonImage.new_from_byteslice(bytes);\n\t\tconst image = applyExifOrientation(photon, rawImage, bytes);\n\t\tif (image !== rawImage) rawImage.free();\n\t\ttry {\n\t\t\treturn new Uint8Array(image.get_bytes());\n\t\t} finally {\n\t\t\timage.free();\n\t\t}\n\t} catch {\n\t\t// Conversion failed\n\t\treturn null;\n\t}\n}\n\n/**\n * Convert image to PNG format for terminal display.\n * Kitty graphics protocol requires PNG format (f=100).\n */\nexport async function convertToPng(\n\tbase64Data: string,\n\tmimeType: string,\n): Promise<{ data: string; mimeType: string } | null> {\n\t// Already PNG, no conversion needed\n\tif (mimeType === \"image/png\") {\n\t\treturn { data: base64Data, mimeType };\n\t}\n\n\tconst bytes = new Uint8Array(Buffer.from(base64Data, \"base64\"));\n\tconst pngBytes = await convertImageBytesToPng(bytes);\n\tif (!pngBytes) {\n\t\treturn null;\n\t}\n\n\treturn {\n\t\tdata: Buffer.from(pngBytes).toString(\"base64\"),\n\t\tmimeType: \"image/png\",\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/utils/image-convert.js b/dist/utils/image-convert.js new file mode 100644 index 0000000..2d0e9e4 --- /dev/null +++ b/dist/utils/image-convert.js @@ -0,0 +1,45 @@ +import { applyExifOrientation } from "./exif-orientation.js"; +import { loadPhoton } from "./photon.js"; +export async function convertImageBytesToPng(bytes) { + const photon = await loadPhoton(); + if (!photon) { + // Photon not available, can't convert + return null; + } + try { + const rawImage = photon.PhotonImage.new_from_byteslice(bytes); + const image = applyExifOrientation(photon, rawImage, bytes); + if (image !== rawImage) + rawImage.free(); + try { + return new Uint8Array(image.get_bytes()); + } + finally { + image.free(); + } + } + catch { + // Conversion failed + return null; + } +} +/** + * Convert image to PNG format for terminal display. + * Kitty graphics protocol requires PNG format (f=100). + */ +export async function convertToPng(base64Data, mimeType) { + // Already PNG, no conversion needed + if (mimeType === "image/png") { + return { data: base64Data, mimeType }; + } + const bytes = new Uint8Array(Buffer.from(base64Data, "base64")); + const pngBytes = await convertImageBytesToPng(bytes); + if (!pngBytes) { + return null; + } + return { + data: Buffer.from(pngBytes).toString("base64"), + mimeType: "image/png", + }; +} +//# sourceMappingURL=image-convert.js.map \ No newline at end of file diff --git a/dist/utils/image-convert.js.map b/dist/utils/image-convert.js.map new file mode 100644 index 0000000..ad4d8ef --- /dev/null +++ b/dist/utils/image-convert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"image-convert.js","sourceRoot":"","sources":["../../src/utils/image-convert.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,KAAiB,EAA8B;IAC3F,MAAM,MAAM,GAAG,MAAM,UAAU,EAAE,CAAC;IAClC,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,sCAAsC;QACtC,OAAO,IAAI,CAAC;IACb,CAAC;IAED,IAAI,CAAC;QACJ,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;QAC9D,MAAM,KAAK,GAAG,oBAAoB,CAAC,MAAM,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;QAC5D,IAAI,KAAK,KAAK,QAAQ;YAAE,QAAQ,CAAC,IAAI,EAAE,CAAC;QACxC,IAAI,CAAC;YACJ,OAAO,IAAI,UAAU,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC,CAAC;QAC1C,CAAC;gBAAS,CAAC;YACV,KAAK,CAAC,IAAI,EAAE,CAAC;QACd,CAAC;IACF,CAAC;IAAC,MAAM,CAAC;QACR,oBAAoB;QACpB,OAAO,IAAI,CAAC;IACb,CAAC;AAAA,CACD;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CACjC,UAAkB,EAClB,QAAgB,EACqC;IACrD,oCAAoC;IACpC,IAAI,QAAQ,KAAK,WAAW,EAAE,CAAC;QAC9B,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC;IACvC,CAAC;IAED,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAC;IAChE,MAAM,QAAQ,GAAG,MAAM,sBAAsB,CAAC,KAAK,CAAC,CAAC;IACrD,IAAI,CAAC,QAAQ,EAAE,CAAC;QACf,OAAO,IAAI,CAAC;IACb,CAAC;IAED,OAAO;QACN,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAC9C,QAAQ,EAAE,WAAW;KACrB,CAAC;AAAA,CACF","sourcesContent":["import { applyExifOrientation } from \"./exif-orientation.ts\";\nimport { loadPhoton } from \"./photon.ts\";\n\nexport async function convertImageBytesToPng(bytes: Uint8Array): Promise {\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\t// Photon not available, can't convert\n\t\treturn null;\n\t}\n\n\ttry {\n\t\tconst rawImage = photon.PhotonImage.new_from_byteslice(bytes);\n\t\tconst image = applyExifOrientation(photon, rawImage, bytes);\n\t\tif (image !== rawImage) rawImage.free();\n\t\ttry {\n\t\t\treturn new Uint8Array(image.get_bytes());\n\t\t} finally {\n\t\t\timage.free();\n\t\t}\n\t} catch {\n\t\t// Conversion failed\n\t\treturn null;\n\t}\n}\n\n/**\n * Convert image to PNG format for terminal display.\n * Kitty graphics protocol requires PNG format (f=100).\n */\nexport async function convertToPng(\n\tbase64Data: string,\n\tmimeType: string,\n): Promise<{ data: string; mimeType: string } | null> {\n\t// Already PNG, no conversion needed\n\tif (mimeType === \"image/png\") {\n\t\treturn { data: base64Data, mimeType };\n\t}\n\n\tconst bytes = new Uint8Array(Buffer.from(base64Data, \"base64\"));\n\tconst pngBytes = await convertImageBytesToPng(bytes);\n\tif (!pngBytes) {\n\t\treturn null;\n\t}\n\n\treturn {\n\t\tdata: Buffer.from(pngBytes).toString(\"base64\"),\n\t\tmimeType: \"image/png\",\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/utils/image-process.d.ts b/dist/utils/image-process.d.ts new file mode 100644 index 0000000..ed600ec --- /dev/null +++ b/dist/utils/image-process.d.ts @@ -0,0 +1,18 @@ +import { type ImageResizeOptions } from "./image-resize.ts"; +export interface ProcessImageOptions { + /** Whether to resize images to inline provider limits. Default: true */ + autoResizeImages?: boolean; + /** Optional resize overrides. Uses resizeImage defaults when omitted. */ + resizeOptions?: ImageResizeOptions; +} +export type ProcessImageResult = { + ok: true; + data: string; + mimeType: string; + hints: string[]; +} | { + ok: false; + message: string; +}; +export declare function processImage(bytes: Uint8Array, mimeType: string, options?: ProcessImageOptions): Promise; +//# sourceMappingURL=image-process.d.ts.map \ No newline at end of file diff --git a/dist/utils/image-process.d.ts.map b/dist/utils/image-process.d.ts.map new file mode 100644 index 0000000..5556ffd --- /dev/null +++ b/dist/utils/image-process.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"image-process.d.ts","sourceRoot":"","sources":["../../src/utils/image-process.ts"],"names":[],"mappings":"AACA,OAAO,EAAuB,KAAK,kBAAkB,EAAe,MAAM,mBAAmB,CAAC;AAE9F,MAAM,WAAW,mBAAmB;IACnC,wEAAwE;IACxE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,yEAAyE;IACzE,aAAa,CAAC,EAAE,kBAAkB,CAAC;CACnC;AAED,MAAM,MAAM,kBAAkB,GAC3B;IACA,EAAE,EAAE,IAAI,CAAC;IACT,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,EAAE,CAAC;CACf,GACD;IACA,EAAE,EAAE,KAAK,CAAC;IACV,OAAO,EAAE,MAAM,CAAC;CACf,CAAC;AAmDL,wBAAsB,YAAY,CACjC,KAAK,EAAE,UAAU,EACjB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,kBAAkB,CAAC,CA2C7B","sourcesContent":["import { convertImageBytesToPng } from \"./image-convert.ts\";\nimport { formatDimensionNote, type ImageResizeOptions, resizeImage } from \"./image-resize.ts\";\n\nexport interface ProcessImageOptions {\n\t/** Whether to resize images to inline provider limits. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Optional resize overrides. Uses resizeImage defaults when omitted. */\n\tresizeOptions?: ImageResizeOptions;\n}\n\nexport type ProcessImageResult =\n\t| {\n\t\t\tok: true;\n\t\t\tdata: string;\n\t\t\tmimeType: string;\n\t\t\thints: string[];\n\t }\n\t| {\n\t\t\tok: false;\n\t\t\tmessage: string;\n\t };\n\ninterface NormalizedImage {\n\tbytes: Uint8Array;\n\tmimeType: string;\n\tconvertedFrom?: string;\n}\n\nfunction baseMimeType(mimeType: string): string {\n\treturn mimeType.split(\";\")[0]?.trim().toLowerCase() ?? mimeType.toLowerCase();\n}\n\nfunction normalizeSupportedImageMimeType(mimeType: string): string | null {\n\tswitch (baseMimeType(mimeType)) {\n\t\tcase \"image/png\":\n\t\t\treturn \"image/png\";\n\t\tcase \"image/jpeg\":\n\t\tcase \"image/jpg\":\n\t\t\treturn \"image/jpeg\";\n\t\tcase \"image/gif\":\n\t\t\treturn \"image/gif\";\n\t\tcase \"image/webp\":\n\t\t\treturn \"image/webp\";\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nasync function normalizeImage(bytes: Uint8Array, mimeType: string): Promise {\n\tconst normalizedMimeType = normalizeSupportedImageMimeType(mimeType);\n\tif (normalizedMimeType) {\n\t\treturn { bytes, mimeType: normalizedMimeType };\n\t}\n\n\tconst pngBytes = await convertImageBytesToPng(bytes);\n\tif (!pngBytes) {\n\t\treturn null;\n\t}\n\n\treturn {\n\t\tbytes: pngBytes,\n\t\tmimeType: \"image/png\",\n\t\tconvertedFrom: baseMimeType(mimeType),\n\t};\n}\n\nfunction conversionHint(from: string | undefined, to: string): string | undefined {\n\tif (!from || from === to) return undefined;\n\treturn `[Image converted from ${from} to ${to}.]`;\n}\n\nexport async function processImage(\n\tbytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ProcessImageOptions,\n): Promise {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst normalized = await normalizeImage(bytes, mimeType);\n\tif (!normalized) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmessage: \"[Image omitted: could not be converted to a supported inline image format.]\",\n\t\t};\n\t}\n\n\tif (autoResizeImages) {\n\t\tconst resized = await resizeImage(normalized.bytes, normalized.mimeType, options?.resizeOptions);\n\t\tif (!resized) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage: \"[Image omitted: could not be resized below the inline image size limit.]\",\n\t\t\t};\n\t\t}\n\n\t\tconst hints: string[] = [];\n\t\tconst convertedHint = conversionHint(normalized.convertedFrom, resized.mimeType);\n\t\tif (convertedHint) hints.push(convertedHint);\n\t\tconst dimensionNote = formatDimensionNote(resized);\n\t\tif (dimensionNote) hints.push(dimensionNote);\n\n\t\treturn {\n\t\t\tok: true,\n\t\t\tdata: resized.data,\n\t\t\tmimeType: resized.mimeType,\n\t\t\thints,\n\t\t};\n\t}\n\n\tconst hints: string[] = [];\n\tconst convertedHint = conversionHint(normalized.convertedFrom, normalized.mimeType);\n\tif (convertedHint) hints.push(convertedHint);\n\n\treturn {\n\t\tok: true,\n\t\tdata: Buffer.from(normalized.bytes).toString(\"base64\"),\n\t\tmimeType: normalized.mimeType,\n\t\thints,\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/utils/image-process.js b/dist/utils/image-process.js new file mode 100644 index 0000000..65b15af --- /dev/null +++ b/dist/utils/image-process.js @@ -0,0 +1,83 @@ +import { convertImageBytesToPng } from "./image-convert.js"; +import { formatDimensionNote, resizeImage } from "./image-resize.js"; +function baseMimeType(mimeType) { + return mimeType.split(";")[0]?.trim().toLowerCase() ?? mimeType.toLowerCase(); +} +function normalizeSupportedImageMimeType(mimeType) { + switch (baseMimeType(mimeType)) { + case "image/png": + return "image/png"; + case "image/jpeg": + case "image/jpg": + return "image/jpeg"; + case "image/gif": + return "image/gif"; + case "image/webp": + return "image/webp"; + default: + return null; + } +} +async function normalizeImage(bytes, mimeType) { + const normalizedMimeType = normalizeSupportedImageMimeType(mimeType); + if (normalizedMimeType) { + return { bytes, mimeType: normalizedMimeType }; + } + const pngBytes = await convertImageBytesToPng(bytes); + if (!pngBytes) { + return null; + } + return { + bytes: pngBytes, + mimeType: "image/png", + convertedFrom: baseMimeType(mimeType), + }; +} +function conversionHint(from, to) { + if (!from || from === to) + return undefined; + return `[Image converted from ${from} to ${to}.]`; +} +export async function processImage(bytes, mimeType, options) { + const autoResizeImages = options?.autoResizeImages ?? true; + const normalized = await normalizeImage(bytes, mimeType); + if (!normalized) { + return { + ok: false, + message: "[Image omitted: could not be converted to a supported inline image format.]", + }; + } + if (autoResizeImages) { + const resized = await resizeImage(normalized.bytes, normalized.mimeType, options?.resizeOptions); + if (!resized) { + return { + ok: false, + message: "[Image omitted: could not be resized below the inline image size limit.]", + }; + } + const hints = []; + const convertedHint = conversionHint(normalized.convertedFrom, resized.mimeType); + if (convertedHint) + hints.push(convertedHint); + const dimensionNote = formatDimensionNote(resized); + if (dimensionNote) + hints.push(dimensionNote); + return { + ok: true, + data: resized.data, + mimeType: resized.mimeType, + hints, + }; + } + const hints = []; + const convertedHint = conversionHint(normalized.convertedFrom, normalized.mimeType); + if (convertedHint) + hints.push(convertedHint); + return { + ok: true, + data: Buffer.from(normalized.bytes).toString("base64"), + mimeType: normalized.mimeType, + hints, + }; +} +//# sourceMappingURL=image-process.js.map \ No newline at end of file diff --git a/dist/utils/image-process.js.map b/dist/utils/image-process.js.map new file mode 100644 index 0000000..491443d --- /dev/null +++ b/dist/utils/image-process.js.map @@ -0,0 +1 @@ +{"version":3,"file":"image-process.js","sourceRoot":"","sources":["../../src/utils/image-process.ts"],"names":[],"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C,UAAU,CAAC,aAAa,EAAE,UAAU,CAAC,QAAQ,CAAC,CAAC;IACpF,IAAI,aAAa;QAAE,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;IAE7C,OAAO;QACN,EAAE,EAAE,IAAI;QACR,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;QACtD,QAAQ,EAAE,UAAU,CAAC,QAAQ;QAC7B,KAAK;KACL,CAAC;AAAA,CACF","sourcesContent":["import { convertImageBytesToPng } from \"./image-convert.ts\";\nimport { formatDimensionNote, type ImageResizeOptions, resizeImage } from \"./image-resize.ts\";\n\nexport interface ProcessImageOptions {\n\t/** Whether to resize images to inline provider limits. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Optional resize overrides. Uses resizeImage defaults when omitted. */\n\tresizeOptions?: ImageResizeOptions;\n}\n\nexport type ProcessImageResult =\n\t| {\n\t\t\tok: true;\n\t\t\tdata: string;\n\t\t\tmimeType: string;\n\t\t\thints: string[];\n\t }\n\t| {\n\t\t\tok: false;\n\t\t\tmessage: string;\n\t };\n\ninterface NormalizedImage {\n\tbytes: Uint8Array;\n\tmimeType: string;\n\tconvertedFrom?: string;\n}\n\nfunction baseMimeType(mimeType: string): string {\n\treturn mimeType.split(\";\")[0]?.trim().toLowerCase() ?? mimeType.toLowerCase();\n}\n\nfunction normalizeSupportedImageMimeType(mimeType: string): string | null {\n\tswitch (baseMimeType(mimeType)) {\n\t\tcase \"image/png\":\n\t\t\treturn \"image/png\";\n\t\tcase \"image/jpeg\":\n\t\tcase \"image/jpg\":\n\t\t\treturn \"image/jpeg\";\n\t\tcase \"image/gif\":\n\t\t\treturn \"image/gif\";\n\t\tcase \"image/webp\":\n\t\t\treturn \"image/webp\";\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nasync function normalizeImage(bytes: Uint8Array, mimeType: string): Promise {\n\tconst normalizedMimeType = normalizeSupportedImageMimeType(mimeType);\n\tif (normalizedMimeType) {\n\t\treturn { bytes, mimeType: normalizedMimeType };\n\t}\n\n\tconst pngBytes = await convertImageBytesToPng(bytes);\n\tif (!pngBytes) {\n\t\treturn null;\n\t}\n\n\treturn {\n\t\tbytes: pngBytes,\n\t\tmimeType: \"image/png\",\n\t\tconvertedFrom: baseMimeType(mimeType),\n\t};\n}\n\nfunction conversionHint(from: string | undefined, to: string): string | undefined {\n\tif (!from || from === to) return undefined;\n\treturn `[Image converted from ${from} to ${to}.]`;\n}\n\nexport async function processImage(\n\tbytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ProcessImageOptions,\n): Promise {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst normalized = await normalizeImage(bytes, mimeType);\n\tif (!normalized) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tmessage: \"[Image omitted: could not be converted to a supported inline image format.]\",\n\t\t};\n\t}\n\n\tif (autoResizeImages) {\n\t\tconst resized = await resizeImage(normalized.bytes, normalized.mimeType, options?.resizeOptions);\n\t\tif (!resized) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage: \"[Image omitted: could not be resized below the inline image size limit.]\",\n\t\t\t};\n\t\t}\n\n\t\tconst hints: string[] = [];\n\t\tconst convertedHint = conversionHint(normalized.convertedFrom, resized.mimeType);\n\t\tif (convertedHint) hints.push(convertedHint);\n\t\tconst dimensionNote = formatDimensionNote(resized);\n\t\tif (dimensionNote) hints.push(dimensionNote);\n\n\t\treturn {\n\t\t\tok: true,\n\t\t\tdata: resized.data,\n\t\t\tmimeType: resized.mimeType,\n\t\t\thints,\n\t\t};\n\t}\n\n\tconst hints: string[] = [];\n\tconst convertedHint = conversionHint(normalized.convertedFrom, normalized.mimeType);\n\tif (convertedHint) hints.push(convertedHint);\n\n\treturn {\n\t\tok: true,\n\t\tdata: Buffer.from(normalized.bytes).toString(\"base64\"),\n\t\tmimeType: normalized.mimeType,\n\t\thints,\n\t};\n}\n"]} \ No newline at end of file diff --git a/dist/utils/image-resize-core.d.ts b/dist/utils/image-resize-core.d.ts new file mode 100644 index 0000000..8214d6b --- /dev/null +++ b/dist/utils/image-resize-core.d.ts @@ -0,0 +1,30 @@ +export interface ImageResizeOptions { + maxWidth?: number; + maxHeight?: number; + maxBytes?: number; + jpegQuality?: number; +} +export interface ResizedImage { + data: string; + mimeType: string; + originalWidth: number; + originalHeight: number; + width: number; + height: number; + wasResized: boolean; +} +/** + * Resize an image to fit within the specified max dimensions and encoded file size. + * Returns null if the image cannot be resized below maxBytes. + * + * Uses Photon (Rust/WASM) for image processing. If Photon is not available, + * returns null. + * + * Strategy for staying under maxBytes: + * 1. First resize to maxWidth/maxHeight + * 2. Try both PNG and JPEG formats, pick the smaller one + * 3. If still too large, try JPEG with decreasing quality + * 4. If still too large, progressively reduce dimensions until 1x1 + */ +export declare function resizeImageInProcess(inputBytes: Uint8Array, mimeType: string, options?: ImageResizeOptions): Promise; +//# sourceMappingURL=image-resize-core.d.ts.map \ No newline at end of file diff --git a/dist/utils/image-resize-core.d.ts.map b/dist/utils/image-resize-core.d.ts.map new file mode 100644 index 0000000..5667a24 --- /dev/null +++ b/dist/utils/image-resize-core.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"image-resize-core.d.ts","sourceRoot":"","sources":["../../src/utils/image-resize-core.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,OAAO,CAAC;CACpB;AA2BD;;;;;;;;;;;;GAYG;AACH,wBAAsB,oBAAoB,CACzC,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAqG9B","sourcesContent":["import { applyExifOrientation } from \"./exif-orientation.ts\";\nimport { loadPhoton } from \"./photon.ts\";\n\nexport interface ImageResizeOptions {\n\tmaxWidth?: number; // Default: 2000\n\tmaxHeight?: number; // Default: 2000\n\tmaxBytes?: number; // Default: 4.5MB of base64 payload (below Anthropic's 5MB limit)\n\tjpegQuality?: number; // Default: 80\n}\n\nexport interface ResizedImage {\n\tdata: string; // base64\n\tmimeType: string;\n\toriginalWidth: number;\n\toriginalHeight: number;\n\twidth: number;\n\theight: number;\n\twasResized: boolean;\n}\n\n// 4.5MB of base64 payload. Provides headroom below Anthropic's 5MB limit.\nconst DEFAULT_MAX_BYTES = 4.5 * 1024 * 1024;\n\nconst DEFAULT_OPTIONS: Required = {\n\tmaxWidth: 2000,\n\tmaxHeight: 2000,\n\tmaxBytes: DEFAULT_MAX_BYTES,\n\tjpegQuality: 80,\n};\n\ninterface EncodedCandidate {\n\tdata: string;\n\tencodedSize: number;\n\tmimeType: string;\n}\n\nfunction encodeCandidate(buffer: Uint8Array, mimeType: string): EncodedCandidate {\n\tconst data = Buffer.from(buffer).toString(\"base64\");\n\treturn {\n\t\tdata,\n\t\tencodedSize: Buffer.byteLength(data, \"utf-8\"),\n\t\tmimeType,\n\t};\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Returns null if the image cannot be resized below maxBytes.\n *\n * Uses Photon (Rust/WASM) for image processing. If Photon is not available,\n * returns null.\n *\n * Strategy for staying under maxBytes:\n * 1. First resize to maxWidth/maxHeight\n * 2. Try both PNG and JPEG formats, pick the smaller one\n * 3. If still too large, try JPEG with decreasing quality\n * 4. If still too large, progressively reduce dimensions until 1x1\n */\nexport async function resizeImageInProcess(\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise {\n\tconst opts = { ...DEFAULT_OPTIONS, ...options };\n\tconst inputBase64Size = Math.ceil(inputBytes.byteLength / 3) * 4;\n\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\treturn null;\n\t}\n\n\tlet image: ReturnType | undefined;\n\ttry {\n\t\tconst rawImage = photon.PhotonImage.new_from_byteslice(inputBytes);\n\t\timage = applyExifOrientation(photon, rawImage, inputBytes);\n\t\tif (image !== rawImage) rawImage.free();\n\n\t\tconst originalWidth = image.get_width();\n\t\tconst originalHeight = image.get_height();\n\t\tconst format = mimeType.split(\"/\")[1] ?? \"png\";\n\n\t\t// Check if already within all limits (dimensions AND encoded size)\n\t\tif (originalWidth <= opts.maxWidth && originalHeight <= opts.maxHeight && inputBase64Size < opts.maxBytes) {\n\t\t\treturn {\n\t\t\t\tdata: Buffer.from(inputBytes).toString(\"base64\"),\n\t\t\t\tmimeType: mimeType || `image/${format}`,\n\t\t\t\toriginalWidth,\n\t\t\t\toriginalHeight,\n\t\t\t\twidth: originalWidth,\n\t\t\t\theight: originalHeight,\n\t\t\t\twasResized: false,\n\t\t\t};\n\t\t}\n\n\t\t// Calculate initial dimensions respecting max limits\n\t\tlet targetWidth = originalWidth;\n\t\tlet targetHeight = originalHeight;\n\n\t\tif (targetWidth > opts.maxWidth) {\n\t\t\ttargetHeight = Math.round((targetHeight * opts.maxWidth) / targetWidth);\n\t\t\ttargetWidth = opts.maxWidth;\n\t\t}\n\t\tif (targetHeight > opts.maxHeight) {\n\t\t\ttargetWidth = Math.round((targetWidth * opts.maxHeight) / targetHeight);\n\t\t\ttargetHeight = opts.maxHeight;\n\t\t}\n\n\t\tfunction tryEncodings(width: number, height: number, jpegQualities: number[]): EncodedCandidate[] {\n\t\t\tconst resized = photon!.resize(image!, width, height, photon!.SamplingFilter.Lanczos3);\n\n\t\t\ttry {\n\t\t\t\tconst candidates: EncodedCandidate[] = [encodeCandidate(resized.get_bytes(), \"image/png\")];\n\t\t\t\tfor (const quality of jpegQualities) {\n\t\t\t\t\tcandidates.push(encodeCandidate(resized.get_bytes_jpeg(quality), \"image/jpeg\"));\n\t\t\t\t}\n\t\t\t\treturn candidates;\n\t\t\t} finally {\n\t\t\t\tresized.free();\n\t\t\t}\n\t\t}\n\n\t\tconst qualitySteps = Array.from(new Set([opts.jpegQuality, 85, 70, 55, 40]));\n\t\tlet currentWidth = targetWidth;\n\t\tlet currentHeight = targetHeight;\n\n\t\twhile (true) {\n\t\t\tconst candidates = tryEncodings(currentWidth, currentHeight, qualitySteps);\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tif (candidate.encodedSize < opts.maxBytes) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: candidate.data,\n\t\t\t\t\t\tmimeType: candidate.mimeType,\n\t\t\t\t\t\toriginalWidth,\n\t\t\t\t\t\toriginalHeight,\n\t\t\t\t\t\twidth: currentWidth,\n\t\t\t\t\t\theight: currentHeight,\n\t\t\t\t\t\twasResized: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentWidth === 1 && currentHeight === 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst nextWidth = currentWidth === 1 ? 1 : Math.max(1, Math.floor(currentWidth * 0.75));\n\t\t\tconst nextHeight = currentHeight === 1 ? 1 : Math.max(1, Math.floor(currentHeight * 0.75));\n\t\t\tif (nextWidth === currentWidth && nextHeight === currentHeight) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcurrentWidth = nextWidth;\n\t\t\tcurrentHeight = nextHeight;\n\t\t}\n\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\tif (image) {\n\t\t\timage.free();\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/image-resize-core.js b/dist/utils/image-resize-core.js new file mode 100644 index 0000000..767976b --- /dev/null +++ b/dist/utils/image-resize-core.js @@ -0,0 +1,124 @@ +import { applyExifOrientation } from "./exif-orientation.js"; +import { loadPhoton } from "./photon.js"; +// 4.5MB of base64 payload. Provides headroom below Anthropic's 5MB limit. +const DEFAULT_MAX_BYTES = 4.5 * 1024 * 1024; +const DEFAULT_OPTIONS = { + maxWidth: 2000, + maxHeight: 2000, + maxBytes: DEFAULT_MAX_BYTES, + jpegQuality: 80, +}; +function encodeCandidate(buffer, mimeType) { + const data = Buffer.from(buffer).toString("base64"); + return { + data, + encodedSize: Buffer.byteLength(data, "utf-8"), + mimeType, + }; +} +/** + * Resize an image to fit within the specified max dimensions and encoded file size. + * Returns null if the image cannot be resized below maxBytes. + * + * Uses Photon (Rust/WASM) for image processing. If Photon is not available, + * returns null. + * + * Strategy for staying under maxBytes: + * 1. First resize to maxWidth/maxHeight + * 2. Try both PNG and JPEG formats, pick the smaller one + * 3. If still too large, try JPEG with decreasing quality + * 4. If still too large, progressively reduce dimensions until 1x1 + */ +export async function resizeImageInProcess(inputBytes, mimeType, options) { + const opts = { ...DEFAULT_OPTIONS, ...options }; + const inputBase64Size = Math.ceil(inputBytes.byteLength / 3) * 4; + const photon = await loadPhoton(); + if (!photon) { + return null; + } + let image; + try { + const rawImage = photon.PhotonImage.new_from_byteslice(inputBytes); + image = applyExifOrientation(photon, rawImage, inputBytes); + if (image !== rawImage) + rawImage.free(); + const originalWidth = image.get_width(); + const originalHeight = image.get_height(); + const format = mimeType.split("/")[1] ?? "png"; + // Check if already within all limits (dimensions AND encoded size) + if (originalWidth <= opts.maxWidth && originalHeight <= opts.maxHeight && inputBase64Size < opts.maxBytes) { + return { + data: Buffer.from(inputBytes).toString("base64"), + mimeType: mimeType || `image/${format}`, + originalWidth, + originalHeight, + width: originalWidth, + height: originalHeight, + wasResized: false, + }; + } + // Calculate initial dimensions respecting max limits + let targetWidth = originalWidth; + let targetHeight = originalHeight; + if (targetWidth > opts.maxWidth) { + targetHeight = Math.round((targetHeight * opts.maxWidth) / targetWidth); + targetWidth = opts.maxWidth; + } + if (targetHeight > opts.maxHeight) { + targetWidth = Math.round((targetWidth * opts.maxHeight) / targetHeight); + targetHeight = opts.maxHeight; + } + function tryEncodings(width, height, jpegQualities) { + const resized = photon.resize(image, width, height, photon.SamplingFilter.Lanczos3); + try { + const candidates = [encodeCandidate(resized.get_bytes(), "image/png")]; + for (const quality of jpegQualities) { + candidates.push(encodeCandidate(resized.get_bytes_jpeg(quality), "image/jpeg")); + } + return candidates; + } + finally { + resized.free(); + } + } + const qualitySteps = Array.from(new Set([opts.jpegQuality, 85, 70, 55, 40])); + let currentWidth = targetWidth; + let currentHeight = targetHeight; + while (true) { + const candidates = tryEncodings(currentWidth, currentHeight, qualitySteps); + for (const candidate of candidates) { + if (candidate.encodedSize < opts.maxBytes) { + return { + data: candidate.data, + mimeType: candidate.mimeType, + originalWidth, + originalHeight, + width: currentWidth, + height: currentHeight, + wasResized: true, + }; + } + } + if (currentWidth === 1 && currentHeight === 1) { + break; + } + const nextWidth = currentWidth === 1 ? 1 : Math.max(1, Math.floor(currentWidth * 0.75)); + const nextHeight = currentHeight === 1 ? 1 : Math.max(1, Math.floor(currentHeight * 0.75)); + if (nextWidth === currentWidth && nextHeight === currentHeight) { + break; + } + currentWidth = nextWidth; + currentHeight = nextHeight; + } + return null; + } + catch { + return null; + } + finally { + if (image) { + image.free(); + } + } +} +//# sourceMappingURL=image-resize-core.js.map \ No newline at end of file diff --git a/dist/utils/image-resize-core.js.map b/dist/utils/image-resize-core.js.map new file mode 100644 index 0000000..3b3519d --- /dev/null +++ b/dist/utils/image-resize-core.js.map @@ -0,0 +1 @@ +{"version":3,"file":"image-resize-core.js","sourceRoot":"","sources":["../../src/utils/image-resize-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAmBzC,0EAA0E;AAC1E,MAAM,iBAAiB,GAAG,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AAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC;YACxF,MAAM,UAAU,GAAG,aAAa,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC,CAAC;YAC3F,IAAI,SAAS,KAAK,YAAY,IAAI,UAAU,KAAK,aAAa,EAAE,CAAC;gBAChE,MAAM;YACP,CAAC;YAED,YAAY,GAAG,SAAS,CAAC;YACzB,aAAa,GAAG,UAAU,CAAC;QAC5B,CAAC;QAED,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,IAAI,CAAC;IACb,CAAC;YAAS,CAAC;QACV,IAAI,KAAK,EAAE,CAAC;YACX,KAAK,CAAC,IAAI,EAAE,CAAC;QACd,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import { applyExifOrientation } from \"./exif-orientation.ts\";\nimport { loadPhoton } from \"./photon.ts\";\n\nexport interface ImageResizeOptions {\n\tmaxWidth?: number; // Default: 2000\n\tmaxHeight?: number; // Default: 2000\n\tmaxBytes?: number; // Default: 4.5MB of base64 payload (below Anthropic's 5MB limit)\n\tjpegQuality?: number; // Default: 80\n}\n\nexport interface ResizedImage {\n\tdata: string; // base64\n\tmimeType: string;\n\toriginalWidth: number;\n\toriginalHeight: number;\n\twidth: number;\n\theight: number;\n\twasResized: boolean;\n}\n\n// 4.5MB of base64 payload. Provides headroom below Anthropic's 5MB limit.\nconst DEFAULT_MAX_BYTES = 4.5 * 1024 * 1024;\n\nconst DEFAULT_OPTIONS: Required = {\n\tmaxWidth: 2000,\n\tmaxHeight: 2000,\n\tmaxBytes: DEFAULT_MAX_BYTES,\n\tjpegQuality: 80,\n};\n\ninterface EncodedCandidate {\n\tdata: string;\n\tencodedSize: number;\n\tmimeType: string;\n}\n\nfunction encodeCandidate(buffer: Uint8Array, mimeType: string): EncodedCandidate {\n\tconst data = Buffer.from(buffer).toString(\"base64\");\n\treturn {\n\t\tdata,\n\t\tencodedSize: Buffer.byteLength(data, \"utf-8\"),\n\t\tmimeType,\n\t};\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Returns null if the image cannot be resized below maxBytes.\n *\n * Uses Photon (Rust/WASM) for image processing. If Photon is not available,\n * returns null.\n *\n * Strategy for staying under maxBytes:\n * 1. First resize to maxWidth/maxHeight\n * 2. Try both PNG and JPEG formats, pick the smaller one\n * 3. If still too large, try JPEG with decreasing quality\n * 4. If still too large, progressively reduce dimensions until 1x1\n */\nexport async function resizeImageInProcess(\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise {\n\tconst opts = { ...DEFAULT_OPTIONS, ...options };\n\tconst inputBase64Size = Math.ceil(inputBytes.byteLength / 3) * 4;\n\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\treturn null;\n\t}\n\n\tlet image: ReturnType | undefined;\n\ttry {\n\t\tconst rawImage = photon.PhotonImage.new_from_byteslice(inputBytes);\n\t\timage = applyExifOrientation(photon, rawImage, inputBytes);\n\t\tif (image !== rawImage) rawImage.free();\n\n\t\tconst originalWidth = image.get_width();\n\t\tconst originalHeight = image.get_height();\n\t\tconst format = mimeType.split(\"/\")[1] ?? \"png\";\n\n\t\t// Check if already within all limits (dimensions AND encoded size)\n\t\tif (originalWidth <= opts.maxWidth && originalHeight <= opts.maxHeight && inputBase64Size < opts.maxBytes) {\n\t\t\treturn {\n\t\t\t\tdata: Buffer.from(inputBytes).toString(\"base64\"),\n\t\t\t\tmimeType: mimeType || `image/${format}`,\n\t\t\t\toriginalWidth,\n\t\t\t\toriginalHeight,\n\t\t\t\twidth: originalWidth,\n\t\t\t\theight: originalHeight,\n\t\t\t\twasResized: false,\n\t\t\t};\n\t\t}\n\n\t\t// Calculate initial dimensions respecting max limits\n\t\tlet targetWidth = originalWidth;\n\t\tlet targetHeight = originalHeight;\n\n\t\tif (targetWidth > opts.maxWidth) {\n\t\t\ttargetHeight = Math.round((targetHeight * opts.maxWidth) / targetWidth);\n\t\t\ttargetWidth = opts.maxWidth;\n\t\t}\n\t\tif (targetHeight > opts.maxHeight) {\n\t\t\ttargetWidth = Math.round((targetWidth * opts.maxHeight) / targetHeight);\n\t\t\ttargetHeight = opts.maxHeight;\n\t\t}\n\n\t\tfunction tryEncodings(width: number, height: number, jpegQualities: number[]): EncodedCandidate[] {\n\t\t\tconst resized = photon!.resize(image!, width, height, photon!.SamplingFilter.Lanczos3);\n\n\t\t\ttry {\n\t\t\t\tconst candidates: EncodedCandidate[] = [encodeCandidate(resized.get_bytes(), \"image/png\")];\n\t\t\t\tfor (const quality of jpegQualities) {\n\t\t\t\t\tcandidates.push(encodeCandidate(resized.get_bytes_jpeg(quality), \"image/jpeg\"));\n\t\t\t\t}\n\t\t\t\treturn candidates;\n\t\t\t} finally {\n\t\t\t\tresized.free();\n\t\t\t}\n\t\t}\n\n\t\tconst qualitySteps = Array.from(new Set([opts.jpegQuality, 85, 70, 55, 40]));\n\t\tlet currentWidth = targetWidth;\n\t\tlet currentHeight = targetHeight;\n\n\t\twhile (true) {\n\t\t\tconst candidates = tryEncodings(currentWidth, currentHeight, qualitySteps);\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tif (candidate.encodedSize < opts.maxBytes) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: candidate.data,\n\t\t\t\t\t\tmimeType: candidate.mimeType,\n\t\t\t\t\t\toriginalWidth,\n\t\t\t\t\t\toriginalHeight,\n\t\t\t\t\t\twidth: currentWidth,\n\t\t\t\t\t\theight: currentHeight,\n\t\t\t\t\t\twasResized: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentWidth === 1 && currentHeight === 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst nextWidth = currentWidth === 1 ? 1 : Math.max(1, Math.floor(currentWidth * 0.75));\n\t\t\tconst nextHeight = currentHeight === 1 ? 1 : Math.max(1, Math.floor(currentHeight * 0.75));\n\t\t\tif (nextWidth === currentWidth && nextHeight === currentHeight) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcurrentWidth = nextWidth;\n\t\t\tcurrentHeight = nextHeight;\n\t\t}\n\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\tif (image) {\n\t\t\timage.free();\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/image-resize-worker.d.ts b/dist/utils/image-resize-worker.d.ts new file mode 100644 index 0000000..d87e6eb --- /dev/null +++ b/dist/utils/image-resize-worker.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=image-resize-worker.d.ts.map \ No newline at end of file diff --git a/dist/utils/image-resize-worker.d.ts.map b/dist/utils/image-resize-worker.d.ts.map new file mode 100644 index 0000000..3d20b14 --- /dev/null +++ b/dist/utils/image-resize-worker.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"image-resize-worker.d.ts","sourceRoot":"","sources":["../../src/utils/image-resize-worker.ts"],"names":[],"mappings":"","sourcesContent":["import { parentPort } from \"node:worker_threads\";\nimport { type ImageResizeOptions, type ResizedImage, resizeImageInProcess } from \"./image-resize-core.ts\";\n\ninterface ResizeImageWorkerRequest {\n\tinputBytes: Uint8Array;\n\tmimeType: string;\n\toptions?: ImageResizeOptions;\n}\n\ninterface ResizeImageWorkerResponse {\n\tresult?: ResizedImage | null;\n\terror?: string;\n}\n\nfunction isResizeImageWorkerRequest(value: unknown): value is ResizeImageWorkerRequest {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst record = value as Record;\n\treturn record.inputBytes instanceof Uint8Array && typeof record.mimeType === \"string\";\n}\n\nconst port = parentPort;\nif (!port) {\n\tthrow new Error(\"image resize worker requires parentPort\");\n}\n\nport.once(\"message\", (message: unknown) => {\n\tvoid (async () => {\n\t\ttry {\n\t\t\tif (!isResizeImageWorkerRequest(message)) {\n\t\t\t\tthrow new Error(\"Invalid image resize worker request\");\n\t\t\t}\n\t\t\tconst result = await resizeImageInProcess(message.inputBytes, message.mimeType, message.options);\n\t\t\tconst response: ResizeImageWorkerResponse = { result };\n\t\t\tport.postMessage(response);\n\t\t} catch (error) {\n\t\t\tconst response: ResizeImageWorkerResponse = {\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t\tport.postMessage(response);\n\t\t}\n\t})();\n});\n"]} \ No newline at end of file diff --git a/dist/utils/image-resize-worker.js b/dist/utils/image-resize-worker.js new file mode 100644 index 0000000..8310c93 --- /dev/null +++ b/dist/utils/image-resize-worker.js @@ -0,0 +1,31 @@ +import { parentPort } from "node:worker_threads"; +import { resizeImageInProcess } from "./image-resize-core.js"; +function isResizeImageWorkerRequest(value) { + if (!value || typeof value !== "object") + return false; + const record = value; + return record.inputBytes instanceof Uint8Array && typeof record.mimeType === "string"; +} +const port = parentPort; +if (!port) { + throw new Error("image resize worker requires parentPort"); +} +port.once("message", (message) => { + void (async () => { + try { + if (!isResizeImageWorkerRequest(message)) { + throw new Error("Invalid image resize worker request"); + } + const result = await resizeImageInProcess(message.inputBytes, message.mimeType, message.options); + const response = { result }; + port.postMessage(response); + } + catch (error) { + const response = { + error: error instanceof Error ? error.message : String(error), + }; + port.postMessage(response); + } + })(); +}); +//# sourceMappingURL=image-resize-worker.js.map \ No newline at end of file diff --git a/dist/utils/image-resize-worker.js.map b/dist/utils/image-resize-worker.js.map new file mode 100644 index 0000000..493199d --- /dev/null +++ b/dist/utils/image-resize-worker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"image-resize-worker.js","sourceRoot":"","sources":["../../src/utils/image-resize-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAA8C,oBAAoB,EAAE,MAAM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\";\nimport { type ImageResizeOptions, type ResizedImage, resizeImageInProcess } from \"./image-resize-core.ts\";\n\ninterface ResizeImageWorkerRequest {\n\tinputBytes: Uint8Array;\n\tmimeType: string;\n\toptions?: ImageResizeOptions;\n}\n\ninterface ResizeImageWorkerResponse {\n\tresult?: ResizedImage | null;\n\terror?: string;\n}\n\nfunction isResizeImageWorkerRequest(value: unknown): value is ResizeImageWorkerRequest {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst record = value as Record;\n\treturn record.inputBytes instanceof Uint8Array && typeof record.mimeType === \"string\";\n}\n\nconst port = parentPort;\nif (!port) {\n\tthrow new Error(\"image resize worker requires parentPort\");\n}\n\nport.once(\"message\", (message: unknown) => {\n\tvoid (async () => {\n\t\ttry {\n\t\t\tif (!isResizeImageWorkerRequest(message)) {\n\t\t\t\tthrow new Error(\"Invalid image resize worker request\");\n\t\t\t}\n\t\t\tconst result = await resizeImageInProcess(message.inputBytes, message.mimeType, message.options);\n\t\t\tconst response: ResizeImageWorkerResponse = { result };\n\t\t\tport.postMessage(response);\n\t\t} catch (error) {\n\t\t\tconst response: ResizeImageWorkerResponse = {\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t\tport.postMessage(response);\n\t\t}\n\t})();\n});\n"]} \ No newline at end of file diff --git a/dist/utils/image-resize.d.ts b/dist/utils/image-resize.d.ts new file mode 100644 index 0000000..ef46753 --- /dev/null +++ b/dist/utils/image-resize.d.ts @@ -0,0 +1,16 @@ +import { type ImageResizeOptions, type ResizedImage } from "./image-resize-core.ts"; +export type { ImageResizeOptions, ResizedImage } from "./image-resize-core.ts"; +/** + * Resize an image to fit within the specified max dimensions and encoded file size. + * Runs Photon in a worker thread so WASM decoding, resizing, and encoding do not + * block the TUI event loop. If the worker cannot be loaded (for example in some + * Bun compiled executable layouts), fall back to in-process resizing so image + * reads still work. + */ +export declare function resizeImage(inputBytes: Uint8Array, mimeType: string, options?: ImageResizeOptions): Promise; +/** + * Format a dimension note for resized images. + * This helps the model understand the coordinate mapping. + */ +export declare function formatDimensionNote(result: ResizedImage): string | undefined; +//# sourceMappingURL=image-resize.d.ts.map \ No newline at end of file diff --git a/dist/utils/image-resize.d.ts.map b/dist/utils/image-resize.d.ts.map new file mode 100644 index 0000000..61cbc94 --- /dev/null +++ b/dist/utils/image-resize.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"image-resize.d.ts","sourceRoot":"","sources":["../../src/utils/image-resize.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,kBAAkB,EAAE,KAAK,YAAY,EAAwB,MAAM,wBAAwB,CAAC;AAE1G,YAAY,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AA0E/E;;;;;;GAMG;AACH,wBAAsB,WAAW,CAChC,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAqB9B;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAO5E","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { type ImageResizeOptions, type ResizedImage, resizeImageInProcess } from \"./image-resize-core.ts\";\n\nexport type { ImageResizeOptions, ResizedImage } from \"./image-resize-core.ts\";\n\ninterface ResizeImageWorkerResponse {\n\tresult?: ResizedImage | null;\n\terror?: string;\n}\n\nfunction toTransferableBytes(input: Uint8Array): Uint8Array {\n\t// Transfer detaches the buffer, so transfer a worker-owned copy and leave the\n\t// caller's bytes intact.\n\treturn new Uint8Array(input);\n}\n\nfunction isResizeImageWorkerResponse(value: unknown): value is ResizeImageWorkerResponse {\n\treturn value !== null && typeof value === \"object\";\n}\n\nfunction createResizeWorker(workerSpecifier: string | URL): Worker {\n\treturn new Worker(workerSpecifier);\n}\n\nasync function resizeImageInWorker(\n\tworkerSpecifier: string | URL,\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise {\n\tconst worker = createResizeWorker(workerSpecifier);\n\ttry {\n\t\tconst inputBytesForWorker = toTransferableBytes(inputBytes);\n\t\treturn await new Promise((resolve, reject) => {\n\t\t\tlet settled = false;\n\t\t\tconst settle = (result: ResizedImage | null): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolve(result);\n\t\t\t};\n\t\t\tconst fail = (error: Error): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\treject(error);\n\t\t\t};\n\n\t\t\tworker.once(\"message\", (message: unknown) => {\n\t\t\t\tif (!isResizeImageWorkerResponse(message)) {\n\t\t\t\t\tfail(new Error(\"Invalid image resize worker response\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (message.error) {\n\t\t\t\t\tfail(new Error(message.error));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettle(message.result ?? null);\n\t\t\t});\n\t\t\tworker.once(\"error\", fail);\n\t\t\tworker.once(\"exit\", (code) => {\n\t\t\t\tif (!settled) {\n\t\t\t\t\tfail(new Error(`Image resize worker exited with code ${code}`));\n\t\t\t\t}\n\t\t\t});\n\t\t\tworker.postMessage(\n\t\t\t\t{\n\t\t\t\t\tinputBytes: inputBytesForWorker,\n\t\t\t\t\tmimeType,\n\t\t\t\t\toptions,\n\t\t\t\t},\n\t\t\t\t[inputBytesForWorker.buffer],\n\t\t\t);\n\t\t});\n\t} finally {\n\t\tvoid worker.terminate().catch(() => undefined);\n\t}\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Runs Photon in a worker thread so WASM decoding, resizing, and encoding do not\n * block the TUI event loop. If the worker cannot be loaded (for example in some\n * Bun compiled executable layouts), fall back to in-process resizing so image\n * reads still work.\n */\nexport async function resizeImage(\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise {\n\tconst isTypeScriptRuntime = import.meta.url.endsWith(\".ts\");\n\tconst workerUrl = new URL(\n\t\tisTypeScriptRuntime ? \"./image-resize-worker.ts\" : \"./image-resize-worker.js\",\n\t\timport.meta.url,\n\t);\n\n\t// Bun compiled executables resolve worker entrypoints by string path, not via\n\t// new URL(..., import.meta.url). Try the string path first under Bun so the\n\t// release binary uses the embedded worker instead of falling back in-process.\n\tif (typeof process.versions.bun === \"string\") {\n\t\ttry {\n\t\t\treturn await resizeImageInWorker(\"./src/utils/image-resize-worker.ts\", inputBytes, mimeType, options);\n\t\t} catch {}\n\t}\n\n\ttry {\n\t\treturn await resizeImageInWorker(workerUrl, inputBytes, mimeType, options);\n\t} catch {\n\t\treturn resizeImageInProcess(inputBytes, mimeType, options);\n\t}\n}\n\n/**\n * Format a dimension note for resized images.\n * This helps the model understand the coordinate mapping.\n */\nexport function formatDimensionNote(result: ResizedImage): string | undefined {\n\tif (!result.wasResized) {\n\t\treturn undefined;\n\t}\n\n\tconst scale = result.originalWidth / result.width;\n\treturn `[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`;\n}\n"]} \ No newline at end of file diff --git a/dist/utils/image-resize.js b/dist/utils/image-resize.js new file mode 100644 index 0000000..686c9f3 --- /dev/null +++ b/dist/utils/image-resize.js @@ -0,0 +1,97 @@ +import { Worker } from "node:worker_threads"; +import { resizeImageInProcess } from "./image-resize-core.js"; +function toTransferableBytes(input) { + // Transfer detaches the buffer, so transfer a worker-owned copy and leave the + // caller's bytes intact. + return new Uint8Array(input); +} +function isResizeImageWorkerResponse(value) { + return value !== null && typeof value === "object"; +} +function createResizeWorker(workerSpecifier) { + return new Worker(workerSpecifier); +} +async function resizeImageInWorker(workerSpecifier, inputBytes, mimeType, options) { + const worker = createResizeWorker(workerSpecifier); + try { + const inputBytesForWorker = toTransferableBytes(inputBytes); + return await new Promise((resolve, reject) => { + let settled = false; + const settle = (result) => { + if (settled) + return; + settled = true; + resolve(result); + }; + const fail = (error) => { + if (settled) + return; + settled = true; + reject(error); + }; + worker.once("message", (message) => { + if (!isResizeImageWorkerResponse(message)) { + fail(new Error("Invalid image resize worker response")); + return; + } + if (message.error) { + fail(new Error(message.error)); + return; + } + settle(message.result ?? null); + }); + worker.once("error", fail); + worker.once("exit", (code) => { + if (!settled) { + fail(new Error(`Image resize worker exited with code ${code}`)); + } + }); + worker.postMessage({ + inputBytes: inputBytesForWorker, + mimeType, + options, + }, [inputBytesForWorker.buffer]); + }); + } + finally { + void worker.terminate().catch(() => undefined); + } +} +/** + * Resize an image to fit within the specified max dimensions and encoded file size. + * Runs Photon in a worker thread so WASM decoding, resizing, and encoding do not + * block the TUI event loop. If the worker cannot be loaded (for example in some + * Bun compiled executable layouts), fall back to in-process resizing so image + * reads still work. + */ +export async function resizeImage(inputBytes, mimeType, options) { + const isTypeScriptRuntime = import.meta.url.endsWith(".ts"); + const workerUrl = new URL(isTypeScriptRuntime ? "./image-resize-worker.ts" : "./image-resize-worker.js", import.meta.url); + // Bun compiled executables resolve worker entrypoints by string path, not via + // new URL(..., import.meta.url). Try the string path first under Bun so the + // release binary uses the embedded worker instead of falling back in-process. + if (typeof process.versions.bun === "string") { + try { + return await resizeImageInWorker("./src/utils/image-resize-worker.ts", inputBytes, mimeType, options); + } + catch { } + } + try { + return await resizeImageInWorker(workerUrl, inputBytes, mimeType, options); + } + catch { + return resizeImageInProcess(inputBytes, mimeType, options); + } +} +/** + * Format a dimension note for resized images. + * This helps the model understand the coordinate mapping. + */ +export function formatDimensionNote(result) { + if (!result.wasResized) { + return undefined; + } + const scale = result.originalWidth / result.width; + return `[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`; +} +//# sourceMappingURL=image-resize.js.map \ No newline at end of file diff --git a/dist/utils/image-resize.js.map b/dist/utils/image-resize.js.map new file mode 100644 index 0000000..ecbe198 --- /dev/null +++ b/dist/utils/image-resize.js.map @@ -0,0 +1 @@ +{"version":3,"file":"image-resize.js","sourceRoot":"","sources":["../../src/utils/image-resize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAA8C,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAS1G,SAAS,mBAAmB,CAAC,KAAiB,EAA2B;IACxE,8EAA8E;IAC9E,yBAAyB;IACzB,OAAO,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;AAAA,CAC7B;AAED,SAAS,2BAA2B,CAAC,KAAc,EAAsC;IACxF,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC;AAAA,CACnD;AAED,SAAS,kBAAkB,CAAC,eAA6B,EAAU;IAClE,OAAO,IAAI,MAAM,CAAC,eAAe,CAAC,CAAC;AAAA,CACnC;AAED,KAAK,UAAU,mBAAmB,CACjC,eAA6B,EAC7B,UAAsB,EACtB,QAAgB,EAChB,OAA4B,EACG;IAC/B,MAAM,MAAM,GAAG,kBAAkB,CAAC,eAAe,CAAC,CAAC;IACnD,IAAI,CAAC;QACJ,MAAM,mBAAmB,GAAG,mBAAmB,CAAC,UAAU,CAAC,CAAC;QAC5D,OAAO,MAAM,IAAI,OAAO,CAAsB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,CAAC;YAClE,IAAI,OAAO,GAAG,KAAK,CAAC;YACpB,MAAM,MAAM,GAAG,CAAC,MAA2B,EAAQ,EAAE,CAAC;gBACrD,IAAI,OAAO;oBAAE,OAAO;gBACpB,OAAO,GAAG,IAAI,CAAC;gBACf,OAAO,CAAC,MAAM,CAAC,CAAC;YAAA,CAChB,CAAC;YACF,MAAM,IAAI,GAAG,CAAC,KAAY,EAAQ,EAAE,CAAC;gBACpC,IAAI,OAAO;oBAAE,OAAO;gBACpB,OAAO,GAAG,IAAI,CAAC;gBACf,MAAM,CAAC,KAAK,CAAC,CAAC;YAAA,C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AAM,SAAS,GAAG,IAAI,GAAG,CACxB,mBAAmB,CAAC,CAAC,CAAC,0BAA0B,CAAC,CAAC,CAAC,0BAA0B,EAC7E,OAAO,IAAI,CAAC,GAAG,CACf,CAAC;IAEF,8EAA8E;IAC9E,4EAA4E;IAC5E,8EAA8E;IAC9E,IAAI,OAAO,OAAO,CAAC,QAAQ,CAAC,GAAG,KAAK,QAAQ,EAAE,CAAC;QAC9C,IAAI,CAAC;YACJ,OAAO,MAAM,mBAAmB,CAAC,oCAAoC,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;QACvG,CAAC;QAAC,MAAM,CAAC,CAAA,CAAC;IACX,CAAC;IAED,IAAI,CAAC;QACJ,OAAO,MAAM,mBAAmB,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5E,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,oBAAoB,CAAC,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5D,CAAC;AAAA,CACD;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAoB,EAAsB;IAC7E,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;QACxB,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,MAAM,KAAK,GAAG,MAAM,CAAC,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC;IAClD,OAAO,oBAAoB,MAAM,CAAC,aAAa,IAAI,MAAM,CAAC,cAAc,kBAAkB,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,6BAA6B,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,6BAA6B,CAAC;AAAA,CAClM","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { type ImageResizeOptions, type ResizedImage, resizeImageInProcess } from \"./image-resize-core.ts\";\n\nexport type { ImageResizeOptions, ResizedImage } from \"./image-resize-core.ts\";\n\ninterface ResizeImageWorkerResponse {\n\tresult?: ResizedImage | null;\n\terror?: string;\n}\n\nfunction toTransferableBytes(input: Uint8Array): Uint8Array {\n\t// Transfer detaches the buffer, so transfer a worker-owned copy and leave the\n\t// caller's bytes intact.\n\treturn new Uint8Array(input);\n}\n\nfunction isResizeImageWorkerResponse(value: unknown): value is ResizeImageWorkerResponse {\n\treturn value !== null && typeof value === \"object\";\n}\n\nfunction createResizeWorker(workerSpecifier: string | URL): Worker {\n\treturn new Worker(workerSpecifier);\n}\n\nasync function resizeImageInWorker(\n\tworkerSpecifier: string | URL,\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise {\n\tconst worker = createResizeWorker(workerSpecifier);\n\ttry {\n\t\tconst inputBytesForWorker = toTransferableBytes(inputBytes);\n\t\treturn await new Promise((resolve, reject) => {\n\t\t\tlet settled = false;\n\t\t\tconst settle = (result: ResizedImage | null): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolve(result);\n\t\t\t};\n\t\t\tconst fail = (error: Error): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\treject(error);\n\t\t\t};\n\n\t\t\tworker.once(\"message\", (message: unknown) => {\n\t\t\t\tif (!isResizeImageWorkerResponse(message)) {\n\t\t\t\t\tfail(new Error(\"Invalid image resize worker response\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (message.error) {\n\t\t\t\t\tfail(new Error(message.error));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettle(message.result ?? null);\n\t\t\t});\n\t\t\tworker.once(\"error\", fail);\n\t\t\tworker.once(\"exit\", (code) => {\n\t\t\t\tif (!settled) {\n\t\t\t\t\tfail(new Error(`Image resize worker exited with code ${code}`));\n\t\t\t\t}\n\t\t\t});\n\t\t\tworker.postMessage(\n\t\t\t\t{\n\t\t\t\t\tinputBytes: inputBytesForWorker,\n\t\t\t\t\tmimeType,\n\t\t\t\t\toptions,\n\t\t\t\t},\n\t\t\t\t[inputBytesForWorker.buffer],\n\t\t\t);\n\t\t});\n\t} finally {\n\t\tvoid worker.terminate().catch(() => undefined);\n\t}\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Runs Photon in a worker thread so WASM decoding, resizing, and encoding do not\n * block the TUI event loop. If the worker cannot be loaded (for example in some\n * Bun compiled executable layouts), fall back to in-process resizing so image\n * reads still work.\n */\nexport async function resizeImage(\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise {\n\tconst isTypeScriptRuntime = import.meta.url.endsWith(\".ts\");\n\tconst workerUrl = new URL(\n\t\tisTypeScriptRuntime ? \"./image-resize-worker.ts\" : \"./image-resize-worker.js\",\n\t\timport.meta.url,\n\t);\n\n\t// Bun compiled executables resolve worker entrypoints by string path, not via\n\t// new URL(..., import.meta.url). Try the string path first under Bun so the\n\t// release binary uses the embedded worker instead of falling back in-process.\n\tif (typeof process.versions.bun === \"string\") {\n\t\ttry {\n\t\t\treturn await resizeImageInWorker(\"./src/utils/image-resize-worker.ts\", inputBytes, mimeType, options);\n\t\t} catch {}\n\t}\n\n\ttry {\n\t\treturn await resizeImageInWorker(workerUrl, inputBytes, mimeType, options);\n\t} catch {\n\t\treturn resizeImageInProcess(inputBytes, mimeType, options);\n\t}\n}\n\n/**\n * Format a dimension note for resized images.\n * This helps the model understand the coordinate mapping.\n */\nexport function formatDimensionNote(result: ResizedImage): string | undefined {\n\tif (!result.wasResized) {\n\t\treturn undefined;\n\t}\n\n\tconst scale = result.originalWidth / result.width;\n\treturn `[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`;\n}\n"]} \ No newline at end of file diff --git a/dist/utils/json.d.ts b/dist/utils/json.d.ts new file mode 100644 index 0000000..ee125d8 --- /dev/null +++ b/dist/utils/json.d.ts @@ -0,0 +1,3 @@ +/** Strip `//` line comments and trailing commas from JSON, leaving string literals untouched. */ +export declare function stripJsonComments(input: string): string; +//# sourceMappingURL=json.d.ts.map \ No newline at end of file diff --git a/dist/utils/json.d.ts.map b/dist/utils/json.d.ts.map new file mode 100644 index 0000000..a751681 --- /dev/null +++ b/dist/utils/json.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"json.d.ts","sourceRoot":"","sources":["../../src/utils/json.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAIvD","sourcesContent":["/** Strip `//` line comments and trailing commas from JSON, leaving string literals untouched. */\nexport function stripJsonComments(input: string): string {\n\treturn input\n\t\t.replace(/\"(?:\\\\.|[^\"\\\\])*\"|\\/\\/[^\\n]*/g, (m) => (m[0] === '\"' ? m : \"\"))\n\t\t.replace(/\"(?:\\\\.|[^\"\\\\])*\"|,(\\s*[}\\]])/g, (m, tail) => tail ?? (m[0] === '\"' ? m : \"\"));\n}\n"]} \ No newline at end of file diff --git a/dist/utils/json.js b/dist/utils/json.js new file mode 100644 index 0000000..02913a0 --- /dev/null +++ b/dist/utils/json.js @@ -0,0 +1,7 @@ +/** Strip `//` line comments and trailing commas from JSON, leaving string literals untouched. */ +export function stripJsonComments(input) { + return input + .replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g, (m) => (m[0] === '"' ? m : "")) + .replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g, (m, tail) => tail ?? (m[0] === '"' ? m : "")); +} +//# sourceMappingURL=json.js.map \ No newline at end of file diff --git a/dist/utils/json.js.map b/dist/utils/json.js.map new file mode 100644 index 0000000..24da953 --- /dev/null +++ b/dist/utils/json.js.map @@ -0,0 +1 @@ +{"version":3,"file":"json.js","sourceRoot":"","sources":["../../src/utils/json.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,MAAM,UAAU,iBAAiB,CAAC,KAAa,EAAU;IACxD,OAAO,KAAK;SACV,OAAO,CAAC,+BAA+B,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;SACxE,OAAO,CAAC,gCAAgC,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAAA,CAC1F","sourcesContent":["/** Strip `//` line comments and trailing commas from JSON, leaving string literals untouched. */\nexport function stripJsonComments(input: string): string {\n\treturn input\n\t\t.replace(/\"(?:\\\\.|[^\"\\\\])*\"|\\/\\/[^\\n]*/g, (m) => (m[0] === '\"' ? m : \"\"))\n\t\t.replace(/\"(?:\\\\.|[^\"\\\\])*\"|,(\\s*[}\\]])/g, (m, tail) => tail ?? (m[0] === '\"' ? m : \"\"));\n}\n"]} \ No newline at end of file diff --git a/dist/utils/mime.d.ts b/dist/utils/mime.d.ts new file mode 100644 index 0000000..882ba74 --- /dev/null +++ b/dist/utils/mime.d.ts @@ -0,0 +1,3 @@ +export declare function detectSupportedImageMimeType(buffer: Uint8Array): string | null; +export declare function detectSupportedImageMimeTypeFromFile(filePath: string): Promise; +//# sourceMappingURL=mime.d.ts.map \ No newline at end of file diff --git a/dist/utils/mime.d.ts.map b/dist/utils/mime.d.ts.map new file mode 100644 index 0000000..2c240ce --- /dev/null +++ b/dist/utils/mime.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mime.d.ts","sourceRoot":"","sources":["../../src/utils/mime.ts"],"names":[],"mappings":"AAKA,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,GAAG,IAAI,CAiB9E;AAED,wBAAsB,oCAAoC,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CASnG","sourcesContent":["import { open } from \"node:fs/promises\";\n\nconst IMAGE_TYPE_SNIFF_BYTES = 4100;\nconst PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\n\nexport function detectSupportedImageMimeType(buffer: Uint8Array): string | null {\n\tif (startsWith(buffer, [0xff, 0xd8, 0xff])) {\n\t\treturn buffer[3] === 0xf7 ? null : \"image/jpeg\";\n\t}\n\tif (startsWith(buffer, PNG_SIGNATURE)) {\n\t\treturn isPng(buffer) && !isAnimatedPng(buffer) ? \"image/png\" : null;\n\t}\n\tif (startsWithAscii(buffer, 0, \"GIF\")) {\n\t\treturn \"image/gif\";\n\t}\n\tif (startsWithAscii(buffer, 0, \"RIFF\") && startsWithAscii(buffer, 8, \"WEBP\")) {\n\t\treturn \"image/webp\";\n\t}\n\tif (startsWithAscii(buffer, 0, \"BM\") && isBmp(buffer)) {\n\t\treturn \"image/bmp\";\n\t}\n\treturn null;\n}\n\nexport async function detectSupportedImageMimeTypeFromFile(filePath: string): Promise {\n\tconst fileHandle = await open(filePath, \"r\");\n\ttry {\n\t\tconst buffer = Buffer.alloc(IMAGE_TYPE_SNIFF_BYTES);\n\t\tconst { bytesRead } = await fileHandle.read(buffer, 0, IMAGE_TYPE_SNIFF_BYTES, 0);\n\t\treturn detectSupportedImageMimeType(buffer.subarray(0, bytesRead));\n\t} finally {\n\t\tawait fileHandle.close();\n\t}\n}\n\nfunction isPng(buffer: Uint8Array): boolean {\n\treturn (\n\t\tbuffer.length >= 16 && readUint32BE(buffer, PNG_SIGNATURE.length) === 13 && startsWithAscii(buffer, 12, \"IHDR\")\n\t);\n}\n\nfunction isAnimatedPng(buffer: Uint8Array): boolean {\n\tlet offset = PNG_SIGNATURE.length;\n\twhile (offset + 8 <= buffer.length) {\n\t\tconst chunkLength = readUint32BE(buffer, offset);\n\t\tconst chunkTypeOffset = offset + 4;\n\t\tif (startsWithAscii(buffer, chunkTypeOffset, \"acTL\")) return true;\n\t\tif (startsWithAscii(buffer, chunkTypeOffset, \"IDAT\")) return false;\n\n\t\tconst nextOffset = offset + 8 + chunkLength + 4;\n\t\tif (nextOffset <= offset || nextOffset > buffer.length) return false;\n\t\toffset = nextOffset;\n\t}\n\treturn false;\n}\n\nfunction isBmp(buffer: Uint8Array): boolean {\n\tif (buffer.length < 26) return false;\n\n\tconst declaredFileSize = readUint32LE(buffer, 2);\n\tconst pixelDataOffset = readUint32LE(buffer, 10);\n\tconst dibHeaderSize = readUint32LE(buffer, 14);\n\tif (declaredFileSize !== 0 && declaredFileSize < 26) return false;\n\tif (pixelDataOffset < 14 + dibHeaderSize) return false;\n\tif (declaredFileSize !== 0 && pixelDataOffset >= declaredFileSize) return false;\n\n\tlet colorPlanes: number;\n\tlet bitsPerPixel: number;\n\tif (dibHeaderSize === 12) {\n\t\tcolorPlanes = readUint16LE(buffer, 22);\n\t\tbitsPerPixel = readUint16LE(buffer, 24);\n\t} else if (dibHeaderSize >= 40 && dibHeaderSize <= 124) {\n\t\tif (buffer.length < 30) return false;\n\t\tcolorPlanes = readUint16LE(buffer, 26);\n\t\tbitsPerPixel = readUint16LE(buffer, 28);\n\t} else {\n\t\treturn false;\n\t}\n\n\treturn colorPlanes === 1 && [1, 4, 8, 16, 24, 32].includes(bitsPerPixel);\n}\n\nfunction readUint16LE(buffer: Uint8Array, offset: number): number {\n\treturn (buffer[offset] ?? 0) + ((buffer[offset + 1] ?? 0) << 8);\n}\n\nfunction readUint32BE(buffer: Uint8Array, offset: number): number {\n\treturn (\n\t\t(buffer[offset] ?? 0) * 0x1000000 +\n\t\t((buffer[offset + 1] ?? 0) << 16) +\n\t\t((buffer[offset + 2] ?? 0) << 8) +\n\t\t(buffer[offset + 3] ?? 0)\n\t);\n}\n\nfunction readUint32LE(buffer: Uint8Array, offset: number): number {\n\treturn (\n\t\t(buffer[offset] ?? 0) +\n\t\t((buffer[offset + 1] ?? 0) << 8) +\n\t\t((buffer[offset + 2] ?? 0) << 16) +\n\t\t(buffer[offset + 3] ?? 0) * 0x1000000\n\t);\n}\n\nfunction startsWith(buffer: Uint8Array, bytes: number[]): boolean {\n\tif (buffer.length < bytes.length) return false;\n\treturn bytes.every((byte, index) => buffer[index] === byte);\n}\n\nfunction startsWithAscii(buffer: Uint8Array, offset: number, text: string): boolean {\n\tif (buffer.length < offset + text.length) return false;\n\tfor (let index = 0; index < text.length; index++) {\n\t\tif (buffer[offset + index] !== text.charCodeAt(index)) return false;\n\t}\n\treturn true;\n}\n"]} \ No newline at end of file diff --git a/dist/utils/mime.js b/dist/utils/mime.js new file mode 100644 index 0000000..4b51659 --- /dev/null +++ b/dist/utils/mime.js @@ -0,0 +1,110 @@ +import { open } from "node:fs/promises"; +const IMAGE_TYPE_SNIFF_BYTES = 4100; +const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; +export function detectSupportedImageMimeType(buffer) { + if (startsWith(buffer, [0xff, 0xd8, 0xff])) { + return buffer[3] === 0xf7 ? null : "image/jpeg"; + } + if (startsWith(buffer, PNG_SIGNATURE)) { + return isPng(buffer) && !isAnimatedPng(buffer) ? "image/png" : null; + } + if (startsWithAscii(buffer, 0, "GIF")) { + return "image/gif"; + } + if (startsWithAscii(buffer, 0, "RIFF") && startsWithAscii(buffer, 8, "WEBP")) { + return "image/webp"; + } + if (startsWithAscii(buffer, 0, "BM") && isBmp(buffer)) { + return "image/bmp"; + } + return null; +} +export async function detectSupportedImageMimeTypeFromFile(filePath) { + const fileHandle = await open(filePath, "r"); + try { + const buffer = Buffer.alloc(IMAGE_TYPE_SNIFF_BYTES); + const { bytesRead } = await fileHandle.read(buffer, 0, IMAGE_TYPE_SNIFF_BYTES, 0); + return detectSupportedImageMimeType(buffer.subarray(0, bytesRead)); + } + finally { + await fileHandle.close(); + } +} +function isPng(buffer) { + return (buffer.length >= 16 && readUint32BE(buffer, PNG_SIGNATURE.length) === 13 && startsWithAscii(buffer, 12, "IHDR")); +} +function isAnimatedPng(buffer) { + let offset = PNG_SIGNATURE.length; + while (offset + 8 <= buffer.length) { + const chunkLength = readUint32BE(buffer, offset); + const chunkTypeOffset = offset + 4; + if (startsWithAscii(buffer, chunkTypeOffset, "acTL")) + return true; + if (startsWithAscii(buffer, chunkTypeOffset, "IDAT")) + return false; + const nextOffset = offset + 8 + chunkLength + 4; + if (nextOffset <= offset || nextOffset > buffer.length) + return false; + offset = nextOffset; + } + return false; +} +function isBmp(buffer) { + if (buffer.length < 26) + return false; + const declaredFileSize = readUint32LE(buffer, 2); + const pixelDataOffset = readUint32LE(buffer, 10); + const dibHeaderSize = readUint32LE(buffer, 14); + if (declaredFileSize !== 0 && declaredFileSize < 26) + return false; + if (pixelDataOffset < 14 + dibHeaderSize) + return false; + if (declaredFileSize !== 0 && pixelDataOffset >= declaredFileSize) + return false; + let colorPlanes; + let bitsPerPixel; + if (dibHeaderSize === 12) { + colorPlanes = readUint16LE(buffer, 22); + bitsPerPixel = readUint16LE(buffer, 24); + } + else if (dibHeaderSize >= 40 && dibHeaderSize <= 124) { + if (buffer.length < 30) + return false; + colorPlanes = readUint16LE(buffer, 26); + bitsPerPixel = readUint16LE(buffer, 28); + } + else { + return false; + } + return colorPlanes === 1 && [1, 4, 8, 16, 24, 32].includes(bitsPerPixel); +} +function readUint16LE(buffer, offset) { + return (buffer[offset] ?? 0) + ((buffer[offset + 1] ?? 0) << 8); +} +function readUint32BE(buffer, offset) { + return ((buffer[offset] ?? 0) * 0x1000000 + + ((buffer[offset + 1] ?? 0) << 16) + + ((buffer[offset + 2] ?? 0) << 8) + + (buffer[offset + 3] ?? 0)); +} +function readUint32LE(buffer, offset) { + return ((buffer[offset] ?? 0) + + ((buffer[offset + 1] ?? 0) << 8) + + ((buffer[offset + 2] ?? 0) << 16) + + (buffer[offset + 3] ?? 0) * 0x1000000); +} +function startsWith(buffer, bytes) { + if (buffer.length < bytes.length) + return false; + return bytes.every((byte, index) => buffer[index] === byte); +} +function startsWithAscii(buffer, offset, text) { + if (buffer.length < offset + text.length) + return false; + for (let index = 0; index < text.length; index++) { + if (buffer[offset + index] !== text.charCodeAt(index)) + return false; + } + return true; +} +//# sourceMappingURL=mime.js.map \ No newline at end of file diff --git a/dist/utils/mime.js.map b/dist/utils/mime.js.map new file mode 100644 index 0000000..9123472 --- /dev/null +++ b/dist/utils/mime.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mime.js","sourceRoot":"","sources":["../../src/utils/mime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAExC,MAAM,sBAAsB,GAAG,IAAI,CAAC;AACpC,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAEvE,MAAM,UAAU,4BAA4B,CAAC,MAAkB,EAAiB;IAC/E,IAAI,UAAU,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC;QAC5C,OAAO,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC;IACjD,CAAC;IACD,IAAI,UAAU,CAAC,MAAM,EAAE,aAAa,CAAC,EAAE,CAAC;QACvC,OAAO,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC;IACrE,CAAC;IACD,IAAI,eAAe,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC;QACvC,OAAO,WAAW,CAAC;IACpB,CAAC;IACD,IAAI,eAAe,CAAC,MAAM,EAAE,CAAC,EAAE,MAAM,CAAC,IAAI,eAAe,CAAC,MAAM,EAAE,CAAC,EAAE,MAAM,CAAC,EAAE,CAAC;QAC9E,OAAO,YAAY,CAAC;IACrB,CAAC;IACD,IAAI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AAC,CAAC,IAAI,EAAE,CAAC;QACjC,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,SAAS,CACrC,CAAC;AAAA,CACF;AAED,SAAS,UAAU,CAAC,MAAkB,EAAE,KAAe,EAAW;IACjE,IAAI,MAAM,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC/C,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,CAAC;AAAA,CAC5D;AAED,SAAS,eAAe,CAAC,MAAkB,EAAE,MAAc,EAAE,IAAY,EAAW;IACnF,IAAI,MAAM,CAAC,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACvD,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC;QAClD,IAAI,MAAM,CAAC,MAAM,GAAG,KAAK,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;YAAE,OAAO,KAAK,CAAC;IACrE,CAAC;IACD,OAAO,IAAI,CAAC;AAAA,CACZ","sourcesContent":["import { open } from \"node:fs/promises\";\n\nconst IMAGE_TYPE_SNIFF_BYTES = 4100;\nconst PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\n\nexport function detectSupportedImageMimeType(buffer: Uint8Array): string | null {\n\tif (startsWith(buffer, [0xff, 0xd8, 0xff])) {\n\t\treturn buffer[3] === 0xf7 ? null : \"image/jpeg\";\n\t}\n\tif (startsWith(buffer, PNG_SIGNATURE)) {\n\t\treturn isPng(buffer) && !isAnimatedPng(buffer) ? \"image/png\" : null;\n\t}\n\tif (startsWithAscii(buffer, 0, \"GIF\")) {\n\t\treturn \"image/gif\";\n\t}\n\tif (startsWithAscii(buffer, 0, \"RIFF\") && startsWithAscii(buffer, 8, \"WEBP\")) {\n\t\treturn \"image/webp\";\n\t}\n\tif (startsWithAscii(buffer, 0, \"BM\") && isBmp(buffer)) {\n\t\treturn \"image/bmp\";\n\t}\n\treturn null;\n}\n\nexport async function detectSupportedImageMimeTypeFromFile(filePath: string): Promise {\n\tconst fileHandle = await open(filePath, \"r\");\n\ttry {\n\t\tconst buffer = Buffer.alloc(IMAGE_TYPE_SNIFF_BYTES);\n\t\tconst { bytesRead } = await fileHandle.read(buffer, 0, IMAGE_TYPE_SNIFF_BYTES, 0);\n\t\treturn detectSupportedImageMimeType(buffer.subarray(0, bytesRead));\n\t} finally {\n\t\tawait fileHandle.close();\n\t}\n}\n\nfunction isPng(buffer: Uint8Array): boolean {\n\treturn (\n\t\tbuffer.length >= 16 && readUint32BE(buffer, PNG_SIGNATURE.length) === 13 && startsWithAscii(buffer, 12, \"IHDR\")\n\t);\n}\n\nfunction isAnimatedPng(buffer: Uint8Array): boolean {\n\tlet offset = PNG_SIGNATURE.length;\n\twhile (offset + 8 <= buffer.length) {\n\t\tconst chunkLength = readUint32BE(buffer, offset);\n\t\tconst chunkTypeOffset = offset + 4;\n\t\tif (startsWithAscii(buffer, chunkTypeOffset, \"acTL\")) return true;\n\t\tif (startsWithAscii(buffer, chunkTypeOffset, \"IDAT\")) return false;\n\n\t\tconst nextOffset = offset + 8 + chunkLength + 4;\n\t\tif (nextOffset <= offset || nextOffset > buffer.length) return false;\n\t\toffset = nextOffset;\n\t}\n\treturn false;\n}\n\nfunction isBmp(buffer: Uint8Array): boolean {\n\tif (buffer.length < 26) return false;\n\n\tconst declaredFileSize = readUint32LE(buffer, 2);\n\tconst pixelDataOffset = readUint32LE(buffer, 10);\n\tconst dibHeaderSize = readUint32LE(buffer, 14);\n\tif (declaredFileSize !== 0 && declaredFileSize < 26) return false;\n\tif (pixelDataOffset < 14 + dibHeaderSize) return false;\n\tif (declaredFileSize !== 0 && pixelDataOffset >= declaredFileSize) return false;\n\n\tlet colorPlanes: number;\n\tlet bitsPerPixel: number;\n\tif (dibHeaderSize === 12) {\n\t\tcolorPlanes = readUint16LE(buffer, 22);\n\t\tbitsPerPixel = readUint16LE(buffer, 24);\n\t} else if (dibHeaderSize >= 40 && dibHeaderSize <= 124) {\n\t\tif (buffer.length < 30) return false;\n\t\tcolorPlanes = readUint16LE(buffer, 26);\n\t\tbitsPerPixel = readUint16LE(buffer, 28);\n\t} else {\n\t\treturn false;\n\t}\n\n\treturn colorPlanes === 1 && [1, 4, 8, 16, 24, 32].includes(bitsPerPixel);\n}\n\nfunction readUint16LE(buffer: Uint8Array, offset: number): number {\n\treturn (buffer[offset] ?? 0) + ((buffer[offset + 1] ?? 0) << 8);\n}\n\nfunction readUint32BE(buffer: Uint8Array, offset: number): number {\n\treturn (\n\t\t(buffer[offset] ?? 0) * 0x1000000 +\n\t\t((buffer[offset + 1] ?? 0) << 16) +\n\t\t((buffer[offset + 2] ?? 0) << 8) +\n\t\t(buffer[offset + 3] ?? 0)\n\t);\n}\n\nfunction readUint32LE(buffer: Uint8Array, offset: number): number {\n\treturn (\n\t\t(buffer[offset] ?? 0) +\n\t\t((buffer[offset + 1] ?? 0) << 8) +\n\t\t((buffer[offset + 2] ?? 0) << 16) +\n\t\t(buffer[offset + 3] ?? 0) * 0x1000000\n\t);\n}\n\nfunction startsWith(buffer: Uint8Array, bytes: number[]): boolean {\n\tif (buffer.length < bytes.length) return false;\n\treturn bytes.every((byte, index) => buffer[index] === byte);\n}\n\nfunction startsWithAscii(buffer: Uint8Array, offset: number, text: string): boolean {\n\tif (buffer.length < offset + text.length) return false;\n\tfor (let index = 0; index < text.length; index++) {\n\t\tif (buffer[offset + index] !== text.charCodeAt(index)) return false;\n\t}\n\treturn true;\n}\n"]} \ No newline at end of file diff --git a/dist/utils/open-browser.d.ts b/dist/utils/open-browser.d.ts new file mode 100644 index 0000000..56aed9a --- /dev/null +++ b/dist/utils/open-browser.d.ts @@ -0,0 +1,9 @@ +/** + * Open a URL or file in the platform browser/default handler. + * + * This intentionally never invokes a shell. On Windows, do not use + * `cmd /c start`: cmd.exe re-parses metacharacters (&, |, ^, ...) before + * `start` runs, which would make attacker-controlled URLs injectable. + */ +export declare function openBrowser(target: string): void; +//# sourceMappingURL=open-browser.d.ts.map \ No newline at end of file diff --git a/dist/utils/open-browser.d.ts.map b/dist/utils/open-browser.d.ts.map new file mode 100644 index 0000000..a24373a --- /dev/null +++ b/dist/utils/open-browser.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"open-browser.d.ts","sourceRoot":"","sources":["../../src/utils/open-browser.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAchD","sourcesContent":["import { spawn } from \"node:child_process\";\n\n/**\n * Open a URL or file in the platform browser/default handler.\n *\n * This intentionally never invokes a shell. On Windows, do not use\n * `cmd /c start`: cmd.exe re-parses metacharacters (&, |, ^, ...) before\n * `start` runs, which would make attacker-controlled URLs injectable.\n */\nexport function openBrowser(target: string): void {\n\tconst [cmd, args]: [string, string[]] =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? [\"open\", [target]]\n\t\t\t: process.platform === \"win32\"\n\t\t\t\t? [\"rundll32\", [\"url.dll,FileProtocolHandler\", target]]\n\t\t\t\t: [\"xdg-open\", [target]];\n\n\t// spawn reports launcher failures (for example, missing xdg-open) via an\n\t// error event. Browser launch is best-effort: callers still present the target\n\t// to the user, so keep the launcher failure from becoming a process crash.\n\tspawn(cmd, args, { stdio: \"ignore\", detached: true })\n\t\t.on(\"error\", () => {})\n\t\t.unref();\n}\n"]} \ No newline at end of file diff --git a/dist/utils/open-browser.js b/dist/utils/open-browser.js new file mode 100644 index 0000000..f6fb21b --- /dev/null +++ b/dist/utils/open-browser.js @@ -0,0 +1,22 @@ +import { spawn } from "node:child_process"; +/** + * Open a URL or file in the platform browser/default handler. + * + * This intentionally never invokes a shell. On Windows, do not use + * `cmd /c start`: cmd.exe re-parses metacharacters (&, |, ^, ...) before + * `start` runs, which would make attacker-controlled URLs injectable. + */ +export function openBrowser(target) { + const [cmd, args] = process.platform === "darwin" + ? ["open", [target]] + : process.platform === "win32" + ? ["rundll32", ["url.dll,FileProtocolHandler", target]] + : ["xdg-open", [target]]; + // spawn reports launcher failures (for example, missing xdg-open) via an + // error event. Browser launch is best-effort: callers still present the target + // to the user, so keep the launcher failure from becoming a process crash. + spawn(cmd, args, { stdio: "ignore", detached: true }) + .on("error", () => { }) + .unref(); +} +//# sourceMappingURL=open-browser.js.map \ No newline at end of file diff --git a/dist/utils/open-browser.js.map b/dist/utils/open-browser.js.map new file mode 100644 index 0000000..cc1f2b7 --- /dev/null +++ b/dist/utils/open-browser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"open-browser.js","sourceRoot":"","sources":["../../src/utils/open-browser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAE3C;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,MAAc,EAAQ;IACjD,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,GAChB,OAAO,CAAC,QAAQ,KAAK,QAAQ;QAC5B,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,CAAC;QACpB,CAAC,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO;YAC7B,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,6BAA6B,EAAE,MAAM,CAAC,CAAC;YACvD,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAE5B,yEAAyE;IACzE,+EAA+E;IAC/E,2EAA2E;IAC3E,KAAK,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;SACnD,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,EAAC,CAAC,CAAC;SACrB,KAAK,EAAE,CAAC;AAAA,CACV","sourcesContent":["import { spawn } from \"node:child_process\";\n\n/**\n * Open a URL or file in the platform browser/default handler.\n *\n * This intentionally never invokes a shell. On Windows, do not use\n * `cmd /c start`: cmd.exe re-parses metacharacters (&, |, ^, ...) before\n * `start` runs, which would make attacker-controlled URLs injectable.\n */\nexport function openBrowser(target: string): void {\n\tconst [cmd, args]: [string, string[]] =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? [\"open\", [target]]\n\t\t\t: process.platform === \"win32\"\n\t\t\t\t? [\"rundll32\", [\"url.dll,FileProtocolHandler\", target]]\n\t\t\t\t: [\"xdg-open\", [target]];\n\n\t// spawn reports launcher failures (for example, missing xdg-open) via an\n\t// error event. Browser launch is best-effort: callers still present the target\n\t// to the user, so keep the launcher failure from becoming a process crash.\n\tspawn(cmd, args, { stdio: \"ignore\", detached: true })\n\t\t.on(\"error\", () => {})\n\t\t.unref();\n}\n"]} \ No newline at end of file diff --git a/dist/utils/paths.d.ts b/dist/utils/paths.d.ts new file mode 100644 index 0000000..eb25e71 --- /dev/null +++ b/dist/utils/paths.d.ts @@ -0,0 +1,31 @@ +export interface PathInputOptions { + /** Trim leading/trailing whitespace before normalization. */ + trim?: boolean; + /** Expand leading `~` to a home directory. Defaults to true. */ + expandTilde?: boolean; + /** Home directory used for `~` expansion. Defaults to `os.homedir()`. */ + homeDir?: string; + /** Strip a leading `@`, used for CLI @file paths. */ + stripAtPrefix?: boolean; + /** Normalize unicode space variants to regular spaces. */ + normalizeUnicodeSpaces?: boolean; +} +/** + * Resolve a path to its canonical (real) form, following symlinks. + * Falls back to the raw path if resolution fails (e.g. the target does + * not exist yet), so that callers never crash on missing filesystem + * entries. + */ +export declare function canonicalizePath(path: string): string; +/** + * Returns true if the value is NOT a package source (npm:, git:, etc.) + * or a remote URL protocol. Bare names, relative paths, and file: URLs + * are considered local. + */ +export declare function isLocalPath(value: string): boolean; +export declare function normalizePath(input: string, options?: PathInputOptions): string; +export declare function resolvePath(input: string, baseDir?: string, options?: PathInputOptions): string; +export declare function getCwdRelativePath(filePath: string, cwd: string): string | undefined; +export declare function formatPathRelativeToCwdOrAbsolute(filePath: string, cwd: string): string; +export declare function markPathIgnoredByCloudSync(path: string): void; +//# sourceMappingURL=paths.d.ts.map \ No newline at end of file diff --git a/dist/utils/paths.d.ts.map b/dist/utils/paths.d.ts.map new file mode 100644 index 0000000..09f60f5 --- /dev/null +++ b/dist/utils/paths.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"paths.d.ts","sourceRoot":"","sources":["../../src/utils/paths.ts"],"names":[],"mappings":"AAQA,MAAM,WAAW,gBAAgB;IAChC,6DAA6D;IAC7D,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,gEAAgE;IAChE,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,yEAAyE;IACzE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,qDAAqD;IACrD,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,0DAA0D;IAC1D,sBAAsB,CAAC,EAAE,OAAO,CAAC;CACjC;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMrD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAclD;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB,GAAG,MAAM,CAsBnF;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,MAAsB,EAAE,OAAO,GAAE,gBAAqB,GAAG,MAAM,CAIlH;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CASpF;AAED,wBAAgB,iCAAiC,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAGvF;AAED,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAe7D","sourcesContent":["import { realpathSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join, resolve as nodeResolvePath, relative, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { spawnProcessSync } from \"./child-process.ts\";\n\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g;\n\nexport interface PathInputOptions {\n\t/** Trim leading/trailing whitespace before normalization. */\n\ttrim?: boolean;\n\t/** Expand leading `~` to a home directory. Defaults to true. */\n\texpandTilde?: boolean;\n\t/** Home directory used for `~` expansion. Defaults to `os.homedir()`. */\n\thomeDir?: string;\n\t/** Strip a leading `@`, used for CLI @file paths. */\n\tstripAtPrefix?: boolean;\n\t/** Normalize unicode space variants to regular spaces. */\n\tnormalizeUnicodeSpaces?: boolean;\n}\n\n/**\n * Resolve a path to its canonical (real) form, following symlinks.\n * Falls back to the raw path if resolution fails (e.g. the target does\n * not exist yet), so that callers never crash on missing filesystem\n * entries.\n */\nexport function canonicalizePath(path: string): string {\n\ttry {\n\t\treturn realpathSync(path);\n\t} catch {\n\t\treturn path;\n\t}\n}\n\n/**\n * Returns true if the value is NOT a package source (npm:, git:, etc.)\n * or a remote URL protocol. Bare names, relative paths, and file: URLs\n * are considered local.\n */\nexport function isLocalPath(value: string): boolean {\n\tconst trimmed = value.trim();\n\t// Known non-local prefixes. file: URLs are local paths and are intentionally resolved by resolvePath().\n\tif (\n\t\ttrimmed.startsWith(\"npm:\") ||\n\t\ttrimmed.startsWith(\"git:\") ||\n\t\ttrimmed.startsWith(\"github:\") ||\n\t\ttrimmed.startsWith(\"http:\") ||\n\t\ttrimmed.startsWith(\"https:\") ||\n\t\ttrimmed.startsWith(\"ssh:\")\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport function normalizePath(input: string, options: PathInputOptions = {}): string {\n\tlet normalized = options.trim ? input.trim() : input;\n\tif (options.normalizeUnicodeSpaces) {\n\t\tnormalized = normalized.replace(UNICODE_SPACES, \" \");\n\t}\n\tif (options.stripAtPrefix && normalized.startsWith(\"@\")) {\n\t\tnormalized = normalized.slice(1);\n\t}\n\n\tif (options.expandTilde ?? true) {\n\t\tconst home = options.homeDir ?? homedir();\n\t\tif (normalized === \"~\") return home;\n\t\tif (normalized.startsWith(\"~/\") || (process.platform === \"win32\" && normalized.startsWith(\"~\\\\\"))) {\n\t\t\treturn join(home, normalized.slice(2));\n\t\t}\n\t}\n\n\tif (/^file:\\/\\//.test(normalized)) {\n\t\treturn fileURLToPath(normalized);\n\t}\n\n\treturn normalized;\n}\n\nexport function resolvePath(input: string, baseDir: string = process.cwd(), options: PathInputOptions = {}): string {\n\tconst normalized = normalizePath(input, options);\n\tconst normalizedBaseDir = normalizePath(baseDir);\n\treturn isAbsolute(normalized) ? nodeResolvePath(normalized) : nodeResolvePath(normalizedBaseDir, normalized);\n}\n\nexport function getCwdRelativePath(filePath: string, cwd: string): string | undefined {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedPath = resolvePath(filePath, resolvedCwd);\n\tconst relativePath = relative(resolvedCwd, resolvedPath);\n\tconst isInsideCwd =\n\t\trelativePath === \"\" ||\n\t\t(relativePath !== \"..\" && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath));\n\n\treturn isInsideCwd ? relativePath || \".\" : undefined;\n}\n\nexport function formatPathRelativeToCwdOrAbsolute(filePath: string, cwd: string): string {\n\tconst absolutePath = resolvePath(filePath, cwd);\n\treturn (getCwdRelativePath(absolutePath, cwd) ?? absolutePath).split(sep).join(\"/\");\n}\n\nexport function markPathIgnoredByCloudSync(path: string): void {\n\tconst attrs =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? [\"com.dropbox.ignored\", \"com.apple.fileprovider.ignore#P\"]\n\t\t\t: process.platform === \"linux\"\n\t\t\t\t? [\"user.com.dropbox.ignored\"]\n\t\t\t\t: [];\n\n\tfor (const attr of attrs) {\n\t\tif (process.platform === \"darwin\") {\n\t\t\tspawnProcessSync(\"xattr\", [\"-w\", attr, \"1\", path], { encoding: \"utf-8\", stdio: \"ignore\" });\n\t\t} else {\n\t\t\tspawnProcessSync(\"setfattr\", [\"-n\", attr, \"-v\", \"1\", path], { encoding: \"utf-8\", stdio: \"ignore\" });\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/paths.js b/dist/utils/paths.js new file mode 100644 index 0000000..dfb0dab --- /dev/null +++ b/dist/utils/paths.js @@ -0,0 +1,92 @@ +import { realpathSync } from "node:fs"; +import { homedir } from "node:os"; +import { isAbsolute, join, resolve as nodeResolvePath, relative, sep } from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawnProcessSync } from "./child-process.js"; +const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g; +/** + * Resolve a path to its canonical (real) form, following symlinks. + * Falls back to the raw path if resolution fails (e.g. the target does + * not exist yet), so that callers never crash on missing filesystem + * entries. + */ +export function canonicalizePath(path) { + try { + return realpathSync(path); + } + catch { + return path; + } +} +/** + * Returns true if the value is NOT a package source (npm:, git:, etc.) + * or a remote URL protocol. Bare names, relative paths, and file: URLs + * are considered local. + */ +export function isLocalPath(value) { + const trimmed = value.trim(); + // Known non-local prefixes. file: URLs are local paths and are intentionally resolved by resolvePath(). + if (trimmed.startsWith("npm:") || + trimmed.startsWith("git:") || + trimmed.startsWith("github:") || + trimmed.startsWith("http:") || + trimmed.startsWith("https:") || + trimmed.startsWith("ssh:")) { + return false; + } + return true; +} +export function normalizePath(input, options = {}) { + let normalized = options.trim ? input.trim() : input; + if (options.normalizeUnicodeSpaces) { + normalized = normalized.replace(UNICODE_SPACES, " "); + } + if (options.stripAtPrefix && normalized.startsWith("@")) { + normalized = normalized.slice(1); + } + if (options.expandTilde ?? true) { + const home = options.homeDir ?? homedir(); + if (normalized === "~") + return home; + if (normalized.startsWith("~/") || (process.platform === "win32" && normalized.startsWith("~\\"))) { + return join(home, normalized.slice(2)); + } + } + if (/^file:\/\//.test(normalized)) { + return fileURLToPath(normalized); + } + return normalized; +} +export function resolvePath(input, baseDir = process.cwd(), options = {}) { + const normalized = normalizePath(input, options); + const normalizedBaseDir = normalizePath(baseDir); + return isAbsolute(normalized) ? nodeResolvePath(normalized) : nodeResolvePath(normalizedBaseDir, normalized); +} +export function getCwdRelativePath(filePath, cwd) { + const resolvedCwd = resolvePath(cwd); + const resolvedPath = resolvePath(filePath, resolvedCwd); + const relativePath = relative(resolvedCwd, resolvedPath); + const isInsideCwd = relativePath === "" || + (relativePath !== ".." && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath)); + return isInsideCwd ? relativePath || "." : undefined; +} +export function formatPathRelativeToCwdOrAbsolute(filePath, cwd) { + const absolutePath = resolvePath(filePath, cwd); + return (getCwdRelativePath(absolutePath, cwd) ?? absolutePath).split(sep).join("/"); +} +export function markPathIgnoredByCloudSync(path) { + const attrs = process.platform === "darwin" + ? ["com.dropbox.ignored", "com.apple.fileprovider.ignore#P"] + : process.platform === "linux" + ? ["user.com.dropbox.ignored"] + : []; + for (const attr of attrs) { + if (process.platform === "darwin") { + spawnProcessSync("xattr", ["-w", attr, "1", path], { encoding: "utf-8", stdio: "ignore" }); + } + else { + spawnProcessSync("setfattr", ["-n", attr, "-v", "1", path], { encoding: "utf-8", stdio: "ignore" }); + } + } +} +//# sourceMappingURL=paths.js.map \ No newline at end of file diff --git a/dist/utils/paths.js.map b/dist/utils/paths.js.map new file mode 100644 index 0000000..4dea95e --- /dev/null +++ b/dist/utils/paths.js.map @@ -0,0 +1 @@ +{"version":3,"file":"paths.js","sourceRoot":"","sources":["../../src/utils/paths.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,IAAI,eAAe,EAAE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AAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;QACrG,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import { realpathSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join, resolve as nodeResolvePath, relative, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { spawnProcessSync } from \"./child-process.ts\";\n\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g;\n\nexport interface PathInputOptions {\n\t/** Trim leading/trailing whitespace before normalization. */\n\ttrim?: boolean;\n\t/** Expand leading `~` to a home directory. Defaults to true. */\n\texpandTilde?: boolean;\n\t/** Home directory used for `~` expansion. Defaults to `os.homedir()`. */\n\thomeDir?: string;\n\t/** Strip a leading `@`, used for CLI @file paths. */\n\tstripAtPrefix?: boolean;\n\t/** Normalize unicode space variants to regular spaces. */\n\tnormalizeUnicodeSpaces?: boolean;\n}\n\n/**\n * Resolve a path to its canonical (real) form, following symlinks.\n * Falls back to the raw path if resolution fails (e.g. the target does\n * not exist yet), so that callers never crash on missing filesystem\n * entries.\n */\nexport function canonicalizePath(path: string): string {\n\ttry {\n\t\treturn realpathSync(path);\n\t} catch {\n\t\treturn path;\n\t}\n}\n\n/**\n * Returns true if the value is NOT a package source (npm:, git:, etc.)\n * or a remote URL protocol. Bare names, relative paths, and file: URLs\n * are considered local.\n */\nexport function isLocalPath(value: string): boolean {\n\tconst trimmed = value.trim();\n\t// Known non-local prefixes. file: URLs are local paths and are intentionally resolved by resolvePath().\n\tif (\n\t\ttrimmed.startsWith(\"npm:\") ||\n\t\ttrimmed.startsWith(\"git:\") ||\n\t\ttrimmed.startsWith(\"github:\") ||\n\t\ttrimmed.startsWith(\"http:\") ||\n\t\ttrimmed.startsWith(\"https:\") ||\n\t\ttrimmed.startsWith(\"ssh:\")\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport function normalizePath(input: string, options: PathInputOptions = {}): string {\n\tlet normalized = options.trim ? input.trim() : input;\n\tif (options.normalizeUnicodeSpaces) {\n\t\tnormalized = normalized.replace(UNICODE_SPACES, \" \");\n\t}\n\tif (options.stripAtPrefix && normalized.startsWith(\"@\")) {\n\t\tnormalized = normalized.slice(1);\n\t}\n\n\tif (options.expandTilde ?? true) {\n\t\tconst home = options.homeDir ?? homedir();\n\t\tif (normalized === \"~\") return home;\n\t\tif (normalized.startsWith(\"~/\") || (process.platform === \"win32\" && normalized.startsWith(\"~\\\\\"))) {\n\t\t\treturn join(home, normalized.slice(2));\n\t\t}\n\t}\n\n\tif (/^file:\\/\\//.test(normalized)) {\n\t\treturn fileURLToPath(normalized);\n\t}\n\n\treturn normalized;\n}\n\nexport function resolvePath(input: string, baseDir: string = process.cwd(), options: PathInputOptions = {}): string {\n\tconst normalized = normalizePath(input, options);\n\tconst normalizedBaseDir = normalizePath(baseDir);\n\treturn isAbsolute(normalized) ? nodeResolvePath(normalized) : nodeResolvePath(normalizedBaseDir, normalized);\n}\n\nexport function getCwdRelativePath(filePath: string, cwd: string): string | undefined {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedPath = resolvePath(filePath, resolvedCwd);\n\tconst relativePath = relative(resolvedCwd, resolvedPath);\n\tconst isInsideCwd =\n\t\trelativePath === \"\" ||\n\t\t(relativePath !== \"..\" && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath));\n\n\treturn isInsideCwd ? relativePath || \".\" : undefined;\n}\n\nexport function formatPathRelativeToCwdOrAbsolute(filePath: string, cwd: string): string {\n\tconst absolutePath = resolvePath(filePath, cwd);\n\treturn (getCwdRelativePath(absolutePath, cwd) ?? absolutePath).split(sep).join(\"/\");\n}\n\nexport function markPathIgnoredByCloudSync(path: string): void {\n\tconst attrs =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? [\"com.dropbox.ignored\", \"com.apple.fileprovider.ignore#P\"]\n\t\t\t: process.platform === \"linux\"\n\t\t\t\t? [\"user.com.dropbox.ignored\"]\n\t\t\t\t: [];\n\n\tfor (const attr of attrs) {\n\t\tif (process.platform === \"darwin\") {\n\t\t\tspawnProcessSync(\"xattr\", [\"-w\", attr, \"1\", path], { encoding: \"utf-8\", stdio: \"ignore\" });\n\t\t} else {\n\t\t\tspawnProcessSync(\"setfattr\", [\"-n\", attr, \"-v\", \"1\", path], { encoding: \"utf-8\", stdio: \"ignore\" });\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/photon.d.ts b/dist/utils/photon.d.ts new file mode 100644 index 0000000..ad394d7 --- /dev/null +++ b/dist/utils/photon.d.ts @@ -0,0 +1,21 @@ +/** + * Photon image processing wrapper. + * + * This module provides a unified interface to @silvia-odwyer/photon-node that works in: + * 1. Node.js (development, npm run build) + * 2. Bun compiled binaries (standalone distribution) + * + * The challenge: photon-node's CJS entry uses fs.readFileSync(__dirname + '/photon_rs_bg.wasm') + * which bakes the build machine's absolute path into Bun compiled binaries. + * + * Solution: + * 1. Patch fs.readFileSync to redirect missing photon_rs_bg.wasm reads + * 2. Copy photon_rs_bg.wasm next to the executable in build:binary + */ +export type { PhotonImage as PhotonImageType } from "@silvia-odwyer/photon-node"; +/** + * Load the photon module asynchronously. + * Returns cached module on subsequent calls. + */ +export declare function loadPhoton(): Promise; +//# sourceMappingURL=photon.d.ts.map \ No newline at end of file diff --git a/dist/utils/photon.d.ts.map b/dist/utils/photon.d.ts.map new file mode 100644 index 0000000..bdbf1bf --- /dev/null +++ b/dist/utils/photon.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"photon.d.ts","sourceRoot":"","sources":["../../src/utils/photon.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAWH,YAAY,EAAE,WAAW,IAAI,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAuFjF;;;GAGG;AACH,wBAAsB,UAAU,IAAI,OAAO,CAAC,cAAc,4BAA4B,CAAC,GAAG,IAAI,CAAC,CAuB9F","sourcesContent":["/**\n * Photon image processing wrapper.\n *\n * This module provides a unified interface to @silvia-odwyer/photon-node that works in:\n * 1. Node.js (development, npm run build)\n * 2. Bun compiled binaries (standalone distribution)\n *\n * The challenge: photon-node's CJS entry uses fs.readFileSync(__dirname + '/photon_rs_bg.wasm')\n * which bakes the build machine's absolute path into Bun compiled binaries.\n *\n * Solution:\n * 1. Patch fs.readFileSync to redirect missing photon_rs_bg.wasm reads\n * 2. Copy photon_rs_bg.wasm next to the executable in build:binary\n */\n\nimport type { PathOrFileDescriptor } from \"fs\";\nimport { createRequire } from \"module\";\nimport * as path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nconst require = createRequire(import.meta.url);\nconst fs = require(\"fs\") as typeof import(\"fs\");\n\n// Re-export types from the main package\nexport type { PhotonImage as PhotonImageType } from \"@silvia-odwyer/photon-node\";\n\ntype ReadFileSync = typeof fs.readFileSync;\n\nconst WASM_FILENAME = \"photon_rs_bg.wasm\";\n\n// Lazy-loaded photon module\nlet photonModule: typeof import(\"@silvia-odwyer/photon-node\") | null = null;\nlet loadPromise: Promise | null = null;\n\nfunction pathOrNull(file: PathOrFileDescriptor): string | null {\n\tif (typeof file === \"string\") {\n\t\treturn file;\n\t}\n\tif (file instanceof URL) {\n\t\treturn fileURLToPath(file);\n\t}\n\treturn null;\n}\n\nfunction getFallbackWasmPaths(): string[] {\n\tconst execDir = path.dirname(process.execPath);\n\treturn [\n\t\tpath.join(execDir, WASM_FILENAME),\n\t\tpath.join(execDir, \"photon\", WASM_FILENAME),\n\t\tpath.join(process.cwd(), WASM_FILENAME),\n\t];\n}\n\nfunction patchPhotonWasmRead(): () => void {\n\tconst originalReadFileSync: ReadFileSync = fs.readFileSync.bind(fs);\n\tconst fallbackPaths = getFallbackWasmPaths();\n\tconst mutableFs = fs as { readFileSync: ReadFileSync };\n\n\tconst patchedReadFileSync: ReadFileSync = ((...args: Parameters) => {\n\t\tconst [file, options] = args;\n\t\tconst resolvedPath = pathOrNull(file);\n\n\t\tif (resolvedPath?.endsWith(WASM_FILENAME)) {\n\t\t\ttry {\n\t\t\t\treturn originalReadFileSync(...args);\n\t\t\t} catch (error) {\n\t\t\t\tconst err = error as NodeJS.ErrnoException;\n\t\t\t\tif (err?.code && err.code !== \"ENOENT\") {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\n\t\t\t\tfor (const fallbackPath of fallbackPaths) {\n\t\t\t\t\tif (!fs.existsSync(fallbackPath)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (options === undefined) {\n\t\t\t\t\t\treturn originalReadFileSync(fallbackPath);\n\t\t\t\t\t}\n\t\t\t\t\treturn originalReadFileSync(fallbackPath, options);\n\t\t\t\t}\n\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\treturn originalReadFileSync(...args);\n\t}) as ReadFileSync;\n\n\ttry {\n\t\tmutableFs.readFileSync = patchedReadFileSync;\n\t} catch {\n\t\tObject.defineProperty(fs, \"readFileSync\", {\n\t\t\tvalue: patchedReadFileSync,\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\n\treturn () => {\n\t\ttry {\n\t\t\tmutableFs.readFileSync = originalReadFileSync;\n\t\t} catch {\n\t\t\tObject.defineProperty(fs, \"readFileSync\", {\n\t\t\t\tvalue: originalReadFileSync,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\t}\n\t};\n}\n\n/**\n * Load the photon module asynchronously.\n * Returns cached module on subsequent calls.\n */\nexport async function loadPhoton(): Promise {\n\tif (photonModule) {\n\t\treturn photonModule;\n\t}\n\n\tif (loadPromise) {\n\t\treturn loadPromise;\n\t}\n\n\tloadPromise = (async () => {\n\t\tconst restoreReadFileSync = patchPhotonWasmRead();\n\t\ttry {\n\t\t\tphotonModule = await import(\"@silvia-odwyer/photon-node\");\n\t\t\treturn photonModule;\n\t\t} catch {\n\t\t\tphotonModule = null;\n\t\t\treturn photonModule;\n\t\t} finally {\n\t\t\trestoreReadFileSync();\n\t\t}\n\t})();\n\n\treturn loadPromise;\n}\n"]} \ No newline at end of file diff --git a/dist/utils/photon.js b/dist/utils/photon.js new file mode 100644 index 0000000..3078895 --- /dev/null +++ b/dist/utils/photon.js @@ -0,0 +1,121 @@ +/** + * Photon image processing wrapper. + * + * This module provides a unified interface to @silvia-odwyer/photon-node that works in: + * 1. Node.js (development, npm run build) + * 2. Bun compiled binaries (standalone distribution) + * + * The challenge: photon-node's CJS entry uses fs.readFileSync(__dirname + '/photon_rs_bg.wasm') + * which bakes the build machine's absolute path into Bun compiled binaries. + * + * Solution: + * 1. Patch fs.readFileSync to redirect missing photon_rs_bg.wasm reads + * 2. Copy photon_rs_bg.wasm next to the executable in build:binary + */ +import { createRequire } from "module"; +import * as path from "path"; +import { fileURLToPath } from "url"; +const require = createRequire(import.meta.url); +const fs = require("fs"); +const WASM_FILENAME = "photon_rs_bg.wasm"; +// Lazy-loaded photon module +let photonModule = null; +let loadPromise = null; +function pathOrNull(file) { + if (typeof file === "string") { + return file; + } + if (file instanceof URL) { + return fileURLToPath(file); + } + return null; +} +function getFallbackWasmPaths() { + const execDir = path.dirname(process.execPath); + return [ + path.join(execDir, WASM_FILENAME), + path.join(execDir, "photon", WASM_FILENAME), + path.join(process.cwd(), WASM_FILENAME), + ]; +} +function patchPhotonWasmRead() { + const originalReadFileSync = fs.readFileSync.bind(fs); + const fallbackPaths = getFallbackWasmPaths(); + const mutableFs = fs; + const patchedReadFileSync = ((...args) => { + const [file, options] = args; + const resolvedPath = pathOrNull(file); + if (resolvedPath?.endsWith(WASM_FILENAME)) { + try { + return originalReadFileSync(...args); + } + catch (error) { + const err = error; + if (err?.code && err.code !== "ENOENT") { + throw error; + } + for (const fallbackPath of fallbackPaths) { + if (!fs.existsSync(fallbackPath)) { + continue; + } + if (options === undefined) { + return originalReadFileSync(fallbackPath); + } + return originalReadFileSync(fallbackPath, options); + } + throw error; + } + } + return originalReadFileSync(...args); + }); + try { + mutableFs.readFileSync = patchedReadFileSync; + } + catch { + Object.defineProperty(fs, "readFileSync", { + value: patchedReadFileSync, + writable: true, + configurable: true, + }); + } + return () => { + try { + mutableFs.readFileSync = originalReadFileSync; + } + catch { + Object.defineProperty(fs, "readFileSync", { + value: originalReadFileSync, + writable: true, + configurable: true, + }); + } + }; +} +/** + * Load the photon module asynchronously. + * Returns cached module on subsequent calls. + */ +export async function loadPhoton() { + if (photonModule) { + return photonModule; + } + if (loadPromise) { + return loadPromise; + } + loadPromise = (async () => { + const restoreReadFileSync = patchPhotonWasmRead(); + try { + photonModule = await import("@silvia-odwyer/photon-node"); + return photonModule; + } + catch { + photonModule = null; + return photonModule; + } + finally { + restoreReadFileSync(); + } + })(); + return loadPromise; +} +//# sourceMappingURL=photon.js.map \ No newline at end of file diff --git a/dist/utils/photon.js.map b/dist/utils/photon.js.map new file mode 100644 index 0000000..0c5fd2c --- /dev/null +++ b/dist/utils/photon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"photon.js","sourceRoot":"","sources":["../../src/utils/photon.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAEpC,MAAM,OAAO,GAAG,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AAC/C,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAwB,CAAC;AAOhD,MAAM,aAAa,GAAG,mBAAmB,CAAC;AAE1C,4BAA4B;AAC5B,IAAI,YAAY,GAAuD,IAAI,CAAC;AAC5E,IAAI,WAAW,GAAuE,IAAI,CAAC;AAE3F,SAAS,UAAU,CAAC,IAA0B,EAAiB;IAC9D,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CA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AM,mBAAmB,GAAG,mBAAmB,EAAE,CAAC;QAClD,IAAI,CAAC;YACJ,YAAY,GAAG,MAAM,MAAM,CAAC,4BAA4B,CAAC,CAAC;YAC1D,OAAO,YAAY,CAAC;QACrB,CAAC;QAAC,MAAM,CAAC;YACR,YAAY,GAAG,IAAI,CAAC;YACpB,OAAO,YAAY,CAAC;QACrB,CAAC;gBAAS,CAAC;YACV,mBAAmB,EAAE,CAAC;QACvB,CAAC;IAAA,CACD,CAAC,EAAE,CAAC;IAEL,OAAO,WAAW,CAAC;AAAA,CACnB","sourcesContent":["/**\n * Photon image processing wrapper.\n *\n * This module provides a unified interface to @silvia-odwyer/photon-node that works in:\n * 1. Node.js (development, npm run build)\n * 2. Bun compiled binaries (standalone distribution)\n *\n * The challenge: photon-node's CJS entry uses fs.readFileSync(__dirname + '/photon_rs_bg.wasm')\n * which bakes the build machine's absolute path into Bun compiled binaries.\n *\n * Solution:\n * 1. Patch fs.readFileSync to redirect missing photon_rs_bg.wasm reads\n * 2. Copy photon_rs_bg.wasm next to the executable in build:binary\n */\n\nimport type { PathOrFileDescriptor } from \"fs\";\nimport { createRequire } from \"module\";\nimport * as path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nconst require = createRequire(import.meta.url);\nconst fs = require(\"fs\") as typeof import(\"fs\");\n\n// Re-export types from the main package\nexport type { PhotonImage as PhotonImageType } from \"@silvia-odwyer/photon-node\";\n\ntype ReadFileSync = typeof fs.readFileSync;\n\nconst WASM_FILENAME = \"photon_rs_bg.wasm\";\n\n// Lazy-loaded photon module\nlet photonModule: typeof import(\"@silvia-odwyer/photon-node\") | null = null;\nlet loadPromise: Promise | null = null;\n\nfunction pathOrNull(file: PathOrFileDescriptor): string | null {\n\tif (typeof file === \"string\") {\n\t\treturn file;\n\t}\n\tif (file instanceof URL) {\n\t\treturn fileURLToPath(file);\n\t}\n\treturn null;\n}\n\nfunction getFallbackWasmPaths(): string[] {\n\tconst execDir = path.dirname(process.execPath);\n\treturn [\n\t\tpath.join(execDir, WASM_FILENAME),\n\t\tpath.join(execDir, \"photon\", WASM_FILENAME),\n\t\tpath.join(process.cwd(), WASM_FILENAME),\n\t];\n}\n\nfunction patchPhotonWasmRead(): () => void {\n\tconst originalReadFileSync: ReadFileSync = fs.readFileSync.bind(fs);\n\tconst fallbackPaths = getFallbackWasmPaths();\n\tconst mutableFs = fs as { readFileSync: ReadFileSync };\n\n\tconst patchedReadFileSync: ReadFileSync = ((...args: Parameters) => {\n\t\tconst [file, options] = args;\n\t\tconst resolvedPath = pathOrNull(file);\n\n\t\tif (resolvedPath?.endsWith(WASM_FILENAME)) {\n\t\t\ttry {\n\t\t\t\treturn originalReadFileSync(...args);\n\t\t\t} catch (error) {\n\t\t\t\tconst err = error as NodeJS.ErrnoException;\n\t\t\t\tif (err?.code && err.code !== \"ENOENT\") {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\n\t\t\t\tfor (const fallbackPath of fallbackPaths) {\n\t\t\t\t\tif (!fs.existsSync(fallbackPath)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (options === undefined) {\n\t\t\t\t\t\treturn originalReadFileSync(fallbackPath);\n\t\t\t\t\t}\n\t\t\t\t\treturn originalReadFileSync(fallbackPath, options);\n\t\t\t\t}\n\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\treturn originalReadFileSync(...args);\n\t}) as ReadFileSync;\n\n\ttry {\n\t\tmutableFs.readFileSync = patchedReadFileSync;\n\t} catch {\n\t\tObject.defineProperty(fs, \"readFileSync\", {\n\t\t\tvalue: patchedReadFileSync,\n\t\t\twritable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\n\treturn () => {\n\t\ttry {\n\t\t\tmutableFs.readFileSync = originalReadFileSync;\n\t\t} catch {\n\t\t\tObject.defineProperty(fs, \"readFileSync\", {\n\t\t\t\tvalue: originalReadFileSync,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\t}\n\t};\n}\n\n/**\n * Load the photon module asynchronously.\n * Returns cached module on subsequent calls.\n */\nexport async function loadPhoton(): Promise {\n\tif (photonModule) {\n\t\treturn photonModule;\n\t}\n\n\tif (loadPromise) {\n\t\treturn loadPromise;\n\t}\n\n\tloadPromise = (async () => {\n\t\tconst restoreReadFileSync = patchPhotonWasmRead();\n\t\ttry {\n\t\t\tphotonModule = await import(\"@silvia-odwyer/photon-node\");\n\t\t\treturn photonModule;\n\t\t} catch {\n\t\t\tphotonModule = null;\n\t\t\treturn photonModule;\n\t\t} finally {\n\t\t\trestoreReadFileSync();\n\t\t}\n\t})();\n\n\treturn loadPromise;\n}\n"]} \ No newline at end of file diff --git a/dist/utils/pi-user-agent.d.ts b/dist/utils/pi-user-agent.d.ts new file mode 100644 index 0000000..3540d8a --- /dev/null +++ b/dist/utils/pi-user-agent.d.ts @@ -0,0 +1,2 @@ +export declare function getPiUserAgent(version: string): string; +//# sourceMappingURL=pi-user-agent.d.ts.map \ No newline at end of file diff --git a/dist/utils/pi-user-agent.d.ts.map b/dist/utils/pi-user-agent.d.ts.map new file mode 100644 index 0000000..c80be09 --- /dev/null +++ b/dist/utils/pi-user-agent.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pi-user-agent.d.ts","sourceRoot":"","sources":["../../src/utils/pi-user-agent.ts"],"names":[],"mappings":"AAAA,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAGtD","sourcesContent":["export function getPiUserAgent(version: string): string {\n\tconst runtime = process.versions.bun ? `bun/${process.versions.bun}` : `node/${process.version}`;\n\treturn `pi/${version} (${process.platform}; ${runtime}; ${process.arch})`;\n}\n"]} \ No newline at end of file diff --git a/dist/utils/pi-user-agent.js b/dist/utils/pi-user-agent.js new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/dist/utils/pi-user-agent.js @@ -0,0 +1,5 @@ +export function getPiUserAgent(version) { + const runtime = process.versions.bun ? `bun/${process.versions.bun}` : `node/${process.version}`; + return `pi/${version} (${process.platform}; ${runtime}; ${process.arch})`; +} +//# sourceMappingURL=pi-user-agent.js.map \ No newline at end of file diff --git a/dist/utils/pi-user-agent.js.map b/dist/utils/pi-user-agent.js.map new file mode 100644 index 0000000..d9615c6 --- /dev/null +++ b/dist/utils/pi-user-agent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pi-user-agent.js","sourceRoot":"","sources":["../../src/utils/pi-user-agent.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,cAAc,CAAC,OAAe,EAAU;IACvD,MAAM,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,OAAO,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,QAAQ,OAAO,CAAC,OAAO,EAAE,CAAC;IACjG,OAAO,MAAM,OAAO,KAAK,OAAO,CAAC,QAAQ,KAAK,OAAO,KAAK,OAAO,CAAC,IAAI,GAAG,CAAC;AAAA,CAC1E","sourcesContent":["export function getPiUserAgent(version: string): string {\n\tconst runtime = process.versions.bun ? `bun/${process.versions.bun}` : `node/${process.version}`;\n\treturn `pi/${version} (${process.platform}; ${runtime}; ${process.arch})`;\n}\n"]} \ No newline at end of file diff --git a/dist/utils/shell.d.ts b/dist/utils/shell.d.ts new file mode 100644 index 0000000..7034bed --- /dev/null +++ b/dist/utils/shell.d.ts @@ -0,0 +1,31 @@ +export interface ShellConfig { + shell: string; + args: string[]; + commandTransport?: "argv" | "stdin"; +} +/** + * Resolve shell configuration based on platform and an optional explicit shell path. + * Resolution order: + * 1. User-specified shellPath + * 2. On Windows: Git Bash in known locations, then bash on PATH + * 3. On Unix: /bin/bash, then bash on PATH, then fallback to sh + */ +export declare function getShellConfig(customShellPath?: string): ShellConfig; +export declare function getShellEnv(): NodeJS.ProcessEnv; +/** + * Sanitize binary output for display/storage. + * Removes characters that crash string-width or cause display issues: + * - Control characters (except tab, newline, carriage return) + * - Lone surrogates + * - Unicode Format characters (crash string-width due to a bug) + * - Characters with undefined code points + */ +export declare function sanitizeBinaryOutput(str: string): string; +export declare function trackDetachedChildPid(pid: number): void; +export declare function untrackDetachedChildPid(pid: number): void; +export declare function killTrackedDetachedChildren(): void; +/** + * Kill a process and all its children (cross-platform) + */ +export declare function killProcessTree(pid: number): void; +//# sourceMappingURL=shell.d.ts.map \ No newline at end of file diff --git a/dist/utils/shell.d.ts.map b/dist/utils/shell.d.ts.map new file mode 100644 index 0000000..d4c1e44 --- /dev/null +++ b/dist/utils/shell.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../../src/utils/shell.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,WAAW;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,gBAAgB,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;CACpC;AAkDD;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,eAAe,CAAC,EAAE,MAAM,GAAG,WAAW,CAqDpE;AAED,wBAAgB,WAAW,IAAI,MAAM,CAAC,UAAU,CAY/C;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CA8BxD;AAQD,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEvD;AAED,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEzD;AAED,wBAAgB,2BAA2B,IAAI,IAAI,CAKlD;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAyBjD","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { delimiter } from \"node:path\";\nimport { spawn, spawnSync } from \"child_process\";\nimport { getBinDir } from \"../config.ts\";\n\nexport interface ShellConfig {\n\tshell: string;\n\targs: string[];\n\tcommandTransport?: \"argv\" | \"stdin\";\n}\n\n/**\n * Find bash executable on PATH (cross-platform)\n */\nfunction isLegacyWslBashPath(path: string): boolean {\n\tconst normalized = path.replace(/\\//g, \"\\\\\").toLowerCase();\n\treturn /^[a-z]:\\\\windows\\\\(?:system32|sysnative)\\\\bash\\.exe$/.test(normalized);\n}\n\nfunction getBashShellConfig(shell: string): ShellConfig {\n\treturn isLegacyWslBashPath(shell) ? { shell, args: [\"-s\"], commandTransport: \"stdin\" } : { shell, args: [\"-c\"] };\n}\n\nfunction findBashOnPath(): string | null {\n\tif (process.platform === \"win32\") {\n\t\t// Windows: Use 'where' and verify file exists (where can return non-existent paths)\n\t\ttry {\n\t\t\tconst result = spawnSync(\"where\", [\"bash.exe\"], {\n\t\t\t\tencoding: \"utf-8\",\n\t\t\t\ttimeout: 5000,\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (result.status === 0 && result.stdout) {\n\t\t\t\tconst firstMatch = result.stdout.trim().split(/\\r?\\n/)[0];\n\t\t\t\tif (firstMatch && existsSync(firstMatch)) {\n\t\t\t\t\treturn firstMatch;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore errors\n\t\t}\n\t\treturn null;\n\t}\n\n\t// Unix: Use 'which' and trust its output (handles Termux and special filesystems)\n\ttry {\n\t\tconst result = spawnSync(\"which\", [\"bash\"], { encoding: \"utf-8\", timeout: 5000 });\n\t\tif (result.status === 0 && result.stdout) {\n\t\t\tconst firstMatch = result.stdout.trim().split(/\\r?\\n/)[0];\n\t\t\tif (firstMatch) {\n\t\t\t\treturn firstMatch;\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\treturn null;\n}\n\n/**\n * Resolve shell configuration based on platform and an optional explicit shell path.\n * Resolution order:\n * 1. User-specified shellPath\n * 2. On Windows: Git Bash in known locations, then bash on PATH\n * 3. On Unix: /bin/bash, then bash on PATH, then fallback to sh\n */\nexport function getShellConfig(customShellPath?: string): ShellConfig {\n\t// 1. Check user-specified shell path\n\tif (customShellPath) {\n\t\tif (existsSync(customShellPath)) {\n\t\t\treturn getBashShellConfig(customShellPath);\n\t\t}\n\t\tthrow new Error(`Custom shell path not found: ${customShellPath}`);\n\t}\n\n\tif (process.platform === \"win32\") {\n\t\t// 2. Try Git Bash in known locations\n\t\tconst paths: string[] = [];\n\t\tconst programFiles = process.env.ProgramFiles;\n\t\tif (programFiles) {\n\t\t\tpaths.push(`${programFiles}\\\\Git\\\\bin\\\\bash.exe`);\n\t\t}\n\t\tconst programFilesX86 = process.env[\"ProgramFiles(x86)\"];\n\t\tif (programFilesX86) {\n\t\t\tpaths.push(`${programFilesX86}\\\\Git\\\\bin\\\\bash.exe`);\n\t\t}\n\n\t\tfor (const path of paths) {\n\t\t\tif (existsSync(path)) {\n\t\t\t\treturn getBashShellConfig(path);\n\t\t\t}\n\t\t}\n\n\t\t// 3. Fallback: search bash.exe on PATH (Cygwin, MSYS2, WSL, etc.)\n\t\tconst bashOnPath = findBashOnPath();\n\t\tif (bashOnPath) {\n\t\t\treturn getBashShellConfig(bashOnPath);\n\t\t}\n\n\t\tthrow new Error(\n\t\t\t`No bash shell found. Options:\\n` +\n\t\t\t\t` 1. Install Git for Windows: https://git-scm.com/download/win\\n` +\n\t\t\t\t` 2. Add your bash to PATH (Cygwin, MSYS2, etc.)\\n` +\n\t\t\t\t\" 3. Set shellPath in settings.json\\n\\n\" +\n\t\t\t\t`Searched Git Bash in:\\n${paths.map((p) => ` ${p}`).join(\"\\n\")}`,\n\t\t);\n\t}\n\n\t// Unix: try /bin/bash, then bash on PATH, then fallback to sh\n\tif (existsSync(\"/bin/bash\")) {\n\t\treturn getBashShellConfig(\"/bin/bash\");\n\t}\n\n\tconst bashOnPath = findBashOnPath();\n\tif (bashOnPath) {\n\t\treturn getBashShellConfig(bashOnPath);\n\t}\n\n\treturn { shell: \"sh\", args: [\"-c\"] };\n}\n\nexport function getShellEnv(): NodeJS.ProcessEnv {\n\tconst binDir = getBinDir();\n\tconst pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === \"path\") ?? \"PATH\";\n\tconst currentPath = process.env[pathKey] ?? \"\";\n\tconst pathEntries = currentPath.split(delimiter).filter(Boolean);\n\tconst hasBinDir = pathEntries.includes(binDir);\n\tconst updatedPath = hasBinDir ? currentPath : [binDir, currentPath].filter(Boolean).join(delimiter);\n\n\treturn {\n\t\t...process.env,\n\t\t[pathKey]: updatedPath,\n\t};\n}\n\n/**\n * Sanitize binary output for display/storage.\n * Removes characters that crash string-width or cause display issues:\n * - Control characters (except tab, newline, carriage return)\n * - Lone surrogates\n * - Unicode Format characters (crash string-width due to a bug)\n * - Characters with undefined code points\n */\nexport function sanitizeBinaryOutput(str: string): string {\n\t// Use Array.from to properly iterate over code points (not code units)\n\t// This handles surrogate pairs correctly and catches edge cases where\n\t// codePointAt() might return undefined\n\treturn Array.from(str)\n\t\t.filter((char) => {\n\t\t\t// Filter out characters that cause string-width to crash\n\t\t\t// This includes:\n\t\t\t// - Unicode format characters\n\t\t\t// - Lone surrogates (already filtered by Array.from)\n\t\t\t// - Control chars except \\t \\n \\r\n\t\t\t// - Characters with undefined code points\n\n\t\t\tconst code = char.codePointAt(0);\n\n\t\t\t// Skip if code point is undefined (edge case with invalid strings)\n\t\t\tif (code === undefined) return false;\n\n\t\t\t// Allow tab, newline, carriage return\n\t\t\tif (code === 0x09 || code === 0x0a || code === 0x0d) return true;\n\n\t\t\t// Filter out control characters (0x00-0x1F, except 0x09, 0x0a, 0x0x0d)\n\t\t\tif (code <= 0x1f) return false;\n\n\t\t\t// Filter out Unicode format characters\n\t\t\tif (code >= 0xfff9 && code <= 0xfffb) return false;\n\n\t\t\treturn true;\n\t\t})\n\t\t.join(\"\");\n}\n\n/**\n * Detached child processes must be tracked so they can be killed on parent\n * shutdown signals (SIGHUP/SIGTERM).\n */\nconst trackedDetachedChildPids = new Set();\n\nexport function trackDetachedChildPid(pid: number): void {\n\ttrackedDetachedChildPids.add(pid);\n}\n\nexport function untrackDetachedChildPid(pid: number): void {\n\ttrackedDetachedChildPids.delete(pid);\n}\n\nexport function killTrackedDetachedChildren(): void {\n\tfor (const pid of trackedDetachedChildPids) {\n\t\tkillProcessTree(pid);\n\t}\n\ttrackedDetachedChildPids.clear();\n}\n\n/**\n * Kill a process and all its children (cross-platform)\n */\nexport function killProcessTree(pid: number): void {\n\tif (process.platform === \"win32\") {\n\t\t// Use taskkill on Windows to kill process tree\n\t\ttry {\n\t\t\tspawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], {\n\t\t\t\tstdio: \"ignore\",\n\t\t\t\tdetached: true,\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t} catch {\n\t\t\t// Ignore errors if taskkill fails\n\t\t}\n\t} else {\n\t\t// Use SIGKILL on Unix/Linux/Mac\n\t\ttry {\n\t\t\tprocess.kill(-pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t// Fallback to killing just the child if process group kill fails\n\t\t\ttry {\n\t\t\t\tprocess.kill(pid, \"SIGKILL\");\n\t\t\t} catch {\n\t\t\t\t// Process already dead\n\t\t\t}\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/shell.js b/dist/utils/shell.js new file mode 100644 index 0000000..68e7e51 --- /dev/null +++ b/dist/utils/shell.js @@ -0,0 +1,202 @@ +import { existsSync } from "node:fs"; +import { delimiter } from "node:path"; +import { spawn, spawnSync } from "child_process"; +import { getBinDir } from "../config.js"; +/** + * Find bash executable on PATH (cross-platform) + */ +function isLegacyWslBashPath(path) { + const normalized = path.replace(/\//g, "\\").toLowerCase(); + return /^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized); +} +function getBashShellConfig(shell) { + return isLegacyWslBashPath(shell) ? { shell, args: ["-s"], commandTransport: "stdin" } : { shell, args: ["-c"] }; +} +function findBashOnPath() { + if (process.platform === "win32") { + // Windows: Use 'where' and verify file exists (where can return non-existent paths) + try { + const result = spawnSync("where", ["bash.exe"], { + encoding: "utf-8", + timeout: 5000, + windowsHide: true, + }); + if (result.status === 0 && result.stdout) { + const firstMatch = result.stdout.trim().split(/\r?\n/)[0]; + if (firstMatch && existsSync(firstMatch)) { + return firstMatch; + } + } + } + catch { + // Ignore errors + } + return null; + } + // Unix: Use 'which' and trust its output (handles Termux and special filesystems) + try { + const result = spawnSync("which", ["bash"], { encoding: "utf-8", timeout: 5000 }); + if (result.status === 0 && result.stdout) { + const firstMatch = result.stdout.trim().split(/\r?\n/)[0]; + if (firstMatch) { + return firstMatch; + } + } + } + catch { + // Ignore errors + } + return null; +} +/** + * Resolve shell configuration based on platform and an optional explicit shell path. + * Resolution order: + * 1. User-specified shellPath + * 2. On Windows: Git Bash in known locations, then bash on PATH + * 3. On Unix: /bin/bash, then bash on PATH, then fallback to sh + */ +export function getShellConfig(customShellPath) { + // 1. Check user-specified shell path + if (customShellPath) { + if (existsSync(customShellPath)) { + return getBashShellConfig(customShellPath); + } + throw new Error(`Custom shell path not found: ${customShellPath}`); + } + if (process.platform === "win32") { + // 2. Try Git Bash in known locations + const paths = []; + const programFiles = process.env.ProgramFiles; + if (programFiles) { + paths.push(`${programFiles}\\Git\\bin\\bash.exe`); + } + const programFilesX86 = process.env["ProgramFiles(x86)"]; + if (programFilesX86) { + paths.push(`${programFilesX86}\\Git\\bin\\bash.exe`); + } + for (const path of paths) { + if (existsSync(path)) { + return getBashShellConfig(path); + } + } + // 3. Fallback: search bash.exe on PATH (Cygwin, MSYS2, WSL, etc.) + const bashOnPath = findBashOnPath(); + if (bashOnPath) { + return getBashShellConfig(bashOnPath); + } + throw new Error(`No bash shell found. Options:\n` + + ` 1. Install Git for Windows: https://git-scm.com/download/win\n` + + ` 2. Add your bash to PATH (Cygwin, MSYS2, etc.)\n` + + " 3. Set shellPath in settings.json\n\n" + + `Searched Git Bash in:\n${paths.map((p) => ` ${p}`).join("\n")}`); + } + // Unix: try /bin/bash, then bash on PATH, then fallback to sh + if (existsSync("/bin/bash")) { + return getBashShellConfig("/bin/bash"); + } + const bashOnPath = findBashOnPath(); + if (bashOnPath) { + return getBashShellConfig(bashOnPath); + } + return { shell: "sh", args: ["-c"] }; +} +export function getShellEnv() { + const binDir = getBinDir(); + const pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === "path") ?? "PATH"; + const currentPath = process.env[pathKey] ?? ""; + const pathEntries = currentPath.split(delimiter).filter(Boolean); + const hasBinDir = pathEntries.includes(binDir); + const updatedPath = hasBinDir ? currentPath : [binDir, currentPath].filter(Boolean).join(delimiter); + return { + ...process.env, + [pathKey]: updatedPath, + }; +} +/** + * Sanitize binary output for display/storage. + * Removes characters that crash string-width or cause display issues: + * - Control characters (except tab, newline, carriage return) + * - Lone surrogates + * - Unicode Format characters (crash string-width due to a bug) + * - Characters with undefined code points + */ +export function sanitizeBinaryOutput(str) { + // Use Array.from to properly iterate over code points (not code units) + // This handles surrogate pairs correctly and catches edge cases where + // codePointAt() might return undefined + return Array.from(str) + .filter((char) => { + // Filter out characters that cause string-width to crash + // This includes: + // - Unicode format characters + // - Lone surrogates (already filtered by Array.from) + // - Control chars except \t \n \r + // - Characters with undefined code points + const code = char.codePointAt(0); + // Skip if code point is undefined (edge case with invalid strings) + if (code === undefined) + return false; + // Allow tab, newline, carriage return + if (code === 0x09 || code === 0x0a || code === 0x0d) + return true; + // Filter out control characters (0x00-0x1F, except 0x09, 0x0a, 0x0x0d) + if (code <= 0x1f) + return false; + // Filter out Unicode format characters + if (code >= 0xfff9 && code <= 0xfffb) + return false; + return true; + }) + .join(""); +} +/** + * Detached child processes must be tracked so they can be killed on parent + * shutdown signals (SIGHUP/SIGTERM). + */ +const trackedDetachedChildPids = new Set(); +export function trackDetachedChildPid(pid) { + trackedDetachedChildPids.add(pid); +} +export function untrackDetachedChildPid(pid) { + trackedDetachedChildPids.delete(pid); +} +export function killTrackedDetachedChildren() { + for (const pid of trackedDetachedChildPids) { + killProcessTree(pid); + } + trackedDetachedChildPids.clear(); +} +/** + * Kill a process and all its children (cross-platform) + */ +export function killProcessTree(pid) { + if (process.platform === "win32") { + // Use taskkill on Windows to kill process tree + try { + spawn("taskkill", ["/F", "/T", "/PID", String(pid)], { + stdio: "ignore", + detached: true, + windowsHide: true, + }); + } + catch { + // Ignore errors if taskkill fails + } + } + else { + // Use SIGKILL on Unix/Linux/Mac + try { + process.kill(-pid, "SIGKILL"); + } + catch { + // Fallback to killing just the child if process group kill fails + try { + process.kill(pid, "SIGKILL"); + } + catch { + // Process already dead + } + } + } +} +//# sourceMappingURL=shell.js.map \ No newline at end of file diff --git a/dist/utils/shell.js.map b/dist/utils/shell.js.map new file mode 100644 index 0000000..b546793 --- /dev/null +++ b/dist/utils/shell.js.map @@ -0,0 +1 @@ +{"version":3,"file":"shell.js","sourceRoot":"","sources":["../../src/utils/shell.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAQzC;;GAEG;AACH,SAAS,mBAAmB,CAAC,IAAY,EAAW;IACnD,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC;IAC3D,OAAO,sDAAsD,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;AAAA,CAC/E;AAED,SAAS,kBAAkB,CAAC,KAAa,EAAe;IACvD,OAAO,mBAAmB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,IAAI,CAAC,EAAE,gBAAgB,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;AAAA,CACjH;AAED,SAAS,cAAc,GAAkB;IACxC,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC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AAE,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE;gBACpD,KAAK,EAAE,QAAQ;gBACf,QAAQ,EAAE,IAAI;gBACd,WAAW,EAAE,IAAI;aACjB,CAAC,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACR,kCAAkC;QACnC,CAAC;IACF,CAAC;SAAM,CAAC;QACP,gCAAgC;QAChC,IAAI,CAAC;YACJ,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACR,iEAAiE;YACjE,IAAI,CAAC;gBACJ,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;YAC9B,CAAC;YAAC,MAAM,CAAC;gBACR,uBAAuB;YACxB,CAAC;QACF,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { delimiter } from \"node:path\";\nimport { spawn, spawnSync } from \"child_process\";\nimport { getBinDir } from \"../config.ts\";\n\nexport interface ShellConfig {\n\tshell: string;\n\targs: string[];\n\tcommandTransport?: \"argv\" | \"stdin\";\n}\n\n/**\n * Find bash executable on PATH (cross-platform)\n */\nfunction isLegacyWslBashPath(path: string): boolean {\n\tconst normalized = path.replace(/\\//g, \"\\\\\").toLowerCase();\n\treturn /^[a-z]:\\\\windows\\\\(?:system32|sysnative)\\\\bash\\.exe$/.test(normalized);\n}\n\nfunction getBashShellConfig(shell: string): ShellConfig {\n\treturn isLegacyWslBashPath(shell) ? { shell, args: [\"-s\"], commandTransport: \"stdin\" } : { shell, args: [\"-c\"] };\n}\n\nfunction findBashOnPath(): string | null {\n\tif (process.platform === \"win32\") {\n\t\t// Windows: Use 'where' and verify file exists (where can return non-existent paths)\n\t\ttry {\n\t\t\tconst result = spawnSync(\"where\", [\"bash.exe\"], {\n\t\t\t\tencoding: \"utf-8\",\n\t\t\t\ttimeout: 5000,\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (result.status === 0 && result.stdout) {\n\t\t\t\tconst firstMatch = result.stdout.trim().split(/\\r?\\n/)[0];\n\t\t\t\tif (firstMatch && existsSync(firstMatch)) {\n\t\t\t\t\treturn firstMatch;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore errors\n\t\t}\n\t\treturn null;\n\t}\n\n\t// Unix: Use 'which' and trust its output (handles Termux and special filesystems)\n\ttry {\n\t\tconst result = spawnSync(\"which\", [\"bash\"], { encoding: \"utf-8\", timeout: 5000 });\n\t\tif (result.status === 0 && result.stdout) {\n\t\t\tconst firstMatch = result.stdout.trim().split(/\\r?\\n/)[0];\n\t\t\tif (firstMatch) {\n\t\t\t\treturn firstMatch;\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Ignore errors\n\t}\n\treturn null;\n}\n\n/**\n * Resolve shell configuration based on platform and an optional explicit shell path.\n * Resolution order:\n * 1. User-specified shellPath\n * 2. On Windows: Git Bash in known locations, then bash on PATH\n * 3. On Unix: /bin/bash, then bash on PATH, then fallback to sh\n */\nexport function getShellConfig(customShellPath?: string): ShellConfig {\n\t// 1. Check user-specified shell path\n\tif (customShellPath) {\n\t\tif (existsSync(customShellPath)) {\n\t\t\treturn getBashShellConfig(customShellPath);\n\t\t}\n\t\tthrow new Error(`Custom shell path not found: ${customShellPath}`);\n\t}\n\n\tif (process.platform === \"win32\") {\n\t\t// 2. Try Git Bash in known locations\n\t\tconst paths: string[] = [];\n\t\tconst programFiles = process.env.ProgramFiles;\n\t\tif (programFiles) {\n\t\t\tpaths.push(`${programFiles}\\\\Git\\\\bin\\\\bash.exe`);\n\t\t}\n\t\tconst programFilesX86 = process.env[\"ProgramFiles(x86)\"];\n\t\tif (programFilesX86) {\n\t\t\tpaths.push(`${programFilesX86}\\\\Git\\\\bin\\\\bash.exe`);\n\t\t}\n\n\t\tfor (const path of paths) {\n\t\t\tif (existsSync(path)) {\n\t\t\t\treturn getBashShellConfig(path);\n\t\t\t}\n\t\t}\n\n\t\t// 3. Fallback: search bash.exe on PATH (Cygwin, MSYS2, WSL, etc.)\n\t\tconst bashOnPath = findBashOnPath();\n\t\tif (bashOnPath) {\n\t\t\treturn getBashShellConfig(bashOnPath);\n\t\t}\n\n\t\tthrow new Error(\n\t\t\t`No bash shell found. Options:\\n` +\n\t\t\t\t` 1. Install Git for Windows: https://git-scm.com/download/win\\n` +\n\t\t\t\t` 2. Add your bash to PATH (Cygwin, MSYS2, etc.)\\n` +\n\t\t\t\t\" 3. Set shellPath in settings.json\\n\\n\" +\n\t\t\t\t`Searched Git Bash in:\\n${paths.map((p) => ` ${p}`).join(\"\\n\")}`,\n\t\t);\n\t}\n\n\t// Unix: try /bin/bash, then bash on PATH, then fallback to sh\n\tif (existsSync(\"/bin/bash\")) {\n\t\treturn getBashShellConfig(\"/bin/bash\");\n\t}\n\n\tconst bashOnPath = findBashOnPath();\n\tif (bashOnPath) {\n\t\treturn getBashShellConfig(bashOnPath);\n\t}\n\n\treturn { shell: \"sh\", args: [\"-c\"] };\n}\n\nexport function getShellEnv(): NodeJS.ProcessEnv {\n\tconst binDir = getBinDir();\n\tconst pathKey = Object.keys(process.env).find((key) => key.toLowerCase() === \"path\") ?? \"PATH\";\n\tconst currentPath = process.env[pathKey] ?? \"\";\n\tconst pathEntries = currentPath.split(delimiter).filter(Boolean);\n\tconst hasBinDir = pathEntries.includes(binDir);\n\tconst updatedPath = hasBinDir ? currentPath : [binDir, currentPath].filter(Boolean).join(delimiter);\n\n\treturn {\n\t\t...process.env,\n\t\t[pathKey]: updatedPath,\n\t};\n}\n\n/**\n * Sanitize binary output for display/storage.\n * Removes characters that crash string-width or cause display issues:\n * - Control characters (except tab, newline, carriage return)\n * - Lone surrogates\n * - Unicode Format characters (crash string-width due to a bug)\n * - Characters with undefined code points\n */\nexport function sanitizeBinaryOutput(str: string): string {\n\t// Use Array.from to properly iterate over code points (not code units)\n\t// This handles surrogate pairs correctly and catches edge cases where\n\t// codePointAt() might return undefined\n\treturn Array.from(str)\n\t\t.filter((char) => {\n\t\t\t// Filter out characters that cause string-width to crash\n\t\t\t// This includes:\n\t\t\t// - Unicode format characters\n\t\t\t// - Lone surrogates (already filtered by Array.from)\n\t\t\t// - Control chars except \\t \\n \\r\n\t\t\t// - Characters with undefined code points\n\n\t\t\tconst code = char.codePointAt(0);\n\n\t\t\t// Skip if code point is undefined (edge case with invalid strings)\n\t\t\tif (code === undefined) return false;\n\n\t\t\t// Allow tab, newline, carriage return\n\t\t\tif (code === 0x09 || code === 0x0a || code === 0x0d) return true;\n\n\t\t\t// Filter out control characters (0x00-0x1F, except 0x09, 0x0a, 0x0x0d)\n\t\t\tif (code <= 0x1f) return false;\n\n\t\t\t// Filter out Unicode format characters\n\t\t\tif (code >= 0xfff9 && code <= 0xfffb) return false;\n\n\t\t\treturn true;\n\t\t})\n\t\t.join(\"\");\n}\n\n/**\n * Detached child processes must be tracked so they can be killed on parent\n * shutdown signals (SIGHUP/SIGTERM).\n */\nconst trackedDetachedChildPids = new Set();\n\nexport function trackDetachedChildPid(pid: number): void {\n\ttrackedDetachedChildPids.add(pid);\n}\n\nexport function untrackDetachedChildPid(pid: number): void {\n\ttrackedDetachedChildPids.delete(pid);\n}\n\nexport function killTrackedDetachedChildren(): void {\n\tfor (const pid of trackedDetachedChildPids) {\n\t\tkillProcessTree(pid);\n\t}\n\ttrackedDetachedChildPids.clear();\n}\n\n/**\n * Kill a process and all its children (cross-platform)\n */\nexport function killProcessTree(pid: number): void {\n\tif (process.platform === \"win32\") {\n\t\t// Use taskkill on Windows to kill process tree\n\t\ttry {\n\t\t\tspawn(\"taskkill\", [\"/F\", \"/T\", \"/PID\", String(pid)], {\n\t\t\t\tstdio: \"ignore\",\n\t\t\t\tdetached: true,\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t} catch {\n\t\t\t// Ignore errors if taskkill fails\n\t\t}\n\t} else {\n\t\t// Use SIGKILL on Unix/Linux/Mac\n\t\ttry {\n\t\t\tprocess.kill(-pid, \"SIGKILL\");\n\t\t} catch {\n\t\t\t// Fallback to killing just the child if process group kill fails\n\t\t\ttry {\n\t\t\t\tprocess.kill(pid, \"SIGKILL\");\n\t\t\t} catch {\n\t\t\t\t// Process already dead\n\t\t\t}\n\t\t}\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/sleep.d.ts b/dist/utils/sleep.d.ts new file mode 100644 index 0000000..6495425 --- /dev/null +++ b/dist/utils/sleep.d.ts @@ -0,0 +1,5 @@ +/** + * Sleep helper that respects abort signal. + */ +export declare function sleep(ms: number, signal?: AbortSignal): Promise; +//# sourceMappingURL=sleep.d.ts.map \ No newline at end of file diff --git a/dist/utils/sleep.d.ts.map b/dist/utils/sleep.d.ts.map new file mode 100644 index 0000000..04d78f8 --- /dev/null +++ b/dist/utils/sleep.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sleep.d.ts","sourceRoot":"","sources":["../../src/utils/sleep.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAcrE","sourcesContent":["/**\n * Sleep helper that respects abort signal.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Aborted\"));\n\t\t\treturn;\n\t\t}\n\n\t\tconst timeout = setTimeout(resolve, ms);\n\n\t\tsignal?.addEventListener(\"abort\", () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(new Error(\"Aborted\"));\n\t\t});\n\t});\n}\n"]} \ No newline at end of file diff --git a/dist/utils/sleep.js b/dist/utils/sleep.js new file mode 100644 index 0000000..bfb1c2a --- /dev/null +++ b/dist/utils/sleep.js @@ -0,0 +1,17 @@ +/** + * Sleep helper that respects abort signal. + */ +export function sleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(new Error("Aborted")); + return; + } + const timeout = setTimeout(resolve, ms); + signal?.addEventListener("abort", () => { + clearTimeout(timeout); + reject(new Error("Aborted")); + }); + }); +} +//# sourceMappingURL=sleep.js.map \ No newline at end of file diff --git a/dist/utils/sleep.js.map b/dist/utils/sleep.js.map new file mode 100644 index 0000000..e85573a --- /dev/null +++ b/dist/utils/sleep.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sleep.js","sourceRoot":"","sources":["../../src/utils/sleep.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,UAAU,KAAK,CAAC,EAAU,EAAE,MAAoB,EAAiB;IACtE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,CAAC;QACvC,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;YACrB,MAAM,CAAC,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC;YAC7B,OAAO;QACR,CAAC;QAED,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QAExC,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC;YACvC,YAAY,CAAC,OAAO,CAAC,CAAC;YACtB,MAAM,CAAC,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC;QAAA,CAC7B,CAAC,CAAC;IAAA,CACH,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Sleep helper that respects abort signal.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Aborted\"));\n\t\t\treturn;\n\t\t}\n\n\t\tconst timeout = setTimeout(resolve, ms);\n\n\t\tsignal?.addEventListener(\"abort\", () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(new Error(\"Aborted\"));\n\t\t});\n\t});\n}\n"]} \ No newline at end of file diff --git a/dist/utils/syntax-highlight.d.ts b/dist/utils/syntax-highlight.d.ts new file mode 100644 index 0000000..b2fe3d8 --- /dev/null +++ b/dist/utils/syntax-highlight.d.ts @@ -0,0 +1,12 @@ +export type HighlightFormatter = (text: string) => string; +export type HighlightTheme = Partial>; +export interface HighlightOptions { + language?: string; + ignoreIllegals?: boolean; + languageSubset?: string[]; + theme?: HighlightTheme; +} +export declare function renderHighlightedHtml(html: string, theme?: HighlightTheme): string; +export declare function highlight(code: string, options?: HighlightOptions): string; +export declare function supportsLanguage(name: string): boolean; +//# sourceMappingURL=syntax-highlight.d.ts.map \ No newline at end of file diff --git a/dist/utils/syntax-highlight.d.ts.map b/dist/utils/syntax-highlight.d.ts.map new file mode 100644 index 0000000..dcd7204 --- /dev/null +++ b/dist/utils/syntax-highlight.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"syntax-highlight.d.ts","sourceRoot":"","sources":["../../src/utils/syntax-highlight.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,kBAAkB,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;AAC1D,MAAM,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC,CAAC;AAEzE,MAAM,WAAW,gBAAgB;IAChC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,KAAK,CAAC,EAAE,cAAc,CAAC;CACvB;AAoED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,GAAE,cAAmB,GAAG,MAAM,CAoDtF;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB,GAAG,MAAM,CAQ9E;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEtD","sourcesContent":["import hljs from \"highlight.js/lib/index.js\";\nimport { decodeHtmlEntityAt } from \"./html.ts\";\n\nexport type HighlightFormatter = (text: string) => string;\nexport type HighlightTheme = Partial>;\n\nexport interface HighlightOptions {\n\tlanguage?: string;\n\tignoreIllegals?: boolean;\n\tlanguageSubset?: string[];\n\ttheme?: HighlightTheme;\n}\n\nconst SPAN_CLOSE = \"\";\nconst HIGHLIGHT_CLASS_PREFIX = \"hljs-\";\n\nfunction getScopeFromSpanTag(tag: string): string | undefined {\n\tconst match = /\\sclass\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/.exec(tag);\n\tconst classValue = match?.[1] ?? match?.[2];\n\tif (!classValue) {\n\t\treturn undefined;\n\t}\n\n\tfor (const className of classValue.split(/\\s+/)) {\n\t\tif (className.startsWith(HIGHLIGHT_CLASS_PREFIX)) {\n\t\t\treturn className.slice(HIGHLIGHT_CLASS_PREFIX.length);\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getScopeFormatter(scope: string, theme: HighlightTheme): HighlightFormatter | undefined {\n\tconst exact = theme[scope];\n\tif (exact) {\n\t\treturn exact;\n\t}\n\n\tconst dotIndex = scope.indexOf(\".\");\n\tif (dotIndex !== -1) {\n\t\tconst prefixFormatter = theme[scope.slice(0, dotIndex)];\n\t\tif (prefixFormatter) {\n\t\t\treturn prefixFormatter;\n\t\t}\n\t}\n\n\tconst dashIndex = scope.indexOf(\"-\");\n\tif (dashIndex !== -1) {\n\t\tconst prefixFormatter = theme[scope.slice(0, dashIndex)];\n\t\tif (prefixFormatter) {\n\t\t\treturn prefixFormatter;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getActiveFormatter(scopes: Array, theme: HighlightTheme): HighlightFormatter | undefined {\n\tfor (let i = scopes.length - 1; i >= 0; i--) {\n\t\tconst scope = scopes[i];\n\t\tif (!scope) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst formatter = getScopeFormatter(scope, theme);\n\t\tif (formatter) {\n\t\t\treturn formatter;\n\t\t}\n\t}\n\treturn theme.default;\n}\n\nfunction isSpanOpenTagStart(html: string, index: number): boolean {\n\tif (!html.startsWith(\"\" || nextChar === \" \" || nextChar === \"\\t\" || nextChar === \"\\n\" || nextChar === \"\\r\";\n}\n\nexport function renderHighlightedHtml(html: string, theme: HighlightTheme = {}): string {\n\tlet output = \"\";\n\tlet textBuffer = \"\";\n\tconst scopes: Array = [];\n\n\tconst flushText = () => {\n\t\tif (!textBuffer) {\n\t\t\treturn;\n\t\t}\n\t\tconst formatter = getActiveFormatter(scopes, theme);\n\t\toutput += formatter ? formatter(textBuffer) : textBuffer;\n\t\ttextBuffer = \"\";\n\t};\n\n\tlet index = 0;\n\twhile (index < html.length) {\n\t\tif (isSpanOpenTagStart(html, index)) {\n\t\t\tconst tagEndIndex = html.indexOf(\">\", index + 5);\n\t\t\tif (tagEndIndex !== -1) {\n\t\t\t\tflushText();\n\t\t\t\tconst tag = html.slice(index, tagEndIndex + 1);\n\t\t\t\tconst scope = getScopeFromSpanTag(tag);\n\t\t\t\tscopes.push(scope);\n\t\t\t\tindex = tagEndIndex + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (html.startsWith(SPAN_CLOSE, index)) {\n\t\t\tflushText();\n\t\t\tif (scopes.length > 0) {\n\t\t\t\tscopes.pop();\n\t\t\t}\n\t\t\tindex += SPAN_CLOSE.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (html[index] === \"&\") {\n\t\t\tconst decoded = decodeHtmlEntityAt(html, index);\n\t\t\tif (decoded) {\n\t\t\t\ttextBuffer += decoded.text;\n\t\t\t\tindex += decoded.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\ttextBuffer += html[index];\n\t\tindex++;\n\t}\n\n\tflushText();\n\treturn output;\n}\n\nexport function highlight(code: string, options: HighlightOptions = {}): string {\n\tconst html = options.language\n\t\t? hljs.highlight(code, {\n\t\t\t\tlanguage: options.language,\n\t\t\t\tignoreIllegals: options.ignoreIllegals,\n\t\t\t}).value\n\t\t: hljs.highlightAuto(code, options.languageSubset).value;\n\treturn renderHighlightedHtml(html, options.theme);\n}\n\nexport function supportsLanguage(name: string): boolean {\n\treturn hljs.getLanguage(name) !== undefined;\n}\n"]} \ No newline at end of file diff --git a/dist/utils/syntax-highlight.js b/dist/utils/syntax-highlight.js new file mode 100644 index 0000000..e882674 --- /dev/null +++ b/dist/utils/syntax-highlight.js @@ -0,0 +1,118 @@ +import hljs from "highlight.js/lib/index.js"; +import { decodeHtmlEntityAt } from "./html.js"; +const SPAN_CLOSE = ""; +const HIGHLIGHT_CLASS_PREFIX = "hljs-"; +function getScopeFromSpanTag(tag) { + const match = /\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(tag); + const classValue = match?.[1] ?? match?.[2]; + if (!classValue) { + return undefined; + } + for (const className of classValue.split(/\s+/)) { + if (className.startsWith(HIGHLIGHT_CLASS_PREFIX)) { + return className.slice(HIGHLIGHT_CLASS_PREFIX.length); + } + } + return undefined; +} +function getScopeFormatter(scope, theme) { + const exact = theme[scope]; + if (exact) { + return exact; + } + const dotIndex = scope.indexOf("."); + if (dotIndex !== -1) { + const prefixFormatter = theme[scope.slice(0, dotIndex)]; + if (prefixFormatter) { + return prefixFormatter; + } + } + const dashIndex = scope.indexOf("-"); + if (dashIndex !== -1) { + const prefixFormatter = theme[scope.slice(0, dashIndex)]; + if (prefixFormatter) { + return prefixFormatter; + } + } + return undefined; +} +function getActiveFormatter(scopes, theme) { + for (let i = scopes.length - 1; i >= 0; i--) { + const scope = scopes[i]; + if (!scope) { + continue; + } + const formatter = getScopeFormatter(scope, theme); + if (formatter) { + return formatter; + } + } + return theme.default; +} +function isSpanOpenTagStart(html, index) { + if (!html.startsWith("" || nextChar === " " || nextChar === "\t" || nextChar === "\n" || nextChar === "\r"; +} +export function renderHighlightedHtml(html, theme = {}) { + let output = ""; + let textBuffer = ""; + const scopes = []; + const flushText = () => { + if (!textBuffer) { + return; + } + const formatter = getActiveFormatter(scopes, theme); + output += formatter ? formatter(textBuffer) : textBuffer; + textBuffer = ""; + }; + let index = 0; + while (index < html.length) { + if (isSpanOpenTagStart(html, index)) { + const tagEndIndex = html.indexOf(">", index + 5); + if (tagEndIndex !== -1) { + flushText(); + const tag = html.slice(index, tagEndIndex + 1); + const scope = getScopeFromSpanTag(tag); + scopes.push(scope); + index = tagEndIndex + 1; + continue; + } + } + if (html.startsWith(SPAN_CLOSE, index)) { + flushText(); + if (scopes.length > 0) { + scopes.pop(); + } + index += SPAN_CLOSE.length; + continue; + } + if (html[index] === "&") { + const decoded = decodeHtmlEntityAt(html, index); + if (decoded) { + textBuffer += decoded.text; + index += decoded.length; + continue; + } + } + textBuffer += html[index]; + index++; + } + flushText(); + return output; +} +export function highlight(code, options = {}) { + const html = options.language + ? hljs.highlight(code, { + language: options.language, + ignoreIllegals: options.ignoreIllegals, + }).value + : hljs.highlightAuto(code, options.languageSubset).value; + return renderHighlightedHtml(html, options.theme); +} +export function supportsLanguage(name) { + return hljs.getLanguage(name) !== undefined; +} +//# sourceMappingURL=syntax-highlight.js.map \ No newline at end of file diff --git a/dist/utils/syntax-highlight.js.map b/dist/utils/syntax-highlight.js.map new file mode 100644 index 0000000..c45c3c1 --- /dev/null +++ b/dist/utils/syntax-highlight.js.map @@ -0,0 +1 @@ +{"version":3,"file":"syntax-highlight.js","sourceRoot":"","sources":["../../src/utils/syntax-highlight.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,2BAA2B,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAY/C,MAAM,UAAU,GAAG,SAAS,CAAC;AAC7B,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAEvC,SAAS,mBAAmB,CAAC,GAAW,EAAsB;IAC7D,MAAM,KAAK,GAAG,uCAAuC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAChE,MAAM,UAAU,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;IAC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ED,SAAS,EAAE,CAAC;IACZ,OAAO,MAAM,CAAC;AAAA,CACd;AAED,MAAM,UAAU,SAAS,CAAC,IAAY,EAAE,OAAO,GAAqB,EAAE,EAAU;IAC/E,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ;QAC5B,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE;YACrB,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,cAAc,EAAE,OAAO,CAAC,cAAc;SACtC,CAAC,CAAC,KAAK;QACT,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC,KAAK,CAAC;IAC1D,OAAO,qBAAqB,CAAC,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAClD;AAED,MAAM,UAAU,gBAAgB,CAAC,IAAY,EAAW;IACvD,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC;AAAA,CAC5C","sourcesContent":["import hljs from \"highlight.js/lib/index.js\";\nimport { decodeHtmlEntityAt } from \"./html.ts\";\n\nexport type HighlightFormatter = (text: string) => string;\nexport type HighlightTheme = Partial>;\n\nexport interface HighlightOptions {\n\tlanguage?: string;\n\tignoreIllegals?: boolean;\n\tlanguageSubset?: string[];\n\ttheme?: HighlightTheme;\n}\n\nconst SPAN_CLOSE = \"\";\nconst HIGHLIGHT_CLASS_PREFIX = \"hljs-\";\n\nfunction getScopeFromSpanTag(tag: string): string | undefined {\n\tconst match = /\\sclass\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/.exec(tag);\n\tconst classValue = match?.[1] ?? match?.[2];\n\tif (!classValue) {\n\t\treturn undefined;\n\t}\n\n\tfor (const className of classValue.split(/\\s+/)) {\n\t\tif (className.startsWith(HIGHLIGHT_CLASS_PREFIX)) {\n\t\t\treturn className.slice(HIGHLIGHT_CLASS_PREFIX.length);\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getScopeFormatter(scope: string, theme: HighlightTheme): HighlightFormatter | undefined {\n\tconst exact = theme[scope];\n\tif (exact) {\n\t\treturn exact;\n\t}\n\n\tconst dotIndex = scope.indexOf(\".\");\n\tif (dotIndex !== -1) {\n\t\tconst prefixFormatter = theme[scope.slice(0, dotIndex)];\n\t\tif (prefixFormatter) {\n\t\t\treturn prefixFormatter;\n\t\t}\n\t}\n\n\tconst dashIndex = scope.indexOf(\"-\");\n\tif (dashIndex !== -1) {\n\t\tconst prefixFormatter = theme[scope.slice(0, dashIndex)];\n\t\tif (prefixFormatter) {\n\t\t\treturn prefixFormatter;\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getActiveFormatter(scopes: Array, theme: HighlightTheme): HighlightFormatter | undefined {\n\tfor (let i = scopes.length - 1; i >= 0; i--) {\n\t\tconst scope = scopes[i];\n\t\tif (!scope) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst formatter = getScopeFormatter(scope, theme);\n\t\tif (formatter) {\n\t\t\treturn formatter;\n\t\t}\n\t}\n\treturn theme.default;\n}\n\nfunction isSpanOpenTagStart(html: string, index: number): boolean {\n\tif (!html.startsWith(\"\" || nextChar === \" \" || nextChar === \"\\t\" || nextChar === \"\\n\" || nextChar === \"\\r\";\n}\n\nexport function renderHighlightedHtml(html: string, theme: HighlightTheme = {}): string {\n\tlet output = \"\";\n\tlet textBuffer = \"\";\n\tconst scopes: Array = [];\n\n\tconst flushText = () => {\n\t\tif (!textBuffer) {\n\t\t\treturn;\n\t\t}\n\t\tconst formatter = getActiveFormatter(scopes, theme);\n\t\toutput += formatter ? formatter(textBuffer) : textBuffer;\n\t\ttextBuffer = \"\";\n\t};\n\n\tlet index = 0;\n\twhile (index < html.length) {\n\t\tif (isSpanOpenTagStart(html, index)) {\n\t\t\tconst tagEndIndex = html.indexOf(\">\", index + 5);\n\t\t\tif (tagEndIndex !== -1) {\n\t\t\t\tflushText();\n\t\t\t\tconst tag = html.slice(index, tagEndIndex + 1);\n\t\t\t\tconst scope = getScopeFromSpanTag(tag);\n\t\t\t\tscopes.push(scope);\n\t\t\t\tindex = tagEndIndex + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (html.startsWith(SPAN_CLOSE, index)) {\n\t\t\tflushText();\n\t\t\tif (scopes.length > 0) {\n\t\t\t\tscopes.pop();\n\t\t\t}\n\t\t\tindex += SPAN_CLOSE.length;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (html[index] === \"&\") {\n\t\t\tconst decoded = decodeHtmlEntityAt(html, index);\n\t\t\tif (decoded) {\n\t\t\t\ttextBuffer += decoded.text;\n\t\t\t\tindex += decoded.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\ttextBuffer += html[index];\n\t\tindex++;\n\t}\n\n\tflushText();\n\treturn output;\n}\n\nexport function highlight(code: string, options: HighlightOptions = {}): string {\n\tconst html = options.language\n\t\t? hljs.highlight(code, {\n\t\t\t\tlanguage: options.language,\n\t\t\t\tignoreIllegals: options.ignoreIllegals,\n\t\t\t}).value\n\t\t: hljs.highlightAuto(code, options.languageSubset).value;\n\treturn renderHighlightedHtml(html, options.theme);\n}\n\nexport function supportsLanguage(name: string): boolean {\n\treturn hljs.getLanguage(name) !== undefined;\n}\n"]} \ No newline at end of file diff --git a/dist/utils/tools-manager.d.ts b/dist/utils/tools-manager.d.ts new file mode 100644 index 0000000..0bed525 --- /dev/null +++ b/dist/utils/tools-manager.d.ts @@ -0,0 +1,3 @@ +export declare function getToolPath(tool: "fd" | "rg"): string | null; +export declare function ensureTool(tool: "fd" | "rg", silent?: boolean): Promise; +//# sourceMappingURL=tools-manager.d.ts.map \ No newline at end of file diff --git a/dist/utils/tools-manager.d.ts.map b/dist/utils/tools-manager.d.ts.map new file mode 100644 index 0000000..e5b285c --- /dev/null +++ b/dist/utils/tools-manager.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tools-manager.d.ts","sourceRoot":"","sources":["../../src/utils/tools-manager.ts"],"names":[],"mappings":"AAoFA,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CAmB5D;AA8ND,wBAAsB,UAAU,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,MAAM,GAAE,OAAe,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA2CxG","sourcesContent":["import chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport { chmodSync, createWriteStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from \"fs\";\nimport { arch, platform } from \"os\";\nimport { join } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { APP_NAME, getBinDir } from \"../config.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst NETWORK_TIMEOUT_MS = 10_000;\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.PI_OFFLINE;\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n\tgetAssetName: (version: string, plat: string, architecture: string) => string | null;\n}\n\nconst TOOLS: Record = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-unknown-linux-gnu.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tif (architecture === \"arm64\") {\n\t\t\t\t\treturn `ripgrep-${version}-aarch64-unknown-linux-gnu.tar.gz`;\n\t\t\t\t}\n\t\t\t\treturn `ripgrep-${version}-x86_64-unknown-linux-musl.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n};\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\" });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: \"fd\" | \"rg\"): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first\n\tconst localPath = join(TOOLS_DIR, config.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"));\n\tif (existsSync(localPath)) {\n\t\treturn localPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n// Fetch latest release version from GitHub\nasync function getLatestVersion(repo: string): Promise {\n\tconst response = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, {\n\t\theaders: { \"User-Agent\": `${APP_NAME}-coding-agent` },\n\t\tsignal: AbortSignal.timeout(NETWORK_TIMEOUT_MS),\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub API error: ${response.status}`);\n\t}\n\n\tconst data = (await response.json()) as { tag_name: string };\n\treturn data.tag_name.replace(/^v/, \"\");\n}\n\n// Download a file from URL\nasync function downloadFile(url: string, dest: string): Promise {\n\tconst response = await fetch(url, {\n\t\tsignal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to download: ${response.status}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst fileStream = createWriteStream(dest);\n\tawait pipeline(Readable.fromWeb(response.body as any), fileStream);\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\" });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\n// Download and install a tool\nasync function downloadTool(tool: \"fd\" | \"rg\"): Promise {\n\tconst config = TOOLS[tool];\n\tif (!config) throw new Error(`Unknown tool: ${tool}`);\n\n\tconst plat = platform();\n\tconst architecture = arch();\n\n\t// Get latest version\n\tlet version = await getLatestVersion(config.repo);\n\tif (tool === \"fd\" && plat === \"darwin\" && architecture === \"x64\") {\n\t\tversion = \"10.3.0\";\n\t}\n\n\t// Get asset name for this platform\n\tconst assetName = config.getAssetName(version, plat, architecture);\n\tif (!assetName) {\n\t\tthrow new Error(`Unsupported platform: ${plat}/${architecture}`);\n\t}\n\n\t// Create tools directory\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\tconst downloadUrl = `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`;\n\tconst archivePath = join(TOOLS_DIR, assetName);\n\tconst binaryExt = plat === \"win32\" ? \".exe\" : \"\";\n\tconst binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);\n\n\t// Download\n\tawait downloadFile(downloadUrl, archivePath);\n\n\t// Extract into a unique temp directory. fd and rg downloads can run concurrently\n\t// during startup, so sharing a fixed directory causes races.\n\tconst extractDir = join(\n\t\tTOOLS_DIR,\n\t\t`extract_tmp_${config.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(extractDir, { recursive: true });\n\n\ttry {\n\t\tif (assetName.endsWith(\".tar.gz\")) {\n\t\t\textractTarGzArchive(archivePath, extractDir, assetName);\n\t\t} else if (assetName.endsWith(\".zip\")) {\n\t\t\textractZipArchive(archivePath, extractDir, assetName);\n\t\t} else {\n\t\t\tthrow new Error(`Unsupported archive format: ${assetName}`);\n\t\t}\n\n\t\t// Find the binary in extracted files. Some archives contain files directly\n\t\t// at root, others nest under a versioned subdirectory.\n\t\tconst binaryFileName = config.binaryName + binaryExt;\n\t\tconst extractedDir = join(extractDir, assetName.replace(/\\.(tar\\.gz|zip)$/, \"\"));\n\t\tconst extractedBinaryCandidates = [join(extractedDir, binaryFileName), join(extractDir, binaryFileName)];\n\t\tlet extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync(candidate));\n\n\t\tif (!extractedBinary) {\n\t\t\textractedBinary = findBinaryRecursively(extractDir, binaryFileName) ?? undefined;\n\t\t}\n\n\t\tif (extractedBinary) {\n\t\t\trenameSync(extractedBinary, binaryPath);\n\t\t} else {\n\t\t\tthrow new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`);\n\t\t}\n\n\t\t// Make executable (Unix only)\n\t\tif (plat !== \"win32\") {\n\t\t\tchmodSync(binaryPath, 0o755);\n\t\t}\n\t} finally {\n\t\t// Cleanup\n\t\trmSync(archivePath, { force: true });\n\t\trmSync(extractDir, { recursive: true, force: true });\n\t}\n\n\treturn binaryPath;\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n};\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or null if unavailable\nexport async function ensureTool(tool: \"fd\" | \"rg\", silent: boolean = false): Promise {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, Linux binaries don't work due to Bionic libc incompatibility.\n\t// Users must install via pkg.\n\tif (platform() === \"android\") {\n\t\tconst pkgName = TERMUX_PACKAGES[tool] ?? tool;\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${pkgName}`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Tool not found - download it\n\tif (!silent) {\n\t\tconsole.log(chalk.dim(`${config.name} not found. Downloading...`));\n\t}\n\n\ttry {\n\t\tconst path = await downloadTool(tool);\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(`${config.name} installed to ${path}`));\n\t\t}\n\t\treturn path;\n\t} catch (e) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`));\n\t\t}\n\t\treturn undefined;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/tools-manager.js b/dist/utils/tools-manager.js new file mode 100644 index 0000000..01ccd31 --- /dev/null +++ b/dist/utils/tools-manager.js @@ -0,0 +1,328 @@ +import chalk from "chalk"; +import { spawnSync } from "child_process"; +import { chmodSync, createWriteStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from "fs"; +import { arch, platform } from "os"; +import { join } from "path"; +import { Readable } from "stream"; +import { pipeline } from "stream/promises"; +import { APP_NAME, getBinDir } from "../config.js"; +const TOOLS_DIR = getBinDir(); +const NETWORK_TIMEOUT_MS = 10_000; +const DOWNLOAD_TIMEOUT_MS = 120_000; +function isOfflineModeEnabled() { + const value = process.env.PI_OFFLINE; + if (!value) + return false; + return value === "1" || value.toLowerCase() === "true" || value.toLowerCase() === "yes"; +} +const TOOLS = { + fd: { + name: "fd", + repo: "sharkdp/fd", + binaryName: "fd", + systemBinaryNames: ["fd", "fdfind"], + tagPrefix: "v", + getAssetName: (version, plat, architecture) => { + if (plat === "darwin") { + const archStr = architecture === "arm64" ? "aarch64" : "x86_64"; + return `fd-v${version}-${archStr}-apple-darwin.tar.gz`; + } + else if (plat === "linux") { + const archStr = architecture === "arm64" ? "aarch64" : "x86_64"; + return `fd-v${version}-${archStr}-unknown-linux-gnu.tar.gz`; + } + else if (plat === "win32") { + const archStr = architecture === "arm64" ? "aarch64" : "x86_64"; + return `fd-v${version}-${archStr}-pc-windows-msvc.zip`; + } + return null; + }, + }, + rg: { + name: "ripgrep", + repo: "BurntSushi/ripgrep", + binaryName: "rg", + tagPrefix: "", + getAssetName: (version, plat, architecture) => { + if (plat === "darwin") { + const archStr = architecture === "arm64" ? "aarch64" : "x86_64"; + return `ripgrep-${version}-${archStr}-apple-darwin.tar.gz`; + } + else if (plat === "linux") { + if (architecture === "arm64") { + return `ripgrep-${version}-aarch64-unknown-linux-gnu.tar.gz`; + } + return `ripgrep-${version}-x86_64-unknown-linux-musl.tar.gz`; + } + else if (plat === "win32") { + const archStr = architecture === "arm64" ? "aarch64" : "x86_64"; + return `ripgrep-${version}-${archStr}-pc-windows-msvc.zip`; + } + return null; + }, + }, +}; +// Check if a command exists in PATH by trying to run it +function commandExists(cmd) { + try { + const result = spawnSync(cmd, ["--version"], { stdio: "pipe" }); + // Check for ENOENT error (command not found) + return result.error === undefined || result.error === null; + } + catch { + return false; + } +} +// Get the path to a tool (system-wide or in our tools dir) +export function getToolPath(tool) { + const config = TOOLS[tool]; + if (!config) + return null; + // Check our tools directory first + const localPath = join(TOOLS_DIR, config.binaryName + (platform() === "win32" ? ".exe" : "")); + if (existsSync(localPath)) { + return localPath; + } + // Check system PATH - if found, just return the command name (it's in PATH) + const systemBinaryNames = config.systemBinaryNames ?? [config.binaryName]; + for (const systemBinaryName of systemBinaryNames) { + if (commandExists(systemBinaryName)) { + return systemBinaryName; + } + } + return null; +} +// Fetch latest release version from GitHub +async function getLatestVersion(repo) { + const response = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, { + headers: { "User-Agent": `${APP_NAME}-coding-agent` }, + signal: AbortSignal.timeout(NETWORK_TIMEOUT_MS), + }); + if (!response.ok) { + throw new Error(`GitHub API error: ${response.status}`); + } + const data = (await response.json()); + return data.tag_name.replace(/^v/, ""); +} +// Download a file from URL +async function downloadFile(url, dest) { + const response = await fetch(url, { + signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS), + }); + if (!response.ok) { + throw new Error(`Failed to download: ${response.status}`); + } + if (!response.body) { + throw new Error("No response body"); + } + const fileStream = createWriteStream(dest); + await pipeline(Readable.fromWeb(response.body), fileStream); +} +function findBinaryRecursively(rootDir, binaryFileName) { + const stack = [rootDir]; + while (stack.length > 0) { + const currentDir = stack.pop(); + if (!currentDir) + continue; + const entries = readdirSync(currentDir, { withFileTypes: true }); + for (const entry of entries) { + const fullPath = join(currentDir, entry.name); + if (entry.isFile() && entry.name === binaryFileName) { + return fullPath; + } + if (entry.isDirectory()) { + stack.push(fullPath); + } + } + } + return null; +} +function formatSpawnFailure(result) { + if (result.error?.message) { + return result.error.message; + } + const stderr = result.stderr?.toString().trim(); + if (stderr) { + return stderr; + } + const stdout = result.stdout?.toString().trim(); + if (stdout) { + return stdout; + } + return `exit status ${result.status ?? "unknown"}`; +} +function runExtractionCommand(command, args) { + const result = spawnSync(command, args, { stdio: "pipe" }); + if (!result.error && result.status === 0) { + return null; + } + return `${command}: ${formatSpawnFailure(result)}`; +} +function extractTarGzArchive(archivePath, extractDir, assetName) { + const failure = runExtractionCommand("tar", ["xzf", archivePath, "-C", extractDir]); + if (failure) { + throw new Error(`Failed to extract ${assetName}: ${failure}`); + } +} +function getWindowsTarCommand() { + const systemRoot = process.env.SystemRoot ?? process.env.WINDIR; + if (systemRoot) { + const systemTar = join(systemRoot, "System32", "tar.exe"); + if (existsSync(systemTar)) { + return systemTar; + } + } + return "tar.exe"; +} +function extractZipArchive(archivePath, extractDir, assetName) { + const failures = []; + if (platform() === "win32") { + // Windows ships bsdtar as tar.exe, which supports zip files. Prefer the + // System32 binary over Git Bash's GNU tar, which does not handle zip archives. + const tarFailure = runExtractionCommand(getWindowsTarCommand(), ["xf", archivePath, "-C", extractDir]); + if (!tarFailure) + return; + failures.push(tarFailure); + const script = "& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }"; + const powershellFailure = runExtractionCommand("powershell.exe", [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-Command", + script, + archivePath, + extractDir, + ]); + if (!powershellFailure) + return; + failures.push(powershellFailure); + } + else { + const unzipFailure = runExtractionCommand("unzip", ["-q", archivePath, "-d", extractDir]); + if (!unzipFailure) + return; + failures.push(unzipFailure); + const tarFailure = runExtractionCommand("tar", ["xf", archivePath, "-C", extractDir]); + if (!tarFailure) + return; + failures.push(tarFailure); + } + throw new Error(`Failed to extract ${assetName}: ${failures.join("; ")}`); +} +// Download and install a tool +async function downloadTool(tool) { + const config = TOOLS[tool]; + if (!config) + throw new Error(`Unknown tool: ${tool}`); + const plat = platform(); + const architecture = arch(); + // Get latest version + let version = await getLatestVersion(config.repo); + if (tool === "fd" && plat === "darwin" && architecture === "x64") { + version = "10.3.0"; + } + // Get asset name for this platform + const assetName = config.getAssetName(version, plat, architecture); + if (!assetName) { + throw new Error(`Unsupported platform: ${plat}/${architecture}`); + } + // Create tools directory + mkdirSync(TOOLS_DIR, { recursive: true }); + const downloadUrl = `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`; + const archivePath = join(TOOLS_DIR, assetName); + const binaryExt = plat === "win32" ? ".exe" : ""; + const binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt); + // Download + await downloadFile(downloadUrl, archivePath); + // Extract into a unique temp directory. fd and rg downloads can run concurrently + // during startup, so sharing a fixed directory causes races. + const extractDir = join(TOOLS_DIR, `extract_tmp_${config.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`); + mkdirSync(extractDir, { recursive: true }); + try { + if (assetName.endsWith(".tar.gz")) { + extractTarGzArchive(archivePath, extractDir, assetName); + } + else if (assetName.endsWith(".zip")) { + extractZipArchive(archivePath, extractDir, assetName); + } + else { + throw new Error(`Unsupported archive format: ${assetName}`); + } + // Find the binary in extracted files. Some archives contain files directly + // at root, others nest under a versioned subdirectory. + const binaryFileName = config.binaryName + binaryExt; + const extractedDir = join(extractDir, assetName.replace(/\.(tar\.gz|zip)$/, "")); + const extractedBinaryCandidates = [join(extractedDir, binaryFileName), join(extractDir, binaryFileName)]; + let extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync(candidate)); + if (!extractedBinary) { + extractedBinary = findBinaryRecursively(extractDir, binaryFileName) ?? undefined; + } + if (extractedBinary) { + renameSync(extractedBinary, binaryPath); + } + else { + throw new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`); + } + // Make executable (Unix only) + if (plat !== "win32") { + chmodSync(binaryPath, 0o755); + } + } + finally { + // Cleanup + rmSync(archivePath, { force: true }); + rmSync(extractDir, { recursive: true, force: true }); + } + return binaryPath; +} +// Termux package names for tools +const TERMUX_PACKAGES = { + fd: "fd", + rg: "ripgrep", +}; +// Ensure a tool is available, downloading if necessary +// Returns the path to the tool, or null if unavailable +export async function ensureTool(tool, silent = false) { + const existingPath = getToolPath(tool); + if (existingPath) { + return existingPath; + } + const config = TOOLS[tool]; + if (!config) + return undefined; + if (isOfflineModeEnabled()) { + if (!silent) { + console.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`)); + } + return undefined; + } + // On Android/Termux, Linux binaries don't work due to Bionic libc incompatibility. + // Users must install via pkg. + if (platform() === "android") { + const pkgName = TERMUX_PACKAGES[tool] ?? tool; + if (!silent) { + console.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${pkgName}`)); + } + return undefined; + } + // Tool not found - download it + if (!silent) { + console.log(chalk.dim(`${config.name} not found. Downloading...`)); + } + try { + const path = await downloadTool(tool); + if (!silent) { + console.log(chalk.dim(`${config.name} installed to ${path}`)); + } + return path; + } + catch (e) { + if (!silent) { + console.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`)); + } + return undefined; + } +} +//# sourceMappingURL=tools-manager.js.map \ No newline at end of file diff --git a/dist/utils/tools-manager.js.map b/dist/utils/tools-manager.js.map new file mode 100644 index 0000000..cd54b09 --- /dev/null +++ b/dist/utils/tools-manager.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tools-manager.js","sourceRoot":"","sources":["../../src/utils/tools-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAyB,SAAS,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAC1G,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEnD,MAAM,SAAS,GAAG,SAAS,EAAE,CAAC;AAC9B,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,mBAAmB,GAAG,OAAO,CAAC;AAEpC,SAAS,oBAAoB,GAAY;IACxC,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;IACrC,IAAI,CAAC,KAAK;QAAE,OAAO,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AC,OAAO,CAAC,EAAE,CAAC;QACZ,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,sBAAsB,MAAM,CAAC,IAAI,KAAK,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACvG,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["import chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport { chmodSync, createWriteStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from \"fs\";\nimport { arch, platform } from \"os\";\nimport { join } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { APP_NAME, getBinDir } from \"../config.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst NETWORK_TIMEOUT_MS = 10_000;\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.PI_OFFLINE;\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n\tgetAssetName: (version: string, plat: string, architecture: string) => string | null;\n}\n\nconst TOOLS: Record = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-unknown-linux-gnu.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tif (architecture === \"arm64\") {\n\t\t\t\t\treturn `ripgrep-${version}-aarch64-unknown-linux-gnu.tar.gz`;\n\t\t\t\t}\n\t\t\t\treturn `ripgrep-${version}-x86_64-unknown-linux-musl.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n};\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\" });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: \"fd\" | \"rg\"): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first\n\tconst localPath = join(TOOLS_DIR, config.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"));\n\tif (existsSync(localPath)) {\n\t\treturn localPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n// Fetch latest release version from GitHub\nasync function getLatestVersion(repo: string): Promise {\n\tconst response = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, {\n\t\theaders: { \"User-Agent\": `${APP_NAME}-coding-agent` },\n\t\tsignal: AbortSignal.timeout(NETWORK_TIMEOUT_MS),\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub API error: ${response.status}`);\n\t}\n\n\tconst data = (await response.json()) as { tag_name: string };\n\treturn data.tag_name.replace(/^v/, \"\");\n}\n\n// Download a file from URL\nasync function downloadFile(url: string, dest: string): Promise {\n\tconst response = await fetch(url, {\n\t\tsignal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to download: ${response.status}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst fileStream = createWriteStream(dest);\n\tawait pipeline(Readable.fromWeb(response.body as any), fileStream);\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\" });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\n// Download and install a tool\nasync function downloadTool(tool: \"fd\" | \"rg\"): Promise {\n\tconst config = TOOLS[tool];\n\tif (!config) throw new Error(`Unknown tool: ${tool}`);\n\n\tconst plat = platform();\n\tconst architecture = arch();\n\n\t// Get latest version\n\tlet version = await getLatestVersion(config.repo);\n\tif (tool === \"fd\" && plat === \"darwin\" && architecture === \"x64\") {\n\t\tversion = \"10.3.0\";\n\t}\n\n\t// Get asset name for this platform\n\tconst assetName = config.getAssetName(version, plat, architecture);\n\tif (!assetName) {\n\t\tthrow new Error(`Unsupported platform: ${plat}/${architecture}`);\n\t}\n\n\t// Create tools directory\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\tconst downloadUrl = `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`;\n\tconst archivePath = join(TOOLS_DIR, assetName);\n\tconst binaryExt = plat === \"win32\" ? \".exe\" : \"\";\n\tconst binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);\n\n\t// Download\n\tawait downloadFile(downloadUrl, archivePath);\n\n\t// Extract into a unique temp directory. fd and rg downloads can run concurrently\n\t// during startup, so sharing a fixed directory causes races.\n\tconst extractDir = join(\n\t\tTOOLS_DIR,\n\t\t`extract_tmp_${config.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(extractDir, { recursive: true });\n\n\ttry {\n\t\tif (assetName.endsWith(\".tar.gz\")) {\n\t\t\textractTarGzArchive(archivePath, extractDir, assetName);\n\t\t} else if (assetName.endsWith(\".zip\")) {\n\t\t\textractZipArchive(archivePath, extractDir, assetName);\n\t\t} else {\n\t\t\tthrow new Error(`Unsupported archive format: ${assetName}`);\n\t\t}\n\n\t\t// Find the binary in extracted files. Some archives contain files directly\n\t\t// at root, others nest under a versioned subdirectory.\n\t\tconst binaryFileName = config.binaryName + binaryExt;\n\t\tconst extractedDir = join(extractDir, assetName.replace(/\\.(tar\\.gz|zip)$/, \"\"));\n\t\tconst extractedBinaryCandidates = [join(extractedDir, binaryFileName), join(extractDir, binaryFileName)];\n\t\tlet extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync(candidate));\n\n\t\tif (!extractedBinary) {\n\t\t\textractedBinary = findBinaryRecursively(extractDir, binaryFileName) ?? undefined;\n\t\t}\n\n\t\tif (extractedBinary) {\n\t\t\trenameSync(extractedBinary, binaryPath);\n\t\t} else {\n\t\t\tthrow new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`);\n\t\t}\n\n\t\t// Make executable (Unix only)\n\t\tif (plat !== \"win32\") {\n\t\t\tchmodSync(binaryPath, 0o755);\n\t\t}\n\t} finally {\n\t\t// Cleanup\n\t\trmSync(archivePath, { force: true });\n\t\trmSync(extractDir, { recursive: true, force: true });\n\t}\n\n\treturn binaryPath;\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n};\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or null if unavailable\nexport async function ensureTool(tool: \"fd\" | \"rg\", silent: boolean = false): Promise {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, Linux binaries don't work due to Bionic libc incompatibility.\n\t// Users must install via pkg.\n\tif (platform() === \"android\") {\n\t\tconst pkgName = TERMUX_PACKAGES[tool] ?? tool;\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${pkgName}`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Tool not found - download it\n\tif (!silent) {\n\t\tconsole.log(chalk.dim(`${config.name} not found. Downloading...`));\n\t}\n\n\ttry {\n\t\tconst path = await downloadTool(tool);\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(`${config.name} installed to ${path}`));\n\t\t}\n\t\treturn path;\n\t} catch (e) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`));\n\t\t}\n\t\treturn undefined;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/version-check.d.ts b/dist/utils/version-check.d.ts new file mode 100644 index 0000000..d85e30e --- /dev/null +++ b/dist/utils/version-check.d.ts @@ -0,0 +1,15 @@ +export interface LatestPiRelease { + version: string; + packageName?: string; + note?: string; +} +export declare function comparePackageVersions(leftVersion: string, rightVersion: string): number | undefined; +export declare function isNewerPackageVersion(candidateVersion: string, currentVersion: string): boolean; +export declare function getLatestPiRelease(currentVersion: string, options?: { + timeoutMs?: number; +}): Promise; +export declare function getLatestPiVersion(currentVersion: string, options?: { + timeoutMs?: number; +}): Promise; +export declare function checkForNewPiVersion(currentVersion: string): Promise; +//# sourceMappingURL=version-check.d.ts.map \ No newline at end of file diff --git a/dist/utils/version-check.d.ts.map b/dist/utils/version-check.d.ts.map new file mode 100644 index 0000000..8db4b36 --- /dev/null +++ b/dist/utils/version-check.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"version-check.d.ts","sourceRoot":"","sources":["../../src/utils/version-check.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,eAAe;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAOpG;AAED,wBAAgB,qBAAqB,CAAC,gBAAgB,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,OAAO,CAM/F;AAED,wBAAsB,kBAAkB,CACvC,cAAc,EAAE,MAAM,EACtB,OAAO,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GAClC,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CA4BtC;AAED,wBAAsB,kBAAkB,CACvC,cAAc,EAAE,MAAM,EACtB,OAAO,GAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GAClC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAE7B;AAED,wBAAsB,oBAAoB,CAAC,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAYvG","sourcesContent":["import { compare, valid } from \"semver\";\nimport { getPiUserAgent } from \"./pi-user-agent.ts\";\n\nconst LATEST_VERSION_URL = \"https://pi.dev/api/latest-version\";\nconst DEFAULT_VERSION_CHECK_TIMEOUT_MS = 10000;\n\nexport interface LatestPiRelease {\n\tversion: string;\n\tpackageName?: string;\n\tnote?: string;\n}\n\nexport function comparePackageVersions(leftVersion: string, rightVersion: string): number | undefined {\n\tconst left = valid(leftVersion.trim());\n\tconst right = valid(rightVersion.trim());\n\tif (!left || !right) {\n\t\treturn undefined;\n\t}\n\treturn compare(left, right);\n}\n\nexport function isNewerPackageVersion(candidateVersion: string, currentVersion: string): boolean {\n\tconst comparison = comparePackageVersions(candidateVersion, currentVersion);\n\tif (comparison !== undefined) {\n\t\treturn comparison > 0;\n\t}\n\treturn candidateVersion.trim() !== currentVersion.trim();\n}\n\nexport async function getLatestPiRelease(\n\tcurrentVersion: string,\n\toptions: { timeoutMs?: number } = {},\n): Promise {\n\tif (process.env.PI_OFFLINE) return undefined;\n\n\tconst response = await fetch(LATEST_VERSION_URL, {\n\t\theaders: {\n\t\t\t\"User-Agent\": getPiUserAgent(currentVersion),\n\t\t\taccept: \"application/json\",\n\t\t},\n\t\tsignal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_VERSION_CHECK_TIMEOUT_MS),\n\t});\n\tif (!response.ok) return undefined;\n\n\tconst data = (await response.json()) as {\n\t\tpackageName?: unknown;\n\t\tversion?: unknown;\n\t\tnote?: unknown;\n\t};\n\tif (typeof data.version !== \"string\" || !data.version.trim()) {\n\t\treturn undefined;\n\t}\n\tconst packageName =\n\t\ttypeof data.packageName === \"string\" && data.packageName.trim() ? data.packageName.trim() : undefined;\n\tconst note = typeof data.note === \"string\" && data.note.trim() ? data.note.trim() : undefined;\n\treturn {\n\t\tversion: data.version.trim(),\n\t\tpackageName,\n\t\t...(note ? { note } : {}),\n\t};\n}\n\nexport async function getLatestPiVersion(\n\tcurrentVersion: string,\n\toptions: { timeoutMs?: number } = {},\n): Promise {\n\treturn (await getLatestPiRelease(currentVersion, options))?.version;\n}\n\nexport async function checkForNewPiVersion(currentVersion: string): Promise {\n\tif (process.env.PI_SKIP_VERSION_CHECK) return undefined;\n\n\ttry {\n\t\tconst latestRelease = await getLatestPiRelease(currentVersion);\n\t\tif (latestRelease && isNewerPackageVersion(latestRelease.version, currentVersion)) {\n\t\t\treturn latestRelease;\n\t\t}\n\t\treturn undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/version-check.js b/dist/utils/version-check.js new file mode 100644 index 0000000..1c3bdbd --- /dev/null +++ b/dist/utils/version-check.js @@ -0,0 +1,61 @@ +import { compare, valid } from "semver"; +import { getPiUserAgent } from "./pi-user-agent.js"; +const LATEST_VERSION_URL = "https://pi.dev/api/latest-version"; +const DEFAULT_VERSION_CHECK_TIMEOUT_MS = 10000; +export function comparePackageVersions(leftVersion, rightVersion) { + const left = valid(leftVersion.trim()); + const right = valid(rightVersion.trim()); + if (!left || !right) { + return undefined; + } + return compare(left, right); +} +export function isNewerPackageVersion(candidateVersion, currentVersion) { + const comparison = comparePackageVersions(candidateVersion, currentVersion); + if (comparison !== undefined) { + return comparison > 0; + } + return candidateVersion.trim() !== currentVersion.trim(); +} +export async function getLatestPiRelease(currentVersion, options = {}) { + if (process.env.PI_OFFLINE) + return undefined; + const response = await fetch(LATEST_VERSION_URL, { + headers: { + "User-Agent": getPiUserAgent(currentVersion), + accept: "application/json", + }, + signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_VERSION_CHECK_TIMEOUT_MS), + }); + if (!response.ok) + return undefined; + const data = (await response.json()); + if (typeof data.version !== "string" || !data.version.trim()) { + return undefined; + } + const packageName = typeof data.packageName === "string" && data.packageName.trim() ? data.packageName.trim() : undefined; + const note = typeof data.note === "string" && data.note.trim() ? data.note.trim() : undefined; + return { + version: data.version.trim(), + packageName, + ...(note ? { note } : {}), + }; +} +export async function getLatestPiVersion(currentVersion, options = {}) { + return (await getLatestPiRelease(currentVersion, options))?.version; +} +export async function checkForNewPiVersion(currentVersion) { + if (process.env.PI_SKIP_VERSION_CHECK) + return undefined; + try { + const latestRelease = await getLatestPiRelease(currentVersion); + if (latestRelease && isNewerPackageVersion(latestRelease.version, currentVersion)) { + return latestRelease; + } + return undefined; + } + catch { + return undefined; + } +} +//# sourceMappingURL=version-check.js.map \ No newline at end of file diff --git a/dist/utils/version-check.js.map b/dist/utils/version-check.js.map new file mode 100644 index 0000000..57a9359 --- /dev/null +++ b/dist/utils/version-check.js.map @@ -0,0 +1 @@ +{"version":3,"file":"version-check.js","sourceRoot":"","sources":["../../src/utils/version-check.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,MAAM,kBAAkB,GAAG,mCAAmC,CAAC;AAC/D,MAAM,gCAAgC,GAAG,KAAK,CAAC;AAQ/C,MAAM,UAAU,sBAAsB,CAAC,WAAmB,EAAE,YAAoB,EAAsB;IACrG,MAAM,IAAI,GAAG,KAAK,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,CAAC;IACvC,MAAM,KAAK,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC,CAAC;IACzC,IAAI,CAAC,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;QACrB,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,OAAO,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;AAAA,CAC5B;AAED,MAAM,UAAU,qBAAqB,CAAC,gBAAwB,EAAE,cAAsB,EAAW;IAChG,MAAM,UAAU,GAAG,sBAAsB,CAAC,gBAAgB,EAAE,cAAc,CAAC,CAAC;IAC5E,IAAI,UAAU,KAAK,SAAS,EAAE,CAAC;QAC9B,OAAO,UAAU,GAAG,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,gBAAgB,CAAC,IAAI,EAAE,KAAK,cAAc,CAAC,IAAI,EAAE,CAAC;AAAA,CACzD;AAED,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACvC,cAAsB,EACtB,OAAO,GAA2B,EAAE,EACG;IACvC,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU;QAAE,OAAO,SAAS,CAAC;IAE7C,MAAM,QAAQ,GAAG,MAAM,KAAK,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,CACpE;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,cAAsB,EAAwC;IACxG,IAAI,OAAO,CAAC,GAAG,CAAC,qBAAqB;QAAE,OAAO,SAAS,CAAC;IAExD,IAAI,CAAC;QACJ,MAAM,aAAa,GAAG,MAAM,kBAAkB,CAAC,cAAc,CAAC,CAAC;QAC/D,IAAI,aAAa,IAAI,qBAAqB,CAAC,aAAa,CAAC,OAAO,EAAE,cAAc,CAAC,EAAE,CAAC;YACnF,OAAO,aAAa,CAAC;QACtB,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["import { compare, valid } from \"semver\";\nimport { getPiUserAgent } from \"./pi-user-agent.ts\";\n\nconst LATEST_VERSION_URL = \"https://pi.dev/api/latest-version\";\nconst DEFAULT_VERSION_CHECK_TIMEOUT_MS = 10000;\n\nexport interface LatestPiRelease {\n\tversion: string;\n\tpackageName?: string;\n\tnote?: string;\n}\n\nexport function comparePackageVersions(leftVersion: string, rightVersion: string): number | undefined {\n\tconst left = valid(leftVersion.trim());\n\tconst right = valid(rightVersion.trim());\n\tif (!left || !right) {\n\t\treturn undefined;\n\t}\n\treturn compare(left, right);\n}\n\nexport function isNewerPackageVersion(candidateVersion: string, currentVersion: string): boolean {\n\tconst comparison = comparePackageVersions(candidateVersion, currentVersion);\n\tif (comparison !== undefined) {\n\t\treturn comparison > 0;\n\t}\n\treturn candidateVersion.trim() !== currentVersion.trim();\n}\n\nexport async function getLatestPiRelease(\n\tcurrentVersion: string,\n\toptions: { timeoutMs?: number } = {},\n): Promise {\n\tif (process.env.PI_OFFLINE) return undefined;\n\n\tconst response = await fetch(LATEST_VERSION_URL, {\n\t\theaders: {\n\t\t\t\"User-Agent\": getPiUserAgent(currentVersion),\n\t\t\taccept: \"application/json\",\n\t\t},\n\t\tsignal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_VERSION_CHECK_TIMEOUT_MS),\n\t});\n\tif (!response.ok) return undefined;\n\n\tconst data = (await response.json()) as {\n\t\tpackageName?: unknown;\n\t\tversion?: unknown;\n\t\tnote?: unknown;\n\t};\n\tif (typeof data.version !== \"string\" || !data.version.trim()) {\n\t\treturn undefined;\n\t}\n\tconst packageName =\n\t\ttypeof data.packageName === \"string\" && data.packageName.trim() ? data.packageName.trim() : undefined;\n\tconst note = typeof data.note === \"string\" && data.note.trim() ? data.note.trim() : undefined;\n\treturn {\n\t\tversion: data.version.trim(),\n\t\tpackageName,\n\t\t...(note ? { note } : {}),\n\t};\n}\n\nexport async function getLatestPiVersion(\n\tcurrentVersion: string,\n\toptions: { timeoutMs?: number } = {},\n): Promise {\n\treturn (await getLatestPiRelease(currentVersion, options))?.version;\n}\n\nexport async function checkForNewPiVersion(currentVersion: string): Promise {\n\tif (process.env.PI_SKIP_VERSION_CHECK) return undefined;\n\n\ttry {\n\t\tconst latestRelease = await getLatestPiRelease(currentVersion);\n\t\tif (latestRelease && isNewerPackageVersion(latestRelease.version, currentVersion)) {\n\t\t\treturn latestRelease;\n\t\t}\n\t\treturn undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/windows-self-update.d.ts b/dist/utils/windows-self-update.d.ts new file mode 100644 index 0000000..f8a2e32 --- /dev/null +++ b/dist/utils/windows-self-update.d.ts @@ -0,0 +1,3 @@ +export declare function cleanupWindowsSelfUpdateQuarantine(packageDir: string): void; +export declare function quarantineWindowsNativeDependencies(packageDir: string): void; +//# sourceMappingURL=windows-self-update.d.ts.map \ No newline at end of file diff --git a/dist/utils/windows-self-update.d.ts.map b/dist/utils/windows-self-update.d.ts.map new file mode 100644 index 0000000..9994edb --- /dev/null +++ b/dist/utils/windows-self-update.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"windows-self-update.d.ts","sourceRoot":"","sources":["../../src/utils/windows-self-update.ts"],"names":[],"mappings":"AAiDA,wBAAgB,kCAAkC,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAU3E;AAED,wBAAgB,mCAAmC,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAsB5E","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { copyFileSync, existsSync, mkdirSync, renameSync, rmSync } from \"node:fs\";\nimport { basename, dirname, join, relative, resolve, toNamespacedPath } from \"node:path\";\nimport { getCwdRelativePath } from \"./paths.ts\";\n\nconst QUARANTINE_DIR_NAME = \".pi-native-quarantine\";\n\nfunction normalizePath(path: string): string {\n\treturn toNamespacedPath(resolve(path));\n}\n\nfunction getQuarantineRoot(packageDir: string): string | undefined {\n\tlet current = resolve(packageDir);\n\twhile (true) {\n\t\tif (basename(current).toLowerCase() === \"node_modules\") {\n\t\t\treturn join(current, QUARANTINE_DIR_NAME);\n\t\t}\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) {\n\t\t\treturn undefined;\n\t\t}\n\t\tcurrent = parent;\n\t}\n}\n\nfunction getLoadedSharedObjectsInPackageDir(packageDir: string): string[] {\n\tconst sharedObjects = (process.report.getReport() as { sharedObjects?: unknown }).sharedObjects;\n\tif (!Array.isArray(sharedObjects)) {\n\t\treturn [];\n\t}\n\n\tconst root = normalizePath(packageDir).toLowerCase();\n\tconst seen = new Set();\n\tconst loadedFiles: string[] = [];\n\tfor (const value of sharedObjects) {\n\t\tif (typeof value !== \"string\") {\n\t\t\tcontinue;\n\t\t}\n\t\tconst filePath = normalizePath(value);\n\t\tconst comparisonPath = filePath.toLowerCase();\n\t\tif (getCwdRelativePath(comparisonPath, root) === undefined || seen.has(comparisonPath)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(comparisonPath);\n\t\tloadedFiles.push(filePath);\n\t}\n\treturn loadedFiles;\n}\n\nexport function cleanupWindowsSelfUpdateQuarantine(packageDir: string): void {\n\tconst quarantineRoot = getQuarantineRoot(packageDir);\n\tif (!quarantineRoot) {\n\t\treturn;\n\t}\n\ttry {\n\t\trmSync(quarantineRoot, { recursive: true, force: true });\n\t} catch {\n\t\t// A previous pi process may still be exiting and holding a native addon.\n\t}\n}\n\nexport function quarantineWindowsNativeDependencies(packageDir: string): void {\n\tconst resolvedPackageDir = normalizePath(packageDir);\n\tconst quarantineRoot = getQuarantineRoot(resolvedPackageDir);\n\tif (!quarantineRoot) {\n\t\treturn;\n\t}\n\n\tconst loadedFiles = getLoadedSharedObjectsInPackageDir(resolvedPackageDir);\n\tif (loadedFiles.length === 0) {\n\t\treturn;\n\t}\n\n\tconst quarantineRunDir = join(quarantineRoot, `${Date.now()}-${process.pid}-${randomUUID()}`);\n\tfor (const loadedFile of loadedFiles) {\n\t\tif (!existsSync(loadedFile)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst quarantinePath = join(quarantineRunDir, relative(resolvedPackageDir, loadedFile));\n\t\tmkdirSync(dirname(quarantinePath), { recursive: true });\n\t\trenameSync(loadedFile, quarantinePath);\n\t\tcopyFileSync(quarantinePath, loadedFile);\n\t}\n}\n"]} \ No newline at end of file diff --git a/dist/utils/windows-self-update.js b/dist/utils/windows-self-update.js new file mode 100644 index 0000000..a2487f9 --- /dev/null +++ b/dist/utils/windows-self-update.js @@ -0,0 +1,77 @@ +import { randomUUID } from "node:crypto"; +import { copyFileSync, existsSync, mkdirSync, renameSync, rmSync } from "node:fs"; +import { basename, dirname, join, relative, resolve, toNamespacedPath } from "node:path"; +import { getCwdRelativePath } from "./paths.js"; +const QUARANTINE_DIR_NAME = ".pi-native-quarantine"; +function normalizePath(path) { + return toNamespacedPath(resolve(path)); +} +function getQuarantineRoot(packageDir) { + let current = resolve(packageDir); + while (true) { + if (basename(current).toLowerCase() === "node_modules") { + return join(current, QUARANTINE_DIR_NAME); + } + const parent = dirname(current); + if (parent === current) { + return undefined; + } + current = parent; + } +} +function getLoadedSharedObjectsInPackageDir(packageDir) { + const sharedObjects = process.report.getReport().sharedObjects; + if (!Array.isArray(sharedObjects)) { + return []; + } + const root = normalizePath(packageDir).toLowerCase(); + const seen = new Set(); + const loadedFiles = []; + for (const value of sharedObjects) { + if (typeof value !== "string") { + continue; + } + const filePath = normalizePath(value); + const comparisonPath = filePath.toLowerCase(); + if (getCwdRelativePath(comparisonPath, root) === undefined || seen.has(comparisonPath)) { + continue; + } + seen.add(comparisonPath); + loadedFiles.push(filePath); + } + return loadedFiles; +} +export function cleanupWindowsSelfUpdateQuarantine(packageDir) { + const quarantineRoot = getQuarantineRoot(packageDir); + if (!quarantineRoot) { + return; + } + try { + rmSync(quarantineRoot, { recursive: true, force: true }); + } + catch { + // A previous pi process may still be exiting and holding a native addon. + } +} +export function quarantineWindowsNativeDependencies(packageDir) { + const resolvedPackageDir = normalizePath(packageDir); + const quarantineRoot = getQuarantineRoot(resolvedPackageDir); + if (!quarantineRoot) { + return; + } + const loadedFiles = getLoadedSharedObjectsInPackageDir(resolvedPackageDir); + if (loadedFiles.length === 0) { + return; + } + const quarantineRunDir = join(quarantineRoot, `${Date.now()}-${process.pid}-${randomUUID()}`); + for (const loadedFile of loadedFiles) { + if (!existsSync(loadedFile)) { + continue; + } + const quarantinePath = join(quarantineRunDir, relative(resolvedPackageDir, loadedFile)); + mkdirSync(dirname(quarantinePath), { recursive: true }); + renameSync(loadedFile, quarantinePath); + copyFileSync(quarantinePath, loadedFile); + } +} +//# sourceMappingURL=windows-self-update.js.map \ No newline at end of file diff --git a/dist/utils/windows-self-update.js.map b/dist/utils/windows-self-update.js.map new file mode 100644 index 0000000..b5e9cdc --- /dev/null +++ b/dist/utils/windows-self-update.js.map @@ -0,0 +1 @@ +{"version":3,"file":"windows-self-update.js","sourceRoot":"","sources":["../../src/utils/windows-self-update.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAClF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI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9F,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE,CAAC;QACtC,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAC7B,SAAS;QACV,CAAC;QACD,MAAM,cAAc,GAAG,IAAI,CAAC,gBAAgB,EAAE,QAAQ,CAAC,kBAAkB,EAAE,UAAU,CAAC,CAAC,CAAC;QACxF,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACxD,UAAU,CAAC,UAAU,EAAE,cAAc,CAAC,CAAC;QACvC,YAAY,CAAC,cAAc,EAAE,UAAU,CAAC,CAAC;IAC1C,CAAC;AAAA,CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { copyFileSync, existsSync, mkdirSync, renameSync, rmSync } from \"node:fs\";\nimport { basename, dirname, join, relative, resolve, toNamespacedPath } from \"node:path\";\nimport { getCwdRelativePath } from \"./paths.ts\";\n\nconst QUARANTINE_DIR_NAME = \".pi-native-quarantine\";\n\nfunction normalizePath(path: string): string {\n\treturn toNamespacedPath(resolve(path));\n}\n\nfunction getQuarantineRoot(packageDir: string): string | undefined {\n\tlet current = resolve(packageDir);\n\twhile (true) {\n\t\tif (basename(current).toLowerCase() === \"node_modules\") {\n\t\t\treturn join(current, QUARANTINE_DIR_NAME);\n\t\t}\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) {\n\t\t\treturn undefined;\n\t\t}\n\t\tcurrent = parent;\n\t}\n}\n\nfunction getLoadedSharedObjectsInPackageDir(packageDir: string): string[] {\n\tconst sharedObjects = (process.report.getReport() as { sharedObjects?: unknown }).sharedObjects;\n\tif (!Array.isArray(sharedObjects)) {\n\t\treturn [];\n\t}\n\n\tconst root = normalizePath(packageDir).toLowerCase();\n\tconst seen = new Set();\n\tconst loadedFiles: string[] = [];\n\tfor (const value of sharedObjects) {\n\t\tif (typeof value !== \"string\") {\n\t\t\tcontinue;\n\t\t}\n\t\tconst filePath = normalizePath(value);\n\t\tconst comparisonPath = filePath.toLowerCase();\n\t\tif (getCwdRelativePath(comparisonPath, root) === undefined || seen.has(comparisonPath)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(comparisonPath);\n\t\tloadedFiles.push(filePath);\n\t}\n\treturn loadedFiles;\n}\n\nexport function cleanupWindowsSelfUpdateQuarantine(packageDir: string): void {\n\tconst quarantineRoot = getQuarantineRoot(packageDir);\n\tif (!quarantineRoot) {\n\t\treturn;\n\t}\n\ttry {\n\t\trmSync(quarantineRoot, { recursive: true, force: true });\n\t} catch {\n\t\t// A previous pi process may still be exiting and holding a native addon.\n\t}\n}\n\nexport function quarantineWindowsNativeDependencies(packageDir: string): void {\n\tconst resolvedPackageDir = normalizePath(packageDir);\n\tconst quarantineRoot = getQuarantineRoot(resolvedPackageDir);\n\tif (!quarantineRoot) {\n\t\treturn;\n\t}\n\n\tconst loadedFiles = getLoadedSharedObjectsInPackageDir(resolvedPackageDir);\n\tif (loadedFiles.length === 0) {\n\t\treturn;\n\t}\n\n\tconst quarantineRunDir = join(quarantineRoot, `${Date.now()}-${process.pid}-${randomUUID()}`);\n\tfor (const loadedFile of loadedFiles) {\n\t\tif (!existsSync(loadedFile)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst quarantinePath = join(quarantineRunDir, relative(resolvedPackageDir, loadedFile));\n\t\tmkdirSync(dirname(quarantinePath), { recursive: true });\n\t\trenameSync(loadedFile, quarantinePath);\n\t\tcopyFileSync(quarantinePath, loadedFile);\n\t}\n}\n"]} \ No newline at end of file diff --git a/docs/compaction.md b/docs/compaction.md new file mode 100644 index 0000000..b47a66a --- /dev/null +++ b/docs/compaction.md @@ -0,0 +1,401 @@ +# Compaction & Branch Summarization + +LLMs have limited context windows. When conversations grow too long, pi uses compaction to summarize older content while preserving recent work. This page covers both auto-compaction and branch summarization. + +**Source files** ([pi-mono](https://github.com/earendil-works/pi-mono)): +- [`packages/coding-agent/src/core/compaction/compaction.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/compaction.ts) - Auto-compaction logic +- [`packages/coding-agent/src/core/compaction/branch-summarization.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/branch-summarization.ts) - Branch summarization +- [`packages/coding-agent/src/core/compaction/utils.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/utils.ts) - Shared utilities (file tracking, serialization) +- [`packages/coding-agent/src/core/session-manager.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/session-manager.ts) - Entry types (`CompactionEntry`, `BranchSummaryEntry`) +- [`packages/coding-agent/src/core/extensions/types.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/extensions/types.ts) - Extension event types + +For TypeScript definitions in your project, inspect `node_modules/@earendil-works/pi-coding-agent/dist/`. + +## Overview + +Pi has two summarization mechanisms: + +| Mechanism | Trigger | Purpose | +|-----------|---------|---------| +| Compaction | Context exceeds threshold, or `/compact` | Summarize old messages to free up context | +| Branch summarization | `/tree` navigation | Preserve context when switching branches | + +Both use the same structured summary format and track file operations cumulatively. Compaction and branch-summary requests use fresh routing session IDs and, where supported by the provider, disable prompt-cache writes because these one-off prompts are unlikely to be reused. + +## Compaction + +### When It Triggers + +Auto-compaction triggers when: + +``` +contextTokens > contextWindow - reserveTokens +``` + +By default, `reserveTokens` is 16384 tokens (configurable in `~/.pi/agent/settings.json` or `/.pi/settings.json`). This leaves room for the LLM's response. + +You can also trigger manually with `/compact [instructions]`, where optional instructions focus the summary. + +### How It Works + +1. **Find cut point**: Walk backwards from newest message, accumulating token estimates until `keepRecentTokens` (default 20k, configurable in `~/.pi/agent/settings.json` or `/.pi/settings.json`) is reached +2. **Extract messages**: Collect messages from the previous kept boundary (or session start) up to the cut point +3. **Generate summary**: Call LLM to summarize with structured format, passing the previous summary as iterative context when present +4. **Append entry**: Save `CompactionEntry` with summary and `firstKeptEntryId` +5. **Reload**: Session reloads, using summary + messages from `firstKeptEntryId` onwards + +``` +Before compaction: + + entry: 0 1 2 3 4 5 6 7 8 9 + ┌─────┬─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┐ + │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│ + └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┘ + └────────┬───────┘ └──────────────┬──────────────┘ + messagesToSummarize kept messages + ↑ + firstKeptEntryId (entry 4) + +After compaction (new entry appended): + + entry: 0 1 2 3 4 5 6 7 8 9 10 + ┌─────┬─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬─────┐ + │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│ cmp │ + └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┴─────┘ + └──────────┬──────┘ └──────────────────────┬───────────────────┘ + not sent to LLM sent to LLM + ↑ + starts from firstKeptEntryId + +What the LLM sees: + + ┌────────┬─────────┬─────┬─────┬──────┬──────┬─────┬──────┐ + │ system │ summary │ usr │ ass │ tool │ tool │ ass │ tool │ + └────────┴─────────┴─────┴─────┴──────┴──────┴─────┴──────┘ + ↑ ↑ └─────────────────┬────────────────┘ + prompt from cmp messages from firstKeptEntryId +``` + +On repeated compactions, the summarized span starts at the previous compaction's kept boundary (`firstKeptEntryId`), not at the compaction entry itself, falling back to the entry after the previous compaction if that kept entry cannot be found in the path. This preserves messages that survived the earlier compaction by including them in the next summarization pass as well. Pi also recalculates `tokensBefore` from the rebuilt session context before writing the new `CompactionEntry`, so the token count reflects the actual pre-compaction context being replaced. + +### Split Turns + +A "turn" starts with a user message and includes all assistant responses and tool calls until the next user message. Normally, compaction cuts at turn boundaries. + +When a single turn exceeds `keepRecentTokens`, the cut point lands mid-turn at an assistant message. This is a "split turn": + +``` +Split turn (one huge turn exceeds budget): + + entry: 0 1 2 3 4 5 6 7 8 + ┌─────┬─────┬─────┬──────┬─────┬──────┬──────┬─────┬──────┐ + │ hdr │ usr │ ass │ tool │ ass │ tool │ tool │ ass │ tool │ + └─────┴─────┴─────┴──────┴─────┴──────┴──────┴─────┴──────┘ + ↑ ↑ + turnStartIndex = 1 firstKeptEntryId = 7 + │ │ + └──── turnPrefixMessages (1-6) ───────┘ + └── kept (7-8) + + isSplitTurn = true + messagesToSummarize = [] (no complete turns before) + turnPrefixMessages = [usr, ass, tool, ass, tool, tool] +``` + +For split turns, pi generates two summaries and merges them: +1. **History summary**: Previous context (if any) +2. **Turn prefix summary**: The early part of the split turn + +### Cut Point Rules + +Valid cut points are: +- User messages +- Assistant messages +- BashExecution messages +- Custom messages (custom_message, branch_summary) + +Never cut at tool results (they must stay with their tool call). + +### CompactionEntry Structure + +Defined in [`session-manager.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/session-manager.ts): + +```typescript +interface CompactionEntry { + type: "compaction"; + id: string; + parentId: string; + timestamp: number; + summary: string; + firstKeptEntryId: string; + tokensBefore: number; + usage?: Usage; // LLM usage that generated the summary + fromHook?: boolean; // true if provided by extension (legacy field name) + details?: T; // implementation-specific data +} + +// Default compaction uses this for details (from compaction.ts): +interface CompactionDetails { + readFiles: string[]; + modifiedFiles: string[]; +} +``` + +Extensions can store any JSON-serializable data in `details`. The default compaction tracks file operations, but custom extension implementations can use their own structure. Generated and extension-provided summaries store their LLM `usage` when available so session totals include summarization work. + +See [`prepareCompaction()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/compaction.ts) and [`compact()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/compaction.ts) for the implementation. For direct programmatic summarization, `generateSummary()` returns the summary text and `generateSummaryWithUsage()` returns `{ text, usage }`. + +## Branch Summarization + +### When It Triggers + +When you use `/tree` to navigate to a different branch, pi offers to summarize the work you're leaving. This injects context from the left branch into the new branch. + +### How It Works + +1. **Find common ancestor**: Deepest node shared by old and new positions +2. **Collect entries**: Walk from old leaf back to common ancestor +3. **Prepare with budget**: Include messages up to token budget (newest first) +4. **Generate summary**: Call LLM with structured format +5. **Append entry**: Save `BranchSummaryEntry` at navigation point + +``` +Tree before navigation: + + ┌─ B ─ C ─ D (old leaf, being abandoned) + A ───┤ + └─ E ─ F (target) + +Common ancestor: A +Entries to summarize: B, C, D + +After navigation with summary: + + ┌─ B ─ C ─ D ─ [summary of B,C,D] + A ───┤ + └─ E ─ F (new leaf) +``` + +### Cumulative File Tracking + +Both compaction and branch summarization track files cumulatively. When generating a summary, pi extracts file operations from: +- Tool calls in the messages being summarized +- Previous compaction or branch summary `details` (if any) + +This means file tracking accumulates across multiple compactions or nested branch summaries, preserving the full history of read and modified files. + +### BranchSummaryEntry Structure + +Defined in [`session-manager.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/session-manager.ts): + +```typescript +interface BranchSummaryEntry { + type: "branch_summary"; + id: string; + parentId: string; + timestamp: number; + summary: string; + fromId: string; // Entry we navigated from + usage?: Usage; // LLM usage that generated the summary + fromHook?: boolean; // true if provided by extension (legacy field name) + details?: T; // implementation-specific data +} + +// Default branch summarization uses this for details (from branch-summarization.ts): +interface BranchSummaryDetails { + readFiles: string[]; + modifiedFiles: string[]; +} +``` + +Same as compaction, extensions can store custom data in `details`. + +See [`collectEntriesForBranchSummary()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/branch-summarization.ts), [`prepareBranchEntries()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/branch-summarization.ts), and [`generateBranchSummary()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/branch-summarization.ts) for the implementation. + +## Summary Format + +Both compaction and branch summarization use the same structured format: + +```markdown +## Goal +[What the user is trying to accomplish] + +## Constraints & Preferences +- [Requirements mentioned by user] + +## Progress +### Done +- [x] [Completed tasks] + +### In Progress +- [ ] [Current work] + +### Blocked +- [Issues, if any] + +## Key Decisions +- **[Decision]**: [Rationale] + +## Next Steps +1. [What should happen next] + +## Critical Context +- [Data needed to continue] + + +path/to/file1.ts +path/to/file2.ts + + + +path/to/changed.ts + +``` + +### Message Serialization + +Before summarization, messages are serialized to text via [`serializeConversation()`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/utils.ts): + +``` +[User]: What they said +[Assistant thinking]: Internal reasoning +[Assistant]: Response text +[Assistant tool calls]: read(path="foo.ts"); edit(path="bar.ts", ...) +[Tool result]: Output from tool +``` + +This prevents the model from treating it as a conversation to continue. + +Tool results are truncated to 2000 characters during serialization. Content beyond that limit is replaced with a marker indicating how many characters were truncated. This keeps summarization requests within reasonable token budgets, since tool results (especially from `read` and `bash`) are typically the largest contributors to context size. + +## Custom Summarization via Extensions + +Extensions can intercept and customize both compaction and branch summarization. See [`extensions/types.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/extensions/types.ts) for event type definitions. + +### session_before_compact + +Fired before auto-compaction or `/compact`. Can cancel or provide custom summary. See `SessionBeforeCompactEvent` and `CompactionPreparation` in the types file. + +```typescript +pi.on("session_before_compact", async (event, ctx) => { + const { preparation, branchEntries, customInstructions, reason, willRetry, signal } = event; + + // preparation.messagesToSummarize - messages to summarize + // preparation.turnPrefixMessages - split turn prefix (if isSplitTurn) + // preparation.previousSummary - previous compaction summary + // preparation.fileOps - extracted file operations + // preparation.tokensBefore - context tokens before compaction + // preparation.firstKeptEntryId - where kept messages start + // preparation.settings - compaction settings + + // branchEntries - all entries on current branch (for custom state) + // reason - "manual" (/compact), "threshold", or "overflow" + // willRetry - whether the aborted turn is retried after compaction (overflow recovery) + // signal - AbortSignal (pass to LLM calls) + + // Cancel: + return { cancel: true }; + + // Custom summary: + return { + compaction: { + summary: "Your summary...", + firstKeptEntryId: preparation.firstKeptEntryId, + tokensBefore: preparation.tokensBefore, + // usage: summaryResponse.usage, // Optional; included in session totals + details: { /* custom data */ }, + } + }; +}); +``` + +#### Converting Messages to Text + +To generate a summary with your own model, convert messages to text using `serializeConversation`: + +```typescript +import { convertToLlm, serializeConversation } from "@earendil-works/pi-coding-agent"; + +pi.on("session_before_compact", async (event, ctx) => { + const { preparation } = event; + + // Convert AgentMessage[] to Message[], then serialize to text + const conversationText = serializeConversation( + convertToLlm(preparation.messagesToSummarize) + ); + // Returns: + // [User]: message text + // [Assistant thinking]: thinking content + // [Assistant]: response text + // [Assistant tool calls]: read(path="..."); bash(command="...") + // [Tool result]: output text + + // Now send to your model for summarization + const { summary, usage } = await myModel.summarize(conversationText); + + return { + compaction: { + summary, + firstKeptEntryId: preparation.firstKeptEntryId, + tokensBefore: preparation.tokensBefore, + usage, + } + }; +}); +``` + +See [custom-compaction.ts](../examples/extensions/custom-compaction.ts) for a complete example using a different model. + +### session_before_tree + +Fired before `/tree` navigation. Always fires regardless of whether user chose to summarize. Can cancel navigation or provide custom summary. + +```typescript +pi.on("session_before_tree", async (event, ctx) => { + const { preparation, signal } = event; + + // preparation.targetId - where we're navigating to + // preparation.oldLeafId - current position (being abandoned) + // preparation.commonAncestorId - shared ancestor + // preparation.entriesToSummarize - entries that would be summarized + // preparation.userWantsSummary - whether user chose to summarize + + // Cancel navigation entirely: + return { cancel: true }; + + // Provide custom summary (only used if userWantsSummary is true): + if (preparation.userWantsSummary) { + return { + summary: { + summary: "Your summary...", + // usage: summaryResponse.usage, // Optional; included in session totals + details: { /* custom data */ }, + } + }; + } +}); +``` + +See `SessionBeforeTreeEvent` and `TreePreparation` in the types file. + +## Settings + +Configure compaction in `~/.pi/agent/settings.json` or `/.pi/settings.json`: + +```json +{ + "compaction": { + "enabled": true, + "reserveTokens": 16384, + "keepRecentTokens": 20000 + } +} +``` + +| Setting | Default | Description | +|---------|---------|-------------| +| `enabled` | `true` | Enable auto-compaction | +| `reserveTokens` | `16384` | Tokens to reserve for LLM response | +| `keepRecentTokens` | `20000` | Recent tokens to keep (not summarized) | + +Disable auto-compaction with `"enabled": false`. You can still compact manually with `/compact`. diff --git a/docs/containerization.md b/docs/containerization.md new file mode 100644 index 0000000..33f2df3 --- /dev/null +++ b/docs/containerization.md @@ -0,0 +1,111 @@ +# Containerization + +Pi runs with all permissions by default, but in some cases, you will want to have more control over what directories Pi can write to and which accesses it has. + +There are two general options. You can either +1. run the whole `pi` process inside an isolated environment, or +2. run `pi` on the host and route tool execution into an isolated environment. + +## Choose a pattern + +| Pattern | What is isolated | Best for | Notes | +| --- | --- | --- | --- | +| Gondolin extension | Built-in tools and `!` commands | Local micro-VM isolation while keeping auth on host | See [`examples/extensions/gondolin/`](../examples/extensions/gondolin/). | +| Plain Docker | Whole `pi` process in a local container | Simple local isolation | Provider API keys enter the container. | +| OpenShell | Whole `pi` process in a policy-controlled sandbox | Local or remote managed sandbox | Requires an OpenShell gateway | + +Extensions run wherever the `pi` process runs. If you run host `pi` with a tool-routing extension, other custom extension tools still run on the host unless they also delegate their operations. + +## Gondolin + +[Gondolin](https://github.com/earendil-works/gondolin) is a local Linux micro-VM. +Use the [example extension](../examples/extensions/gondolin) when you want `pi` on the host but all built-in tools routed into the VM. + +Setup: + +```bash +cp -R packages/coding-agent/examples/extensions/gondolin ~/.pi/agent/extensions/gondolin +cd ~/.pi/agent/extensions/gondolin +npm install --ignore-scripts +``` + +Run from the project you want mounted: + +```bash +cd /path/to/project +pi -e ~/.pi/agent/extensions/gondolin +``` + +The extension mounts the host cwd at `/workspace` in the VM and overrides `read`, `write`, `edit`, `bash`, `grep`, `find`, and `ls`. +User `!` commands are routed into the VM, as well. +File changes under `/workspace` write through to the host. + +Requirements: Node.js >= 23.6.0 for `@earendil-works/gondolin`, plus QEMU (requires installation through your package manager). + +## Plain Docker + +Run the whole `pi` process in Docker when you want the simplest local container boundary. + +`Dockerfile.pi`: + +```dockerfile +FROM node:24-bookworm-slim + +RUN apt-get update \ + && apt-get install -y --no-install-recommends bash ca-certificates git ripgrep \ + && rm -rf /var/lib/apt/lists/* +RUN npm install -g --ignore-scripts @earendil-works/pi-coding-agent + +WORKDIR /workspace +ENTRYPOINT ["pi"] +``` + +Build and run: + +```bash +docker build -t pi-sandbox -f Dockerfile.pi . + +docker run --rm -it \ + -e ANTHROPIC_API_KEY \ + -v "$PWD:/workspace" \ + -v pi-agent-home:/root/.pi/agent \ + pi-sandbox +``` + +The `-v "$PWD:/workspace"` mounts your current directory into the container at /workspace such that reads and writes in `/workspace` inside Docker directly affect your host files, like in the Gondolin example. + +Use a named volume for `/root/.pi/agent` if you want container-local settings and sessions. Mounting your host `~/.pi/agent` exposes host auth and session files to the container. + +## OpenShell + +Use [NVIDIA OpenShell](https://docs.nvidia.com/openshell/about/overview) when you want a policy-controlled sandbox with filesystem, process, network, credential, and inference controls. +OpenShell can run sandboxes through a local gateway backed by Docker, Podman, or a VM runtime, or through a remote Kubernetes gateway. + +Every sandbox requires an active gateway. +Register and select one before creating a sandbox: + +```bash +openshell gateway add --name +openshell gateway select +``` + +Launch `pi` inside an OpenShell sandbox: + +```bash +openshell sandbox create --name pi-sandbox --from pi -- pi +``` + +In this pattern, the whole `pi` process runs inside the sandbox. +Built-in tools, `!` commands, and extension tools execute inside the OpenShell boundary. + +If the gateway is remote, project files are not bind-mounted from the host, meaning writes in the sandbox are not reflected on your machine. +Clone the repository inside the sandbox or use OpenShell file transfer commands: + +```bash +openshell sandbox upload pi-sandbox ./repo /workspace +openshell sandbox download pi-sandbox /workspace/repo ./repo-out +``` + +OpenShell providers can keep raw model API keys outside the sandbox. +When inference routing is configured, code inside the sandbox can call `https://inference.local`, and the gateway injects the configured provider credentials upstream. +Configure Pi to use the corresponding OpenAI-compatible or Anthropic-compatible endpoint if you want model traffic to use this route. diff --git a/docs/custom-provider.md b/docs/custom-provider.md new file mode 100644 index 0000000..652e234 --- /dev/null +++ b/docs/custom-provider.md @@ -0,0 +1,772 @@ +# Custom Providers + +Extensions can register custom model providers via `pi.registerProvider()`. This enables: + +- **Proxies** - Route requests through corporate proxies or API gateways +- **Custom endpoints** - Use self-hosted or private model deployments +- **OAuth/SSO** - Add authentication flows for enterprise providers +- **Custom APIs** - Implement streaming for non-standard LLM APIs + +## Example Extensions + +See these complete provider examples: + +- [`examples/extensions/custom-provider-anthropic/`](../examples/extensions/custom-provider-anthropic/) +- [`examples/extensions/custom-provider-gitlab-duo/`](../examples/extensions/custom-provider-gitlab-duo/) + +## Table of Contents + +- [Example Extensions](#example-extensions) +- [Quick Reference](#quick-reference) +- [Override Existing Provider](#override-existing-provider) +- [Register New Provider](#register-new-provider) +- [Unregister Provider](#unregister-provider) +- [OAuth Support](#oauth-support) +- [Custom Streaming API](#custom-streaming-api) +- [Context Overflow Errors](#context-overflow-errors) +- [Testing Your Implementation](#testing-your-implementation) +- [Config Reference](#config-reference) +- [Model Definition Reference](#model-definition-reference) + +## Quick Reference + +Extensions can register either a complete pi-ai `Provider` or use the legacy provider-config form. Prefer a complete provider when custom authentication, filtering, refresh, or streaming behavior is required. Pi composes `models.json` overrides above registered native providers. + +```typescript +import { createProvider, openAICompletionsApi } from "@earendil-works/pi-ai"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.registerProvider(createProvider({ + id: "native-local", + name: "Native Local", + baseUrl: "http://localhost:8080/v1", + auth: { + apiKey: { + name: "Local server API key", + async login(interaction) { + return { + type: "api_key", + key: await interaction.prompt({ type: "secret", message: "API key" }) + }; + }, + async resolve({ credential }) { + return credential?.key + ? { auth: { apiKey: credential.key }, source: "stored API key" } + : undefined; + } + } + }, + models: [], + api: openAICompletionsApi() + })); + + // Legacy provider-config form: + // Override baseUrl for existing provider + pi.registerProvider("anthropic", { + baseUrl: "https://proxy.example.com" + }); + + // Register new provider with models + pi.registerProvider("my-provider", { + name: "My Provider", + baseUrl: "https://api.example.com", + apiKey: "$MY_API_KEY", + api: "openai-completions", + models: [ + { + id: "my-model", + name: "My Model", + reasoning: false, + input: ["text", "image"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 128000, + maxTokens: 4096 + } + ] + }); +} +``` + +The extension factory can also be `async`. For dynamic model discovery, fetch and register models in the factory instead of `session_start`. pi waits for the factory before startup continues, so the provider is available during interactive startup and to `pi --list-models`. + +## Override Existing Provider + +The simplest use case: redirect an existing provider through a proxy. + +```typescript +// All Anthropic requests now go through your proxy +pi.registerProvider("anthropic", { + baseUrl: "https://proxy.example.com" +}); + +// Add custom headers to OpenAI requests +pi.registerProvider("openai", { + headers: { + "X-Custom-Header": "value" + } +}); + +// Both baseUrl and headers +pi.registerProvider("google", { + baseUrl: "https://ai-gateway.corp.com/google", + headers: { + "X-Corp-Auth": "$CORP_AUTH_TOKEN" // env var or literal + } +}); +``` + +When only `baseUrl` and/or `headers` are provided (no `models`), all existing models for that provider are preserved with the new endpoint. + +## Register New Provider + +To add a completely new provider, specify `models` along with the required configuration. + +If the model list comes from a remote endpoint, use an async extension factory: + +```typescript +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default async function (pi: ExtensionAPI) { + const response = await fetch("http://localhost:1234/v1/models"); + const payload = (await response.json()) as { + data: Array<{ + id: string; + name?: string; + context_window?: number; + max_tokens?: number; + }>; + }; + + pi.registerProvider("local-openai", { + baseUrl: "http://localhost:1234/v1", + apiKey: "$LOCAL_OPENAI_API_KEY", + api: "openai-completions", + models: payload.data.map((model) => ({ + id: model.id, + name: model.name ?? model.id, + reasoning: false, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: model.context_window ?? 128000, + maxTokens: model.max_tokens ?? 4096, + })), + }); +} +``` + +This registers the fetched models before startup finishes. + +```typescript +pi.registerProvider("my-llm", { + baseUrl: "https://api.my-llm.com/v1", + apiKey: "$MY_LLM_API_KEY", // env var reference + api: "openai-completions", // which streaming API to use + models: [ + { + id: "my-llm-large", + name: "My LLM Large", + reasoning: true, // supports extended thinking + input: ["text", "image"], + cost: { + input: 3.0, // $/million tokens + output: 15.0, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 200000, + maxTokens: 16384 + } + ] +}); +``` + +When `models` is provided, it **replaces** all existing models for that provider. + +`apiKey` and custom header values use the same config value syntax as `models.json`: `!command` at the start executes a command for the whole value, `$ENV_VAR` and `${ENV_VAR}` interpolate environment variables, `$$` emits a literal `$`, and `$!` emits a literal `!`. + +## Unregister Provider + +Use `pi.unregisterProvider(name)` to remove a provider that was previously registered via `pi.registerProvider(name, ...)`: + +```typescript +// Register +pi.registerProvider("my-llm", { + baseUrl: "https://api.my-llm.com/v1", + apiKey: "$MY_LLM_API_KEY", + api: "openai-completions", + models: [ + { + id: "my-llm-large", + name: "My LLM Large", + reasoning: true, + input: ["text", "image"], + cost: { input: 3.0, output: 15.0, cacheRead: 0.3, cacheWrite: 3.75 }, + contextWindow: 200000, + maxTokens: 16384 + } + ] +}); + +// Later, remove it +pi.unregisterProvider("my-llm"); +``` + +Unregistering removes that provider's dynamic models, API key fallback, OAuth provider registration, and custom stream handler registrations. Any built-in models or provider behavior that were overridden are restored. + +Calls made after the initial extension load phase are applied immediately, so no `/reload` is required. + +### API Types + +The `api` field determines which streaming implementation is used: + +| API | Use for | +|-----|---------| +| `anthropic-messages` | Anthropic Claude API and compatibles | +| `openai-completions` | OpenAI Chat Completions API and compatibles | +| `openai-responses` | OpenAI Responses API | +| `azure-openai-responses` | Azure OpenAI Responses API | +| `openai-codex-responses` | OpenAI Codex Responses API | +| `mistral-conversations` | Mistral SDK Conversations/Chat streaming | +| `google-generative-ai` | Google Generative AI API | +| `google-vertex` | Google Vertex AI API | +| `bedrock-converse-stream` | Amazon Bedrock Converse API | + +Most OpenAI-compatible providers work with `openai-completions`. Use model-level `thinkingLevelMap` for model-specific thinking levels, and `compat` for provider quirks. The `xhigh` and `max` levels are opt-in, require non-null map entries, and may be separated by unsupported holes: + +```typescript +models: [{ + id: "custom-model", + // ... + reasoning: true, + thinkingLevelMap: { // map pi levels to provider values; null hides unsupported levels + minimal: null, + low: null, + medium: null, + high: "default", + xhigh: null, + max: "max" + }, + compat: { + supportsDeveloperRole: false, // use "system" instead of "developer" + supportsReasoningEffort: true, + maxTokensField: "max_tokens", // instead of "max_completion_tokens" + requiresToolResultName: true, // tool results need name field + thinkingFormat: "qwen", // top-level enable_thinking: true + cacheControlFormat: "anthropic" // Anthropic-style cache_control markers + } +}] +``` + +Use `openrouter` for OpenRouter-style `reasoning: { effort }` controls. Use `together` for Together-style `reasoning: { enabled }` controls; with `supportsReasoningEffort`, it also sends `reasoning_effort`. Use `qwen-chat-template` for local Qwen-compatible servers that read `chat_template_kwargs.enable_thinking` and need `preserve_thinking`. +Use `cacheControlFormat: "anthropic"` for OpenAI-compatible providers that expose Anthropic-style prompt caching via `cache_control` on the system prompt, last tool definition, and last user, assistant, or tool-result text content. + +For Anthropic-compatible providers using `api: "anthropic-messages"`, set `compat.forceAdaptiveThinking: true` on models or providers whose upstream model requires adaptive thinking (`thinking.type: "adaptive"` plus `output_config.effort`). Built-in adaptive Claude models set this automatically. Set `compat.allowEmptySignature: true` only for providers that emit empty thinking signatures and expect `signature: ""` on replay. + +> Migration note: Mistral moved from `openai-completions` to `mistral-conversations`. +> Use `mistral-conversations` for native Mistral models. +> If you intentionally route Mistral-compatible/custom endpoints through `openai-completions`, set `compat` flags explicitly as needed. + +### Auth Header + +If your provider expects `Authorization: Bearer ` but doesn't use a standard API, set `authHeader: true`: + +```typescript +pi.registerProvider("custom-api", { + baseUrl: "https://api.example.com", + apiKey: "$MY_API_KEY", + authHeader: true, // adds Authorization: Bearer header + api: "openai-completions", + models: [...] +}); +``` + +The key is resolved for each request. An explicit request `Authorization` header takes precedence over the generated value. + +## OAuth Support + +Add OAuth/SSO authentication that integrates with `/login`: + +```typescript +import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai"; + +pi.registerProvider("corporate-ai", { + baseUrl: "https://ai.corp.com/v1", + api: "openai-responses", + models: [...], + oauth: { + name: "Corporate AI (SSO)", + + async login(callbacks: OAuthLoginCallbacks): Promise { + const method = await callbacks.onSelect({ + message: "Select login method:", + options: [ + { id: "browser", label: "Browser OAuth" }, + { id: "device", label: "Device code" } + ] + }); + if (!method) throw new Error("Login cancelled"); + + let code: string; + if (method === "device") { + callbacks.onDeviceCode({ + userCode: "ABCD-1234", + verificationUri: "https://sso.corp.com/device", + intervalSeconds: 5, + expiresInSeconds: 900 + }); + code = await pollDeviceCodeUntilComplete(); + } else { + callbacks.onAuth({ url: "https://sso.corp.com/authorize?..." }); + code = await callbacks.onPrompt({ message: "Enter SSO code:" }); + } + + // Exchange for tokens (your implementation) + const tokens = await exchangeCodeForTokens(code); + + return { + refresh: tokens.refreshToken, + access: tokens.accessToken, + expires: Date.now() + tokens.expiresIn * 1000 + }; + }, + + async refreshToken(credentials: OAuthCredentials): Promise { + const tokens = await refreshAccessToken(credentials.refresh); + return { + refresh: tokens.refreshToken ?? credentials.refresh, + access: tokens.accessToken, + expires: Date.now() + tokens.expiresIn * 1000 + }; + }, + + getApiKey(credentials: OAuthCredentials): string { + return credentials.access; + } + } +}); +``` + +After registration, users can authenticate via `/login corporate-ai`. + +### OAuthLoginCallbacks + +The `callbacks` object provides UI-neutral interactions for the provider-owned flow: + +```typescript +interface OAuthLoginCallbacks { + // Open URL in browser (for OAuth redirects) + onAuth(params: { url: string }): void; + + // Show device code (for device authorization flow) + onDeviceCode(params: { + userCode: string; + verificationUri: string; + intervalSeconds?: number; + expiresInSeconds?: number; + }): void; + + // Show transient progress + onProgress?(message: string): void; + + // Prompt user for input (for manual token entry) + onPrompt(params: { message: string }): Promise; + + // Show an interactive selector, e.g. to choose browser OAuth vs device code + onSelect(params: { + message: string; + options: { id: string; label: string }[]; + }): Promise; +} +``` + +### OAuthCredentials + +Credentials are persisted in `~/.pi/agent/auth.json`: + +```typescript +interface OAuthCredentials { + refresh: string; // Refresh token (for refreshToken()) + access: string; // Access token (returned by getApiKey()) + expires: number; // Expiration timestamp in milliseconds +} +``` + +## Custom Streaming API + +For providers with non-standard APIs, implement `streamSimple`. Study the existing provider implementations before writing your own: + +**Reference implementations:** +- [anthropic.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/providers/anthropic.ts) - Anthropic Messages API +- [mistral.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/providers/mistral.ts) - Mistral Conversations API +- [openai-completions.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/providers/openai-completions.ts) - OpenAI Chat Completions +- [openai-responses.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/providers/openai-responses.ts) - OpenAI Responses API +- [google.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/providers/google.ts) - Google Generative AI +- [amazon-bedrock.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/providers/amazon-bedrock.ts) - AWS Bedrock + +### Stream Pattern + +All providers follow the same pattern: + +```typescript +import { + type AssistantMessage, + type AssistantMessageEventStream, + type Context, + type Model, + type SimpleStreamOptions, + calculateCost, + createAssistantMessageEventStream, +} from "@earendil-works/pi-ai"; + +function streamMyProvider( + model: Model, + context: Context, + options?: SimpleStreamOptions +): AssistantMessageEventStream { + const stream = createAssistantMessageEventStream(); + + (async () => { + // Initialize output message + const output: AssistantMessage = { + role: "assistant", + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "pending", + timestamp: Date.now(), + }; + + try { + // Push start event + stream.push({ type: "start", partial: output }); + + // Make API request and process response... + // Push content events as they arrive and set stopReason from the terminal event. + if (output.stopReason === "pending") { + throw new Error("Provider stream ended without a stop reason"); + } + if (output.stopReason === "error" || output.stopReason === "aborted") { + throw new Error(output.errorMessage || "An unknown error occurred"); + } + + // Push done event + stream.push({ + type: "done", + reason: output.stopReason, + message: output + }); + stream.end(); + } catch (error) { + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = error instanceof Error ? error.message : String(error); + stream.push({ type: "error", reason: output.stopReason, error: output }); + stream.end(); + } + })(); + + return stream; +} +``` + +### Event Types + +Push events via `stream.push()` in this order: + +1. `{ type: "start", partial: output }` - Stream started + +2. Content events (repeatable, track `contentIndex` for each block): + - `{ type: "text_start", contentIndex, partial }` - Text block started + - `{ type: "text_delta", contentIndex, delta, partial }` - Text chunk + - `{ type: "text_end", contentIndex, content, partial }` - Text block ended + - `{ type: "thinking_start", contentIndex, partial }` - Thinking started + - `{ type: "thinking_delta", contentIndex, delta, partial }` - Thinking chunk + - `{ type: "thinking_end", contentIndex, content, partial }` - Thinking ended + - `{ type: "toolcall_start", contentIndex, partial }` - Tool call started + - `{ type: "toolcall_delta", contentIndex, delta, partial }` - Tool call JSON chunk + - `{ type: "toolcall_end", contentIndex, toolCall, partial }` - Tool call ended + +3. `{ type: "done", reason, message }` or `{ type: "error", reason, error }` - Stream ended + +The `partial` field in each event contains the current `AssistantMessage` state. Update `output.content` as you receive data, then include `output` as the `partial`. + +### Content Blocks + +Add content blocks to `output.content` as they arrive: + +```typescript +// Text block +output.content.push({ type: "text", text: "" }); +stream.push({ type: "text_start", contentIndex: output.content.length - 1, partial: output }); + +// As text arrives +const block = output.content[contentIndex]; +if (block.type === "text") { + block.text += delta; + stream.push({ type: "text_delta", contentIndex, delta, partial: output }); +} + +// When block completes +stream.push({ type: "text_end", contentIndex, content: block.text, partial: output }); +``` + +### Tool Calls + +Tool calls require accumulating JSON and parsing: + +```typescript +// Start tool call +output.content.push({ + type: "toolCall", + id: toolCallId, + name: toolName, + arguments: {} +}); +stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output }); + +// Accumulate JSON +let partialJson = ""; +partialJson += jsonDelta; +try { + block.arguments = JSON.parse(partialJson); +} catch {} +stream.push({ type: "toolcall_delta", contentIndex, delta: jsonDelta, partial: output }); + +// Complete +stream.push({ + type: "toolcall_end", + contentIndex, + toolCall: { type: "toolCall", id, name, arguments: block.arguments }, + partial: output +}); +``` + +### Usage and Cost + +Update usage from API response and calculate cost: + +```typescript +output.usage.input = response.usage.input_tokens; +output.usage.output = response.usage.output_tokens; +output.usage.cacheRead = response.usage.cache_read_tokens ?? 0; +output.usage.cacheWrite = response.usage.cache_write_tokens ?? 0; +output.usage.totalTokens = output.usage.input + output.usage.output + + output.usage.cacheRead + output.usage.cacheWrite; +calculateCost(model, output.usage); +``` + +### Context Overflow Errors + +When a request exceeds the model's context window, pi can recover automatically by compacting the conversation and retrying. This recovery only kicks in if pi recognizes the failure as an overflow. + +Detection runs on the finalized assistant message: + +- `stopReason === "error"` +- `errorMessage` matches one of pi's known overflow patterns (see [`packages/ai/src/utils/overflow.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/utils/overflow.ts)) + +If your provider returns overflow errors with a message pi does not recognize, normalize the error from the same extension that registers the provider. Use a `message_end` handler to rewrite the assistant message so its `errorMessage` starts with a phrase pi recognizes. The generic fallback `context_length_exceeded` is the safest choice. + +```typescript +const MY_PROVIDER_OVERFLOW_PATTERN = /your provider's overflow phrase/i; + +export default function (pi: ExtensionAPI) { + pi.registerProvider("my-provider", { /* ... */ }); + + pi.on("message_end", (event, ctx) => { + const message = event.message; + if (message.role !== "assistant") return; + if (message.stopReason !== "error") return; + if ( + message.provider !== "my-provider" && + ctx.model?.provider !== "my-provider" + ) + return; + + const errorMessage = message.errorMessage ?? ""; + if (errorMessage.includes("context_length_exceeded")) return; + if (!MY_PROVIDER_OVERFLOW_PATTERN.test(errorMessage)) return; + + return { + message: { + ...message, + errorMessage: `context_length_exceeded: ${errorMessage}`, + }, + }; + }); +} +``` + +`message_end` runs before pi tracks the assistant message for auto-compaction, so the rewritten `errorMessage` is what pi checks. With this in place, pi will: + +1. Detect the overflow from `errorMessage`. +2. Drop the failed assistant message from live context. +3. Run compaction. +4. Retry the request once. + +Guard the rewrite carefully: + +- Scope it to your provider (`message.provider` and `ctx.model?.provider`) so unrelated errors from other providers are untouched. +- Match a provider-specific pattern, not pi's generic overflow patterns. Rewriting rate-limit or throttling errors (`rate limit`, `too many requests`) would falsely trigger compaction instead of pi's normal retry-with-backoff path. +- Skip when `errorMessage` already includes `context_length_exceeded` so the handler is idempotent. + +### Registration + +Register your stream function: + +```typescript +pi.registerProvider("my-provider", { + baseUrl: "https://api.example.com", + apiKey: "$MY_API_KEY", + api: "my-custom-api", + models: [...], + streamSimple: streamMyProvider +}); +``` + +## Testing Your Implementation + +Test your provider against the same test suites used by built-in providers. Copy and adapt these test files from [packages/ai/test/](https://github.com/earendil-works/pi-mono/tree/main/packages/ai/test): + +| Test | Purpose | +|------|---------| +| `stream.test.ts` | Basic streaming, text output | +| `tokens.test.ts` | Token counting and usage | +| `abort.test.ts` | AbortSignal handling | +| `empty.test.ts` | Empty/minimal responses | +| `context-overflow.test.ts` | Context window limits | +| `image-limits.test.ts` | Image input handling | +| `unicode-surrogate.test.ts` | Unicode edge cases | +| `tool-call-without-result.test.ts` | Tool call edge cases | +| `image-tool-result.test.ts` | Images in tool results | +| `total-tokens.test.ts` | Total token calculation | +| `cross-provider-handoff.test.ts` | Context handoff between providers | + +Run tests with your provider/model pairs to verify compatibility. + +## Config Reference + +```typescript +interface ProviderConfig { + /** Display name for the provider in UI such as /login. */ + name?: string; + + /** API endpoint URL. Required when defining models. */ + baseUrl?: string; + + /** API key literal, env interpolation ($ENV_VAR or ${ENV_VAR}), or !command. Required when defining models (unless oauth). */ + apiKey?: string; + + /** API type for streaming. Required at provider or model level when defining models. */ + api?: Api; + + /** Custom streaming implementation for non-standard APIs. */ + streamSimple?: ( + model: Model, + context: Context, + options?: SimpleStreamOptions + ) => AssistantMessageEventStream; + + /** Custom headers to include in requests. Values use the same resolution syntax as apiKey. */ + headers?: Record; + + /** If true, adds Authorization: Bearer header with the resolved API key. */ + authHeader?: boolean; + + /** Models to register. If provided, replaces all existing models for this provider. */ + models?: ProviderModelConfig[]; + + /** OAuth provider for /login support. */ + oauth?: { + name: string; + login(callbacks: OAuthLoginCallbacks): Promise; + refreshToken(credentials: OAuthCredentials): Promise; + getApiKey(credentials: OAuthCredentials): string; + }; +} +``` + +## Model Definition Reference + +```typescript +interface ProviderModelConfig { + /** Model ID (e.g., "claude-sonnet-4-20250514"). */ + id: string; + + /** Display name (e.g., "Claude 4 Sonnet"). */ + name: string; + + /** API type override for this specific model. */ + api?: Api; + + /** API endpoint URL override for this specific model. */ + baseUrl?: string; + + /** Whether the model supports extended thinking. */ + reasoning: boolean; + + /** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */ + thinkingLevelMap?: Partial>; + + /** Supported input types. */ + input: ("text" | "image")[]; + + /** Cost per million tokens (for usage tracking). */ + cost: { + input: number; + output: number; + cacheRead: number; + cacheWrite: number; + }; + + /** Maximum context window size in tokens. */ + contextWindow: number; + + /** Maximum output tokens. */ + maxTokens: number; + + /** Custom headers for this specific model. */ + headers?: Record; + + /** Compatibility settings for the selected API. */ + compat?: { + // openai-completions + supportsStore?: boolean; + supportsDeveloperRole?: boolean; + supportsReasoningEffort?: boolean; + supportsUsageInStreaming?: boolean; + supportsStrictMode?: boolean; + supportsOpenAIGrammarTools?: boolean; // openai-completions/openai-responses; false falls back to normal function tools + maxTokensField?: "max_completion_tokens" | "max_tokens"; + requiresToolResultName?: boolean; + requiresAssistantAfterToolResult?: boolean; + requiresThinkingAsText?: boolean; + requiresReasoningContentOnAssistantMessages?: boolean; + thinkingFormat?: "openai" | "openrouter" | "deepseek" | "together" | "zai" | "qwen" | "chat-template" | "qwen-chat-template" | "string-thinking" | "ant-ling"; + chatTemplateKwargs?: Record; + cacheControlFormat?: "anthropic"; + sessionAffinityFormat?: "openai" | "openai-nosession" | "openrouter"; + sendSessionAffinityHeaders?: boolean; + + // anthropic-messages + supportsEagerToolInputStreaming?: boolean; + supportsLongCacheRetention?: boolean; + sendSessionAffinityHeaders?: boolean; + supportsCacheControlOnTools?: boolean; + forceAdaptiveThinking?: boolean; + allowEmptySignature?: boolean; + supportsStrictTools?: boolean; + }; +} +``` + +`openrouter` sends `reasoning: { effort }`. `deepseek` sends `thinking: { type: "enabled" | "disabled" }` and `reasoning_effort` when enabled. `together` sends `reasoning: { enabled }` and also `reasoning_effort` when `supportsReasoningEffort` is enabled. `qwen` is for DashScope-style top-level `enable_thinking`. Use `qwen-chat-template` for local Qwen-compatible servers that read `chat_template_kwargs.enable_thinking` and need `preserve_thinking`. Use `chat-template` for configurable `chat_template_kwargs`, for example DeepSeek V3.x behind vLLM with `chatTemplateKwargs: { "thinking": { "$var": "thinking.enabled" } }`. +`cacheControlFormat: "anthropic"` applies Anthropic-style `cache_control` markers to the system prompt, last tool definition, and last user, assistant, or tool-result text content. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..fc57bef --- /dev/null +++ b/docs/development.md @@ -0,0 +1,71 @@ +# Development + +See [AGENTS.md](https://github.com/earendil-works/pi-mono/blob/main/AGENTS.md) for additional guidelines. + +## Setup + +```bash +git clone https://github.com/earendil-works/pi-mono +cd pi-mono +npm install +npm run build +``` + +Run from source: + +```bash +/path/to/pi-mono/pi-test.sh +``` + +The script can be run from any directory. Pi keeps the caller's current working directory. + +## Forking / Rebranding + +Configure via `package.json`: + +```json +{ + "piConfig": { + "name": "pi", + "configDir": ".pi" + } +} +``` + +Change `name`, `configDir`, and `bin` field for your fork. Affects CLI banner, config paths, and environment variable names. + +## Path Resolution + +Three execution modes: npm install, standalone binary, tsx from source. + +**Always use `src/config.ts`** for package assets: + +```typescript +import { getPackageDir, getThemeDir } from "./config.js"; +``` + +Never use `__dirname` directly for package assets. + +## Debug Command + +`/debug` (hidden) writes to `~/.pi/agent/pi-debug.log`: +- Rendered TUI lines with ANSI codes +- Last messages sent to the LLM + +## Testing + +```bash +./test.sh # Run non-LLM tests (no API keys needed) +npm test # Run all tests +npm test -- test/specific.test.ts # Run specific test +``` + +## Project Structure + +``` +packages/ + ai/ # LLM provider abstraction + agent/ # Agent loop and message types + tui/ # Terminal UI components + coding-agent/ # CLI and interactive mode +``` diff --git a/docs/docs.json b/docs/docs.json new file mode 100644 index 0000000..bbc9e74 --- /dev/null +++ b/docs/docs.json @@ -0,0 +1,156 @@ +{ + "navigation": [ + { + "title": "Start here", + "items": [ + { + "title": "Overview", + "path": "index.md" + }, + { + "title": "Quickstart", + "path": "quickstart.md" + }, + { + "title": "Using Pi", + "path": "usage.md" + }, + { + "title": "Providers", + "path": "providers.md" + }, + { + "title": "Security", + "path": "security.md" + }, + { + "title": "Containerization", + "path": "containerization.md" + }, + { + "title": "Settings", + "path": "settings.md" + }, + { + "title": "Keybindings", + "path": "keybindings.md" + }, + { + "title": "Sessions", + "path": "sessions.md" + }, + { + "title": "Compaction", + "path": "compaction.md" + } + ] + }, + { + "title": "Customization", + "items": [ + { + "title": "Extensions", + "path": "extensions.md" + }, + { + "title": "Skills", + "path": "skills.md" + }, + { + "title": "Prompt Templates", + "path": "prompt-templates.md" + }, + { + "title": "Themes", + "path": "themes.md" + }, + { + "title": "Pi Packages", + "path": "packages.md" + }, + { + "title": "Custom Models", + "path": "models.md" + }, + { + "title": "Custom Providers", + "path": "custom-provider.md" + } + ] + }, + { + "title": "Reference", + "items": [ + { + "title": "Session Format", + "path": "session-format.md" + } + ] + }, + { + "title": "Programmatic Usage", + "items": [ + { + "title": "SDK", + "path": "sdk.md" + }, + { + "title": "RPC Mode", + "path": "rpc.md" + }, + { + "title": "JSON Event Stream Mode", + "path": "json.md" + }, + { + "title": "TUI Components", + "path": "tui.md" + } + ] + }, + { + "title": "Platform Setup", + "items": [ + { + "title": "Windows", + "path": "windows.md" + }, + { + "title": "Termux on Android", + "path": "termux.md" + }, + { + "title": "tmux", + "path": "tmux.md" + }, + { + "title": "Terminal Setup", + "path": "terminal-setup.md" + }, + { + "title": "Shell Aliases", + "path": "shell-aliases.md" + } + ] + }, + { + "title": "Development", + "items": [ + { + "title": "Development", + "path": "development.md" + } + ] + } + ], + "redirects": [ + { + "from": "session.md", + "to": "session-format.md" + }, + { + "from": "tree.md", + "to": "sessions.md" + } + ] +} diff --git a/docs/environment-variables.md b/docs/environment-variables.md new file mode 100644 index 0000000..072744c --- /dev/null +++ b/docs/environment-variables.md @@ -0,0 +1,88 @@ +# Environment Variables + +Pi uses environment variables in three ways: + +- Variables such as `PI_OFFLINE` configure the Pi process. +- Pi sets `PI_CODING_AGENT` so child processes can detect that they run inside Pi. +- Commands run by the LLM-callable bash tool receive `PI_*` variables describing the current session. + +Provider API-key variables are documented separately in [Providers](providers.md#environment-variables-or-auth-file). + +## Process Marker + +The CLI and RPC entry points set `PI_CODING_AGENT=true`. Child processes inherit it and can use it to detect that they run inside Pi. It is not session-specific and is not set automatically when Pi is embedded through the SDK. + +## Bash Tool Session Environment + +Commands run by the bash tool receive the current Pi session state: + +| Variable | Description | +|----------|-------------| +| `PI_SESSION_ID` | Current session ID | +| `PI_SESSION_FILE` | Absolute path to the current session JSONL file; unset for ephemeral sessions | +| `PI_PROVIDER` | Currently selected model provider | +| `PI_MODEL` | Currently selected model ID | +| `PI_REASONING_LEVEL` | Current effective reasoning level: `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` | + +The values are resolved when each command starts. Switching models or changing the reasoning level therefore affects the next bash command without restarting Pi. `PI_PROVIDER` and `PI_MODEL` identify the selected Pi model, not a different upstream model that a router may choose internally. + +When asked which model or provider is running, inspect these variables instead of inferring the answer from the system prompt: + +```bash +printf '%s/%s\n' "$PI_PROVIDER" "$PI_MODEL" +printf 'reasoning=%s session=%s\n' "$PI_REASONING_LEVEL" "$PI_SESSION_ID" +``` + +The session file can be inspected directly when the session is persistent: + +```bash +if [ -n "$PI_SESSION_FILE" ]; then + tail -n 1 "$PI_SESSION_FILE" +fi +``` + +These variables are injected into the LLM-callable bash tool. They are not injected into user-entered `!` or `!!` commands. + +### Custom Bash Tools + +Bash tools created with `createBashTool()` expose the session environment by default when registered with Pi. Injection happens before `spawnHook`, so a hook receives the variables in `ctx.env`: + +```typescript +const bashTool = createBashTool(cwd, { + spawnHook: (ctx) => ({ + ...ctx, + env: { ...ctx.env, CI: "1" }, + }), +}); +``` + +Disable session metadata independently of the spawn hook: + +```typescript +const bashTool = createBashTool(cwd, { + exposeSessionEnvironment: false, + spawnHook: (ctx) => ctx, +}); +``` + +When disabled, Pi removes inherited values for these variables so nested Pi processes do not expose stale parent-session metadata. + +## Pi Process Configuration + +These variables are read by Pi itself: + +| Variable | Description | +|----------|-------------| +| `PI_CODING_AGENT_DIR` | Override the config directory; default is `~/.pi/agent` | +| `PI_CODING_AGENT_SESSION_DIR` | Override session storage; overridden by `--session-dir` | +| `PI_PACKAGE_DIR` | Override the package directory, useful for Nix/Guix store paths | +| `PI_OFFLINE` | Disable startup network operations, including update checks, package updates, and install/update telemetry | +| `PI_SKIP_VERSION_CHECK` | Disable the `pi.dev` latest-version request | +| `PI_TELEMETRY` | Override install/update telemetry and provider attribution headers: `1`/`true`/`yes` or `0`/`false`/`no` | +| `PI_CACHE_RETENTION` | Set to `long` for extended provider prompt caching where supported | +| `PI_SHARE_VIEWER_URL` | Override the base URL used by `/share` | +| `PI_HARDWARE_CURSOR` | Set to `1` to show the hardware cursor; see [Terminal setup](terminal-setup.md) | +| `VISUAL`, `EDITOR` | External editor fallback when `externalEditor` is unset | +| `HTTP_PROXY`, `HTTPS_PROXY` | Proxy outbound HTTP requests | + +Provider credentials such as `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, and cloud-provider configuration are listed in [Providers](providers.md#environment-variables-or-auth-file). diff --git a/docs/extensions.md b/docs/extensions.md new file mode 100644 index 0000000..7eea02c --- /dev/null +++ b/docs/extensions.md @@ -0,0 +1,2963 @@ +> pi can create extensions. Ask it to build one for your use case. + +# Extensions + +Extensions are TypeScript modules that extend pi's behavior. They can subscribe to lifecycle events, register custom tools callable by the LLM, add commands, and more. + +> **Placement for /reload:** Put extensions in `~/.pi/agent/extensions/` (global) or `.pi/extensions/` (project-local) for auto-discovery. Use `pi -e ./path.ts` only for quick tests. Extensions in auto-discovered locations can be hot-reloaded with `/reload`. + +**Key capabilities:** +- **Custom tools** - Register tools the LLM can call via `pi.registerTool()` +- **Event interception** - Block or modify tool calls, inject context, customize compaction +- **User interaction** - Prompt users via `ctx.ui` (select, confirm, input, notify) +- **Custom UI components** - Full TUI components with keyboard input via `ctx.ui.custom()` for complex interactions +- **Custom commands** - Register commands like `/mycommand` via `pi.registerCommand()` +- **Session persistence** - Store state that survives restarts via `pi.appendEntry()` +- **Custom rendering** - Control how tool calls/results and messages appear in TUI + +**Example use cases:** +- Permission gates (confirm before `rm -rf`, `sudo`, etc.) +- Git checkpointing (stash at each turn, restore on branch) +- Path protection (block writes to `.env`, `node_modules/`) +- Custom compaction (summarize conversation your way) +- Conversation summaries (see `summarize.ts` example) +- Interactive tools (questions, wizards, custom dialogs) +- Stateful tools (todo lists, connection pools) +- External integrations (file watchers, webhooks, CI triggers) +- Games while you wait (see `snake.ts` example) + +See [examples/extensions/](../examples/extensions/) for working implementations. + +## Table of Contents + +- [Quick Start](#quick-start) +- [Extension Locations](#extension-locations) +- [Available Imports](#available-imports) +- [Writing an Extension](#writing-an-extension) + - [Extension Styles](#extension-styles) +- [Events](#events) + - [Lifecycle Overview](#lifecycle-overview) + - [Resource Events](#resource-events) + - [Session Events](#session-events) + - [Agent Events](#agent-events) + - [Model Events](#model-events) + - [Tool Events](#tool-events) +- [ExtensionContext](#extensioncontext) +- [ExtensionCommandContext](#extensioncommandcontext) +- [ExtensionAPI Methods](#extensionapi-methods) +- [State Management](#state-management) +- [Custom Tools](#custom-tools) + - [Dynamic Tool Loading](#dynamic-tool-loading) +- [Custom UI](#custom-ui) +- [Error Handling](#error-handling) +- [Mode Behavior](#mode-behavior) +- [Examples Reference](#examples-reference) + +## Quick Start + +Create `~/.pi/agent/extensions/my-extension.ts`: + +```typescript +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { Type } from "typebox"; + +export default function (pi: ExtensionAPI) { + // React to events + pi.on("session_start", async (_event, ctx) => { + ctx.ui.notify("Extension loaded!", "info"); + }); + + pi.on("tool_call", async (event, ctx) => { + if (event.toolName === "bash" && event.input.command?.includes("rm -rf")) { + const ok = await ctx.ui.confirm("Dangerous!", "Allow rm -rf?"); + if (!ok) return { block: true, reason: "Blocked by user" }; + } + }); + + // Register a custom tool + pi.registerTool({ + name: "greet", + label: "Greet", + description: "Greet someone by name", + parameters: Type.Object({ + name: Type.String({ description: "Name to greet" }), + }), + async execute(toolCallId, params, signal, onUpdate, ctx) { + return { + content: [{ type: "text", text: `Hello, ${params.name}!` }], + details: {}, + }; + }, + }); + + // Register a command + pi.registerCommand("hello", { + description: "Say hello", + handler: async (args, ctx) => { + ctx.ui.notify(`Hello ${args || "world"}!`, "info"); + }, + }); +} +``` + +Test with `--extension` (or `-e`) flag: + +```bash +pi -e ./my-extension.ts +``` + +## Extension Locations + +> **Security:** Extensions run with your full system permissions and can execute arbitrary code. Only install from sources you trust. + +Extensions are auto-discovered from trusted locations. Project-local `.pi/extensions` entries load only after the project is trusted. + +| Location | Scope | +|----------|-------| +| `~/.pi/agent/extensions/*.ts` | Global (all projects) | +| `~/.pi/agent/extensions/*/index.ts` | Global (subdirectory) | +| `.pi/extensions/*.ts` | Project-local | +| `.pi/extensions/*/index.ts` | Project-local (subdirectory) | + +Additional paths via `settings.json`: + +```json +{ + "packages": [ + "npm:@foo/bar@1.0.0", + "git:github.com/user/repo@v1" + ], + "extensions": [ + "/path/to/local/extension.ts", + "/path/to/local/extension/dir" + ] +} +``` + +To share extensions via npm or git as pi packages, see [packages.md](packages.md). + +## Available Imports + +| Package | Purpose | +|---------|---------| +| `@earendil-works/pi-coding-agent` | Extension types (`ExtensionAPI`, `ExtensionContext`, events) | +| `typebox` | Schema definitions for tool parameters | +| `@earendil-works/pi-ai` | AI utilities (`StringEnum` for Google-compatible enums) | +| `@earendil-works/pi-tui` | TUI components for custom rendering | + +npm dependencies work too. Add a `package.json` next to your extension (or in a parent directory), run `npm install`, and imports from `node_modules/` are resolved automatically. + +For distributed pi packages installed with `pi install` (npm or git), runtime deps must be in `dependencies`. Package installation uses production installs (`npm install --omit=dev`) by default, so `devDependencies` are not available at runtime; when `npmCommand` is configured, git packages use plain `install` for compatibility with wrappers. + +Node.js built-ins (`node:fs`, `node:path`, etc.) are also available. + +## Writing an Extension + +An extension exports a default factory function that receives `ExtensionAPI`. The factory can be synchronous or asynchronous: + +```typescript +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + // Subscribe to events + pi.on("event_name", async (event, ctx) => { + // ctx.ui for user interaction + const ok = await ctx.ui.confirm("Title", "Are you sure?"); + ctx.ui.notify("Done!", "info"); + ctx.ui.setStatus("my-ext", "Processing..."); // Footer status + ctx.ui.setWidget("my-ext", ["Line 1", "Line 2"]); // Widget above editor (default) + }); + + // Register tools, commands, shortcuts, flags + pi.registerTool({ ... }); + pi.registerCommand("name", { ... }); + pi.registerShortcut("ctrl+x", { ... }); + pi.registerFlag("my-flag", { ... }); +} +``` + +Extensions are loaded via [jiti](https://github.com/unjs/jiti), so TypeScript works without compilation. + +If the factory returns a `Promise`, pi awaits it before continuing startup. That means async initialization completes before `session_start`, before `resources_discover`, and before provider registrations queued via `pi.registerProvider()` are flushed. + +### Async factory functions + +Use an async factory for one-time startup work such as fetching remote configuration or dynamically discovering available models. + +```typescript +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default async function (pi: ExtensionAPI) { + const response = await fetch("http://localhost:1234/v1/models"); + const payload = (await response.json()) as { + data: Array<{ + id: string; + name?: string; + context_window?: number; + max_tokens?: number; + }>; + }; + + pi.registerProvider("local-openai", { + baseUrl: "http://localhost:1234/v1", + apiKey: "$LOCAL_OPENAI_API_KEY", + api: "openai-completions", + models: payload.data.map((model) => ({ + id: model.id, + name: model.name ?? model.id, + reasoning: false, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: model.context_window ?? 128000, + maxTokens: model.max_tokens ?? 4096, + })), + }); +} +``` + +This pattern makes the fetched models available during normal startup and to `pi --list-models`. + +### Long-lived resources and shutdown + +Extension factories may run in invocations that never start a session. Do not start background resources such as processes, sockets, file watchers, or timers from the factory. + +Defer background resource startup until `session_start` or the command/tool/event that needs the resource. Register an idempotent `session_shutdown` handler to close any session-scoped resources you start. + +### Extension Styles + +**Single file** - simplest, for small extensions: + +``` +~/.pi/agent/extensions/ +└── my-extension.ts +``` + +**Directory with index.ts** - for multi-file extensions: + +``` +~/.pi/agent/extensions/ +└── my-extension/ + ├── index.ts # Entry point (exports default function) + ├── tools.ts # Helper module + └── utils.ts # Helper module +``` + +**Package with dependencies** - for extensions that need npm packages: + +``` +~/.pi/agent/extensions/ +└── my-extension/ + ├── package.json # Declares dependencies and entry points + ├── package-lock.json + ├── node_modules/ # After npm install + └── src/ + └── index.ts +``` + +```json +// package.json +{ + "name": "my-extension", + "dependencies": { + "zod": "^3.0.0", + "chalk": "^5.0.0" + }, + "pi": { + "extensions": ["./src/index.ts"] + } +} +``` + +Run `npm install` in the extension directory, then imports from `node_modules/` work automatically. + +## Events + +### Lifecycle Overview + +``` +pi starts + │ + ├─► project_trust (user/global and CLI extensions only, before project resources load) + ├─► session_start { reason: "startup" } + └─► resources_discover { reason: "startup" } + │ + ▼ +user sends prompt ─────────────────────────────────────────┐ + │ │ + ├─► (extension commands checked first, bypass if found) │ + ├─► input (can intercept, transform, or handle) │ + ├─► (skill/template expansion if not handled) │ + ├─► before_agent_start (can inject message, modify system prompt) + ├─► agent_start │ + ├─► message_start / message_update / message_end │ + │ │ + │ ┌─── turn (repeats while LLM calls tools) ───┐ │ + │ │ │ │ + │ ├─► turn_start │ │ + │ ├─► context (can modify messages) │ │ + │ ├─► before_provider_headers (can mutate headers) | + │ ├─► before_provider_request (can inspect or replace payload) + │ ├─► after_provider_response (status + headers, before stream consume) + │ │ │ │ + │ │ LLM responds, may call tools: │ │ + │ │ ├─► tool_execution_start │ │ + │ │ ├─► tool_call (can block) │ │ + │ │ ├─► tool_execution_update │ │ + │ │ ├─► tool_result (can modify) │ │ + │ │ └─► tool_execution_end │ │ + │ │ │ │ + │ └─► turn_end │ │ + │ │ + ├─► agent_end │ + └─► agent_settled (no retry/compaction/follow-up left) │ + │ +user sends another prompt ◄────────────────────────────────┘ + +/new (new session) or /resume (switch session) + ├─► session_before_switch (can cancel) + ├─► session_shutdown + ├─► session_start { reason: "new" | "resume", previousSessionFile? } + └─► resources_discover { reason: "startup" } + +/fork or /clone + ├─► session_before_fork (can cancel) + ├─► session_shutdown + ├─► session_start { reason: "fork", previousSessionFile } + └─► resources_discover { reason: "startup" } + +/name or pi.setSessionName() + └─► session_info_changed + +/compact or auto-compaction + ├─► session_before_compact (can cancel or customize) + └─► session_compact + +/tree navigation + ├─► session_before_tree (can cancel or customize) + └─► session_tree + +/model or Ctrl+P (model selection/cycling) + ├─► thinking_level_select (if model change changes/clamps thinking level) + └─► model_select + +thinking level changes (settings, keybinding, pi.setThinkingLevel()) + └─► thinking_level_select + +exit (Ctrl+C, Ctrl+D, SIGHUP, SIGTERM) + └─► session_shutdown +``` + +### Startup Events + +#### project_trust + +Fired before pi decides whether to trust a project with dynamic configs (`.pi` or `.agents/skills`). It runs during startup and when session replacement (for example `/resume`) enters a cwd whose trust has not been resolved in the current process. Only user/global extensions and CLI `-e` extensions participate; project-local extensions are not loaded until after trust is resolved. + +```typescript +pi.on("project_trust", async (event, ctx) => { + // event.cwd - current working directory + // ctx has a limited trust context: cwd, mode, hasUI, and select/confirm/input/notify UI helpers + if (await ctx.ui.confirm("Trust project?", event.cwd)) { + return { trusted: "yes", remember: true }; + } + return { trusted: "undecided" }; +}); +``` + +A `project_trust` handler must return `{ trusted: "yes" | "no" | "undecided" }`. A user/global or CLI extension that returns `"yes"` or `"no"` owns the decision; the first yes/no decision wins and suppresses the built-in trust prompt. Use `remember: true` to persist a yes/no decision; otherwise it applies only to the current process. Return `"undecided"` to let later handlers or the built-in trust flow decide. Check `ctx.hasUI` before prompting. If no handler returns yes/no, normal trust resolution continues: saved `trust.json` decisions apply first, then `defaultProjectTrust` controls whether pi asks, trusts, or declines by default. + +### Resource Events + +#### resources_discover + +Fired after `session_start` so extensions can contribute additional skill, prompt, and theme paths. +The startup path uses `reason: "startup"`. Reload uses `reason: "reload"`. + +```typescript +pi.on("resources_discover", async (event, _ctx) => { + // event.cwd - current working directory + // event.reason - "startup" | "reload" + return { + skillPaths: ["/path/to/skills"], + promptPaths: ["/path/to/prompts"], + themePaths: ["/path/to/themes"], + }; +}); +``` + +### Session Events + +See [Session Format](session-format.md) for session storage internals and the SessionManager API. + +#### session_start + +Fired when a session is started, loaded, or reloaded. + +```typescript +pi.on("session_start", async (event, ctx) => { + // event.reason - "startup" | "reload" | "new" | "resume" | "fork" + // event.previousSessionFile - present for "new", "resume", and "fork" + ctx.ui.notify(`Session: ${ctx.sessionManager.getSessionFile() ?? "ephemeral"}`, "info"); +}); +``` + +#### session_info_changed + +Fired when the current session display name is set via `/name`, RPC, or `pi.setSessionName()`. + +```typescript +pi.on("session_info_changed", async (event, ctx) => { + // event.name - current normalized name, or undefined if cleared + ctx.ui.notify(`Session renamed: ${event.name ?? "(none)"}`, "info"); +}); +``` + +#### session_before_switch + +Fired before starting a new session (`/new`) or switching sessions (`/resume`). + +```typescript +pi.on("session_before_switch", async (event, ctx) => { + // event.reason - "new" or "resume" + // event.targetSessionFile - session we're switching to (only for "resume") + + if (event.reason === "new") { + const ok = await ctx.ui.confirm("Clear?", "Delete all messages?"); + if (!ok) return { cancel: true }; + } +}); +``` + +After a successful switch or new-session action, pi emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "new" | "resume"` and `previousSessionFile`. +Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`. + +#### session_before_fork + +Fired when forking via `/fork` or cloning via `/clone`. + +```typescript +pi.on("session_before_fork", async (event, ctx) => { + // event.entryId - ID of the selected entry + // event.position - "before" for /fork, "at" for /clone + return { cancel: true }; // Cancel fork/clone + // OR + return { skipConversationRestore: true }; // Reserved for future conversation restore control +}); +``` + +After a successful fork or clone, pi emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "fork"` and `previousSessionFile`. +Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`. + +#### session_before_compact / session_compact + +Fired on compaction. See [compaction.md](compaction.md) for details. + +```typescript +pi.on("session_before_compact", async (event, ctx) => { + const { preparation, branchEntries, customInstructions, reason, willRetry, signal } = event; + + // reason - "manual" (/compact), "threshold", or "overflow" + // willRetry - whether the aborted turn is retried after compaction (overflow recovery) + + // Cancel: + return { cancel: true }; + + // Custom summary: + return { + compaction: { + summary: "...", + firstKeptEntryId: preparation.firstKeptEntryId, + tokensBefore: preparation.tokensBefore, + // usage: summaryResponse.usage, // Optional; included in session totals + } + }; +}); + +pi.on("session_compact", async (event, ctx) => { + // event.compactionEntry - the saved compaction + // event.fromExtension - whether extension provided it + // event.reason - "manual" (/compact), "threshold", or "overflow" + // event.willRetry - whether the aborted turn is retried after compaction (overflow recovery) +}); +``` + +#### session_before_tree / session_tree + +Fired on `/tree` navigation. See [Sessions](sessions.md) for tree navigation concepts. + +```typescript +pi.on("session_before_tree", async (event, ctx) => { + const { preparation, signal } = event; + return { cancel: true }; + // OR provide custom summary: + return { + summary: { + summary: "...", + // usage: summaryResponse.usage, // Optional; included in session totals + details: {}, + }, + }; +}); + +pi.on("session_tree", async (event, ctx) => { + // event.newLeafId, oldLeafId, summaryEntry, fromExtension +}); +``` + +#### session_shutdown + +Fired before a started session runtime is torn down. Use this to clean up resources opened from `session_start` or other session-scoped hooks. + +```typescript +pi.on("session_shutdown", async (event, ctx) => { + // event.reason - "quit" | "reload" | "new" | "resume" | "fork" + // event.targetSessionFile - destination session for session replacement flows + // Cleanup, save state, etc. +}); +``` + +### Agent Events + +#### before_agent_start + +Fired after user submits prompt, before agent loop. Can inject a message and/or modify the system prompt. + +```typescript +pi.on("before_agent_start", async (event, ctx) => { + // event.prompt - user's prompt text + // event.images - attached images (if any) + // event.systemPrompt - current chained system prompt for this handler + // (includes changes from earlier before_agent_start handlers) + // event.systemPromptOptions - structured options used to build the system prompt + // .customPrompt - any custom system prompt (from --system-prompt, SYSTEM.md, or custom templates) + // .selectedTools - tools currently active in the prompt + // .toolSnippets - one-line descriptions for each tool + // .promptGuidelines - custom guideline bullets + // .appendSystemPrompt - text from --append-system-prompt flags + // .cwd - working directory + // .contextFiles - AGENTS.md files and other loaded context files + // .skills - loaded skills + + return { + // Inject a persistent message (stored in session, sent to LLM) + message: { + customType: "my-extension", + content: "Additional context for the LLM", + display: true, + }, + // Replace the system prompt for this turn (chained across extensions) + systemPrompt: event.systemPrompt + "\n\nExtra instructions for this turn...", + }; +}); +``` + +The `systemPromptOptions` field gives extensions access to the same structured data Pi uses to build the system prompt. This lets you inspect what Pi has loaded — custom prompts, guidelines, tool snippets, context files, skills — without re-discovering resources or re-parsing flags. Use it when your extension needs to make deep, informed changes to the system prompt while respecting user-provided configuration. + +Inside `before_agent_start`, `event.systemPrompt` and `ctx.getSystemPrompt()` both reflect the chained system prompt as of the current handler. Later `before_agent_start` handlers can still modify it again. + +#### agent_start / agent_end / agent_settled + +`agent_start` fires when a low-level agent run begins. `agent_end` fires when that run ends, but Pi may still auto-retry, auto-compact and retry, or continue with queued follow-up messages. Use `agent_settled` for status integrations that need to know Pi will not continue running automatically. + +```typescript +pi.on("agent_start", async (_event, ctx) => {}); + +pi.on("agent_end", async (event, ctx) => { + // event.messages - messages from this low-level run +}); + +pi.on("agent_settled", async (_event, ctx) => { + // ctx.isIdle() is true here unless another extension started a new run. +}); +``` + +#### turn_start / turn_end + +Fired for each turn (one LLM response + tool calls). + +```typescript +pi.on("turn_start", async (event, ctx) => { + // event.turnIndex, event.timestamp +}); + +pi.on("turn_end", async (event, ctx) => { + // event.turnIndex, event.message, event.toolResults +}); +``` + +#### message_start / message_update / message_end + +Fired for message lifecycle updates. + +- `message_start` and `message_end` fire for user, assistant, and toolResult messages. +- `message_update` fires for assistant streaming updates. +- `message_end` handlers can return `{ message }` to replace the finalized message. The replacement must keep the same `role`. + +```typescript +pi.on("message_start", async (event, ctx) => { + // event.message +}); + +pi.on("message_update", async (event, ctx) => { + // event.message + // event.assistantMessageEvent (token-by-token stream event) +}); + +pi.on("message_end", async (event, ctx) => { + if (event.message.role !== "assistant") return; + + return { + message: { + ...event.message, + usage: { + ...event.message.usage, + cost: { + ...event.message.usage.cost, + total: 0.123, + }, + }, + }, + }; +}); +``` + +#### tool_execution_start / tool_execution_update / tool_execution_end + +Fired for tool execution lifecycle updates. + +In parallel tool mode: +- `tool_execution_start` is emitted in assistant source order during the preflight phase +- `tool_execution_update` events may interleave across tools +- `tool_execution_end` is emitted in tool completion order after each tool is finalized +- final `toolResult` message events are still emitted later in assistant source order + +```typescript +pi.on("tool_execution_start", async (event, ctx) => { + // event.toolCallId, event.toolName, event.args +}); + +pi.on("tool_execution_update", async (event, ctx) => { + // event.toolCallId, event.toolName, event.args, event.partialResult +}); + +pi.on("tool_execution_end", async (event, ctx) => { + // event.toolCallId, event.toolName, event.result, event.isError +}); +``` + +#### context + +Fired before each LLM call. Modify messages non-destructively. See [Session Format](session-format.md) for message types. + +```typescript +pi.on("context", async (event, ctx) => { + // event.messages - deep copy, safe to modify + const filtered = event.messages.filter(m => !shouldPrune(m)); + return { messages: filtered }; +}); +``` + +#### before_provider_headers + +Fired after the outgoing HTTP headers are assembled. Use it to add, override, or remove request headers. + +Handlers mutate `event.headers` in place. Set a key to a string to add or override it, or to `null` to delete it. + +```typescript +pi.on("before_provider_headers", (event, ctx) => { + // Add or override — e.g. a session id for gateway tracing/attribution + event.headers["x-session-id"] = ctx.sessionManager.getSessionId(); + + // Drop a tracking header pi adds for this call + event.headers["X-OpenRouter-Title"] = null; +}); +``` + +Runs once per provider request; retries reuse the same headers rather than re-firing the hook. + +#### before_provider_request + +Fired after the provider-specific payload is built, right before the request is sent. Handlers run in extension load order. Returning `undefined` keeps the payload unchanged. Returning any other value replaces the payload for later handlers and for the actual request. + +This hook can rewrite provider-level system instructions or remove them entirely. Those payload-level changes are not reflected by `ctx.getSystemPrompt()`, which reports Pi's system prompt string rather than the final serialized provider payload. + +```typescript +pi.on("before_provider_request", (event, ctx) => { + console.log(JSON.stringify(event.payload, null, 2)); + + // Optional: replace payload + // return { ...event.payload, temperature: 0 }; +}); +``` + +This is mainly useful for debugging provider serialization and cache behavior. + +#### after_provider_response + +Fired after an HTTP response is received and before its stream body is consumed. Handlers run in extension load order. + +```typescript +pi.on("after_provider_response", (event, ctx) => { + // event.status - HTTP status code + // event.headers - normalized response headers + if (event.status === 429) { + console.log("rate limited", event.headers["retry-after"]); + } +}); +``` + +Header availability depends on provider and transport. Providers that abstract HTTP responses may not expose headers. + +### Model Events + +#### model_select + +Fired when the model changes via `/model` command, model cycling (`Ctrl+P`), or session restore. + +```typescript +pi.on("model_select", async (event, ctx) => { + // event.model - newly selected model + // event.previousModel - previous model (undefined if first selection) + // event.source - "set" | "cycle" | "restore" + + const prev = event.previousModel + ? `${event.previousModel.provider}/${event.previousModel.id}` + : "none"; + const next = `${event.model.provider}/${event.model.id}`; + + ctx.ui.notify(`Model changed (${event.source}): ${prev} -> ${next}`, "info"); +}); +``` + +Use this to update UI elements (status bars, footers) or perform model-specific initialization when the active model changes. + +#### thinking_level_select + +Fired when the thinking level changes. This is notification-only; handler return values are ignored. + +```typescript +pi.on("thinking_level_select", async (event, ctx) => { + // event.level - newly selected thinking level + // event.previousLevel - previous thinking level + + ctx.ui.setStatus("thinking", `thinking: ${event.level}`); +}); +``` + +Use this to update extension UI when `pi.setThinkingLevel()`, model changes, or built-in thinking-level controls change the active thinking level. + +### Tool Events + +#### tool_call + +Fired after `tool_execution_start`, before the tool executes. **Can block.** Use `isToolCallEventType` to narrow and get typed inputs. + +Before `tool_call` runs, pi waits for previously emitted Agent events to finish draining through `AgentSession`. This means `ctx.sessionManager` is up to date through the current assistant tool-calling message. + +In the default parallel tool execution mode, sibling tool calls from the same assistant message are preflighted sequentially, then executed concurrently. `tool_call` is not guaranteed to see sibling tool results from that same assistant message in `ctx.sessionManager`. + +`event.input` is mutable. Mutate it in place to patch tool arguments before execution. + +Behavior guarantees: +- Mutations to `event.input` affect the actual tool execution +- Later `tool_call` handlers see mutations made by earlier handlers +- No re-validation is performed after your mutation +- Return values from `tool_call` only control blocking via `{ block: true, reason?: string }` + +```typescript +import { isToolCallEventType } from "@earendil-works/pi-coding-agent"; + +pi.on("tool_call", async (event, ctx) => { + // event.toolName - "bash", "read", "write", "edit", etc. + // event.toolCallId + // event.input - tool parameters (mutable) + + // Built-in tools: no type params needed + if (isToolCallEventType("bash", event)) { + // event.input is { command: string; timeout?: number } + event.input.command = `source ~/.profile\n${event.input.command}`; + + if (event.input.command.includes("rm -rf")) { + return { block: true, reason: "Dangerous command" }; + } + } + + if (isToolCallEventType("read", event)) { + // event.input is { path: string; offset?: number; limit?: number } + console.log(`Reading: ${event.input.path}`); + } +}); +``` + +#### Typing custom tool input + +Custom tools should export their input type: + +```typescript +// my-extension.ts +export type MyToolInput = Static; +``` + +Use `isToolCallEventType` with explicit type parameters: + +```typescript +import { isToolCallEventType } from "@earendil-works/pi-coding-agent"; +import type { MyToolInput } from "my-extension"; + +pi.on("tool_call", (event) => { + if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) { + event.input.action; // typed + } +}); +``` + +#### tool_result + +Fired after tool execution finishes and before `tool_execution_end` plus the final tool result message events are emitted. **Can modify result.** + +In parallel tool mode, `tool_result` and `tool_execution_end` may interleave in tool completion order, while final `toolResult` message events are still emitted later in assistant source order. + +`tool_result` handlers chain like middleware: +- Handlers run in extension load order +- Each handler sees the latest result after previous handler changes +- Handlers can return partial patches (`content`, `details`, `isError`, or `usage`); omitted fields keep their current values + +Use `ctx.signal` for nested async work inside the handler. This lets Esc cancel model calls, `fetch()`, and other abort-aware operations started by the extension. + +```typescript +import { isBashToolResult } from "@earendil-works/pi-coding-agent"; + +pi.on("tool_result", async (event, ctx) => { + // event.toolName, event.toolCallId, event.input + // event.content, event.details, event.isError, event.usage + + if (isBashToolResult(event)) { + // event.details is typed as BashToolDetails + } + + const response = await fetch("https://example.com/summarize", { + method: "POST", + body: JSON.stringify({ content: event.content }), + signal: ctx.signal, + }); + + // Modify result: + return { content: [...], details: {...}, isError: false, usage: nestedModelUsage }; +}); +``` + +### User Bash Events + +#### user_bash + +Fired when user executes `!` or `!!` commands. **Can intercept.** + +```typescript +import { createLocalBashOperations } from "@earendil-works/pi-coding-agent"; + +pi.on("user_bash", (event, ctx) => { + // event.command - the bash command + // event.excludeFromContext - true if !! prefix + // event.cwd - working directory + + // Option 1: Provide custom operations (e.g., SSH) + return { operations: remoteBashOps }; + + // Option 2: Wrap pi's built-in local bash backend + const local = createLocalBashOperations(); + return { + operations: { + exec(command, cwd, options) { + return local.exec(`source ~/.profile\n${command}`, cwd, options); + } + } + }; + + // Option 3: Full replacement - return result directly + return { result: { output: "...", exitCode: 0, cancelled: false, truncated: false } }; +}); +``` + +### Input Events + +#### input + +Fired when user input is received, after extension commands are checked but before skill and template expansion. The event sees the raw input text, so `/skill:foo` and `/template` are not yet expanded. + +**Processing order:** +1. Extension commands (`/cmd`) checked first - if found, handler runs and input event is skipped +2. `input` event fires - can intercept, transform, or handle +3. If not handled: skill commands (`/skill:name`) expanded to skill content +4. If not handled: prompt templates (`/template`) expanded to template content +5. Agent processing begins (`before_agent_start`, etc.) + +```typescript +pi.on("input", async (event, ctx) => { + // event.text - raw input (before skill/template expansion) + // event.images - attached images, if any + // event.source - "interactive" (typed), "rpc" (API), or "extension" (via sendUserMessage) + // event.streamingBehavior - "steer" | "followUp" | undefined + // undefined when idle, "steer" for mid-stream interrupts, + // "followUp" for messages queued until the agent finishes + + // Transform: rewrite input before expansion + if (event.text.startsWith("?quick ")) + return { action: "transform", text: `Respond briefly: ${event.text.slice(7)}` }; + + // Handle: respond without LLM (extension shows its own feedback) + if (event.text === "ping") { + ctx.ui.notify("pong", "info"); + return { action: "handled" }; + } + + // Route by source: skip processing for extension-injected messages + if (event.source === "extension") return { action: "continue" }; + + // Intercept skill commands before expansion + if (event.text.startsWith("/skill:")) { + // Could transform, block, or let pass through + } + + return { action: "continue" }; // Default: pass through to expansion +}); +``` + +**Results:** +- `continue` - pass through unchanged (default if handler returns nothing) +- `transform` - modify text/images, then continue to expansion +- `handled` - skip agent entirely (first handler to return this wins) + +Transforms chain across handlers. See [input-transform.ts](../examples/extensions/input-transform.ts) and [input-transform-streaming.ts](../examples/extensions/input-transform-streaming.ts) for `streamingBehavior`-aware routing. + +## ExtensionContext + +All handlers receive `ctx: ExtensionContext`. + +### ctx.ui + +UI methods for user interaction. See [Custom UI](#custom-ui) for full details. + +### ctx.mode + +Current run mode: `"tui"`, `"rpc"`, `"json"`, or `"print"`. Use `ctx.mode === "tui"` to guard terminal-only features such as `custom()`, component factories, terminal input, and direct TUI rendering. + +### ctx.hasUI + +`true` in TUI and RPC modes. `false` in print mode (`-p`) and JSON mode. Use this to guard dialog methods (`select`, `confirm`, `input`, `editor`) and fire-and-forget methods (`notify`, `setStatus`, `setWidget`, `setTitle`, `setEditorText`) that work in both TUI and RPC modes. In RPC mode, some TUI-specific methods are no-ops or return defaults (see [rpc.md](rpc.md#extension-ui-protocol)). + +### ctx.cwd + +Current working directory. + +Use `CONFIG_DIR_NAME` instead of hardcoding `.pi` when constructing project-local config paths. Rebranded distributions can use a different config directory name. + +```typescript +import { CONFIG_DIR_NAME, type ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { join } from "node:path"; + +export default function (pi: ExtensionAPI) { + pi.on("session_start", (_event, ctx) => { + const projectConfigPath = join(ctx.cwd, CONFIG_DIR_NAME, "my-extension.json"); + // ... + }); +} +``` + +### ctx.isProjectTrusted() + +Returns whether project-local trust is active for the current session context. This includes temporary trust decisions and CLI trust overrides, not just saved decisions in the global trust store. + +Use this before reading project-local extension configuration that should only be honored for trusted projects. + +### ctx.sessionManager + +Read-only access to session state. See [Session Format](session-format.md) for the full SessionManager API and entry types. + +For `tool_call`, this state is synchronized through the current assistant message before handlers run. In parallel tool execution mode it is still not guaranteed to include sibling tool results from the same assistant message. + +```typescript +ctx.sessionManager.getEntries() // All entries +ctx.sessionManager.getBranch() // Current branch +ctx.sessionManager.buildContextEntries() // Active branch entries with compaction applied +ctx.sessionManager.getLeafId() // Current leaf entry ID +``` + +### ctx.modelRegistry / ctx.model / ctx.thinkingLevel / ctx.scopedModels + +Access to models, providers, and resolved authentication. `ctx.modelRegistry.getProvider(id)` returns the effective pi-ai provider, while `getProviderAuth(id)` resolves its current API key, headers, base URL, and provider-scoped environment without requiring a loaded model. `ctx.model` is the active model, and `ctx.thinkingLevel` is its current effective thinking level. + +`ctx.scopedModels` is the read-only list of models scoped to the current session — the same set the `/scoped-models` command shows. It is resolved at session start from the `--models` CLI flag and the `enabledModels` setting (matched against the available catalogue with minimatch on `provider/modelId` or a bare `modelId`). It is empty when no scoping is configured, meaning every available model is usable. Each entry is `{ model, thinkingLevel? }`, where `thinkingLevel` is set only when a pattern pinned it (e.g. `anthropic/*:high`). Use it to populate a model picker that mirrors the built-in one instead of enumerating the whole catalogue via `ctx.modelRegistry.getAvailable()`. + +### ctx.signal + +The current agent abort signal, or `undefined` when no agent turn is active. + +Use this for abort-aware nested work started by extension handlers, for example: +- `fetch(..., { signal: ctx.signal })` +- model calls that accept `signal` +- file or process helpers that accept `AbortSignal` + +`ctx.signal` is typically defined during active turn events such as `tool_call`, `tool_result`, `message_update`, and `turn_end`. +It is usually `undefined` in idle or non-turn contexts such as session events, extension commands, and shortcuts fired while pi is idle. + +```typescript +pi.on("tool_result", async (event, ctx) => { + const response = await fetch("https://example.com/api", { + method: "POST", + body: JSON.stringify(event), + signal: ctx.signal, + }); + + const data = await response.json(); + return { details: data }; +}); +``` + +### ctx.isIdle() / ctx.abort() / ctx.hasPendingMessages() + +Control flow helpers. `ctx.isIdle()` is false while Pi is processing an agent run, automatic retry, auto-compaction retry, or queued continuation. + +### ctx.shutdown() + +Request a graceful shutdown of pi. + +- **Interactive mode:** Deferred until the agent becomes idle (after processing all queued steering and follow-up messages). +- **RPC mode:** Deferred until the next idle state (after completing the current command response, when waiting for the next command). +- **Print mode:** No-op. The process exits automatically when all prompts are processed. + +Emits `session_shutdown` event to all extensions before exiting. Available in all contexts (event handlers, tools, commands, shortcuts). + +```typescript +pi.on("tool_call", (event, ctx) => { + if (isFatal(event.input)) { + ctx.shutdown(); + } +}); +``` + +### ctx.getContextUsage() + +Returns current context usage for the active model. Uses last assistant usage when available, then estimates tokens for trailing messages. + +```typescript +const usage = ctx.getContextUsage(); +if (usage && usage.tokens > 100_000) { + // ... +} +``` + +### ctx.compact() + +Trigger compaction without awaiting completion. Use `onComplete` and `onError` for follow-up actions. + +```typescript +ctx.compact({ + customInstructions: "Focus on recent changes", + onComplete: (result) => { + ctx.ui.notify("Compaction completed", "info"); + }, + onError: (error) => { + ctx.ui.notify(`Compaction failed: ${error.message}`, "error"); + }, +}); +``` + +### ctx.getSystemPrompt() + +Returns Pi's current system prompt string. + +- During `before_agent_start`, this reflects chained system-prompt changes made so far for the current turn. +- It does not include later `context` message mutations. +- It does not include `before_provider_request` payload rewrites. +- If later-loaded extensions run after yours, they can still change what is ultimately sent. + +```typescript +pi.on("before_agent_start", (event, ctx) => { + const prompt = ctx.getSystemPrompt(); + console.log(`System prompt length: ${prompt.length}`); +}); +``` + +## ExtensionCommandContext + +Command handlers receive `ExtensionCommandContext`, which extends `ExtensionContext` with session control methods. These are only available in commands because they can deadlock if called from event handlers. + +### ctx.getSystemPromptOptions() + +Returns the base inputs Pi currently uses to build the system prompt. + +```typescript +const options = ctx.getSystemPromptOptions(); +const contextPaths = options.contextFiles?.map((file) => file.path) ?? []; +``` + +This has the same shape and mutability as `before_agent_start` `event.systemPromptOptions`: custom prompt, active tools, tool snippets, prompt guidelines, appended system prompt text, cwd, loaded context files, and loaded skills. It may include full context file contents, so treat it as sensitive extension-local data and avoid exposing it through command lists, logs, or autocomplete metadata. + +This reports the current base prompt inputs. It does not include per-turn `before_agent_start` chained system-prompt changes, later `context` event message mutations, or `before_provider_request` payload rewrites. + +### ctx.waitForIdle() + +Wait for the agent to fully settle, including automatic retries, auto-compaction retries, and queued continuations: + +```typescript +pi.registerCommand("my-cmd", { + handler: async (args, ctx) => { + await ctx.waitForIdle(); + // Agent is now idle, safe to modify session + }, +}); +``` + +### ctx.newSession(options?) + +Create a new session: + +```typescript +const parentSession = ctx.sessionManager.getSessionFile(); +const kickoff = "Continue in the replacement session"; + +const result = await ctx.newSession({ + parentSession, + setup: async (sm) => { + sm.appendMessage({ + role: "user", + content: [{ type: "text", text: "Context from previous session..." }], + timestamp: Date.now(), + }); + }, + withSession: async (ctx) => { + // Use only the replacement-session ctx here. + await ctx.sendUserMessage(kickoff); + }, +}); + +if (result.cancelled) { + // An extension cancelled the new session +} +``` + +Options: +- `parentSession`: parent session file to record in the new session header +- `setup`: mutate the new session's `SessionManager` before `withSession` runs +- `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `pi` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns). + +### ctx.fork(entryId, options?) + +Fork from a specific entry, creating a new session file: + +```typescript +const result = await ctx.fork("entry-id-123", { + withSession: async (ctx) => { + // Use only the replacement-session ctx here. + ctx.ui.notify("Now in the forked session", "info"); + }, +}); +if (result.cancelled) { + // An extension cancelled the fork +} + +const cloneResult = await ctx.fork("entry-id-456", { position: "at" }); +if (cloneResult.cancelled) { + // An extension cancelled the clone +} +``` + +Options: +- `position`: `"before"` (default) forks before the selected user message, restoring that prompt into the editor +- `position`: `"at"` duplicates the active path through the selected entry without restoring editor text +- `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `pi` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns). + +### ctx.navigateTree(targetId, options?) + +Navigate to a different point in the session tree: + +```typescript +const result = await ctx.navigateTree("entry-id-456", { + summarize: true, + customInstructions: "Focus on error handling changes", + replaceInstructions: false, // true = replace default prompt entirely + label: "review-checkpoint", +}); +``` + +Options: +- `summarize`: Whether to generate a summary of the abandoned branch +- `customInstructions`: Custom instructions for the summarizer +- `replaceInstructions`: If true, `customInstructions` replaces the default prompt instead of being appended +- `label`: Label to attach to the branch summary entry (or target entry if not summarizing) + +### ctx.switchSession(sessionPath, options?) + +Switch to a different session file: + +```typescript +const result = await ctx.switchSession("/path/to/session.jsonl", { + withSession: async (ctx) => { + await ctx.sendUserMessage("Resume work in the replacement session"); + }, +}); +if (result.cancelled) { + // An extension cancelled the switch via session_before_switch +} +``` + +Options: +- `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `pi` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns). + +To discover available sessions, use the static `SessionManager.list()` or `SessionManager.listAll()` methods: + +```typescript +import { SessionManager } from "@earendil-works/pi-coding-agent"; + +pi.registerCommand("switch", { + description: "Switch to another session", + handler: async (args, ctx) => { + const sessions = await SessionManager.list(ctx.cwd); + if (sessions.length === 0) return; + const choice = await ctx.ui.select( + "Pick session:", + sessions.map(s => s.file), + ); + if (choice) { + await ctx.switchSession(choice, { + withSession: async (ctx) => { + ctx.ui.notify("Switched session", "info"); + }, + }); + } + }, +}); +``` + +### Session replacement lifecycle and footguns + +`withSession` receives a fresh `ReplacedSessionContext`, which extends `ExtensionCommandContext` with async `sendMessage()` and `sendUserMessage()` helpers bound to the replacement session. + +Lifecycle and footguns: +- `withSession` runs only after the old session has emitted `session_shutdown`, the old runtime has been torn down, the replacement session has been rebound, and the new extension instance has already received `session_start`. +- The callback still executes in the original closure, not inside the new extension instance. That means your old extension instance may already have run its shutdown cleanup before `withSession` starts. +- Captured old `pi` / old command `ctx` session-bound objects are stale after replacement and will throw if used. Use only the `ctx` passed to `withSession` for session-bound work. +- Previously extracted raw objects are still your responsibility. For example, if you capture `const sm = ctx.sessionManager` before replacement, `sm` is still the old `SessionManager` object. Do not reuse it after replacement. +- Code in `withSession` should assume any state invalidated by your `session_shutdown` handler is already gone. Only capture plain data that survives shutdown cleanly, such as strings, ids, and serialized config. + +Safe pattern: + +```typescript +pi.registerCommand("handoff", { + handler: async (_args, ctx) => { + const kickoff = "Continue from the replacement session"; + await ctx.newSession({ + withSession: async (ctx) => { + await ctx.sendUserMessage(kickoff); + }, + }); + }, +}); +``` + +Unsafe pattern: + +```typescript +pi.registerCommand("handoff", { + handler: async (_args, ctx) => { + const oldSessionManager = ctx.sessionManager; + await ctx.newSession({ + withSession: async (_ctx) => { + // stale old objects: do not do this + oldSessionManager.getSessionFile(); + pi.sendUserMessage("wrong"); + }, + }); + }, +}); +``` + +### ctx.reload() + +Run the same reload flow as `/reload`. + +```typescript +pi.registerCommand("reload-runtime", { + description: "Reload extensions, skills, prompts, themes, and context files", + handler: async (_args, ctx) => { + await ctx.reload(); + return; + }, +}); +``` + +Important behavior: +- `await ctx.reload()` emits `session_shutdown` for the current extension runtime +- It then reloads resources and emits `session_start` with `reason: "reload"` and `resources_discover` with reason `"reload"` +- The currently running command handler still continues in the old call frame +- Code after `await ctx.reload()` still runs from the pre-reload version +- Code after `await ctx.reload()` must not assume old in-memory extension state is still valid +- After the handler returns, future commands/events/tool calls use the new extension version + +For predictable behavior, treat reload as terminal for that handler (`await ctx.reload(); return;`). + +Tools run with `ExtensionContext`, so they cannot call `ctx.reload()` directly. Use a command as the reload entrypoint, then expose a tool that queues that command as a follow-up user message. + +Example tool the LLM can call to trigger reload: + +```typescript +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { Type } from "typebox"; + +export default function (pi: ExtensionAPI) { + pi.registerCommand("reload-runtime", { + description: "Reload extensions, skills, prompts, themes, and context files", + handler: async (_args, ctx) => { + await ctx.reload(); + return; + }, + }); + + pi.registerTool({ + name: "reload_runtime", + label: "Reload Runtime", + description: "Reload extensions, skills, prompts, themes, and context files", + parameters: Type.Object({}), + async execute() { + pi.sendUserMessage("/reload-runtime", { deliverAs: "followUp" }); + return { + content: [{ type: "text", text: "Queued /reload-runtime as a follow-up command." }], + }; + }, + }); +} +``` + +## ExtensionAPI Methods + +### pi.on(event, handler) + +Subscribe to events. See [Events](#events) for event types and return values. + +### pi.registerTool(definition) + +Register a custom tool callable by the LLM. See [Custom Tools](#custom-tools) for full details. + +`pi.registerTool()` works both during extension load and after startup. You can call it inside `session_start`, command handlers, or other event handlers. New tools are refreshed immediately in the same session, so they appear in `pi.getAllTools()` and are callable by the LLM without `/reload`. + +Use `pi.setActiveTools()` to enable or disable tools (including dynamically added tools) at runtime. + +Use `promptSnippet` to opt a custom tool into a one-line entry in `Available tools`, and `promptGuidelines` to append tool-specific bullets to the default `Guidelines` section when the tool is active. + +**Important:** `promptGuidelines` bullets are appended flat to the `Guidelines` section with no tool name prefix. Each guideline must name the tool it refers to — avoid "Use this tool when..." because the LLM cannot tell which tool "this" means. Write "Use my_tool when..." instead. + +See [dynamic-tools.ts](../examples/extensions/dynamic-tools.ts) for a full example. + +```typescript +import { Type } from "typebox"; +import { StringEnum } from "@earendil-works/pi-ai"; + +pi.registerTool({ + name: "my_tool", + label: "My Tool", + description: "What this tool does", + promptSnippet: "Summarize or transform text according to action", + promptGuidelines: ["Use my_tool when the user asks to summarize previously generated text."], + parameters: Type.Object({ + action: StringEnum(["list", "add"] as const), + text: Type.Optional(Type.String()), + }), + prepareArguments(args) { + // Optional compatibility shim. Runs before schema validation. + // Return the current schema shape, for example to fold legacy fields + // into the modern parameter object. + return args; + }, + + async execute(toolCallId, params, signal, onUpdate, ctx) { + // Stream progress + onUpdate?.({ content: [{ type: "text", text: "Working..." }] }); + + return { + content: [{ type: "text", text: "Done" }], + details: { result: "..." }, + }; + }, + + // Optional: Custom rendering + renderCall(args, theme, context) { ... }, + renderResult(result, options, theme, context) { ... }, +}); +``` + +### pi.sendMessage(message, options?) + +Inject a custom message into the session. Custom messages participate in LLM context. For durable TUI-only content that should not be sent to the LLM, use [`pi.appendEntry()`](#piappendentrycustomtype-data) with [`pi.registerEntryRenderer()`](#piregisterentryrenderercustomtype-renderer). + +```typescript +pi.sendMessage({ + customType: "my-extension", + content: "Message text", + display: true, + details: { ... }, +}, { + triggerTurn: true, + deliverAs: "steer", +}); +``` + +**Options:** +- `deliverAs` - Delivery mode: + - `"steer"` (default) - Queues the message while streaming. Delivered after the current assistant turn finishes executing its tool calls, before the next LLM call. + - `"followUp"` - Waits for agent to finish. Delivered only when agent has no more tool calls. + - `"nextTurn"` - Queued for next user prompt. Does not interrupt or trigger anything. +- `triggerTurn: true` - If agent is idle, trigger an LLM response immediately. Only applies to `"steer"` and `"followUp"` modes (ignored for `"nextTurn"`). + +### pi.sendUserMessage(content, options?) + +Send a user message to the agent. Unlike `sendMessage()` which sends custom messages, this sends an actual user message that appears as if typed by the user. Always triggers a turn. + +```typescript +// Simple text message +pi.sendUserMessage("What is 2+2?"); + +// With content array (text + images) +pi.sendUserMessage([ + { type: "text", text: "Describe this image:" }, + { type: "image", source: { type: "base64", mediaType: "image/png", data: "..." } }, +]); + +// During streaming - must specify delivery mode +pi.sendUserMessage("Focus on error handling", { deliverAs: "steer" }); +pi.sendUserMessage("And then summarize", { deliverAs: "followUp" }); +``` + +**Options:** +- `deliverAs` - Required when agent is streaming: + - `"steer"` - Queues the message for delivery after the current assistant turn finishes executing its tool calls + - `"followUp"` - Waits for agent to finish all tools + +When not streaming, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`, throws an error. + +See [send-user-message.ts](../examples/extensions/send-user-message.ts) for a complete example. + +### pi.appendEntry(customType, data?) + +Persist extension data. Custom entries do NOT participate in LLM context. In interactive mode, they can also render inside the chat transcript when paired with `pi.registerEntryRenderer()`. + +```typescript +pi.appendEntry("my-state", { count: 42 }); +pi.appendEntry("status-card", { title: "Indexed files", count: 17 }); + +// Restore on reload +pi.on("session_start", async (_event, ctx) => { + for (const entry of ctx.sessionManager.getEntries()) { + if (entry.type === "custom" && entry.customType === "my-state") { + // Reconstruct from entry.data + } + } +}); +``` + +### pi.setSessionName(name) + +Set the session display name (shown in session selector instead of first message). + +```typescript +pi.setSessionName("Refactor auth module"); +``` + +### pi.getSessionName() + +Get the current session name, if set. + +```typescript +const name = pi.getSessionName(); +if (name) { + console.log(`Session: ${name}`); +} +``` + +### pi.setLabel(entryId, label) + +Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation (shown in `/tree` selector). + +```typescript +// Set a label +pi.setLabel(entryId, "checkpoint-before-refactor"); + +// Clear a label +pi.setLabel(entryId, undefined); + +// Read labels via sessionManager +const label = ctx.sessionManager.getLabel(entryId); +``` + +Labels persist in the session and survive restarts. Use them to mark important points (turns, checkpoints) in the conversation tree. + +### pi.registerCommand(name, options) + +Register a command. + +If multiple extensions register the same command name, pi keeps them all and assigns numeric invocation suffixes in load order, for example `/review:1` and `/review:2`. + +```typescript +pi.registerCommand("stats", { + description: "Show session statistics", + handler: async (args, ctx) => { + const count = ctx.sessionManager.getEntries().length; + ctx.ui.notify(`${count} entries`, "info"); + } +}); +``` + +Optional: add argument auto-completion for `/command ...`: + +```typescript +import type { AutocompleteItem } from "@earendil-works/pi-tui"; + +pi.registerCommand("deploy", { + description: "Deploy to an environment", + getArgumentCompletions: (prefix: string): AutocompleteItem[] | null => { + const envs = ["dev", "staging", "prod"]; + const items = envs.map((e) => ({ value: e, label: e })); + const filtered = items.filter((i) => i.value.startsWith(prefix)); + return filtered.length > 0 ? filtered : null; + }, + handler: async (args, ctx) => { + ctx.ui.notify(`Deploying: ${args}`, "info"); + }, +}); +``` + +### pi.getCommands() + +Get the slash commands available for invocation via `prompt` in the current session. Includes extension commands, prompt templates, and skill commands. +The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills. + +```typescript +const commands = pi.getCommands(); +const bySource = commands.filter((command) => command.source === "extension"); +const userScoped = commands.filter((command) => command.sourceInfo.scope === "user"); +``` + +Each entry has this shape: + +```typescript +{ + name: string; // Invokable command name without the leading slash. May be suffixed like "review:1" + description?: string; + source: "extension" | "prompt" | "skill"; + sourceInfo: { + path: string; + source: string; + scope: "user" | "project" | "temporary"; + origin: "package" | "top-level"; + baseDir?: string; + }; +} +``` + +Use `sourceInfo` as the canonical provenance field. Do not infer ownership from command names or from ad hoc path parsing. + +Built-in interactive commands (like `/model` and `/settings`) are not included here. They are handled only in interactive +mode and would not execute if sent via `prompt`. + +### pi.registerMessageRenderer(customType, renderer) + +Register a custom TUI renderer for custom messages with your `customType`. Custom messages are created with `pi.sendMessage()` and participate in LLM context. See [Custom UI](#custom-ui). + +### pi.registerEntryRenderer(customType, renderer) + +Register a custom TUI renderer for custom entries with your `customType`. Custom entries are created with `pi.appendEntry()` and do not participate in LLM context. + +```typescript +import { Box, Text } from "@earendil-works/pi-tui"; + +pi.registerEntryRenderer("status-card", (entry, { expanded }, theme) => { + const data = entry.data as { title: string; count: number }; + const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text)); + box.addChild(new Text(`${theme.bold(data.title)}: ${data.count}`)); + if (expanded) { + box.addChild(new Text(theme.fg("dim", JSON.stringify(data, null, 2)))); + } + return box; +}); + +pi.appendEntry("status-card", { title: "Indexed files", count: 17 }); +``` + +### pi.registerShortcut(shortcut, options) + +Register a keyboard shortcut. See [keybindings.md](keybindings.md) for the shortcut format and built-in keybindings. + +```typescript +pi.registerShortcut("ctrl+shift+p", { + description: "Toggle plan mode", + handler: async (ctx) => { + ctx.ui.notify("Toggled!"); + }, +}); +``` + +### pi.registerFlag(name, options) + +Register a CLI flag. + +```typescript +pi.registerFlag("plan", { + description: "Start in plan mode", + type: "boolean", + default: false, +}); + +// Check value +if (pi.getFlag("plan")) { + // Plan mode enabled +} +``` + +### pi.exec(command, args, options?) + +Execute a shell command. + +```typescript +const result = await pi.exec("git", ["status"], { signal, timeout: 5000 }); +// result.stdout, result.stderr, result.code, result.killed +``` + +### pi.getActiveTools() / pi.getAllTools() / pi.setActiveTools(names) + +Manage active tools. This works for both built-in tools and dynamically registered tools. `pi.getActiveTools()` returns the active tool names as `string[]`; `pi.getAllTools()` returns metadata for all configured tools. + +```typescript +const active = pi.getActiveTools(); // ["read", "bash", ...] +const all = pi.getAllTools(); +// all = [{ +// name: "read", +// description: "Read file contents...", +// parameters: ..., +// promptGuidelines: ["Use read to examine files instead of cat or sed."], +// sourceInfo: { path: "", source: "builtin", scope: "temporary", origin: "top-level" } +// }, ...] +const builtinTools = all.filter((t) => t.sourceInfo.source === "builtin"); +const extensionTools = all.filter((t) => t.sourceInfo.source !== "builtin" && t.sourceInfo.source !== "sdk"); +pi.setActiveTools([...new Set([...active, "my_custom_tool"])]); // Keep current tools and enable my_custom_tool +pi.setActiveTools(["read", "bash"]); // Switch to read-only +``` + +`pi.getAllTools()` returns `name`, `description`, `parameters`, `promptGuidelines`, and `sourceInfo`. + +Typical `sourceInfo.source` values: +- `builtin` for built-in tools +- `sdk` for tools passed via `createAgentSession({ customTools })` +- extension source metadata for tools registered by extensions + +### pi.setModel(model) + +Set the current model. Returns `false` if no API key is available for the model. See [models.md](models.md) for configuring custom models. + +```typescript +const model = ctx.modelRegistry.find("anthropic", "claude-sonnet-4-5"); +if (model) { + const success = await pi.setModel(model); + if (!success) { + ctx.ui.notify("No API key for this model", "error"); + } +} +``` + +### pi.getThinkingLevel() / pi.setThinkingLevel(level) + +Get or set the thinking level. Level is clamped to model capabilities (non-reasoning models always use "off"). Changes emit `thinking_level_select`. + +```typescript +const current = pi.getThinkingLevel(); // "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" +pi.setThinkingLevel("high"); +``` + +### pi.events + +Shared event bus for communication between extensions: + +```typescript +pi.events.on("my:event", (data) => { ... }); +pi.events.emit("my:event", { ... }); +``` + +### pi.registerProvider(name, config) + +Register or override a model provider dynamically. Useful for proxies, custom endpoints, or team-wide model configurations. + +Calls made during the extension factory function are queued and applied once the runner initialises. Calls made after that — for example from a command handler following a user setup flow — take effect immediately without requiring a `/reload`. + +Dynamic providers can implement `refreshModels`. Pi calls it during model refresh, publishes the returned list synchronously through the provider, and passes the canonical credential/store/network/signal context. The extension decides whether to persist the catalog through `context.store`; live servers such as llama.cpp can ignore it. + +Extensions that need native provider auth, filtering, refresh, or stream behavior can register a complete `Provider` from `@earendil-works/pi-ai`. The provider becomes the composition base and `models.json` overrides still apply above it. + +```typescript +import { createProvider, openAICompletionsApi } from "@earendil-works/pi-ai"; + +const provider = createProvider({ + id: "local-server", + name: "Local Server", + baseUrl: "http://localhost:8080/v1", + auth: { + apiKey: { + name: "Local server setup", + async login(interaction) { + return { + type: "api_key", + key: await interaction.prompt({ type: "secret", message: "API key" }), + }; + }, + async resolve({ credential }) { + return credential?.key + ? { auth: { apiKey: credential.key }, source: "stored API key" } + : undefined; + }, + }, + }, + models: [], + api: openAICompletionsApi(), +}); + +pi.registerProvider(provider); + +// Register a new provider with custom models +pi.registerProvider("my-proxy", { + name: "My Proxy", + baseUrl: "https://proxy.example.com", + apiKey: "$PROXY_API_KEY", // env var reference + api: "anthropic-messages", + models: [ + { + id: "claude-sonnet-4-20250514", + name: "Claude 4 Sonnet (proxy)", + reasoning: false, + input: ["text", "image"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 200000, + maxTokens: 16384 + } + ] +}); + +// Register a live llama.cpp catalog without persisting discovered models +pi.registerProvider("llama.cpp", { + baseUrl: "http://localhost:8080/v1", + apiKey: "local", + api: "openai-completions", + async refreshModels({ signal }) { + const response = await fetch("http://localhost:8080/v1/models", { signal }); + const { data } = await response.json(); + return data.map(({ id }) => ({ + id, + name: id, + reasoning: false, + input: ["text"], + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 128000, + maxTokens: 16384 + })); + } +}); + +// Override baseUrl for an existing provider (keeps all models) +pi.registerProvider("anthropic", { + baseUrl: "https://proxy.example.com" +}); + +// Register provider with OAuth support for /login +pi.registerProvider("corporate-ai", { + baseUrl: "https://ai.corp.com", + api: "openai-responses", + models: [...], + oauth: { + name: "Corporate AI (SSO)", + async login(callbacks) { + // Custom OAuth flow + callbacks.onAuth({ url: "https://sso.corp.com/..." }); + const code = await callbacks.onPrompt({ message: "Enter code:" }); + return { refresh: code, access: code, expires: Date.now() + 3600000 }; + }, + async refreshToken(credentials) { + // Refresh logic + return credentials; + }, + getApiKey(credentials) { + return credentials.access; + } + } +}); +``` + +The object form accepts a complete pi-ai `Provider`, including native `auth`, `getModels`, `refreshModels`, `filterModels`, `stream`, and `streamSimple` behavior. + +**Legacy config options:** +- `name` - Display name for the provider in UI such as `/login`. +- `baseUrl` - API endpoint URL. Required when defining models. +- `apiKey` - API key literal, environment interpolation (`$ENV_VAR` or `${ENV_VAR}`), or leading `!command`. Required when defining models (unless `oauth` provided). `$$` escapes `$`, and `$!` escapes a literal `!` without triggering command execution. +- `api` - API type: `"anthropic-messages"`, `"openai-completions"`, `"openai-responses"`, etc. +- `headers` - Custom headers to include in requests. +- `authHeader` - If true, adds `Authorization: Bearer` header automatically. +- `models` - Array of model definitions. If provided, replaces all existing models for this provider. Model definitions can set `baseUrl` to override the provider endpoint for that model. +- `refreshModels` - Async dynamic discovery callback. Its returned models replace extension-provided models. Use the scoped `context.store` only when results should persist. +- `oauth` - OAuth provider config for `/login` support. When provided, the provider appears in the login menu. +- `streamSimple` - Custom streaming implementation for non-standard APIs. + +See [custom-provider.md](custom-provider.md) for advanced topics: custom streaming APIs, OAuth details, model definition reference. + +### pi.unregisterProvider(name) + +Remove a previously registered provider and its models. Built-in models that were overridden by the provider are restored. Has no effect if the provider was not registered. + +Like `registerProvider`, this takes effect immediately when called after the initial load phase, so a `/reload` is not required. + +```typescript +pi.registerCommand("my-setup-teardown", { + description: "Remove the custom proxy provider", + handler: async (_args, _ctx) => { + pi.unregisterProvider("my-proxy"); + }, +}); +``` + +## State Management + +Extensions with state should store it in tool result `details` for proper branching support: + +```typescript +export default function (pi: ExtensionAPI) { + let items: string[] = []; + + // Reconstruct state from session + pi.on("session_start", async (_event, ctx) => { + items = []; + for (const entry of ctx.sessionManager.getBranch()) { + if (entry.type === "message" && entry.message.role === "toolResult") { + if (entry.message.toolName === "my_tool") { + items = entry.message.details?.items ?? []; + } + } + } + }); + + pi.registerTool({ + name: "my_tool", + // ... + async execute(toolCallId, params, signal, onUpdate, ctx) { + items.push("new item"); + return { + content: [{ type: "text", text: "Added" }], + details: { items: [...items] }, // Store for reconstruction + }; + }, + }); +} +``` + +## Custom Tools + +Register tools the LLM can call via `pi.registerTool()`. Tools appear in the system prompt and can have custom rendering. + +Use `promptSnippet` for a short one-line entry in the `Available tools` section in the default system prompt. If omitted, custom tools are left out of that section. + +Use `promptGuidelines` to add tool-specific bullets to the default system prompt `Guidelines` section. These bullets are included only while the tool is active (for example, after `pi.setActiveTools([...])`). + +**Important:** `promptGuidelines` bullets are appended flat to the `Guidelines` section with no tool name prefix or grouping. Each guideline must name the tool it refers to — avoid "Use this tool when..." because the LLM cannot tell which tool "this" means. Write "Use my_tool when..." instead. + +Note: Some models are idiots and include the @ prefix in tool path arguments. Built-in tools strip a leading @ before resolving paths. If your custom tool accepts a path, normalize a leading @ as well. + +If your custom tool mutates files, use `withFileMutationQueue()` so it participates in the same per-file queue as built-in `edit` and `write`. This matters because tool calls run in parallel by default. Without the queue, two tools can read the same old file contents, compute different updates, and then whichever write lands last overwrites the other. + +Example failure case: your custom tool edits `foo.ts` while built-in `edit` also changes `foo.ts` in the same assistant turn. If your tool does not participate in the queue, both can read the original `foo.ts`, apply separate changes, and one of those changes is lost. + +Pass the real target file path to `withFileMutationQueue()`, not the raw user argument. Resolve it to an absolute path first, relative to `ctx.cwd` or your tool's working directory. For existing files, the helper canonicalizes through `realpath()`, so symlink aliases for the same file share one queue. For new files, it falls back to the resolved absolute path because there is nothing to `realpath()` yet. + +Queue the entire mutation window on that target path. That includes read-modify-write logic, not just the final write. + +```typescript +import { withFileMutationQueue } from "@earendil-works/pi-coding-agent"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { dirname, resolve } from "node:path"; + +async execute(_toolCallId, params, _signal, _onUpdate, ctx) { + const absolutePath = resolve(ctx.cwd, params.path); + + return withFileMutationQueue(absolutePath, async () => { + await mkdir(dirname(absolutePath), { recursive: true }); + const current = await readFile(absolutePath, "utf8"); + const next = current.replace(params.oldText, params.newText); + await writeFile(absolutePath, next, "utf8"); + + return { + content: [{ type: "text", text: `Updated ${params.path}` }], + details: {}, + }; + }); +} +``` + +### Tool Definition + +```typescript +import { Type } from "typebox"; +import { StringEnum } from "@earendil-works/pi-ai"; +import { Text } from "@earendil-works/pi-tui"; + +pi.registerTool({ + name: "my_tool", + label: "My Tool", + description: "What this tool does (shown to LLM)", + promptSnippet: "List or add items in the project todo list", + promptGuidelines: [ + "Use my_tool for todo planning instead of direct file edits when the user asks for a task list." + ], + parameters: Type.Object({ + action: StringEnum(["list", "add"] as const), // Use StringEnum for Google compatibility + text: Type.Optional(Type.String()), + }), + prepareArguments(args) { + if (!args || typeof args !== "object") return args; + const input = args as { action?: string; oldAction?: string }; + if (typeof input.oldAction === "string" && input.action === undefined) { + return { ...input, action: input.oldAction }; + } + return args; + }, + + async execute(toolCallId, params, signal, onUpdate, ctx) { + // Check for cancellation + if (signal?.aborted) { + return { content: [{ type: "text", text: "Cancelled" }] }; + } + + // Stream progress updates + onUpdate?.({ + content: [{ type: "text", text: "Working..." }], + details: { progress: 50 }, + }); + + // Run commands via pi.exec (captured from extension closure) + const result = await pi.exec("some-command", [], { signal }); + + // Return result + return { + content: [{ type: "text", text: "Done" }], // Sent to LLM + details: { data: result }, // For rendering & state + // usage: nestedModelResponse.usage, // Optional nested LLM usage + // Optional: stop after this tool batch when every finalized tool result + // in the batch also returns terminate: true. + terminate: true, + }; + }, + + // Optional: Custom rendering + renderCall(args, theme, context) { ... }, + renderResult(result, options, theme, context) { ... }, +}); +``` + +**Usage accounting:** If a tool makes nested LLM calls, return their combined `Usage` as `usage`. Pi persists it on the tool result and includes it in footer, `/session`, and RPC session totals. `tool_result` handlers can inspect or replace this value. + +**Signaling errors:** To mark a tool execution as failed (sets `isError: true` on the result and reports it to the LLM), throw an error from `execute`. Returning a value never sets the error flag regardless of what properties you include in the return object. + +**Early termination:** Return `terminate: true` from `execute()` to hint that the automatic follow-up LLM call should be skipped after the current tool batch. This only takes effect when every finalized tool result in that batch is terminating. See [examples/extensions/structured-output.ts](../examples/extensions/structured-output.ts) for a minimal example where the agent ends on a final structured-output tool call. + +```typescript +// Correct: throw to signal an error +async execute(toolCallId, params) { + if (!isValid(params.input)) { + throw new Error(`Invalid input: ${params.input}`); + } + return { content: [{ type: "text", text: "OK" }], details: {} }; +} +``` + +**Important:** Use `StringEnum` from `@earendil-works/pi-ai` for string enums. `Type.Union`/`Type.Literal` doesn't work with Google's API. + +**Argument preparation:** `prepareArguments(args)` is optional. If defined, it runs before schema validation and before `execute()`. Use it to mimic an older accepted input shape when pi resumes an older session whose stored tool call arguments no longer match the current schema. Return the object you want validated against `parameters`. Keep the public schema strict. Do not add deprecated compatibility fields to `parameters` just to keep old resumed sessions working. + +Example: an older session may contain an `edit` tool call with top-level `oldText` and `newText`, while the current schema only accepts `edits: [{ oldText, newText }]`. + +```typescript +pi.registerTool({ + name: "edit", + label: "Edit", + description: "Edit a single file using exact text replacement", + parameters: Type.Object({ + path: Type.String(), + edits: Type.Array( + Type.Object({ + oldText: Type.String(), + newText: Type.String(), + }), + ), + }), + prepareArguments(args) { + if (!args || typeof args !== "object") return args; + + const input = args as { + path?: string; + edits?: Array<{ oldText: string; newText: string }>; + oldText?: unknown; + newText?: unknown; + }; + + if (typeof input.oldText !== "string" || typeof input.newText !== "string") { + return args; + } + + return { + ...input, + edits: [...(input.edits ?? []), { oldText: input.oldText, newText: input.newText }], + }; + }, + async execute(toolCallId, params, signal, onUpdate, ctx) { + // params now matches the current schema + return { + content: [{ type: "text", text: `Applying ${params.edits.length} edit block(s)` }], + details: {}, + }; + }, +}); +``` + +### Overriding Built-in Tools + +Extensions can override built-in tools (`read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`) by registering a tool with the same name. Interactive mode displays a warning when this happens. + +```bash +# Extension's read tool replaces built-in read +pi -e ./tool-override.ts +``` + +Alternatively, use `--no-builtin-tools` to start without any built-in tools while keeping extension tools enabled: +```bash +# No built-in tools, only extension tools +pi --no-builtin-tools -e ./my-extension.ts +``` + +See [examples/extensions/tool-override.ts](../examples/extensions/tool-override.ts) for a complete example that overrides `read` with logging and access control. + +**Rendering:** Built-in renderer inheritance is resolved per slot. Execution override and rendering override are independent. If your override omits `renderCall`, the built-in `renderCall` is used. If your override omits `renderResult`, the built-in `renderResult` is used. If your override omits both, the built-in renderer is used automatically (syntax highlighting, diffs, etc.). This lets you wrap built-in tools for logging or access control without reimplementing the UI. + +**Prompt metadata:** `promptSnippet` and `promptGuidelines` are not inherited from the built-in tool. If your override should keep those prompt instructions, define them on the override explicitly. + +**Your implementation must match the exact result shape**, including the `details` type. The UI and session logic depend on these shapes for rendering and state tracking. + +Built-in tool implementations: +- [read.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/read.ts) - `ReadToolDetails` +- [bash.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/bash.ts) - `BashToolDetails` +- [edit.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/edit.ts) +- [write.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/write.ts) +- [grep.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/grep.ts) - `GrepToolDetails` +- [find.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/find.ts) - `FindToolDetails` +- [ls.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/ls.ts) - `LsToolDetails` + +### Remote Execution + +Built-in tools support pluggable operations for delegating to remote systems (SSH, containers, etc.): + +```typescript +import { createReadTool, createBashTool, type ReadOperations } from "@earendil-works/pi-coding-agent"; + +// Create tool with custom operations +const remoteRead = createReadTool(cwd, { + operations: { + readFile: (path) => sshExec(remote, `cat ${path}`), + access: (path) => sshExec(remote, `test -r ${path}`).then(() => {}), + } +}); + +// Register, checking flag at execution time +pi.registerTool({ + ...remoteRead, + async execute(id, params, signal, onUpdate, _ctx) { + const ssh = getSshConfig(); + if (ssh) { + const tool = createReadTool(cwd, { operations: createRemoteOps(ssh) }); + return tool.execute(id, params, signal, onUpdate); + } + return localRead.execute(id, params, signal, onUpdate); + }, +}); +``` + +**Operations interfaces:** `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `LsOperations`, `GrepOperations`, `FindOperations` + +For `user_bash`, extensions can reuse pi's local shell backend via `createLocalBashOperations()` instead of reimplementing local process spawning, shell resolution, and process-tree termination. + +The bash tool also supports a spawn hook to adjust the command, cwd, or env before execution: + +```typescript +import { createBashTool } from "@earendil-works/pi-coding-agent"; + +const bashTool = createBashTool(cwd, { + spawnHook: ({ command, cwd, env }) => ({ + command: `source ~/.profile\n${command}`, + cwd: `/mnt/sandbox${cwd}`, + env: { ...env, CI: "1" }, + }), +}); +``` + +`createBashTool()` exposes the current session to commands through `PI_SESSION_ID`, `PI_SESSION_FILE`, `PI_PROVIDER`, `PI_MODEL`, and `PI_REASONING_LEVEL`. Injection happens before `spawnHook`, so hooks receive these values in `env` and preserve them when they spread the existing environment as above. Set `exposeSessionEnvironment: false` to disable them: + +```typescript +const bashTool = createBashTool(cwd, { + exposeSessionEnvironment: false, +}); +``` + +See [Bash tool session environment](environment-variables.md#bash-tool-session-environment) for variable semantics. See [examples/extensions/ssh.ts](../examples/extensions/ssh.ts) for a complete SSH example with `--ssh` flag. + +### Output Truncation + +**Tools MUST truncate their output** to avoid overwhelming the LLM context. Large outputs can cause: +- Context overflow errors (prompt too long) +- Compaction failures +- Degraded model performance + +The built-in limit is **50KB** (~10k tokens) and **2000 lines**, whichever is hit first. Use the exported truncation utilities: + +```typescript +import { + truncateHead, // Keep first N lines/bytes (good for file reads, search results) + truncateTail, // Keep last N lines/bytes (good for logs, command output) + truncateLine, // Truncate a single line to maxBytes with ellipsis + formatSize, // Human-readable size (e.g., "50KB", "1.5MB") + DEFAULT_MAX_BYTES, // 50KB + DEFAULT_MAX_LINES, // 2000 +} from "@earendil-works/pi-coding-agent"; + +async execute(toolCallId, params, signal, onUpdate, ctx) { + const output = await runCommand(); + + // Apply truncation + const truncation = truncateHead(output, { + maxLines: DEFAULT_MAX_LINES, + maxBytes: DEFAULT_MAX_BYTES, + }); + + let result = truncation.content; + + if (truncation.truncated) { + // Write full output to temp file + const tempFile = writeTempFile(output); + + // Inform the LLM where to find complete output + result += `\n\n[Output truncated: ${truncation.outputLines} of ${truncation.totalLines} lines`; + result += ` (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).`; + result += ` Full output saved to: ${tempFile}]`; + } + + return { content: [{ type: "text", text: result }] }; +} +``` + +**Key points:** +- Use `truncateHead` for content where the beginning matters (search results, file reads) +- Use `truncateTail` for content where the end matters (logs, command output) +- Always inform the LLM when output is truncated and where to find the full version +- Document the truncation limits in your tool's description + +See [examples/extensions/truncated-tool.ts](../examples/extensions/truncated-tool.ts) for a complete example wrapping `rg` (ripgrep) with proper truncation. + +### Multiple Tools + +One extension can register multiple tools with shared state: + +```typescript +export default function (pi: ExtensionAPI) { + let connection = null; + + pi.registerTool({ name: "db_connect", ... }); + pi.registerTool({ name: "db_query", ... }); + pi.registerTool({ name: "db_close", ... }); + + pi.on("session_shutdown", async () => { + connection?.close(); + }); +} +``` + +### Custom Rendering + +Tools can provide `renderCall` and `renderResult` for custom TUI display. See [tui.md](tui.md) for the full component API and [tool-execution.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/modes/interactive/components/tool-execution.ts) for how tool rows are composed. + +By default, tool output is wrapped in a `Box` that handles padding and background. A defined `renderCall` or `renderResult` must return a `Component`. If a slot renderer is not defined, `tool-execution.ts` uses fallback rendering for that slot. + +Set `renderShell: "self"` when the tool should render its own shell instead of using the default `Box`. This is useful for tools that need complete control over framing or background behavior, for example large previews that must stay visually stable after the tool settles. + +```typescript +pi.registerTool({ + name: "my_tool", + label: "My Tool", + description: "Custom shell example", + parameters: Type.Object({}), + renderShell: "self", + async execute() { + return { content: [{ type: "text", text: "ok" }], details: undefined }; + }, + renderCall(args, theme, context) { + return new Text(theme.fg("accent", "my custom shell"), 0, 0); + }, +}); +``` + +`renderCall` and `renderResult` each receive a `context` object with: +- `args` - the current tool call arguments +- `state` - shared row-local state across `renderCall` and `renderResult` +- `lastComponent` - the previously returned component for that slot, if any +- `invalidate()` - request a rerender of this tool row +- `toolCallId`, `cwd`, `executionStarted`, `argsComplete`, `isPartial`, `expanded`, `showImages`, `isError` + +Use `context.state` for cross-slot shared state. Keep slot-local caches on the returned component instance when you want to reuse and mutate the same component across renders. + +#### renderCall + +Renders the tool call or header: + +```typescript +import { Text } from "@earendil-works/pi-tui"; + +renderCall(args, theme, context) { + const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0); + let content = theme.fg("toolTitle", theme.bold("my_tool ")); + content += theme.fg("muted", args.action); + if (args.text) { + content += " " + theme.fg("dim", `"${args.text}"`); + } + text.setText(content); + return text; +} +``` + +#### renderResult + +Renders the tool result or output: + +```typescript +renderResult(result, { expanded, isPartial }, theme, context) { + if (isPartial) { + return new Text(theme.fg("warning", "Processing..."), 0, 0); + } + + if (result.details?.error) { + return new Text(theme.fg("error", `Error: ${result.details.error}`), 0, 0); + } + + let text = theme.fg("success", "✓ Done"); + if (expanded && result.details?.items) { + for (const item of result.details.items) { + text += "\n " + theme.fg("dim", item); + } + } + return new Text(text, 0, 0); +} +``` + +If a slot intentionally has no visible content, return an empty `Component` such as an empty `Container`. + +#### Keybinding Hints + +Use `keyHint()` to display keybinding hints that respect the active keybinding configuration: + +```typescript +import { keyHint } from "@earendil-works/pi-coding-agent"; + +renderResult(result, { expanded }, theme, context) { + let text = theme.fg("success", "✓ Done"); + if (!expanded) { + text += ` (${keyHint("app.tools.expand", "to expand")})`; + } + return new Text(text, 0, 0); +} +``` + +Available functions: +- `keyHint(keybinding, description)` - Formats a configured keybinding id such as `"app.tools.expand"` or `"tui.select.confirm"` +- `keyText(keybinding)` - Returns the raw configured key text for a keybinding id +- `rawKeyHint(key, description)` - Format a raw key string + +Use namespaced keybinding ids: +- Coding-agent ids use the `app.*` namespace, for example `app.tools.expand`, `app.editor.external`, `app.session.rename` +- Shared TUI ids use the `tui.*` namespace, for example `tui.select.confirm`, `tui.select.cancel`, `tui.input.tab` + +For the exhaustive list of keybinding ids and defaults, see [keybindings.md](keybindings.md). `keybindings.json` uses those same namespaced ids. + +Custom editors and `ctx.ui.custom()` components receive `keybindings: KeybindingsManager` as an injected argument. They should use that injected manager directly instead of calling `getKeybindings()` or `setKeybindings()`. + +#### Best Practices + +- Use `Text` with padding `(0, 0)`. The default Box handles padding. +- Use `\n` for multi-line content. +- Handle `isPartial` for streaming progress. +- Support `expanded` for detail on demand. +- Keep default view compact. +- Read `context.args` in `renderResult` instead of copying args into `context.state`. +- Use `context.state` only for data that must be shared across call and result slots. +- Reuse `context.lastComponent` when the same component instance can be updated in place. +- Use `renderShell: "self"` only when the default boxed shell gets in the way. In self-shell mode the tool is responsible for its own framing, padding, and background. + +#### Fallback + +If a slot renderer is not defined or throws: +- `renderCall`: Shows the tool name +- `renderResult`: Shows raw text from `content` + +### Dynamic Tool Loading + +Extensions can register many tools while keeping only a small initial set active. A tool can then add more tools with `pi.setActiveTools()` during execution. Pi detects purely additive changes, records the newly available tool names on that tool result, and applies the updated active set before the next model request. + +This works with every model. Models with native deferred-loading support preserve the stable prompt prefix and load the new definitions at the tool-result position. Other models use the fallback described below. + +The lifecycle is: + +1. Register every tool with `pi.registerTool()` so it appears in `pi.getAllTools()`. +2. Keep loader tools, such as `search_tools`, active and leave searchable tools inactive. +3. During loader execution, call `pi.setActiveTools([...currentTools, ...matchingTools])`. The change must be additive: do not remove currently active tools in the same call. +4. Pi records which tools were added on the loader's tool result. +5. Before the next model response, Pi exposes the added definitions using native deferred loading when supported, or the normal active tool list otherwise. + +You do not need to return provider-specific tool references or mark the loader as a special search tool. The active-tool change is the signal. Names passed to `pi.setActiveTools()` must already be registered; unknown names are ignored. + +#### Models with native deferred loading + +- **Anthropic** + - **Models:** Sonnet, Opus, Fable version 4.5 or newer (without Haiku) + - **Native representation:** Deferred definitions use `defer_loading`; the load point uses `tool_reference` content. +- **OpenAI** + - **Models:** `gpt-5.4` and newer family + - **Native representation:** Pi adds completed client `tool_search_call` and `tool_search_output` items at the load point. + +For a verified custom model or proxy, native handling can be enabled with `compat.supportsToolReferences: true` for `anthropic-messages`, or `compat.supportsToolSearch: true` for `openai-responses` and `openai-codex-responses`. Leave these disabled unless the endpoint and model accept the corresponding native protocol. + +#### Fallback behavior + +For all other models and providers, dynamic activation still works: Pi sends the complete current active tool list normally on the next request. The model can call the newly activated tools, but adding their definitions may invalidate the provider's cached prompt prefix. + +Pi also uses this safe fallback when the active set is not purely additive, such as replacing one group of tools with another. Tool removals therefore work, but they do not use deferred loading. + +For the best cache behavior, keep the loader tool active for the whole session and add tools instead of replacing the active set. Also note that activating a tool with `promptSnippet` or `promptGuidelines` rebuilds the system prompt; that system-prompt change can invalidate the prefix even when the provider supports deferred schemas. Lazily loaded tools should usually rely on their tool `description` and omit active-only prompt metadata. + +#### Search tool example + +The following extension registers two searchable tools, removes them from the initial active set, and keeps only `search_tools` as their loader. The example uses simple keyword matching, but the search implementation could use BM25, embeddings, a remote catalog, or project-specific routing. + +```typescript +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { Type } from "typebox"; + +const SEARCHABLE_TOOL_NAMES = new Set(["lookup_weather", "search_issues"]); + +export default function (pi: ExtensionAPI) { + pi.registerTool({ + name: "lookup_weather", + label: "Lookup Weather", + description: "Look up the current weather for a city", + parameters: Type.Object({ city: Type.String() }), + async execute(_toolCallId, params) { + return { + content: [{ type: "text", text: `Weather for ${params.city}: sunny` }], + details: {}, + }; + }, + }); + + pi.registerTool({ + name: "search_issues", + label: "Search Issues", + description: "Search project issues by keyword", + parameters: Type.Object({ query: Type.String() }), + async execute(_toolCallId, params) { + return { + content: [{ type: "text", text: `No open issues matching ${params.query}` }], + details: {}, + }; + }, + }); + + pi.registerTool({ + name: "search_tools", + label: "Search Tools", + description: "Search for and enable tools relevant to a task", + promptSnippet: "Search for additional tools when the active tools cannot perform the task", + promptGuidelines: [ + "Use search_tools when a task requires a capability that is not currently available.", + ], + parameters: Type.Object({ + query: Type.String({ description: "Capability or task to search for" }), + limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 10 })), + }), + async execute(_toolCallId, params) { + const terms = params.query.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean); + const matches = pi.getAllTools() + .filter((tool) => SEARCHABLE_TOOL_NAMES.has(tool.name)) + .map((tool) => ({ + tool, + score: terms.reduce( + (score, term) => + score + (`${tool.name} ${tool.description}`.toLowerCase().includes(term) ? 1 : 0), + 0, + ), + })) + .filter((match) => match.score > 0) + .sort((a, b) => b.score - a.score) + .slice(0, params.limit ?? 3) + .map((match) => match.tool.name); + + if (matches.length === 0) { + return { + content: [{ type: "text", text: `No tools found for: ${params.query}` }], + details: { matches: [] }, + }; + } + + const active = pi.getActiveTools(); + const added = matches.filter((name) => !active.includes(name)); + pi.setActiveTools([...new Set([...active, ...added])]); + + return { + content: [{ + type: "text", + text: added.length > 0 + ? `Loaded tools: ${added.join(", ")}` + : `Matching tools already active: ${matches.join(", ")}`, + }], + details: { matches, added }, + }; + }, + }); + + pi.on("session_start", () => { + // Keep searchable tools registered but initially inactive. Preserve built-ins + // and tools owned by other extensions, and keep the loader itself active. + const initialTools = pi.getActiveTools().filter( + (name) => !SEARCHABLE_TOOL_NAMES.has(name), + ); + pi.setActiveTools([...new Set([...initialTools, "search_tools"])]); + }); +} +``` + +When `search_tools` adds a match, the model receives that definition on the immediately following request. On a native-capable model the definition is anchored after the search result without changing the initial tool-schema prefix. On other models it appears in the normal tool list on that same following request. + +## Custom UI + +Extensions can interact with users via `ctx.ui` methods and customize how messages/tools render. + +**For custom components, see [tui.md](tui.md)** which has copy-paste patterns for: +- Selection dialogs (SelectList) +- Async operations with cancel (BorderedLoader) +- Settings toggles (SettingsList) +- Status indicators (setStatus) +- Working message, visibility, and indicator during streaming (`setWorkingMessage`, `setWorkingVisible`, `setWorkingIndicator`) +- Widgets above/below editor (setWidget) +- Autocomplete providers layered on top of built-in slash/path completion (addAutocompleteProvider) +- Custom footers (setFooter) + +### Dialogs + +```typescript +// Select from options +const choice = await ctx.ui.select("Pick one:", ["A", "B", "C"]); + +// Confirm dialog +const ok = await ctx.ui.confirm("Delete?", "This cannot be undone"); + +// Text input +const name = await ctx.ui.input("Name:", "placeholder"); + +// Multi-line editor +const text = await ctx.ui.editor("Edit:", "prefilled text"); + +// Notification (non-blocking) +ctx.ui.notify("Done!", "info"); // "info" | "warning" | "error" +``` + +#### Timed Dialogs with Countdown + +Dialogs support a `timeout` option that auto-dismisses with a live countdown display: + +```typescript +// Dialog shows "Title (5s)" → "Title (4s)" → ... → auto-dismisses at 0 +const confirmed = await ctx.ui.confirm( + "Timed Confirmation", + "This dialog will auto-cancel in 5 seconds. Confirm?", + { timeout: 5000 } +); + +if (confirmed) { + // User confirmed +} else { + // User cancelled or timed out +} +``` + +**Return values on timeout:** +- `select()` returns `undefined` +- `confirm()` returns `false` +- `input()` returns `undefined` + +#### Manual Dismissal with AbortSignal + +For more control (e.g., to distinguish timeout from user cancel), use `AbortSignal`: + +```typescript +const controller = new AbortController(); +const timeoutId = setTimeout(() => controller.abort(), 5000); + +const confirmed = await ctx.ui.confirm( + "Timed Confirmation", + "This dialog will auto-cancel in 5 seconds. Confirm?", + { signal: controller.signal } +); + +clearTimeout(timeoutId); + +if (confirmed) { + // User confirmed +} else if (controller.signal.aborted) { + // Dialog timed out +} else { + // User cancelled (pressed Escape or selected "No") +} +``` + +See [examples/extensions/timed-confirm.ts](../examples/extensions/timed-confirm.ts) for complete examples. + +### Widgets, Status, and Footer + +```typescript +// Status in footer (persistent until cleared) +ctx.ui.setStatus("my-ext", "Processing..."); +ctx.ui.setStatus("my-ext", undefined); // Clear + +// Working loader (shown during streaming) +ctx.ui.setWorkingMessage("Thinking deeply..."); +ctx.ui.setWorkingMessage(); // Restore default +ctx.ui.setWorkingVisible(false); // Hide the built-in working loader row entirely +ctx.ui.setWorkingVisible(true); // Show the built-in working loader row + +// Working indicator (shown during streaming) +ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg("accent", "●")] }); // Static dot +ctx.ui.setWorkingIndicator({ + frames: [ + ctx.ui.theme.fg("dim", "·"), + ctx.ui.theme.fg("muted", "•"), + ctx.ui.theme.fg("accent", "●"), + ctx.ui.theme.fg("muted", "•"), + ], + intervalMs: 120, +}); +ctx.ui.setWorkingIndicator({ frames: [] }); // Hide indicator +ctx.ui.setWorkingIndicator(); // Restore default spinner + +// Widget above editor (default) +ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]); +// Widget below editor +ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" }); +ctx.ui.setWidget("my-widget", (tui, theme) => new Text(theme.fg("accent", "Custom"), 0, 0)); +ctx.ui.setWidget("my-widget", undefined); // Clear + +// Custom footer (replaces built-in footer entirely) +ctx.ui.setFooter((tui, theme) => ({ + render(width) { return [theme.fg("dim", "Custom footer")]; }, + invalidate() {}, +})); +ctx.ui.setFooter(undefined); // Restore built-in footer + +// Terminal title +ctx.ui.setTitle("pi - my-project"); + +// Editor text +ctx.ui.setEditorText("Prefill text"); +const current = ctx.ui.getEditorText(); + +// Paste into editor (triggers paste handling, including collapse for large content) +ctx.ui.pasteToEditor("pasted content"); + +// Stack custom autocomplete behavior on top of the built-in provider +ctx.ui.addAutocompleteProvider((current) => ({ + triggerCharacters: ["#"], + async getSuggestions(lines, line, col, options) { + const beforeCursor = (lines[line] ?? "").slice(0, col); + const match = beforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/); + if (!match) { + return current.getSuggestions(lines, line, col, options); + } + + return { + prefix: `#${match[1] ?? ""}`, + items: [{ value: "#2983", label: "#2983", description: "Extension API for autocomplete" }], + }; + }, + applyCompletion(lines, line, col, item, prefix) { + return current.applyCompletion(lines, line, col, item, prefix); + }, + shouldTriggerFileCompletion(lines, line, col) { + return current.shouldTriggerFileCompletion?.(lines, line, col) ?? true; + }, +})); + +// Tool output expansion +const wasExpanded = ctx.ui.getToolsExpanded(); +ctx.ui.setToolsExpanded(true); +ctx.ui.setToolsExpanded(wasExpanded); + +// Custom editor (vim mode, emacs mode, etc.) +ctx.ui.setEditorComponent((tui, theme, keybindings) => new VimEditor(tui, theme, keybindings)); +const currentEditor = ctx.ui.getEditorComponent(); +ctx.ui.setEditorComponent((tui, theme, keybindings) => + new WrappedEditor(tui, theme, keybindings, currentEditor?.(tui, theme, keybindings)) +); +ctx.ui.setEditorComponent(undefined); // Restore default editor + +// Theme management (see themes.md for creating themes) +const themes = ctx.ui.getAllThemes(); // [{ name: "dark", path: "/..." | undefined }, ...] +const lightTheme = ctx.ui.getTheme("light"); // Load without switching +const result = ctx.ui.setTheme("light"); // Switch by name +if (!result.success) { + ctx.ui.notify(`Failed: ${result.error}`, "error"); +} +ctx.ui.setTheme(lightTheme!); // Or switch by Theme object +ctx.ui.theme.fg("accent", "styled text"); // Access current theme +``` + +Custom working-indicator frames are rendered verbatim. If you want colors, add them to the frame strings yourself, for example with `ctx.ui.theme.fg(...)`. + +### Autocomplete Providers + +Use `ctx.ui.addAutocompleteProvider()` to stack custom autocomplete logic on top of the built-in slash-command and path provider. Set `triggerCharacters` for custom natural triggers such as `$`. + +Typical pattern: + +- inspect the text before the cursor +- return your own suggestions when your extension-specific syntax matches +- otherwise delegate to `current.getSuggestions(...)` +- delegate `applyCompletion(...)` unless you need custom insertion behavior + +```typescript +pi.on("session_start", (_event, ctx) => { + ctx.ui.addAutocompleteProvider((current) => ({ + triggerCharacters: ["#"], + async getSuggestions(lines, cursorLine, cursorCol, options) { + const line = lines[cursorLine] ?? ""; + const beforeCursor = line.slice(0, cursorCol); + const match = beforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/); + if (!match) { + return current.getSuggestions(lines, cursorLine, cursorCol, options); + } + + return { + prefix: `#${match[1] ?? ""}`, + items: [ + { value: "#2983", label: "#2983", description: "Extension API for registering custom @ autocomplete providers" }, + { value: "#2753", label: "#2753", description: "Reload stale resource settings" }, + ], + }; + }, + + applyCompletion(lines, cursorLine, cursorCol, item, prefix) { + return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix); + }, + + shouldTriggerFileCompletion(lines, cursorLine, cursorCol) { + return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true; + }, + })); +}); +``` + +See [github-issue-autocomplete.ts](../examples/extensions/github-issue-autocomplete.ts) for a complete example that preloads the latest open GitHub issues with `gh issue list` and filters them locally for fast `#...` completion. It requires GitHub CLI (`gh`) and a GitHub repository checkout. + +### Custom Components + +For complex UI, use `ctx.ui.custom()`. This temporarily replaces the editor with your component until `done()` is called: + +```typescript +import { Text, Component } from "@earendil-works/pi-tui"; + +const result = await ctx.ui.custom((tui, theme, keybindings, done) => { + const text = new Text("Press Enter to confirm, Escape to cancel", 1, 1); + + text.onKey = (key) => { + if (key === "return") done(true); + if (key === "escape") done(false); + return true; + }; + + return text; +}); + +if (result) { + // User pressed Enter +} +``` + +The callback receives: +- `tui` - TUI instance (for screen dimensions, focus management) +- `theme` - Current theme for styling +- `keybindings` - App keybinding manager (for checking shortcuts) +- `done(value)` - Call to close component and return value + +See [tui.md](tui.md) for the full component API. + +#### Overlay Mode (Experimental) + +Pass `{ overlay: true }` to render the component as a floating modal on top of existing content, without clearing the screen: + +```typescript +const result = await ctx.ui.custom( + (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }), + { overlay: true } +); +``` + +For advanced positioning (anchors, margins, percentages, responsive visibility), pass `overlayOptions`. Use `onHandle` to control focus or visibility programmatically: + +```typescript +const result = await ctx.ui.custom( + (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }), + { + overlay: true, + overlayOptions: { anchor: "top-right", width: "50%", margin: 2 }, + onHandle: (handle) => { + handle.focus(); // focus this overlay and bring it to the visual front + // handle.unfocus({ target: editorComponent }); // release input to a specific component + // handle.setHidden(true/false); // toggle visibility + // handle.hide(); // permanently remove + } + } +); +``` + +A focused visible overlay can reclaim input after temporary non-overlay custom UI closes. If you intentionally want another component to keep input while the overlay stays visible, call `handle.unfocus({ target })`. Passing `{ target: null }` releases the overlay without focusing another component. + +See [tui.md](tui.md) for the full `OverlayOptions` and `OverlayHandle` API and [overlay-qa-tests.ts](../examples/extensions/overlay-qa-tests.ts) for examples. + +### Custom Editor + +Replace the main input editor with a custom implementation (vim mode, emacs mode, etc.): + +```typescript +import { CustomEditor, type ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { matchesKey } from "@earendil-works/pi-tui"; + +class VimEditor extends CustomEditor { + private mode: "normal" | "insert" = "insert"; + + handleInput(data: string): void { + if (matchesKey(data, "escape") && this.mode === "insert") { + this.mode = "normal"; + return; + } + if (this.mode === "normal" && data === "i") { + this.mode = "insert"; + return; + } + super.handleInput(data); // App keybindings + text editing + } +} + +export default function (pi: ExtensionAPI) { + pi.on("session_start", (_event, ctx) => { + ctx.ui.setEditorComponent((tui, theme, keybindings) => + new VimEditor(tui, theme, keybindings) + ); + }); +} +``` + +**Key points:** +- Extend `CustomEditor` (not base `Editor`) to get app keybindings (escape to abort, ctrl+d, model switching) +- Call `super.handleInput(data)` for keys you don't handle +- Factory receives `tui`, `theme`, and `keybindings` from the app +- Use `ctx.ui.getEditorComponent()` before `setEditorComponent()` to wrap the previously configured custom editor +- Pass `undefined` to restore default: `ctx.ui.setEditorComponent(undefined)` + +To compose with another extension that already replaced the editor, capture the previous factory before setting yours: + +```typescript +const previous = ctx.ui.getEditorComponent(); +ctx.ui.setEditorComponent((tui, theme, keybindings) => + new MyEditor(tui, theme, keybindings, { base: previous?.(tui, theme, keybindings) }) +); +``` + +See [tui.md](tui.md) Pattern 7 for a complete example with mode indicator. + +### Message and Entry Rendering + +Register a custom renderer for messages with your `customType`. Use message renderers for content that should participate in LLM context: + +```typescript +import { Text } from "@earendil-works/pi-tui"; + +pi.registerMessageRenderer("my-extension", (message, options, theme) => { + const { expanded, outputPad } = options; + let text = theme.fg("accent", `[${message.customType}] `); + text += message.content; + + if (expanded && message.details) { + text += "\n" + theme.fg("dim", JSON.stringify(message.details, null, 2)); + } + + return new Text(text, outputPad, 0); +}); +``` + +Messages are sent via `pi.sendMessage()`: + +```typescript +pi.sendMessage({ + customType: "my-extension", // Matches registerMessageRenderer + content: "Status update", + display: true, // Show in TUI + details: { ... }, // Available in renderer +}); +``` + +For TUI-only content that should not be sent to the LLM, render custom entries instead: + +```typescript +pi.registerEntryRenderer("my-card", (entry, options, theme) => { + return new Text(theme.fg("accent", JSON.stringify(entry.data))); +}); + +pi.appendEntry("my-card", { status: "done" }); +``` + +### Theme Colors + +All render functions receive a `theme` object. See [themes.md](themes.md) for creating custom themes and the full color palette. + +```typescript +// Foreground colors +theme.fg("toolTitle", text) // Tool names +theme.fg("accent", text) // Highlights +theme.fg("success", text) // Success (green) +theme.fg("error", text) // Errors (red) +theme.fg("warning", text) // Warnings (yellow) +theme.fg("muted", text) // Secondary text +theme.fg("dim", text) // Tertiary text + +// Text styles +theme.bold(text) +theme.italic(text) +theme.strikethrough(text) +``` + +For syntax highlighting in custom tool renderers: + +```typescript +import { highlightCode, getLanguageFromPath } from "@earendil-works/pi-coding-agent"; + +// Highlight code with explicit language +const highlighted = highlightCode("const x = 1;", "typescript", theme); + +// Auto-detect language from file path +const lang = getLanguageFromPath("/path/to/file.rs"); // "rust" +const highlighted = highlightCode(code, lang, theme); +``` + +## Error Handling + +- Extension errors are logged, agent continues +- `tool_call` errors block the tool (fail-safe) +- Tool `execute` errors must be signaled by throwing; the thrown error is caught, reported to the LLM with `isError: true`, and execution continues + +## Mode Behavior + +| Mode | `ctx.mode` | `ctx.hasUI` | Notes | +|------|------------|-------------|-------| +| Interactive | `"tui"` | `true` | Full TUI with terminal rendering | +| RPC (`--mode rpc`) | `"rpc"` | `true` | Dialogs and notifications via JSON protocol; `custom()` returns `undefined`. See [rpc.md](rpc.md) | +| JSON (`--mode json`) | `"json"` | `false` | Event stream to stdout; UI methods are no-ops | +| Print (`-p`) | `"print"` | `false` | Extensions run but can't prompt | + +Use `ctx.mode === "tui"` before TUI-specific features (`custom()`, component factories, terminal input). Use `ctx.hasUI` before dialog and notification methods that work in both TUI and RPC modes. + +## Examples Reference + +All examples in [examples/extensions/](../examples/extensions/). + +| Example | Description | Key APIs | +|---------|-------------|----------| +| **Tools** ||| +| `hello.ts` | Minimal tool registration | `registerTool` | +| `question.ts` | Tool with user interaction | `registerTool`, `ui.select` | +| `questionnaire.ts` | Multi-step wizard tool | `registerTool`, `ui.custom` | +| `todo.ts` | Stateful tool with persistence | `registerTool`, `appendEntry`, `renderResult`, session events | +| `dynamic-tools.ts` | Register tools after startup and during commands | `registerTool`, `session_start`, `registerCommand` | +| `structured-output.ts` | Final structured-output tool with `terminate: true` | `registerTool`, terminating tool results | +| `truncated-tool.ts` | Output truncation example | `registerTool`, `truncateHead` | +| `tool-override.ts` | Override built-in read tool | `registerTool` (same name as built-in) | +| **Commands** ||| +| `pirate.ts` | Modify system prompt per-turn | `registerCommand`, `before_agent_start` | +| `summarize.ts` | Conversation summary command | `registerCommand`, `ui.custom` | +| `handoff.ts` | Cross-provider model handoff | `registerCommand`, `ui.editor`, `ui.custom` | +| `qna.ts` | Q&A with custom UI | `registerCommand`, `ui.custom`, `setEditorText` | +| `send-user-message.ts` | Inject user messages | `registerCommand`, `sendUserMessage` | +| `reload-runtime.ts` | Reload command and LLM tool handoff | `registerCommand`, `ctx.reload()`, `sendUserMessage` | +| `shutdown-command.ts` | Graceful shutdown command | `registerCommand`, `shutdown()` | +| **Events & Gates** ||| +| `permission-gate.ts` | Block dangerous commands | `on("tool_call")`, `ui.confirm` | +| `project-trust.ts` | Decide or defer project trust from a user/global or CLI extension | `on("project_trust")`, trust UI, required trust result | +| `protected-paths.ts` | Block writes to specific paths | `on("tool_call")` | +| `confirm-destructive.ts` | Confirm session changes | `on("session_before_switch")`, `on("session_before_fork")` | +| `dirty-repo-guard.ts` | Warn on dirty git repo | `on("session_before_*")`, `exec` | +| `input-transform.ts` | Transform user input | `on("input")` | +| `input-transform-streaming.ts` | Streaming-aware input transform | `on("input")`, `streamingBehavior` | +| `model-status.ts` | React to model changes | `on("model_select")`, `setStatus` | +| `provider-payload.ts` | Inspect payloads and provider response headers | `on("before_provider_request")`, `on("after_provider_response")` | +| `system-prompt-header.ts` | Display system prompt info | `on("agent_start")`, `getSystemPrompt` | +| `claude-rules.ts` | Load rules from files | `on("session_start")`, `on("before_agent_start")` | +| `prompt-customizer.ts` | Add context-aware tool guidance using `systemPromptOptions` | `on("before_agent_start")`, `BuildSystemPromptOptions` | +| `file-trigger.ts` | File watcher triggers messages | `sendMessage` | +| **Compaction & Sessions** ||| +| `custom-compaction.ts` | Custom compaction summary | `on("session_before_compact")` | +| `trigger-compact.ts` | Trigger compaction manually | `compact()` | +| `git-checkpoint.ts` | Git stash on turns | `on("turn_start")`, `on("session_before_fork")`, `exec` | +| `git-merge-and-resolve.ts` | Fetch, merge, and resolve conflicts | `on("agent_end")`, `exec`, `sendUserMessage` | +| `auto-commit-on-exit.ts` | Commit on shutdown | `on("session_shutdown")`, `exec` | +| **UI Components** ||| +| `status-line.ts` | Footer status indicator | `setStatus`, session events | +| `working-indicator.ts` | Customize the streaming working indicator | `setWorkingIndicator`, `registerCommand` | +| `github-issue-autocomplete.ts` | Add `#1234` issue completions on top of built-in autocomplete by preloading recent open issues from `gh issue list` | `addAutocompleteProvider`, `on("session_start")`, `exec` | +| `custom-footer.ts` | Replace footer entirely | `registerCommand`, `setFooter` | +| `custom-header.ts` | Replace startup header | `on("session_start")`, `setHeader` | +| `modal-editor.ts` | Vim-style modal editor | `setEditorComponent`, `CustomEditor` | +| `rainbow-editor.ts` | Custom editor styling | `setEditorComponent` | +| `widget-placement.ts` | Widget above/below editor | `setWidget` | +| `overlay-test.ts` | Overlay components | `ui.custom` with overlay options | +| `overlay-qa-tests.ts` | Comprehensive overlay tests | `ui.custom`, all overlay options | +| `notify.ts` | Simple notifications | `ui.notify` | +| `timed-confirm.ts` | Dialogs with timeout | `ui.confirm` with timeout/signal | +| `mac-system-theme.ts` | Auto-switch theme | `setTheme`, `exec` | +| **Complex Extensions** ||| +| `plan-mode/` | Full plan mode implementation | All event types, `registerCommand`, `registerShortcut`, `registerFlag`, `setStatus`, `setWidget`, `sendMessage`, `setActiveTools` | +| `preset.ts` | Saveable presets (model, tools, thinking) | `registerCommand`, `registerShortcut`, `registerFlag`, `setModel`, `setActiveTools`, `setThinkingLevel`, `appendEntry` | +| `tools.ts` | Toggle tools on/off UI | `registerCommand`, `setActiveTools`, `SettingsList`, session events | +| **Remote & Sandbox** ||| +| `ssh.ts` | SSH remote execution | `registerFlag`, `on("user_bash")`, `on("before_agent_start")`, tool operations | +| `interactive-shell.ts` | Persistent shell session | `on("user_bash")` | +| `sandbox/` | Sandboxed tool execution | Tool operations | +| `gondolin/` | Route built-in tools and `!` commands into a Gondolin micro-VM | Tool operations, built-in tool overrides, `on("user_bash")` | +| `subagent/` | Spawn sub-agents | `registerTool`, `exec` | +| **Games** ||| +| `snake.ts` | Snake game | `registerCommand`, `ui.custom`, keyboard handling | +| `space-invaders.ts` | Space Invaders game | `registerCommand`, `ui.custom` | +| `doom-overlay/` | Doom in overlay | `ui.custom` with overlay | +| **Providers** ||| +| `custom-provider-anthropic/` | Custom Anthropic proxy | `registerProvider` | +| `custom-provider-gitlab-duo/` | GitLab Duo integration | `registerProvider` with OAuth | +| **Messages & Communication** ||| +| `message-renderer.ts` | Custom message rendering | `registerMessageRenderer`, `sendMessage` | +| `entry-renderer.ts` | TUI-only custom entry rendering | `registerEntryRenderer`, `appendEntry` | +| `event-bus.ts` | Inter-extension events | `pi.events` | +| **Session Metadata** ||| +| `session-name.ts` | Name sessions for selector | `setSessionName`, `getSessionName` | +| `bookmark.ts` | Bookmark entries for /tree | `setLabel` | +| **Misc** ||| +| `inline-bash.ts` | Inline bash in tool calls | `on("tool_call")` | +| `bash-spawn-hook.ts` | Adjust bash command, cwd, and env before execution | `createBashTool`, `spawnHook` | +| `with-deps/` | Extension with npm dependencies | Package structure with `package.json` | diff --git a/docs/images/doom-extension.png b/docs/images/doom-extension.png new file mode 100644 index 0000000..965acc9 Binary files /dev/null and b/docs/images/doom-extension.png differ diff --git a/docs/images/exy.png b/docs/images/exy.png new file mode 100644 index 0000000..250f5f0 Binary files /dev/null and b/docs/images/exy.png differ diff --git a/docs/images/interactive-mode.png b/docs/images/interactive-mode.png new file mode 100644 index 0000000..8a5be0d Binary files /dev/null and b/docs/images/interactive-mode.png differ diff --git a/docs/images/tree-view.png b/docs/images/tree-view.png new file mode 100644 index 0000000..8ef603d Binary files /dev/null and b/docs/images/tree-view.png differ diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..c09cfc9 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,84 @@ +# Pi Documentation + +Pi is a minimal terminal coding harness. It is designed to stay small at the core while being extended through TypeScript extensions, skills, prompt templates, themes, and pi packages. + +## Quick start + +Install Pi with npm: + +```bash +npm install -g --ignore-scripts @earendil-works/pi-coding-agent +``` + +`--ignore-scripts` disables dependency lifecycle scripts during install. Pi does not require install scripts for normal npm installs. + +On Linux or macOS, you can also use the installer: + +```bash +curl -fsSL https://pi.dev/install.sh | sh +``` + +To uninstall pi itself, use npm for curl and npm installs: + +```bash +npm uninstall -g @earendil-works/pi-coding-agent +``` + +For pnpm, Yarn, or Bun installs, use the matching global remove command: `pnpm remove -g @earendil-works/pi-coding-agent`, `yarn global remove @earendil-works/pi-coding-agent`, or `bun uninstall -g @earendil-works/pi-coding-agent`. + +Then run it in a project directory: + +```bash +pi +``` + +Authenticate with `/login` for subscription providers, or set an API key such as `ANTHROPIC_API_KEY` before starting pi. + +For the full first-run flow, see [Quickstart](quickstart.md). + +## Start here + +- [Quickstart](quickstart.md) - install, authenticate, and run a first session. +- [Using Pi](usage.md) - interactive mode, slash commands, context files, and CLI reference. +- [Providers](providers.md) - subscription and API-key setup for built-in providers. +- [llama.cpp](llama-cpp.md) - run a local router and manage models with `/llama`. +- [Security](security.md) - project trust, sandbox boundaries, and vulnerability reporting. +- [Containerization](containerization.md) - sandbox pi with Gondolin, Docker, or OpenShell. +- [Settings](settings.md) - global and project settings. +- [Keybindings](keybindings.md) - default shortcuts and custom keybindings. +- [Sessions](sessions.md) - session management, branching, and tree navigation. +- [Compaction](compaction.md) - context compaction and branch summarization. + +## Customization + +- [Extensions](extensions.md) - TypeScript modules for tools, commands, events, and custom UI. +- [Skills](skills.md) - Agent Skills for reusable on-demand capabilities. +- [Prompt templates](prompt-templates.md) - reusable prompts that expand from slash commands. +- [Themes](themes.md) - built-in and custom terminal themes. +- [Pi packages](packages.md) - bundle and share extensions, skills, prompts, and themes. +- [Custom models](models.md) - add model entries for supported provider APIs. +- [Custom providers](custom-provider.md) - implement custom APIs and OAuth flows. + +## Programmatic usage + +- [SDK](sdk.md) - embed pi in Node.js applications. +- [RPC mode](rpc.md) - integrate over stdin/stdout JSONL. +- [JSON event stream mode](json.md) - print mode with structured events. +- [TUI components](tui.md) - build custom terminal UI for extensions. + +## Reference + +- [Environment variables](environment-variables.md) - Pi process configuration and session metadata available to bash tools. +- [Session format](session-format.md) - JSONL session file format, entry types, and SessionManager API. + +## Platform setup + +- [Windows](windows.md) +- [Termux on Android](termux.md) +- [tmux](tmux.md) +- [Terminal setup](terminal-setup.md) +- [Shell aliases](shell-aliases.md) + +## Development + +- [Development](development.md) - local setup, project structure, and debugging. diff --git a/docs/json.md b/docs/json.md new file mode 100644 index 0000000..a9d28cb --- /dev/null +++ b/docs/json.md @@ -0,0 +1,86 @@ +# JSON Event Stream Mode + +```bash +pi --mode json "Your prompt" +``` + +Outputs all session events as JSON lines to stdout. Useful for integrating pi into other tools or custom UIs. + +## Event Types + +Events are defined in [`AgentSessionEvent`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/agent-session.ts#L102): + +```typescript +type AgentSessionEvent = + | AgentEvent + | { type: "queue_update"; steering: readonly string[]; followUp: readonly string[] } + | { type: "compaction_start"; reason: "manual" | "threshold" | "overflow" } + | { type: "compaction_end"; reason: "manual" | "threshold" | "overflow"; result: CompactionResult | undefined; aborted: boolean; willRetry: boolean; errorMessage?: string } + | { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string } + | { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string } + | { type: "summarization_retry_scheduled"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string } + | { type: "summarization_retry_attempt_start"; source: "branchSummary" } + | { type: "summarization_retry_attempt_start"; source: "compaction"; reason: "manual" | "threshold" | "overflow" } + | { type: "summarization_retry_finished" }; +``` + +`queue_update` emits the full pending steering and follow-up queues whenever they change. `compaction_start` and `compaction_end` cover both manual and automatic compaction. + +Base events from [`AgentEvent`](https://github.com/earendil-works/pi-mono/blob/main/packages/agent/src/types.ts#L179): + +```typescript +type AgentEvent = + // Agent lifecycle + | { type: "agent_start" } + | { type: "agent_end"; messages: AgentMessage[] } + // Turn lifecycle + | { type: "turn_start" } + | { type: "turn_end"; message: AgentMessage; toolResults: ToolResultMessage[] } + // Message lifecycle + | { type: "message_start"; message: AgentMessage } + | { type: "message_update"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent } + | { type: "message_end"; message: AgentMessage } + // Tool execution + | { type: "tool_execution_start"; toolCallId: string; toolName: string; args: any } + | { type: "tool_execution_update"; toolCallId: string; toolName: string; args: any; partialResult: any } + | { type: "tool_execution_end"; toolCallId: string; toolName: string; result: any; isError: boolean }; +``` + +## Message Types + +Base messages from [`packages/ai/src/types.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/types.ts#L134): +- `UserMessage` (line 134) +- `AssistantMessage` (line 140) +- `ToolResultMessage` (line 152) + +Extended messages from [`packages/coding-agent/src/core/messages.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/messages.ts#L29): +- `BashExecutionMessage` (line 29) +- `CustomMessage` (line 46) +- `BranchSummaryMessage` (line 55) +- `CompactionSummaryMessage` (line 62) + +## Output Format + +Each line is a JSON object. The first line is the session header: + +```json +{"type":"session","version":3,"id":"uuid","timestamp":"...","cwd":"/path"} +``` + +Followed by events as they occur: + +```json +{"type":"agent_start"} +{"type":"turn_start"} +{"type":"message_start","message":{"role":"assistant","content":[],...}} +{"type":"message_update","message":{...},"assistantMessageEvent":{"type":"text_delta","delta":"Hello",...}} +{"type":"message_end","message":{...}} +{"type":"turn_end","message":{...},"toolResults":[]} +{"type":"agent_end","messages":[...]} +``` + +## Example + +```bash +pi --mode json "List files" 2>/dev/null | jq -c 'select(.type == "message_end")' +``` diff --git a/docs/keybindings.md b/docs/keybindings.md new file mode 100644 index 0000000..08a5815 --- /dev/null +++ b/docs/keybindings.md @@ -0,0 +1,198 @@ +# Keybindings + +All keyboard shortcuts can be customized via `~/.pi/agent/keybindings.json`. Each action can be bound to one or more keys. + +The config file uses the same namespaced keybinding ids that pi uses internally and that extension authors use in `keyHint()` and injected `keybindings` managers. + +Older configs using pre-namespaced ids such as `cursorUp` or `expandTools` are migrated automatically to the namespaced ids on startup. + +After editing `keybindings.json`, run `/reload` in pi to apply the changes without restarting the session. + +## Key Format + +`modifier+key` where modifiers are `ctrl`, `shift`, `alt` (combinable) and keys are: + +- **Letters:** `a-z` +- **Digits:** `0-9` +- **Special:** `escape`, `esc`, `enter`, `return`, `tab`, `space`, `backspace`, `delete`, `insert`, `clear`, `home`, `end`, `pageUp`, `pageDown`, `up`, `down`, `left`, `right` +- **Function:** `f1`-`f12` +- **Symbols:** `` ` ``, `-`, `=`, `[`, `]`, `\`, `;`, `'`, `,`, `.`, `/`, `!`, `@`, `#`, `$`, `%`, `^`, `&`, `*`, `(`, `)`, `_`, `+`, `|`, `~`, `{`, `}`, `:`, `<`, `>`, `?` + +Modifier combinations: `ctrl+shift+x`, `alt+ctrl+x`, `ctrl+shift+alt+x`, `ctrl+1`, etc. + +## All Actions + +### TUI Editor Cursor Movement + +| Keybinding id | Default | Description | +|--------|---------|-------------| +| `tui.editor.cursorUp` | `up` | Move cursor up | +| `tui.editor.cursorDown` | `down` | Move cursor down | +| `tui.editor.cursorLeft` | `left`, `ctrl+b` | Move cursor left | +| `tui.editor.cursorRight` | `right`, `ctrl+f` | Move cursor right | +| `tui.editor.cursorWordLeft` | `alt+left`, `ctrl+left`, `alt+b` | Move cursor word left | +| `tui.editor.cursorWordRight` | `alt+right`, `ctrl+right`, `alt+f` | Move cursor word right | +| `tui.editor.cursorLineStart` | `home`, `ctrl+a` | Move to line start | +| `tui.editor.cursorLineEnd` | `end`, `ctrl+e` | Move to line end | +| `tui.editor.jumpForward` | `ctrl+]` | Jump forward to character | +| `tui.editor.jumpBackward` | `ctrl+alt+]` | Jump backward to character | +| `tui.editor.pageUp` | `pageUp` | Scroll up by page | +| `tui.editor.pageDown` | `pageDown` | Scroll down by page | + +### TUI Editor Deletion + +| Keybinding id | Default | Description | +|--------|---------|-------------| +| `tui.editor.deleteCharBackward` | `backspace` | Delete character backward | +| `tui.editor.deleteCharForward` | `delete`, `ctrl+d` | Delete character forward | +| `tui.editor.deleteWordBackward` | `ctrl+w`, `alt+backspace` | Delete word backward | +| `tui.editor.deleteWordForward` | `alt+d`, `alt+delete` | Delete word forward | +| `tui.editor.deleteToLineStart` | `ctrl+u` | Delete to line start | +| `tui.editor.deleteToLineEnd` | `ctrl+k` | Delete to line end | + +### TUI Input + +| Keybinding id | Default | Description | +|--------|---------|-------------| +| `tui.input.newLine` | `shift+enter`, `ctrl+j` | Insert new line | +| `tui.input.submit` | `enter` | Submit input | +| `tui.input.tab` | `tab` | Tab / autocomplete | + +### TUI Kill Ring + +| Keybinding id | Default | Description | +|--------|---------|-------------| +| `tui.editor.yank` | `ctrl+y` | Paste most recently deleted text | +| `tui.editor.yankPop` | `alt+y` | Cycle through deleted text after yank | +| `tui.editor.undo` | `ctrl+-` | Undo last edit | + +### TUI Clipboard and Selection + +| Keybinding id | Default | Description | +|--------|---------|-------------| +| `tui.input.copy` | `ctrl+c` | Copy selection | +| `tui.select.up` | `up` | Move selection up | +| `tui.select.down` | `down` | Move selection down | +| `tui.select.pageUp` | `pageUp` | Page up in list | +| `tui.select.pageDown` | `pageDown` | Page down in list | +| `tui.select.confirm` | `enter` | Confirm selection | +| `tui.select.cancel` | `escape`, `ctrl+c` | Cancel selection | + +### Application + +| Keybinding id | Default | Description | +|--------|---------|-------------| +| `app.interrupt` | `escape` | Cancel / abort | +| `app.clear` | `ctrl+c` | Clear editor | +| `app.exit` | `ctrl+d` | Exit (when editor empty) | +| `app.suspend` | `ctrl+z` (none on Windows) | Suspend to background | +| `app.editor.external` | `ctrl+g` | Open in external editor (`externalEditor`, `$VISUAL`, `$EDITOR`, Notepad on Windows, or `nano` elsewhere) | +| `app.clipboard.pasteImage` | `ctrl+v` (`alt+v` on Windows) | Paste image from clipboard | + +### Sessions + +| Keybinding id | Default | Description | +|--------|---------|-------------| +| `app.session.new` | *(none)* | Start a new session (`/new`) | +| `app.session.tree` | *(none)* | Open session tree navigator (`/tree`) | +| `app.session.fork` | *(none)* | Fork current session (`/fork`) | +| `app.session.resume` | *(none)* | Open session resume picker (`/resume`) | +| `app.session.togglePath` | `ctrl+p` | Toggle path display | +| `app.session.toggleSort` | `ctrl+s` | Toggle sort mode | +| `app.session.toggleNamedFilter` | `ctrl+n` | Toggle named-only filter | +| `app.session.rename` | `ctrl+r` | Rename session | +| `app.session.delete` | `ctrl+d` | Delete session | +| `app.session.deleteNoninvasive` | `ctrl+backspace` | Delete session when query is empty | + +### Models and Thinking + +| Keybinding id | Default | Description | +|--------|---------|-------------| +| `app.model.select` | `ctrl+l` | Open model selector | +| `app.model.cycleForward` | `ctrl+p` | Cycle to next model | +| `app.model.cycleBackward` | `shift+ctrl+p` | Cycle to previous model | +| `app.thinking.cycle` | `shift+tab` | Cycle thinking level | +| `app.thinking.toggle` | `ctrl+t` | Collapse or expand thinking blocks | + +### Display and Message Queue + +| Keybinding id | Default | Description | +|--------|---------|-------------| +| `app.tools.expand` | `ctrl+o` | Collapse or expand tool output | +| `app.message.copy` | `ctrl+x` | Copy the last assistant message, or the selected message in `/tree` | +| `app.message.followUp` | `alt+enter` | Queue follow-up message | +| `app.message.dequeue` | `alt+up` | Restore queued messages to editor | + +### Tree Navigation + +| Keybinding id | Default | Description | +|--------|---------|-------------| +| `app.tree.foldOrUp` | `ctrl+left`, `alt+left` | Fold current branch segment, or jump to the previous segment start | +| `app.tree.unfoldOrDown` | `ctrl+right`, `alt+right` | Unfold current branch segment, or jump to the next segment start or branch end | +| `app.tree.editLabel` | `shift+l` | Edit the label on the selected tree node | +| `app.tree.toggleLabelTimestamp` | `shift+t` | Toggle label timestamps in the tree | +| `app.tree.filter.default` | `ctrl+d` | Set tree filter to default view | +| `app.tree.filter.noTools` | `ctrl+t` | Toggle tree filter that hides tool results | +| `app.tree.filter.userOnly` | `ctrl+u` | Toggle tree filter that shows only user messages | +| `app.tree.filter.labeledOnly` | `ctrl+l` | Toggle tree filter that shows only labeled entries | +| `app.tree.filter.all` | `ctrl+a` | Toggle tree filter that shows all entries | +| `app.tree.filter.cycleForward` | `ctrl+o` | Cycle tree filter forward | +| `app.tree.filter.cycleBackward` | `shift+ctrl+o` | Cycle tree filter backward | + +### Scoped Models Selector + +Used inside the scoped models selector (opened via `/scoped-models`). + +| Keybinding id | Default | Description | +|--------|---------|-------------| +| `app.models.save` | `ctrl+s` | Save current model selection to settings | +| `app.models.enableAll` | `ctrl+a` | Enable all models (or all matching the current search) | +| `app.models.clearAll` | `ctrl+x` | Clear all models (or all matching the current search) | +| `app.models.toggleProvider` | `ctrl+p` | Toggle all models for the current provider | +| `app.models.reorderUp` | `alt+up` | Move the selected model up in the cycle order | +| `app.models.reorderDown` | `alt+down` | Move the selected model down in the cycle order | + +## Custom Configuration + +Create `~/.pi/agent/keybindings.json`: + +```json +{ + "tui.editor.cursorUp": ["up", "ctrl+p"], + "tui.editor.cursorDown": ["down", "ctrl+n"], + "tui.editor.deleteWordBackward": ["ctrl+w", "alt+backspace"] +} +``` + +Each action can have a single key or an array of keys. User config overrides defaults. + +On native Windows, `app.suspend` has no default binding because Windows terminals do not support Unix job control. If you bind it manually, pi shows a status message instead of suspending. In WSL, the normal Linux `ctrl+z`/`fg` behavior still applies. + +### Emacs Example + +```json +{ + "tui.editor.cursorUp": ["up", "ctrl+p"], + "tui.editor.cursorDown": ["down", "ctrl+n"], + "tui.editor.cursorLeft": ["left", "ctrl+b"], + "tui.editor.cursorRight": ["right", "ctrl+f"], + "tui.editor.cursorWordLeft": ["alt+left", "alt+b"], + "tui.editor.cursorWordRight": ["alt+right", "alt+f"], + "tui.editor.deleteCharForward": ["delete", "ctrl+d"], + "tui.editor.deleteCharBackward": ["backspace", "ctrl+h"], + "tui.input.newLine": ["shift+enter", "ctrl+j"] +} +``` + +### Vim Example + +```json +{ + "tui.editor.cursorUp": ["up", "alt+k"], + "tui.editor.cursorDown": ["down", "alt+j"], + "tui.editor.cursorLeft": ["left", "alt+h"], + "tui.editor.cursorRight": ["right", "alt+l"], + "tui.editor.cursorWordLeft": ["alt+left", "alt+b"], + "tui.editor.cursorWordRight": ["alt+right", "alt+w"] +} +``` diff --git a/docs/llama-cpp.md b/docs/llama-cpp.md new file mode 100644 index 0000000..13f314c --- /dev/null +++ b/docs/llama-cpp.md @@ -0,0 +1,99 @@ +# llama.cpp + +Pi supports the [llama.cpp](https://github.com/ggml-org/llama.cpp) router server. The router discovers multiple GGUF models and loads or unloads them on demand. + +Use a current llama.cpp build with router support. Follow the [build instructions](https://github.com/ggml-org/llama.cpp/blob/master/docs/build.md) or install a [prebuilt release](https://github.com/ggml-org/llama.cpp/releases) for your platform. + +## Start the router + +Start `llama-server` without `--model` or `-m`. Passing a model starts single-model mode instead of router mode. + +```bash +llama-server \ + --models-dir ~/models \ + --no-models-autoload \ + --jinja \ + --host 127.0.0.1 \ + --port 8080 \ + -ngl 999 \ + -c 32768 +``` + +Important options: + +- `--models-dir ~/models` discovers local GGUF files. +- `--no-models-autoload` keeps loading explicit through `/llama`. +- `--jinja` enables compatible chat templates and tool calling. +- `-ngl 999` offloads as many layers as possible to the GPU. +- `-c 32768` sets the context window for each loaded model. Omit it to use the model's native context, which may require substantially more memory. + +A single-file model can sit directly in the model directory. Put multimodal and multi-shard models in separate subdirectories: + +```text +~/models/ +├── llama-3.2-1b-Q4_K_M.gguf +├── gemma-3-4b-it-Q4_K_M/ +│ ├── gemma-3-4b-it-Q4_K_M.gguf +│ └── mmproj-F16.gguf +└── large-model-Q4_K_M/ + ├── large-model-Q4_K_M-00001-of-00003.gguf + ├── large-model-Q4_K_M-00002-of-00003.gguf + └── large-model-Q4_K_M-00003-of-00003.gguf +``` + +Restart the router after manually adding files. For per-model context sizes and other options, use [llama.cpp model presets](https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md#model-presets). + +## Configure Pi + +Start Pi and configure the provider: + +```text +/login llama.cpp +``` + +Enter the router URL and optional API key. The default URL is `http://127.0.0.1:8080`. + +Environment variables can configure the same values without `/login`: + +```bash +export LLAMA_BASE_URL=http://127.0.0.1:8080 +export LLAMA_API_KEY=optional-secret +pi +``` + +If the server uses an API key, start `llama-server` with the matching `--api-key` value. Keep `--host 127.0.0.1` for local-only access. + +## Manage models + +Run: + +```text +/llama +``` + +- Select an unloaded model to load it. +- Select a loaded model to unload it. +- Select **Download model…**, search Hugging Face, then choose a repository and quantization. Exact `owner/repository[:quant]` values also work. +- Press Escape during a load or download to confirm cancellation. + +Hugging Face search uses `HF_TOKEN` when set, then checks `$HF_TOKEN_PATH`, `$HF_HOME/token`, `$XDG_CACHE_HOME/huggingface/token`, and `~/.cache/huggingface/token`. Search also works without authentication, subject to lower rate limits. Pi warns before downloading gated repositories and links to their access page. The llama.cpp server performs the download, so its process must also have `HF_TOKEN` when the selected repository requires access. + +If other models are loaded, Pi asks whether to unload them first or keep them loaded. Pi does not silently unload models and never deletes model files. The router may be shared with other clients, so `/llama` always displays the router's current state. + +Only loaded models appear in `/model`. After loading a model, run `/model` to select it for the current Pi session. + +If the router disconnects, `/llama` shows **Retry** and **Close**. Retry reconnects and refreshes model state without replaying the interrupted operation. + +## Troubleshooting + +Check that the router is reachable: + +```bash +curl http://127.0.0.1:8080/health +curl http://127.0.0.1:8080/models +``` + +- **No models in `/llama`:** Check `--models-dir`, the directory layout, and restart the router. +- **Model missing from `/model`:** Load it with `/llama` first. +- **Load fails or uses too much memory:** Lower `-c` or unload another model. +- **Server is not in router mode:** Start it without `--model`, `-m`, or `-hf`. diff --git a/docs/models.md b/docs/models.md new file mode 100644 index 0000000..f2493b2 --- /dev/null +++ b/docs/models.md @@ -0,0 +1,544 @@ +# Custom Models + +Add custom providers and models (Ollama, vLLM, LM Studio, proxies) via `~/.pi/agent/models.json`. + +## Table of Contents + +- [Minimal Example](#minimal-example) +- [Full Example](#full-example) +- [Supported APIs](#supported-apis) +- [Provider Configuration](#provider-configuration) +- [Model Configuration](#model-configuration) +- [Overriding Built-in Providers](#overriding-built-in-providers) +- [Per-model Overrides](#per-model-overrides) +- [Anthropic Messages Compatibility](#anthropic-messages-compatibility) +- [OpenAI Compatibility](#openai-compatibility) + +## Minimal Example + +For local models (Ollama, LM Studio, vLLM), only `id` is required per model: + +```json +{ + "providers": { + "ollama": { + "baseUrl": "http://localhost:11434/v1", + "api": "openai-completions", + "apiKey": "ollama", + "models": [ + { "id": "llama3.1:8b" }, + { "id": "qwen2.5-coder:7b" } + ] + } + } +} +``` + +The `apiKey` value is a placeholder because Ollama ignores it. pi still treats models as requiring auth before they appear in `/model`, so keyless local servers should keep a dummy value, save a key for that provider with `/login`, or pass `--api-key` when selecting the model. + +Some OpenAI-compatible servers do not understand the `developer` role used for reasoning-capable models. For those providers, set `compat.supportsDeveloperRole` to `false` so pi sends the system prompt as a `system` message instead. If the server also does not support `reasoning_effort`, set `compat.supportsReasoningEffort` to `false` too. + +You can set `compat` at the provider level to apply to all models, or at the model level to override a specific model. This commonly applies to Ollama, vLLM, SGLang, and similar OpenAI-compatible servers. + +```json +{ + "providers": { + "ollama": { + "baseUrl": "http://localhost:11434/v1", + "api": "openai-completions", + "apiKey": "ollama", + "compat": { + "supportsDeveloperRole": false, + "supportsReasoningEffort": false + }, + "models": [ + { + "id": "gpt-oss:20b", + "reasoning": true + } + ] + } + } +} +``` + +## Full Example + +Override defaults when you need specific values: + +```json +{ + "providers": { + "ollama": { + "baseUrl": "http://localhost:11434/v1", + "api": "openai-completions", + "apiKey": "ollama", + "models": [ + { + "id": "llama3.1:8b", + "name": "Llama 3.1 8B (Local)", + "reasoning": false, + "input": ["text"], + "contextWindow": 128000, + "maxTokens": 32000, + "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 } + } + ] + } + } +} +``` + +The file reloads each time you open `/model`. Edit during session; no restart needed. + +## Google AI Studio Example + +Use `google-generative-ai` with a `baseUrl` to add models from Google AI Studio, including custom Gemma 4 entries: + +```json +{ + "providers": { + "my-google": { + "baseUrl": "https://generativelanguage.googleapis.com/v1beta", + "api": "google-generative-ai", + "apiKey": "$GEMINI_API_KEY", + "models": [ + { + "id": "gemma-4-31b-it", + "name": "Gemma 4 31B", + "input": ["text", "image"], + "contextWindow": 262144, + "reasoning": true + } + ] + } + } +} +``` + +The `baseUrl` is required when adding custom models to the `google-generative-ai` API type. + +## Supported APIs + +| API | Description | +|-----|-------------| +| `openai-completions` | OpenAI Chat Completions (most compatible) | +| `openai-responses` | OpenAI Responses API | +| `anthropic-messages` | Anthropic Messages API | +| `google-generative-ai` | Google Generative AI | + +Set `api` at provider level (default for all models) or model level (override per model). + +## Provider Configuration + +| Field | Description | +|-------|-------------| +| `baseUrl` | API endpoint URL | +| `api` | API type (see above) | +| `apiKey` | Optional API key config (see value resolution below). Omit it when auth is provided by `/login`/`auth.json` or CLI `--api-key`. | +| `oauth` | Dynamic OAuth provider type. Currently supports `"radius"`; requires the gateway `baseUrl`. | +| `headers` | Custom headers (see value resolution below) | +| `authHeader` | Set `true` to add `Authorization: Bearer ` automatically | +| `models` | Array of model configurations | +| `modelOverrides` | Per-model overrides for built-in or extension-registered models on this provider | + +For providers with `models`, non-built-in provider configs need `baseUrl` and an `api` value at either provider or model level. `apiKey` is not required to load the file: models become available when auth is configured through `/login`/`auth.json`, CLI `--api-key`, or provider `apiKey`. If no auth is configured, the models load but stay unavailable in `/model` and `--list-models`. + +### Value Resolution + +The `apiKey` and `headers` fields support command execution, environment interpolation, and literals: + +- **Shell command:** `"!command"` at the start executes the whole value as a command and uses stdout + ```json + "apiKey": "!security find-generic-password -ws 'anthropic'" + "apiKey": "!op read 'op://vault/item/credential'" + ``` +- **Environment interpolation:** `"$ENV_VAR"` or `"${ENV_VAR}"` uses the value of the named variable. Interpolation works inside larger literals. + ```json + "apiKey": "$MY_API_KEY" + "apiKey": "${KEY_PREFIX}_${KEY_SUFFIX}" + ``` + `$FOO_BAR` is the variable `FOO_BAR`; use `${FOO}_BAR` when `BAR` is literal text. Missing environment variables make the value unresolved. +- **Escapes:** `"$$"` emits a literal `"$"`; `"$!"` emits a literal `"!"` without triggering command execution. + ```json + "apiKey": "$$literal-dollar-prefix" + "apiKey": "$!literal-bang-prefix" + ``` +- **Literal value:** Used directly. Plain uppercase strings such as `MY_API_KEY` are literals; use `$MY_API_KEY` for environment variables. + ```json + "apiKey": "sk-..." + ``` + +For `models.json`, shell commands are resolved at request time. pi intentionally does not apply built-in TTL, stale reuse, or recovery logic for arbitrary commands. Different commands need different caching and failure strategies, and pi cannot infer the right one. + +If your command is slow, expensive, rate-limited, or should keep using a previous value on transient failures, wrap it in your own script or command that implements the caching or TTL behavior you want. + +`/model` availability checks use configured auth presence and do not execute shell commands. + +### Custom Headers + +```json +{ + "providers": { + "custom-proxy": { + "baseUrl": "https://proxy.example.com/v1", + "apiKey": "$MY_API_KEY", + "api": "anthropic-messages", + "headers": { + "x-portkey-api-key": "$PORTKEY_API_KEY", + "x-secret": "!op read 'op://vault/item/secret'" + }, + "models": [...] + } + } +} +``` + +## Model Configuration + +| Field | Required | Default | Description | +|-------|----------|---------|-------------| +| `id` | Yes | — | Model identifier (passed to the API) | +| `name` | No | `id` | Human-readable model label. Used for matching (`--model` patterns) and shown as secondary model detail text. | +| `api` | No | provider's `api` | Override provider's API for this model | +| `reasoning` | No | `false` | Supports extended thinking | +| `thinkingLevelMap` | No | omitted | Maps pi thinking levels to provider values and marks unsupported levels (see below) | +| `input` | No | `["text"]` | Input types: `["text"]` or `["text", "image"]` | +| `contextWindow` | No | `128000` | Context window size in tokens | +| `maxTokens` | No | `16384` | Maximum output tokens | +| `cost` | No | all zeros | Per-million-token rates with optional request-wide input pricing tiers | +| `compat` | No | provider `compat` | Provider compatibility overrides. Merged with provider-level `compat` when both are set. | + +A cost tier supplies a complete alternate rate set and applies to the full request when total input usage (`input + cacheRead + cacheWrite`) exceeds `inputTokensAbove`. When multiple tiers match, the highest threshold wins. + +```json +{ + "cost": { + "input": 5, + "output": 30, + "cacheRead": 0.5, + "cacheWrite": 6.25, + "tiers": [ + { + "inputTokensAbove": 272000, + "input": 10, + "output": 45, + "cacheRead": 1, + "cacheWrite": 12.5 + } + ] + } +} +``` + +Current behavior: +- `/model`, `--list-models`, and the interactive footer display entries by model `id`. +- The configured `name` is used for model matching and secondary model detail text. It does not replace the footer/status-bar model id. + +### Thinking Level Map + +Use `thinkingLevelMap` on a model to describe model-specific thinking controls. Keys are pi thinking levels: `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. Maps may contain holes; for example, a model can expose `high` and `max` without exposing `xhigh`. + +Values are tristate: + +| Value | Meaning | +|-------|---------| +| omitted | Standard levels through `high` use the provider's default mapping; extended `xhigh` and `max` levels are unsupported | +| string | Level is supported and this value is sent to the provider | +| `null` | Level is unsupported and hidden/skipped/clamped away | + +Example for a model that only supports off, high, and max reasoning: + +```json +{ + "id": "deepseek-v4-pro", + "reasoning": true, + "thinkingLevelMap": { + "minimal": null, + "low": null, + "medium": null, + "high": "high", + "xhigh": null, + "max": "max" + } +} +``` + +Example for a model where thinking cannot be disabled: + +```json +{ + "id": "always-thinking-model", + "reasoning": true, + "thinkingLevelMap": { + "off": null + } +} +``` + +Migration: older configs that used `compat.reasoningEffortMap` should move that mapping to model-level `thinkingLevelMap`. Use `null` for levels that should not appear in the UI. + +## Overriding Built-in Providers + +Route a built-in provider through a proxy without redefining models: + +```json +{ + "providers": { + "anthropic": { + "baseUrl": "https://my-proxy.example.com/v1" + } + } +} +``` + +All built-in Anthropic models remain available. Existing OAuth or API key auth continues to work. + +To merge custom models into a built-in provider, include the `models` array: + +```json +{ + "providers": { + "anthropic": { + "baseUrl": "https://my-proxy.example.com/v1", + "apiKey": "$ANTHROPIC_API_KEY", + "api": "anthropic-messages", + "models": [...] + } + } +} +``` + +Merge semantics: +- Built-in models are kept. +- Custom models are upserted by `id` within the provider. +- If a custom model `id` matches a built-in model `id`, the custom model replaces that built-in model. +- If a custom model `id` is new, it is added alongside built-in models. + +## Per-model Overrides + +Use `modelOverrides` to customize built-in models and matching extension-registered models without replacing the provider's full model list. + +```json +{ + "providers": { + "openrouter": { + "modelOverrides": { + "anthropic/claude-sonnet-4": { + "name": "Claude Sonnet 4 (Bedrock Route)", + "compat": { + "openRouterRouting": { + "only": ["amazon-bedrock"] + } + } + } + } + } + } +} +``` + +`modelOverrides` supports these fields per model: `name`, `reasoning`, `thinkingLevelMap`, `input`, `cost` (partial), `contextWindow`, `maxTokens`, `headers`, `compat`. + +Direct OpenAI GPT-5.6 Sol, Terra, and Luna default to a `272000` context window so requests remain within OpenAI's short-context pricing tier. To opt into OpenAI's 1.05M context window, increase it for each model you use: + +```json +{ + "providers": { + "openai": { + "modelOverrides": { + "gpt-5.6-sol": { + "contextWindow": 1050000 + } + } + } + } +} +``` + +The override preserves the built-in pricing metadata. Requests with more than 272K total input tokens use GPT-5.6's long-context rates for the entire request. Apply the same override to `gpt-5.6-terra` or `gpt-5.6-luna` when needed. + +Behavior notes: +- `modelOverrides` are applied to built-in provider models and matching extension-registered provider models. +- Unknown model IDs are ignored. +- You can combine provider-level `baseUrl`/`headers` with `modelOverrides`. +- Overriding `name` changes model matching and secondary detail text only; the footer and primary model lists continue to show the model `id`. +- If `models` is also defined for a provider, custom models are merged after built-in overrides. A custom model with the same `id` replaces the overridden built-in model entry. + +## Anthropic Messages Compatibility + +For providers or proxies using `api: "anthropic-messages"`, use `compat` to control Anthropic-specific request compatibility. + +By default pi sends per-tool `eager_input_streaming: true`. If a proxy or Anthropic-compatible backend rejects that field, set `supportsEagerToolInputStreaming` to `false`. Pi will omit `tools[].eager_input_streaming` and send the legacy `fine-grained-tool-streaming-2025-05-14` beta header for tool-enabled requests instead. + +Some Anthropic models require adaptive thinking (`thinking.type: "adaptive"` plus `output_config.effort`) instead of the legacy budget-based thinking payload. Built-in models set this automatically. For custom providers or aliases that route to those models, set `forceAdaptiveThinking` to `true`. + +Some Anthropic-compatible providers emit thinking blocks with empty signatures and still expect them on replay. Set `allowEmptySignature` to `true` only for those providers; real Anthropic rejects empty thinking signatures. + +Built-in Anthropic models enable `supportsStrictTools` in their model metadata. Custom Anthropic-compatible models must set it to `true` when their endpoint accepts strict JSON-schema tool definitions. + +```json +{ + "providers": { + "anthropic-proxy": { + "baseUrl": "https://proxy.example.com", + "api": "anthropic-messages", + "apiKey": "$ANTHROPIC_PROXY_KEY", + "compat": { + "supportsEagerToolInputStreaming": false, + "supportsLongCacheRetention": true, + "forceAdaptiveThinking": true, + "allowEmptySignature": true + }, + "models": [ + { + "id": "claude-opus-4-7", + "reasoning": true, + "input": ["text", "image"] + } + ] + } + } +} +``` + +| Field | Description | +|-------|-------------| +| `supportsEagerToolInputStreaming` | Whether the provider accepts per-tool `eager_input_streaming`. Default: `true`. Set to `false` to omit that field and use the legacy fine-grained tool streaming beta header on tool-enabled requests. | +| `supportsLongCacheRetention` | Whether the provider accepts Anthropic long cache retention (`cache_control.ttl: "1h"`) when cache retention is `long`. Default: `true`. | +| `sendSessionAffinityHeaders` | Whether to send `x-session-affinity` from the session id when caching is enabled. Default: auto-detected for known providers. | +| `supportsCacheControlOnTools` | Whether the provider accepts Anthropic-style `cache_control` markers on tool definitions. Default: `true`. | +| `forceAdaptiveThinking` | Whether to send adaptive thinking (`thinking.type: "adaptive"` plus `output_config.effort`) for this model. Built-in adaptive models set this automatically. Default: `false`. | +| `allowEmptySignature` | Whether to replay empty thinking signatures as `signature: ""` instead of converting thinking to text. Default: `false`. | +| `supportsStrictTools` | Whether the provider accepts strict JSON-schema tool definitions. Default: `false`; built-in Anthropic models enable it in generated metadata. | + +## OpenAI Compatibility + +For providers with partial OpenAI compatibility, use the `compat` field. + +- Provider-level `compat` applies defaults to all models under that provider. +- Model-level `compat` overrides provider-level values for that model. + +```json +{ + "providers": { + "local-llm": { + "baseUrl": "http://localhost:8080/v1", + "api": "openai-completions", + "compat": { + "supportsUsageInStreaming": false, + "maxTokensField": "max_tokens" + }, + "models": [...] + } + } +} +``` + +| Field | Description | +|-------|-------------| +| `supportsStore` | Provider supports `store` field | +| `supportsDeveloperRole` | Use `developer` vs `system` role | +| `supportsReasoningEffort` | Support for `reasoning_effort` parameter | +| `supportsUsageInStreaming` | Supports `stream_options: { include_usage: true }` (default: `true`) | +| `maxTokensField` | Use `max_completion_tokens` or `max_tokens` | +| `requiresToolResultName` | Include `name` on tool result messages | +| `requiresAssistantAfterToolResult` | Insert an assistant message before a user message after tool results | +| `requiresThinkingAsText` | Convert thinking blocks to plain text | +| `requiresReasoningContentOnAssistantMessages` | Include empty `reasoning_content` on all replayed assistant messages when reasoning is enabled | +| `thinkingFormat` | Use `reasoning_effort`, `openrouter`, `deepseek`, `together`, `zai`, `qwen`, `chat-template`, or `qwen-chat-template` thinking parameters | +| `chatTemplateKwargs` | `chat_template_kwargs` values for `thinkingFormat: "chat-template"`; use `{ "$var": "thinking.enabled" }` or `{ "$var": "thinking.effort" }` for pi-controlled thinking values | +| `cacheControlFormat` | Use Anthropic-style `cache_control` markers on the system prompt, last tool definition, and last user, assistant, or tool-result text content. Currently only `anthropic` is supported. | +| `sendSessionAffinityHeaders` | For `openai-completions`, send session-affinity headers from the session id when caching is enabled. Default: `false`. | +| `sessionAffinityFormat` | For `openai-completions` and `openai-responses`, the session-affinity header format: `openai` sends `session_id`/`x-client-request-id` (completions also `x-session-affinity`), `openai-nosession` omits the underscore-containing `session_id` header, `openrouter` sends `x-session-id`. Does not affect the `prompt_cache_key` body param. Default: auto-detected. | +| `supportsStrictMode` | Whether the provider accepts strict JSON-schema function tool definitions. Defaults depend on the API; built-in OpenAI models carry explicit capability metadata. | +| `supportsOpenAIGrammarTools` | Whether OpenAI-compatible APIs emit custom Lark/regex grammar tools. When `false`, grammar-constrained tools fall back to normal function tools. Default: `false`; the built-in model catalog enables it for GPT-5+ models on OpenAI, OpenAI Codex, Azure OpenAI, GitHub Copilot, opencode, and Cloudflare AI Gateway. | +| `deferredToolsMode` | Use provider-specific deferred tool serialization. Currently only `"kimi"` is supported for Kimi's OpenAI-compatible Chat Completions format. | +| `supportsLongCacheRetention` | Whether the provider accepts long cache retention when cache retention is `long`: `prompt_cache_retention: "24h"` for OpenAI prompt caching, or `cache_control.ttl: "1h"` when `cacheControlFormat` is `anthropic`. Default: `true`. | +| `openRouterRouting` | OpenRouter provider routing preferences. This object is sent as-is in the `provider` field of the [OpenRouter API request](https://openrouter.ai/docs/guides/routing/provider-selection). | +| `vercelGatewayRouting` | Vercel AI Gateway routing config for provider selection (`only`, `order`) | + +`openrouter` uses `reasoning: { effort }`. `together` uses `reasoning: { enabled }` and also `reasoning_effort` when `supportsReasoningEffort` is enabled. `qwen` uses top-level `enable_thinking`. Use `qwen-chat-template` for local Qwen-compatible servers that require `chat_template_kwargs.enable_thinking` and `preserve_thinking`. Use `chat-template` for vLLM/Hugging Face chat templates that need configurable `chat_template_kwargs`, such as `chatTemplateKwargs: { "thinking": { "$var": "thinking.enabled" } }` for DeepSeek V3.x templates. + +`cacheControlFormat: "anthropic"` is for OpenAI-compatible providers that expose Anthropic-style prompt caching through `cache_control` markers on text content and tool definitions. + +Example: + +```json +{ + "providers": { + "openrouter": { + "baseUrl": "https://openrouter.ai/api/v1", + "apiKey": "$OPENROUTER_API_KEY", + "api": "openai-completions", + "models": [ + { + "id": "openrouter/anthropic/claude-3.5-sonnet", + "name": "OpenRouter Claude 3.5 Sonnet", + "compat": { + "openRouterRouting": { + "allow_fallbacks": true, + "require_parameters": false, + "data_collection": "deny", + "zdr": true, + "enforce_distillable_text": false, + "order": ["anthropic", "amazon-bedrock", "google-vertex"], + "only": ["anthropic", "amazon-bedrock"], + "ignore": ["gmicloud", "friendli"], + "quantizations": ["fp16", "bf16"], + "sort": { + "by": "price", + "partition": "model" + }, + "max_price": { + "prompt": 10, + "completion": 20 + }, + "preferred_min_throughput": { + "p50": 100, + "p90": 50 + }, + "preferred_max_latency": { + "p50": 1, + "p90": 3, + "p99": 5 + } + } + } + } + ] + } + } +} +``` + +Vercel AI Gateway example: + +```json +{ + "providers": { + "vercel-ai-gateway": { + "baseUrl": "https://ai-gateway.vercel.sh/v1", + "apiKey": "$AI_GATEWAY_API_KEY", + "api": "openai-completions", + "models": [ + { + "id": "moonshotai/kimi-k2.5", + "name": "Kimi K2.5 (Fireworks via Vercel)", + "reasoning": true, + "input": ["text", "image"], + "cost": { "input": 0.6, "output": 3, "cacheRead": 0, "cacheWrite": 0 }, + "contextWindow": 262144, + "maxTokens": 262144, + "compat": { + "vercelGatewayRouting": { + "only": ["fireworks", "novita"], + "order": ["fireworks", "novita"] + } + } + } + ] + } + } +} +``` diff --git a/docs/packages.md b/docs/packages.md new file mode 100644 index 0000000..b2f493b --- /dev/null +++ b/docs/packages.md @@ -0,0 +1,228 @@ +> pi can help you create pi packages. Ask it to bundle your extensions, skills, prompt templates, or themes. + +# Pi Packages + +Pi packages bundle extensions, skills, prompt templates, and themes so you can share them through npm or git. A package can declare resources in `package.json` under the `pi` key, or use conventional directories. + +## Table of Contents + +- [Install and Manage](#install-and-manage) +- [Package Sources](#package-sources) +- [Creating a Pi Package](#creating-a-pi-package) +- [Package Structure](#package-structure) +- [Dependencies](#dependencies) +- [Package Filtering](#package-filtering) +- [Enable and Disable Resources](#enable-and-disable-resources) +- [Scope and Deduplication](#scope-and-deduplication) + +## Install and Manage + +> **Security:** Pi packages run with full system access. Extensions execute arbitrary code, and skills can instruct the model to perform any action including running executables. Review source code before installing third-party packages. + +```bash +pi install npm:@foo/bar@1.0.0 +pi install git:github.com/user/repo@v1 +pi install https://github.com/user/repo # raw URLs work too +pi install /absolute/path/to/package +pi install ./relative/path/to/package + +pi remove npm:@foo/bar +pi list # show installed packages from settings +pi update # update pi only +pi update --all # update pi, update packages, and reconcile pinned git refs +pi update --extensions # update packages and reconcile pinned git refs only +pi update --models # refresh model catalogs only +pi update --self # update pi only +pi update --self --force # reinstall pi even if current +pi update npm:@foo/bar # update one package +pi update --extension npm:@foo/bar +``` + +These commands manage pi packages and `pi update` can update the pi CLI installation. To uninstall pi itself, see [Quickstart](quickstart.md#uninstall). + +By default, `install` and `remove` write to user settings (`~/.pi/agent/settings.json`). Use `-l` to write to project settings (`.pi/settings.json`) instead. Project settings can be shared with your team, and pi installs any missing packages automatically on startup after the project is trusted. + +To try a package without installing it, use `--extension` or `-e`. This installs to a temporary directory for the current run only: + +```bash +pi -e npm:@foo/bar +pi -e git:github.com/user/repo +``` + +## Package Sources + +Pi accepts three source types in settings and `pi install`. + +### npm + +``` +npm:@scope/pkg@1.2.3 +npm:pkg +``` + +- Versioned specs are pinned and skipped by package updates (`pi update --extensions`, `pi update --all`). +- User installs go under `~/.pi/agent/npm/`. +- Project installs go under `.pi/npm/`. +- Set `npmCommand` in `settings.json` to pin npm package lookup and install operations to a specific wrapper command such as `mise` or `asdf`. + +Example: + +```json +{ + "npmCommand": ["mise", "exec", "node@20", "--", "npm"] +} +``` + +### git + +``` +git:github.com/user/repo@v1 +git:git@github.com:user/repo@v1 +https://github.com/user/repo@v1 +ssh://git@github.com/user/repo@v1 +``` + +- Without `git:` prefix, only protocol URLs are accepted (`https://`, `http://`, `ssh://`, `git://`). +- With `git:` prefix, shorthand formats are accepted, including `github.com/user/repo` and `git@github.com:user/repo`. +- HTTPS and SSH URLs are both supported. +- SSH URLs use your configured SSH keys automatically (respects `~/.ssh/config`). +- For non-interactive runs (for example CI), you can set `GIT_TERMINAL_PROMPT=0` to disable credential prompts and set `GIT_SSH_COMMAND` (for example `ssh -o BatchMode=yes -o ConnectTimeout=5`) to fail fast. +- Refs are pinned tags or commits. `pi update --extensions` and `pi update --all` do not move them to newer refs, but they do reconcile an existing clone to the configured ref. +- Use `pi install git:host/user/repo@new-ref` to update settings and move an existing package to a new pinned ref. +- Cloned to `~/.pi/agent/git//` (global) or `.pi/git//` (project). +- When reconciliation changes the checkout, pi resets and cleans the clone, then runs `npm install` if `package.json` exists. + +**SSH examples:** +```bash +# git@host:path shorthand (requires git: prefix) +pi install git:git@github.com:user/repo + +# ssh:// protocol format +pi install ssh://git@github.com/user/repo + +# With version ref +pi install git:git@github.com:user/repo@v1.0.0 +``` + +### Local Paths + +``` +/absolute/path/to/package +./relative/path/to/package +``` + +Local paths point to files or directories on disk and are added to settings without copying. Relative paths are resolved against the settings file they appear in. If the path is a file, it loads as a single extension. If it is a directory, pi loads resources using package rules. + +## Creating a Pi Package + +Add a `pi` manifest to `package.json` or use conventional directories. Include the `pi-package` keyword for discoverability. + +```json +{ + "name": "my-package", + "keywords": ["pi-package"], + "pi": { + "extensions": ["./extensions"], + "skills": ["./skills"], + "prompts": ["./prompts"], + "themes": ["./themes"] + } +} +``` + +Paths are relative to the package root. Arrays support glob patterns and `!exclusions`. + +### Gallery Metadata + +The [package gallery](https://pi.dev/packages) displays packages tagged with `pi-package`. Add `video` or `image` fields to show a preview: + +```json +{ + "name": "my-package", + "keywords": ["pi-package"], + "pi": { + "extensions": ["./extensions"], + "video": "https://example.com/demo.mp4", + "image": "https://example.com/screenshot.png" + } +} +``` + +- **video**: MP4 only. On desktop, autoplays on hover. Clicking opens a fullscreen player. +- **image**: PNG, JPEG, GIF, or WebP. Displayed as a static preview. + +If both are set, video takes precedence. + +## Package Structure + +### Convention Directories + +If no `pi` manifest is present, pi auto-discovers resources from these directories: + +- `extensions/` loads `.ts` and `.js` files +- `skills/` recursively finds `SKILL.md` folders and loads top-level `.md` files as skills +- `prompts/` loads `.md` files +- `themes/` loads `.json` files + +## Dependencies + +Third party runtime dependencies belong in `dependencies` in `package.json`. Dependencies that do not register extensions, skills, prompt templates, or themes also belong in `dependencies`. When pi installs a package from npm or git, it runs `npm install`, so those dependencies are installed automatically. + +Pi bundles core packages for extensions and skills. If you import any of these, list them in `peerDependencies` with a `"*"` range and do not bundle them: `@earendil-works/pi-ai`, `@earendil-works/pi-agent-core`, `@earendil-works/pi-coding-agent`, `@earendil-works/pi-tui`, `typebox`. + +Other pi packages must be bundled in your tarball. Add them to `dependencies` and `bundledDependencies`, then reference their resources through `node_modules/` paths. Pi loads packages with separate module roots, so separate installs do not collide or share modules. + +Example: + +```json +{ + "dependencies": { + "shitty-extensions": "^1.0.1" + }, + "bundledDependencies": ["shitty-extensions"], + "pi": { + "extensions": ["extensions", "node_modules/shitty-extensions/extensions"], + "skills": ["skills", "node_modules/shitty-extensions/skills"] + } +} +``` + +## Package Filtering + +Filter what a package loads using the object form in settings: + +```json +{ + "packages": [ + "npm:simple-pkg", + { + "source": "npm:my-package", + "extensions": ["extensions/*.ts", "!extensions/legacy.ts"], + "skills": [], + "prompts": ["prompts/review.md"], + "themes": ["+themes/legacy.json"] + } + ] +} +``` + +`+path` and `-path` are exact paths relative to the package root. + +- Omit a key to load all of that type. +- Use `[]` to load none of that type. +- `!pattern` excludes matches. +- `+path` force-includes an exact path. +- `-path` force-excludes an exact path. +- Filters layer on top of the manifest. They narrow down what is already allowed. + +## Enable and Disable Resources + +Use `pi config` to enable or disable extensions, skills, prompt templates, and themes from installed packages and local directories. `pi config` starts in global settings (`~/.pi/agent/settings.json`); press Tab to switch between global and project-local modes. Use `pi config -l` to start in project overrides (`.pi/settings.json`) with inherited global resources dimmed. + +## Scope and Deduplication + +Packages can appear in both global and project settings. If the same package appears in both, the project entry wins unless the project entry has `autoload: false`, in which case it is applied as a delta over the global entry. Identity is determined by: + +- npm: package name +- git: repository URL without ref +- local: resolved absolute path diff --git a/docs/prompt-templates.md b/docs/prompt-templates.md new file mode 100644 index 0000000..073b9f0 --- /dev/null +++ b/docs/prompt-templates.md @@ -0,0 +1,96 @@ +> pi can create prompt templates. Ask it to build one for your workflow. + +# Prompt Templates + +Prompt templates are Markdown snippets that expand into full prompts. Type `/name` in the editor to invoke a template, where `name` is the filename without `.md`. + +## Locations + +Pi loads prompt templates from: + +- Global: `~/.pi/agent/prompts/*.md` +- Project: `.pi/prompts/*.md` (only after the project is trusted) +- Packages: `prompts/` directories or `pi.prompts` entries in `package.json` +- Settings: `prompts` array with files or directories +- CLI: `--prompt-template ` (repeatable) + +Disable discovery with `--no-prompt-templates`. + +## Format + +```markdown +--- +description: Review staged git changes +--- +Review the staged changes (`git diff --cached`). Focus on: +- Bugs and logic errors +- Security issues +- Error handling gaps +``` + +- The filename becomes the command name. `review.md` becomes `/review`. +- `description` is optional. If missing, the first non-empty line is used. +- `argument-hint` is optional. When set, the hint is displayed before the description in the autocomplete dropdown. + +### Argument Hints + +Use `argument-hint` in frontmatter to show expected arguments in autocomplete. Use `` for required arguments and `[square brackets]` for optional ones: + +```markdown +--- +description: Review PRs from URLs with structured issue and code analysis +argument-hint: "" +--- +``` + +This renders in the autocomplete dropdown as: + +``` +→ pr — Review PRs from URLs with structured issue and code analysis + is — Analyze GitHub issues (bugs or feature requests) + wr [instructions] — Finish the current task end-to-end + cl — Audit changelog entries before release +``` + +## Usage + +Type `/` followed by the template name in the editor. Autocomplete shows available templates with descriptions. + +``` +/review # Expands review.md +/component Button # Expands with argument +/component Button "click handler" # Multiple arguments +``` + +## Arguments + +Templates support positional arguments, defaults, and simple slicing: + +- `$1`, `$2`, ... positional args +- `$@` or `$ARGUMENTS` for all args joined +- `${1:-default}` uses arg 1 when present/non-empty, otherwise `default` +- `${@:-default}` or `${ARGUMENTS:-default}` uses all arguments when present/non-empty, otherwise `default` +- `${@:N}` for args from the Nth position (1-indexed) +- `${@:N:L}` for `L` args starting at N + +Example: + +```markdown +--- +description: Create a component +--- +Create a React component named $1 with features: $@ +``` + +Default values are useful for optional arguments: + +```markdown +Summarize the current state in ${1:-7} bullet points. +``` + +Usage: `/component Button "onClick handler" "disabled support"` + +## Loading Rules + +- Template discovery in `prompts/` is non-recursive. +- If you want templates in subdirectories, add them explicitly via `prompts` settings or a package manifest. diff --git a/docs/providers.md b/docs/providers.md new file mode 100644 index 0000000..e70dc4d --- /dev/null +++ b/docs/providers.md @@ -0,0 +1,309 @@ +# Providers + +Pi supports subscription-based providers via OAuth and API key providers via environment variables or auth file. Built-in catalogs ship with pi; configured providers may refresh newer catalogs and cache them in `~/.pi/agent/models-store.json` for offline use. + +## Table of Contents + +- [Subscriptions](#subscriptions) +- [API Keys](#api-keys) +- [Auth File](#auth-file) +- [Cloud Providers](#cloud-providers) +- [llama.cpp](#llamacpp) +- [Custom Providers](#custom-providers) +- [Resolution Order](#resolution-order) + +## Subscriptions + +Use `/login` in interactive mode, then select a provider: + +- ChatGPT Plus/Pro (Codex) +- Claude Pro/Max +- GitHub Copilot +- xAI (Grok/X subscription) +- OpenRouter (OAuth-minted API key billed from OpenRouter credits) +- Radius + +Use `/logout` to clear credentials. Tokens are stored in `~/.pi/agent/auth.json` and auto-refresh when expired. OpenRouter instead mints a user-controlled API key that does not expire automatically. + +### OpenAI Codex + +- Requires ChatGPT Plus or Pro subscription +- Officially endorsed by OpenAI: [Codex for OSS](https://developers.openai.com/community/codex-for-oss) + +### Claude Pro/Max + +Anthropic subscription auth is active for Claude Pro/Max accounts. Third-party harness usage draws from [extra usage](https://claude.ai/settings/usage) and is billed per token, not against Claude plan limits. + +### GitHub Copilot + +- Press Enter for github.com, or enter your GitHub Enterprise Server domain +- If you get "model not supported", enable it in VS Code: Copilot Chat → model selector → select model → "Enable" + +### xAI (Grok/X subscription) + +- Run `/login xai`, then select **Use a subscription** +- `XAI_API_KEY` remains available through **Use an API key** + +### OpenRouter + +- Run `/login openrouter`, then select **Sign in with OpenRouter** to open the OpenRouter PKCE authorization flow +- The authorization creates a user-controlled OpenRouter API key billed from your OpenRouter credits +- On remote/headless machines (e.g. over SSH) the browser cannot reach the loopback callback; paste the final redirect URL (or the authorization code) into the login prompt instead +- `OPENROUTER_API_KEY` remains available through **Use an API key** + +### Radius + +Radius is a dynamic `pi-messages` gateway. `/login radius` stores OAuth tokens in `auth.json`; the gateway catalog is refreshed independently and cached in `models-store.json`. Custom Radius gateways can be declared in `models.json` with `"oauth": "radius"` and a gateway `baseUrl`. + +## API Keys + +### Environment Variables or Auth File + +Use `/login` in interactive mode and select a provider to store an API key in `auth.json`, or set credentials via environment variable: + +```bash +export ANTHROPIC_API_KEY=sk-ant-... +pi +``` + +| Provider | Environment Variable | `auth.json` key | +|----------|----------------------|------------------| +| Anthropic | `ANTHROPIC_API_KEY` | `anthropic` | +| Ant Ling | `ANT_LING_API_KEY` | `ant-ling` | +| Azure OpenAI Responses | `AZURE_OPENAI_API_KEY` | `azure-openai-responses` | +| OpenAI | `OPENAI_API_KEY` | `openai` | +| DeepSeek | `DEEPSEEK_API_KEY` | `deepseek` | +| NVIDIA NIM | `NVIDIA_API_KEY` | `nvidia` | +| Google Gemini | `GEMINI_API_KEY` | `google` | +| Amazon Bedrock | `AWS_BEARER_TOKEN_BEDROCK` | `amazon-bedrock` | +| Mistral | `MISTRAL_API_KEY` | `mistral` | +| Groq | `GROQ_API_KEY` | `groq` | +| Cerebras | `CEREBRAS_API_KEY` | `cerebras` | +| Cloudflare AI Gateway | `CLOUDFLARE_API_KEY` (+ `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_GATEWAY_ID`) | `cloudflare-ai-gateway` | +| Cloudflare Workers AI | `CLOUDFLARE_API_KEY` (+ `CLOUDFLARE_ACCOUNT_ID`) | `cloudflare-workers-ai` | +| xAI | `XAI_API_KEY` | `xai` | +| OpenRouter | `OPENROUTER_API_KEY` | `openrouter` | +| Vercel AI Gateway | `AI_GATEWAY_API_KEY` | `vercel-ai-gateway` | +| ZAI Coding Plan (Global) | `ZAI_API_KEY` | `zai` | +| ZAI Coding Plan (China) | `ZAI_CODING_CN_API_KEY` | `zai-coding-cn` | +| OpenCode Zen | `OPENCODE_API_KEY` | `opencode` | +| OpenCode Go | `OPENCODE_API_KEY` | `opencode-go` | +| Radius | `RADIUS_API_KEY` | `radius` | +| Hugging Face | `HF_TOKEN` | `huggingface` | +| Fireworks | `FIREWORKS_API_KEY` | `fireworks` | +| Together AI | `TOGETHER_API_KEY` | `together` | +| Kimi For Coding | `KIMI_API_KEY` | `kimi-coding` | +| MiniMax | `MINIMAX_API_KEY` | `minimax` | +| MiniMax (China) | `MINIMAX_CN_API_KEY` | `minimax-cn` | +| Qwen Token Plan | `QWEN_TOKEN_PLAN_API_KEY` | `qwen-token-plan` | +| Qwen Token Plan (China) | `QWEN_TOKEN_PLAN_CN_API_KEY` | `qwen-token-plan-cn` | +| Xiaomi MiMo | `XIAOMI_API_KEY` | `xiaomi` | +| Xiaomi MiMo Token Plan (China) | `XIAOMI_TOKEN_PLAN_CN_API_KEY` | `xiaomi-token-plan-cn` | +| Xiaomi MiMo Token Plan (Amsterdam) | `XIAOMI_TOKEN_PLAN_AMS_API_KEY` | `xiaomi-token-plan-ams` | +| Xiaomi MiMo Token Plan (Singapore) | `XIAOMI_TOKEN_PLAN_SGP_API_KEY` | `xiaomi-token-plan-sgp` | + +Reference for environment variables and `auth.json` keys: [`const envMap`](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/env-api-keys.ts) in [`packages/ai/src/env-api-keys.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/env-api-keys.ts). + +#### Auth File + +Store credentials in `~/.pi/agent/auth.json`: + +```json +{ + "anthropic": { "type": "api_key", "key": "sk-ant-..." }, + "ant-ling": { "type": "api_key", "key": "..." }, + "openai": { "type": "api_key", "key": "sk-..." }, + "deepseek": { "type": "api_key", "key": "sk-..." }, + "nvidia": { "type": "api_key", "key": "nvapi-..." }, + "google": { "type": "api_key", "key": "..." }, + "opencode": { "type": "api_key", "key": "..." }, + "opencode-go": { "type": "api_key", "key": "..." }, + "together": { "type": "api_key", "key": "..." }, + "qwen-token-plan": { "type": "api_key", "key": "sk-sp-..." }, + "qwen-token-plan-cn": { "type": "api_key", "key": "sk-sp-..." }, + "xiaomi": { "type": "api_key", "key": "..." }, + "xiaomi-token-plan-cn": { "type": "api_key", "key": "..." }, + "xiaomi-token-plan-ams": { "type": "api_key", "key": "..." }, + "xiaomi-token-plan-sgp": { "type": "api_key", "key": "..." } +} +``` + +The file is created with `0600` permissions (user read/write only). Auth file credentials take priority over environment variables. + +API key credentials can also include provider-scoped environment values. These values are used before process environment variables when resolving the credential key, provider/model headers, and provider configuration such as Cloudflare account IDs, Azure OpenAI settings, Vertex project/location, Bedrock settings, `PI_CACHE_RETENTION`, and `HTTP_PROXY`/`HTTPS_PROXY`. + +```json +{ + "cloudflare-ai-gateway": { + "type": "api_key", + "key": "$CLOUDFLARE_API_KEY", + "env": { + "CLOUDFLARE_API_KEY": "...", + "CLOUDFLARE_ACCOUNT_ID": "account-id", + "CLOUDFLARE_GATEWAY_ID": "gateway-id" + } + } +} +``` + +Use this when pi should use different provider settings than the project shell environment. + +### Key Resolution + +The `key` field supports command execution, environment interpolation, and literals: + +- **Shell command:** `"!command"` at the start executes the whole value as a command and uses stdout (cached for process lifetime) + ```json + { "type": "api_key", "key": "!security find-generic-password -ws 'anthropic'" } + { "type": "api_key", "key": "!op read 'op://vault/item/credential'" } + ``` +- **Environment interpolation:** `"$ENV_VAR"` or `"${ENV_VAR}"` uses the value of the named variable. Interpolation works inside larger literals. + ```json + { "type": "api_key", "key": "$MY_ANTHROPIC_KEY" } + { "type": "api_key", "key": "${KEY_PREFIX}_${KEY_SUFFIX}" } + ``` + `$FOO_BAR` is the variable `FOO_BAR`; use `${FOO}_BAR` when `BAR` is literal text. Missing environment variables make the value unresolved. +- **Escapes:** `"$$"` emits a literal `"$"`; `"$!"` emits a literal `"!"` without triggering command execution. + ```json + { "type": "api_key", "key": "$$literal-dollar-prefix" } + { "type": "api_key", "key": "$!literal-bang-prefix" } + ``` +- **Literal value:** Used directly. Plain uppercase strings such as `MY_API_KEY` are literals; use `$MY_API_KEY` for environment variables. + ```json + { "type": "api_key", "key": "sk-ant-..." } + { "type": "api_key", "key": "public" } + ``` + +OAuth credentials are also stored here after `/login` and managed automatically. + +## Cloud Providers + +### Azure OpenAI + +```bash +export AZURE_OPENAI_API_KEY=... +export AZURE_OPENAI_BASE_URL=https://your-resource.ai.azure.com +# also supported: https://your-resource.cognitiveservices.azure.com +# also supported: https://your-resource.openai.azure.com +# root endpoints are auto-normalized to /openai/v1 +# or use resource name instead of base URL +export AZURE_OPENAI_RESOURCE_NAME=your-resource + +# Optional +export AZURE_OPENAI_API_VERSION=2024-02-01 +export AZURE_OPENAI_DEPLOYMENT_NAME_MAP=gpt-4=my-gpt4,gpt-4o=my-gpt4o +``` + +### Amazon Bedrock + +Use `/login amazon-bedrock` to store a Bedrock API key, or configure one of the ambient AWS credential sources below: + +```bash +# Option 1: AWS Profile +export AWS_PROFILE=your-profile + +# Option 2: IAM Keys +export AWS_ACCESS_KEY_ID=AKIA... +export AWS_SECRET_ACCESS_KEY=... + +# Option 3: Bearer Token +export AWS_BEARER_TOKEN_BEDROCK=... + +# Optional region (defaults to us-east-1) +export AWS_REGION=us-west-2 +``` + +Also supports ECS task roles (`AWS_CONTAINER_CREDENTIALS_*`) and IRSA (`AWS_WEB_IDENTITY_TOKEN_FILE`). + +```bash +pi --provider amazon-bedrock --model us.anthropic.claude-sonnet-4-20250514-v1:0 +``` + +Prompt caching is enabled automatically for Claude models whose ID contains a recognizable model name (base models and system-defined inference profiles). For application inference profiles (whose ARNs don't contain the model name), set `AWS_BEDROCK_FORCE_CACHE=1` to enable cache points: + +```bash +export AWS_BEDROCK_FORCE_CACHE=1 +pi --provider amazon-bedrock --model arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123 +``` + +If you are connecting to a Bedrock API proxy, the following environment variables can be used: + +```bash +# Set the URL for the Bedrock proxy (standard AWS SDK env var) +export AWS_ENDPOINT_URL_BEDROCK_RUNTIME=https://my.corp.proxy/bedrock + +# Set if your proxy does not require authentication +export AWS_BEDROCK_SKIP_AUTH=1 + +# Set if your proxy only supports HTTP/1.1 +export AWS_BEDROCK_FORCE_HTTP1=1 +``` + +### Cloudflare AI Gateway + +`CLOUDFLARE_API_KEY` can be set via `/login`. The account ID and gateway slug can be set as environment variables or in the API key credential's `env` object in `auth.json`. + +```bash +export CLOUDFLARE_API_KEY=... # or use /login +export CLOUDFLARE_ACCOUNT_ID=... +export CLOUDFLARE_GATEWAY_ID=... # create at dash.cloudflare.com → AI → AI Gateway +pi --provider cloudflare-ai-gateway --model "claude-sonnet-4-5" +``` + +Routes to OpenAI, Anthropic, and Workers AI through Cloudflare AI Gateway. Workers AI uses the Unified API (`/compat`) and prefixed model IDs (`workers-ai/@cf/...`). OpenAI uses the OpenAI passthrough route (`/openai`) with native OpenAI model IDs such as `gpt-5.1`. Anthropic uses the Anthropic passthrough route (`/anthropic`) with native Anthropic model IDs such as `claude-sonnet-4-5`. + +AI Gateway authentication uses `CLOUDFLARE_API_KEY` as `cf-aig-authorization`. Upstream authentication can be one of: + +| Mode | Request auth | Upstream auth | +|------|--------------|---------------| +| Workers AI | Cloudflare token only | Cloudflare-native | +| Unified billing | Cloudflare token only | Cloudflare handles upstream auth and deducts credits | +| Stored BYOK | Cloudflare token only | Cloudflare injects provider keys stored in the AI Gateway dashboard | +| Inline BYOK | Cloudflare token plus upstream `Authorization` header | The request supplies the upstream provider key | + +For normal pi usage, prefer unified billing or stored BYOK. Inline BYOK requires configuring an additional upstream `Authorization` header for the Cloudflare AI Gateway provider, for example via a `models.json` provider/model override. + +### Cloudflare Workers AI + +`CLOUDFLARE_API_KEY` can be set via `/login`. `CLOUDFLARE_ACCOUNT_ID` can be set as an environment variable or in the API key credential's `env` object in `auth.json`. + +```bash +export CLOUDFLARE_API_KEY=... # or use /login +export CLOUDFLARE_ACCOUNT_ID=... +pi --provider cloudflare-workers-ai --model "@cf/moonshotai/kimi-k2.6" +``` + +Pi automatically sets `x-session-affinity` for [prefix caching](https://developers.cloudflare.com/workers-ai/features/prompt-caching/) discounts. + +### Google Vertex AI + +Uses Application Default Credentials: + +```bash +gcloud auth application-default login +export GOOGLE_CLOUD_PROJECT=your-project +export GOOGLE_CLOUD_LOCATION=us-central1 +``` + +Or set `GOOGLE_APPLICATION_CREDENTIALS` to a service account key file. + +## llama.cpp + +Pi supports the llama.cpp router server. Configure it with `/login llama.cpp`, manage loaded models with `/llama`, and select a loaded model with `/model`. + +See [llama.cpp](llama-cpp.md) for server setup, model directory layout, environment variables, and command usage. + +## Custom Providers + +**Via models.json:** Add Ollama, LM Studio, vLLM, or any provider that speaks a supported API (OpenAI Completions, OpenAI Responses, Anthropic Messages, Google Generative AI). See [models.md](models.md). + +**Via extensions:** For providers that need custom API implementations or OAuth flows, create an extension. See [custom-provider.md](custom-provider.md) and [examples/extensions/custom-provider-gitlab-duo](../examples/extensions/custom-provider-gitlab-duo/). + +## Resolution Order + +When resolving credentials for a provider: + +1. CLI `--api-key` flag +2. `auth.json` entry (API key or OAuth token) +3. Environment variable +4. Custom provider keys from `models.json` diff --git a/docs/quickstart.md b/docs/quickstart.md new file mode 100644 index 0000000..8931433 --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,165 @@ +# Quickstart + +This page gets you from install to a useful first pi session. + +## Install + +Pi is distributed as an npm package: + +```bash +npm install -g --ignore-scripts @earendil-works/pi-coding-agent +``` + +`--ignore-scripts` disables dependency lifecycle scripts during install. Pi does not require install scripts for normal npm installs. + +### Uninstall + +Use the package manager that installed pi. The curl installer uses npm globally, so curl and npm installs are removed with npm: + +```bash +# curl installer or npm install -g +npm uninstall -g @earendil-works/pi-coding-agent + +# pnpm +pnpm remove -g @earendil-works/pi-coding-agent + +# Yarn +yarn global remove @earendil-works/pi-coding-agent + +# Bun +bun uninstall -g @earendil-works/pi-coding-agent +``` + +Uninstalling pi leaves settings, credentials, sessions, and installed pi packages in `~/.pi/agent/`. + +Then start pi in the project directory you want it to work on: + +```bash +cd /path/to/project +pi +``` + +## Authenticate + +Pi can use subscription providers through `/login`, or API-key providers through environment variables or the auth file. + +### Option 1: subscription login + +Start pi and run: + +```text +/login +``` + +Then select a provider. Built-in subscription logins include Claude Pro/Max, ChatGPT Plus/Pro (Codex), and GitHub Copilot. + +### Option 2: API key + +Set an API key before launching pi: + +```bash +export ANTHROPIC_API_KEY=sk-ant-... +pi +``` + +You can also run `/login` and select an API-key provider to store the key in `~/.pi/agent/auth.json`. + +See [Providers](providers.md) for all supported providers, environment variables, and cloud-provider setup. + +## First session + +Once pi starts, type a request and press Enter: + +```text +Summarize this repository and tell me how to run its checks. +``` + +By default, pi gives the model four tools: + +- `read` - read files +- `write` - create or overwrite files +- `edit` - patch files +- `bash` - run shell commands + +Additional built-in read-only tools (`grep`, `find`, `ls`) are available through tool options. Pi runs in your current working directory and can modify files there. Use git or another checkpointing workflow if you want easy rollback. + +## Give pi project instructions + +Pi loads context files at startup. Add an `AGENTS.md` file to tell it how to work in a project: + +```markdown +# Project Instructions + +- Run `npm run check` after code changes. +- Do not run production migrations locally. +- Keep responses concise. +``` + +Pi loads: + +- `~/.pi/agent/AGENTS.md` for global instructions +- `AGENTS.md` or `CLAUDE.md` from parent directories and the current directory + +Restart pi, or run `/reload`, after changing context files. + +## Common things to try + +### Reference files + +Type `@` in the editor to fuzzy-search files, or pass files on the command line: + +```bash +pi @README.md "Summarize this" +pi @src/app.ts @src/app.test.ts "Review these together" +``` + +Images or text can be pasted with Ctrl+V (Alt+V on Windows); images can also be dragged into supported terminals. + +### Run shell commands + +In interactive mode: + +```text +!npm run lint +``` + +The command output is sent to the model. Use `!!command` to run a command without adding its output to the model context. + +### Switch models + +Use `/model` or Ctrl+L to choose a model. Use Shift+Tab to cycle thinking level. Use Ctrl+P / Shift+Ctrl+P to cycle through scoped models. + +### Continue later + +Sessions are saved automatically: + +```bash +pi -c # Continue most recent session +pi -r # Browse previous sessions +pi --name "my task" # Set session display name at startup +pi --session # Open a specific session +``` + +Inside pi, use `/resume`, `/new`, `/tree`, `/fork`, and `/clone` to manage sessions. + +### Non-interactive mode + +For one-shot prompts: + +```bash +pi -p "Summarize this codebase" +cat README.md | pi -p "Summarize this text" +pi -p @screenshot.png "What's in this image?" +``` + +Use `--mode json` for JSON event output or `--mode rpc` for process integration. + +## Next steps + +- [Using Pi](usage.md) - interactive mode, slash commands, sessions, context files, and CLI reference. +- [Providers](providers.md) - authentication and model setup. +- [Settings](settings.md) - global and project configuration. +- [Keybindings](keybindings.md) - shortcuts and customization. +- [Pi Packages](packages.md) - install shared extensions, skills, prompts, and themes. + +Platform notes: [Windows](windows.md), [Termux](termux.md), [tmux](tmux.md), [Terminal setup](terminal-setup.md), [Shell aliases](shell-aliases.md). diff --git a/docs/rpc.md b/docs/rpc.md new file mode 100644 index 0000000..12f5b02 --- /dev/null +++ b/docs/rpc.md @@ -0,0 +1,1576 @@ +# RPC Mode + +RPC mode enables headless operation of the coding agent via a JSON protocol over stdin/stdout. This is useful for embedding the agent in other applications, IDEs, or custom UIs. + +**Note for Node.js/TypeScript users**: If you're building a Node.js application, consider using `AgentSession` directly from `@earendil-works/pi-coding-agent` instead of spawning a subprocess. See [`src/core/agent-session.ts`](../src/core/agent-session.ts) for the API. For a subprocess-based TypeScript client, see [`src/modes/rpc/rpc-client.ts`](../src/modes/rpc/rpc-client.ts). + +## Starting RPC Mode + +```bash +pi --mode rpc [options] +``` + +Common options: +- `--provider `: Set the LLM provider (anthropic, openai, google, etc.) +- `--model `: Model pattern or ID (supports `provider/id` and optional `:`) +- `--name ` / `-n `: Set the session display name at startup +- `--no-session`: Disable session persistence +- `--session-dir `: Custom session storage directory + +## Protocol Overview + +- **Commands**: JSON objects sent to stdin, one per line +- **Responses**: JSON objects with `type: "response"` indicating command success/failure +- **Events**: Agent events streamed to stdout as JSON lines + +All commands support an optional `id` field for request/response correlation. If provided, the corresponding response will include the same `id`. `bash_execution_update` events also include the `id` of their originating `bash` command. + +### Framing + +RPC mode uses strict JSONL semantics with LF (`\n`) as the only record delimiter. + +This matters for clients: +- Split records on `\n` only +- Accept optional `\r\n` input by stripping a trailing `\r` +- Do not use generic line readers that treat Unicode separators as newlines + +In particular, Node `readline` is not protocol-compliant for RPC mode because it also splits on `U+2028` and `U+2029`, which are valid inside JSON strings. + +## Commands + +### Prompting + +#### prompt + +Send a user prompt to the agent. The command response is emitted after the prompt is accepted, queued, or handled. Events continue streaming asynchronously after acceptance. + +```json +{"id": "req-1", "type": "prompt", "message": "Hello, world!"} +``` + +With images: +```json +{"type": "prompt", "message": "What's in this image?", "images": [{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}]} +``` + +**During streaming**: If the agent is already streaming, you must specify `streamingBehavior` to queue the message: + +```json +{"type": "prompt", "message": "New instruction", "streamingBehavior": "steer"} +``` + +- `"steer"`: Queue the message while the agent is running. It is delivered after the current assistant turn finishes executing its tool calls, before the next LLM call. +- `"followUp"`: Wait until the agent finishes. Message is delivered only when agent stops. + +If the agent is streaming and no `streamingBehavior` is specified, the command returns an error. + +**Extension commands**: If the message is an extension command (e.g., `/mycommand`), it executes immediately even during streaming. Extension commands manage their own LLM interaction via `pi.sendMessage()`. + +**Input expansion**: Skill commands (`/skill:name`) and prompt templates (`/template`) are expanded before sending/queueing. + +Response: +```json +{"id": "req-1", "type": "response", "command": "prompt", "success": true} +``` + +`success: true` means the prompt was accepted, queued, or handled immediately. `success: false` means the prompt was rejected before acceptance. Failures after acceptance are reported through the normal event and message stream, not as a second `response` for the same request id. + +The `images` field is optional. Each image uses `ImageContent` format: `{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}`. + +#### steer + +Queue a steering message while the agent is running. It is delivered after the current assistant turn finishes executing its tool calls, before the next LLM call. Skill commands and prompt templates are expanded. Extension commands are not allowed (use `prompt` instead). + +```json +{"type": "steer", "message": "Stop and do this instead"} +``` + +With images: +```json +{"type": "steer", "message": "Look at this instead", "images": [{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}]} +``` + +The `images` field is optional. Each image uses `ImageContent` format (same as `prompt`). + +Response: +```json +{"type": "response", "command": "steer", "success": true} +``` + +See [set_steering_mode](#set_steering_mode) for controlling how steering messages are processed. + +#### follow_up + +Queue a follow-up message to be processed after the agent finishes. Delivered only when agent has no more tool calls or steering messages. Skill commands and prompt templates are expanded. Extension commands are not allowed (use `prompt` instead). + +```json +{"type": "follow_up", "message": "After you're done, also do this"} +``` + +With images: +```json +{"type": "follow_up", "message": "Also check this image", "images": [{"type": "image", "data": "base64-encoded-data", "mimeType": "image/png"}]} +``` + +The `images` field is optional. Each image uses `ImageContent` format (same as `prompt`). + +Response: +```json +{"type": "response", "command": "follow_up", "success": true} +``` + +See [set_follow_up_mode](#set_follow_up_mode) for controlling how follow-up messages are processed. + +#### abort + +Abort the current agent operation. + +```json +{"type": "abort"} +``` + +Response: +```json +{"type": "response", "command": "abort", "success": true} +``` + +#### new_session + +Start a fresh session. Can be cancelled by a `session_before_switch` extension event handler. + +```json +{"type": "new_session"} +``` + +With optional parent session tracking: +```json +{"type": "new_session", "parentSession": "/path/to/parent-session.jsonl"} +``` + +Response: +```json +{"type": "response", "command": "new_session", "success": true, "data": {"cancelled": false}} +``` + +If an extension cancelled: +```json +{"type": "response", "command": "new_session", "success": true, "data": {"cancelled": true}} +``` + +### State + +#### get_state + +Get current session state. + +```json +{"type": "get_state"} +``` + +Response: +```json +{ + "type": "response", + "command": "get_state", + "success": true, + "data": { + "model": {...}, + "thinkingLevel": "medium", + "isStreaming": false, + "isCompacting": false, + "steeringMode": "all", + "followUpMode": "one-at-a-time", + "sessionFile": "/path/to/session.jsonl", + "sessionId": "abc123", + "sessionName": "my-feature-work", + "autoCompactionEnabled": true, + "messageCount": 5, + "pendingMessageCount": 0 + } +} +``` + +The `model` field is a full [Model](#model) object or `null`. The `sessionName` field is the display name set via `set_session_name`, or omitted if not set. + +#### get_messages + +Get all messages in the conversation. + +```json +{"type": "get_messages"} +``` + +Response: +```json +{ + "type": "response", + "command": "get_messages", + "success": true, + "data": {"messages": [...]} +} +``` + +Messages are `AgentMessage` objects (see [Message Types](#message-types)). + +### Model + +#### set_model + +Switch to a specific model. + +```json +{"type": "set_model", "provider": "anthropic", "modelId": "claude-sonnet-4-20250514"} +``` + +Response contains the full [Model](#model) object: +```json +{ + "type": "response", + "command": "set_model", + "success": true, + "data": {...} +} +``` + +#### cycle_model + +Cycle to the next available model. Returns `null` data if only one model available. + +```json +{"type": "cycle_model"} +``` + +Response: +```json +{ + "type": "response", + "command": "cycle_model", + "success": true, + "data": { + "model": {...}, + "thinkingLevel": "medium", + "isScoped": false + } +} +``` + +The `model` field is a full [Model](#model) object. + +#### get_available_models + +List all configured models. + +```json +{"type": "get_available_models"} +``` + +Response contains an array of full [Model](#model) objects: +```json +{ + "type": "response", + "command": "get_available_models", + "success": true, + "data": { + "models": [...] + } +} +``` + +### Thinking + +#### set_thinking_level + +Set the reasoning/thinking level for models that support it. + +```json +{"type": "set_thinking_level", "level": "high"} +``` + +Levels: `"off"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"`, `"max"` + +`"xhigh"` and `"max"` are exposed only when supported by the selected model. Some models, including GPT-5.6, expose both. + +Response: +```json +{"type": "response", "command": "set_thinking_level", "success": true} +``` + +#### cycle_thinking_level + +Cycle through available thinking levels. Returns `null` data if model doesn't support thinking. + +```json +{"type": "cycle_thinking_level"} +``` + +Response: +```json +{ + "type": "response", + "command": "cycle_thinking_level", + "success": true, + "data": {"level": "high"} +} +``` + +#### get_available_thinking_levels + +List the thinking levels supported by the current model. Returns `["off"]` for a model without reasoning support. + +```json +{"type": "get_available_thinking_levels"} +``` + +Response: +```json +{ + "type": "response", + "command": "get_available_thinking_levels", + "success": true, + "data": { + "levels": ["off", "minimal", "low", "medium", "high"] + } +} +``` + +### Queue Modes + +#### set_steering_mode + +Control how steering messages (from `steer`) are delivered. + +```json +{"type": "set_steering_mode", "mode": "one-at-a-time"} +``` + +Modes: +- `"all"`: Deliver all steering messages after the current assistant turn finishes executing its tool calls +- `"one-at-a-time"`: Deliver one steering message per completed assistant turn (default) + +Response: +```json +{"type": "response", "command": "set_steering_mode", "success": true} +``` + +#### set_follow_up_mode + +Control how follow-up messages (from `follow_up`) are delivered. + +```json +{"type": "set_follow_up_mode", "mode": "one-at-a-time"} +``` + +Modes: +- `"all"`: Deliver all follow-up messages when agent finishes +- `"one-at-a-time"`: Deliver one follow-up message per agent completion (default) + +Response: +```json +{"type": "response", "command": "set_follow_up_mode", "success": true} +``` + +### Compaction + +#### compact + +Manually compact conversation context to reduce token usage. + +```json +{"type": "compact"} +``` + +With custom instructions: +```json +{"type": "compact", "customInstructions": "Focus on code changes"} +``` + +Response: +```json +{ + "type": "response", + "command": "compact", + "success": true, + "data": { + "summary": "Summary of conversation...", + "firstKeptEntryId": "abc123", + "tokensBefore": 150000, + "estimatedTokensAfter": 32000, + "usage": { + "input": 32000, + "output": 1200, + "cacheRead": 0, + "cacheWrite": 0, + "totalTokens": 33200, + "cost": {"input": 0.01, "output": 0.02, "cacheRead": 0, "cacheWrite": 0, "total": 0.03} + }, + "details": {} + } +} +``` + +`estimatedTokensAfter` is a heuristic estimate over the rebuilt message context immediately after compaction, not a provider-exact token count. `usage` reports the LLM call or calls that generated the summary and may be omitted by custom compaction handlers. + +#### set_auto_compaction + +Enable or disable automatic compaction when context is nearly full. + +```json +{"type": "set_auto_compaction", "enabled": true} +``` + +Response: +```json +{"type": "response", "command": "set_auto_compaction", "success": true} +``` + +### Retry + +#### set_auto_retry + +Enable or disable automatic retry on transient errors (overloaded, rate limit, 5xx). + +```json +{"type": "set_auto_retry", "enabled": true} +``` + +Response: +```json +{"type": "response", "command": "set_auto_retry", "success": true} +``` + +#### abort_retry + +Abort an in-progress retry (cancel the delay and stop retrying). + +```json +{"type": "abort_retry"} +``` + +Response: +```json +{"type": "response", "command": "abort_retry", "success": true} +``` + +### Bash + +#### bash + +Execute a shell command and add output to conversation context. Output streams as `bash_execution_update` events while the command runs; the response contains the final result. + +```json +{"id": "req-1", "type": "bash", "command": "ls -la"} +``` + +Include an `id` to associate streamed `bash_execution_update` events with this command. + +Response: +```json +{ + "id": "req-1", + "type": "response", + "command": "bash", + "success": true, + "data": { + "output": "total 48\ndrwxr-xr-x ...", + "exitCode": 0, + "cancelled": false, + "truncated": false + } +} +``` + +If output was truncated, includes `fullOutputPath`: +```json +{ + "type": "response", + "command": "bash", + "success": true, + "data": { + "output": "truncated output...", + "exitCode": 0, + "cancelled": false, + "truncated": true, + "fullOutputPath": "/tmp/pi-bash-abc123.log" + } +} +``` + +**How bash results reach the LLM:** + +The `bash` command executes immediately and returns a `BashResult`. Internally, a `BashExecutionMessage` is created and stored in the agent's message state. + +When the next `prompt` command is sent, all messages (including `BashExecutionMessage`) are transformed before being sent to the LLM. The `BashExecutionMessage` is converted to a `UserMessage` with this format: + +```` +Ran `ls -la` +``` +total 48 +drwxr-xr-x ... +``` +```` + +This means: +1. Bash output is included in the LLM context on the **next prompt**, not immediately +2. Multiple bash commands can be executed before a prompt; all outputs will be included + +#### abort_bash + +Abort a running bash command. + +```json +{"type": "abort_bash"} +``` + +Response: +```json +{"type": "response", "command": "abort_bash", "success": true} +``` + +### Session + +#### get_session_stats + +Get token usage, cost statistics, and current context window usage. + +```json +{"type": "get_session_stats"} +``` + +Response: +```json +{ + "type": "response", + "command": "get_session_stats", + "success": true, + "data": { + "sessionFile": "/path/to/session.jsonl", + "sessionId": "abc123", + "userMessages": 5, + "assistantMessages": 5, + "toolCalls": 12, + "toolResults": 12, + "totalMessages": 22, + "tokens": { + "input": 50000, + "output": 10000, + "cacheRead": 40000, + "cacheWrite": 5000, + "total": 105000 + }, + "cost": 0.45, + "contextUsage": { + "tokens": 60000, + "contextWindow": 200000, + "percent": 30 + } + } +} +``` + +`tokens` and `cost` include assistant messages, usage reported by tools, and compaction/branch-summary generation across the full session. `contextUsage` contains the actual current context-window estimate used for compaction and footer display. + +`contextUsage` is omitted when no model or context window is available. `contextUsage.tokens` and `contextUsage.percent` are `null` immediately after compaction until a fresh post-compaction assistant response provides valid usage data. + +#### export_html + +Export session to an HTML file. + +```json +{"type": "export_html"} +``` + +With custom path: +```json +{"type": "export_html", "outputPath": "/tmp/session.html"} +``` + +Response: +```json +{ + "type": "response", + "command": "export_html", + "success": true, + "data": {"path": "/tmp/session.html"} +} +``` + +#### switch_session + +Load a different session file. Can be cancelled by a `session_before_switch` extension event handler. + +```json +{"type": "switch_session", "sessionPath": "/path/to/session.jsonl"} +``` + +Response: +```json +{"type": "response", "command": "switch_session", "success": true, "data": {"cancelled": false}} +``` + +If an extension cancelled the switch: +```json +{"type": "response", "command": "switch_session", "success": true, "data": {"cancelled": true}} +``` + +#### fork + +Create a new fork from a previous user message on the active branch. Can be cancelled by a `session_before_fork` extension event handler. Returns the text of the message being forked from. + +```json +{"type": "fork", "entryId": "abc123"} +``` + +Response: +```json +{ + "type": "response", + "command": "fork", + "success": true, + "data": {"text": "The original prompt text...", "cancelled": false} +} +``` + +If an extension cancelled the fork: +```json +{ + "type": "response", + "command": "fork", + "success": true, + "data": {"text": "The original prompt text...", "cancelled": true} +} +``` + +#### clone + +Duplicate the current active branch into a new session at the current position. Can be cancelled by a `session_before_fork` extension event handler. + +```json +{"type": "clone"} +``` + +Response: +```json +{ + "type": "response", + "command": "clone", + "success": true, + "data": {"cancelled": false} +} +``` + +If an extension cancelled the clone: +```json +{ + "type": "response", + "command": "clone", + "success": true, + "data": {"cancelled": true} +} +``` + +#### get_fork_messages + +Get user messages available for forking. + +```json +{"type": "get_fork_messages"} +``` + +Response: +```json +{ + "type": "response", + "command": "get_fork_messages", + "success": true, + "data": { + "messages": [ + {"entryId": "abc123", "text": "First prompt..."}, + {"entryId": "def456", "text": "Second prompt..."} + ] + } +} +``` + +#### get_entries + +Get all session entries in append order (excluding the session header). The session is an append-only tree of entries with stable ids, so an entry id works as a durable cursor: pass the last entry id you have seen as `since` to get only entries strictly after it, even across client restarts. Unlike `get_messages`, this includes pre-compaction history and abandoned branches. + +```json +{"type": "get_entries"} +``` + +With a cursor: +```json +{"type": "get_entries", "since": "abc123"} +``` + +Response: +```json +{ + "type": "response", + "command": "get_entries", + "success": true, + "data": { + "entries": [ + {"type": "message", "id": "def456", "parentId": "abc123", "timestamp": "...", "message": {"role": "user", "...": "..."}} + ], + "leafId": "def456" + } +} +``` + +`leafId` is the id of the current leaf entry (`null` for an empty session), so a client can tell in one round trip whether the active branch moved. If `since` does not match any entry id, the response is `success: false`. + +#### get_tree + +Get the session as a tree of entries. Each node is `{entry, children, label?, labelTimestamp?}`. A well-formed session has a single root; orphaned entries (broken parent chain) also appear as roots. + +```json +{"type": "get_tree"} +``` + +Response: +```json +{ + "type": "response", + "command": "get_tree", + "success": true, + "data": { + "tree": [ + { + "entry": {"type": "message", "id": "abc123", "parentId": null, "...": "..."}, + "children": [ + {"entry": {"type": "message", "id": "def456", "parentId": "abc123", "...": "..."}, "children": []} + ] + } + ], + "leafId": "def456" + } +} +``` + +#### get_last_assistant_text + +Get the text content of the last assistant message. + +```json +{"type": "get_last_assistant_text"} +``` + +Response: +```json +{ + "type": "response", + "command": "get_last_assistant_text", + "success": true, + "data": {"text": "The assistant's response..."} +} +``` + +Returns `{"text": null}` if no assistant messages exist. + +#### set_session_name + +Set a display name for the current session. The name appears in session listings and helps identify sessions. + +```json +{"type": "set_session_name", "name": "my-feature-work"} +``` + +Response: +```json +{ + "type": "response", + "command": "set_session_name", + "success": true +} +``` + +The current session name is available via `get_state` in the `sessionName` field. To set the initial name when starting RPC mode, pass `--name ` or `-n ` to the `pi --mode rpc` process. + +### Commands + +#### get_commands + +Get available commands (extension commands, prompt templates, and skills). These can be invoked via the `prompt` command by prefixing with `/`. + +```json +{"type": "get_commands"} +``` + +Response: +```json +{ + "type": "response", + "command": "get_commands", + "success": true, + "data": { + "commands": [ + {"name": "session-name", "description": "Set or clear session name", "source": "extension", "path": "/home/user/.pi/agent/extensions/session.ts"}, + {"name": "fix-tests", "description": "Fix failing tests", "source": "prompt", "location": "project", "path": "/home/user/myproject/.pi/agent/prompts/fix-tests.md"}, + {"name": "skill:brave-search", "description": "Web search via Brave API", "source": "skill", "location": "user", "path": "/home/user/.pi/agent/skills/brave-search/SKILL.md"} + ] + } +} +``` + +Each command has: +- `name`: Command name (invoke with `/name`) +- `description`: Human-readable description (optional for extension commands) +- `source`: What kind of command: + - `"extension"`: Registered via `pi.registerCommand()` in an extension + - `"prompt"`: Loaded from a prompt template `.md` file + - `"skill"`: Loaded from a skill directory (name is prefixed with `skill:`) +- `location`: Where it was loaded from (optional, not present for extensions): + - `"user"`: User-level (`~/.pi/agent/`) + - `"project"`: Project-level (`./.pi/agent/`) + - `"path"`: Explicit path via CLI or settings +- `path`: Absolute file path to the command source (optional) + +**Note**: Built-in TUI commands (`/settings`, `/hotkeys`, etc.) are not included. They are handled only in interactive mode and would not execute if sent via `prompt`. + +## Events + +Events are streamed to stdout as JSON lines during agent operation. Events do not generally include an `id` field; `bash_execution_update` includes the `id` of its originating `bash` command when one was provided. + +### Event Types + +| Event | Description | +|-------|-------------| +| `agent_start` | Agent begins processing | +| `agent_end` | One low-level agent run completes (may still be followed by retry, compaction, or queued continuations) | +| `agent_settled` | Agent run is fully settled; no automatic retry, compaction retry, or queued continuation remains | +| `turn_start` | New turn begins | +| `turn_end` | Turn completes (includes assistant message and tool results) | +| `message_start` | Message begins | +| `message_update` | Streaming update (text/thinking/toolcall deltas) | +| `message_end` | Message completes | +| `bash_execution_update` | Direct RPC bash command output chunk | +| `tool_execution_start` | Tool begins execution | +| `tool_execution_update` | Tool execution progress (streaming output) | +| `tool_execution_end` | Tool completes | +| `queue_update` | Pending steering/follow-up queue changed | +| `compaction_start` | Compaction begins | +| `compaction_end` | Compaction completes | +| `auto_retry_start` | Auto-retry begins (after transient error) | +| `auto_retry_end` | Auto-retry completes (success or final failure) | +| `summarization_retry_scheduled` | Retry scheduled for a transient compaction or branch-summary summarization error | +| `summarization_retry_attempt_start` | Retried summarization request starts | +| `summarization_retry_finished` | Summarization retry loop completes | +| `extension_error` | Extension threw an error | + +### agent_start + +Emitted when the agent begins processing a prompt. + +```json +{"type": "agent_start"} +``` + +### agent_end + +Emitted when one low-level agent run completes. Contains all messages generated during this run. If `willRetry` is true, an automatic retry will follow. + +```json +{ + "type": "agent_end", + "messages": [...], + "willRetry": false +} +``` + +### agent_settled + +Emitted after the full session-level run settles. At this point Pi will not continue automatically through retry, compaction retry, or queued follow-up messages. + +```json +{"type": "agent_settled"} +``` + +### turn_start / turn_end + +A turn consists of one assistant response plus any resulting tool calls and results. + +```json +{"type": "turn_start"} +``` + +```json +{ + "type": "turn_end", + "message": {...}, + "toolResults": [...] +} +``` + +### message_start / message_end + +Emitted when a message begins and completes. The `message` field contains an `AgentMessage`. + +```json +{"type": "message_start", "message": {...}} +{"type": "message_end", "message": {...}} +``` + +### message_update (Streaming) + +Emitted during streaming of assistant messages. Contains both the partial message and a streaming delta event. + +```json +{ + "type": "message_update", + "message": {...}, + "assistantMessageEvent": { + "type": "text_delta", + "contentIndex": 0, + "delta": "Hello ", + "partial": {...} + } +} +``` + +The `assistantMessageEvent` field contains one of these delta types: + +| Type | Description | +|------|-------------| +| `start` | Message generation started | +| `text_start` | Text content block started | +| `text_delta` | Text content chunk | +| `text_end` | Text content block ended | +| `thinking_start` | Thinking block started | +| `thinking_delta` | Thinking content chunk | +| `thinking_end` | Thinking block ended | +| `toolcall_start` | Tool call started | +| `toolcall_delta` | Tool call arguments chunk | +| `toolcall_end` | Tool call ended (includes full `toolCall` object) | +| `done` | Message complete (reason: `"stop"`, `"length"`, `"toolUse"`) | +| `error` | Error occurred (reason: `"aborted"`, `"error"`) | + +Example streaming a text response: +```json +{"type":"message_update","message":{...},"assistantMessageEvent":{"type":"text_start","contentIndex":0,"partial":{...}}} +{"type":"message_update","message":{...},"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"Hello","partial":{...}}} +{"type":"message_update","message":{...},"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":" world","partial":{...}}} +{"type":"message_update","message":{...},"assistantMessageEvent":{"type":"text_end","contentIndex":0,"content":"Hello world","partial":{...}}} +``` + +### bash_execution_update + +Emitted once for each output chunk from a direct `bash` command. `id` matches the command's `id`, allowing clients to associate output with the correct command. + +Events stream all output while the command runs, even if the final `bash` response's `output` is truncated. + +```json +{ + "type": "bash_execution_update", + "id": "req-1", + "delta": "total 48\n" +} +``` + +### tool_execution_start / tool_execution_update / tool_execution_end + +Emitted when a tool begins, streams progress, and completes execution. + +```json +{ + "type": "tool_execution_start", + "toolCallId": "call_abc123", + "toolName": "bash", + "args": {"command": "ls -la"} +} +``` + +During execution, `tool_execution_update` events stream partial results (e.g., bash output as it arrives): + +```json +{ + "type": "tool_execution_update", + "toolCallId": "call_abc123", + "toolName": "bash", + "args": {"command": "ls -la"}, + "partialResult": { + "content": [{"type": "text", "text": "partial output so far..."}], + "details": {"truncation": null, "fullOutputPath": null} + } +} +``` + +When complete: + +```json +{ + "type": "tool_execution_end", + "toolCallId": "call_abc123", + "toolName": "bash", + "result": { + "content": [{"type": "text", "text": "total 48\n..."}], + "details": {...} + }, + "isError": false +} +``` + +Use `toolCallId` to correlate events. The `partialResult` in `tool_execution_update` contains the accumulated output so far (not just the delta), allowing clients to simply replace their display on each update. + +### queue_update + +Emitted whenever the pending steering or follow-up queue changes. + +```json +{ + "type": "queue_update", + "steering": ["Focus on error handling"], + "followUp": ["After that, summarize the result"] +} +``` + +### compaction_start / compaction_end + +Emitted when compaction runs, whether manual or automatic. + +```json +{"type": "compaction_start", "reason": "threshold"} +``` + +The `reason` field is `"manual"`, `"threshold"`, or `"overflow"`. + +```json +{ + "type": "compaction_end", + "reason": "threshold", + "result": { + "summary": "Summary of conversation...", + "firstKeptEntryId": "abc123", + "tokensBefore": 150000, + "estimatedTokensAfter": 32000, + "usage": { + "input": 32000, + "output": 1200, + "cacheRead": 0, + "cacheWrite": 0, + "totalTokens": 33200, + "cost": {"input": 0.01, "output": 0.02, "cacheRead": 0, "cacheWrite": 0, "total": 0.03} + }, + "details": {} + }, + "aborted": false, + "willRetry": false +} +``` + +If `reason` was `"overflow"` and compaction succeeds, `willRetry` is `true` and the agent will automatically retry the prompt. + +If compaction was aborted, `result` is `null` and `aborted` is `true`. + +If compaction failed (e.g., API quota exceeded), `result` is `null`, `aborted` is `false`, and `errorMessage` contains the error description. + +### auto_retry_start / auto_retry_end + +Emitted when automatic retry is triggered after a transient error (overloaded, rate limit, 5xx). + +```json +{ + "type": "auto_retry_start", + "attempt": 1, + "maxAttempts": 3, + "delayMs": 2000, + "errorMessage": "529 {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}" +} +``` + +```json +{ + "type": "auto_retry_end", + "success": true, + "attempt": 2 +} +``` + +On final failure (max retries exceeded): +```json +{ + "type": "auto_retry_end", + "success": false, + "attempt": 3, + "finalError": "529 overloaded_error: Overloaded" +} +``` + +### summarization_retry_scheduled / summarization_retry_attempt_start / summarization_retry_finished + +Emitted when compaction or branch-summary summarization retries after a transient provider error. These events use the same retry settings as automatic assistant-turn retries. + +```json +{ + "type": "summarization_retry_scheduled", + "attempt": 1, + "maxAttempts": 3, + "delayMs": 2000, + "errorMessage": "terminated" +} +``` + +```json +{ + "type": "summarization_retry_attempt_start", + "source": "compaction", + "reason": "threshold" +} +``` + +For branch summaries, `source` is `"branchSummary"` and no `reason` is present. + +```json +{ + "type": "summarization_retry_finished" +} +``` + +### extension_error + +Emitted when an extension throws an error. + +```json +{ + "type": "extension_error", + "extensionPath": "/path/to/extension.ts", + "event": "tool_call", + "error": "Error message..." +} +``` + +## Extension UI Protocol + +Extensions can request user interaction via `ctx.ui.select()`, `ctx.ui.confirm()`, etc. In RPC mode, these are translated into a request/response sub-protocol on top of the base command/event flow. + +There are two categories of extension UI methods: + +- **Dialog methods** (`select`, `confirm`, `input`, `editor`): emit an `extension_ui_request` on stdout and block until the client sends back an `extension_ui_response` on stdin with the matching `id`. +- **Fire-and-forget methods** (`notify`, `setStatus`, `setWidget`, `setTitle`, `set_editor_text`): emit an `extension_ui_request` on stdout but do not expect a response. The client can display the information or ignore it. + +If a dialog method includes a `timeout` field, the agent-side will auto-resolve with a default value when the timeout expires. The client does not need to track timeouts. + +Some `ExtensionUIContext` methods are not supported or degraded in RPC mode because they require direct TUI access: +- `custom()` returns `undefined` +- `setWorkingMessage()`, `setWorkingIndicator()`, `setFooter()`, `setHeader()`, `setEditorComponent()`, `setToolsExpanded()` are no-ops +- `getEditorText()` returns `""` +- `getToolsExpanded()` returns `false` +- `pasteToEditor()` delegates to `setEditorText()` (no paste/collapse handling) +- `getAllThemes()` returns `[]` +- `getTheme()` returns `undefined` +- `setTheme()` returns `{ success: false, error: "..." }` + +Note: `ctx.mode` is `"rpc"` and `ctx.hasUI` is `true` in RPC mode because the dialog and fire-and-forget methods are functional via the extension UI sub-protocol. Use `ctx.mode === "tui"` to guard TUI-specific features like `custom()` that require a real terminal. + +### Extension UI Requests (stdout) + +All requests have `type: "extension_ui_request"`, a unique `id`, and a `method` field. + +#### select + +Prompt the user to choose from a list. Dialog methods with a `timeout` field include the timeout in milliseconds; the agent auto-resolves with `undefined` if the client doesn't respond in time. + +```json +{ + "type": "extension_ui_request", + "id": "uuid-1", + "method": "select", + "title": "Allow dangerous command?", + "options": ["Allow", "Block"], + "timeout": 10000 +} +``` + +Expected response: `extension_ui_response` with `value` (the selected option string) or `cancelled: true`. + +#### confirm + +Prompt the user for yes/no confirmation. + +```json +{ + "type": "extension_ui_request", + "id": "uuid-2", + "method": "confirm", + "title": "Clear session?", + "message": "All messages will be lost.", + "timeout": 5000 +} +``` + +Expected response: `extension_ui_response` with `confirmed: true/false` or `cancelled: true`. + +#### input + +Prompt the user for free-form text. + +```json +{ + "type": "extension_ui_request", + "id": "uuid-3", + "method": "input", + "title": "Enter a value", + "placeholder": "type something..." +} +``` + +Expected response: `extension_ui_response` with `value` (the entered text) or `cancelled: true`. + +#### editor + +Open a multi-line text editor with optional prefilled content. + +```json +{ + "type": "extension_ui_request", + "id": "uuid-4", + "method": "editor", + "title": "Edit some text", + "prefill": "Line 1\nLine 2\nLine 3" +} +``` + +Expected response: `extension_ui_response` with `value` (the edited text) or `cancelled: true`. + +#### notify + +Display a notification. Fire-and-forget, no response expected. + +```json +{ + "type": "extension_ui_request", + "id": "uuid-5", + "method": "notify", + "message": "Command blocked by user", + "notifyType": "warning" +} +``` + +The `notifyType` field is `"info"`, `"warning"`, or `"error"`. Defaults to `"info"` if omitted. + +#### setStatus + +Set or clear a status entry in the footer/status bar. Fire-and-forget. + +```json +{ + "type": "extension_ui_request", + "id": "uuid-6", + "method": "setStatus", + "statusKey": "my-ext", + "statusText": "Turn 3 running..." +} +``` + +Send `statusText: undefined` (or omit it) to clear the status entry for that key. + +#### setWidget + +Set or clear a widget (block of text lines) displayed above or below the editor. Fire-and-forget. + +```json +{ + "type": "extension_ui_request", + "id": "uuid-7", + "method": "setWidget", + "widgetKey": "my-ext", + "widgetLines": ["--- My Widget ---", "Line 1", "Line 2"], + "widgetPlacement": "aboveEditor" +} +``` + +Send `widgetLines: undefined` (or omit it) to clear the widget. The `widgetPlacement` field is `"aboveEditor"` (default) or `"belowEditor"`. Only string arrays are supported in RPC mode; component factories are ignored. + +#### setTitle + +Set the terminal window/tab title. Fire-and-forget. + +```json +{ + "type": "extension_ui_request", + "id": "uuid-8", + "method": "setTitle", + "title": "pi - my project" +} +``` + +#### set_editor_text + +Set the text in the input editor. Fire-and-forget. + +```json +{ + "type": "extension_ui_request", + "id": "uuid-9", + "method": "set_editor_text", + "text": "prefilled text for the user" +} +``` + +### Extension UI Responses (stdin) + +Responses are sent for dialog methods only (`select`, `confirm`, `input`, `editor`). The `id` must match the request. + +#### Value response (select, input, editor) + +```json +{"type": "extension_ui_response", "id": "uuid-1", "value": "Allow"} +``` + +#### Confirmation response (confirm) + +```json +{"type": "extension_ui_response", "id": "uuid-2", "confirmed": true} +``` + +#### Cancellation response (any dialog) + +Dismiss any dialog method. The extension receives `undefined` (for select/input/editor) or `false` (for confirm). + +```json +{"type": "extension_ui_response", "id": "uuid-3", "cancelled": true} +``` + +## Error Handling + +Failed commands return a response with `success: false`: + +```json +{ + "type": "response", + "command": "set_model", + "success": false, + "error": "Model not found: invalid/model" +} +``` + +Parse errors: + +```json +{ + "type": "response", + "command": "parse", + "success": false, + "error": "Failed to parse command: Unexpected token..." +} +``` + +## Types + +Source files: +- [`packages/ai/src/types.ts`](../../ai/src/types.ts) - `Model`, `UserMessage`, `AssistantMessage`, `ToolResultMessage` +- [`packages/agent/src/types.ts`](../../agent/src/types.ts) - `AgentMessage`, `AgentEvent` +- [`src/core/messages.ts`](../src/core/messages.ts) - `BashExecutionMessage` +- [`src/modes/rpc/rpc-types.ts`](../src/modes/rpc/rpc-types.ts) - RPC command/response types, extension UI request/response types + +### Model + +```json +{ + "id": "claude-sonnet-4-20250514", + "name": "Claude Sonnet 4", + "api": "anthropic-messages", + "provider": "anthropic", + "baseUrl": "https://api.anthropic.com", + "reasoning": true, + "input": ["text", "image"], + "contextWindow": 200000, + "maxTokens": 16384, + "cost": { + "input": 3.0, + "output": 15.0, + "cacheRead": 0.3, + "cacheWrite": 3.75 + } +} +``` + +### UserMessage + +```json +{ + "role": "user", + "content": "Hello!", + "timestamp": 1733234567890, + "attachments": [] +} +``` + +The `content` field can be a string or an array of `TextContent`/`ImageContent` blocks. + +### AssistantMessage + +```json +{ + "role": "assistant", + "content": [ + {"type": "text", "text": "Hello! How can I help?"}, + {"type": "thinking", "thinking": "User is greeting me..."}, + {"type": "toolCall", "id": "call_123", "name": "bash", "arguments": {"command": "ls"}} + ], + "api": "anthropic-messages", + "provider": "anthropic", + "model": "claude-sonnet-4-20250514", + "usage": { + "input": 100, + "output": 50, + "cacheRead": 0, + "cacheWrite": 0, + "cost": {"input": 0.0003, "output": 0.00075, "cacheRead": 0, "cacheWrite": 0, "total": 0.00105} + }, + "stopReason": "stop", + "timestamp": 1733234567890 +} +``` + +Stop reasons: `"stop"`, `"length"`, `"toolUse"`, `"error"`, `"aborted"` + +### ToolResultMessage + +```json +{ + "role": "toolResult", + "toolCallId": "call_123", + "toolName": "bash", + "content": [{"type": "text", "text": "total 48\ndrwxr-xr-x ..."}], + "usage": { + "input": 100, + "output": 50, + "cacheRead": 0, + "cacheWrite": 0, + "totalTokens": 150, + "cost": {"input": 0.0003, "output": 0.00075, "cacheRead": 0, "cacheWrite": 0, "total": 0.00105} + }, + "isError": false, + "timestamp": 1733234567890 +} +``` + +`usage` is optional and reports nested LLM work performed by the tool. When present, it contributes to session token and cost totals. + +### BashExecutionMessage + +Created by the `bash` RPC command (not by LLM tool calls): + +```json +{ + "role": "bashExecution", + "command": "ls -la", + "output": "total 48\ndrwxr-xr-x ...", + "exitCode": 0, + "cancelled": false, + "truncated": false, + "fullOutputPath": null, + "timestamp": 1733234567890 +} +``` + +### Attachment + +```json +{ + "id": "img1", + "type": "image", + "fileName": "photo.jpg", + "mimeType": "image/jpeg", + "size": 102400, + "content": "base64-encoded-data...", + "extractedText": null, + "preview": null +} +``` + +## Example: Basic Client (Python) + +```python +import subprocess +import json + +proc = subprocess.Popen( + ["pi", "--mode", "rpc", "--no-session"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True +) + +def send(cmd): + proc.stdin.write(json.dumps(cmd) + "\n") + proc.stdin.flush() + +def read_events(): + for line in proc.stdout: + yield json.loads(line) + +# Send prompt +send({"type": "prompt", "message": "Hello!"}) + +# Process events +for event in read_events(): + if event.get("type") == "message_update": + delta = event.get("assistantMessageEvent", {}) + if delta.get("type") == "text_delta": + print(delta["delta"], end="", flush=True) + + if event.get("type") == "agent_end": + print() + break +``` + +## Example: Interactive Client (Node.js) + +See [`test/rpc-example.ts`](../test/rpc-example.ts) for a complete interactive example, or [`src/modes/rpc/rpc-client.ts`](../src/modes/rpc/rpc-client.ts) for a typed client implementation. + +For a complete example of handling the extension UI protocol, see [`examples/rpc-extension-ui.ts`](../examples/rpc-extension-ui.ts) which pairs with the [`examples/extensions/rpc-demo.ts`](../examples/extensions/rpc-demo.ts) extension. + +```javascript +const { spawn } = require("child_process"); +const { StringDecoder } = require("string_decoder"); + +const agent = spawn("pi", ["--mode", "rpc", "--no-session"]); + +function attachJsonlReader(stream, onLine) { + const decoder = new StringDecoder("utf8"); + let buffer = ""; + + stream.on("data", (chunk) => { + buffer += typeof chunk === "string" ? chunk : decoder.write(chunk); + + while (true) { + const newlineIndex = buffer.indexOf("\n"); + if (newlineIndex === -1) break; + + let line = buffer.slice(0, newlineIndex); + buffer = buffer.slice(newlineIndex + 1); + if (line.endsWith("\r")) line = line.slice(0, -1); + onLine(line); + } + }); + + stream.on("end", () => { + buffer += decoder.end(); + if (buffer.length > 0) { + onLine(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer); + } + }); +} + +attachJsonlReader(agent.stdout, (line) => { + const event = JSON.parse(line); + + if (event.type === "message_update") { + const { assistantMessageEvent } = event; + if (assistantMessageEvent.type === "text_delta") { + process.stdout.write(assistantMessageEvent.delta); + } + } +}); + +// Send prompt +agent.stdin.write(JSON.stringify({ type: "prompt", message: "Hello" }) + "\n"); + +// Abort on Ctrl+C +process.on("SIGINT", () => { + agent.stdin.write(JSON.stringify({ type: "abort" }) + "\n"); +}); +``` diff --git a/docs/sdk.md b/docs/sdk.md new file mode 100644 index 0000000..1dc32a1 --- /dev/null +++ b/docs/sdk.md @@ -0,0 +1,1186 @@ +> pi can help you use the SDK. Ask it to build an integration for your use case. + +# SDK + +The SDK provides programmatic access to pi's agent capabilities. Use it to embed pi in other applications, build custom interfaces, or integrate with automated workflows. + +**Example use cases:** +- Build a custom UI (web, desktop, mobile) +- Integrate agent capabilities into existing applications +- Create automated pipelines with agent reasoning +- Build custom tools that spawn sub-agents +- Test agent behavior programmatically + +See [examples/sdk/](../examples/sdk/) for working examples from minimal to full control. + +## Quick Start + +```typescript +import { createAgentSession, ModelRuntime, SessionManager } from "@earendil-works/pi-coding-agent"; + +const modelRuntime = await ModelRuntime.create(); +const { session } = await createAgentSession({ + sessionManager: SessionManager.inMemory(), + modelRuntime, +}); + +session.subscribe((event) => { + if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { + process.stdout.write(event.assistantMessageEvent.delta); + } +}); + +await session.prompt("What files are in the current directory?"); +``` + +## Installation + +```bash +npm install @earendil-works/pi-coding-agent +``` + +The SDK is included in the main package. No separate installation needed. + +## Core Concepts + +### createAgentSession() + +The main factory function for a single `AgentSession`. + +`createAgentSession()` uses a `ResourceLoader` to supply extensions, skills, prompt templates, themes, and context files. If you do not provide one, it uses `DefaultResourceLoader` with standard discovery. + +```typescript +import { createAgentSession, SessionManager } from "@earendil-works/pi-coding-agent"; + +// Minimal: defaults with DefaultResourceLoader +const { session } = await createAgentSession(); + +// Custom: override specific options +const { session } = await createAgentSession({ + model: myModel, + tools: ["read", "bash"], + sessionManager: SessionManager.inMemory(), +}); +``` + +### AgentSession + +The session manages agent lifecycle, message history, model state, compaction, and event streaming. + +```typescript +interface AgentSession { + // Send a prompt and wait for completion + prompt(text: string, options?: PromptOptions): Promise; + + // Queue messages during streaming + steer(text: string): Promise; + followUp(text: string): Promise; + + // Subscribe to events (returns unsubscribe function) + subscribe(listener: (event: AgentSessionEvent) => void): () => void; + + // Session info + sessionFile: string | undefined; + sessionId: string; + + // Model control + setModel(model: Model): Promise; + setThinkingLevel(level: ThinkingLevel): void; + cycleModel(): Promise; + cycleThinkingLevel(): ThinkingLevel | undefined; + + // State access + agent: Agent; + model: Model | undefined; + thinkingLevel: ThinkingLevel; + messages: AgentMessage[]; + isStreaming: boolean; + + // In-place tree navigation within the current session file + navigateTree(targetId: string, options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string }): Promise<{ editorText?: string; cancelled: boolean }>; + + // Compaction + compact(customInstructions?: string): Promise; + abortCompaction(): void; + + // Abort current operation + abort(): Promise; + + // Cleanup + dispose(): void; +} +``` + +Session replacement APIs such as new-session, resume, fork, and import live on `AgentSessionRuntime`, not on `AgentSession`. + +### createAgentSessionRuntime() and AgentSessionRuntime + +Use the runtime API when you need to replace the active session and rebuild cwd-bound runtime state. +This is the same layer used by the built-in interactive, print, and RPC modes. + +`createAgentSessionRuntime()` takes a runtime factory plus the initial cwd/session target. The factory closes over process-global fixed inputs, recreates cwd-bound services for the effective cwd, resolves session options against those services, and returns a full runtime result. + +```typescript +import { + type CreateAgentSessionRuntimeFactory, + createAgentSessionFromServices, + createAgentSessionRuntime, + createAgentSessionServices, + getAgentDir, + SessionManager, +} from "@earendil-works/pi-coding-agent"; + +const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => { + const services = await createAgentSessionServices({ cwd }); + return { + ...(await createAgentSessionFromServices({ + services, + sessionManager, + sessionStartEvent, + })), + services, + diagnostics: services.diagnostics, + }; +}; + +const runtime = await createAgentSessionRuntime(createRuntime, { + cwd: process.cwd(), + agentDir: getAgentDir(), + sessionManager: SessionManager.create(process.cwd()), +}); +``` + +`AgentSessionRuntime` owns replacement of the active runtime across: + +- `newSession()` +- `switchSession()` +- `fork()` +- clone flows via `fork(entryId, { position: "at" })` +- `importFromJsonl()` + +Important behavior: + +- `runtime.session` changes after those operations +- event subscriptions are attached to a specific `AgentSession`, so re-subscribe after replacement +- if you use extensions, call `runtime.session.bindExtensions(...)` again for the new session +- creation returns diagnostics on `runtime.diagnostics` +- if runtime creation or replacement fails, the method throws and the caller decides how to handle it + +```typescript +let session = runtime.session; +let unsubscribe = session.subscribe(() => {}); + +await runtime.newSession(); + +unsubscribe(); +session = runtime.session; +unsubscribe = session.subscribe(() => {}); +``` + +### Prompting and Message Queueing + +`PromptOptions` controls prompt expansion, queueing behavior while streaming, and prompt preflight notifications: + +```typescript +interface PromptOptions { + expandPromptTemplates?: boolean; + images?: ImageContent[]; + streamingBehavior?: "steer" | "followUp"; + source?: InputSource; + preflightResult?: (success: boolean) => void; +} +``` + +`preflightResult` is called once per `prompt()` invocation: + +- `true` when the prompt was accepted, queued, or handled immediately +- `false` when prompt preflight rejected before acceptance + +It fires before `prompt()` resolves. `prompt()` still resolves only after the full accepted run finishes, including retries. Failures after acceptance are reported through the normal event and message stream, not through `preflightResult(false)`. + +The `prompt()` method handles prompt templates, extension commands, and message sending: + +```typescript +// Basic prompt (when not streaming) +await session.prompt("What files are here?"); + +// With images +await session.prompt("What's in this image?", { + images: [{ type: "image", source: { type: "base64", mediaType: "image/png", data: "..." } }] +}); + +// During streaming: must specify how to queue the message +await session.prompt("Stop and do this instead", { streamingBehavior: "steer" }); +await session.prompt("After you're done, also check X", { streamingBehavior: "followUp" }); +``` + +**Behavior:** +- **Extension commands** (e.g., `/mycommand`): Execute immediately, even during streaming. They manage their own LLM interaction via `pi.sendMessage()`. +- **File-based prompt templates** (from `.md` files): Expanded to their content before sending or queueing. +- **During streaming without `streamingBehavior`**: Throws an error. Use `steer()` or `followUp()` directly, or specify the option. +- **`preflightResult(true)`**: Means the prompt was accepted, queued, or handled immediately. +- **`preflightResult(false)`**: Means preflight rejected before acceptance. + +For explicit queueing during streaming: + +```typescript +// Queue a steering message for delivery after the current assistant turn finishes its tool calls +await session.steer("New instruction"); + +// Wait for agent to finish (delivered only when agent stops) +await session.followUp("After you're done, also do this"); +``` + +Both `steer()` and `followUp()` expand file-based prompt templates but error on extension commands (extension commands cannot be queued). + +### Agent and AgentState + +The `Agent` class (from `@earendil-works/pi-agent-core`) handles the core LLM interaction. Access it via `session.agent`. + +```typescript +// Access current state +const state = session.agent.state; + +// state.messages: AgentMessage[] - conversation history +// state.model: Model - current model +// state.thinkingLevel: ThinkingLevel - current thinking level +// state.systemPrompt: string - system prompt +// state.tools: AgentTool[] - available tools +// state.streamingMessage?: AgentMessage - current partial assistant message +// state.errorMessage?: string - latest assistant error + +// Replace messages (useful for branching or restoration) +session.agent.state.messages = messages; // copies the top-level array + +// Replace tools +session.agent.state.tools = tools; // copies the top-level array + +// Wait for agent to finish processing +await session.agent.waitForIdle(); +``` + +### Events + +Subscribe to events to receive streaming output and lifecycle notifications. + +```typescript +session.subscribe((event) => { + switch (event.type) { + // Streaming text from assistant + case "message_update": + if (event.assistantMessageEvent.type === "text_delta") { + process.stdout.write(event.assistantMessageEvent.delta); + } + if (event.assistantMessageEvent.type === "thinking_delta") { + // Thinking output (if thinking enabled) + } + break; + + // Tool execution + case "tool_execution_start": + console.log(`Tool: ${event.toolName}`); + break; + case "tool_execution_update": + // Streaming tool output + break; + case "tool_execution_end": + console.log(`Result: ${event.isError ? "error" : "success"}`); + break; + + // Message lifecycle + case "message_start": + // New message starting + break; + case "message_end": + // Message complete + break; + + // Agent lifecycle + case "agent_start": + // Agent started processing prompt + break; + case "agent_end": + // Agent finished (event.messages contains new messages) + break; + + // Turn lifecycle (one LLM response + tool calls) + case "turn_start": + break; + case "turn_end": + // event.message: assistant response + // event.toolResults: tool results from this turn + break; + + // Session events (queue, compaction, retry) + case "queue_update": + console.log(event.steering, event.followUp); + break; + case "compaction_start": + case "compaction_end": + case "auto_retry_start": + case "auto_retry_end": + case "summarization_retry_scheduled": + case "summarization_retry_attempt_start": + case "summarization_retry_finished": + break; + } +}); +``` + +## Options Reference + +### Directories + +```typescript +const { session } = await createAgentSession({ + // Working directory for DefaultResourceLoader discovery + cwd: process.cwd(), // default + + // Global config directory + agentDir: "~/.pi/agent", // default (expands ~) +}); +``` + +`cwd` is used by `DefaultResourceLoader` for: +- Project extensions (`.pi/extensions/`) +- Project skills: + - `.pi/skills/` + - `.agents/skills/` in `cwd` and ancestor directories (up to git repo root, or filesystem root when not in a repo) +- Project prompts (`.pi/prompts/`) +- Context files (`AGENTS.md` walking up from cwd) +- Session directory naming + +`agentDir` is used by `DefaultResourceLoader` for: +- Global extensions (`extensions/`) +- Global skills: + - `skills/` under `agentDir` (for example `~/.pi/agent/skills/`) + - `~/.agents/skills/` +- Global prompts (`prompts/`) +- Global context file (`AGENTS.md`) +- Settings (`settings.json`) +- Custom models (`models.json`) +- Credentials (`auth.json`) +- Sessions (`sessions/`) + +When you pass a custom `ResourceLoader`, `cwd` and `agentDir` no longer control resource discovery. They still influence session naming and tool path resolution. + +### Model + +```typescript +import { getModel } from "@earendil-works/pi-ai"; +import { ModelRuntime } from "@earendil-works/pi-coding-agent"; + +const modelRuntime = await ModelRuntime.create(); + +// Find specific built-in model (doesn't check if API key exists) +const opus = getModel("anthropic", "claude-opus-4-5"); +if (!opus) throw new Error("Model not found"); + +// Find any model by provider/id, including custom models from models.json +// (doesn't check if API key exists) +const customModel = modelRuntime.getModel("my-provider", "my-model"); + +// Get only models that have valid authentication configured +const available = await modelRuntime.getAvailable(); + +const { session } = await createAgentSession({ + model: opus, + thinkingLevel: "medium", // off, minimal, low, medium, high, xhigh, max + + // Models for cycling (Ctrl+P in interactive mode) + scopedModels: [ + { model: opus, thinkingLevel: "high" }, + { model: haiku, thinkingLevel: "off" }, + ], + + modelRuntime, +}); +``` + +If no model is provided: +1. Tries to restore from session (if continuing) +2. Uses default from settings +3. Falls back to first available model + +To match CLI model parsing, use the exported resolver helpers: + +```typescript +import { + resolveCliModel, + resolveModelScopeWithDiagnostics, +} from "@earendil-works/pi-coding-agent"; + +const cliModel = resolveCliModel({ + cliModel: "anthropic/claude-opus-4-5:high", + modelRuntime, +}); +if (cliModel.error) throw new Error(cliModel.error); +if (cliModel.warning) console.warn(cliModel.warning); + +const { scopedModels, diagnostics } = await resolveModelScopeWithDiagnostics( + ["anthropic/*:high", "gpt-5"], + modelRuntime, +); +for (const diagnostic of diagnostics) { + console.warn(diagnostic.message); +} +``` + +`resolveCliModel()` uses all registered models so `--api-key` style first-time setup can resolve a model before stored auth exists. `resolveModelScopeWithDiagnostics()` matches `--models` and `enabledModels` semantics while returning warnings instead of printing them. + +> See [examples/sdk/02-custom-model.ts](../examples/sdk/02-custom-model.ts) + +### API Keys and OAuth + +Authentication resolution priority (handled by `ModelRuntime`): +1. Runtime overrides (via `setRuntimeApiKey`, not persisted) +2. Stored credentials in `auth.json` (API keys or OAuth tokens) +3. Environment variables (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, etc.) +4. Fallback resolver (for custom provider keys from `models.json`) + +```typescript +import { InMemoryCredentialStore } from "@earendil-works/pi-ai"; +import { createAgentSession, ModelRuntime } from "@earendil-works/pi-coding-agent"; + +// Default: uses ~/.pi/agent/auth.json and ~/.pi/agent/models.json +const modelRuntime = await ModelRuntime.create(); + +// Provider-owned auth methods and current status +for (const provider of modelRuntime.getProviders()) { + const status = await modelRuntime.checkAuth(provider.id); + console.log(provider.name, provider.auth, status); +} + +// Runtime API key override (not persisted to disk) +modelRuntime.setRuntimeApiKey("anthropic", "sk-my-temp-key"); + +// Custom credential and model locations +const customRuntime = await ModelRuntime.create({ + authPath: "/my/app/auth.json", + modelsPath: "/my/app/models.json", +}); + +// Or inject any pi-ai CredentialStore +const credentials = new InMemoryCredentialStore(); +const inMemoryRuntime = await ModelRuntime.create({ credentials }); + +const { session } = await createAgentSession({ + modelRuntime: customRuntime, +}); +``` + +> See [examples/sdk/09-api-keys-and-oauth.ts](../examples/sdk/09-api-keys-and-oauth.ts) + +### System Prompt + +Use a `ResourceLoader` to override the system prompt: + +```typescript +import { createAgentSession, DefaultResourceLoader } from "@earendil-works/pi-coding-agent"; + +const loader = new DefaultResourceLoader({ + systemPromptOverride: () => "You are a helpful assistant.", +}); +await loader.reload(); + +const { session } = await createAgentSession({ resourceLoader: loader }); +``` + +> See [examples/sdk/03-custom-prompt.ts](../examples/sdk/03-custom-prompt.ts) + +### Tools + +Specify which built-in tools to enable: + +- Built-in tool names: `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls` +- Default built-ins: `read`, `bash`, `edit`, `write` +- `noTools: "all"` disables all tools +- `noTools: "builtin"` disables default built-ins while keeping extension and custom tools enabled +- `excludeTools` disables specific built-in, extension, or custom tool names after any `tools` allowlist is applied + +The `edit` tool returns `details.diff` for Pi's TUI display and `details.patch` as a standard unified patch for SDK consumers. + +```typescript +import { createAgentSession } from "@earendil-works/pi-coding-agent"; + +// Read-only mode +const { session } = await createAgentSession({ + tools: ["read", "grep", "find", "ls"], +}); + +// Pick specific tools +const { session } = await createAgentSession({ + tools: ["read", "bash", "grep"], +}); + +// Disable one tool while keeping the rest available +const { session } = await createAgentSession({ + excludeTools: ["ask_question"], +}); +``` + +#### Tools with Custom cwd + +When you pass a custom `cwd`, `createAgentSession()` builds selected built-in tools for that cwd. + +```typescript +import { createAgentSession, SessionManager } from "@earendil-works/pi-coding-agent"; + +const cwd = "/path/to/project"; + +// Use default tools for custom cwd +const { session } = await createAgentSession({ + cwd, + sessionManager: SessionManager.inMemory(cwd), +}); + +// Or pick specific tools for custom cwd +const { session } = await createAgentSession({ + cwd, + tools: ["read", "bash", "grep"], + sessionManager: SessionManager.inMemory(cwd), +}); +``` + +> See [examples/sdk/05-tools.ts](../examples/sdk/05-tools.ts) + +### Custom Tools + +```typescript +import { Type } from "typebox"; +import { createAgentSession, defineTool } from "@earendil-works/pi-coding-agent"; + +// Inline custom tool +const myTool = defineTool({ + name: "my_tool", + label: "My Tool", + description: "Does something useful", + parameters: Type.Object({ + input: Type.String({ description: "Input value" }), + }), + execute: async (_toolCallId, params) => ({ + content: [{ type: "text", text: `Result: ${params.input}` }], + details: {}, + }), +}); + +// Pass custom tools directly +const { session } = await createAgentSession({ + customTools: [myTool], +}); +``` + +Use `defineTool()` for standalone definitions and arrays like `customTools: [myTool]`. Inline `pi.registerTool({ ... })` already infers parameter types correctly. + +Custom tools passed via `customTools` are combined with extension-registered tools. Extensions loaded by the ResourceLoader can also register tools via `pi.registerTool()`. + +If you pass `tools`, include each custom or extension tool name you want enabled, for example `tools: ["read", "bash", "my_tool"]`. + +> See [examples/sdk/05-tools.ts](../examples/sdk/05-tools.ts) + +### Extensions + +Extensions are loaded by the `ResourceLoader`. `DefaultResourceLoader` discovers extensions from `~/.pi/agent/extensions/`, `.pi/extensions/`, and settings.json extension sources. + +```typescript +import { createAgentSession, DefaultResourceLoader } from "@earendil-works/pi-coding-agent"; + +const loader = new DefaultResourceLoader({ + additionalExtensionPaths: ["/path/to/my-extension.ts"], + extensionFactories: [ + (pi) => { + pi.on("agent_start", () => { + console.log("[Inline Extension] Agent starting"); + }); + }, + ], +}); +await loader.reload(); + +const { session } = await createAgentSession({ resourceLoader: loader }); +``` + +Extensions can register tools, subscribe to events, add commands, and more. See [extensions.md](extensions.md) for the full API. + +**Named inline extensions:** By default, inline factories display as ``, ``, etc. in the startup Extensions list. To show a descriptive name instead, wrap the factory: + +```typescript +import type { InlineExtension } from "@earendil-works/pi-coding-agent"; + +const myProvider: InlineExtension = { + name: "my-provider", + factory: (pi) => { + pi.on("agent_start", () => { + console.log("[my-provider] Agent starting"); + }); + }, +}; + +const loader = new DefaultResourceLoader({ + extensionFactories: [myProvider], +}); +``` + +This displays as `` instead of ``. Bare factory functions are still accepted for backward compatibility. + +**Event Bus:** Extensions can communicate via `pi.events`. Pass a shared `eventBus` to `DefaultResourceLoader` if you need to emit or listen from outside: + +```typescript +import { createEventBus, DefaultResourceLoader } from "@earendil-works/pi-coding-agent"; + +const eventBus = createEventBus(); +const loader = new DefaultResourceLoader({ + eventBus, +}); +await loader.reload(); + +eventBus.on("my-extension:status", (data) => console.log(data)); +``` + +> See [examples/sdk/06-extensions.ts](../examples/sdk/06-extensions.ts) and [docs/extensions.md](extensions.md) + +### Skills + +```typescript +import { + createAgentSession, + DefaultResourceLoader, + type Skill, +} from "@earendil-works/pi-coding-agent"; + +const customSkill: Skill = { + name: "my-skill", + description: "Custom instructions", + filePath: "/path/to/SKILL.md", + baseDir: "/path/to", + source: "custom", +}; + +const loader = new DefaultResourceLoader({ + skillsOverride: (current) => ({ + skills: [...current.skills, customSkill], + diagnostics: current.diagnostics, + }), +}); +await loader.reload(); + +const { session } = await createAgentSession({ resourceLoader: loader }); +``` + +> See [examples/sdk/04-skills.ts](../examples/sdk/04-skills.ts) + +### Context Files + +```typescript +import { createAgentSession, DefaultResourceLoader } from "@earendil-works/pi-coding-agent"; + +const loader = new DefaultResourceLoader({ + agentsFilesOverride: (current) => ({ + agentsFiles: [ + ...current.agentsFiles, + { path: "/virtual/AGENTS.md", content: "# Guidelines\n\n- Be concise" }, + ], + }), +}); +await loader.reload(); + +const { session } = await createAgentSession({ resourceLoader: loader }); +``` + +> See [examples/sdk/07-context-files.ts](../examples/sdk/07-context-files.ts) + +### Slash Commands + +```typescript +import { + createAgentSession, + DefaultResourceLoader, + type PromptTemplate, +} from "@earendil-works/pi-coding-agent"; + +const customCommand: PromptTemplate = { + name: "deploy", + description: "Deploy the application", + source: "(custom)", + content: "# Deploy\n\n1. Build\n2. Test\n3. Deploy", +}; + +const loader = new DefaultResourceLoader({ + promptsOverride: (current) => ({ + prompts: [...current.prompts, customCommand], + diagnostics: current.diagnostics, + }), +}); +await loader.reload(); + +const { session } = await createAgentSession({ resourceLoader: loader }); +``` + +> See [examples/sdk/08-prompt-templates.ts](../examples/sdk/08-prompt-templates.ts) + +### Session Management + +Sessions use a tree structure with `id`/`parentId` linking, enabling in-place branching. + +```typescript +import { + type CreateAgentSessionRuntimeFactory, + createAgentSession, + createAgentSessionFromServices, + createAgentSessionRuntime, + createAgentSessionServices, + getAgentDir, + SessionManager, +} from "@earendil-works/pi-coding-agent"; + +// In-memory (no persistence) +const { session } = await createAgentSession({ + sessionManager: SessionManager.inMemory(), +}); + +// New persistent session +const { session: persisted } = await createAgentSession({ + sessionManager: SessionManager.create(process.cwd()), +}); + +// Continue most recent +const { session: continued, modelFallbackMessage } = await createAgentSession({ + sessionManager: SessionManager.continueRecent(process.cwd()), +}); +if (modelFallbackMessage) { + console.log("Note:", modelFallbackMessage); +} + +// Open specific file +const { session: opened } = await createAgentSession({ + sessionManager: SessionManager.open("/path/to/session.jsonl"), +}); + +// List sessions +const currentProjectSessions = await SessionManager.list(process.cwd()); +const allSessions = await SessionManager.listAll(process.cwd()); + +// Session replacement API for /new, /resume, /fork, /clone, and import flows. +const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => { + const services = await createAgentSessionServices({ cwd }); + return { + ...(await createAgentSessionFromServices({ + services, + sessionManager, + sessionStartEvent, + })), + services, + diagnostics: services.diagnostics, + }; +}; + +const runtime = await createAgentSessionRuntime(createRuntime, { + cwd: process.cwd(), + agentDir: getAgentDir(), + sessionManager: SessionManager.create(process.cwd()), +}); + +// Replace the active session with a fresh one +await runtime.newSession(); + +// Replace the active session with another saved session +await runtime.switchSession("/path/to/session.jsonl"); + +// Replace the active session with a fork from a specific user entry +await runtime.fork("entry-id"); + +// Clone the active path through a specific entry +await runtime.fork("entry-id", { position: "at" }); +``` + +**SessionManager tree API:** + +```typescript +const sm = SessionManager.open("/path/to/session.jsonl"); + +// Session listing +const currentProjectSessions = await SessionManager.list(process.cwd()); +const allSessions = await SessionManager.listAll(process.cwd()); + +// Tree traversal +const entries = sm.getEntries(); // All entries (excludes header) +const tree = sm.getTree(); // Full tree structure +const path = sm.getPath(); // Path from root to current leaf +const leaf = sm.getLeafEntry(); // Current leaf entry +const entry = sm.getEntry(id); // Get entry by ID +const children = sm.getChildren(id); // Direct children of entry + +// Labels +const label = sm.getLabel(id); // Get label for entry +sm.appendLabelChange(id, "checkpoint"); // Set label + +// Branching +sm.branch(entryId); // Move leaf to earlier entry +sm.branchWithSummary(id, "Summary..."); // Branch with context summary +sm.createBranchedSession(leafId); // Extract path to new file +``` + +> See [examples/sdk/11-sessions.ts](../examples/sdk/11-sessions.ts) and [Session Format](session-format.md) + +### Settings Management + +```typescript +import { createAgentSession, SettingsManager, SessionManager } from "@earendil-works/pi-coding-agent"; + +// Default: loads from files (global + project merged) +const { session } = await createAgentSession({ + settingsManager: SettingsManager.create(), +}); + +// With overrides +const settingsManager = SettingsManager.create(); +settingsManager.applyOverrides({ + compaction: { enabled: false }, + retry: { enabled: true, maxRetries: 5 }, +}); +const { session } = await createAgentSession({ settingsManager }); + +// In-memory (no file I/O, for testing) +const { session } = await createAgentSession({ + settingsManager: SettingsManager.inMemory({ compaction: { enabled: false } }), + sessionManager: SessionManager.inMemory(), +}); + +// Custom directories +const { session } = await createAgentSession({ + settingsManager: SettingsManager.create("/custom/cwd", "/custom/agent"), +}); +``` + +**Static factories:** +- `SettingsManager.create(cwd?, agentDir?)` - Load from files +- `SettingsManager.inMemory(settings?)` - No file I/O + +**Project-specific settings:** + +Settings load from two locations and merge: +1. Global: `~/.pi/agent/settings.json` +2. Project: `/.pi/settings.json` + +Project overrides global. Nested objects merge keys. Setters modify global settings by default. + +**Persistence and error handling semantics:** + +- Settings getters/setters are synchronous for in-memory state. +- Setters enqueue persistence writes asynchronously. +- Call `await settingsManager.flush()` when you need a durability boundary (for example, before process exit or before asserting file contents in tests). +- `SettingsManager` does not print settings I/O errors. Use `settingsManager.drainErrors()` and report them in your app layer. + +> See [examples/sdk/10-settings.ts](../examples/sdk/10-settings.ts) + +## ResourceLoader + +Use `DefaultResourceLoader` to discover extensions, skills, prompts, themes, and context files. + +```typescript +import { + DefaultResourceLoader, + getAgentDir, +} from "@earendil-works/pi-coding-agent"; + +const loader = new DefaultResourceLoader({ + cwd, + agentDir: getAgentDir(), +}); +await loader.reload(); + +const extensions = loader.getExtensions(); +const skills = loader.getSkills(); +const prompts = loader.getPrompts(); +const themes = loader.getThemes(); +const contextFiles = loader.getAgentsFiles().agentsFiles; +``` + +## Return Value + +`createAgentSession()` returns: + +```typescript +interface CreateAgentSessionResult { + // The session + session: AgentSession; + + // Extensions result (for runner setup) + extensionsResult: LoadExtensionsResult; + + // Warning if session model couldn't be restored + modelFallbackMessage?: string; +} + +interface LoadExtensionsResult { + extensions: Extension[]; + errors: Array<{ path: string; error: string }>; + runtime: ExtensionRuntime; +} +``` + +## Complete Example + +```typescript +import { getModel } from "@earendil-works/pi-ai"; +import { Type } from "typebox"; +import { + createAgentSession, + DefaultResourceLoader, + defineTool, + ModelRuntime, + SessionManager, + SettingsManager, +} from "@earendil-works/pi-coding-agent"; + +const modelRuntime = await ModelRuntime.create({ + authPath: "/custom/agent/auth.json", + modelsPath: "/custom/agent/models.json", +}); +if (process.env.MY_KEY) { + modelRuntime.setRuntimeApiKey("anthropic", process.env.MY_KEY); +} + +// Inline tool +const statusTool = defineTool({ + name: "status", + label: "Status", + description: "Get system status", + parameters: Type.Object({}), + execute: async () => ({ + content: [{ type: "text", text: `Uptime: ${process.uptime()}s` }], + details: {}, + }), +}); + +const model = getModel("anthropic", "claude-opus-4-5"); +if (!model) throw new Error("Model not found"); + +// In-memory settings with overrides +const settingsManager = SettingsManager.inMemory({ + compaction: { enabled: false }, + retry: { enabled: true, maxRetries: 2 }, +}); + +const loader = new DefaultResourceLoader({ + cwd: process.cwd(), + agentDir: "/custom/agent", + settingsManager, + systemPromptOverride: () => "You are a minimal assistant. Be concise.", +}); +await loader.reload(); + +const { session } = await createAgentSession({ + cwd: process.cwd(), + agentDir: "/custom/agent", + + model, + thinkingLevel: "off", + modelRuntime, + + tools: ["read", "bash", "status"], + customTools: [statusTool], + resourceLoader: loader, + + sessionManager: SessionManager.inMemory(), + settingsManager, +}); + +session.subscribe((event) => { + if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { + process.stdout.write(event.assistantMessageEvent.delta); + } +}); + +await session.prompt("Get status and list files."); +``` + +## Run Modes + +The SDK exports run mode utilities for building custom interfaces on top of `createAgentSession()`: + +### InteractiveMode + +Full TUI interactive mode with editor, chat history, and all built-in commands: + +```typescript +import { + type CreateAgentSessionRuntimeFactory, + createAgentSessionFromServices, + createAgentSessionRuntime, + createAgentSessionServices, + getAgentDir, + InteractiveMode, + SessionManager, +} from "@earendil-works/pi-coding-agent"; + +const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => { + const services = await createAgentSessionServices({ cwd }); + return { + ...(await createAgentSessionFromServices({ services, sessionManager, sessionStartEvent })), + services, + diagnostics: services.diagnostics, + }; +}; +const runtime = await createAgentSessionRuntime(createRuntime, { + cwd: process.cwd(), + agentDir: getAgentDir(), + sessionManager: SessionManager.create(process.cwd()), +}); + +const mode = new InteractiveMode(runtime, { + migratedProviders: [], + modelFallbackMessage: undefined, + initialMessage: "Hello", + initialImages: [], + initialMessages: [], +}); + +await mode.run(); +``` + +### runPrintMode + +Single-shot mode: send prompts, output result, exit: + +```typescript +import { + type CreateAgentSessionRuntimeFactory, + createAgentSessionFromServices, + createAgentSessionRuntime, + createAgentSessionServices, + getAgentDir, + runPrintMode, + SessionManager, +} from "@earendil-works/pi-coding-agent"; + +const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => { + const services = await createAgentSessionServices({ cwd }); + return { + ...(await createAgentSessionFromServices({ services, sessionManager, sessionStartEvent })), + services, + diagnostics: services.diagnostics, + }; +}; +const runtime = await createAgentSessionRuntime(createRuntime, { + cwd: process.cwd(), + agentDir: getAgentDir(), + sessionManager: SessionManager.create(process.cwd()), +}); + +await runPrintMode(runtime, { + mode: "text", + initialMessage: "Hello", + initialImages: [], + messages: ["Follow up"], +}); +``` + +### runRpcMode + +JSON-RPC mode for subprocess integration: + +```typescript +import { + type CreateAgentSessionRuntimeFactory, + createAgentSessionFromServices, + createAgentSessionRuntime, + createAgentSessionServices, + getAgentDir, + runRpcMode, + SessionManager, +} from "@earendil-works/pi-coding-agent"; + +const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => { + const services = await createAgentSessionServices({ cwd }); + return { + ...(await createAgentSessionFromServices({ services, sessionManager, sessionStartEvent })), + services, + diagnostics: services.diagnostics, + }; +}; +const runtime = await createAgentSessionRuntime(createRuntime, { + cwd: process.cwd(), + agentDir: getAgentDir(), + sessionManager: SessionManager.create(process.cwd()), +}); + +await runRpcMode(runtime); +``` + +See [RPC documentation](rpc.md) for the JSON protocol. + +## RPC Mode Alternative + +For subprocess-based integration without building with the SDK, use the CLI directly: + +```bash +pi --mode rpc --no-session +``` + +See [RPC documentation](rpc.md) for the JSON protocol. + +The SDK is preferred when: +- You want type safety +- You're in the same Node.js process +- You need direct access to agent state +- You want to customize tools/extensions programmatically + +RPC mode is preferred when: +- You're integrating from another language +- You want process isolation +- You're building a language-agnostic client + +## Exports + +The main entry point exports: + +```typescript +// Factory +createAgentSession +createAgentSessionRuntime +AgentSessionRuntime + +// Auth and Models +ModelRuntime // implements pi-ai Models and owns credential storage +ModelRegistry // synchronous extension compatibility facade +resolveCliModel +resolveModelScopeWithDiagnostics + +// Resource loading +DefaultResourceLoader +type ResourceLoader +createEventBus + +// Constants and helpers +CONFIG_DIR_NAME +defineTool +getAgentDir +getPackageDir +getReadmePath +getDocsPath +getExamplesPath + +// Session management +SessionManager +SettingsManager + +// Tool factories +createCodingTools +createReadOnlyTools +createReadTool, createBashTool, createEditTool, createWriteTool +createGrepTool, createFindTool, createLsTool + +// Types +type CreateAgentSessionOptions +type CreateAgentSessionResult +type ExtensionFactory +type InlineExtension +type ExtensionAPI +type ToolDefinition +type Skill +type PromptTemplate +type Tool +``` + +For extension types, see [extensions.md](extensions.md) for the full API. diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 0000000..29828e0 --- /dev/null +++ b/docs/security.md @@ -0,0 +1,59 @@ +# Security + +Pi is a local coding agent. It runs with the permissions of the user account that starts it, and it treats files writable by that user as inside the same local trust boundary. + +## Project Trust + +Project trust controls whether pi loads project-local settings, resources, packages, and extensions. It is not a sandbox and it does not restrict what the model can ask tools to do after you start working in a directory. + +Pi considers a project to have resources that require trust when it finds any of these from the current working directory: + +- `.pi/settings.json` +- `.pi/extensions`, `.pi/skills`, `.pi/prompts`, or `.pi/themes` +- `.pi/SYSTEM.md` or `.pi/APPEND_SYSTEM.md` +- project `.agents/skills` in the current directory or an ancestor directory + +A bare `.pi` directory does not count as a project resource that requires trust. + +When an interactive session starts in a project with resources that require trust and no saved decision for the current directory or a parent directory, pi follows `defaultProjectTrust` from global settings. The default value is `"ask"`, which asks whether to trust the project when UI is available. Saved decisions are stored by canonical directory in `~/.pi/agent/trust.json`, and the closest saved decision on the current or parent path applies before the global default. + +Trusting a project allows pi to load project resources that require trust, including: + +- `.pi/settings.json` +- `.pi` resources such as extensions, skills, prompt templates, themes, and system prompt files +- missing project packages configured through project settings +- project-local extensions and project package-managed extensions + +Declining trust skips protected resources. `AGENTS.md` and `CLAUDE.md` context files are loaded regardless of project trust unless context loading is disabled. Before trust is resolved, pi only loads context files, user/global extensions, and CLI `-e` extensions. User/global and CLI extensions can handle the `project_trust` event; the first extension that returns a yes/no decision owns the decision. + +Non-interactive modes (`-p`, `--mode json`, and `--mode rpc`) do not show a trust prompt. Without an applicable saved trust decision, `defaultProjectTrust: "ask"` and `"never"` ignore such resources, while `"always"` trusts them. Use `--approve`/`-a` or `--no-approve`/`-na` to override project trust for one run. + +## No Built-in Sandbox + +Pi does not include a built-in sandbox. Built-in tools can read files, write files, edit files, and run shell commands with the permissions of the pi process. Extensions are TypeScript modules that run with the same permissions. Package installs, shell commands, language servers, test commands, and other developer tools behave as ordinary local processes. + +This is intentional. Pi is designed to operate on local source trees, invoke project toolchains, and integrate with the user's existing development environment. A partial in-process sandbox would be easy to misunderstand as a security boundary while still depending on the host shell, filesystem, package managers, credentials, and extension code. Real isolation needs to come from the operating system or a virtualization/container boundary. + +Project trust is only an input-loading guard. It prevents a repository from silently changing pi's settings or extensions before you approve it. It does not make untrusted code, untrusted prompts, or untrusted model output safe. Prompt injection from repository files, comments, documentation, context files, or build output is expected local-agent risk and cannot be reliably prevented by pi. + +## Running Untrusted or Unmonitored Work + +For untrusted repositories, generated code you do not intend to monitor closely, or unattended automation, run pi in a contained environment. Use a container, VM, micro-VM, remote sandbox, or policy-controlled sandbox with only the files and credentials required for the task. + +Common patterns are documented in [Containerization](containerization.md): + +- run the whole `pi` process inside a container/sandbox +- run host pi while routing built-in tool execution into a Gondolin micro-VM +- mount only the workspace paths the agent should access +- avoid mounting host `~/.pi/agent` unless the container should access host sessions, settings, and credentials +- pass the minimum required API keys or use short-lived credentials +- restrict network access when the task does not need it +- review diffs and outputs before copying results back to trusted systems + +If you bind-mount a host workspace read/write, writes from inside the container or VM can still modify host files. Use read-only mounts or copy files into and out of the sandbox when you need stronger protection from unintended writes. + +## Reporting Security Issues + +To report a security issue, follow the repository [Security Policy](https://github.com/earendil-works/pi-mono/blob/main/SECURITY.md). Do not open a public issue for security-sensitive reports. + +Expected local-agent behavior, lack of a built-in sandbox, prompt injection from untrusted content, and behavior of user-installed extensions or skills are generally outside the security boundary unless the report demonstrates a real privilege-boundary bypass or shows how pi grants access that the local user did not already have. diff --git a/docs/session-format.md b/docs/session-format.md new file mode 100644 index 0000000..c5956ed --- /dev/null +++ b/docs/session-format.md @@ -0,0 +1,438 @@ +# Session File Format + +Sessions are stored as JSONL (JSON Lines) files. Each line is a JSON object with a `type` field. Session entries form a tree structure via `id`/`parentId` fields, enabling in-place branching without creating new files. + +## File Location + +``` +~/.pi/agent/sessions/----/_.jsonl +``` + +Where `` is the working directory with `/` replaced by `-`. + +## Deleting Sessions + +Sessions can be removed by deleting their `.jsonl` files under `~/.pi/agent/sessions/`. + +Pi also supports deleting sessions interactively from `/resume` (select a session and press `Ctrl+D`, then confirm). When available, pi uses the `trash` CLI to avoid permanent deletion. + +## Session Version + +Sessions have a version field in the header: + +- **Version 1**: Linear entry sequence (legacy, auto-migrated on load) +- **Version 2**: Tree structure with `id`/`parentId` linking +- **Version 3**: Renamed `hookMessage` role to `custom` (extensions unification) + +Existing sessions are automatically migrated to the current version (v3) when loaded. + +## Source Files + +Source on GitHub ([pi-mono](https://github.com/earendil-works/pi-mono)): +- [`packages/coding-agent/src/core/session-manager.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/session-manager.ts) - Session entry types and SessionManager +- [`packages/coding-agent/src/core/messages.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/messages.ts) - Extended message types (BashExecutionMessage, CustomMessage, etc.) +- [`packages/ai/src/types.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/ai/src/types.ts) - Base message types (UserMessage, AssistantMessage, ToolResultMessage) +- [`packages/agent/src/types.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/agent/src/types.ts) - AgentMessage union type + +For TypeScript definitions in your project, inspect `node_modules/@earendil-works/pi-coding-agent/dist/` and `node_modules/@earendil-works/pi-ai/dist/`. + +## Message Types + +Session entries contain `AgentMessage` objects. Understanding these types is essential for parsing sessions and writing extensions. + +### Content Blocks + +Messages contain arrays of typed content blocks: + +```typescript +interface TextContent { + type: "text"; + text: string; +} + +interface ImageContent { + type: "image"; + data: string; // base64 encoded + mimeType: string; // e.g., "image/jpeg", "image/png" +} + +interface ThinkingContent { + type: "thinking"; + thinking: string; +} + +interface ToolCall { + type: "toolCall"; + id: string; + name: string; + arguments: Record; +} +``` + +### Base Message Types (from pi-ai) + +```typescript +interface UserMessage { + role: "user"; + content: string | (TextContent | ImageContent)[]; + timestamp: number; // Unix ms +} + +interface AssistantMessage { + role: "assistant"; + content: (TextContent | ThinkingContent | ToolCall)[]; + api: string; + provider: string; + model: string; + usage: Usage; + stopReason: "stop" | "length" | "toolUse" | "error" | "aborted"; + errorMessage?: string; + timestamp: number; +} + +interface ToolResultMessage { + role: "toolResult"; + toolCallId: string; + toolName: string; + content: (TextContent | ImageContent)[]; + details?: any; // Tool-specific metadata + usage?: Usage; // Nested LLM work performed by the tool + isError: boolean; + timestamp: number; +} + +interface Usage { + input: number; + output: number; + cacheRead: number; + cacheWrite: number; + totalTokens: number; + cost: { + input: number; + output: number; + cacheRead: number; + cacheWrite: number; + total: number; + }; +} +``` + +The exported pi-ai `StopReason` type also includes `"pending"`, but that value is reserved for partial messages in streaming events. Terminal `done`/`error` messages replace it with a completion reason before pi persists the assistant message, so `"pending"` should never appear in session JSONL. + +### Extended Message Types (from pi-coding-agent) + +```typescript +interface BashExecutionMessage { + role: "bashExecution"; + command: string; + output: string; + exitCode: number | undefined; + cancelled: boolean; + truncated: boolean; + fullOutputPath?: string; + excludeFromContext?: boolean; // true for !! prefix commands + timestamp: number; +} + +interface CustomMessage { + role: "custom"; + customType: string; // Extension identifier + content: string | (TextContent | ImageContent)[]; + display: boolean; // Show in TUI + details?: any; // Extension-specific metadata + timestamp: number; +} + +interface BranchSummaryMessage { + role: "branchSummary"; + summary: string; + fromId: string; // Entry we branched from + timestamp: number; +} + +interface CompactionSummaryMessage { + role: "compactionSummary"; + summary: string; + tokensBefore: number; + timestamp: number; +} +``` + +### AgentMessage Union + +```typescript +type AgentMessage = + | UserMessage + | AssistantMessage + | ToolResultMessage + | BashExecutionMessage + | CustomMessage + | BranchSummaryMessage + | CompactionSummaryMessage; +``` + +## Entry Base + +All entries (except `SessionHeader`) extend `SessionEntryBase`: + +```typescript +interface SessionEntryBase { + type: string; + id: string; // 8-char hex ID + parentId: string | null; // Parent entry ID (null for first entry) + timestamp: string; // ISO timestamp +} +``` + +## Entry Types + +### SessionHeader + +First line of the file. Metadata only, not part of the tree (no `id`/`parentId`). + +```json +{"type":"session","version":3,"id":"uuid","timestamp":"2024-12-03T14:00:00.000Z","cwd":"/path/to/project"} +``` + +For sessions with a parent (created via `/fork`, `/clone`, or `newSession({ parentSession })`): + +```json +{"type":"session","version":3,"id":"uuid","timestamp":"2024-12-03T14:00:00.000Z","cwd":"/path/to/project","parentSession":"/path/to/original/session.jsonl"} +``` + +### SessionMessageEntry + +A message in the conversation. The `message` field contains an `AgentMessage`. + +```json +{"type":"message","id":"a1b2c3d4","parentId":"prev1234","timestamp":"2024-12-03T14:00:01.000Z","message":{"role":"user","content":"Hello"}} +{"type":"message","id":"b2c3d4e5","parentId":"a1b2c3d4","timestamp":"2024-12-03T14:00:02.000Z","message":{"role":"assistant","content":[{"type":"text","text":"Hi!"}],"provider":"anthropic","model":"claude-sonnet-4-5","usage":{...},"stopReason":"stop"}} +{"type":"message","id":"c3d4e5f6","parentId":"b2c3d4e5","timestamp":"2024-12-03T14:00:03.000Z","message":{"role":"toolResult","toolCallId":"call_123","toolName":"bash","content":[{"type":"text","text":"output"}],"isError":false}} +``` + +### ModelChangeEntry + +Emitted when the user switches models mid-session. + +```json +{"type":"model_change","id":"d4e5f6g7","parentId":"c3d4e5f6","timestamp":"2024-12-03T14:05:00.000Z","provider":"openai","modelId":"gpt-4o"} +``` + +### ThinkingLevelChangeEntry + +Emitted when the user changes the thinking/reasoning level. + +```json +{"type":"thinking_level_change","id":"e5f6g7h8","parentId":"d4e5f6g7","timestamp":"2024-12-03T14:06:00.000Z","thinkingLevel":"high"} +``` + +### CompactionEntry + +Created when context is compacted. Stores a summary of earlier messages. + +```json +{"type":"compaction","id":"f6g7h8i9","parentId":"e5f6g7h8","timestamp":"2024-12-03T14:10:00.000Z","summary":"User discussed X, Y, Z...","firstKeptEntryId":"c3d4e5f6","tokensBefore":50000} +``` + +Newer harness-generated compactions embed the retained post-compaction context directly on the entry, instead of `firstKeptEntryId`: + +```json +{"type":"compaction","id":"f6g7h8i9","parentId":"e5f6g7h8","timestamp":"2024-12-03T14:10:00.000Z","summary":"User discussed X, Y, Z...","tokensBefore":50000,"retainedTail":[{"role":"user","content":"latest request"},{"role":"assistant","content":[{"type":"text","text":"latest reply"}],"provider":"anthropic","model":"claude-sonnet-4-5","usage":{...},"stopReason":"stop"}]} +``` + +Optional fields: +- `usage`: LLM usage from generating the summary; included in session token and cost totals +- `retainedTail`: Materialized `AgentMessage[]` kept after compaction. This is optional only for backward compatibility with older sessions. Newer harness-generated compactions include it so we can rebuild context from this checkpoint without walking older entries before the compaction entry. +- `details`: Implementation-specific data (e.g., `{ readFiles: string[], modifiedFiles: string[] }` for default, or custom data for extensions) +- `fromHook`: `true` if generated by an extension, `false`/`undefined` if pi-generated (legacy field name) +- `firstKeptEntryId`: for compatibility with old entry format. + +### BranchSummaryEntry + +Created when switching branches via `/tree` with an LLM generated summary of the left branch up to the common ancestor. Captures context from the abandoned path. + +```json +{"type":"branch_summary","id":"g7h8i9j0","parentId":"a1b2c3d4","timestamp":"2024-12-03T14:15:00.000Z","fromId":"f6g7h8i9","summary":"Branch explored approach A..."} +``` + +Optional fields: +- `usage`: LLM usage from generating the summary; included in session token and cost totals +- `details`: File tracking data (`{ readFiles: string[], modifiedFiles: string[] }`) for default, or custom data for extensions +- `fromHook`: `true` if generated by an extension, `false`/`undefined` if pi-generated (legacy field name) + +### CustomEntry + +Extension state persistence. Does NOT participate in LLM context. + +```json +{"type":"custom","id":"h8i9j0k1","parentId":"g7h8i9j0","timestamp":"2024-12-03T14:20:00.000Z","customType":"my-extension","data":{"count":42}} +``` + +Use `customType` to identify your extension's entries on reload. Interactive mode can render custom entries via `pi.registerEntryRenderer(customType, renderer)`, but they still do not participate in LLM context. + +### CustomMessageEntry + +Extension-injected messages that DO participate in LLM context. + +```json +{"type":"custom_message","id":"i9j0k1l2","parentId":"h8i9j0k1","timestamp":"2024-12-03T14:25:00.000Z","customType":"my-extension","content":"Injected context...","display":true} +``` + +Fields: +- `content`: String or `(TextContent | ImageContent)[]` (same as UserMessage) +- `display`: `true` = show in TUI with distinct styling, `false` = hidden +- `details`: Optional extension-specific metadata (not sent to LLM) + +### LabelEntry + +User-defined bookmark/marker on an entry. + +```json +{"type":"label","id":"j0k1l2m3","parentId":"i9j0k1l2","timestamp":"2024-12-03T14:30:00.000Z","targetId":"a1b2c3d4","label":"checkpoint-1"} +``` + +Set `label` to `undefined` to clear a label. + +### SessionInfoEntry + +Session metadata (e.g., user-defined display name). Set via `/name`, `--name` / `-n`, or `pi.setSessionName()` in extensions. + +```json +{"type":"session_info","id":"k1l2m3n4","parentId":"j0k1l2m3","timestamp":"2024-12-03T14:35:00.000Z","name":"Refactor auth module"} +``` + +The session name is displayed in the session selector (`/resume`) instead of the first message when set. + +## Tree Structure + +Entries form a tree: +- First entry has `parentId: null` +- Each subsequent entry points to its parent via `parentId` +- Branching creates new children from an earlier entry +- The "leaf" is the current position in the tree + +``` +[user msg] ─── [assistant] ─── [user msg] ─── [assistant] ─┬─ [user msg] ← current leaf + │ + └─ [branch_summary] ─── [user msg] ← alternate branch +``` + +## Context Building + +`buildContextEntries()` walks from the current leaf to the root, producing the active entry list while honoring compaction: + +1. Collects all entries on the path +2. If a `CompactionEntry` is on the path: + - Includes the compaction entry first + - If `retainedTail` is present, it acts as a self-contained checkpoint and entries after the compaction are included + - Otherwise entries from `firstKeptEntryId` to the compaction are included + - Then entries after compaction are included +3. Preserves non-message entries in the selected range so interactive mode can render them + +`buildSessionContext()` builds on that entry list to produce the message list for the LLM: + +1. Extracts current model and thinking level settings from the full path +2. Converts selected entries to messages: + - `message` -> stored `AgentMessage` + - `compaction` -> `compactionSummary` plus `retainedTail` when present + - `branch_summary` -> `branchSummary` + - `custom_message` -> `CustomMessage` + - `custom` -> no context message + +This makes newer compactions act like self-contained checkpoints. `retainedTail` is optional only so older sessions that only store `firstKeptEntryId` continue to load correctly. + +## Parsing Example + +```typescript +import { readFileSync } from "fs"; + +const lines = readFileSync("session.jsonl", "utf8").trim().split("\n"); + +for (const line of lines) { + const entry = JSON.parse(line); + + switch (entry.type) { + case "session": + console.log(`Session v${entry.version ?? 1}: ${entry.id}`); + break; + case "message": + console.log(`[${entry.id}] ${entry.message.role}: ${JSON.stringify(entry.message.content)}`); + break; + case "compaction": + console.log(`[${entry.id}] Compaction: ${entry.tokensBefore} tokens summarized`); + break; + case "branch_summary": + console.log(`[${entry.id}] Branch from ${entry.fromId}`); + break; + case "custom": + console.log(`[${entry.id}] Custom (${entry.customType}): ${JSON.stringify(entry.data)}`); + break; + case "custom_message": + console.log(`[${entry.id}] Extension message (${entry.customType}): ${entry.content}`); + break; + case "label": + console.log(`[${entry.id}] Label "${entry.label}" on ${entry.targetId}`); + break; + case "model_change": + console.log(`[${entry.id}] Model: ${entry.provider}/${entry.modelId}`); + break; + case "thinking_level_change": + console.log(`[${entry.id}] Thinking: ${entry.thinkingLevel}`); + break; + } +} +``` + +## SessionManager API + +Key methods for working with sessions programmatically. + +### Static Creation Methods +- `SessionManager.create(cwd, sessionDir?)` - New session +- `SessionManager.open(path, sessionDir?)` - Open existing session file +- `SessionManager.continueRecent(cwd, sessionDir?)` - Continue most recent or create new +- `SessionManager.inMemory(cwd?)` - No file persistence +- `SessionManager.forkFrom(sourcePath, targetCwd, sessionDir?)` - Fork session from another project + +### Static Listing Methods +- `SessionManager.list(cwd, sessionDir?, onProgress?)` - List sessions for a directory +- `SessionManager.listAll(onProgress?)` - List all sessions across all projects + +### Instance Methods - Session Management +- `newSession(options?)` - Start a new session (options: `{ parentSession?: string }`) +- `setSessionFile(path)` - Switch to a different session file +- `createBranchedSession(leafId)` - Extract branch to new session file + +### Instance Methods - Appending (all return entry ID) +- `appendMessage(message)` - Add message +- `appendThinkingLevelChange(level)` - Record thinking change +- `appendModelChange(provider, modelId)` - Record model change +- `appendCompaction(summary, firstKeptEntryId, tokensBefore, details?, fromHook?)` - Add compaction +- `appendCustomEntry(customType, data?)` - Extension state (not in context) +- `appendSessionInfo(name)` - Set session display name +- `appendCustomMessageEntry(customType, content, display, details?)` - Extension message (in context) +- `appendLabelChange(targetId, label)` - Set/clear label + +### Instance Methods - Tree Navigation +- `getLeafId()` - Current position +- `getLeafEntry()` - Get current leaf entry +- `getEntry(id)` - Get entry by ID +- `getBranch(fromId?)` - Walk from entry to root +- `getTree()` - Get full tree structure +- `getChildren(parentId)` - Get direct children +- `getLabel(id)` - Get label for entry +- `branch(entryId)` - Move leaf to earlier entry +- `resetLeaf()` - Reset leaf to null (before any entries) +- `branchWithSummary(entryId, summary, details?, fromHook?)` - Branch with context summary + +### Instance Methods - Context & Info +- `buildContextEntries()` - Get active branch entries with compaction applied +- `buildSessionContext()` - Get messages, thinkingLevel, and model for LLM +- `getEntries()` - All entries (excluding header) +- `getHeader()` - Session header metadata +- `getSessionName()` - Get display name from latest session_info entry +- `getCwd()` - Working directory +- `getSessionDir()` - Session storage directory +- `getSessionId()` - Session UUID +- `getSessionFile()` - Session file path (undefined for in-memory) +- `isPersisted()` - Whether session is saved to disk diff --git a/docs/sessions.md b/docs/sessions.md new file mode 100644 index 0000000..1a50ee0 --- /dev/null +++ b/docs/sessions.md @@ -0,0 +1,145 @@ +# Sessions + +Pi saves conversations as sessions so you can continue work, branch from earlier turns, and revisit previous paths. + +## Session Storage + +Sessions auto-save to `~/.pi/agent/sessions/`, organized by working directory. Each session is a JSONL file with a tree structure. + +```bash +pi -c # Continue most recent session +pi -r # Browse and select from past sessions +pi --no-session # Ephemeral mode; do not save +pi --name "my task" # Set session display name at startup +pi --session # Use a specific session file or partial session ID +pi --fork # Fork a session file or partial session ID into a new session +``` + +Use `/session` in interactive mode to see the current session file, session ID, message count, tokens, and cost. + +For the JSONL file format and SessionManager API, see [Session Format](session-format.md). + +## Session Commands + +| Command | Description | +|---------|-------------| +| `/resume` | Browse and select previous sessions | +| `/new` | Start a new session | +| `/name ` | Set the current session display name | +| `/session` | Show session info | +| `/tree` | Navigate the current session tree | +| `/fork` | Create a new session from a previous user message | +| `/clone` | Duplicate the current active branch into a new session | +| `/compact [prompt]` | Summarize older context; see [Compaction](compaction.md) | +| `/export [file]` | Export session to HTML | +| `/share` | Upload as private GitHub gist with shareable HTML link | + +## Resuming and Deleting Sessions + +`/resume` opens an interactive session picker for the current project. `pi -r` opens the same picker at startup. + +In the picker you can: + +- search by typing +- toggle path display with Ctrl+P +- toggle sort mode with Ctrl+S +- filter to named sessions with Ctrl+N +- rename with Ctrl+R +- delete with Ctrl+D, then confirm + +When available, pi uses the `trash` CLI for deletion instead of permanently removing files. + +## Naming Sessions + +Use `/name ` to set a human-readable session name: + +```text +/name Refactor auth module +``` + +Set the name at startup with `--name` or `-n`: + +```bash +pi --name "Refactor auth module" +pi --name "CI audit" -p "Review this build failure" +``` + +Named sessions are easier to find in `/resume` and `pi -r`. + +## Branching with `/tree` + +Sessions are stored as trees. Every entry has an `id` and `parentId`, and the current position is the active leaf. `/tree` lets you jump to any previous point and continue from there without creating a new file. + +

    Tree View

    + +Example shape: + +```text +├─ user: "Hello, can you help..." +│ └─ assistant: "Of course! I can..." +│ ├─ user: "Let's try approach A..." +│ │ └─ assistant: "For approach A..." +│ │ └─ user: "That worked..." ← active +│ └─ user: "Actually, approach B..." +│ └─ assistant: "For approach B..." +``` + +### Tree Controls + +| Key | Action | +|-----|--------| +| ↑/↓ | Navigate visible entries | +| ←/→ | Page up/down | +| Ctrl+←/Ctrl+→ or Alt+←/Alt+→ | Fold/unfold or jump between branch segments | +| Shift+L | Set or clear a label on the selected entry | +| Shift+T | Toggle label timestamps | +| Enter | Select entry | +| Escape/Ctrl+C | Cancel | +| Ctrl+O | Cycle filter mode | + +Filter modes are: default, no-tools, user-only, labeled-only, and all. Configure the default with `treeFilterMode` in [Settings](settings.md). + +### Selection Behavior + +Selecting a user or custom message: + +1. Moves the leaf to the selected message's parent. +2. Places the selected message text in the editor. +3. Lets you edit and resubmit, creating a new branch. + +Selecting an assistant, tool, compaction, or other non-user entry: + +1. Moves the leaf to that entry. +2. Leaves the editor empty. +3. Lets you continue from that point. + +Selecting the root user message resets the leaf to an empty conversation and places the original prompt in the editor. + +## `/tree`, `/fork`, and `/clone` + +| Feature | `/tree` | `/fork` | `/clone` | +|---------|---------|---------|----------| +| Output | Same session file | New session file | New session file | +| View | Full tree | User-message selector | Current active branch | +| Typical use | Explore alternatives in place | Start a new session from an earlier prompt | Duplicate current work before continuing | +| Summary | Optional branch summary | None | None | + +Use `/tree` when you want to keep alternatives together. Use `/fork` or `/clone` when you want a separate session file. + +## Branch Summaries + +When `/tree` switches away from one branch to another, pi can summarize the abandoned branch and attach that summary at the new position. This preserves important context from the path you left without replaying the whole branch. + +When prompted, choose one of: + +1. no summary +2. summarize with the default prompt +3. summarize with custom focus instructions + +See [Compaction](compaction.md) for branch summarization internals and extension hooks. + +## Session Format + +Session files are JSONL and contain message entries, model changes, thinking-level changes, labels, compactions, branch summaries, and extension entries. + +For parsers, extensions, SDK usage, and the full SessionManager API, see [Session Format](session-format.md). diff --git a/docs/settings.md b/docs/settings.md new file mode 100644 index 0000000..c8fc371 --- /dev/null +++ b/docs/settings.md @@ -0,0 +1,319 @@ +# Settings + +Pi uses JSON settings files with project settings overriding global settings. + +| Location | Scope | +|----------|-------| +| `~/.pi/agent/settings.json` | Global (all projects) | +| `.pi/settings.json` | Project (current directory) | + +Edit directly or use `/settings` for common options. + +## Project Trust + +On interactive startup, pi asks before trusting a project folder that contains project-local settings, resources, or project `.agents/skills` and has no saved decision for the folder or a parent folder in `~/.pi/agent/trust.json`. Trusting a project allows pi to load `.pi/settings.json` and `.pi` resources, install missing project packages, and execute project extensions. + +Non-interactive modes (`-p`, `--mode json`, and `--mode rpc`) do not show a trust prompt. Without an applicable saved trust decision, they use `defaultProjectTrust` from global settings: `ask` (default) and `never` ignore those project resources, while `always` trusts them. Pass `--approve`/`-a` or `--no-approve`/`-na` to override project trust for one run. + +If no extension or saved decision applies, `defaultProjectTrust` controls the fallback behavior. Set it to `"ask"`, `"always"`, or `"never"` in `~/.pi/agent/settings.json`, or change it with `/settings`. + +`pi config` and package commands use the same project trust flow, except `pi update` never prompts. Pass `--approve` to trust project-local settings for one command or `--no-approve` to ignore them. + +Use `/trust` in interactive mode to save a project trust decision for future sessions, including trust for the immediate parent folder. It writes `~/.pi/agent/trust.json` only; the current session is not reloaded, so restart pi for changes to take effect. + +## All Settings + +### Model & Thinking + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `defaultProvider` | string | - | Default provider (e.g., `"anthropic"`, `"openai"`) | +| `defaultModel` | string | - | Default model ID | +| `defaultThinkingLevel` | string | - | `"off"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"`, `"max"` | +| `hideThinkingBlock` | boolean | `false` | Hide thinking blocks in output | +| `showCacheMissNotices` | boolean | `false` | Show transcript notices for significant prompt-cache misses | +| `thinkingBudgets` | object | - | Custom token budgets per thinking level | + +#### thinkingBudgets + +```json +{ + "thinkingBudgets": { + "minimal": 1024, + "low": 4096, + "medium": 10240, + "high": 32768 + } +} +``` + +### UI & Display + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `theme` | string | `"dark"` | Theme name (`"dark"`, `"light"`, or custom) | +| `externalEditor` | string | `$VISUAL`, then `$EDITOR`, then Notepad on Windows or `nano` elsewhere | Command for Ctrl+G external editor; takes precedence over environment variables | +| `quietStartup` | boolean | `false` | Hide startup header | +| `defaultProjectTrust` | string | `"ask"` | Fallback project trust behavior: `"ask"`, `"always"`, or `"never"`. Global setting only | +| `collapseChangelog` | boolean | `false` | Show condensed changelog after updates | +| `enableInstallTelemetry` | boolean | `true` | Send an anonymous install/update version ping after first install or changelog-detected updates. This does not control update checks | +| `enableAnalytics` | boolean | `false` | Opt-in analytics data sharing. Currently only asked for during the experimental first-time setup (`PI_EXPERIMENTAL=1`) | +| `trackingId` | string | - | Analytics tracking identifier, generated when `enableAnalytics` is turned on | +| `doubleEscapeAction` | string | `"tree"` | Action for double-escape: `"tree"`, `"fork"`, or `"none"` | +| `treeFilterMode` | string | `"default"` | Default filter for `/tree`: `"default"`, `"no-tools"`, `"user-only"`, `"labeled-only"`, `"all"` | +| `editorPaddingX` | number | `0` | Horizontal padding for input editor (0-3) | +| `outputPad` | number | `1` | Horizontal padding for user messages, assistant messages, and thinking (0 or 1) | +| `autocompleteMaxVisible` | number | `5` | Max visible items in autocomplete dropdown (3-20) | +| `showHardwareCursor` | boolean | `false` | Show the terminal cursor while TUI positions it for IME support | + +For VS Code, include `--wait` so pi resumes after the editor exits: + +```json +{ + "externalEditor": "code --wait" +} +``` + +### Telemetry and update checks + +`enableInstallTelemetry` only controls the anonymous install/update ping to `https://pi.dev/api/report-install`. Opting out of telemetry does not disable update checks; Pi can still fetch `https://pi.dev/api/latest-version` to look for the latest version. + +Set `PI_SKIP_VERSION_CHECK=1` to disable the Pi version update check. Use `--offline` or `PI_OFFLINE=1` to disable all startup network operations described here, including update checks, package update checks, and install/update telemetry. + +### Network + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `httpProxy` | string | - | HTTP proxy URL applied as `HTTP_PROXY` and `HTTPS_PROXY`. Global setting only. | + +```json +{ + "httpProxy": "http://127.0.0.1:7890" +} +``` + +### Warnings + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `warnings.anthropicExtraUsage` | boolean | `true` | Show a warning when Anthropic subscription auth may use paid extra usage | + +```json +{ + "warnings": { + "anthropicExtraUsage": false + } +} +``` + +### Compaction + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `compaction.enabled` | boolean | `true` | Enable auto-compaction | +| `compaction.reserveTokens` | number | `16384` | Tokens reserved for LLM response | +| `compaction.keepRecentTokens` | number | `20000` | Recent tokens to keep (not summarized) | + +```json +{ + "compaction": { + "enabled": true, + "reserveTokens": 16384, + "keepRecentTokens": 20000 + } +} +``` + +### Branch Summary + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `branchSummary.reserveTokens` | number | `16384` | Tokens reserved for branch summarization | +| `branchSummary.skipPrompt` | boolean | `false` | Skip "Summarize branch?" prompt on `/tree` navigation (defaults to no summary) | + +### Retry + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `retry.enabled` | boolean | `true` | Enable automatic agent-level retry on transient errors | +| `retry.maxRetries` | number | `3` | Maximum agent-level retry attempts | +| `retry.baseDelayMs` | number | `2000` | Base delay for agent-level exponential backoff (2s, 4s, 8s) | +| `retry.provider.timeoutMs` | number | SDK default | Provider/SDK request timeout in milliseconds | +| `retry.provider.maxRetries` | number | `0` | Provider/SDK retry attempts | +| `retry.provider.maxRetryDelayMs` | number | `60000` | Max server-requested delay before failing (60s) | + +When a provider requests a retry delay longer than `retry.provider.maxRetryDelayMs`, the request fails immediately with an informative error instead of waiting silently. Set it to `0` to disable the limit. + +Keep `retry.provider.maxRetries` at `0` unless provider-level retries are explicitly needed. Setting it above `0` can make SDK/provider retries handle out-of-usage-limit errors before Pi sees them, which may block the agent until the provider quota resets in some circumstances. + +```json +{ + "retry": { + "enabled": true, + "maxRetries": 3, + "baseDelayMs": 2000, + "provider": { + "timeoutMs": 3600000, + "maxRetries": 0, + "maxRetryDelayMs": 60000 + } + } +} +``` + +### Message Delivery + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `steeringMode` | string | `"one-at-a-time"` | How steering messages are sent: `"all"` or `"one-at-a-time"` | +| `followUpMode` | string | `"one-at-a-time"` | How follow-up messages are sent: `"all"` or `"one-at-a-time"` | +| `transport` | string | `"auto"` | Preferred transport for providers that support multiple transports: `"sse"`, `"websocket"`, `"websocket-cached"`, or `"auto"` | +| `httpIdleTimeoutMs` | number | `300000` | HTTP header/body idle timeout in milliseconds, also used by providers with explicit stream idle timeouts. Set to `0` to disable. | +| `websocketConnectTimeoutMs` | number | `15000` | WebSocket connect/open handshake timeout in milliseconds for providers that support WebSocket transports. Set to `0` to disable. | + +### Terminal & Images + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `terminal.showImages` | boolean | `true` | Show images in terminal (if supported) | +| `terminal.imageWidthCells` | number | `60` | Preferred inline image width in terminal cells | +| `terminal.clearOnShrink` | boolean | `false` | Clear empty rows when content shrinks (can cause flicker) | +| `images.autoResize` | boolean | `true` | Resize images to 2000x2000 max | +| `images.blockImages` | boolean | `false` | Block all images from being sent to LLM | + +### Shell + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `shellPath` | string | - | Custom shell path (e.g., for Cygwin on Windows); supports a leading `~` for the home directory | +| `shellCommandPrefix` | string | - | Prefix for every bash command (e.g., `"shopt -s expand_aliases"`) | +| `npmCommand` | string[] | - | Command argv used for npm package lookup/install operations (e.g., `["mise", "exec", "node@20", "--", "npm"]`) | + +```json +{ + "npmCommand": ["mise", "exec", "node@20", "--", "npm"] +} +``` + +`npmCommand` is used for all npm package-manager operations, including installs, uninstalls, and dependency installs inside git packages. User-scoped npm packages install under `~/.pi/agent/npm/`; project-scoped npm packages install under `.pi/npm/`. Use argv-style entries exactly as the process should be launched. When `npmCommand` is configured, git package dependency installs use plain `install` to avoid npm-specific flags in wrappers or alternate package managers. + +### Sessions + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `sessionDir` | string | - | Directory where session files are stored. Accepts absolute or relative paths, plus `~`. | + +```json +{ "sessionDir": ".pi/sessions" } +``` + +When multiple sources specify a session directory, precedence is `--session-dir`, `PI_CODING_AGENT_SESSION_DIR`, then `sessionDir` in settings.json. + +### Model Cycling + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `enabledModels` | string[] | - | Model patterns for Ctrl+P cycling (same format as `--models` CLI flag) | + +```json +{ + "enabledModels": ["claude-*", "gpt-4o", "gemini-2*"] +} +``` + +### Markdown + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `markdown.codeBlockIndent` | string | `" "` | Indentation for code blocks | + +### Resources + +These settings define where to load extensions, skills, prompts, and themes from. + +Paths in `~/.pi/agent/settings.json` resolve relative to `~/.pi/agent`. Paths in `.pi/settings.json` resolve relative to `.pi`. Absolute paths and `~` are supported. + +| Setting | Type | Default | Description | +|---------|------|---------|-------------| +| `packages` | array | `[]` | npm/git packages to load resources from | +| `extensions` | string[] | `[]` | Local extension file paths or directories | +| `skills` | string[] | `[]` | Local skill file paths or directories | +| `prompts` | string[] | `[]` | Local prompt template paths or directories | +| `themes` | string[] | `[]` | Local theme file paths or directories | +| `enableSkillCommands` | boolean | `true` | Register skills as `/skill:name` commands | + +Arrays support glob patterns and exclusions. Use `!pattern` to exclude. Use `+path` to force-include an exact path and `-path` to force-exclude an exact path. + +#### packages + +String form loads all resources from a package: + +```json +{ + "packages": ["pi-skills", "@org/my-extension"] +} +``` + +Object form filters which resources to load: + +```json +{ + "packages": [ + { + "source": "pi-skills", + "skills": ["brave-search", "transcribe"], + "extensions": [] + } + ] +} +``` + +See [packages.md](packages.md) for package management details. + +## Example + +```json +{ + "defaultProvider": "anthropic", + "defaultModel": "claude-sonnet-4-20250514", + "defaultThinkingLevel": "medium", + "theme": "dark", + "compaction": { + "enabled": true, + "reserveTokens": 16384, + "keepRecentTokens": 20000 + }, + "retry": { + "enabled": true, + "maxRetries": 3 + }, + "enabledModels": ["claude-*", "gpt-4o"], + "warnings": { + "anthropicExtraUsage": true + }, + "packages": ["pi-skills"] +} +``` + +## Project Overrides + +Project settings (`.pi/settings.json`) override global settings. Nested objects are merged: + +```json +// ~/.pi/agent/settings.json (global) +{ + "theme": "dark", + "compaction": { "enabled": true, "reserveTokens": 16384 } +} + +// .pi/settings.json (project) +{ + "compaction": { "reserveTokens": 8192 } +} + +// Result +{ + "theme": "dark", + "compaction": { "enabled": true, "reserveTokens": 8192 } +} +``` diff --git a/docs/shell-aliases.md b/docs/shell-aliases.md new file mode 100644 index 0000000..af0cd25 --- /dev/null +++ b/docs/shell-aliases.md @@ -0,0 +1,13 @@ +# Shell Aliases + +Pi runs bash in non-interactive mode (`bash -c`), which doesn't expand aliases by default. + +To enable your shell aliases, add to `~/.pi/agent/settings.json`: + +```json +{ + "shellCommandPrefix": "shopt -s expand_aliases\neval \"$(grep '^alias ' ~/.zshrc)\"" +} +``` + +Adjust the path (`~/.zshrc`, `~/.bashrc`, etc.) to match your shell config. diff --git a/docs/skills.md b/docs/skills.md new file mode 100644 index 0000000..d3ffeea --- /dev/null +++ b/docs/skills.md @@ -0,0 +1,231 @@ +> pi can create skills. Ask it to build one for your use case. + +# Skills + +Skills are self-contained capability packages that the agent loads on-demand. A skill provides specialized workflows, setup instructions, helper scripts, and reference documentation for specific tasks. + +Pi implements the [Agent Skills standard](https://agentskills.io/specification), warning about most violations but remaining lenient. Pi allows skill names to differ from their parent directory even though the standard disallows it; that rule is suboptimal for shared skill directories used across multiple agent harnesses. + +## Table of Contents + +- [Locations](#locations) +- [How Skills Work](#how-skills-work) +- [Skill Commands](#skill-commands) +- [Skill Structure](#skill-structure) +- [Frontmatter](#frontmatter) +- [Validation](#validation) +- [Example](#example) +- [Skill Repositories](#skill-repositories) + +## Locations + +> **Security:** Skills can instruct the model to perform any action and may include executable code the model invokes. Review skill content before use. + +Pi loads skills from: + +- Global: + - `~/.pi/agent/skills/` + - `~/.agents/skills/` +- Project (only after the project is trusted): + - `.pi/skills/` + - `.agents/skills/` in `cwd` and ancestor directories (up to git repo root, or filesystem root when not in a repo) +- Packages: `skills/` directories or `pi.skills` entries in `package.json` +- Settings: `skills` array with files or directories +- CLI: `--skill ` (repeatable, additive even with `--no-skills`) + +Discovery rules: +- In `~/.pi/agent/skills/` and `.pi/skills/`, direct root `.md` files are discovered as individual skills +- In all skill locations, directories containing `SKILL.md` are discovered recursively +- In `~/.agents/skills/` and project `.agents/skills/`, root `.md` files are ignored + +Disable discovery with `--no-skills` (explicit `--skill` paths still load). + +### Using Skills from Other Harnesses + +To use skills from Claude Code or OpenAI Codex, add their directories to settings: + +```json +{ + "skills": [ + "~/.claude/skills", + "~/.codex/skills" + ] +} +``` + +For project-level Claude Code skills, add to `.pi/settings.json`: + +```json +{ + "skills": ["../.claude/skills"] +} +``` + +## How Skills Work + +1. At startup, pi scans skill locations and extracts names and descriptions +2. The system prompt includes available skills in XML format per the [specification](https://agentskills.io/integrate-skills) +3. When a task matches, the agent uses `read` to load the full SKILL.md (models don't always do this; use prompting or `/skill:name` to force it) +4. The agent follows the instructions, using relative paths to reference scripts and assets + +This is progressive disclosure: only descriptions are always in context, full instructions load on-demand. + +## Skill Commands + +Skills register as `/skill:name` commands: + +```bash +/skill:brave-search # Load and execute the skill +/skill:pdf-tools extract # Load skill with arguments +``` + +Arguments after the command are appended to the skill content as `User: `. + +Toggle skill commands via `/settings` in interactive mode or in `settings.json`: + +```json +{ + "enableSkillCommands": true +} +``` + +## Skill Structure + +A skill is a directory with a `SKILL.md` file. Everything else is freeform. + +``` +my-skill/ +├── SKILL.md # Required: frontmatter + instructions +├── scripts/ # Helper scripts +│ └── process.sh +├── references/ # Detailed docs loaded on-demand +│ └── api-reference.md +└── assets/ + └── template.json +``` + +### SKILL.md Format + +````markdown +--- +name: my-skill +description: What this skill does and when to use it. Be specific. +--- + +# My Skill + +## Setup + +Run once before first use: +```bash +cd /path/to/skill && npm install +``` + +## Usage + +```bash +./scripts/process.sh +``` +```` + +Use relative paths from the skill directory: + +```markdown +See [the reference guide](references/REFERENCE.md) for details. +``` + +## Frontmatter + +Per the [Agent Skills specification](https://agentskills.io/specification#frontmatter-required): + +| Field | Required | Description | +|-------|----------|-------------| +| `name` | Yes | Max 64 chars. Lowercase a-z, 0-9, hyphens. Unlike the standard, Pi does not require this to match the parent directory because that standard requirement is suboptimal for shared skill directories. | +| `description` | Yes | Max 1024 chars. What the skill does and when to use it. | +| `license` | No | License name or reference to bundled file. | +| `compatibility` | No | Max 500 chars. Environment requirements. | +| `metadata` | No | Arbitrary key-value mapping. | +| `allowed-tools` | No | Space-delimited list of pre-approved tools (experimental). | +| `disable-model-invocation` | No | When `true`, skill is hidden from system prompt. Users must use `/skill:name`. | + +### Name Rules + +- 1-64 characters +- Lowercase letters, numbers, hyphens only +- No leading/trailing hyphens +- No consecutive hyphens +Pi does not require the name to match the parent directory. The Agent Skills standard does, but that requirement is suboptimal for shared skill directories used by multiple tools. + +Valid: `pdf-processing`, `data-analysis`, `code-review` +Invalid: `PDF-Processing`, `-pdf`, `pdf--processing` + +### Description Best Practices + +The description determines when the agent loads the skill. Be specific. + +Good: +```yaml +description: Extracts text and tables from PDF files, fills PDF forms, and merges multiple PDFs. Use when working with PDF documents. +``` + +Poor: +```yaml +description: Helps with PDFs. +``` + +## Validation + +Pi validates skills against the Agent Skills standard. Most issues produce warnings but still load the skill: + +- Name exceeds 64 characters or contains invalid characters +- Name starts/ends with hyphen or has consecutive hyphens +- Description exceeds 1024 characters + +Unknown frontmatter fields are ignored. + +**Exception:** Skills with missing description are not loaded. + +Name collisions (same name from different locations) warn and keep the first skill found. + +## Example + +``` +brave-search/ +├── SKILL.md +├── search.js +└── content.js +``` + +**SKILL.md:** +````markdown +--- +name: brave-search +description: Web search and content extraction via Brave Search API. Use for searching documentation, facts, or any web content. +--- + +# Brave Search + +## Setup + +```bash +cd /path/to/brave-search && npm install +``` + +## Search + +```bash +./search.js "query" # Basic search +./search.js "query" --content # Include page content +``` + +## Extract Page Content + +```bash +./content.js https://example.com +``` +```` + +## Skill Repositories + +- [Anthropic Skills](https://github.com/anthropics/skills) - Document processing (docx, pdf, pptx, xlsx), web development +- [Pi Skills](https://github.com/badlogic/pi-skills) - Web search, browser automation, Google APIs, transcription diff --git a/docs/terminal-setup.md b/docs/terminal-setup.md new file mode 100644 index 0000000..d2a8fb9 --- /dev/null +++ b/docs/terminal-setup.md @@ -0,0 +1,142 @@ +# Terminal Setup + +Pi uses the [Kitty keyboard protocol](https://sw.kovidgoyal.net/kitty/keyboard-protocol/) for reliable modifier key detection. Most modern terminals support this protocol, but some require configuration. + +## Kitty, iTerm2 + +Work out of the box. + +## Apple Terminal + +Pi enables enhanced key reporting when available. If Terminal.app still sends plain Return for `Shift+Enter`, pi uses a local macOS modifier fallback to treat that Return as `Shift+Enter`. + +This fallback only works when pi runs on the same Mac as Terminal.app. It cannot detect the local keyboard over remote SSH. + +## Ghostty + +Add to your Ghostty config (`~/Library/Application Support/com.mitchellh.ghostty/config` on macOS, `~/.config/ghostty/config` on Linux): + +``` +keybind = alt+backspace=text:\x1b\x7f +``` + +Older Claude Code versions may have added this Ghostty mapping: + +``` +keybind = shift+enter=text:\n +``` + +That mapping sends a raw linefeed byte. Inside pi, that is indistinguishable from `Ctrl+J`, so tmux and pi no longer see a real `shift+enter` key event. + +If Claude Code 2.x or newer is the only reason you added that mapping, you can remove it, unless you want to use Claude Code in tmux, where it still requires that Ghostty mapping. + +Pi binds `Ctrl+J` as a default newline alias, so `Shift+Enter` keeps working in tmux via that remap without extra pi configuration. + +## WezTerm + +WezTerm usually works out of the box for `Shift+Enter` via xterm modifyOtherKeys. To use the Kitty keyboard protocol explicitly, create `~/.wezterm.lua`: + +```lua +local wezterm = require 'wezterm' +local config = wezterm.config_builder() +config.enable_kitty_keyboard = true +return config +``` + +On macOS, WezTerm binds `Option+Enter` to fullscreen by default. To use `Option+Enter` for pi follow-up queueing, add this key override: + +```lua +local wezterm = require 'wezterm' +local config = wezterm.config_builder() +config.keys = { + { + key = 'Enter', + mods = 'ALT', + action = wezterm.action.SendString('\x1b[13;3u'), + }, +} +return config +``` + +If you already have a `config.keys` table, add the entry to it. + +On WSL, WezTerm may require a visible hardware cursor for IME candidate window positioning. If CJK IME candidates do not follow the text cursor, set `PI_HARDWARE_CURSOR=1` before running pi or set `showHardwareCursor` to `true` in settings. + +## Alacritty + +Alacritty usually works out of the box for `Shift+Enter`. On macOS, `Option+Enter` may arrive as plain `Enter`. To use `Option+Enter` for pi follow-up queueing, add to `~/.config/alacritty/alacritty.toml`: + +```toml +[[keyboard.bindings]] +key = "Enter" +mods = "Alt" +chars = "\u001b[13;3u" +``` + +Restart Alacritty after changing the config. + +## VS Code (Integrated Terminal) + +VS Code 1.109.5 and newer enable Kitty keyboard protocol in the integrated terminal by default, so `Shift+Enter` should work out of the box. + +VS Code versions older than 1.109.5 need an explicit terminal keybinding for `Shift+Enter`. + +`keybindings.json` locations: +- macOS: `~/Library/Application Support/Code/User/keybindings.json` +- Linux: `~/.config/Code/User/keybindings.json` +- Windows: `%APPDATA%\\Code\\User\\keybindings.json` + +Add to `keybindings.json`: + +```json +{ + "key": "shift+enter", + "command": "workbench.action.terminal.sendSequence", + "args": { "text": "\u001b[13;2u" }, + "when": "terminalFocus" +} +``` + +## Windows Terminal + +Add to `settings.json` (Ctrl+Shift+, or Settings → Open JSON file) to forward the modified Enter keys pi uses: + +```json +{ + "actions": [ + { + "command": { "action": "sendInput", "input": "\u001b[13;2u" }, + "keys": "shift+enter" + }, + { + "command": { "action": "sendInput", "input": "\u001b[13;3u" }, + "keys": "alt+enter" + } + ] +} +``` + +- `Shift+Enter` inserts a new line. +- Windows Terminal binds `Alt+Enter` to fullscreen by default. That prevents pi from receiving `Alt+Enter` for follow-up queueing. +- Remapping `Alt+Enter` to `sendInput` forwards the real key chord to pi instead. + +If you already have an `actions` array, add the objects to it. If the old fullscreen behavior persists, fully close and reopen Windows Terminal. + +## xfce4-terminal, terminator + +These terminals have limited escape sequence support. Modified Enter keys like `Ctrl+Enter` and `Shift+Enter` cannot be distinguished from plain `Enter`, preventing custom keybindings such as `submit: ["ctrl+enter"]` from working. + +For the best experience, use a terminal that supports the Kitty keyboard protocol: +- [Kitty](https://sw.kovidgoyal.net/kitty/) +- [Ghostty](https://ghostty.org/) +- [WezTerm](https://wezfurlong.org/wezterm/) +- [iTerm2](https://iterm2.com/) +- [Alacritty](https://github.com/alacritty/alacritty) (requires compilation with Kitty protocol support) + +## IntelliJ IDEA (Integrated Terminal) + +The built-in terminal has limited escape sequence support. Shift+Enter cannot be distinguished from Enter in IntelliJ's terminal. + +If you want the hardware cursor visible, set `PI_HARDWARE_CURSOR=1` before running pi (disabled by default for compatibility). + +Consider using a dedicated terminal emulator for the best experience. diff --git a/docs/termux.md b/docs/termux.md new file mode 100644 index 0000000..aba6e29 --- /dev/null +++ b/docs/termux.md @@ -0,0 +1,127 @@ +# Termux (Android) Setup + +Pi runs on Android via [Termux](https://termux.dev/), a terminal emulator and Linux environment for Android. + +## Prerequisites + +1. Install [Termux](https://github.com/termux/termux-app#installation) from GitHub or F-Droid (not Google Play, that version is deprecated) +2. Install [Termux:API](https://github.com/termux/termux-api#installation) from GitHub or F-Droid for clipboard and other device integrations + +## Installation + +```bash +# Update packages +pkg update && pkg upgrade + +# Install dependencies +pkg install nodejs termux-api git + +# Install pi +npm install -g --ignore-scripts @earendil-works/pi-coding-agent + +# Create config directory +mkdir -p ~/.pi/agent + +# Run pi +pi +``` + +## Clipboard Support + +Clipboard operations use `termux-clipboard-set` and `termux-clipboard-get` when running in Termux. The Termux:API app must be installed for these to work. + +Image clipboard is not supported on Termux (the `ctrl+v` image paste feature will not work). + +## Example AGENTS.md for Termux + +Create `~/.pi/agent/AGENTS.md` to help the agent understand the Termux environment: + +````markdown +# Agent Environment: Termux on Android + +## Location +- **OS**: Android (Termux terminal emulator) +- **Home**: `/data/data/com.termux/files/home` +- **Prefix**: `/data/data/com.termux/files/usr` +- **Shared storage**: `/storage/emulated/0` (Downloads, Documents, etc.) + +## Opening URLs +```bash +termux-open-url "https://example.com" +``` + +## Opening Files +```bash +termux-open file.pdf # Opens with default app +termux-open --chooser image.jpg # Choose app +``` + +## Clipboard +```bash +termux-clipboard-set "text" # Copy +termux-clipboard-get # Paste +``` + +## Notifications +```bash +termux-notification -t "Title" -c "Content" +``` + +## Device Info +```bash +termux-battery-status # Battery info +termux-wifi-connectioninfo # WiFi info +termux-telephony-deviceinfo # Device info +``` + +## Sharing +```bash +termux-share -a send file.txt # Share file +``` + +## Other Useful Commands +```bash +termux-toast "message" # Quick toast popup +termux-vibrate # Vibrate device +termux-tts-speak "hello" # Text to speech +termux-camera-photo out.jpg # Take photo +``` + +## Notes +- Termux:API app must be installed for `termux-*` commands +- Use `pkg install termux-api` for the command-line tools +- Storage permission needed for `/storage/emulated/0` access +```` + +## Limitations + +- **No image clipboard**: Termux clipboard API only supports text +- **No native binaries**: Some optional native dependencies (like the clipboard module) are unavailable on Android ARM64 and are skipped during installation +- **Storage access**: To access files in `/storage/emulated/0` (Downloads, etc.), run `termux-setup-storage` once to grant permissions + +## Troubleshooting + +### Clipboard not working + +Ensure both apps are installed: +1. Termux (from GitHub or F-Droid) +2. Termux:API (from GitHub or F-Droid) + +Then install the CLI tools: +```bash +pkg install termux-api +``` + +### Permission denied for shared storage + +Run once to grant storage permissions: +```bash +termux-setup-storage +``` + +### Node.js installation issues + +If npm fails, try clearing the cache: +```bash +npm cache clean --force +``` diff --git a/docs/themes.md b/docs/themes.md new file mode 100644 index 0000000..8bb8695 --- /dev/null +++ b/docs/themes.md @@ -0,0 +1,297 @@ +> pi can create themes. Ask it to build one for your setup. + +# Themes + +Themes are JSON files that define colors for the TUI. + +## Table of Contents + +- [Locations](#locations) +- [Selecting a Theme](#selecting-a-theme) +- [Creating a Custom Theme](#creating-a-custom-theme) +- [Theme Format](#theme-format) +- [Color Tokens](#color-tokens) +- [Color Values](#color-values) +- [Tips](#tips) + +## Locations + +Pi loads themes from: + +- Built-in: `dark`, `light` +- Global: `~/.pi/agent/themes/*.json` +- Project: `.pi/themes/*.json` (only after the project is trusted) +- Packages: `themes/` directories or `pi.themes` entries in `package.json` +- Settings: `themes` array with files or directories +- CLI: `--theme ` (repeatable) + +Disable discovery with `--no-themes`. + +## Selecting a Theme + +Select a theme via `/settings` or in `settings.json`: + +```json +{ + "theme": "my-theme" +} +``` + +On first run, pi detects your terminal background and defaults to `dark` or `light`. + +## Creating a Custom Theme + +1. Create a theme file: + +```bash +mkdir -p ~/.pi/agent/themes +vim ~/.pi/agent/themes/my-theme.json +``` + +2. Define the theme with all required colors (see [Color Tokens](#color-tokens)): + +```json +{ + "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "name": "my-theme", + "vars": { + "primary": "#00aaff", + "secondary": 242 + }, + "colors": { + "accent": "primary", + "border": "primary", + "borderAccent": "#00ffff", + "borderMuted": "secondary", + "success": "#00ff00", + "error": "#ff0000", + "warning": "#ffff00", + "muted": "secondary", + "dim": 240, + "text": "", + "thinkingText": "secondary", + "selectedBg": "#2d2d30", + "userMessageBg": "#2d2d30", + "userMessageText": "", + "customMessageBg": "#2d2d30", + "customMessageText": "", + "customMessageLabel": "primary", + "toolPendingBg": "#1e1e2e", + "toolSuccessBg": "#1e2e1e", + "toolErrorBg": "#2e1e1e", + "toolTitle": "primary", + "toolOutput": "", + "mdHeading": "#ffaa00", + "mdLink": "primary", + "mdLinkUrl": "secondary", + "mdCode": "#00ffff", + "mdCodeBlock": "", + "mdCodeBlockBorder": "secondary", + "mdQuote": "secondary", + "mdQuoteBorder": "secondary", + "mdHr": "secondary", + "mdListBullet": "#00ffff", + "toolDiffAdded": "#00ff00", + "toolDiffRemoved": "#ff0000", + "toolDiffContext": "secondary", + "syntaxComment": "secondary", + "syntaxKeyword": "primary", + "syntaxFunction": "#00aaff", + "syntaxVariable": "#ffaa00", + "syntaxString": "#00ff00", + "syntaxNumber": "#ff00ff", + "syntaxType": "#00aaff", + "syntaxOperator": "primary", + "syntaxPunctuation": "secondary", + "thinkingOff": "secondary", + "thinkingMinimal": "primary", + "thinkingLow": "#00aaff", + "thinkingMedium": "#00ffff", + "thinkingHigh": "#ff00ff", + "thinkingXhigh": "#ff0000", + "thinkingMax": "#ff0088", + "bashMode": "#ffaa00" + } +} +``` + +3. Select the theme via `/settings`. + +**Hot reload:** When you edit the currently active custom theme file, pi reloads it automatically for immediate visual feedback. + +## Theme Format + +```json +{ + "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "name": "my-theme", + "vars": { + "blue": "#0066cc", + "gray": 242 + }, + "colors": { + "accent": "blue", + "muted": "gray", + "text": "", + ... + } +} +``` + +- `name` is required, must be unique, and must not contain `/`. +- `vars` is optional. Define reusable colors here, then reference them in `colors`. +- `colors` must define all 51 required tokens. `thinkingMax` is optional and falls back to `thinkingXhigh`. + +The `$schema` field enables editor auto-completion and validation. + +## Color Tokens + +Every theme must define all 51 required color tokens. `thinkingMax` is optional for compatibility with existing themes; when omitted, it uses `thinkingXhigh`. + +### Core UI (11 colors) + +| Token | Purpose | +|-------|---------| +| `accent` | Primary accent (logo, selected items, cursor) | +| `border` | Normal borders | +| `borderAccent` | Highlighted borders | +| `borderMuted` | Subtle borders (editor) | +| `success` | Success states | +| `error` | Error states | +| `warning` | Warning states | +| `muted` | Secondary text | +| `dim` | Tertiary text | +| `text` | Default text (usually `""`) | +| `thinkingText` | Thinking block text | + +### Backgrounds & Content (11 colors) + +| Token | Purpose | +|-------|---------| +| `selectedBg` | Selected line background | +| `userMessageBg` | User message background | +| `userMessageText` | User message text | +| `customMessageBg` | Extension message background | +| `customMessageText` | Extension message text | +| `customMessageLabel` | Extension message label | +| `toolPendingBg` | Tool box (pending) | +| `toolSuccessBg` | Tool box (success) | +| `toolErrorBg` | Tool box (error) | +| `toolTitle` | Tool title | +| `toolOutput` | Tool output text | + +### Markdown (10 colors) + +| Token | Purpose | +|-------|---------| +| `mdHeading` | Headings | +| `mdLink` | Link text | +| `mdLinkUrl` | Link URL | +| `mdCode` | Inline code | +| `mdCodeBlock` | Code block content | +| `mdCodeBlockBorder` | Code block fences | +| `mdQuote` | Blockquote text | +| `mdQuoteBorder` | Blockquote border | +| `mdHr` | Horizontal rule | +| `mdListBullet` | List bullets | + +### Tool Diffs (3 colors) + +| Token | Purpose | +|-------|---------| +| `toolDiffAdded` | Added lines | +| `toolDiffRemoved` | Removed lines | +| `toolDiffContext` | Context lines | + +### Syntax Highlighting (9 colors) + +| Token | Purpose | +|-------|---------| +| `syntaxComment` | Comments | +| `syntaxKeyword` | Keywords | +| `syntaxFunction` | Function names | +| `syntaxVariable` | Variables | +| `syntaxString` | Strings | +| `syntaxNumber` | Numbers | +| `syntaxType` | Types | +| `syntaxOperator` | Operators | +| `syntaxPunctuation` | Punctuation | + +### Thinking Level Borders (6 required, 1 optional) + +Editor border colors indicating thinking level (visual hierarchy from subtle to prominent): + +| Token | Purpose | +|-------|---------| +| `thinkingOff` | Thinking off | +| `thinkingMinimal` | Minimal thinking | +| `thinkingLow` | Low thinking | +| `thinkingMedium` | Medium thinking | +| `thinkingHigh` | High thinking | +| `thinkingXhigh` | Extra high thinking | +| `thinkingMax` | Maximum thinking; optional, falls back to `thinkingXhigh` | + +### Bash Mode (1 color) + +| Token | Purpose | +|-------|---------| +| `bashMode` | Editor border in bash mode (`!` prefix) | + +### HTML Export (optional) + +The `export` section controls colors for `/export` HTML output. If omitted, colors are derived from `userMessageBg`. + +```json +{ + "export": { + "pageBg": "#18181e", + "cardBg": "#1e1e24", + "infoBg": "#3c3728" + } +} +``` + +## Color Values + +Four formats are supported: + +| Format | Example | Description | +|--------|---------|-------------| +| Hex | `"#ff0000"` | 6-digit hex RGB | +| 256-color | `39` | xterm 256-color palette index (0-255) | +| Variable | `"primary"` | Reference to a `vars` entry | +| Default | `""` | Terminal's default color | + +### 256-Color Palette + +- `0-15`: Basic ANSI colors (terminal-dependent) +- `16-231`: 6×6×6 RGB cube (`16 + 36×R + 6×G + B` where R,G,B are 0-5) +- `232-255`: Grayscale ramp + +### Terminal Compatibility + +Pi uses 24-bit RGB colors. Most modern terminals support this (iTerm2, Kitty, WezTerm, Windows Terminal, VS Code). For older terminals with only 256-color support, pi falls back to the nearest approximation. + +Check truecolor support: + +```bash +echo $COLORTERM # Should output "truecolor" or "24bit" +``` + +## Tips + +**Dark terminals:** Use bright, saturated colors with higher contrast. + +**Light terminals:** Use darker, muted colors with lower contrast. + +**Color harmony:** Start with a base palette (Nord, Gruvbox, Tokyo Night), define it in `vars`, and reference consistently. + +**Testing:** Check your theme with different message types, tool states, markdown content, and long wrapped text. + +**VS Code:** Set `terminal.integrated.minimumContrastRatio` to `1` for accurate colors. + +## Examples + +See the built-in themes: +- [dark.json](../src/modes/interactive/theme/dark.json) +- [light.json](../src/modes/interactive/theme/light.json) diff --git a/docs/tmux.md b/docs/tmux.md new file mode 100644 index 0000000..0083b5f --- /dev/null +++ b/docs/tmux.md @@ -0,0 +1,63 @@ +# tmux Setup + +Pi works inside tmux, but tmux strips modifier information from certain keys by default. Without configuration, `Shift+Enter` and `Ctrl+Enter` are usually indistinguishable from plain `Enter`. + +## Recommended Configuration + +Add to `~/.tmux.conf`: + +```tmux +set -g extended-keys on +set -g extended-keys-format csi-u +``` + +Then restart tmux fully: + +```bash +tmux kill-server +tmux +``` + +Pi requests extended key reporting automatically when Kitty keyboard protocol is not available. With `extended-keys-format csi-u`, tmux forwards modified keys in CSI-u format, which is the most reliable configuration. The `extended-keys-format` option requires tmux 3.5 or later. + +## Why `csi-u` Is Recommended + +With only: + +```tmux +set -g extended-keys on +``` + +tmux defaults to `extended-keys-format xterm`. When an application requests extended key reporting, modified keys are forwarded in xterm `modifyOtherKeys` format such as: + +- `Ctrl+C` → `\x1b[27;5;99~` +- `Ctrl+D` → `\x1b[27;5;100~` +- `Ctrl+Enter` → `\x1b[27;5;13~` + +With `extended-keys-format csi-u`, the same keys are forwarded as: + +- `Ctrl+C` → `\x1b[99;5u` +- `Ctrl+D` → `\x1b[100;5u` +- `Ctrl+Enter` → `\x1b[13;5u` + +Pi supports both formats, but `csi-u` is the recommended tmux setup. + +## What This Fixes + +Without tmux extended keys, modified Enter keys collapse to legacy sequences: + +| Key | Without extkeys | With `csi-u` | +|-----|-----------------|--------------| +| Enter | `\r` | `\r` | +| Shift+Enter | `\r` | `\x1b[13;2u` | +| Ctrl+Enter | `\r` | `\x1b[13;5u` | +| Alt/Option+Enter | `\x1b\r` | `\x1b[13;3u` | + +This affects the default keybindings (`Enter` to submit, `Shift+Enter` for newline) and any custom keybindings using modified Enter. + +## Requirements + +- tmux 3.5 or later for `extended-keys-format csi-u` (run `tmux -V` to check) +- A terminal emulator that supports extended keys (Ghostty, Kitty, iTerm2, WezTerm, Windows Terminal) + +With tmux 3.2 through 3.4, omit `extended-keys-format csi-u`; Pi still supports tmux's default xterm `modifyOtherKeys` format. diff --git a/docs/tui.md b/docs/tui.md new file mode 100644 index 0000000..d9f7892 --- /dev/null +++ b/docs/tui.md @@ -0,0 +1,942 @@ +> pi can create TUI components. Ask it to build one for your use case. + +# TUI Components + +Extensions and custom tools can render custom TUI components for interactive user interfaces. This page covers the component system and available building blocks. + +**Source:** [`@earendil-works/pi-tui`](https://github.com/earendil-works/pi-mono/tree/main/packages/tui) + +## Component Interface + +All components implement: + +```typescript +interface Component { + render(width: number): string[]; + handleInput?(data: string): void; + wantsKeyRelease?: boolean; + invalidate(): void; +} +``` + +| Method | Description | +|--------|-------------| +| `render(width)` | Return array of strings (one per line). Each line **must not exceed `width`**. | +| `handleInput?(data)` | Receive keyboard input when component has focus. | +| `wantsKeyRelease?` | If true, component receives key release events (Kitty protocol). Default: false. | +| `invalidate()` | Clear cached render state. Called on theme changes. | + +The TUI appends a full SGR reset and OSC 8 reset at the end of each rendered line. Styles do not carry across lines. If you emit multi-line text with styling, reapply styles per line or use `wrapTextWithAnsi()` so styles are preserved for each wrapped line. + +## Focusable Interface (IME Support) + +Components that display a text cursor and need IME (Input Method Editor) support should implement the `Focusable` interface: + +```typescript +import { CURSOR_MARKER, type Component, type Focusable } from "@earendil-works/pi-tui"; + +class MyInput implements Component, Focusable { + focused: boolean = false; // Set by TUI when focus changes + + render(width: number): string[] { + const marker = this.focused ? CURSOR_MARKER : ""; + // Emit marker right before the fake cursor + return [`> ${beforeCursor}${marker}\x1b[7m${atCursor}\x1b[27m${afterCursor}`]; + } +} +``` + +When a `Focusable` component has focus, TUI: +1. Sets `focused = true` on the component +2. Scans rendered output for `CURSOR_MARKER` (a zero-width APC escape sequence) +3. Positions the hardware terminal cursor at that location +4. Shows the hardware cursor only when `showHardwareCursor` is enabled + +The cursor remains hidden by default. This keeps the fake cursor rendering, while still positioning the hardware cursor for terminals that track IME candidate windows with hidden cursors. Some terminals require a visible hardware cursor for IME positioning; enable it with `showHardwareCursor`, `setShowHardwareCursor(true)`, or `PI_HARDWARE_CURSOR=1`. The `Editor` and `Input` built-in components already implement this interface. + +### Container Components with Embedded Inputs + +When a container component (dialog, selector, etc.) contains an `Input` or `Editor` child, the container must implement `Focusable` and propagate the focus state to the child. Otherwise, the hardware cursor won't be positioned correctly for IME input. + +```typescript +import { Container, type Focusable, Input } from "@earendil-works/pi-tui"; + +class SearchDialog extends Container implements Focusable { + private searchInput: Input; + + // Focusable implementation - propagate to child input for IME cursor positioning + private _focused = false; + get focused(): boolean { + return this._focused; + } + set focused(value: boolean) { + this._focused = value; + this.searchInput.focused = value; + } + + constructor() { + super(); + this.searchInput = new Input(); + this.addChild(this.searchInput); + } +} +``` + +Without this propagation, typing with an IME (Chinese, Japanese, Korean, etc.) will show the candidate window in the wrong position on screen. + +## Using Components + +**In extensions** via `ctx.ui.custom()`: + +```typescript +pi.on("session_start", async (_event, ctx) => { + const result = await ctx.ui.custom((tui, theme, keybindings, done) => + new MyComponent({ + theme, + keybindings, + onChange: () => tui.requestRender(), + onSelect: (value) => done(value), + onCancel: () => done(null), + }) + ); +}); +``` + +**In custom tools** via `ctx.ui.custom()`: + +```typescript +async execute(toolCallId, params, signal, onUpdate, ctx) { + const result = await ctx.ui.custom((tui, theme, keybindings, done) => + new MyComponent({ + theme, + keybindings, + onChange: () => tui.requestRender(), + onSelect: (value) => done(value), + onCancel: () => done(null), + }) + ); + // Use result... +} +``` + +## Overlays + +Overlays render components on top of existing content without clearing the screen. Pass `{ overlay: true }` to `ctx.ui.custom()`: + +```typescript +const result = await ctx.ui.custom( + (tui, theme, keybindings, done) => new MyDialog({ onClose: done }), + { overlay: true } +); +``` + +For positioning and sizing, use `overlayOptions`: + +```typescript +const result = await ctx.ui.custom( + (tui, theme, keybindings, done) => new SidePanel({ onClose: done }), + { + overlay: true, + overlayOptions: { + // Size: number or percentage string + width: "50%", // 50% of terminal width + minWidth: 40, // minimum 40 columns + maxHeight: "80%", // max 80% of terminal height + + // Position: anchor-based (default: "center") + anchor: "right-center", // 9 positions: center, top-left, top-center, etc. + offsetX: -2, // offset from anchor + offsetY: 0, + + // Or percentage/absolute positioning + row: "25%", // 25% from top + col: 10, // column 10 + + // Margins + margin: 2, // all sides, or { top, right, bottom, left } + + // Responsive: hide on narrow terminals + visible: (termWidth, termHeight) => termWidth >= 80, + }, + // Get handle for programmatic focus and visibility control + onHandle: (handle) => { + // handle.focus() - focus this overlay and bring it to the visual front + // handle.unfocus() - release input to normal fallback + // handle.unfocus({ target }) - release input to a specific component or null + // handle.setHidden(true/false) - toggle visibility + // handle.hide() - permanently remove + }, + } +); +``` + +### Overlay Focus + +A focused visible overlay keeps input ownership across temporary non-overlay UI. If an overlay opens another `ctx.ui.custom()` component without `{ overlay: true }`, that replacement UI receives input while it is active; when it closes, the focused overlay can reclaim input. + +Use `handle.unfocus()` when a visible overlay should stop owning input and let TUI fall back to another visible capturing overlay or the previous focus target. Use `handle.unfocus({ target })` when a specific component should receive input while the overlay stays visible. Passing `{ target: null }` intentionally leaves no focused component until focus is set again. + +### Overlay Lifecycle + +Overlay components are disposed when closed. Don't reuse references - create fresh instances: + +```typescript +// Wrong - stale reference +let menu: MenuComponent; +await ctx.ui.custom((_, __, ___, done) => { + menu = new MenuComponent(done); + return menu; +}, { overlay: true }); +setActiveComponent(menu); // Disposed + +// Correct - re-call to re-show +const showMenu = () => ctx.ui.custom((_, __, ___, done) => + new MenuComponent(done), { overlay: true }); + +await showMenu(); // First show +await showMenu(); // "Back" = just call again +``` + +See [overlay-qa-tests.ts](../examples/extensions/overlay-qa-tests.ts) for comprehensive examples covering anchors, margins, stacking, responsive visibility, and animation. + +## Built-in Components + +Import from `@earendil-works/pi-tui`: + +```typescript +import { Text, Box, Container, Spacer, Markdown } from "@earendil-works/pi-tui"; +``` + +### Text + +Multi-line text with word wrapping. + +```typescript +const text = new Text( + "Hello World", // content + 1, // paddingX (default: 1) + 1, // paddingY (default: 1) + (s) => bgGray(s) // optional background function +); +text.setText("Updated"); +``` + +### Box + +Container with padding and background color. + +```typescript +const box = new Box( + 1, // paddingX + 1, // paddingY + (s) => bgGray(s) // background function +); +box.addChild(new Text("Content", 0, 0)); +box.setBgFn((s) => bgBlue(s)); +``` + +### Container + +Groups child components vertically. + +```typescript +const container = new Container(); +container.addChild(component1); +container.addChild(component2); +container.removeChild(component1); +``` + +### Spacer + +Empty vertical space. + +```typescript +const spacer = new Spacer(2); // 2 empty lines +``` + +### Markdown + +Renders markdown with syntax highlighting. + +```typescript +const md = new Markdown( + "# Title\n\nSome **bold** text", + 1, // paddingX + 1, // paddingY + theme // MarkdownTheme (see below) +); +md.setText("Updated markdown"); +``` + +### Image + +Renders images in supported terminals (Kitty, iTerm2, Ghostty, WezTerm, Warp). + +```typescript +const image = new Image( + base64Data, // base64-encoded image + "image/png", // MIME type + theme, // ImageTheme + { maxWidthCells: 80, maxHeightCells: 24 } +); +``` + +## Keyboard Input + +Use `matchesKey()` for key detection: + +```typescript +import { matchesKey, Key } from "@earendil-works/pi-tui"; + +handleInput(data: string) { + if (matchesKey(data, Key.up)) { + this.selectedIndex--; + } else if (matchesKey(data, Key.enter)) { + this.onSelect?.(this.selectedIndex); + } else if (matchesKey(data, Key.escape)) { + this.onCancel?.(); + } else if (matchesKey(data, Key.ctrl("c"))) { + // Ctrl+C + } +} +``` + +**Key identifiers** (use `Key.*` for autocomplete, or string literals): +- Basic keys: `Key.enter`, `Key.escape`, `Key.tab`, `Key.space`, `Key.backspace`, `Key.delete`, `Key.home`, `Key.end` +- Arrow keys: `Key.up`, `Key.down`, `Key.left`, `Key.right` +- With modifiers: `Key.ctrl("c")`, `Key.shift("tab")`, `Key.alt("left")`, `Key.ctrlShift("p")` +- String format also works: `"enter"`, `"ctrl+c"`, `"shift+tab"`, `"ctrl+shift+p"` + +## Line Width + +**Critical:** Each line from `render()` must not exceed the `width` parameter. + +```typescript +import { visibleWidth, truncateToWidth } from "@earendil-works/pi-tui"; + +render(width: number): string[] { + // Truncate long lines + return [truncateToWidth(this.text, width)]; +} +``` + +Utilities: +- `visibleWidth(str)` - Get display width (ignores ANSI codes) +- `truncateToWidth(str, width, ellipsis?)` - Truncate with optional ellipsis +- `wrapTextWithAnsi(str, width)` - Word wrap preserving ANSI codes + +## Creating Custom Components + +Example: Interactive selector + +```typescript +import { + matchesKey, Key, + truncateToWidth, visibleWidth +} from "@earendil-works/pi-tui"; + +class MySelector { + private items: string[]; + private selected = 0; + private cachedWidth?: number; + private cachedLines?: string[]; + + public onSelect?: (item: string) => void; + public onCancel?: () => void; + + constructor(items: string[]) { + this.items = items; + } + + handleInput(data: string): void { + if (matchesKey(data, Key.up) && this.selected > 0) { + this.selected--; + this.invalidate(); + } else if (matchesKey(data, Key.down) && this.selected < this.items.length - 1) { + this.selected++; + this.invalidate(); + } else if (matchesKey(data, Key.enter)) { + this.onSelect?.(this.items[this.selected]); + } else if (matchesKey(data, Key.escape)) { + this.onCancel?.(); + } + } + + render(width: number): string[] { + if (this.cachedLines && this.cachedWidth === width) { + return this.cachedLines; + } + + this.cachedLines = this.items.map((item, i) => { + const prefix = i === this.selected ? "> " : " "; + return truncateToWidth(prefix + item, width); + }); + this.cachedWidth = width; + return this.cachedLines; + } + + invalidate(): void { + this.cachedWidth = undefined; + this.cachedLines = undefined; + } +} +``` + +Usage in an extension: + +```typescript +pi.registerCommand("pick", { + description: "Pick an item", + handler: async (_args, ctx) => { + const items = ["Option A", "Option B", "Option C"]; + const selected = await ctx.ui.custom((tui, _theme, _keybindings, done) => { + const selector = new MySelector(items); + selector.onSelect = done; + selector.onCancel = () => done(null); + + return { + render: (width) => selector.render(width), + handleInput: (data) => { + selector.handleInput(data); + tui.requestRender(); + }, + invalidate: () => selector.invalidate(), + }; + }); + + if (selected !== null) { + ctx.ui.notify(`Selected: ${selected}`, "info"); + } + } +}); +``` + +## Theming + +Components accept theme objects for styling. + +**In `renderCall`/`renderResult`**, use the `theme` parameter: + +```typescript +renderResult(result, options, theme, context) { + // Use theme.fg() for foreground colors + return new Text(theme.fg("success", "Done!"), 0, 0); + + // Use theme.bg() for background colors + const styled = theme.bg("toolPendingBg", theme.fg("accent", "text")); +} +``` + +**Foreground colors** (`theme.fg(color, text)`): + +| Category | Colors | +|----------|--------| +| General | `text`, `accent`, `muted`, `dim` | +| Status | `success`, `error`, `warning` | +| Borders | `border`, `borderAccent`, `borderMuted` | +| Messages | `userMessageText`, `customMessageText`, `customMessageLabel` | +| Tools | `toolTitle`, `toolOutput` | +| Diffs | `toolDiffAdded`, `toolDiffRemoved`, `toolDiffContext` | +| Markdown | `mdHeading`, `mdLink`, `mdLinkUrl`, `mdCode`, `mdCodeBlock`, `mdCodeBlockBorder`, `mdQuote`, `mdQuoteBorder`, `mdHr`, `mdListBullet` | +| Syntax | `syntaxComment`, `syntaxKeyword`, `syntaxFunction`, `syntaxVariable`, `syntaxString`, `syntaxNumber`, `syntaxType`, `syntaxOperator`, `syntaxPunctuation` | +| Thinking | `thinkingOff`, `thinkingMinimal`, `thinkingLow`, `thinkingMedium`, `thinkingHigh`, `thinkingXhigh`, `thinkingMax` | +| Modes | `bashMode` | + +**Background colors** (`theme.bg(color, text)`): + +`selectedBg`, `userMessageBg`, `customMessageBg`, `toolPendingBg`, `toolSuccessBg`, `toolErrorBg` + +**For Markdown**, use `getMarkdownTheme()`: + +```typescript +import { getMarkdownTheme } from "@earendil-works/pi-coding-agent"; +import { Markdown } from "@earendil-works/pi-tui"; + +renderResult(result, options, theme, context) { + const mdTheme = getMarkdownTheme(); + return new Markdown(result.details.markdown, 0, 0, mdTheme); +} +``` + +**For custom components**, define your own theme interface: + +```typescript +interface MyTheme { + selected: (s: string) => string; + normal: (s: string) => string; +} +``` + +## Debug logging + +Set `PI_TUI_WRITE_LOG` to capture the raw ANSI stream written to stdout. + +```bash +PI_TUI_WRITE_LOG=/tmp/tui-ansi.log npx tsx packages/tui/test/chat-simple.ts +``` + +## Performance + +Cache rendered output when possible: + +```typescript +class CachedComponent { + private cachedWidth?: number; + private cachedLines?: string[]; + + render(width: number): string[] { + if (this.cachedLines && this.cachedWidth === width) { + return this.cachedLines; + } + // ... compute lines ... + this.cachedWidth = width; + this.cachedLines = lines; + return lines; + } + + invalidate(): void { + this.cachedWidth = undefined; + this.cachedLines = undefined; + } +} +``` + +Call `invalidate()` when state changes, then use the injected `tui.requestRender()` to trigger re-render. + +## Invalidation and Theme Changes + +When the theme changes, the TUI calls `invalidate()` on all components to clear their caches. Components must properly implement `invalidate()` to ensure theme changes take effect. + +### The Problem + +If a component pre-bakes theme colors into strings (via `theme.fg()`, `theme.bg()`, etc.) and caches them, the cached strings contain ANSI escape codes from the old theme. Simply clearing the render cache isn't enough if the component stores the themed content separately. + +**Wrong approach** (theme colors won't update): + +```typescript +class BadComponent extends Container { + private content: Text; + + constructor(message: string, theme: Theme) { + super(); + // Pre-baked theme colors stored in Text component + this.content = new Text(theme.fg("accent", message), 1, 0); + this.addChild(this.content); + } + // No invalidate override - parent's invalidate only clears + // child render caches, not the pre-baked content +} +``` + +### The Solution + +Components that build content with theme colors must rebuild that content when `invalidate()` is called: + +```typescript +class GoodComponent extends Container { + private message: string; + private content: Text; + + constructor(message: string) { + super(); + this.message = message; + this.content = new Text("", 1, 0); + this.addChild(this.content); + this.updateDisplay(); + } + + private updateDisplay(): void { + // Rebuild content with current theme + this.content.setText(theme.fg("accent", this.message)); + } + + override invalidate(): void { + super.invalidate(); // Clear child caches + this.updateDisplay(); // Rebuild with new theme + } +} +``` + +### Pattern: Rebuild on Invalidate + +For components with complex content: + +```typescript +class ComplexComponent extends Container { + private data: SomeData; + + constructor(data: SomeData) { + super(); + this.data = data; + this.rebuild(); + } + + private rebuild(): void { + this.clear(); // Remove all children + + // Build UI with current theme + this.addChild(new Text(theme.fg("accent", theme.bold("Title")), 1, 0)); + this.addChild(new Spacer(1)); + + for (const item of this.data.items) { + const color = item.active ? "success" : "muted"; + this.addChild(new Text(theme.fg(color, item.label), 1, 0)); + } + } + + override invalidate(): void { + super.invalidate(); + this.rebuild(); + } +} +``` + +### When This Matters + +This pattern is needed when: + +1. **Pre-baking theme colors** - Using `theme.fg()` or `theme.bg()` to create styled strings stored in child components +2. **Syntax highlighting** - Using `highlightCode()` which applies theme-based syntax colors +3. **Complex layouts** - Building child component trees that embed theme colors + +This pattern is NOT needed when: + +1. **Using theme callbacks** - Passing functions like `(text) => theme.fg("accent", text)` that are called during render +2. **Simple containers** - Just grouping other components without adding themed content +3. **Stateless render** - Computing themed output fresh in every `render()` call (no caching) + +## Common Patterns + +These patterns cover the most common UI needs in extensions. **Copy these patterns instead of building from scratch.** + +### Pattern 1: Selection Dialog (SelectList) + +For letting users pick from a list of options. Use `SelectList` from `@earendil-works/pi-tui` with `DynamicBorder` for framing. + +```typescript +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { DynamicBorder } from "@earendil-works/pi-coding-agent"; +import { Container, type SelectItem, SelectList, Text } from "@earendil-works/pi-tui"; + +pi.registerCommand("pick", { + handler: async (_args, ctx) => { + const items: SelectItem[] = [ + { value: "opt1", label: "Option 1", description: "First option" }, + { value: "opt2", label: "Option 2", description: "Second option" }, + { value: "opt3", label: "Option 3" }, // description is optional + ]; + + const result = await ctx.ui.custom((tui, theme, _kb, done) => { + const container = new Container(); + + // Top border + container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s))); + + // Title + container.addChild(new Text(theme.fg("accent", theme.bold("Pick an Option")), 1, 0)); + + // SelectList with theme + const selectList = new SelectList(items, Math.min(items.length, 10), { + selectedPrefix: (t) => theme.fg("accent", t), + selectedText: (t) => theme.fg("accent", t), + description: (t) => theme.fg("muted", t), + scrollInfo: (t) => theme.fg("dim", t), + noMatch: (t) => theme.fg("warning", t), + }); + selectList.onSelect = (item) => done(item.value); + selectList.onCancel = () => done(null); + container.addChild(selectList); + + // Help text + container.addChild(new Text(theme.fg("dim", "↑↓ navigate • enter select • esc cancel"), 1, 0)); + + // Bottom border + container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s))); + + return { + render: (w) => container.render(w), + invalidate: () => container.invalidate(), + handleInput: (data) => { selectList.handleInput(data); tui.requestRender(); }, + }; + }); + + if (result) { + ctx.ui.notify(`Selected: ${result}`, "info"); + } + }, +}); +``` + +**Examples:** [preset.ts](../examples/extensions/preset.ts), [tools.ts](../examples/extensions/tools.ts) + +### Pattern 2: Async Operation with Cancel (BorderedLoader) + +For operations that take time and should be cancellable. `BorderedLoader` shows a spinner and handles escape to cancel. + +```typescript +import { BorderedLoader } from "@earendil-works/pi-coding-agent"; + +pi.registerCommand("fetch", { + handler: async (_args, ctx) => { + const result = await ctx.ui.custom((tui, theme, _kb, done) => { + const loader = new BorderedLoader(tui, theme, "Fetching data..."); + loader.onAbort = () => done(null); + + // Do async work + fetchData(loader.signal) + .then((data) => done(data)) + .catch(() => done(null)); + + return loader; + }); + + if (result === null) { + ctx.ui.notify("Cancelled", "info"); + } else { + ctx.ui.setEditorText(result); + } + }, +}); +``` + +**Examples:** [qna.ts](../examples/extensions/qna.ts), [handoff.ts](../examples/extensions/handoff.ts) + +### Pattern 3: Settings/Toggles (SettingsList) + +For toggling multiple settings. Use `SettingsList` from `@earendil-works/pi-tui` with `getSettingsListTheme()`. + +```typescript +import { getSettingsListTheme } from "@earendil-works/pi-coding-agent"; +import { Container, type SettingItem, SettingsList, Text } from "@earendil-works/pi-tui"; + +pi.registerCommand("settings", { + handler: async (_args, ctx) => { + const items: SettingItem[] = [ + { id: "verbose", label: "Verbose mode", currentValue: "off", values: ["on", "off"] }, + { id: "color", label: "Color output", currentValue: "on", values: ["on", "off"] }, + ]; + + await ctx.ui.custom((_tui, theme, _kb, done) => { + const container = new Container(); + container.addChild(new Text(theme.fg("accent", theme.bold("Settings")), 1, 1)); + + const settingsList = new SettingsList( + items, + Math.min(items.length + 2, 15), + getSettingsListTheme(), + (id, newValue) => { + // Handle value change + ctx.ui.notify(`${id} = ${newValue}`, "info"); + }, + () => done(undefined), // On close + { enableSearch: true }, // Optional: enable fuzzy search by label + ); + container.addChild(settingsList); + + return { + render: (w) => container.render(w), + invalidate: () => container.invalidate(), + handleInput: (data) => settingsList.handleInput?.(data), + }; + }); + }, +}); +``` + +**Examples:** [tools.ts](../examples/extensions/tools.ts) + +### Pattern 4: Persistent Status Indicator + +Show status in the footer that persists across renders. Good for mode indicators. + +```typescript +// Set status (shown in footer) +ctx.ui.setStatus("my-ext", ctx.ui.theme.fg("accent", "● active")); + +// Clear status +ctx.ui.setStatus("my-ext", undefined); +``` + +**Examples:** [status-line.ts](../examples/extensions/status-line.ts), [plan-mode/index.ts](../examples/extensions/plan-mode/index.ts), [preset.ts](../examples/extensions/preset.ts) + +### Pattern 4b: Working Indicator Customization + +Customize the inline working indicator shown while pi is streaming a response. + +```typescript +// Static indicator +ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg("accent", "●")] }); + +// Custom animated indicator +ctx.ui.setWorkingIndicator({ + frames: [ + ctx.ui.theme.fg("dim", "·"), + ctx.ui.theme.fg("muted", "•"), + ctx.ui.theme.fg("accent", "●"), + ctx.ui.theme.fg("muted", "•"), + ], + intervalMs: 120, +}); + +// Hide the indicator entirely +ctx.ui.setWorkingIndicator({ frames: [] }); + +// Restore pi's default spinner +ctx.ui.setWorkingIndicator(); +``` + +This only affects the normal streaming working indicator. Compaction and retry loaders keep their built-in styling. Custom frames are rendered verbatim, so extensions must add their own colors when needed. + +**Examples:** [working-indicator.ts](../examples/extensions/working-indicator.ts) + +### Pattern 5: Widgets Above/Below Editor + +Show persistent content above or below the input editor. Good for todo lists, progress. + +```typescript +// Simple string array (above editor by default) +ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]); + +// Render below the editor +ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" }); + +// Or with theme +ctx.ui.setWidget("my-widget", (_tui, theme) => { + const lines = items.map((item, i) => + item.done + ? theme.fg("success", "✓ ") + theme.fg("muted", item.text) + : theme.fg("dim", "○ ") + item.text + ); + return { + render: () => lines, + invalidate: () => {}, + }; +}); + +// Clear +ctx.ui.setWidget("my-widget", undefined); +``` + +**Examples:** [plan-mode/index.ts](../examples/extensions/plan-mode/index.ts) + +### Pattern 6: Custom Footer + +Replace the footer. `footerData` exposes data not otherwise accessible to extensions. + +```typescript +ctx.ui.setFooter((tui, theme, footerData) => ({ + invalidate() {}, + render(width: number): string[] { + // footerData.getGitBranch(): string | null + // footerData.getExtensionStatuses(): ReadonlyMap + return [`${ctx.model?.id} (${footerData.getGitBranch() || "no git"})`]; + }, + dispose: footerData.onBranchChange(() => tui.requestRender()), // reactive +})); + +ctx.ui.setFooter(undefined); // restore default +``` + +Token stats available via `ctx.sessionManager.getBranch()` and `ctx.model`. + +**Examples:** [custom-footer.ts](../examples/extensions/custom-footer.ts) + +### Pattern 7: Custom Editor (vim mode, etc.) + +Replace the main input editor with a custom implementation. Useful for modal editing (vim), different keybindings (emacs), or specialized input handling. + +```typescript +import { CustomEditor, type ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { matchesKey, truncateToWidth } from "@earendil-works/pi-tui"; + +type Mode = "normal" | "insert"; + +class VimEditor extends CustomEditor { + private mode: Mode = "insert"; + + handleInput(data: string): void { + // Escape: switch to normal mode, or pass through for app handling + if (matchesKey(data, "escape")) { + if (this.mode === "insert") { + this.mode = "normal"; + return; + } + // In normal mode, escape aborts agent (handled by CustomEditor) + super.handleInput(data); + return; + } + + // Insert mode: pass everything to CustomEditor + if (this.mode === "insert") { + super.handleInput(data); + return; + } + + // Normal mode: vim-style navigation + switch (data) { + case "i": this.mode = "insert"; return; + case "h": super.handleInput("\x1b[D"); return; // Left + case "j": super.handleInput("\x1b[B"); return; // Down + case "k": super.handleInput("\x1b[A"); return; // Up + case "l": super.handleInput("\x1b[C"); return; // Right + } + // Pass unhandled keys to super (ctrl+c, etc.), but filter printable chars + if (data.length === 1 && data.charCodeAt(0) >= 32) return; + super.handleInput(data); + } + + render(width: number): string[] { + const lines = super.render(width); + // Add mode indicator to bottom border (use truncateToWidth for ANSI-safe truncation) + if (lines.length > 0) { + const label = this.mode === "normal" ? " NORMAL " : " INSERT "; + const lastLine = lines[lines.length - 1]!; + // Pass "" as ellipsis to avoid adding "..." when truncating + lines[lines.length - 1] = truncateToWidth(lastLine, width - label.length, "") + label; + } + return lines; + } +} + +export default function (pi: ExtensionAPI) { + pi.on("session_start", (_event, ctx) => { + // Factory receives the TUI, theme, and keybindings from the app + ctx.ui.setEditorComponent((tui, theme, keybindings) => + new VimEditor(tui, theme, keybindings) + ); + }); +} +``` + +**Key points:** + +- **Extend `CustomEditor`** (not base `Editor`) to get app keybindings (escape to abort, ctrl+d to exit, model switching, etc.) +- **Call `super.handleInput(data)`** for keys you don't handle +- **Factory pattern**: `setEditorComponent` receives a factory function that gets `tui`, `theme`, and `keybindings` +- **Pass `undefined`** to restore the default editor: `ctx.ui.setEditorComponent(undefined)` + +**Examples:** [modal-editor.ts](../examples/extensions/modal-editor.ts) + +## Key Rules + +1. **Always use theme from callback** - Don't import theme directly. Use `theme` from the `ctx.ui.custom((tui, theme, keybindings, done) => ...)` callback. + +2. **Always type DynamicBorder color param** - Write `(s: string) => theme.fg("accent", s)`, not `(s) => theme.fg("accent", s)`. + +3. **Call tui.requestRender() after state changes** - In `handleInput`, call `tui.requestRender()` after updating state. + +4. **Return the three-method object** - Custom components need `{ render, invalidate, handleInput }`. + +5. **Use existing components** - `SelectList`, `SettingsList`, `BorderedLoader` cover 90% of cases. Don't rebuild them. + +## Examples + +- **Selection UI**: [examples/extensions/preset.ts](../examples/extensions/preset.ts) - SelectList with DynamicBorder framing +- **Async with cancel**: [examples/extensions/qna.ts](../examples/extensions/qna.ts) - BorderedLoader for LLM calls +- **Settings toggles**: [examples/extensions/tools.ts](../examples/extensions/tools.ts) - SettingsList for tool enable/disable +- **Status indicators**: [examples/extensions/plan-mode/index.ts](../examples/extensions/plan-mode/index.ts) - setStatus and setWidget +- **Working indicator**: [examples/extensions/working-indicator.ts](../examples/extensions/working-indicator.ts) - setWorkingIndicator +- **Custom footer**: [examples/extensions/custom-footer.ts](../examples/extensions/custom-footer.ts) - setFooter with stats +- **Custom editor**: [examples/extensions/modal-editor.ts](../examples/extensions/modal-editor.ts) - Vim-like modal editing +- **Snake game**: [examples/extensions/snake.ts](../examples/extensions/snake.ts) - Full game with keyboard input, game loop +- **Custom tool rendering**: [examples/extensions/todo.ts](../examples/extensions/todo.ts) - renderCall and renderResult diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..8c0aa56 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,298 @@ +# Using Pi + +This page collects day-to-day usage details that do not fit on the quickstart page. + +## Interactive Mode + +

    Interactive Mode

    + +The interface has four main areas: + +- **Startup header** - shortcuts, loaded context files, prompt templates, skills, and extensions +- **Messages** - user messages, assistant responses, tool calls, tool results, notifications, errors, and extension UI +- **Editor** - where you type; border color indicates the current thinking level +- **Footer** - working directory, session name, token/cache usage, cost, context usage, and current model. Totals include assistant responses, usage reported by tools, and summary generation. + +The editor can be replaced temporarily by built-in UI such as `/settings` or by custom extension UI. + +### Editor Features + +| Feature | How | +|---------|-----| +| File reference | Type `@` to fuzzy-search project files | +| Path completion | Press Tab to complete paths | +| Multi-line input | Shift+Enter, or Ctrl+Enter on Windows Terminal | +| Copy response | Ctrl+X copies the last assistant message; in `/tree`, it copies the selected message | +| Images | Paste with Ctrl+V, Alt+V on Windows, or drag into the terminal | +| Shell command | `!command` runs and sends output to the model | +| Hidden shell command | `!!command` runs without sending output to the model | +| External editor | Ctrl+G opens `externalEditor`, `$VISUAL`, `$EDITOR`, Notepad on Windows, or `nano` elsewhere | + +See [Keybindings](keybindings.md) for all shortcuts and customization. + +## Slash Commands + +Type `/` in the editor to open command completion. Extensions can register custom commands, skills are available as `/skill:name`, and prompt templates expand via `/templatename`. + +| Command | Description | +|---------|-------------| +| `/login`, `/logout` | Manage OAuth or API-key credentials | +| [`/llama`](llama-cpp.md) | Download, load, and unload llama.cpp router models | +| `/model` | Switch models | +| `/scoped-models` | Enable/disable models for Ctrl+P cycling | +| `/settings` | Thinking level, theme, message delivery, transport | +| `/resume` | Pick from previous sessions | +| `/new` | Start a new session | +| `/name ` | Set session display name | +| `/session` | Show session file, ID, messages, tokens, and cost | +| `/tree` | Jump to any point in the session and continue from there | +| `/trust` | Save project trust decision for future sessions | +| `/fork` | Create a new session from a previous user message | +| `/clone` | Duplicate the current active branch into a new session | +| `/compact [prompt]` | Manually compact context, optionally with custom instructions | +| `/copy` | Copy last assistant message to clipboard | +| `/export [file]` | Export session to HTML or JSONL | +| `/import ` | Import and resume a session from a JSONL file | +| `/share` | Upload as private GitHub gist with shareable HTML link | +| `/reload` | Reload keybindings, extensions, skills, prompts, themes, and context files | +| `/hotkeys` | Show all keyboard shortcuts | +| `/changelog` | Display version history | +| `/quit` | Quit pi | + +## Message Queue + +You can submit messages while the agent is still working: + +- **Enter** queues a steering message, delivered after the current assistant turn finishes executing its tool calls. +- **Alt+Enter** queues a follow-up message, delivered after the agent finishes all work. +- **Escape** aborts and restores queued messages to the editor. +- **Alt+Up** retrieves queued messages back to the editor. + +On Windows Terminal, Alt+Enter is fullscreen by default. Remap it as described in [Terminal setup](terminal-setup.md) if you want pi to receive the shortcut. + +Configure delivery in [Settings](settings.md) with `steeringMode` and `followUpMode`. + +## Sessions + +Sessions are saved automatically to `~/.pi/agent/sessions/`, organized by working directory. + +```bash +pi -c # Continue most recent session +pi -r # Browse and select a session +pi --no-session # Ephemeral mode; do not save +pi --name "my task" # Set session display name at startup +pi --session # Use a specific session file or session ID +pi --fork # Fork a session into a new session file +``` + +Useful session commands: + +- `/session` shows the current session file and ID. +- `/tree` navigates the in-file session tree and can summarize abandoned branches. +- `/fork` creates a new session from an earlier user message. +- `/clone` duplicates the current active branch into a new session file. +- `/compact` summarizes older messages to free context. + +See [Sessions](sessions.md) and [Compaction](compaction.md) for details. + +## Context Files + +Pi loads `AGENTS.md` or `CLAUDE.md` at startup from: + +- `~/.pi/agent/AGENTS.md` for global instructions +- parent directories, walking up from the current working directory +- the current directory + +Use context files for project conventions, commands, safety rules, and preferences. Disable loading with `--no-context-files` or `-nc`. + +### System Prompt Files + +Replace the default system prompt with: + +- `.pi/SYSTEM.md` for a project +- `~/.pi/agent/SYSTEM.md` globally + +Append to the default prompt without replacing it with `APPEND_SYSTEM.md` in either location. + +### Project Trust + +On interactive startup, pi asks before trusting a project folder that contains project-local settings, resources, or project `.agents/skills` and has no saved decision for the folder or a parent folder in `~/.pi/agent/trust.json`. Trusting a project allows pi to load `.pi/settings.json` and `.pi` resources, install missing project packages, and execute project extensions. + +Before the trust decision, pi loads only context files, user/global extensions, and CLI `-e` extensions so they can handle the `project_trust` event. Project-local extensions, project package-managed extensions, and project settings are loaded only after the project is trusted. This split also applies when switching to a session from a different cwd whose trust has not been resolved in the current process. + +Non-interactive modes (`-p`, `--mode json`, and `--mode rpc`) do not show a trust prompt. Without an applicable saved trust decision, they use `defaultProjectTrust` from global settings: `ask` (default) and `never` ignore those project resources, while `always` trusts them. Pass `--approve`/`-a` or `--no-approve`/`-na` to override project trust for one run. + +If no extension or saved decision applies, `defaultProjectTrust` controls the fallback behavior. Set it to `"ask"`, `"always"`, or `"never"` in `~/.pi/agent/settings.json`, or change it with `/settings`. + +`pi config` and package commands use the same project trust flow, except `pi update` never prompts. Pass `--approve` to trust project-local settings for one command or `--no-approve` to ignore them. + +Use `/trust` in interactive mode to save a project trust decision for future sessions, including trust for the immediate parent folder. It writes `~/.pi/agent/trust.json` only; the current session is not reloaded, so restart pi for changes to take effect. + + +## Exporting and Sharing Sessions + +Use `/export [file]` to write a session to HTML. + +Use `/share` to upload a private GitHub gist with a shareable HTML link. + +If you use pi for open source work and want to publish sessions for model, prompt, tool, and evaluation research, see [`badlogic/pi-share-hf`](https://github.com/badlogic/pi-share-hf). It publishes sessions to Hugging Face datasets. + +## CLI Reference + +```bash +pi [options] [@files...] [messages...] +``` + +### Package Commands + +```bash +pi install [-l] # Install package, -l for project-local +pi remove [-l] # Remove package +pi uninstall [-l] # Alias for remove +pi update [source|self|pi] # Update pi only, or one package source +pi update --all # Update pi and packages; reconcile pinned git refs +pi update --extensions # Update packages only; reconcile pinned git refs +pi update --models # Refresh model catalogs only +pi update --self # Update pi only +pi update --extension # Update one package +pi list # List installed packages +pi config # Enable/disable package resources +``` + +These commands manage pi packages and `pi update` can update the pi CLI installation. To uninstall pi itself, see [Quickstart](quickstart.md#uninstall). `pi config` and project package commands accept `--approve`/`--no-approve` to trust or ignore project-local settings for one command. `pi update` never prompts for project trust. + +See [Pi Packages](packages.md) for package sources and security notes. + +### Modes + +| Flag | Description | +|------|-------------| +| default | Interactive mode | +| `-p`, `--print` | Print response and exit | +| `--mode json` | Output all events as JSON lines; see [JSON mode](json.md) | +| `--mode rpc` | RPC mode over stdin/stdout; see [RPC mode](rpc.md) | +| `--export [out]` | Export a session to HTML | + +In print mode, pi also reads piped stdin and merges it into the initial prompt: + +```bash +cat README.md | pi -p "Summarize this text" +``` + +### Model Options + +| Option | Description | +|--------|-------------| +| `--provider ` | Provider, such as `anthropic`, `openai`, or `google` | +| `--model ` | Model pattern or ID; supports `provider/id` and optional `:` | +| `--api-key ` | API key, overriding environment variables | +| `--thinking ` | `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` | +| `--models ` | Comma-separated patterns for Ctrl+P cycling | +| `--list-models [search]` | List available models | + +### Session Options + +| Option | Description | +|--------|-------------| +| `-c`, `--continue` | Continue the most recent session | +| `-r`, `--resume` | Browse and select a session | +| `--session ` | Use a specific session file or partial UUID | +| `--fork ` | Fork a session file or partial UUID into a new session | +| `--session-dir ` | Custom session storage directory | +| `--no-session` | Ephemeral mode; do not save | +| `--name `, `-n ` | Set session display name at startup | + +### Tool Options + +| Option | Description | +|--------|-------------| +| `--tools `, `-t ` | Allowlist specific built-in, extension, and custom tools | +| `--exclude-tools `, `-xt ` | Disable specific built-in, extension, and custom tools | +| `--no-builtin-tools`, `-nbt` | Disable built-in tools but keep extension/custom tools enabled | +| `--no-tools`, `-nt` | Disable all tools | + +Built-in tools: `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`. + +### Resource Options + +| Option | Description | +|--------|-------------| +| `-e`, `--extension ` | Load an extension from path, npm, or git; repeatable | +| `--no-extensions` | Disable extension discovery | +| `--skill ` | Load a skill; repeatable | +| `--no-skills` | Disable skill discovery | +| `--prompt-template ` | Load a prompt template; repeatable | +| `--no-prompt-templates` | Disable prompt template discovery | +| `--theme ` | Load a theme; repeatable | +| `--no-themes` | Disable theme discovery | +| `--no-context-files`, `-nc` | Disable `AGENTS.md` and `CLAUDE.md` discovery | + +Combine `--no-*` with explicit flags to load exactly what you need, ignoring settings. Example: + +```bash +pi --no-extensions -e ./my-extension.ts +``` + +### Other Options + +| Option | Description | +|--------|-------------| +| `--system-prompt ` | Replace default prompt; context files and skills are still appended | +| `--append-system-prompt ` | Append to system prompt | +| `--verbose` | Force verbose startup | +| `-a`, `--approve` | Trust project-local files for this run | +| `-na`, `--no-approve` | Ignore project-local files for this run | +| `-h`, `--help` | Show help | +| `-v`, `--version` | Show version | + +### File Arguments + +Prefix files with `@` to include them in the message: + +```bash +pi @prompt.md "Answer this" +pi -p @screenshot.png "What's in this image?" +pi @code.ts @test.ts "Review these files" +``` + +### Examples + +```bash +# Interactive with initial prompt +pi "List all .ts files in src/" + +# Non-interactive +pi -p "Summarize this codebase" + +# Non-interactive with piped stdin +cat README.md | pi -p "Summarize this text" + +# Named one-shot session +pi --name "release audit" -p "Audit this repository" + +# Different model +pi --provider openai --model gpt-4o "Help me refactor" + +# Model with provider prefix +pi --model openai/gpt-4o "Help me refactor" + +# Model with thinking level shorthand +pi --model sonnet:high "Solve this complex problem" + +# Limit model cycling +pi --models "claude-*,gpt-4o" + +# Read-only mode +pi --tools read,grep,find,ls -p "Review the code" + +# Disable one extension or built-in tool while keeping the rest available +pi --exclude-tools ask_question +``` + +## Design Principles + +Pi keeps the core small and pushes workflow-specific behavior into extensions, skills, prompt templates, and packages. + +It intentionally does not include built-in MCP, sub-agents, permission popups, plan mode, to-dos, or background bash. You can build or install those workflows as extensions or packages, or use external tools such as containers and tmux. + +For the full rationale, read the [blog post](https://mariozechner.at/posts/2025-11-30-pi-coding-agent/). diff --git a/docs/windows.md b/docs/windows.md new file mode 100644 index 0000000..007f649 --- /dev/null +++ b/docs/windows.md @@ -0,0 +1,17 @@ +# Windows Setup + +Pi requires a bash shell on Windows. Checked locations (in order): + +1. Custom path from `~/.pi/agent/settings.json` +2. Git Bash (`C:\Program Files\Git\bin\bash.exe`) +3. `bash.exe` on PATH (Cygwin, MSYS2, WSL) + +For most users, [Git for Windows](https://git-scm.com/download/win) is sufficient. + +## Custom Shell Path + +```json +{ + "shellPath": "C:\\cygwin64\\bin\\bash.exe" +} +``` diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..8750518 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,25 @@ +# Examples + +Example code for pi-coding-agent SDK and extensions. + +## Directories + +### [sdk/](sdk/) +Programmatic usage via `createAgentSession()`. Shows how to customize models, prompts, tools, extensions, and session management. + +### [extensions/](extensions/) +Example extensions demonstrating: +- Lifecycle event handlers (tool interception, safety gates, context modifications) +- Custom tools (todo lists, questions, subagents, output truncation) +- Commands and keyboard shortcuts +- Custom UI (footers, headers, editors, overlays) +- Git integration (checkpoints, auto-commit) +- System prompt modifications and custom compaction +- External integrations (SSH, file watchers, system theme sync) +- Custom providers (Anthropic with custom streaming, GitLab Duo) + +## Documentation + +- [SDK Reference](sdk/README.md) +- [Extensions Documentation](../docs/extensions.md) +- [Skills Documentation](../docs/skills.md) diff --git a/examples/extensions/README.md b/examples/extensions/README.md new file mode 100644 index 0000000..d60d6e3 --- /dev/null +++ b/examples/extensions/README.md @@ -0,0 +1,213 @@ +# Extension Examples + +Example extensions for pi-coding-agent. + +## Usage + +```bash +# Load an extension with --extension flag +pi --extension examples/extensions/permission-gate.ts + +# Or copy to extensions directory for auto-discovery +cp permission-gate.ts ~/.pi/agent/extensions/ +``` + +## Examples + +### Lifecycle & Safety + +| Extension | Description | +|-----------|-------------| +| `permission-gate.ts` | Prompts for confirmation before dangerous bash commands (rm -rf, sudo, etc.) | +| `project-trust.ts` | Demonstrates the `project_trust` event for user/global and CLI extensions | +| `protected-paths.ts` | Blocks writes to protected paths (.env, .git/, node_modules/) | +| `confirm-destructive.ts` | Confirms before destructive session actions (clear, switch, fork) | +| `dirty-repo-guard.ts` | Prevents session changes with uncommitted git changes | +| `sandbox/` | OS-level sandboxing using `@anthropic-ai/sandbox-runtime` with per-project config | +| `gondolin/` | Route built-in tools and `!` commands into a Gondolin micro-VM | + +### Custom Tools + +| Extension | Description | +|-----------|-------------| +| `todo.ts` | Todo list tool + `/todos` command with custom rendering and state persistence | +| `hello.ts` | Minimal custom tool example | +| `question.ts` | Demonstrates `ctx.ui.select()` for asking the user questions with custom UI | +| `questionnaire.ts` | Multi-question input with tab bar navigation between questions | +| `tool-override.ts` | Override built-in tools (e.g., add logging/access control to `read`) | +| `dynamic-tools.ts` | Register tools after startup (`session_start`) and at runtime via command, with prompt snippets and tool-specific prompt guidelines | +| `kimi-deferred-tools.ts` | Search for and progressively activate tools for Kimi's deferred-tool loading protocol | +| `structured-output.ts` | Final structured-output tool that returns `terminate: true` so the agent can end on the tool call | +| `built-in-tool-renderer.ts` | Custom compact rendering for built-in tools (read, bash, edit, write) while keeping original behavior | +| `minimal-mode.ts` | Override built-in tool rendering for minimal display (only tool calls, no output in collapsed mode) | +| `truncated-tool.ts` | Wraps ripgrep with proper output truncation (50KB/2000 lines) | +| `ssh.ts` | Delegate all tools to a remote machine via SSH using pluggable operations | +| `subagent/` | Delegate tasks to specialized subagents with isolated context windows | + +### Commands & UI + +| Extension | Description | +|-----------|-------------| +| `preset.ts` | Named presets for model, thinking level, tools, and instructions via `--preset` flag and `/preset` command | +| `plan-mode/` | Claude Code-style plan mode for read-only exploration with `/plan` command and step tracking | +| `tools.ts` | Interactive `/tools` command to enable/disable tools with session persistence | +| `handoff.ts` | Transfer context to a new focused session via `/handoff ` | +| `qna.ts` | Extracts questions from last response into editor via `ctx.ui.setEditorText()` | +| `status-line.ts` | Shows turn progress in footer via `ctx.ui.setStatus()` with themed colors | +| `github-issue-autocomplete.ts` | Adds `#1234` issue completions by stacking a custom autocomplete provider that preloads open issues from `gh issue list` | +| `widget-placement.ts` | Shows widgets above and below the editor via `ctx.ui.setWidget()` placement | +| `hidden-thinking-label.ts` | Customizes the collapsed thinking label via `ctx.ui.setHiddenThinkingLabel()` | +| `working-indicator.ts` | Customizes the streaming working indicator via `ctx.ui.setWorkingIndicator()` | +| `model-status.ts` | Shows model changes in status bar via `model_select` hook | +| `snake.ts` | Snake game with custom UI, keyboard handling, and session persistence | +| `tic-tac-toe.ts` | Tic-tac-toe vs the agent with `executionMode: "sequential"` tools to prevent race conditions on shared cursor state | +| `send-user-message.ts` | Demonstrates `pi.sendUserMessage()` for sending user messages from extensions | +| `timed-confirm.ts` | Demonstrates AbortSignal for auto-dismissing `ctx.ui.confirm()` and `ctx.ui.select()` dialogs | +| `rpc-demo.ts` | Exercises all RPC-supported extension UI methods; pair with [`examples/rpc-extension-ui.ts`](../rpc-extension-ui.ts) | +| `modal-editor.ts` | Custom vim-like modal editor via `ctx.ui.setEditorComponent()` | +| `rainbow-editor.ts` | Animated rainbow text effect via custom editor | +| `notify.ts` | Desktop notifications via OSC 777 when agent finishes (Ghostty, iTerm2, WezTerm) | +| `titlebar-spinner.ts` | Braille spinner animation in terminal title while the agent is working | +| `summarize.ts` | Summarize conversation with GPT-5.2 and show in transient UI | +| `custom-footer.ts` | Custom footer with git branch and token stats via `ctx.ui.setFooter()` | +| `custom-header.ts` | Custom header via `ctx.ui.setHeader()` | +| `overlay-test.ts` | Test overlay compositing with inline text inputs and edge cases | +| `overlay-qa-tests.ts` | Comprehensive overlay QA tests: anchors, margins, stacking, overflow, animation | +| `doom-overlay/` | DOOM game running as an overlay at 35 FPS (demonstrates real-time game rendering) | +| `shutdown-command.ts` | Adds `/quit` command demonstrating `ctx.shutdown()` | +| `reload-runtime.ts` | Adds `/reload-runtime` and `reload_runtime` tool showing safe reload flow | +| `interactive-shell.ts` | Run interactive commands (vim, htop) with full terminal via `user_bash` hook | +| `inline-bash.ts` | Expands `!{command}` patterns in prompts via `input` event transformation | +| `input-transform-streaming.ts` | Skips expensive input preprocessing for mid-stream steering via `streamingBehavior` | + +### Git Integration + +| Extension | Description | +|-----------|-------------| +| `git-checkpoint.ts` | Creates git stash checkpoints at each turn for code restoration on fork | +| `auto-commit-on-exit.ts` | Auto-commits on exit using last assistant message for commit message | + +### System Prompt & Compaction + +| Extension | Description | +|-----------|-------------| +| `pirate.ts` | Demonstrates `systemPromptAppend` to dynamically modify system prompt | +| `claude-rules.ts` | Scans `.claude/rules/` folder and lists rules in system prompt | +| `custom-compaction.ts` | Custom compaction that summarizes entire conversation | +| `trigger-compact.ts` | Triggers compaction when context usage exceeds 100k tokens and adds `/trigger-compact` command | + +### System Integration + +| Extension | Description | +|-----------|-------------| +| `mac-system-theme.ts` | Syncs pi theme with macOS dark/light mode | + +### Resources + +| Extension | Description | +|-----------|-------------| +| `dynamic-resources/` | Loads skills, prompts, and themes using `resources_discover` | + +### Messages & Communication + +| Extension | Description | +|-----------|-------------| +| `message-renderer.ts` | Custom message rendering with colors and expandable details via `registerMessageRenderer` | +| `entry-renderer.ts` | TUI-only session entry rendering via `appendEntry` and `registerEntryRenderer` | +| `event-bus.ts` | Inter-extension communication via `pi.events` | + +### Session Metadata + +| Extension | Description | +|-----------|-------------| +| `session-name.ts` | Name sessions for the session selector via `setSessionName` | +| `bookmark.ts` | Bookmark entries with labels for `/tree` navigation via `setLabel` | + +### Custom Providers + +| Extension | Description | +|-----------|-------------| +| `custom-provider-anthropic/` | Custom Anthropic provider with OAuth support and custom streaming implementation | +| `custom-provider-gitlab-duo/` | GitLab Duo provider using pi-ai's built-in Anthropic/OpenAI streaming via proxy | + +### External Dependencies + +| Extension | Description | +|-----------|-------------| +| `with-deps/` | Extension with its own package.json and dependencies (demonstrates jiti module resolution) | +| `file-trigger.ts` | Watches a trigger file and injects contents into conversation | + +## Writing Extensions + +See [docs/extensions.md](../../docs/extensions.md) for full documentation. + +```typescript +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { Type } from "typebox"; + +export default function (pi: ExtensionAPI) { + // Subscribe to lifecycle events + pi.on("tool_call", async (event, ctx) => { + if (event.toolName === "bash" && event.input.command?.includes("rm -rf")) { + const ok = await ctx.ui.confirm("Dangerous!", "Allow rm -rf?"); + if (!ok) return { block: true, reason: "Blocked by user" }; + } + }); + + // Register custom tools + pi.registerTool({ + name: "greet", + label: "Greeting", + description: "Generate a greeting", + parameters: Type.Object({ + name: Type.String({ description: "Name to greet" }), + }), + async execute(toolCallId, params, signal, onUpdate, ctx) { + return { + content: [{ type: "text", text: `Hello, ${params.name}!` }], + details: {}, + }; + }, + }); + + // Register commands + pi.registerCommand("hello", { + description: "Say hello", + handler: async (args, ctx) => { + ctx.ui.notify("Hello!", "info"); + }, + }); +} +``` + +## Key Patterns + +**Use StringEnum for string parameters** (required for Google API compatibility): +```typescript +import { StringEnum } from "@earendil-works/pi-ai"; + +// Good +action: StringEnum(["list", "add"] as const) + +// Bad - doesn't work with Google +action: Type.Union([Type.Literal("list"), Type.Literal("add")]) +``` + +**State persistence via details:** +```typescript +// Store state in tool result details for proper forking support +return { + content: [{ type: "text", text: "Done" }], + details: { todos: [...todos], nextId }, // Persisted in session +}; + +// Reconstruct on session events +pi.on("session_start", async (_event, ctx) => { + for (const entry of ctx.sessionManager.getBranch()) { + if (entry.type === "message" && entry.message.toolName === "my_tool") { + const details = entry.message.details; + // Reconstruct state from details + } + } +}); +``` diff --git a/examples/extensions/auto-commit-on-exit.ts b/examples/extensions/auto-commit-on-exit.ts new file mode 100644 index 0000000..58063e9 --- /dev/null +++ b/examples/extensions/auto-commit-on-exit.ts @@ -0,0 +1,49 @@ +/** + * Auto-Commit on Exit Extension + * + * Automatically commits changes when the agent exits. + * Uses the last assistant message to generate a commit message. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.on("session_shutdown", async (_event, ctx) => { + // Check for uncommitted changes + const { stdout: status, code } = await pi.exec("git", ["status", "--porcelain"]); + + if (code !== 0 || status.trim().length === 0) { + // Not a git repo or no changes + return; + } + + // Find the last assistant message for commit context + const entries = ctx.sessionManager.getEntries(); + let lastAssistantText = ""; + for (let i = entries.length - 1; i >= 0; i--) { + const entry = entries[i]; + if (entry.type === "message" && entry.message.role === "assistant") { + const content = entry.message.content; + if (Array.isArray(content)) { + lastAssistantText = content + .filter((c): c is { type: "text"; text: string } => c.type === "text") + .map((c) => c.text) + .join("\n"); + } + break; + } + } + + // Generate a simple commit message + const firstLine = lastAssistantText.split("\n")[0] || "Work in progress"; + const commitMessage = `[pi] ${firstLine.slice(0, 50)}${firstLine.length > 50 ? "..." : ""}`; + + // Stage and commit + await pi.exec("git", ["add", "-A"]); + const { code: commitCode } = await pi.exec("git", ["commit", "-m", commitMessage]); + + if (commitCode === 0 && ctx.hasUI) { + ctx.ui.notify(`Auto-committed: ${commitMessage}`, "info"); + } + }); +} diff --git a/examples/extensions/bash-spawn-hook.ts b/examples/extensions/bash-spawn-hook.ts new file mode 100644 index 0000000..e4a1d02 --- /dev/null +++ b/examples/extensions/bash-spawn-hook.ts @@ -0,0 +1,30 @@ +/** + * Bash Spawn Hook Example + * + * Adjusts command, cwd, and env before execution. + * + * Usage: + * pi -e ./bash-spawn-hook.ts + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { createBashTool } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + const cwd = process.cwd(); + + const bashTool = createBashTool(cwd, { + spawnHook: ({ command, cwd, env }) => ({ + command: `source ~/.profile\n${command}`, + cwd, + env: { ...env, PI_SPAWN_HOOK: "1" }, + }), + }); + + pi.registerTool({ + ...bashTool, + execute: async (id, params, signal, onUpdate, _ctx) => { + return bashTool.execute(id, params, signal, onUpdate); + }, + }); +} diff --git a/examples/extensions/bookmark.ts b/examples/extensions/bookmark.ts new file mode 100644 index 0000000..3854b86 --- /dev/null +++ b/examples/extensions/bookmark.ts @@ -0,0 +1,50 @@ +/** + * Entry bookmarking example. + * + * Shows setLabel to mark entries with labels for easy navigation in /tree. + * Labels appear in the tree view and help you find important points. + * + * Usage: /bookmark [label] - bookmark the last assistant message + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.registerCommand("bookmark", { + description: "Bookmark last message (usage: /bookmark [label])", + handler: async (args, ctx) => { + const label = args.trim() || `bookmark-${Date.now()}`; + + // Find the last assistant message entry + const entries = ctx.sessionManager.getEntries(); + for (let i = entries.length - 1; i >= 0; i--) { + const entry = entries[i]; + if (entry.type === "message" && entry.message.role === "assistant") { + pi.setLabel(entry.id, label); + ctx.ui.notify(`Bookmarked as: ${label}`, "info"); + return; + } + } + + ctx.ui.notify("No assistant message to bookmark", "warning"); + }, + }); + + // Remove bookmark + pi.registerCommand("unbookmark", { + description: "Remove bookmark from last labeled entry", + handler: async (_args, ctx) => { + const entries = ctx.sessionManager.getEntries(); + for (let i = entries.length - 1; i >= 0; i--) { + const entry = entries[i]; + const label = ctx.sessionManager.getLabel(entry.id); + if (label) { + pi.setLabel(entry.id, undefined); + ctx.ui.notify(`Removed bookmark: ${label}`, "info"); + return; + } + } + ctx.ui.notify("No bookmarked entry found", "warning"); + }, + }); +} diff --git a/examples/extensions/border-status-editor.ts b/examples/extensions/border-status-editor.ts new file mode 100644 index 0000000..dce9e59 --- /dev/null +++ b/examples/extensions/border-status-editor.ts @@ -0,0 +1,150 @@ +import { + CustomEditor, + type ExtensionAPI, + type ExtensionContext, + type KeybindingsManager, +} from "@earendil-works/pi-coding-agent"; +import type { Component, EditorTheme, TUI } from "@earendil-works/pi-tui"; +import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; + +function fitBorder( + left: string, + right: string, + width: number, + border: (text: string) => string, + fill: (text: string) => string = border, +): string { + if (width <= 0) return ""; + if (width === 1) return border("─"); + + let leftText = left; + let rightText = right; + const fixedWidth = 2; + const minimumGap = 3; + + while ( + fixedWidth + visibleWidth(leftText) + visibleWidth(rightText) + minimumGap > width && + visibleWidth(rightText) > 0 + ) { + rightText = truncateToWidth(rightText, Math.max(0, visibleWidth(rightText) - 1), ""); + } + while ( + fixedWidth + visibleWidth(leftText) + visibleWidth(rightText) + minimumGap > width && + visibleWidth(leftText) > 0 + ) { + leftText = truncateToWidth(leftText, Math.max(0, visibleWidth(leftText) - 1), ""); + } + + const gapWidth = Math.max(0, width - fixedWidth - visibleWidth(leftText) - visibleWidth(rightText)); + return `${border("─")}${leftText}${fill("─".repeat(gapWidth))}${rightText}${border("─")}`; +} + +function formatCwd(cwd: string): string { + const home = process.env.HOME; + if (home && cwd.startsWith(home)) { + return `~${cwd.slice(home.length)}`; + } + return cwd; +} + +function formatContext(ctx: ExtensionContext): string { + const usage = ctx.getContextUsage(); + const contextWindow = usage?.contextWindow ?? ctx.model?.contextWindow; + if (!contextWindow || !usage || usage.percent === null) { + return "ctx ?"; + } + return `ctx ${Math.round(usage.percent)}%/${(contextWindow / 1000).toFixed(0)}k`; +} + +function formatThinking(level: string): string { + return level === "off" ? "off" : level; +} + +class EmptyFooter implements Component { + render(): string[] { + return []; + } + + invalidate(): void {} +} + +export default function (pi: ExtensionAPI) { + let isWorking = false; + let spinnerIndex = 0; + let spinnerTimer: ReturnType | undefined; + let activeTui: TUI | undefined; + const spinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; + + const stopSpinner = () => { + if (spinnerTimer) { + clearInterval(spinnerTimer); + spinnerTimer = undefined; + } + }; + + pi.on("agent_start", () => { + isWorking = true; + stopSpinner(); + spinnerTimer = setInterval(() => { + spinnerIndex = (spinnerIndex + 1) % spinnerFrames.length; + activeTui?.requestRender(); + }, 80); + activeTui?.requestRender(); + }); + + pi.on("agent_end", () => { + isWorking = false; + stopSpinner(); + activeTui?.requestRender(); + }); + + pi.on("session_shutdown", () => { + stopSpinner(); + activeTui = undefined; + }); + + pi.on("session_start", (_event, ctx) => { + ctx.ui.setWorkingVisible(false); + ctx.ui.setFooter(() => new EmptyFooter()); + + let branch: string | undefined; + + const refreshBranch = async () => { + const result = await pi.exec("git", ["branch", "--show-current"], { cwd: ctx.cwd }).catch(() => undefined); + const stdout = result?.stdout.trim(); + branch = stdout && stdout.length > 0 ? stdout : undefined; + activeTui?.requestRender(); + }; + void refreshBranch(); + + class BorderStatusEditor extends CustomEditor { + constructor(tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) { + super(tui, theme, keybindings, { paddingX: 0 }); + activeTui = tui; + } + + render(width: number): string[] { + const lines = super.render(width); + if (lines.length < 2) return lines; + + const thm = ctx.ui.theme; + const model = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "no model"; + const thinking = pi.getThinkingLevel(); + const topLeft = isWorking ? thm.fg("accent", ` ${spinnerFrames[spinnerIndex]} `) : ""; + const topRight = ""; + const bottomLeft = thm.fg("muted", ` ${model} · ${formatThinking(thinking)} `); + const bottomRight = thm.fg( + "muted", + ` ${formatContext(ctx)} · ${formatCwd(ctx.cwd)}${branch ? ` (${branch})` : ""} `, + ); + const borderColor = (text: string) => this.borderColor(text); + + lines[0] = fitBorder(topLeft, topRight, width, borderColor); + lines[lines.length - 1] = fitBorder(bottomLeft, bottomRight, width, borderColor); + return lines; + } + } + + ctx.ui.setEditorComponent((tui, theme, keybindings) => new BorderStatusEditor(tui, theme, keybindings)); + }); +} diff --git a/examples/extensions/built-in-tool-renderer.ts b/examples/extensions/built-in-tool-renderer.ts new file mode 100644 index 0000000..3a9dc37 --- /dev/null +++ b/examples/extensions/built-in-tool-renderer.ts @@ -0,0 +1,249 @@ +/** + * Built-in Tool Renderer Example - Custom rendering for built-in tools + * + * Demonstrates how to override the rendering of built-in tools (read, bash, + * edit, write) without changing their behavior. Each tool is re-registered + * with the same name, delegating execution to the original implementation + * while providing compact custom renderCall/renderResult functions. + * + * This is useful for users who prefer more concise tool output, or who want + * to highlight specific information (e.g., showing only the diff stats for + * edit, or just the exit code for bash). + * + * How it works: + * - registerTool() with the same name as a built-in replaces it entirely + * - We create instances of the original tools via createReadTool(), etc. + * and delegate execute() to them + * - renderCall() controls what's shown when the tool is invoked + * - renderResult() controls what's shown after execution completes + * - renderShell: "self" lets a tool render its own outer shell instead of + * using the default boxed shell from ToolExecutionComponent + * - The `expanded` flag in renderResult indicates whether the user has + * toggled the tool output open (via ctrl+e or clicking) + * + * Usage: + * pi -e ./built-in-tool-renderer.ts + */ + +import type { BashToolDetails, EditToolDetails, ExtensionAPI, ReadToolDetails } from "@earendil-works/pi-coding-agent"; +import { createBashTool, createEditTool, createReadTool, createWriteTool } from "@earendil-works/pi-coding-agent"; +import { Text } from "@earendil-works/pi-tui"; + +export default function (pi: ExtensionAPI) { + const cwd = process.cwd(); + + // --- Read tool: show path and line count --- + const originalRead = createReadTool(cwd); + pi.registerTool({ + name: "read", + label: "read", + description: originalRead.description, + parameters: originalRead.parameters, + + async execute(toolCallId, params, signal, onUpdate) { + return originalRead.execute(toolCallId, params, signal, onUpdate); + }, + + renderCall(args, theme, _context) { + let text = theme.fg("toolTitle", theme.bold("read ")); + text += theme.fg("accent", args.path); + if (args.offset || args.limit) { + const parts: string[] = []; + if (args.offset) parts.push(`offset=${args.offset}`); + if (args.limit) parts.push(`limit=${args.limit}`); + text += theme.fg("dim", ` (${parts.join(", ")})`); + } + return new Text(text, 0, 0); + }, + + renderResult(result, { expanded, isPartial }, theme, _context) { + if (isPartial) return new Text(theme.fg("warning", "Reading..."), 0, 0); + + const details = result.details as ReadToolDetails | undefined; + const content = result.content[0]; + + if (content?.type === "image") { + return new Text(theme.fg("success", "Image loaded"), 0, 0); + } + + if (content?.type !== "text") { + return new Text(theme.fg("error", "No content"), 0, 0); + } + + const lineCount = content.text.split("\n").length; + let text = theme.fg("success", `${lineCount} lines`); + + if (details?.truncation?.truncated) { + text += theme.fg("warning", ` (truncated from ${details.truncation.totalLines})`); + } + + if (expanded) { + const lines = content.text.split("\n").slice(0, 15); + for (const line of lines) { + text += `\n${theme.fg("dim", line)}`; + } + if (lineCount > 15) { + text += `\n${theme.fg("muted", `... ${lineCount - 15} more lines`)}`; + } + } + + return new Text(text, 0, 0); + }, + }); + + // --- Bash tool: show command and exit code --- + const originalBash = createBashTool(cwd); + pi.registerTool({ + name: "bash", + label: "bash", + description: originalBash.description, + parameters: originalBash.parameters, + + async execute(toolCallId, params, signal, onUpdate) { + return originalBash.execute(toolCallId, params, signal, onUpdate); + }, + + renderCall(args, theme, _context) { + let text = theme.fg("toolTitle", theme.bold("$ ")); + const cmd = args.command.length > 80 ? `${args.command.slice(0, 77)}...` : args.command; + text += theme.fg("accent", cmd); + if (args.timeout) { + text += theme.fg("dim", ` (timeout: ${args.timeout}s)`); + } + return new Text(text, 0, 0); + }, + + renderResult(result, { expanded, isPartial }, theme, _context) { + if (isPartial) return new Text(theme.fg("warning", "Running..."), 0, 0); + + const details = result.details as BashToolDetails | undefined; + const content = result.content[0]; + const output = content?.type === "text" ? content.text : ""; + + const exitMatch = output.match(/exit code: (\d+)/); + const exitCode = exitMatch ? parseInt(exitMatch[1], 10) : null; + const lineCount = output.split("\n").filter((l) => l.trim()).length; + + let text = ""; + if (exitCode === 0 || exitCode === null) { + text += theme.fg("success", "done"); + } else { + text += theme.fg("error", `exit ${exitCode}`); + } + text += theme.fg("dim", ` (${lineCount} lines)`); + + if (details?.truncation?.truncated) { + text += theme.fg("warning", " [truncated]"); + } + + if (expanded) { + const lines = output.split("\n").slice(0, 20); + for (const line of lines) { + text += `\n${theme.fg("dim", line)}`; + } + if (output.split("\n").length > 20) { + text += `\n${theme.fg("muted", "... more output")}`; + } + } + + return new Text(text, 0, 0); + }, + }); + + // --- Edit tool: show path and diff stats --- + const originalEdit = createEditTool(cwd); + pi.registerTool({ + name: "edit", + label: "edit", + description: originalEdit.description, + parameters: originalEdit.parameters, + renderShell: "self", + + async execute(toolCallId, params, signal, onUpdate) { + return originalEdit.execute(toolCallId, params, signal, onUpdate); + }, + + renderCall(args, theme, _context) { + let text = theme.fg("toolTitle", theme.bold("edit ")); + text += theme.fg("accent", args.path); + return new Text(text, 0, 0); + }, + + renderResult(result, { expanded, isPartial }, theme, _context) { + if (isPartial) return new Text(theme.fg("warning", "Editing..."), 0, 0); + + const details = result.details as EditToolDetails | undefined; + const content = result.content[0]; + + if (content?.type === "text" && content.text.startsWith("Error")) { + return new Text(theme.fg("error", content.text.split("\n")[0]), 0, 0); + } + + if (!details?.diff) { + return new Text(theme.fg("success", "Applied"), 0, 0); + } + + // Count additions and removals from the diff + const diffLines = details.diff.split("\n"); + let additions = 0; + let removals = 0; + for (const line of diffLines) { + if (line.startsWith("+") && !line.startsWith("+++")) additions++; + if (line.startsWith("-") && !line.startsWith("---")) removals++; + } + + let text = theme.fg("success", `+${additions}`); + text += theme.fg("dim", " / "); + text += theme.fg("error", `-${removals}`); + + if (expanded) { + for (const line of diffLines.slice(0, 30)) { + if (line.startsWith("+") && !line.startsWith("+++")) { + text += `\n${theme.fg("success", line)}`; + } else if (line.startsWith("-") && !line.startsWith("---")) { + text += `\n${theme.fg("error", line)}`; + } else { + text += `\n${theme.fg("dim", line)}`; + } + } + if (diffLines.length > 30) { + text += `\n${theme.fg("muted", `... ${diffLines.length - 30} more diff lines`)}`; + } + } + + return new Text(text, 0, 0); + }, + }); + + // --- Write tool: show path and size --- + const originalWrite = createWriteTool(cwd); + pi.registerTool({ + name: "write", + label: "write", + description: originalWrite.description, + parameters: originalWrite.parameters, + + async execute(toolCallId, params, signal, onUpdate) { + return originalWrite.execute(toolCallId, params, signal, onUpdate); + }, + + renderCall(args, theme, _context) { + let text = theme.fg("toolTitle", theme.bold("write ")); + text += theme.fg("accent", args.path); + const lineCount = args.content.split("\n").length; + text += theme.fg("dim", ` (${lineCount} lines)`); + return new Text(text, 0, 0); + }, + + renderResult(result, { isPartial }, theme, _context) { + if (isPartial) return new Text(theme.fg("warning", "Writing..."), 0, 0); + + const content = result.content[0]; + if (content?.type === "text" && content.text.startsWith("Error")) { + return new Text(theme.fg("error", content.text.split("\n")[0]), 0, 0); + } + + return new Text(theme.fg("success", "Written"), 0, 0); + }, + }); +} diff --git a/examples/extensions/claude-rules.ts b/examples/extensions/claude-rules.ts new file mode 100644 index 0000000..be361c5 --- /dev/null +++ b/examples/extensions/claude-rules.ts @@ -0,0 +1,86 @@ +/** + * Claude Rules Extension + * + * Scans the project's .claude/rules/ folder for rule files and lists them + * in the system prompt. The agent can then use the read tool to load + * specific rules when needed. + * + * Best practices for .claude/rules/: + * - Keep rules focused: Each file should cover one topic (e.g., testing.md, api-design.md) + * - Use descriptive filenames: The filename should indicate what the rules cover + * - Use conditional rules sparingly: Only add paths frontmatter when rules truly apply to specific file types + * - Organize with subdirectories: Group related rules (e.g., frontend/, backend/) + * + * Usage: + * 1. Copy this file to ~/.pi/agent/extensions/ or your project's .pi/extensions/ + * 2. Create .claude/rules/ folder in your project root + * 3. Add .md files with your rules + */ + +import * as fs from "node:fs"; +import * as path from "node:path"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +/** + * Recursively find all .md files in a directory + */ +function findMarkdownFiles(dir: string, basePath: string = ""): string[] { + const results: string[] = []; + + if (!fs.existsSync(dir)) { + return results; + } + + const entries = fs.readdirSync(dir, { withFileTypes: true }); + + for (const entry of entries) { + const relativePath = basePath ? `${basePath}/${entry.name}` : entry.name; + + if (entry.isDirectory()) { + results.push(...findMarkdownFiles(path.join(dir, entry.name), relativePath)); + } else if (entry.isFile() && entry.name.endsWith(".md")) { + results.push(relativePath); + } + } + + return results; +} + +export default function claudeRulesExtension(pi: ExtensionAPI) { + let ruleFiles: string[] = []; + let rulesDir: string = ""; + + // Scan for rules on session start + pi.on("session_start", async (_event, ctx) => { + rulesDir = path.join(ctx.cwd, ".claude", "rules"); + ruleFiles = findMarkdownFiles(rulesDir); + + if (ruleFiles.length > 0) { + ctx.ui.notify(`Found ${ruleFiles.length} rule(s) in .claude/rules/`, "info"); + } + }); + + // Append available rules to system prompt + pi.on("before_agent_start", async (event) => { + if (ruleFiles.length === 0) { + return; + } + + const rulesList = ruleFiles.map((f) => `- .claude/rules/${f}`).join("\n"); + + return { + systemPrompt: + event.systemPrompt + + ` + +## Project Rules + +The following project rules are available in .claude/rules/: + +${rulesList} + +When working on tasks related to these rules, use the read tool to load the relevant rule files for guidance. +`, + }; + }); +} diff --git a/examples/extensions/commands.ts b/examples/extensions/commands.ts new file mode 100644 index 0000000..346c5f2 --- /dev/null +++ b/examples/extensions/commands.ts @@ -0,0 +1,72 @@ +/** + * Commands Extension + * + * Demonstrates the pi.getCommands() API by providing a /commands command + * that lists all available slash commands in the current session. + * + * Usage: + * 1. Copy this file to ~/.pi/agent/extensions/ or your project's .pi/extensions/ + * 2. Use /commands to see available commands + * 3. Use /commands extensions to filter by source + */ + +import type { ExtensionAPI, SlashCommandInfo } from "@earendil-works/pi-coding-agent"; + +export default function commandsExtension(pi: ExtensionAPI) { + pi.registerCommand("commands", { + description: "List available slash commands", + getArgumentCompletions: (prefix) => { + const sources = ["extension", "prompt", "skill"]; + const filtered = sources.filter((s) => s.startsWith(prefix)); + return filtered.length > 0 ? filtered.map((s) => ({ value: s, label: s })) : null; + }, + handler: async (args, ctx) => { + const commands = pi.getCommands(); + const sourceFilter = args.trim() as "extension" | "prompt" | "skill" | ""; + + // Filter by source if specified + const filtered = sourceFilter ? commands.filter((c) => c.source === sourceFilter) : commands; + + if (filtered.length === 0) { + ctx.ui.notify(sourceFilter ? `No ${sourceFilter} commands found` : "No commands found", "info"); + return; + } + + // Build selection items grouped by source + const formatCommand = (cmd: SlashCommandInfo): string => { + const desc = cmd.description ? ` - ${cmd.description}` : ""; + return `/${cmd.name}${desc}`; + }; + + const items: string[] = []; + const sources: Array<{ key: "extension" | "prompt" | "skill"; label: string }> = [ + { key: "extension", label: "Extensions" }, + { key: "prompt", label: "Prompts" }, + { key: "skill", label: "Skills" }, + ]; + + for (const { key, label } of sources) { + const cmds = filtered.filter((c) => c.source === key); + if (cmds.length > 0) { + items.push(`--- ${label} ---`); + items.push(...cmds.map(formatCommand)); + } + } + + // Show in a selector (user can scroll and see all commands) + const selected = await ctx.ui.select("Available Commands", items); + + // If user selected a command (not a header), offer to show its path + if (selected && !selected.startsWith("---")) { + const cmdName = selected.split(" - ")[0].slice(1); // Remove leading / + const cmd = commands.find((c) => c.name === cmdName); + if (cmd?.sourceInfo.path) { + const showPath = await ctx.ui.confirm(cmd.name, `View source path?\n${cmd.sourceInfo.path}`); + if (showPath) { + ctx.ui.notify(cmd.sourceInfo.path, "info"); + } + } + } + }, + }); +} diff --git a/examples/extensions/confirm-destructive.ts b/examples/extensions/confirm-destructive.ts new file mode 100644 index 0000000..7d4201f --- /dev/null +++ b/examples/extensions/confirm-destructive.ts @@ -0,0 +1,59 @@ +/** + * Confirm Destructive Actions Extension + * + * Prompts for confirmation before destructive session actions (clear, switch, branch). + * Demonstrates how to cancel session events using the before_* events. + */ + +import type { ExtensionAPI, SessionBeforeSwitchEvent, SessionMessageEntry } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.on("session_before_switch", async (event: SessionBeforeSwitchEvent, ctx) => { + if (!ctx.hasUI) return; + + if (event.reason === "new") { + const confirmed = await ctx.ui.confirm( + "Clear session?", + "This will delete all messages in the current session.", + ); + + if (!confirmed) { + ctx.ui.notify("Clear cancelled", "info"); + return { cancel: true }; + } + return; + } + + // reason === "resume" - check if there are unsaved changes (messages since last assistant response) + const entries = ctx.sessionManager.getEntries(); + const hasUnsavedWork = entries.some( + (e): e is SessionMessageEntry => e.type === "message" && e.message.role === "user", + ); + + if (hasUnsavedWork) { + const confirmed = await ctx.ui.confirm( + "Switch session?", + "You have messages in the current session. Switch anyway?", + ); + + if (!confirmed) { + ctx.ui.notify("Switch cancelled", "info"); + return { cancel: true }; + } + } + }); + + pi.on("session_before_fork", async (event, ctx) => { + if (!ctx.hasUI) return; + + const choice = await ctx.ui.select(`Fork from entry ${event.entryId.slice(0, 8)}?`, [ + "Yes, create fork", + "No, stay in current session", + ]); + + if (choice !== "Yes, create fork") { + ctx.ui.notify("Fork cancelled", "info"); + return { cancel: true }; + } + }); +} diff --git a/examples/extensions/custom-compaction.ts b/examples/extensions/custom-compaction.ts new file mode 100644 index 0000000..e5ec408 --- /dev/null +++ b/examples/extensions/custom-compaction.ts @@ -0,0 +1,132 @@ +/** + * Custom Compaction Extension + * + * Replaces the default compaction behavior with a full summary of the entire context. + * Instead of keeping the last 20k tokens of conversation turns, this extension: + * 1. Summarizes ALL messages (messagesToSummarize + turnPrefixMessages) + * 2. Discards all old turns completely, keeping only the summary + * + * This example also demonstrates using a different model (Gemini Flash) for summarization, + * which can be cheaper/faster than the main conversation model. + * + * Usage: + * pi --extension examples/extensions/custom-compaction.ts + */ + +import { uuidv7 } from "@earendil-works/pi-ai"; +import { complete } from "@earendil-works/pi-ai/compat"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { convertToLlm, serializeConversation } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.on("session_before_compact", async (event, ctx) => { + ctx.ui.notify("Custom compaction extension triggered", "info"); + + const { preparation, branchEntries: _, signal } = event; + const { messagesToSummarize, turnPrefixMessages, tokensBefore, firstKeptEntryId, previousSummary } = preparation; + + // Use Gemini Flash for summarization (cheaper/faster than most conversation models) + const model = ctx.modelRegistry.find("google", "gemini-2.5-flash"); + if (!model) { + ctx.ui.notify(`Could not find Gemini Flash model, using default compaction`, "warning"); + return; + } + + // Resolve request auth for the summarization model + const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model); + if (!auth.ok) { + ctx.ui.notify(`Compaction auth failed: ${auth.error}`, "warning"); + return; + } + if (!auth.apiKey) { + ctx.ui.notify(`No API key for ${model.provider}, using default compaction`, "warning"); + return; + } + + // Combine all messages for full summary + const allMessages = [...messagesToSummarize, ...turnPrefixMessages]; + + ctx.ui.notify( + `Custom compaction: summarizing ${allMessages.length} messages (${tokensBefore.toLocaleString()} tokens) with ${model.id}...`, + "info", + ); + + // Convert messages to readable text format + const conversationText = serializeConversation(convertToLlm(allMessages)); + + // Include previous summary context if available + const previousContext = previousSummary ? `\n\nPrevious session summary for context:\n${previousSummary}` : ""; + + // Build messages that ask for a comprehensive summary + const summaryMessages = [ + { + role: "user" as const, + content: [ + { + type: "text" as const, + text: `You are a conversation summarizer. Create a comprehensive summary of this conversation that captures:${previousContext} + +1. The main goals and objectives discussed +2. Key decisions made and their rationale +3. Important code changes, file modifications, or technical details +4. Current state of any ongoing work +5. Any blockers, issues, or open questions +6. Next steps that were planned or suggested + +Be thorough but concise. The summary will replace the ENTIRE conversation history, so include all information needed to continue the work effectively. + +Format the summary as structured markdown with clear sections. + + +${conversationText} +`, + }, + ], + timestamp: Date.now(), + }, + ]; + + try { + // Pass signal to honor abort requests (e.g., user cancels compaction) + const response = await complete( + model, + { messages: summaryMessages }, + { + apiKey: auth.apiKey, + headers: auth.headers, + env: auth.env, + maxTokens: 8192, + signal, + cacheRetention: "none", + sessionId: uuidv7(), + }, + ); + + const summary = response.content + .filter((c): c is { type: "text"; text: string } => c.type === "text") + .map((c) => c.text) + .join("\n"); + + if (!summary.trim()) { + if (!signal.aborted) ctx.ui.notify("Compaction summary was empty, using default compaction", "warning"); + return; + } + + // Return compaction content - SessionManager adds id/parentId + // Use firstKeptEntryId from preparation to keep recent messages + return { + compaction: { + summary, + firstKeptEntryId, + tokensBefore, + usage: response.usage, + }, + }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + ctx.ui.notify(`Compaction failed: ${message}`, "error"); + // Fall back to default compaction on error + return; + } + }); +} diff --git a/examples/extensions/custom-footer.ts b/examples/extensions/custom-footer.ts new file mode 100644 index 0000000..15e41e0 --- /dev/null +++ b/examples/extensions/custom-footer.ts @@ -0,0 +1,64 @@ +/** + * Custom Footer Extension - demonstrates ctx.ui.setFooter() + * + * footerData exposes data not otherwise accessible: + * - getGitBranch(): current git branch + * - getExtensionStatuses(): texts from ctx.ui.setStatus() + * + * Token stats come from ctx.sessionManager/ctx.model (already accessible). + */ + +import type { AssistantMessage } from "@earendil-works/pi-ai"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; + +export default function (pi: ExtensionAPI) { + let enabled = false; + + pi.registerCommand("footer", { + description: "Toggle custom footer", + handler: async (_args, ctx) => { + enabled = !enabled; + + if (enabled) { + ctx.ui.setFooter((tui, theme, footerData) => { + const unsub = footerData.onBranchChange(() => tui.requestRender()); + + return { + dispose: unsub, + invalidate() {}, + render(width: number): string[] { + // Compute tokens from ctx (already accessible to extensions) + let input = 0, + output = 0, + cost = 0; + for (const e of ctx.sessionManager.getBranch()) { + if (e.type === "message" && e.message.role === "assistant") { + const m = e.message as AssistantMessage; + input += m.usage.input; + output += m.usage.output; + cost += m.usage.cost.total; + } + } + + // Get git branch (not otherwise accessible) + const branch = footerData.getGitBranch(); + const fmt = (n: number) => (n < 1000 ? `${n}` : `${(n / 1000).toFixed(1)}k`); + + const left = theme.fg("dim", `↑${fmt(input)} ↓${fmt(output)} $${cost.toFixed(3)}`); + const branchStr = branch ? ` (${branch})` : ""; + const right = theme.fg("dim", `${ctx.model?.id || "no-model"}${branchStr}`); + + const pad = " ".repeat(Math.max(1, width - visibleWidth(left) - visibleWidth(right))); + return [truncateToWidth(left + pad + right, width)]; + }, + }; + }); + ctx.ui.notify("Custom footer enabled", "info"); + } else { + ctx.ui.setFooter(undefined); + ctx.ui.notify("Default footer restored", "info"); + } + }, + }); +} diff --git a/examples/extensions/custom-header.ts b/examples/extensions/custom-header.ts new file mode 100644 index 0000000..600a85c --- /dev/null +++ b/examples/extensions/custom-header.ts @@ -0,0 +1,73 @@ +/** + * Custom Header Extension + * + * Demonstrates ctx.ui.setHeader() for replacing the built-in header + * (logo + keybinding hints) with a custom component showing the pi mascot. + */ + +import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent"; +import { VERSION } from "@earendil-works/pi-coding-agent"; + +// --- PI MASCOT --- +// Based on pi_mascot.ts - the pi agent character +function getPiMascot(theme: Theme): string[] { + // --- COLORS --- + // 3b1b Blue: R=80, G=180, B=230 + const piBlue = (text: string) => theme.fg("accent", text); + const white = (text: string) => text; // Use plain white (or theme.fg("text", text)) + const black = (text: string) => theme.fg("dim", text); // Use dim for contrast + + // --- GLYPHS --- + const BLOCK = "█"; + const PUPIL = "▌"; // Vertical half-block for the pupil + + // --- CONSTRUCTION --- + + // 1. The Eye Unit: [White Full Block][Black Vertical Sliver] + // This creates the "looking sideways" effect + const eye = `${white(BLOCK)}${black(PUPIL)}`; + + // 2. Line 1: The Eyes + // 5 spaces indent aligns them with the start of the legs + const lineEyes = ` ${eye} ${eye}`; + + // 3. Line 2: The Wide Top Bar (The "Overhang") + // 14 blocks wide for that serif-style roof + const lineBar = ` ${piBlue(BLOCK.repeat(14))}`; + + // 4. Lines 3-6: The Legs + // Indented 5 spaces relative to the very left edge + // Leg width: 2 blocks | Gap: 4 blocks + const lineLeg = ` ${piBlue(BLOCK.repeat(2))} ${piBlue(BLOCK.repeat(2))}`; + + // --- ASSEMBLY --- + return ["", lineEyes, lineBar, lineLeg, lineLeg, lineLeg, lineLeg, ""]; +} + +export default function (pi: ExtensionAPI) { + // Set custom header immediately on load (if UI is available) + pi.on("session_start", async (_event, ctx) => { + if (ctx.mode === "tui") { + ctx.ui.setHeader((_tui, theme) => { + return { + render(_width: number): string[] { + const mascotLines = getPiMascot(theme); + // Add a subtitle with hint + const subtitle = `${theme.fg("muted", " shitty coding agent")}${theme.fg("dim", ` v${VERSION}`)}`; + return [...mascotLines, subtitle]; + }, + invalidate() {}, + }; + }); + } + }); + + // Command to restore built-in header + pi.registerCommand("builtin-header", { + description: "Restore built-in header with keybinding hints", + handler: async (_args, ctx) => { + ctx.ui.setHeader(undefined); + ctx.ui.notify("Built-in header restored", "info"); + }, + }); +} diff --git a/examples/extensions/custom-provider-anthropic/index.ts b/examples/extensions/custom-provider-anthropic/index.ts new file mode 100644 index 0000000..45304be --- /dev/null +++ b/examples/extensions/custom-provider-anthropic/index.ts @@ -0,0 +1,610 @@ +/** + * Custom Provider Example + * + * Demonstrates registering a custom provider with: + * - Custom API identifier ("custom-anthropic-api") + * - Custom streamSimple implementation + * - OAuth support for /login + * - API key support via environment variable + * - Two model definitions + * + * Usage: + * # First install dependencies + * cd packages/coding-agent/examples/extensions/custom-provider && npm install + * + * # With OAuth (run /login custom-anthropic first) + * pi -e ./packages/coding-agent/examples/extensions/custom-provider + * + * # With API key + * CUSTOM_ANTHROPIC_API_KEY=sk-ant-... pi -e ./packages/coding-agent/examples/extensions/custom-provider + * + * Then use /model to select custom-anthropic/claude-sonnet-4-5 + */ + +import Anthropic from "@anthropic-ai/sdk"; +import type { ContentBlockParam, MessageCreateParamsStreaming } from "@anthropic-ai/sdk/resources/messages.js"; +import { + type Api, + type AssistantMessage, + type AssistantMessageEventStream, + type Context, + calculateCost, + createAssistantMessageEventStream, + type ImageContent, + type Message, + type Model, + type OAuthCredentials, + type OAuthLoginCallbacks, + type SimpleStreamOptions, + type StopReason, + type TextContent, + type ThinkingContent, + type Tool, + type ToolCall, + type ToolResultMessage, +} from "@earendil-works/pi-ai"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +// ============================================================================= +// OAuth implementation adapted for the legacy extension compatibility interface. +// ============================================================================= + +const decode = (s: string) => atob(s); +const CLIENT_ID = decode("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"); +const AUTHORIZE_URL = "https://claude.ai/oauth/authorize"; +const TOKEN_URL = "https://console.anthropic.com/v1/oauth/token"; +const REDIRECT_URI = "https://console.anthropic.com/oauth/code/callback"; +const SCOPES = "org:create_api_key user:profile user:inference"; + +async function generatePKCE(): Promise<{ verifier: string; challenge: string }> { + const array = new Uint8Array(32); + crypto.getRandomValues(array); + const verifier = btoa(String.fromCharCode(...array)) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); + + const encoder = new TextEncoder(); + const data = encoder.encode(verifier); + const hash = await crypto.subtle.digest("SHA-256", data); + const challenge = btoa(String.fromCharCode(...new Uint8Array(hash))) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); + + return { verifier, challenge }; +} + +async function loginAnthropic(callbacks: OAuthLoginCallbacks): Promise { + const { verifier, challenge } = await generatePKCE(); + + const authParams = new URLSearchParams({ + code: "true", + client_id: CLIENT_ID, + response_type: "code", + redirect_uri: REDIRECT_URI, + scope: SCOPES, + code_challenge: challenge, + code_challenge_method: "S256", + state: verifier, + }); + + callbacks.onAuth({ url: `${AUTHORIZE_URL}?${authParams.toString()}` }); + + const authCode = await callbacks.onPrompt({ message: "Paste the authorization code:" }); + const [code, state] = authCode.split("#"); + + const tokenResponse = await fetch(TOKEN_URL, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + grant_type: "authorization_code", + client_id: CLIENT_ID, + code, + state, + redirect_uri: REDIRECT_URI, + code_verifier: verifier, + }), + }); + + if (!tokenResponse.ok) { + throw new Error(`Token exchange failed: ${await tokenResponse.text()}`); + } + + const data = (await tokenResponse.json()) as { + access_token: string; + refresh_token: string; + expires_in: number; + }; + + return { + refresh: data.refresh_token, + access: data.access_token, + expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000, + }; +} + +async function refreshAnthropicToken(credentials: OAuthCredentials): Promise { + const response = await fetch(TOKEN_URL, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + grant_type: "refresh_token", + client_id: CLIENT_ID, + refresh_token: credentials.refresh, + }), + }); + + if (!response.ok) { + throw new Error(`Token refresh failed: ${await response.text()}`); + } + + const data = (await response.json()) as { + access_token: string; + refresh_token: string; + expires_in: number; + }; + + return { + refresh: data.refresh_token, + access: data.access_token, + expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000, + }; +} + +// ============================================================================= +// Streaming Implementation (simplified from packages/ai/src/api/anthropic-messages.ts) +// ============================================================================= + +// Claude Code tool names for OAuth stealth mode +const claudeCodeTools = [ + "Read", + "Write", + "Edit", + "Bash", + "Grep", + "Glob", + "AskUserQuestion", + "TodoWrite", + "WebFetch", + "WebSearch", +]; +const ccToolLookup = new Map(claudeCodeTools.map((t) => [t.toLowerCase(), t])); +const toClaudeCodeName = (name: string) => ccToolLookup.get(name.toLowerCase()) ?? name; +const fromClaudeCodeName = (name: string, tools?: Tool[]) => { + const lowerName = name.toLowerCase(); + const matched = tools?.find((t) => t.name.toLowerCase() === lowerName); + return matched?.name ?? name; +}; + +function isOAuthToken(apiKey: string): boolean { + return apiKey.includes("sk-ant-oat"); +} + +function sanitizeSurrogates(text: string): string { + return text.replace(/[\uD800-\uDFFF]/g, "\uFFFD"); +} + +function convertContentBlocks( + content: (TextContent | ImageContent)[], +): string | Array<{ type: "text"; text: string } | { type: "image"; source: any }> { + const hasImages = content.some((c) => c.type === "image"); + if (!hasImages) { + return sanitizeSurrogates(content.map((c) => (c as TextContent).text).join("\n")); + } + + const blocks = content.map((block) => { + if (block.type === "text") { + return { type: "text" as const, text: sanitizeSurrogates(block.text) }; + } + return { + type: "image" as const, + source: { + type: "base64" as const, + media_type: block.mimeType, + data: block.data, + }, + }; + }); + + if (!blocks.some((b) => b.type === "text")) { + blocks.unshift({ type: "text" as const, text: "(see attached image)" }); + } + + return blocks; +} + +function convertMessages(messages: Message[], isOAuth: boolean, _tools?: Tool[]): any[] { + const params: any[] = []; + + for (let i = 0; i < messages.length; i++) { + const msg = messages[i]; + + if (msg.role === "user") { + if (typeof msg.content === "string") { + if (msg.content.trim()) { + params.push({ role: "user", content: sanitizeSurrogates(msg.content) }); + } + } else { + const blocks: ContentBlockParam[] = msg.content.map((item) => + item.type === "text" + ? { type: "text" as const, text: sanitizeSurrogates(item.text) } + : { + type: "image" as const, + source: { type: "base64" as const, media_type: item.mimeType as any, data: item.data }, + }, + ); + if (blocks.length > 0) { + params.push({ role: "user", content: blocks }); + } + } + } else if (msg.role === "assistant") { + const blocks: ContentBlockParam[] = []; + for (const block of msg.content) { + if (block.type === "text" && block.text.trim()) { + blocks.push({ type: "text", text: sanitizeSurrogates(block.text) }); + } else if (block.type === "thinking" && block.thinking.trim()) { + if ((block as ThinkingContent).thinkingSignature) { + blocks.push({ + type: "thinking" as any, + thinking: sanitizeSurrogates(block.thinking), + signature: (block as ThinkingContent).thinkingSignature!, + }); + } else { + blocks.push({ type: "text", text: sanitizeSurrogates(block.thinking) }); + } + } else if (block.type === "toolCall") { + blocks.push({ + type: "tool_use", + id: block.id, + name: isOAuth ? toClaudeCodeName(block.name) : block.name, + input: block.arguments, + }); + } + } + if (blocks.length > 0) { + params.push({ role: "assistant", content: blocks }); + } + } else if (msg.role === "toolResult") { + const toolResults: any[] = []; + toolResults.push({ + type: "tool_result", + tool_use_id: msg.toolCallId, + content: convertContentBlocks(msg.content), + is_error: msg.isError, + }); + + let j = i + 1; + while (j < messages.length && messages[j].role === "toolResult") { + const nextMsg = messages[j] as ToolResultMessage; + toolResults.push({ + type: "tool_result", + tool_use_id: nextMsg.toolCallId, + content: convertContentBlocks(nextMsg.content), + is_error: nextMsg.isError, + }); + j++; + } + i = j - 1; + params.push({ role: "user", content: toolResults }); + } + } + + // Add cache control to last user message + if (params.length > 0) { + const last = params[params.length - 1]; + if (last.role === "user" && Array.isArray(last.content)) { + const lastBlock = last.content[last.content.length - 1]; + if (lastBlock) { + lastBlock.cache_control = { type: "ephemeral" }; + } + } + } + + return params; +} + +function convertTools(tools: Tool[], isOAuth: boolean): any[] { + return tools.map((tool) => ({ + name: isOAuth ? toClaudeCodeName(tool.name) : tool.name, + description: tool.description, + input_schema: { + type: "object", + properties: (tool.parameters as any).properties || {}, + required: (tool.parameters as any).required || [], + }, + })); +} + +function mapStopReason(reason: string): StopReason { + switch (reason) { + case "end_turn": + case "pause_turn": + case "stop_sequence": + return "stop"; + case "max_tokens": + return "length"; + case "tool_use": + return "toolUse"; + default: + return "error"; + } +} + +function streamCustomAnthropic( + model: Model, + context: Context, + options?: SimpleStreamOptions, +): AssistantMessageEventStream { + const stream = createAssistantMessageEventStream(); + + (async () => { + const output: AssistantMessage = { + role: "assistant", + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "pending", + timestamp: Date.now(), + }; + + try { + const apiKey = options?.apiKey ?? ""; + const isOAuth = isOAuthToken(apiKey); + + // Configure client based on auth type + const betaFeatures = ["fine-grained-tool-streaming-2025-05-14", "interleaved-thinking-2025-05-14"]; + const clientOptions: any = { + baseURL: model.baseUrl, + dangerouslyAllowBrowser: true, + }; + + if (isOAuth) { + clientOptions.apiKey = null; + clientOptions.authToken = apiKey; + clientOptions.defaultHeaders = { + accept: "application/json", + "anthropic-dangerous-direct-browser-access": "true", + "anthropic-beta": `claude-code-20250219,oauth-2025-04-20,${betaFeatures.join(",")}`, + "user-agent": "claude-cli/2.1.2 (external, cli)", + "x-app": "cli", + }; + } else { + clientOptions.apiKey = apiKey; + clientOptions.defaultHeaders = { + accept: "application/json", + "anthropic-dangerous-direct-browser-access": "true", + "anthropic-beta": betaFeatures.join(","), + }; + } + + const client = new Anthropic(clientOptions); + + // Build request params + const params: MessageCreateParamsStreaming = { + model: model.id, + messages: convertMessages(context.messages, isOAuth, context.tools), + max_tokens: options?.maxTokens || Math.floor(model.maxTokens / 3), + stream: true, + }; + + // System prompt with Claude Code identity for OAuth + if (isOAuth) { + params.system = [ + { + type: "text", + text: "You are Claude Code, Anthropic's official CLI for Claude.", + cache_control: { type: "ephemeral" }, + }, + ]; + if (context.systemPrompt) { + params.system.push({ + type: "text", + text: sanitizeSurrogates(context.systemPrompt), + cache_control: { type: "ephemeral" }, + }); + } + } else if (context.systemPrompt) { + params.system = [ + { + type: "text", + text: sanitizeSurrogates(context.systemPrompt), + cache_control: { type: "ephemeral" }, + }, + ]; + } + + if (context.tools) { + params.tools = convertTools(context.tools, isOAuth); + } + + // Handle thinking/reasoning + if (options?.reasoning && model.reasoning) { + const defaultBudgets: Record = { + minimal: 1024, + low: 4096, + medium: 10240, + high: 20480, + }; + const customBudget = options.thinkingBudgets?.[options.reasoning as keyof typeof options.thinkingBudgets]; + params.thinking = { + type: "enabled", + budget_tokens: customBudget ?? defaultBudgets[options.reasoning] ?? 10240, + }; + } + + const anthropicStream = client.messages.stream({ ...params }, { signal: options?.signal }); + stream.push({ type: "start", partial: output }); + + type Block = (ThinkingContent | TextContent | (ToolCall & { partialJson: string })) & { index: number }; + const blocks = output.content as Block[]; + + for await (const event of anthropicStream) { + if (event.type === "message_start") { + output.usage.input = event.message.usage.input_tokens || 0; + output.usage.output = event.message.usage.output_tokens || 0; + output.usage.cacheRead = (event.message.usage as any).cache_read_input_tokens || 0; + output.usage.cacheWrite = (event.message.usage as any).cache_creation_input_tokens || 0; + output.usage.totalTokens = + output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite; + calculateCost(model, output.usage); + } else if (event.type === "content_block_start") { + if (event.content_block.type === "text") { + output.content.push({ type: "text", text: "", index: event.index } as any); + stream.push({ type: "text_start", contentIndex: output.content.length - 1, partial: output }); + } else if (event.content_block.type === "thinking") { + output.content.push({ + type: "thinking", + thinking: "", + thinkingSignature: "", + index: event.index, + } as any); + stream.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output }); + } else if (event.content_block.type === "tool_use") { + output.content.push({ + type: "toolCall", + id: event.content_block.id, + name: isOAuth + ? fromClaudeCodeName(event.content_block.name, context.tools) + : event.content_block.name, + arguments: {}, + partialJson: "", + index: event.index, + } as any); + stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output }); + } + } else if (event.type === "content_block_delta") { + const index = blocks.findIndex((b) => b.index === event.index); + const block = blocks[index]; + if (!block) continue; + + if (event.delta.type === "text_delta" && block.type === "text") { + block.text += event.delta.text; + stream.push({ type: "text_delta", contentIndex: index, delta: event.delta.text, partial: output }); + } else if (event.delta.type === "thinking_delta" && block.type === "thinking") { + block.thinking += event.delta.thinking; + stream.push({ + type: "thinking_delta", + contentIndex: index, + delta: event.delta.thinking, + partial: output, + }); + } else if (event.delta.type === "input_json_delta" && block.type === "toolCall") { + (block as any).partialJson += event.delta.partial_json; + try { + block.arguments = JSON.parse((block as any).partialJson); + } catch {} + stream.push({ + type: "toolcall_delta", + contentIndex: index, + delta: event.delta.partial_json, + partial: output, + }); + } else if (event.delta.type === "signature_delta" && block.type === "thinking") { + block.thinkingSignature = (block.thinkingSignature || "") + (event.delta as any).signature; + } + } else if (event.type === "content_block_stop") { + const index = blocks.findIndex((b) => b.index === event.index); + const block = blocks[index]; + if (!block) continue; + + delete (block as any).index; + if (block.type === "text") { + stream.push({ type: "text_end", contentIndex: index, content: block.text, partial: output }); + } else if (block.type === "thinking") { + stream.push({ type: "thinking_end", contentIndex: index, content: block.thinking, partial: output }); + } else if (block.type === "toolCall") { + try { + block.arguments = JSON.parse((block as any).partialJson); + } catch {} + delete (block as any).partialJson; + stream.push({ type: "toolcall_end", contentIndex: index, toolCall: block, partial: output }); + } + } else if (event.type === "message_delta") { + if ((event.delta as any).stop_reason) { + output.stopReason = mapStopReason((event.delta as any).stop_reason); + } + output.usage.input = (event.usage as any).input_tokens || 0; + output.usage.output = (event.usage as any).output_tokens || 0; + output.usage.cacheRead = (event.usage as any).cache_read_input_tokens || 0; + output.usage.cacheWrite = (event.usage as any).cache_creation_input_tokens || 0; + output.usage.totalTokens = + output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite; + calculateCost(model, output.usage); + } + } + + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "pending") { + throw new Error("Anthropic stream ended without a stop reason"); + } + if (output.stopReason === "error" || output.stopReason === "aborted") { + throw new Error(output.errorMessage || "An unknown error occurred"); + } + + stream.push({ type: "done", reason: output.stopReason, message: output }); + stream.end(); + } catch (error) { + for (const block of output.content) delete (block as any).index; + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error); + stream.push({ type: "error", reason: output.stopReason, error: output }); + stream.end(); + } + })(); + + return stream; +} + +// ============================================================================= +// Extension Entry Point +// ============================================================================= + +export default function (pi: ExtensionAPI) { + pi.registerProvider("custom-anthropic", { + baseUrl: "https://api.anthropic.com", + apiKey: "$CUSTOM_ANTHROPIC_API_KEY", + api: "custom-anthropic-api", + + models: [ + { + id: "claude-opus-4-5", + name: "Claude Opus 4.5 (Custom)", + reasoning: true, + input: ["text", "image"], + cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 }, + contextWindow: 200000, + maxTokens: 64000, + }, + { + id: "claude-sonnet-4-5", + name: "Claude Sonnet 4.5 (Custom)", + reasoning: true, + input: ["text", "image"], + cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 }, + contextWindow: 200000, + maxTokens: 64000, + }, + ], + + oauth: { + name: "Custom Anthropic (Claude Pro/Max)", + login: loginAnthropic, + refreshToken: refreshAnthropicToken, + getApiKey: (cred) => cred.access, + }, + + streamSimple: streamCustomAnthropic, + }); +} diff --git a/examples/extensions/custom-provider-anthropic/package-lock.json b/examples/extensions/custom-provider-anthropic/package-lock.json new file mode 100644 index 0000000..cd8b869 --- /dev/null +++ b/examples/extensions/custom-provider-anthropic/package-lock.json @@ -0,0 +1,24 @@ +{ + "name": "pi-extension-custom-provider", + "version": "0.83.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "pi-extension-custom-provider", + "version": "0.83.0", + "dependencies": { + "@anthropic-ai/sdk": "^0.52.0" + } + }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.52.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.52.0.tgz", + "integrity": "sha512-d4c+fg+xy9e46c8+YnrrgIQR45CZlAi7PwdzIfDXDM6ACxEZli1/fxhURsq30ZpMZy6LvSkr41jGq5aF5TD7rQ==", + "license": "MIT", + "bin": { + "anthropic-ai-sdk": "bin/cli" + } + } + } +} diff --git a/examples/extensions/custom-provider-anthropic/package.json b/examples/extensions/custom-provider-anthropic/package.json new file mode 100644 index 0000000..7899726 --- /dev/null +++ b/examples/extensions/custom-provider-anthropic/package.json @@ -0,0 +1,19 @@ +{ + "name": "pi-extension-custom-provider-anthropic", + "private": true, + "version": "0.83.0", + "type": "module", + "scripts": { + "clean": "echo 'nothing to clean'", + "build": "echo 'nothing to build'", + "check": "echo 'nothing to check'" + }, + "pi": { + "extensions": [ + "./index.ts" + ] + }, + "dependencies": { + "@anthropic-ai/sdk": "0.52.0" + } +} diff --git a/examples/extensions/custom-provider-gitlab-duo/index.ts b/examples/extensions/custom-provider-gitlab-duo/index.ts new file mode 100644 index 0000000..60e5a27 --- /dev/null +++ b/examples/extensions/custom-provider-gitlab-duo/index.ts @@ -0,0 +1,404 @@ +/** + * GitLab Duo Provider Extension + * + * Provides access to GitLab Duo AI models (Claude and GPT) through GitLab's AI Gateway. + * Delegates to pi-ai's built-in Anthropic and OpenAI streaming implementations. + * + * Usage: + * pi -e ./packages/coding-agent/examples/extensions/custom-provider-gitlab-duo + * # Then /login gitlab-duo, or set GITLAB_TOKEN=glpat-... + */ + +import { + type Api, + type AssistantMessageEventStream, + anthropicMessagesApi, + type Context, + createAssistantMessageEventStream, + type Model, + type OAuthCredentials, + type OAuthLoginCallbacks, + openAIResponsesApi, + type SimpleStreamOptions, + type ThinkingLevelMap, +} from "@earendil-works/pi-ai/compat"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +// ============================================================================= +// Constants +// ============================================================================= + +const GITLAB_COM_URL = "https://gitlab.com"; +const AI_GATEWAY_URL = "https://cloud.gitlab.com"; +const ANTHROPIC_PROXY_URL = `${AI_GATEWAY_URL}/ai/v1/proxy/anthropic/`; +const OPENAI_PROXY_URL = `${AI_GATEWAY_URL}/ai/v1/proxy/openai/v1`; + +const BUNDLED_CLIENT_ID = "da4edff2e6ebd2bc3208611e2768bc1c1dd7be791dc5ff26ca34ca9ee44f7d4b"; +const OAUTH_SCOPES = ["api"]; +const REDIRECT_URI = "http://127.0.0.1:8080/callback"; +const DIRECT_ACCESS_TTL = 25 * 60 * 1000; + +// ============================================================================= +// Models - exported for use by tests +// ============================================================================= + +type Backend = "anthropic" | "openai"; + +interface GitLabModel { + id: string; + name: string; + backend: Backend; + baseUrl: string; + reasoning: boolean; + thinkingLevelMap?: ThinkingLevelMap; + input: ("text" | "image")[]; + cost: { input: number; output: number; cacheRead: number; cacheWrite: number }; + contextWindow: number; + maxTokens: number; +} + +export const MODELS: GitLabModel[] = [ + // Anthropic + { + id: "claude-opus-4-8", + name: "Claude Opus 4.8", + backend: "anthropic", + baseUrl: ANTHROPIC_PROXY_URL, + reasoning: true, + thinkingLevelMap: { xhigh: "max" }, + input: ["text", "image"], + cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 }, + contextWindow: 1000000, + maxTokens: 128000, + }, + { + id: "claude-sonnet-4-6", + name: "Claude Sonnet 4.6", + backend: "anthropic", + baseUrl: ANTHROPIC_PROXY_URL, + reasoning: true, + thinkingLevelMap: { xhigh: "max" }, + input: ["text", "image"], + cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 }, + contextWindow: 1000000, + maxTokens: 64000, + }, + { + id: "claude-opus-4-5-20251101", + name: "Claude Opus 4.5", + backend: "anthropic", + baseUrl: ANTHROPIC_PROXY_URL, + reasoning: true, + thinkingLevelMap: { xhigh: "max" }, + input: ["text", "image"], + cost: { input: 15, output: 75, cacheRead: 1.5, cacheWrite: 18.75 }, + contextWindow: 200000, + maxTokens: 32000, + }, + { + id: "claude-sonnet-4-5-20250929", + name: "Claude Sonnet 4.5", + backend: "anthropic", + baseUrl: ANTHROPIC_PROXY_URL, + reasoning: true, + thinkingLevelMap: { xhigh: "max" }, + input: ["text", "image"], + cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 }, + contextWindow: 200000, + maxTokens: 16384, + }, + { + id: "claude-haiku-4-5-20251001", + name: "Claude Haiku 4.5", + backend: "anthropic", + baseUrl: ANTHROPIC_PROXY_URL, + reasoning: true, + thinkingLevelMap: { xhigh: "max" }, + input: ["text", "image"], + cost: { input: 1, output: 5, cacheRead: 0.1, cacheWrite: 1.25 }, + contextWindow: 200000, + maxTokens: 8192, + }, + // OpenAI (all use Responses API) + { + id: "gpt-5.5-2026-04-23", + name: "GPT-5.5", + backend: "openai", + baseUrl: OPENAI_PROXY_URL, + reasoning: true, + input: ["text", "image"], + cost: { input: 5, output: 30, cacheRead: 0.5, cacheWrite: 0 }, + contextWindow: 272000, + maxTokens: 128000, + }, + { + id: "gpt-5.1-2025-11-13", + name: "GPT-5.1", + backend: "openai", + baseUrl: OPENAI_PROXY_URL, + reasoning: true, + input: ["text", "image"], + cost: { input: 2.5, output: 10, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 128000, + maxTokens: 16384, + }, + { + id: "gpt-5-mini-2025-08-07", + name: "GPT-5 Mini", + backend: "openai", + baseUrl: OPENAI_PROXY_URL, + reasoning: true, + input: ["text", "image"], + cost: { input: 0.15, output: 0.6, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 128000, + maxTokens: 16384, + }, + { + id: "gpt-5-codex", + name: "GPT-5 Codex", + backend: "openai", + baseUrl: OPENAI_PROXY_URL, + reasoning: true, + input: ["text", "image"], + cost: { input: 2.5, output: 10, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 128000, + maxTokens: 16384, + }, +]; + +const MODEL_MAP = new Map(MODELS.map((m) => [m.id, m])); + +// ============================================================================= +// Direct Access Token Cache +// ============================================================================= + +interface DirectAccessToken { + token: string; + headers: Record; + expiresAt: number; +} + +let cachedDirectAccess: DirectAccessToken | null = null; + +async function getDirectAccessToken(gitlabAccessToken: string): Promise { + const now = Date.now(); + if (cachedDirectAccess && cachedDirectAccess.expiresAt > now) { + return cachedDirectAccess; + } + + const response = await fetch(`${GITLAB_COM_URL}/api/v4/ai/third_party_agents/direct_access`, { + method: "POST", + headers: { Authorization: `Bearer ${gitlabAccessToken}`, "Content-Type": "application/json" }, + body: JSON.stringify({ feature_flags: { DuoAgentPlatformNext: true } }), + }); + + if (!response.ok) { + const errorText = await response.text(); + if (response.status === 403) { + throw new Error( + `GitLab Duo access denied. Ensure GitLab Duo is enabled for your account. Error: ${errorText}`, + ); + } + throw new Error(`Failed to get direct access token: ${response.status} ${errorText}`); + } + + const data = (await response.json()) as { token: string; headers: Record }; + cachedDirectAccess = { token: data.token, headers: data.headers, expiresAt: now + DIRECT_ACCESS_TTL }; + return cachedDirectAccess; +} + +function invalidateDirectAccessToken() { + cachedDirectAccess = null; +} + +// ============================================================================= +// OAuth +// ============================================================================= + +async function generatePKCE(): Promise<{ verifier: string; challenge: string }> { + const array = new Uint8Array(32); + crypto.getRandomValues(array); + const verifier = btoa(String.fromCharCode(...array)) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); + const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)); + const challenge = btoa(String.fromCharCode(...new Uint8Array(hash))) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); + return { verifier, challenge }; +} + +async function loginGitLab(callbacks: OAuthLoginCallbacks): Promise { + const { verifier, challenge } = await generatePKCE(); + const authParams = new URLSearchParams({ + client_id: BUNDLED_CLIENT_ID, + redirect_uri: REDIRECT_URI, + response_type: "code", + scope: OAUTH_SCOPES.join(" "), + code_challenge: challenge, + code_challenge_method: "S256", + state: crypto.randomUUID(), + }); + + callbacks.onAuth({ url: `${GITLAB_COM_URL}/oauth/authorize?${authParams.toString()}` }); + const callbackUrl = await callbacks.onPrompt({ message: "Paste the callback URL:" }); + const code = new URL(callbackUrl).searchParams.get("code"); + if (!code) throw new Error("No authorization code found in callback URL"); + + const tokenResponse = await fetch(`${GITLAB_COM_URL}/oauth/token`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + client_id: BUNDLED_CLIENT_ID, + grant_type: "authorization_code", + code, + code_verifier: verifier, + redirect_uri: REDIRECT_URI, + }).toString(), + }); + + if (!tokenResponse.ok) throw new Error(`Token exchange failed: ${await tokenResponse.text()}`); + const data = (await tokenResponse.json()) as { + access_token: string; + refresh_token: string; + expires_in: number; + created_at: number; + }; + invalidateDirectAccessToken(); + return { + refresh: data.refresh_token, + access: data.access_token, + expires: (data.created_at + data.expires_in) * 1000 - 5 * 60 * 1000, + }; +} + +async function refreshGitLabToken(credentials: OAuthCredentials): Promise { + const response = await fetch(`${GITLAB_COM_URL}/oauth/token`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + client_id: BUNDLED_CLIENT_ID, + grant_type: "refresh_token", + refresh_token: credentials.refresh, + }).toString(), + }); + if (!response.ok) throw new Error(`Token refresh failed: ${await response.text()}`); + const data = (await response.json()) as { + access_token: string; + refresh_token: string; + expires_in: number; + created_at: number; + }; + invalidateDirectAccessToken(); + return { + refresh: data.refresh_token, + access: data.access_token, + expires: (data.created_at + data.expires_in) * 1000 - 5 * 60 * 1000, + }; +} + +// ============================================================================= +// Stream Function +// ============================================================================= + +export function streamGitLabDuo( + model: Model, + context: Context, + options?: SimpleStreamOptions, +): AssistantMessageEventStream { + const stream = createAssistantMessageEventStream(); + + (async () => { + try { + const gitlabAccessToken = options?.apiKey; + if (!gitlabAccessToken) throw new Error("No GitLab access token. Run /login gitlab-duo or set GITLAB_TOKEN"); + + const cfg = MODEL_MAP.get(model.id); + if (!cfg) throw new Error(`Unknown model: ${model.id}`); + + const directAccess = await getDirectAccessToken(gitlabAccessToken); + const modelWithBaseUrl = { ...model, baseUrl: cfg.baseUrl }; + const headers = { ...directAccess.headers, Authorization: `Bearer ${directAccess.token}` }; + const streamOptions = { ...options, apiKey: "gitlab-duo", headers }; + + const innerStream = + cfg.backend === "anthropic" + ? anthropicMessagesApi().streamSimple( + { + ...(modelWithBaseUrl as Model<"anthropic-messages">), + compat: { + ...(modelWithBaseUrl as Model<"anthropic-messages">).compat, + forceAdaptiveThinking: true, + }, + }, + context, + streamOptions, + ) + : openAIResponsesApi().streamSimple( + modelWithBaseUrl as Model<"openai-responses">, + context, + streamOptions, + ); + + for await (const event of innerStream) stream.push(event); + stream.end(); + } catch (error) { + stream.push({ + type: "error", + reason: "error", + error: { + role: "assistant", + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: "error", + errorMessage: error instanceof Error ? error.message : String(error), + timestamp: Date.now(), + }, + }); + stream.end(); + } + })(); + + return stream; +} + +// ============================================================================= +// Extension Entry Point +// ============================================================================= + +export default function (pi: ExtensionAPI) { + pi.registerProvider("gitlab-duo", { + baseUrl: AI_GATEWAY_URL, + apiKey: "$GITLAB_TOKEN", + api: "gitlab-duo-api", + models: MODELS.map(({ id, name, reasoning, thinkingLevelMap, input, cost, contextWindow, maxTokens }) => ({ + id, + name, + reasoning, + thinkingLevelMap, + input, + cost, + contextWindow, + maxTokens, + })), + oauth: { + name: "GitLab Duo", + login: loginGitLab, + refreshToken: refreshGitLabToken, + getApiKey: (cred) => cred.access, + }, + streamSimple: streamGitLabDuo, + }); +} diff --git a/examples/extensions/custom-provider-gitlab-duo/package.json b/examples/extensions/custom-provider-gitlab-duo/package.json new file mode 100644 index 0000000..8a606dc --- /dev/null +++ b/examples/extensions/custom-provider-gitlab-duo/package.json @@ -0,0 +1,16 @@ +{ + "name": "pi-extension-custom-provider-gitlab-duo", + "private": true, + "version": "0.83.0", + "type": "module", + "scripts": { + "clean": "echo 'nothing to clean'", + "build": "echo 'nothing to build'", + "check": "echo 'nothing to check'" + }, + "pi": { + "extensions": [ + "./index.ts" + ] + } +} diff --git a/examples/extensions/custom-provider-gitlab-duo/test.ts b/examples/extensions/custom-provider-gitlab-duo/test.ts new file mode 100644 index 0000000..79ba3d7 --- /dev/null +++ b/examples/extensions/custom-provider-gitlab-duo/test.ts @@ -0,0 +1,82 @@ +/** + * Test script for GitLab Duo extension + * Run: npx tsx test.ts [model-id] [--thinking] + * + * Examples: + * npx tsx test.ts # Test default (claude-sonnet-4-5-20250929) + * npx tsx test.ts gpt-5-codex # Test GPT-5 Codex + * npx tsx test.ts claude-sonnet-4-5-20250929 --thinking + */ + +import { type Api, type Context, type Model, registerApiProvider, streamSimple } from "@earendil-works/pi-ai/compat"; +import { readFileSync } from "fs"; +import { getAgentDir } from "packages/coding-agent/src/config.js"; +import { join } from "path"; +import { MODELS, streamGitLabDuo } from "./index.ts"; + +const MODEL_MAP = new Map(MODELS.map((m) => [m.id, m])); + +async function main() { + const modelId = process.argv[2] || "claude-sonnet-4-5-20250929"; + const useThinking = process.argv.includes("--thinking"); + + const cfg = MODEL_MAP.get(modelId); + if (!cfg) { + console.error(`Unknown model: ${modelId}`); + console.error("Available:", MODELS.map((m) => m.id).join(", ")); + process.exit(1); + } + + // Read auth + const authPath = join(getAgentDir(), "extensions", "auth.json"); + const authData = JSON.parse(readFileSync(authPath, "utf-8")); + const gitlabCred = authData["gitlab-duo"]; + if (!gitlabCred?.access) { + console.error("No gitlab-duo credentials. Run /login gitlab-duo first."); + process.exit(1); + } + + // Register provider + registerApiProvider({ + api: "gitlab-duo-api" as Api, + stream: streamGitLabDuo, + streamSimple: streamGitLabDuo, + }); + + // Create model + const model: Model = { + id: cfg.id, + name: cfg.name, + api: "gitlab-duo-api" as Api, + provider: "gitlab-duo", + baseUrl: cfg.baseUrl, + reasoning: cfg.reasoning, + input: cfg.input, + cost: cfg.cost, + contextWindow: cfg.contextWindow, + maxTokens: cfg.maxTokens, + }; + + const context: Context = { + messages: [{ role: "user", content: "Say hello in exactly 3 words.", timestamp: Date.now() }], + }; + + console.log(`Model: ${model.id}, Backend: ${cfg.backend}, Thinking: ${useThinking}`); + + const stream = streamSimple(model, context, { + apiKey: gitlabCred.access, + maxTokens: 100, + reasoning: useThinking ? "low" : undefined, + }); + + for await (const event of stream) { + if (event.type === "thinking_start") console.log("[Thinking]"); + else if (event.type === "thinking_delta") process.stdout.write(event.delta); + else if (event.type === "thinking_end") console.log("\n[/Thinking]\n"); + else if (event.type === "text_delta") process.stdout.write(event.delta); + else if (event.type === "error") console.error("\nError:", event.error.errorMessage); + else if (event.type === "done") console.log("\n\nDone!", event.reason, event.message.usage); + } +} + +main().catch(console.error); diff --git a/examples/extensions/dirty-repo-guard.ts b/examples/extensions/dirty-repo-guard.ts new file mode 100644 index 0000000..5357464 --- /dev/null +++ b/examples/extensions/dirty-repo-guard.ts @@ -0,0 +1,56 @@ +/** + * Dirty Repo Guard Extension + * + * Prevents session changes when there are uncommitted git changes. + * Useful to ensure work is committed before switching context. + */ + +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; + +async function checkDirtyRepo( + pi: ExtensionAPI, + ctx: ExtensionContext, + action: string, +): Promise<{ cancel: boolean } | undefined> { + // Check for uncommitted changes + const { stdout, code } = await pi.exec("git", ["status", "--porcelain"]); + + if (code !== 0) { + // Not a git repo, allow the action + return; + } + + const hasChanges = stdout.trim().length > 0; + if (!hasChanges) { + return; + } + + if (!ctx.hasUI) { + // In non-interactive mode, block by default + return { cancel: true }; + } + + // Count changed files + const changedFiles = stdout.trim().split("\n").filter(Boolean).length; + + const choice = await ctx.ui.select(`You have ${changedFiles} uncommitted file(s). ${action} anyway?`, [ + "Yes, proceed anyway", + "No, let me commit first", + ]); + + if (choice !== "Yes, proceed anyway") { + ctx.ui.notify("Commit your changes first", "warning"); + return { cancel: true }; + } +} + +export default function (pi: ExtensionAPI) { + pi.on("session_before_switch", async (event, ctx) => { + const action = event.reason === "new" ? "new session" : "switch session"; + return checkDirtyRepo(pi, ctx, action); + }); + + pi.on("session_before_fork", async (_event, ctx) => { + return checkDirtyRepo(pi, ctx, "fork"); + }); +} diff --git a/examples/extensions/doom-overlay/README.md b/examples/extensions/doom-overlay/README.md new file mode 100644 index 0000000..420bd80 --- /dev/null +++ b/examples/extensions/doom-overlay/README.md @@ -0,0 +1,46 @@ +# DOOM Overlay Demo + +Play DOOM as an overlay in pi. Demonstrates that the overlay system can handle real-time game rendering at 35 FPS. + +## Usage + +```bash +pi --extension ./examples/extensions/doom-overlay +``` + +Then run: +``` +/doom-overlay +``` + +The shareware WAD file (~4MB) is auto-downloaded on first run. + +## Controls + +| Action | Keys | +|--------|------| +| Move | WASD or Arrow Keys | +| Run | Shift + WASD | +| Fire | F or Ctrl | +| Use/Open | Space | +| Weapons | 1-7 | +| Map | Tab | +| Menu | Escape | +| Pause/Quit | Q | + +## How It Works + +DOOM runs as WebAssembly compiled from [doomgeneric](https://github.com/ozkl/doomgeneric). Each frame is rendered using half-block characters (▀) with 24-bit color, where the top pixel is the foreground color and the bottom pixel is the background color. + +The overlay uses: +- `width: "90%"` - 90% of terminal width +- `maxHeight: "80%"` - Maximum 80% of terminal height +- `anchor: "center"` - Centered in terminal + +Height is calculated from width to maintain DOOM's 3.2:1 aspect ratio (accounting for half-block rendering). + +## Credits + +- [id Software](https://github.com/id-Software/DOOM) for the original DOOM +- [doomgeneric](https://github.com/ozkl/doomgeneric) for the portable DOOM implementation +- [pi-doom](https://github.com/badlogic/pi-doom) for the original pi integration diff --git a/examples/extensions/doom-overlay/doom-component.ts b/examples/extensions/doom-overlay/doom-component.ts new file mode 100644 index 0000000..ddc2e98 --- /dev/null +++ b/examples/extensions/doom-overlay/doom-component.ts @@ -0,0 +1,132 @@ +/** + * DOOM Component for overlay mode + * + * Renders DOOM frames using half-block characters (▀) with 24-bit color. + * Height is calculated from width to maintain DOOM's aspect ratio. + */ + +import type { Component } from "@earendil-works/pi-tui"; +import { isKeyRelease, type TUI } from "@earendil-works/pi-tui"; +import type { DoomEngine } from "./doom-engine.ts"; +import { DoomKeys, mapKeyToDoom } from "./doom-keys.ts"; + +function renderHalfBlock( + rgba: Uint8Array, + width: number, + height: number, + targetCols: number, + targetRows: number, +): string[] { + const lines: string[] = []; + const scaleX = width / targetCols; + const scaleY = height / (targetRows * 2); + + for (let row = 0; row < targetRows; row++) { + let line = ""; + const srcY1 = Math.floor(row * 2 * scaleY); + const srcY2 = Math.floor((row * 2 + 1) * scaleY); + + for (let col = 0; col < targetCols; col++) { + const srcX = Math.floor(col * scaleX); + const idx1 = (srcY1 * width + srcX) * 4; + const idx2 = (srcY2 * width + srcX) * 4; + const r1 = rgba[idx1] ?? 0, + g1 = rgba[idx1 + 1] ?? 0, + b1 = rgba[idx1 + 2] ?? 0; + const r2 = rgba[idx2] ?? 0, + g2 = rgba[idx2 + 1] ?? 0, + b2 = rgba[idx2 + 2] ?? 0; + line += `\x1b[38;2;${r1};${g1};${b1}m\x1b[48;2;${r2};${g2};${b2}m▀`; + } + line += "\x1b[0m"; + lines.push(line); + } + return lines; +} + +export class DoomOverlayComponent implements Component { + private engine: DoomEngine; + private tui: TUI; + private interval: ReturnType | null = null; + private onExit: () => void; + + // Opt-in to key release events for smooth movement + wantsKeyRelease = true; + + constructor(tui: TUI, engine: DoomEngine, onExit: () => void, resume = false) { + this.tui = tui; + this.engine = engine; + this.onExit = onExit; + + // Unpause if resuming + if (resume) { + this.engine.pushKey(true, DoomKeys.KEY_PAUSE); + this.engine.pushKey(false, DoomKeys.KEY_PAUSE); + } + + this.startGameLoop(); + } + + private startGameLoop(): void { + this.interval = setInterval(() => { + try { + this.engine.tick(); + this.tui.requestRender(); + } catch { + // WASM error (e.g., exit via DOOM menu) - treat as quit + this.dispose(); + this.onExit(); + } + }, 1000 / 35); + } + + handleInput(data: string): void { + // Q to pause and exit (but not on release) + if (!isKeyRelease(data) && (data === "q" || data === "Q")) { + // Send DOOM's pause key before exiting + this.engine.pushKey(true, DoomKeys.KEY_PAUSE); + this.engine.pushKey(false, DoomKeys.KEY_PAUSE); + this.dispose(); + this.onExit(); + return; + } + + const doomKeys = mapKeyToDoom(data); + if (doomKeys.length === 0) return; + + const released = isKeyRelease(data); + + for (const key of doomKeys) { + this.engine.pushKey(!released, key); + } + } + + render(width: number): string[] { + // DOOM renders at 640x400 (1.6:1 ratio) + // With half-block characters, each terminal row = 2 pixels + // So effective ratio is 640:200 = 3.2:1 (width:height in terminal cells) + // Add 1 row for footer + const ASPECT_RATIO = 3.2; + const MIN_HEIGHT = 10; + const height = Math.max(MIN_HEIGHT, Math.floor(width / ASPECT_RATIO)); + + const rgba = this.engine.getFrameRGBA(); + const lines = renderHalfBlock(rgba, this.engine.width, this.engine.height, width, height); + + // Footer + const footer = " DOOM | Q=Pause | WASD=Move | Shift+WASD=Run | Space=Use | F=Fire | 1-7=Weapons"; + const truncatedFooter = footer.length > width ? footer.slice(0, width) : footer; + lines.push(`\x1b[2m${truncatedFooter}\x1b[0m`); + + return lines; + } + + invalidate(): void {} + + dispose(): void { + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + } +} diff --git a/examples/extensions/doom-overlay/doom-engine.ts b/examples/extensions/doom-overlay/doom-engine.ts new file mode 100644 index 0000000..be14237 --- /dev/null +++ b/examples/extensions/doom-overlay/doom-engine.ts @@ -0,0 +1,173 @@ +/** + * DOOM Engine - WebAssembly wrapper for doomgeneric + */ + +import { existsSync, readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +export interface DoomModule { + _doomgeneric_Create: (argc: number, argv: number) => void; + _doomgeneric_Tick: () => void; + _DG_GetFrameBuffer: () => number; + _DG_GetScreenWidth: () => number; + _DG_GetScreenHeight: () => number; + _DG_PushKeyEvent: (pressed: number, key: number) => void; + _malloc: (size: number) => number; + _free: (ptr: number) => void; + HEAPU8: Uint8Array; + HEAPU32: Uint32Array; + FS_createDataFile: (parent: string, name: string, data: number[], canRead: boolean, canWrite: boolean) => void; + FS_createPath: (parent: string, path: string, canRead: boolean, canWrite: boolean) => string; + setValue: (ptr: number, value: number, type: string) => void; + getValue: (ptr: number, type: string) => number; +} + +export class DoomEngine { + private module: DoomModule | null = null; + private frameBufferPtr: number = 0; + private initialized = false; + private wadPath: string; + private _width = 640; + private _height = 400; + + constructor(wadPath: string) { + this.wadPath = wadPath; + } + + get width(): number { + return this._width; + } + + get height(): number { + return this._height; + } + + async init(): Promise { + // Locate WASM build + const __dirname = dirname(fileURLToPath(import.meta.url)); + const buildDir = join(__dirname, "doom", "build"); + const doomJsPath = join(buildDir, "doom.js"); + + if (!existsSync(doomJsPath)) { + throw new Error(`WASM not found at ${doomJsPath}. Run ./doom/build.sh first`); + } + + // Read WAD file + const wadData = readFileSync(this.wadPath); + const wadArray = Array.from(new Uint8Array(wadData)); + + // Load WASM module - eval to bypass jiti completely + const doomJsCode = readFileSync(doomJsPath, "utf-8"); + const moduleExports: { exports: unknown } = { exports: {} }; + const nativeRequire = createRequire(doomJsPath); + const moduleFunc = new Function("module", "exports", "__dirname", "__filename", "require", doomJsCode); + moduleFunc(moduleExports, moduleExports.exports, buildDir, doomJsPath, nativeRequire); + const createDoomModule = moduleExports.exports as (config: unknown) => Promise; + + const moduleConfig = { + locateFile: (path: string) => { + if (path.endsWith(".wasm")) { + return join(buildDir, path); + } + return path; + }, + print: () => {}, + printErr: () => {}, + preRun: [ + (module: DoomModule) => { + // Create /doom directory and add WAD + module.FS_createPath("/", "doom", true, true); + module.FS_createDataFile("/doom", "doom1.wad", wadArray, true, false); + }, + ], + }; + + this.module = await createDoomModule(moduleConfig); + if (!this.module) { + throw new Error("Failed to initialize DOOM module"); + } + + // Initialize DOOM + this.initDoom(); + + // Get framebuffer info + this.frameBufferPtr = this.module._DG_GetFrameBuffer(); + this._width = this.module._DG_GetScreenWidth(); + this._height = this.module._DG_GetScreenHeight(); + this.initialized = true; + } + + private initDoom(): void { + if (!this.module) return; + + const args = ["doom", "-iwad", "/doom/doom1.wad"]; + const argPtrs: number[] = []; + + for (const arg of args) { + const ptr = this.module._malloc(arg.length + 1); + for (let i = 0; i < arg.length; i++) { + this.module.setValue(ptr + i, arg.charCodeAt(i), "i8"); + } + this.module.setValue(ptr + arg.length, 0, "i8"); + argPtrs.push(ptr); + } + + const argvPtr = this.module._malloc(argPtrs.length * 4); + for (let i = 0; i < argPtrs.length; i++) { + this.module.setValue(argvPtr + i * 4, argPtrs[i]!, "i32"); + } + + this.module._doomgeneric_Create(args.length, argvPtr); + + for (const ptr of argPtrs) { + this.module._free(ptr); + } + this.module._free(argvPtr); + } + + /** + * Run one game tick + */ + tick(): void { + if (!this.module || !this.initialized) return; + this.module._doomgeneric_Tick(); + } + + /** + * Get current frame as RGBA pixel data + * DOOM outputs ARGB, we convert to RGBA + */ + getFrameRGBA(): Uint8Array { + if (!this.module || !this.initialized) { + return new Uint8Array(this._width * this._height * 4); + } + + const pixels = this._width * this._height; + const buffer = new Uint8Array(pixels * 4); + + for (let i = 0; i < pixels; i++) { + const argb = this.module.getValue(this.frameBufferPtr + i * 4, "i32"); + const offset = i * 4; + buffer[offset + 0] = (argb >> 16) & 0xff; // R + buffer[offset + 1] = (argb >> 8) & 0xff; // G + buffer[offset + 2] = argb & 0xff; // B + buffer[offset + 3] = 255; // A + } + + return buffer; + } + + /** + * Push a key event + */ + pushKey(pressed: boolean, key: number): void { + if (!this.module || !this.initialized) return; + this.module._DG_PushKeyEvent(pressed ? 1 : 0, key); + } + + isInitialized(): boolean { + return this.initialized; + } +} diff --git a/examples/extensions/doom-overlay/doom-keys.ts b/examples/extensions/doom-overlay/doom-keys.ts new file mode 100644 index 0000000..cb71a44 --- /dev/null +++ b/examples/extensions/doom-overlay/doom-keys.ts @@ -0,0 +1,104 @@ +/** + * DOOM key codes (from doomkeys.h) + */ +export const DoomKeys = { + KEY_RIGHTARROW: 0xae, + KEY_LEFTARROW: 0xac, + KEY_UPARROW: 0xad, + KEY_DOWNARROW: 0xaf, + KEY_STRAFE_L: 0xa0, + KEY_STRAFE_R: 0xa1, + KEY_USE: 0xa2, + KEY_FIRE: 0xa3, + KEY_ESCAPE: 27, + KEY_ENTER: 13, + KEY_TAB: 9, + KEY_F1: 0x80 + 0x3b, + KEY_F2: 0x80 + 0x3c, + KEY_F3: 0x80 + 0x3d, + KEY_F4: 0x80 + 0x3e, + KEY_F5: 0x80 + 0x3f, + KEY_F6: 0x80 + 0x40, + KEY_F7: 0x80 + 0x41, + KEY_F8: 0x80 + 0x42, + KEY_F9: 0x80 + 0x43, + KEY_F10: 0x80 + 0x44, + KEY_F11: 0x80 + 0x57, + KEY_F12: 0x80 + 0x58, + KEY_BACKSPACE: 127, + KEY_PAUSE: 0xff, + KEY_EQUALS: 0x3d, + KEY_MINUS: 0x2d, + KEY_RSHIFT: 0x80 + 0x36, + KEY_RCTRL: 0x80 + 0x1d, + KEY_RALT: 0x80 + 0x38, +} as const; + +import { Key, matchesKey, parseKey } from "@earendil-works/pi-tui"; + +/** + * Map terminal key input to DOOM key codes + * Supports both raw terminal input and Kitty protocol sequences + */ +export function mapKeyToDoom(data: string): number[] { + // Arrow keys + if (matchesKey(data, Key.up)) return [DoomKeys.KEY_UPARROW]; + if (matchesKey(data, Key.down)) return [DoomKeys.KEY_DOWNARROW]; + if (matchesKey(data, Key.right)) return [DoomKeys.KEY_RIGHTARROW]; + if (matchesKey(data, Key.left)) return [DoomKeys.KEY_LEFTARROW]; + + // WASD - check both raw char and Kitty sequences + if (data === "w" || matchesKey(data, "w")) return [DoomKeys.KEY_UPARROW]; + if (data === "W" || matchesKey(data, Key.shift("w"))) return [DoomKeys.KEY_UPARROW, DoomKeys.KEY_RSHIFT]; + if (data === "s" || matchesKey(data, "s")) return [DoomKeys.KEY_DOWNARROW]; + if (data === "S" || matchesKey(data, Key.shift("s"))) return [DoomKeys.KEY_DOWNARROW, DoomKeys.KEY_RSHIFT]; + if (data === "a" || matchesKey(data, "a")) return [DoomKeys.KEY_STRAFE_L]; + if (data === "A" || matchesKey(data, Key.shift("a"))) return [DoomKeys.KEY_STRAFE_L, DoomKeys.KEY_RSHIFT]; + if (data === "d" || matchesKey(data, "d")) return [DoomKeys.KEY_STRAFE_R]; + if (data === "D" || matchesKey(data, Key.shift("d"))) return [DoomKeys.KEY_STRAFE_R, DoomKeys.KEY_RSHIFT]; + + // Fire - F key + if (data === "f" || data === "F" || matchesKey(data, "f") || matchesKey(data, Key.shift("f"))) { + return [DoomKeys.KEY_FIRE]; + } + + // Use/Open + if (data === " " || matchesKey(data, Key.space)) return [DoomKeys.KEY_USE]; + + // Menu/UI keys + if (matchesKey(data, Key.enter)) return [DoomKeys.KEY_ENTER]; + if (matchesKey(data, Key.escape)) return [DoomKeys.KEY_ESCAPE]; + if (matchesKey(data, Key.tab)) return [DoomKeys.KEY_TAB]; + if (matchesKey(data, Key.backspace)) return [DoomKeys.KEY_BACKSPACE]; + + // Ctrl keys (except Ctrl+C) = fire (legacy support) + const parsed = parseKey(data); + if (parsed?.startsWith("ctrl+") && parsed !== "ctrl+c") { + return [DoomKeys.KEY_FIRE]; + } + if (data.length === 1 && data.charCodeAt(0) < 32 && data !== "\x03") { + return [DoomKeys.KEY_FIRE]; + } + + // Weapon selection (0-9) + if (data >= "0" && data <= "9") return [data.charCodeAt(0)]; + + // Plus/minus for screen size + if (data === "+" || data === "=") return [DoomKeys.KEY_EQUALS]; + if (data === "-") return [DoomKeys.KEY_MINUS]; + + // Y/N for prompts + if (data === "y" || data === "Y" || matchesKey(data, "y") || matchesKey(data, Key.shift("y"))) { + return ["y".charCodeAt(0)]; + } + if (data === "n" || data === "N" || matchesKey(data, "n") || matchesKey(data, Key.shift("n"))) { + return ["n".charCodeAt(0)]; + } + + // Other printable characters (for cheats) + if (data.length === 1 && data.charCodeAt(0) >= 32) { + return [data.toLowerCase().charCodeAt(0)]; + } + + return []; +} diff --git a/examples/extensions/doom-overlay/doom/build.sh b/examples/extensions/doom-overlay/doom/build.sh new file mode 100755 index 0000000..90e36c4 --- /dev/null +++ b/examples/extensions/doom-overlay/doom/build.sh @@ -0,0 +1,152 @@ +#!/usr/bin/env bash +# Build DOOM for pi-doom using doomgeneric and Emscripten + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" +DOOM_DIR="$PROJECT_ROOT/doom" +BUILD_DIR="$PROJECT_ROOT/doom/build" + +echo "=== pi-doom Build Script ===" + +# Check for emcc +if ! command -v emcc &> /dev/null; then + echo "Error: Emscripten (emcc) not found!" + echo "" + echo "Install via Homebrew:" + echo " brew install emscripten" + echo "" + echo "Or manually:" + echo " git clone https://github.com/emscripten-core/emsdk.git ~/emsdk" + echo " cd ~/emsdk && ./emsdk install latest && ./emsdk activate latest" + echo " source ~/emsdk/emsdk_env.sh" + exit 1 +fi + +# Clone doomgeneric if not present +if [ ! -d "$DOOM_DIR/doomgeneric" ]; then + echo "Cloning doomgeneric..." + cd "$DOOM_DIR" + git clone https://github.com/ozkl/doomgeneric.git +fi + +# Create build directory +mkdir -p "$BUILD_DIR" + +# Copy our platform file +cp "$DOOM_DIR/doomgeneric_pi.c" "$DOOM_DIR/doomgeneric/doomgeneric/" + +echo "Compiling DOOM to WebAssembly..." +cd "$DOOM_DIR/doomgeneric/doomgeneric" + +# Resolution - 640x400 is doomgeneric default, good balance of speed/quality +RESX=${DOOM_RESX:-640} +RESY=${DOOM_RESY:-400} + +echo "Resolution: ${RESX}x${RESY}" + +# Compile with Emscripten (no sound) +emcc -O2 \ + -s WASM=1 \ + -s EXPORTED_FUNCTIONS="['_doomgeneric_Create','_doomgeneric_Tick','_DG_GetFrameBuffer','_DG_GetScreenWidth','_DG_GetScreenHeight','_DG_PushKeyEvent','_malloc','_free']" \ + -s EXPORTED_RUNTIME_METHODS="['ccall','cwrap','getValue','setValue','FS']" \ + -s ALLOW_MEMORY_GROWTH=1 \ + -s INITIAL_MEMORY=33554432 \ + -s MODULARIZE=1 \ + -s EXPORT_NAME="createDoomModule" \ + -s ENVIRONMENT='node' \ + -s FILESYSTEM=1 \ + -s FORCE_FILESYSTEM=1 \ + -s EXIT_RUNTIME=0 \ + -s NO_EXIT_RUNTIME=1 \ + -DDOOMGENERIC_RESX="$RESX" \ + -DDOOMGENERIC_RESY="$RESY" \ + -I. \ + am_map.c \ + d_event.c \ + d_items.c \ + d_iwad.c \ + d_loop.c \ + d_main.c \ + d_mode.c \ + d_net.c \ + doomdef.c \ + doomgeneric.c \ + doomgeneric_pi.c \ + doomstat.c \ + dstrings.c \ + f_finale.c \ + f_wipe.c \ + g_game.c \ + hu_lib.c \ + hu_stuff.c \ + i_cdmus.c \ + i_input.c \ + i_endoom.c \ + i_joystick.c \ + i_scale.c \ + i_sound.c \ + i_system.c \ + i_timer.c \ + i_video.c \ + icon.c \ + info.c \ + m_argv.c \ + m_bbox.c \ + m_cheat.c \ + m_config.c \ + m_controls.c \ + m_fixed.c \ + m_menu.c \ + m_misc.c \ + m_random.c \ + memio.c \ + p_ceilng.c \ + p_doors.c \ + p_enemy.c \ + p_floor.c \ + p_inter.c \ + p_lights.c \ + p_map.c \ + p_maputl.c \ + p_mobj.c \ + p_plats.c \ + p_pspr.c \ + p_saveg.c \ + p_setup.c \ + p_sight.c \ + p_spec.c \ + p_switch.c \ + p_telept.c \ + p_tick.c \ + p_user.c \ + r_bsp.c \ + r_data.c \ + r_draw.c \ + r_main.c \ + r_plane.c \ + r_segs.c \ + r_sky.c \ + r_things.c \ + s_sound.c \ + sha1.c \ + sounds.c \ + st_lib.c \ + st_stuff.c \ + statdump.c \ + tables.c \ + v_video.c \ + w_checksum.c \ + w_file.c \ + w_file_stdc.c \ + w_main.c \ + w_wad.c \ + wi_stuff.c \ + z_zone.c \ + dummy.c \ + -o "$BUILD_DIR/doom.js" + +echo "" +echo "Build complete!" +echo "Output: $BUILD_DIR/doom.js and $BUILD_DIR/doom.wasm" diff --git a/examples/extensions/doom-overlay/doom/build/doom.js b/examples/extensions/doom-overlay/doom/build/doom.js new file mode 100644 index 0000000..e2221dc --- /dev/null +++ b/examples/extensions/doom-overlay/doom/build/doom.js @@ -0,0 +1,21 @@ +var createDoomModule = (() => { + var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined; + if (typeof __filename != 'undefined') _scriptName = _scriptName || __filename; + return ( +async function(moduleArg = {}) { + var moduleRtn; + +var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=true;if(ENVIRONMENT_IS_NODE){}var moduleOverrides={...Module};var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(!Module["thisProgram"]&&process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var wasmBinary=Module["wasmBinary"];var wasmMemory;var ABORT=false;var EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPU64,HEAPF64;var runtimeInitialized=false;var isFileURI=filename=>filename.startsWith("file://");function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b);Module["HEAP64"]=HEAP64=new BigInt64Array(b);Module["HEAPU64"]=HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["__wasm_call_ctors"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}var runDependencies=0;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("doom.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["memory"];updateMemoryViews();removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(mod,inst)=>{receiveInstance(mod,inst);resolve(mod.exports)})})}wasmBinaryFile??=findWasmBinary();try{var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}catch(e){readyPromiseReject(e);return Promise.reject(e)}}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.unshift(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.unshift(cb);function getValue(ptr,type="i8"){if(type.endsWith("*"))type="*";switch(type){case"i1":return HEAP8[ptr];case"i8":return HEAP8[ptr];case"i16":return HEAP16[ptr>>1];case"i32":return HEAP32[ptr>>2];case"i64":return HEAP64[ptr>>3];case"float":return HEAPF32[ptr>>2];case"double":return HEAPF64[ptr>>3];case"*":return HEAPU32[ptr>>2];default:abort(`invalid type for getValue: ${type}`)}}var noExitRuntime=Module["noExitRuntime"]||true;function setValue(ptr,value,type="i8"){if(type.endsWith("*"))type="*";switch(type){case"i1":HEAP8[ptr]=value;break;case"i8":HEAP8[ptr]=value;break;case"i16":HEAP16[ptr>>1]=value;break;case"i32":HEAP32[ptr>>2]=value;break;case"i64":HEAP64[ptr>>3]=BigInt(value);break;case"float":HEAPF32[ptr>>2]=value;break;case"double":HEAPF64[ptr>>3]=value;break;case"*":HEAPU32[ptr>>2]=value;break;default:abort(`invalid type for setValue: ${type}`)}}var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("crypto");return view=>nodeCrypto.randomFillSync(view)}return view=>crypto.getRandomValues(view)};var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i{var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i0||position+length{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(parent,name,fileData,canRead,canWrite,canOwn)=>{FS.createDataFile(parent,name,fileData,canRead,canWrite,canOwn)};var preloadPlugins=Module["preloadPlugins"]||[];var FS_handledByPreloadPlugin=(byteArray,fullname,finish,onerror)=>{if(typeof Browser!="undefined")Browser.init();var handled=false;preloadPlugins.forEach(plugin=>{if(handled)return;if(plugin["canHandle"](fullname)){plugin["handle"](byteArray,fullname,finish,onerror);handled=true}});return handled};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);function processData(byteArray){function finish(byteArray){preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}onload?.();removeRunDependency(dep)}if(FS_handledByPreloadPlugin(byteArray,fullname,finish,()=>{onerror?.();removeRunDependency(dep)})){return}finish(byteArray)}addRunDependency(dep);if(typeof url=="string"){asyncLoad(url).then(processData,onerror)}else{processData(url)}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}mounts.forEach(mount=>{if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);Object.keys(FS.nameTable).forEach(hash=>{var current=FS.nameTable[hash];while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}});node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}if(Module["logReadFiles"]&&!(flags&1)){if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){throw new Error(`Invalid encoding type "${opts.encoding}"`)}var ret;var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){ret=UTF8ArrayToString(buf)}else if(opts.encoding==="binary"){ret=buf}FS.close(stream);return ret},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){var buf=new Uint8Array(lengthBytesUTF8(data)+1);var actualNumBytes=stringToUTF8Array(data,buf,0,buf.length);FS.write(stream,buf,0,actualNumBytes,undefined,opts.canOwn)}else if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{throw new Error("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;ithis.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")throw new Error("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(typeof XMLHttpRequest!="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};var keys=Object.keys(node.stream_ops);keys.forEach(key=>{var fn=node.stream_ops[key];stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}});function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAP32[buf>>2]=stat.dev;HEAP32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAP32[buf+12>>2]=stat.uid;HEAP32[buf+16>>2]=stat.gid;HEAP32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAP32[buf+4>>2]=stats.bsize;HEAP32[buf+40>>2]=stats.bsize;HEAP32[buf+8>>2]=stats.blocks;HEAP32[buf+12>>2]=stats.bfree;HEAP32[buf+16>>2]=stats.bavail;HEAP32[buf+20>>2]=stats.files;HEAP32[buf+24>>2]=stats.ffree;HEAP32[buf+28>>2]=stats.fsid;HEAP32[buf+44>>2]=stats.flags;HEAP32[buf+36>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_mkdirat(dirfd,path,mode){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);FS.mkdir(path,mode,0);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_renameat(olddirfd,oldpath,newdirfd,newpath){try{oldpath=SYSCALLS.getStr(oldpath);newpath=SYSCALLS.getStr(newpath);oldpath=SYSCALLS.calculateAt(olddirfd,oldpath);newpath=SYSCALLS.calculateAt(newdirfd,newpath);FS.rename(oldpath,newpath);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_rmdir(path){try{path=SYSCALLS.getStr(path);FS.rmdir(path);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_unlinkat(dirfd,path,flags){try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(flags===0){FS.unlink(path)}else if(flags===512){FS.rmdir(path)}else{abort("Invalid flags passed to unlinkat")}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __emscripten_system=command=>{if(ENVIRONMENT_IS_NODE){if(!command)return 1;var cmdstr=UTF8ToString(command);if(!cmdstr.length)return 0;var cp=require("child_process");var ret=cp.spawnSync(cmdstr,[],{shell:true,stdio:"inherit"});var _W_EXITCODE=(ret,sig)=>ret<<8|sig;if(ret.status===null){var signalToNumber=sig=>{switch(sig){case"SIGHUP":return 1;case"SIGQUIT":return 3;case"SIGFPE":return 8;case"SIGKILL":return 9;case"SIGALRM":return 14;case"SIGTERM":return 15;default:return 2}};return _W_EXITCODE(0,signalToNumber(ret.signal))}return _W_EXITCODE(ret.status,0)}if(!command)return 0;return-52};var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var runtimeKeepaliveCounter=0;var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>numINT53_MAX?NaN:Number(num);function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var FS_createPath=FS.createPath;var FS_unlink=path=>FS.unlink(path);var FS_createLazyFile=FS.createLazyFile;var FS_createDevice=FS.createDevice;FS.createPreloadedFile=FS_createPreloadedFile;FS.staticInit();Module["FS_createPath"]=FS.createPath;Module["FS_createDataFile"]=FS.createDataFile;Module["FS_createPreloadedFile"]=FS.createPreloadedFile;Module["FS_unlink"]=FS.unlink;Module["FS_createLazyFile"]=FS.createLazyFile;Module["FS_createDevice"]=FS.createDevice;MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="";var wasmImports={__syscall_fcntl64:___syscall_fcntl64,__syscall_ioctl:___syscall_ioctl,__syscall_mkdirat:___syscall_mkdirat,__syscall_openat:___syscall_openat,__syscall_renameat:___syscall_renameat,__syscall_rmdir:___syscall_rmdir,__syscall_unlinkat:___syscall_unlinkat,_emscripten_system:__emscripten_system,emscripten_get_now:_emscripten_get_now,emscripten_resize_heap:_emscripten_resize_heap,exit:_exit,fd_close:_fd_close,fd_read:_fd_read,fd_seek:_fd_seek,fd_write:_fd_write};var wasmExports=await createWasm();var ___wasm_call_ctors=wasmExports["__wasm_call_ctors"];var _free=Module["_free"]=wasmExports["free"];var _malloc=Module["_malloc"]=wasmExports["malloc"];var _doomgeneric_Tick=Module["_doomgeneric_Tick"]=wasmExports["doomgeneric_Tick"];var _doomgeneric_Create=Module["_doomgeneric_Create"]=wasmExports["doomgeneric_Create"];var _DG_GetFrameBuffer=Module["_DG_GetFrameBuffer"]=wasmExports["DG_GetFrameBuffer"];var _DG_GetScreenWidth=Module["_DG_GetScreenWidth"]=wasmExports["DG_GetScreenWidth"];var _DG_GetScreenHeight=Module["_DG_GetScreenHeight"]=wasmExports["DG_GetScreenHeight"];var _DG_PushKeyEvent=Module["_DG_PushKeyEvent"]=wasmExports["DG_PushKeyEvent"];var __emscripten_stack_restore=wasmExports["_emscripten_stack_restore"];var __emscripten_stack_alloc=wasmExports["_emscripten_stack_alloc"];var _emscripten_stack_get_current=wasmExports["emscripten_stack_get_current"];Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["setValue"]=setValue;Module["getValue"]=getValue;Module["FS_createPreloadedFile"]=FS_createPreloadedFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS"]=FS;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();moduleRtn=readyPromise; + + + return moduleRtn; +} +); +})(); +if (typeof exports === 'object' && typeof module === 'object') { + module.exports = createDoomModule; + // This default export looks redundant, but it allows TS to import this + // commonjs style module. + module.exports.default = createDoomModule; +} else if (typeof define === 'function' && define['amd']) + define([], () => createDoomModule); diff --git a/examples/extensions/doom-overlay/doom/build/doom.wasm b/examples/extensions/doom-overlay/doom/build/doom.wasm new file mode 100755 index 0000000..fb99ae7 Binary files /dev/null and b/examples/extensions/doom-overlay/doom/build/doom.wasm differ diff --git a/examples/extensions/doom-overlay/doom/doomgeneric_pi.c b/examples/extensions/doom-overlay/doom/doomgeneric_pi.c new file mode 100644 index 0000000..bb442f4 --- /dev/null +++ b/examples/extensions/doom-overlay/doom/doomgeneric_pi.c @@ -0,0 +1,72 @@ +/** + * pi-doom platform implementation for doomgeneric + * + * Minimal implementation - no sound, just framebuffer and input. + */ + +#include "doomgeneric.h" +#include "doomkeys.h" +#include +#include + +// Key event queue +#define KEY_QUEUE_SIZE 256 +static struct { + int pressed; + unsigned char key; +} key_queue[KEY_QUEUE_SIZE]; +static int key_queue_read = 0; +static int key_queue_write = 0; + +// Get the framebuffer pointer for JS to read +EMSCRIPTEN_KEEPALIVE +uint32_t *DG_GetFrameBuffer(void) { return DG_ScreenBuffer; } + +// Get framebuffer dimensions +EMSCRIPTEN_KEEPALIVE +int DG_GetScreenWidth(void) { return DOOMGENERIC_RESX; } + +EMSCRIPTEN_KEEPALIVE +int DG_GetScreenHeight(void) { return DOOMGENERIC_RESY; } + +// Push a key event from JavaScript +EMSCRIPTEN_KEEPALIVE +void DG_PushKeyEvent(int pressed, unsigned char key) { + int next_write = (key_queue_write + 1) % KEY_QUEUE_SIZE; + if (next_write != key_queue_read) { + key_queue[key_queue_write].pressed = pressed; + key_queue[key_queue_write].key = key; + key_queue_write = next_write; + } +} + +void DG_Init(void) { + // Nothing to initialize +} + +void DG_DrawFrame(void) { + // Frame is in DG_ScreenBuffer, JS reads via DG_GetFrameBuffer +} + +void DG_SleepMs(uint32_t ms) { + // No-op - JS handles timing + (void)ms; +} + +uint32_t DG_GetTicksMs(void) { + return (uint32_t)emscripten_get_now(); +} + +int DG_GetKey(int *pressed, unsigned char *key) { + if (key_queue_read != key_queue_write) { + *pressed = key_queue[key_queue_read].pressed; + *key = key_queue[key_queue_read].key; + key_queue_read = (key_queue_read + 1) % KEY_QUEUE_SIZE; + return 1; + } + return 0; +} + +void DG_SetWindowTitle(const char *title) { + (void)title; +} diff --git a/examples/extensions/doom-overlay/index.ts b/examples/extensions/doom-overlay/index.ts new file mode 100644 index 0000000..843d52d --- /dev/null +++ b/examples/extensions/doom-overlay/index.ts @@ -0,0 +1,74 @@ +/** + * DOOM Overlay Demo - Play DOOM as an overlay + * + * Usage: pi --extension ./examples/extensions/doom-overlay + * + * Commands: + * /doom-overlay - Play DOOM in an overlay (Q to pause/exit) + * + * This demonstrates that overlays can handle real-time game rendering at 35 FPS. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { DoomOverlayComponent } from "./doom-component.ts"; +import { DoomEngine } from "./doom-engine.ts"; +import { ensureWadFile } from "./wad-finder.ts"; + +// Persistent engine instance - survives between invocations +let activeEngine: DoomEngine | null = null; +let activeWadPath: string | null = null; + +export default function (pi: ExtensionAPI) { + pi.registerCommand("doom-overlay", { + description: "Play DOOM as an overlay. Q to pause and exit.", + + handler: async (args, ctx) => { + if (ctx.mode !== "tui") { + ctx.ui.notify("DOOM requires interactive mode", "error"); + return; + } + + // Auto-download WAD if not present + ctx.ui.notify("Loading DOOM...", "info"); + const wad = args?.trim() ? args.trim() : await ensureWadFile(); + + if (!wad) { + ctx.ui.notify("Failed to download DOOM WAD file. Check your internet connection.", "error"); + return; + } + + try { + // Reuse existing engine if same WAD, otherwise create new + let isResume = false; + if (activeEngine && activeWadPath === wad) { + ctx.ui.notify("Resuming DOOM...", "info"); + isResume = true; + } else { + ctx.ui.notify(`Loading DOOM from ${wad}...`, "info"); + activeEngine = new DoomEngine(wad); + await activeEngine.init(); + activeWadPath = wad; + } + + await ctx.ui.custom( + (tui, _theme, _keybindings, done) => { + return new DoomOverlayComponent(tui, activeEngine!, () => done(undefined), isResume); + }, + { + overlay: true, + overlayOptions: { + width: "75%", + maxHeight: "95%", + anchor: "center", + margin: { top: 1 }, + }, + }, + ); + } catch (error) { + ctx.ui.notify(`Failed to load DOOM: ${error}`, "error"); + activeEngine = null; + activeWadPath = null; + } + }, + }); +} diff --git a/examples/extensions/doom-overlay/wad-finder.ts b/examples/extensions/doom-overlay/wad-finder.ts new file mode 100644 index 0000000..002758d --- /dev/null +++ b/examples/extensions/doom-overlay/wad-finder.ts @@ -0,0 +1,51 @@ +import { existsSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +// Get the bundled WAD path (relative to this module) +const __dirname = dirname(fileURLToPath(import.meta.url)); +const BUNDLED_WAD = join(__dirname, "doom1.wad"); +const WAD_URL = "https://distro.ibiblio.org/slitaz/sources/packages/d/doom1.wad"; + +const DEFAULT_WAD_PATHS = ["./doom1.wad", "./DOOM1.WAD", "~/doom1.wad", "~/.doom/doom1.wad"]; + +export function findWadFile(customPath?: string): string | null { + if (customPath) { + const resolved = resolve(customPath.replace(/^~/, process.env.HOME || "")); + if (existsSync(resolved)) return resolved; + return null; + } + + // Check bundled WAD first + if (existsSync(BUNDLED_WAD)) { + return BUNDLED_WAD; + } + + // Fall back to default paths + for (const p of DEFAULT_WAD_PATHS) { + const resolved = resolve(p.replace(/^~/, process.env.HOME || "")); + if (existsSync(resolved)) return resolved; + } + + return null; +} + +/** Download the shareware WAD if not present. Returns path or null on failure. */ +export async function ensureWadFile(): Promise { + // Check if already exists + const existing = findWadFile(); + if (existing) return existing; + + // Download to bundled location + try { + const response = await fetch(WAD_URL); + if (!response.ok) { + throw new Error(`HTTP ${response.status}`); + } + const buffer = await response.arrayBuffer(); + writeFileSync(BUNDLED_WAD, Buffer.from(buffer)); + return BUNDLED_WAD; + } catch { + return null; + } +} diff --git a/examples/extensions/dynamic-resources/SKILL.md b/examples/extensions/dynamic-resources/SKILL.md new file mode 100644 index 0000000..66162e1 --- /dev/null +++ b/examples/extensions/dynamic-resources/SKILL.md @@ -0,0 +1,8 @@ +--- +name: dynamic-resources +description: Example skill loaded from resources_discover +--- + +# Dynamic Resources Skill + +This skill is provided by the dynamic-resources extension. diff --git a/examples/extensions/dynamic-resources/dynamic.json b/examples/extensions/dynamic-resources/dynamic.json new file mode 100644 index 0000000..e7b01a8 --- /dev/null +++ b/examples/extensions/dynamic-resources/dynamic.json @@ -0,0 +1,79 @@ +{ + "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json", + "name": "dynamic-resources", + "vars": { + "cyan": "#00d7ff", + "blue": "#5f87ff", + "green": "#b5bd68", + "red": "#cc6666", + "yellow": "#ffff00", + "gray": "#808080", + "dimGray": "#666666", + "darkGray": "#505050", + "accent": "#8abeb7", + "selectedBg": "#3a3a4a", + "userMsgBg": "#343541", + "toolPendingBg": "#282832", + "toolSuccessBg": "#283228", + "toolErrorBg": "#3c2828", + "customMsgBg": "#2d2838" + }, + "colors": { + "accent": "accent", + "border": "blue", + "borderAccent": "cyan", + "borderMuted": "darkGray", + "success": "green", + "error": "red", + "warning": "yellow", + "muted": "gray", + "dim": "dimGray", + "text": "", + "thinkingText": "gray", + "selectedBg": "selectedBg", + "userMessageBg": "userMsgBg", + "userMessageText": "", + "customMessageBg": "customMsgBg", + "customMessageText": "", + "customMessageLabel": "#9575cd", + "toolPendingBg": "toolPendingBg", + "toolSuccessBg": "toolSuccessBg", + "toolErrorBg": "toolErrorBg", + "toolTitle": "", + "toolOutput": "gray", + "mdHeading": "#f0c674", + "mdLink": "#81a2be", + "mdLinkUrl": "dimGray", + "mdCode": "accent", + "mdCodeBlock": "green", + "mdCodeBlockBorder": "gray", + "mdQuote": "gray", + "mdQuoteBorder": "gray", + "mdHr": "gray", + "mdListBullet": "accent", + "toolDiffAdded": "green", + "toolDiffRemoved": "red", + "toolDiffContext": "gray", + "syntaxComment": "#6A9955", + "syntaxKeyword": "#569CD6", + "syntaxFunction": "#DCDCAA", + "syntaxVariable": "#9CDCFE", + "syntaxString": "#CE9178", + "syntaxNumber": "#B5CEA8", + "syntaxType": "#4EC9B0", + "syntaxOperator": "#D4D4D4", + "syntaxPunctuation": "#D4D4D4", + "thinkingOff": "darkGray", + "thinkingMinimal": "#6e6e6e", + "thinkingLow": "#5f87af", + "thinkingMedium": "#81a2be", + "thinkingHigh": "#b294bb", + "thinkingXhigh": "#d183e8", + "bashMode": "green" + }, + "export": { + "pageBg": "#18181e", + "cardBg": "#1e1e24", + "infoBg": "#3c3728" + } +} diff --git a/examples/extensions/dynamic-resources/dynamic.md b/examples/extensions/dynamic-resources/dynamic.md new file mode 100644 index 0000000..da85f71 --- /dev/null +++ b/examples/extensions/dynamic-resources/dynamic.md @@ -0,0 +1,5 @@ +--- +description: Example prompt template loaded from resources_discover +--- + +Summarize the current repository structure and mention any build or test commands. diff --git a/examples/extensions/dynamic-resources/index.ts b/examples/extensions/dynamic-resources/index.ts new file mode 100644 index 0000000..2f89f93 --- /dev/null +++ b/examples/extensions/dynamic-resources/index.ts @@ -0,0 +1,15 @@ +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +const baseDir = dirname(fileURLToPath(import.meta.url)); + +export default function (pi: ExtensionAPI) { + pi.on("resources_discover", () => { + return { + skillPaths: [join(baseDir, "SKILL.md")], + promptPaths: [join(baseDir, "dynamic.md")], + themePaths: [join(baseDir, "dynamic.json")], + }; + }); +} diff --git a/examples/extensions/dynamic-tools.ts b/examples/extensions/dynamic-tools.ts new file mode 100644 index 0000000..54ad13b --- /dev/null +++ b/examples/extensions/dynamic-tools.ts @@ -0,0 +1,74 @@ +/** + * Dynamic Tools Extension + * + * Demonstrates registering tools after session initialization. + * + * - Registers one tool during session_start + * - Registers additional tools at runtime via /add-echo-tool + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { Type } from "typebox"; + +const ECHO_PARAMS = Type.Object({ + message: Type.String({ description: "Message to echo" }), +}); + +function normalizeToolName(input: string): string | undefined { + const trimmed = input.trim().toLowerCase(); + if (!trimmed) return undefined; + if (!/^[a-z0-9_]+$/.test(trimmed)) return undefined; + return trimmed; +} + +export default function dynamicToolsExtension(pi: ExtensionAPI) { + const registeredToolNames = new Set(); + + const registerEchoTool = (name: string, label: string, prefix: string): boolean => { + if (registeredToolNames.has(name)) { + return false; + } + + registeredToolNames.add(name); + pi.registerTool({ + name, + label, + description: `Echo a message with prefix: ${prefix}`, + promptSnippet: `Echo back user-provided text with ${prefix.trim()} prefix`, + promptGuidelines: ["Use echo_session when the user asks for exact echo output."], + parameters: ECHO_PARAMS, + async execute(_toolCallId, params) { + return { + content: [{ type: "text", text: `${prefix}${params.message}` }], + details: { tool: name, prefix }, + }; + }, + }); + + return true; + }; + + pi.on("session_start", (_event, ctx) => { + registerEchoTool("echo_session", "Echo Session", "[session] "); + ctx.ui.notify("Registered dynamic tool: echo_session", "info"); + }); + + pi.registerCommand("add-echo-tool", { + description: "Register a new echo tool dynamically: /add-echo-tool ", + handler: async (args, ctx) => { + const toolName = normalizeToolName(args); + if (!toolName) { + ctx.ui.notify("Usage: /add-echo-tool (lowercase, numbers, underscores)", "warning"); + return; + } + + const created = registerEchoTool(toolName, `Echo ${toolName}`, `[${toolName}] `); + if (!created) { + ctx.ui.notify(`Tool already registered: ${toolName}`, "warning"); + return; + } + + ctx.ui.notify(`Registered dynamic tool: ${toolName}`, "info"); + }, + }); +} diff --git a/examples/extensions/entry-renderer.ts b/examples/extensions/entry-renderer.ts new file mode 100644 index 0000000..27c2ced --- /dev/null +++ b/examples/extensions/entry-renderer.ts @@ -0,0 +1,41 @@ +/** + * Custom entry rendering example. + * + * Shows how to render durable extension data inside the chat without sending it + * to the LLM. Custom entries are stored in the session via pi.appendEntry() and + * rendered in interactive mode via pi.registerEntryRenderer(). + * + * Usage: /status-card [message] + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { Box, Text } from "@earendil-works/pi-tui"; + +interface StatusCardData { + message: string; + timestamp: number; +} + +export default function (pi: ExtensionAPI) { + pi.registerEntryRenderer("status-card", (entry, { expanded }, theme) => { + const data = entry.data ?? { message: "No data", timestamp: Date.now() }; + const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text)); + box.addChild(new Text(`${theme.fg("accent", "[status]")} ${data.message}`, 0, 0)); + + if (expanded) { + box.addChild(new Text(theme.fg("dim", new Date(data.timestamp).toLocaleString()), 0, 0)); + } + + return box; + }); + + pi.registerCommand("status-card", { + description: "Render a durable status card that is not sent to the LLM", + handler: async (args) => { + pi.appendEntry("status-card", { + message: args.trim() || "Status card", + timestamp: Date.now(), + }); + }, + }); +} diff --git a/examples/extensions/event-bus.ts b/examples/extensions/event-bus.ts new file mode 100644 index 0000000..e63caa5 --- /dev/null +++ b/examples/extensions/event-bus.ts @@ -0,0 +1,43 @@ +/** + * Inter-extension event bus example. + * + * Shows pi.events for communication between extensions. One extension + * can emit events that other extensions listen to. + * + * Usage: /emit [event-name] [data] - emit an event on the bus + */ + +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + // Store ctx for use in event handler + let currentCtx: ExtensionContext | undefined; + + pi.on("session_start", async (_event, ctx) => { + currentCtx = ctx; + }); + + // Listen for events from other extensions + pi.events.on("my:notification", (data) => { + const { message, from } = data as { message: string; from: string }; + currentCtx?.ui.notify(`Event from ${from}: ${message}`, "info"); + }); + + // Command to emit events (emits "my:notification" which the listener above receives) + pi.registerCommand("emit", { + description: "Emit my:notification event (usage: /emit message)", + handler: async (args, _ctx) => { + const message = args.trim() || "hello"; + pi.events.emit("my:notification", { message, from: "/emit command" }); + // Listener above will show the notification + }, + }); + + // Example: emit on session start + pi.on("session_start", async () => { + pi.events.emit("my:notification", { + message: "Session started", + from: "event-bus-example", + }); + }); +} diff --git a/examples/extensions/file-trigger.ts b/examples/extensions/file-trigger.ts new file mode 100644 index 0000000..8b9894c --- /dev/null +++ b/examples/extensions/file-trigger.ts @@ -0,0 +1,41 @@ +/** + * File Trigger Extension + * + * Watches a trigger file and injects its contents into the conversation. + * Useful for external systems to send messages to the agent. + * + * Usage: + * echo "Run the tests" > /tmp/agent-trigger.txt + */ + +import * as fs from "node:fs"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.on("session_start", async (_event, ctx) => { + const triggerFile = "/tmp/agent-trigger.txt"; + + fs.watch(triggerFile, () => { + try { + const content = fs.readFileSync(triggerFile, "utf-8").trim(); + if (content) { + pi.sendMessage( + { + customType: "file-trigger", + content: `External trigger: ${content}`, + display: true, + }, + { triggerTurn: true }, // triggerTurn - get LLM to respond + ); + fs.writeFileSync(triggerFile, ""); // Clear after reading + } + } catch { + // File might not exist yet + } + }); + + if (ctx.hasUI) { + ctx.ui.notify(`Watching ${triggerFile}`, "info"); + } + }); +} diff --git a/examples/extensions/git-checkpoint.ts b/examples/extensions/git-checkpoint.ts new file mode 100644 index 0000000..7ee5e6a --- /dev/null +++ b/examples/extensions/git-checkpoint.ts @@ -0,0 +1,53 @@ +/** + * Git Checkpoint Extension + * + * Creates git stash checkpoints at each turn so /fork can restore code state. + * When forking, offers to restore code to that point in history. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + const checkpoints = new Map(); + let currentEntryId: string | undefined; + + // Track the current entry ID when user messages are saved + pi.on("tool_result", async (_event, ctx) => { + const leaf = ctx.sessionManager.getLeafEntry(); + if (leaf) currentEntryId = leaf.id; + }); + + pi.on("turn_start", async () => { + // Create a git stash entry before LLM makes changes + const { stdout } = await pi.exec("git", ["stash", "create"]); + const ref = stdout.trim(); + if (ref && currentEntryId) { + checkpoints.set(currentEntryId, ref); + } + }); + + pi.on("session_before_fork", async (event, ctx) => { + const ref = checkpoints.get(event.entryId); + if (!ref) return; + + if (!ctx.hasUI) { + // In non-interactive mode, don't restore automatically + return; + } + + const choice = await ctx.ui.select("Restore code state?", [ + "Yes, restore code to that point", + "No, keep current code", + ]); + + if (choice?.startsWith("Yes")) { + await pi.exec("git", ["stash", "apply", ref]); + ctx.ui.notify("Code restored to checkpoint", "info"); + } + }); + + pi.on("agent_end", async () => { + // Clear checkpoints after agent completes + checkpoints.clear(); + }); +} diff --git a/examples/extensions/git-merge-and-resolve.ts b/examples/extensions/git-merge-and-resolve.ts new file mode 100644 index 0000000..61ad132 --- /dev/null +++ b/examples/extensions/git-merge-and-resolve.ts @@ -0,0 +1,115 @@ +/** + * Merge and Resolve + * + * Keeps the working branch up to date with its upstream tracking ref. + * After each agent turn, fetches and merges. Clean merges complete + * silently. When conflicts arise, the working tree is left dirty and + * the agent receives a follow-up message listing each conflict block + * with file, line range, and ours/theirs sections so it can resolve them. + * Also re-sends unresolved conflicts from a previous incomplete merge. + * + * Start pi with this extension: + * pi -e ./examples/extensions/git-merge-and-resolve.ts + */ +import { createReadStream } from "node:fs"; +import { join } from "node:path"; +import { createInterface } from "node:readline"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +interface ConflictBlock { + file: string; + startLine: number; + separatorLine: number; + endLine: number; +} + +/** Parse conflict markers from working tree files with unmerged paths. */ +async function findConflicts(pi: ExtensionAPI, cwd: string): Promise { + const { stdout, code } = await pi.exec("git", ["diff", "--name-only", "--diff-filter=U"]); + if (code !== 0 || !stdout.trim()) return []; + + const blocks: ConflictBlock[] = []; + for (const file of stdout.trim().split("\n")) { + try { + const rl = createInterface({ input: createReadStream(join(cwd, file), "utf-8") }); + let lineNo = 0; + let blockStart: number | undefined; + let separatorLine: number | undefined; + for await (const line of rl) { + lineNo++; + if (line.startsWith("<<<<<<<")) { + blockStart = lineNo; + separatorLine = undefined; + } else if (line.startsWith("=======") && blockStart !== undefined) { + separatorLine = lineNo; + } else if (line.startsWith(">>>>>>>") && blockStart !== undefined && separatorLine !== undefined) { + blocks.push({ file, startLine: blockStart, separatorLine, endLine: lineNo }); + blockStart = undefined; + separatorLine = undefined; + } + } + } catch {} + } + return blocks; +} + +function formatRange(start: number, end: number): string { + if (start > end) return "empty"; + if (start === end) return `${start}`; + return `${start}-${end}`; +} + +function formatConflicts(ref: string, blocks: ConflictBlock[]): string { + const lines = [`Merged ${ref} with conflicts:`, ""]; + for (const b of blocks) { + const ours = formatRange(b.startLine + 1, b.separatorLine - 1); + const theirs = formatRange(b.separatorLine + 1, b.endLine - 1); + lines.push(` ${b.file}:${b.startLine}-${b.endLine} (ours ${ours}, theirs ${theirs})`); + } + lines.push("", "Resolve these conflicts."); + return lines.join("\n"); +} + +export default function (pi: ExtensionAPI) { + pi.on("agent_end", async (_event, ctx) => { + const { code: revParseCode } = await pi.exec("git", ["rev-parse", "--git-dir"]); + if (revParseCode !== 0) return; + + let ref = "MERGE_HEAD"; + + // If not already in a merge, attempt one + const { code: mergeHeadCode } = await pi.exec("git", ["rev-parse", "MERGE_HEAD"]); + if (mergeHeadCode !== 0) { + // Only attempt a new merge if the working tree is clean + const { stdout: status } = await pi.exec("git", ["status", "--porcelain"]); + if (status.trim()) return; + + const { stdout: upstream, code: upstreamCode } = await pi.exec("git", [ + "rev-parse", + "--abbrev-ref", + "--symbolic-full-name", + "@{u}", + ]); + if (upstreamCode !== 0) return; + + ref = upstream.trim(); + const remote = ref.split("/")[0]; + ctx.ui.notify(`git-merge-and-resolve: fetching ${remote}, merging ${ref}`, "info"); + + const { code: fetchCode, stderr: fetchErr } = await pi.exec("git", ["fetch", remote]); + if (fetchCode !== 0) { + ctx.ui.notify(`git-merge-and-resolve: fetch failed: ${fetchErr.trim()}`, "warning"); + return; + } + + const { code: mergeCode } = await pi.exec("git", ["merge", "--no-ff", ref]); + if (mergeCode === 0) return; + } + + // Either we just merged with conflicts, or we were already in an unfinished merge + const conflicts = await findConflicts(pi, ctx.cwd); + if (conflicts.length === 0) return; + + pi.sendUserMessage(formatConflicts(ref, conflicts), { deliverAs: "followUp" }); + }); +} diff --git a/examples/extensions/github-issue-autocomplete.ts b/examples/extensions/github-issue-autocomplete.ts new file mode 100644 index 0000000..0fd1b7b --- /dev/null +++ b/examples/extensions/github-issue-autocomplete.ts @@ -0,0 +1,185 @@ +// Requires GitHub CLI (`gh`) and a GitHub repository checkout. +// Preloads the latest open issues once per session, then filters them locally for fast `#...` completion. + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { + type AutocompleteItem, + type AutocompleteProvider, + type AutocompleteSuggestions, + fuzzyFilter, +} from "@earendil-works/pi-tui"; + +type GitHubIssue = { + number: number; + title: string; + state: string; +}; + +type RepoResolution = { ok: true; repo: string } | { ok: false; error: string }; + +const MAX_ISSUES = 100; +const MAX_SUGGESTIONS = 20; + +function extractIssueToken(textBeforeCursor: string): string | undefined { + const match = textBeforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/); + return match?.[1]; +} + +function parseGitHubRepo(remoteUrl: string): string | undefined { + const sshMatch = remoteUrl.match(/^git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/); + if (sshMatch) { + return sshMatch[1]; + } + + const httpsMatch = remoteUrl.match(/^https?:\/\/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/); + if (httpsMatch) { + return httpsMatch[1]; + } + + return undefined; +} + +async function resolveGitHubRepo(pi: ExtensionAPI, cwd: string): Promise { + const result = await pi.exec("git", ["remote", "-v"], { cwd, timeout: 5_000 }); + if (result.code !== 0) { + return { ok: false, error: "github-issue-autocomplete: cwd is not a git repository" }; + } + + for (const line of result.stdout.split("\n")) { + const columns = line.trim().split(/\s+/); + const remoteUrl = columns[1]; + if (!remoteUrl) { + continue; + } + const repo = parseGitHubRepo(remoteUrl); + if (repo) { + return { ok: true, repo }; + } + } + + return { ok: false, error: "github-issue-autocomplete: cwd is not a GitHub repository" }; +} + +function formatIssueItem(issue: GitHubIssue): AutocompleteItem { + return { + value: `#${issue.number}`, + label: `#${issue.number}`, + description: `[${issue.state.toLowerCase()}] ${issue.title}`, + }; +} + +function filterIssues(issues: GitHubIssue[], query: string): AutocompleteItem[] { + if (!query.trim()) { + return issues.slice(0, MAX_SUGGESTIONS).map(formatIssueItem); + } + + if (/^\d+$/.test(query)) { + const numericMatches = issues + .filter((issue) => String(issue.number).startsWith(query)) + .slice(0, MAX_SUGGESTIONS) + .map(formatIssueItem); + if (numericMatches.length > 0) { + return numericMatches; + } + } + + return fuzzyFilter(issues, query, (issue) => `${issue.number} ${issue.title}`) + .slice(0, MAX_SUGGESTIONS) + .map(formatIssueItem); +} + +function createIssueAutocompleteProvider( + current: AutocompleteProvider, + getIssues: () => Promise, +): AutocompleteProvider { + return { + async getSuggestions(lines, cursorLine, cursorCol, options): Promise { + const currentLine = lines[cursorLine] ?? ""; + const textBeforeCursor = currentLine.slice(0, cursorCol); + const token = extractIssueToken(textBeforeCursor); + if (token === undefined) { + return current.getSuggestions(lines, cursorLine, cursorCol, options); + } + + const issues = await getIssues(); + if (options.signal.aborted || !issues || issues.length === 0) { + return current.getSuggestions(lines, cursorLine, cursorCol, options); + } + + const suggestions = filterIssues(issues, token); + if (suggestions.length === 0) { + return current.getSuggestions(lines, cursorLine, cursorCol, options); + } + + return { + items: suggestions, + prefix: `#${token}`, + }; + }, + + applyCompletion(lines, cursorLine, cursorCol, item, prefix) { + return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix); + }, + + shouldTriggerFileCompletion(lines, cursorLine, cursorCol) { + return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true; + }, + }; +} + +export default function (pi: ExtensionAPI): void { + pi.on("session_start", async (_event, ctx) => { + const resolvedRepo = await resolveGitHubRepo(pi, ctx.cwd); + if (!resolvedRepo.ok) { + ctx.ui.notify(resolvedRepo.error, "error"); + return; + } + + const repo = resolvedRepo.repo; + let issuesPromise: Promise | undefined; + let loadErrorShown = false; + + const getIssues = async (): Promise => { + issuesPromise ||= (async () => { + const result = await pi.exec( + "gh", + [ + "issue", + "list", + "--repo", + repo, + "--state", + "open", + "--limit", + String(MAX_ISSUES), + "--json", + "number,title,state", + ], + { cwd: ctx.cwd, timeout: 5_000 }, + ); + if (result.code !== 0) { + if (!loadErrorShown) { + loadErrorShown = true; + const details = result.stderr.trim() || `exit code ${result.code}`; + ctx.ui.notify(`github-issue-autocomplete: failed to load issues: ${details}`, "error"); + } + return undefined; + } + + try { + return JSON.parse(result.stdout) as GitHubIssue[]; + } catch { + if (!loadErrorShown) { + loadErrorShown = true; + ctx.ui.notify("github-issue-autocomplete: failed to parse gh issue list output", "error"); + } + return undefined; + } + })(); + return issuesPromise; + }; + + void getIssues(); + ctx.ui.addAutocompleteProvider((current) => createIssueAutocompleteProvider(current, getIssues)); + }); +} diff --git a/examples/extensions/gondolin/index.ts b/examples/extensions/gondolin/index.ts new file mode 100644 index 0000000..ab050df --- /dev/null +++ b/examples/extensions/gondolin/index.ts @@ -0,0 +1,531 @@ +/** + * Gondolin Tool Routing Example + * + * Runs pi's built-in tools inside a local Gondolin micro-VM. The host working + * directory is mounted at /workspace in the guest. File changes under + * /workspace write through to the host; other guest filesystem changes are + * isolated to the VM. + * + * Setup: + * cd packages/coding-agent/examples/extensions/gondolin + * npm install --ignore-scripts + * + * Usage: + * cd /path/to/project + * pi -e /path/to/pi/packages/coding-agent/examples/extensions/gondolin + * + * Requirements: + * - Node.js >= 23.6.0 for @earendil-works/gondolin + * - QEMU installed (for example, `brew install qemu` on macOS) + */ + +import path from "node:path"; +import { RealFSProvider, VM } from "@earendil-works/gondolin"; +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; +import { + type BashOperations, + createBashTool, + createEditTool, + createFindTool, + createGrepTool, + createLsTool, + createReadTool, + createWriteTool, + DEFAULT_MAX_BYTES, + type EditOperations, + type FindOperations, + formatSize, + type GrepToolDetails, + type GrepToolInput, + type LsOperations, + type ReadOperations, + truncateHead, + truncateLine, + type WriteOperations, +} from "@earendil-works/pi-coding-agent"; + +const GUEST_WORKSPACE = "/workspace"; +const DEFAULT_GREP_LIMIT = 100; + +type TextToolResult = { + content: Array<{ type: "text"; text: string }>; + details: TDetails | undefined; +}; + +function stripAtPrefix(value: string): string { + return value.startsWith("@") ? value.slice(1) : value; +} + +function toPosix(value: string): string { + return value.split(path.sep).join(path.posix.sep); +} + +function isInsideHostPath(root: string, value: string): boolean { + const relativePath = path.relative(root, value); + return relativePath === "" || (!relativePath.startsWith("..") && !path.isAbsolute(relativePath)); +} + +function hostPathToGuest(localCwd: string, hostPath: string): string { + const relativePath = path.relative(localCwd, hostPath); + if (!isInsideHostPath(localCwd, hostPath)) return toPosix(hostPath); + return relativePath ? path.posix.join(GUEST_WORKSPACE, toPosix(relativePath)) : GUEST_WORKSPACE; +} + +function toGuestPath(localCwd: string, inputPath: string): string { + const trimmed = stripAtPrefix(inputPath.trim()); + if (!trimmed) return GUEST_WORKSPACE; + if (path.isAbsolute(trimmed)) { + if (isInsideHostPath(localCwd, trimmed)) return hostPathToGuest(localCwd, trimmed); + return path.posix.resolve("/", toPosix(trimmed)); + } + return path.posix.resolve(GUEST_WORKSPACE, toPosix(trimmed)); +} + +function createGondolinReadOps(vm: VM, localCwd: string): ReadOperations { + return { + readFile: async (filePath) => vm.fs.readFile(toGuestPath(localCwd, filePath)), + access: async (filePath) => { + await vm.fs.access(toGuestPath(localCwd, filePath)); + }, + detectImageMimeType: async (filePath) => { + const ext = path.posix.extname(toGuestPath(localCwd, filePath)).toLowerCase(); + if (ext === ".png") return "image/png"; + if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg"; + if (ext === ".gif") return "image/gif"; + if (ext === ".webp") return "image/webp"; + return null; + }, + }; +} + +function createGondolinWriteOps(vm: VM, localCwd: string): WriteOperations { + return { + writeFile: async (filePath, content) => { + await vm.fs.writeFile(toGuestPath(localCwd, filePath), content, { encoding: "utf8" }); + }, + mkdir: async (dirPath) => { + await vm.fs.mkdir(toGuestPath(localCwd, dirPath), { recursive: true }); + }, + }; +} + +function createGondolinEditOps(vm: VM, localCwd: string): EditOperations { + const readOps = createGondolinReadOps(vm, localCwd); + const writeOps = createGondolinWriteOps(vm, localCwd); + return { + readFile: readOps.readFile, + writeFile: writeOps.writeFile, + access: readOps.access, + }; +} + +function createGondolinLsOps(vm: VM, localCwd: string): LsOperations { + return { + exists: async (filePath) => { + try { + await vm.fs.access(toGuestPath(localCwd, filePath)); + return true; + } catch { + return false; + } + }, + stat: async (filePath) => vm.fs.stat(toGuestPath(localCwd, filePath)), + readdir: async (dirPath) => vm.fs.listDir(toGuestPath(localCwd, dirPath)), + }; +} + +async function walkGuestFiles( + vm: VM, + root: string, + visit: (guestPath: string, relativePath: string) => Promise, + signal?: AbortSignal, +): Promise { + if (signal?.aborted) throw new Error("Operation aborted"); + const stat = await vm.fs.stat(root, { signal }); + if (!stat.isDirectory()) return visit(root, path.posix.basename(root)); + + const walkDirectory = async (dir: string, relativeDir: string): Promise => { + if (signal?.aborted) throw new Error("Operation aborted"); + const entries = await vm.fs.listDir(dir, { signal }); + for (const entry of entries) { + if (entry === ".git" || entry === "node_modules") continue; + const guestPath = path.posix.join(dir, entry); + const relativePath = relativeDir ? path.posix.join(relativeDir, entry) : entry; + let entryStat: Awaited>; + try { + entryStat = await vm.fs.stat(guestPath, { signal }); + } catch { + continue; + } + if (entryStat.isDirectory()) { + if (!(await walkDirectory(guestPath, relativePath))) return false; + } else if (!(await visit(guestPath, relativePath))) { + return false; + } + } + return true; + }; + + return walkDirectory(root, ""); +} + +function matchesToolGlob(relativePath: string, pattern: string): boolean { + const normalizedPattern = toPosix(pattern); + if (normalizedPattern.includes("/")) { + return ( + path.posix.matchesGlob(relativePath, normalizedPattern) || + path.posix.matchesGlob(relativePath, `**/${normalizedPattern}`) + ); + } + return path.posix.matchesGlob(path.posix.basename(relativePath), normalizedPattern); +} + +function createGondolinFindOps(vm: VM, localCwd: string): FindOperations { + return { + exists: async (filePath) => { + try { + await vm.fs.access(toGuestPath(localCwd, filePath)); + return true; + } catch { + return false; + } + }, + glob: async (pattern, cwd, options) => { + const root = toGuestPath(localCwd, cwd); + const results: string[] = []; + await walkGuestFiles(vm, root, async (guestPath, relativePath) => { + if (results.length >= options.limit) return false; + if (matchesToolGlob(relativePath, pattern)) results.push(guestPath); + return results.length < options.limit; + }); + return results; + }, + }; +} + +function createLineMatcher(pattern: string, literal: boolean | undefined, ignoreCase: boolean | undefined) { + if (literal) { + const needle = ignoreCase ? pattern.toLowerCase() : pattern; + return (line: string) => (ignoreCase ? line.toLowerCase() : line).includes(needle); + } + const regex = new RegExp(pattern, ignoreCase ? "i" : undefined); + return (line: string) => regex.test(line); +} + +function appendGrepBlock(params: { + outputLines: string[]; + lines: string[]; + relativePath: string; + lineIndex: number; + contextLines: number; +}): boolean { + let linesTruncated = false; + const start = params.contextLines > 0 ? Math.max(0, params.lineIndex - params.contextLines) : params.lineIndex; + const end = + params.contextLines > 0 + ? Math.min(params.lines.length - 1, params.lineIndex + params.contextLines) + : params.lineIndex; + + for (let index = start; index <= end; index++) { + const rawLine = params.lines[index] ?? ""; + const { text, wasTruncated } = truncateLine(rawLine.replace(/\r/g, "")); + if (wasTruncated) linesTruncated = true; + const separator = index === params.lineIndex ? ":" : "-"; + params.outputLines.push(`${params.relativePath}${separator}${index + 1}${separator} ${text}`); + } + return linesTruncated; +} + +async function executeGondolinGrep( + vm: VM, + localCwd: string, + params: GrepToolInput, + signal?: AbortSignal, +): Promise> { + const root = toGuestPath(localCwd, params.path ?? "."); + const rootStat = await vm.fs.stat(root, { signal }); + const rootIsDirectory = rootStat.isDirectory(); + const matcher = createLineMatcher(params.pattern, params.literal, params.ignoreCase); + const contextLines = params.context && params.context > 0 ? params.context : 0; + const effectiveLimit = Math.max(1, params.limit ?? DEFAULT_GREP_LIMIT); + const outputLines: string[] = []; + const details: GrepToolDetails = {}; + let matchCount = 0; + let matchLimitReached = false; + let linesTruncated = false; + + await walkGuestFiles( + vm, + root, + async (guestPath, relativePath) => { + if (matchCount >= effectiveLimit) return false; + if (params.glob && !matchesToolGlob(relativePath, params.glob)) return true; + let content: string; + try { + content = await vm.fs.readFile(guestPath, { encoding: "utf8", signal }); + } catch { + return true; + } + const lines = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n"); + const displayPath = rootIsDirectory ? relativePath : path.posix.basename(guestPath); + for (let index = 0; index < lines.length; index++) { + if (signal?.aborted) throw new Error("Operation aborted"); + if (!matcher(lines[index] ?? "")) continue; + matchCount++; + if (appendGrepBlock({ outputLines, lines, relativePath: displayPath, lineIndex: index, contextLines })) { + linesTruncated = true; + } + if (matchCount >= effectiveLimit) { + matchLimitReached = true; + return false; + } + } + return true; + }, + signal, + ); + + if (matchCount === 0) return { content: [{ type: "text", text: "No matches found" }], details: undefined }; + + const rawOutput = outputLines.join("\n"); + const truncation = truncateHead(rawOutput, { maxLines: Number.MAX_SAFE_INTEGER }); + const notices: string[] = []; + let output = truncation.content; + + if (matchLimitReached) { + details.matchLimitReached = effectiveLimit; + notices.push(`${effectiveLimit} matches limit reached`); + } + if (linesTruncated) { + details.linesTruncated = true; + notices.push("long lines truncated"); + } + if (truncation.truncated) { + details.truncation = truncation; + notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`); + } + if (notices.length > 0) output += `\n\n[${notices.join(". ")}]`; + + return { + content: [{ type: "text", text: output }], + details: Object.keys(details).length > 0 ? details : undefined, + }; +} + +function sanitizeEnv(env: NodeJS.ProcessEnv | undefined): Record | undefined { + if (!env) return undefined; + const result: Record = {}; + for (const [key, value] of Object.entries(env)) { + if (typeof value === "string") result[key] = value; + } + return result; +} + +function createGondolinBashOps(vm: VM, localCwd: string, shellPath: string): BashOperations { + return { + exec: async (command, cwd, { onData, signal, timeout, env }) => { + if (signal?.aborted) throw new Error("aborted"); + const guestCwd = toGuestPath(localCwd, cwd); + const controller = new AbortController(); + const onAbort = () => controller.abort(); + signal?.addEventListener("abort", onAbort, { once: true }); + + let timedOut = false; + const timer = + timeout && timeout > 0 + ? setTimeout(() => { + timedOut = true; + controller.abort(); + }, timeout * 1000) + : undefined; + + try { + const proc = vm.exec([shellPath, "-lc", command], { + cwd: guestCwd, + env: sanitizeEnv(env), + signal: controller.signal, + stdout: "pipe", + stderr: "pipe", + }); + for await (const chunk of proc.output()) onData(chunk.data); + const result = await proc; + return { exitCode: result.exitCode }; + } catch (error) { + if (signal?.aborted) throw new Error("aborted"); + if (timedOut) throw new Error(`timeout:${timeout}`); + throw error; + } finally { + if (timer) clearTimeout(timer); + signal?.removeEventListener("abort", onAbort); + } + }, + }; +} + +export default function (pi: ExtensionAPI) { + const localCwd = process.cwd(); + const localRead = createReadTool(localCwd); + const localWrite = createWriteTool(localCwd); + const localEdit = createEditTool(localCwd); + const localBash = createBashTool(localCwd); + const localGrep = createGrepTool(localCwd); + const localFind = createFindTool(localCwd); + const localLs = createLsTool(localCwd); + + let vm: VM | undefined; + let vmStarting: Promise | undefined; + let shellPath = "/bin/sh"; + + async function startVm(ctx?: ExtensionContext): Promise { + ctx?.ui.setStatus("gondolin", ctx.ui.theme.fg("accent", `Gondolin: starting ${GUEST_WORKSPACE}`)); + const created = await VM.create({ + sessionLabel: `pi ${path.basename(localCwd)}`, + vfs: { + mounts: { + [GUEST_WORKSPACE]: new RealFSProvider(localCwd), + }, + }, + }); + const bashProbe = await created.exec(["/bin/sh", "-lc", "command -v bash || true"]); + shellPath = bashProbe.stdout.trim() || "/bin/sh"; + vm = created; + ctx?.ui.setStatus( + "gondolin", + ctx.ui.theme.fg("accent", `Gondolin: ${created.id.slice(0, 8)} (${GUEST_WORKSPACE})`), + ); + ctx?.ui.notify(`Gondolin VM ready. ${localCwd} is mounted at ${GUEST_WORKSPACE}.`, "info"); + return created; + } + + async function ensureVm(ctx?: ExtensionContext): Promise { + if (vm) return vm; + if (!vmStarting) { + vmStarting = startVm(ctx).finally(() => { + vmStarting = undefined; + }); + } + return vmStarting; + } + + pi.on("session_start", async (_event, ctx) => { + await ensureVm(ctx); + }); + + pi.on("session_shutdown", async (_event, ctx) => { + const activeVm = vm; + vm = undefined; + vmStarting = undefined; + if (!activeVm) return; + ctx.ui.setStatus("gondolin", ctx.ui.theme.fg("muted", "Gondolin: stopping")); + try { + await activeVm.close(); + } finally { + ctx.ui.setStatus("gondolin", undefined); + } + }); + + pi.registerCommand("gondolin", { + description: "Show Gondolin VM status", + handler: async (_args, ctx) => { + const activeVm = await ensureVm(ctx); + ctx.ui.notify( + [ + `Gondolin VM: ${activeVm.id}`, + `Host workspace: ${localCwd}`, + `Guest workspace: ${GUEST_WORKSPACE}`, + `Shell: ${shellPath}`, + ].join("\n"), + "info", + ); + }, + }); + + pi.registerTool({ + ...localRead, + async execute(id, params, signal, onUpdate, ctx) { + const activeVm = await ensureVm(ctx); + const tool = createReadTool(GUEST_WORKSPACE, { + operations: createGondolinReadOps(activeVm, localCwd), + }); + return tool.execute(id, params, signal, onUpdate); + }, + }); + + pi.registerTool({ + ...localWrite, + async execute(id, params, signal, onUpdate, ctx) { + const activeVm = await ensureVm(ctx); + const tool = createWriteTool(GUEST_WORKSPACE, { + operations: createGondolinWriteOps(activeVm, localCwd), + }); + return tool.execute(id, params, signal, onUpdate); + }, + }); + + pi.registerTool({ + ...localEdit, + async execute(id, params, signal, onUpdate, ctx) { + const activeVm = await ensureVm(ctx); + const tool = createEditTool(GUEST_WORKSPACE, { + operations: createGondolinEditOps(activeVm, localCwd), + }); + return tool.execute(id, params, signal, onUpdate); + }, + }); + + pi.registerTool({ + ...localBash, + async execute(id, params, signal, onUpdate, ctx) { + const activeVm = await ensureVm(ctx); + const tool = createBashTool(GUEST_WORKSPACE, { + operations: createGondolinBashOps(activeVm, localCwd, shellPath), + }); + return tool.execute(id, params, signal, onUpdate); + }, + }); + + pi.registerTool({ + ...localLs, + async execute(id, params, signal, onUpdate, ctx) { + const activeVm = await ensureVm(ctx); + const tool = createLsTool(GUEST_WORKSPACE, { + operations: createGondolinLsOps(activeVm, localCwd), + }); + return tool.execute(id, params, signal, onUpdate); + }, + }); + + pi.registerTool({ + ...localFind, + async execute(id, params, signal, onUpdate, ctx) { + const activeVm = await ensureVm(ctx); + const tool = createFindTool(GUEST_WORKSPACE, { + operations: createGondolinFindOps(activeVm, localCwd), + }); + return tool.execute(id, params, signal, onUpdate); + }, + }); + + pi.registerTool({ + ...localGrep, + async execute(_id, params, signal, _onUpdate, ctx) { + const activeVm = await ensureVm(ctx); + return executeGondolinGrep(activeVm, localCwd, params, signal); + }, + }); + + pi.on("user_bash", async (_event, ctx) => { + const activeVm = await ensureVm(ctx); + return { operations: createGondolinBashOps(activeVm, localCwd, shellPath) }; + }); + + pi.on("before_agent_start", async (event, ctx) => { + await ensureVm(ctx); + const localLine = `Current working directory: ${localCwd}`; + const guestLine = `Current working directory: ${GUEST_WORKSPACE} (Gondolin VM; host workspace mounted from ${localCwd})`; + const systemPrompt = event.systemPrompt.includes(localLine) + ? event.systemPrompt.replace(localLine, guestLine) + : `${event.systemPrompt}\n\n${guestLine}`; + return { systemPrompt }; + }); +} diff --git a/examples/extensions/gondolin/package-lock.json b/examples/extensions/gondolin/package-lock.json new file mode 100644 index 0000000..1df21a2 --- /dev/null +++ b/examples/extensions/gondolin/package-lock.json @@ -0,0 +1,185 @@ +{ + "name": "pi-extension-gondolin", + "version": "0.83.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "pi-extension-gondolin", + "version": "0.83.0", + "dependencies": { + "@earendil-works/gondolin": "0.12.0" + } + }, + "node_modules/@cto.af/wtf8": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/@cto.af/wtf8/-/wtf8-0.0.5.tgz", + "integrity": "sha512-LfUFi+Vv4eDzj+XAtR89e3wwjXA/NZjUSwU5NhwbBrLecxPaBYFy3exCuc1j+D4UZeOVdqlsl8G7LmOt18V0tg==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/@earendil-works/gondolin": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@earendil-works/gondolin/-/gondolin-0.12.0.tgz", + "integrity": "sha512-BXbvzQKb5QmxY5NtthRDONJTu7+IDKbzqWGrJyyNXMP7N681Tx0Q9TK8pK1ba8nUvYQTipNJyGZOsJfYiZll1A==", + "license": "Apache-2.0", + "dependencies": { + "cbor2": "^2.3.0", + "node-forge": "^1.3.3", + "ssh2": "^1.17.0", + "undici": "^6.21.0" + }, + "bin": { + "gondolin": "dist/bin/gondolin.js" + }, + "engines": { + "node": ">=23.6.0" + }, + "optionalDependencies": { + "@earendil-works/gondolin-krun-runner-darwin-arm64": "0.12.0", + "@earendil-works/gondolin-krun-runner-linux-x64": "0.12.0" + } + }, + "node_modules/@earendil-works/gondolin-krun-runner-darwin-arm64": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@earendil-works/gondolin-krun-runner-darwin-arm64/-/gondolin-krun-runner-darwin-arm64-0.12.0.tgz", + "integrity": "sha512-ftDlusht4PcT7Y3TuPrZIKrCXy3isiBTVMvlXYK0pcud2uXY6uwFTGeunYgP+8ND/60ddb+MImqbfmkcK8B84A==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "bin": { + "gondolin-krun-runner": "bin/gondolin-krun-runner" + } + }, + "node_modules/@earendil-works/gondolin-krun-runner-linux-x64": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@earendil-works/gondolin-krun-runner-linux-x64/-/gondolin-krun-runner-linux-x64-0.12.0.tgz", + "integrity": "sha512-RRYsgwe2r5ApKmFNy469QgwnyjAHpAs9XANdWpTd9ol4iUYOY3sX7e0xIooAKxd+ktxGI4N/xRWicwGen3D/Ow==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "bin": { + "gondolin-krun-runner": "bin/gondolin-krun-runner" + } + }, + "node_modules/asn1": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", + "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": "~2.1.0" + } + }, + "node_modules/bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", + "license": "BSD-3-Clause", + "dependencies": { + "tweetnacl": "^0.14.3" + } + }, + "node_modules/buildcheck": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz", + "integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==", + "optional": true, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/cbor2": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/cbor2/-/cbor2-2.3.0.tgz", + "integrity": "sha512-76WB3hq8BoaGkMkBVJ27fW5LJU+qqDLEpgRNCG/SYKhODWXpVPOTD4UcUto3IEzYLA52nsvbhb0wabhHDn3qXg==", + "license": "MIT", + "dependencies": { + "@cto.af/wtf8": "0.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cpu-features": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz", + "integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==", + "hasInstallScript": true, + "optional": true, + "dependencies": { + "buildcheck": "~0.0.6", + "nan": "^2.19.0" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/nan": { + "version": "2.27.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.27.0.tgz", + "integrity": "sha512-hC+0LidcL3XE4rp1C4H54KujgXKzbfyTngZTwBByQxsOxCEKZT0MPQ4hOKUH2jU1OYstqdDH4onyHPDzcV0XdQ==", + "license": "MIT", + "optional": true + }, + "node_modules/node-forge": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.0.tgz", + "integrity": "sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ==", + "license": "(BSD-3-Clause OR GPL-2.0)", + "engines": { + "node": ">= 6.13.0" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/ssh2": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz", + "integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==", + "hasInstallScript": true, + "dependencies": { + "asn1": "^0.2.6", + "bcrypt-pbkdf": "^1.0.2" + }, + "engines": { + "node": ">=10.16.0" + }, + "optionalDependencies": { + "cpu-features": "~0.0.10", + "nan": "^2.23.0" + } + }, + "node_modules/tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==", + "license": "Unlicense" + }, + "node_modules/undici": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.26.0.tgz", + "integrity": "sha512-4yqz8a3n5HmGTlsbADNtr/dJlhkh/55Rq798G6ibiULcXbDtaLpTl1pvdqcbFfeoj3iSi52lePFM7h9H21cw/A==", + "license": "MIT", + "engines": { + "node": ">=18.17" + } + } + } +} diff --git a/examples/extensions/gondolin/package.json b/examples/extensions/gondolin/package.json new file mode 100644 index 0000000..caeead4 --- /dev/null +++ b/examples/extensions/gondolin/package.json @@ -0,0 +1,19 @@ +{ + "name": "pi-extension-gondolin", + "private": true, + "version": "0.83.0", + "type": "module", + "scripts": { + "clean": "echo 'nothing to clean'", + "build": "echo 'nothing to build'", + "check": "echo 'nothing to check'" + }, + "pi": { + "extensions": [ + "./index.ts" + ] + }, + "dependencies": { + "@earendil-works/gondolin": "0.12.0" + } +} diff --git a/examples/extensions/handoff.ts b/examples/extensions/handoff.ts new file mode 100644 index 0000000..f9d8967 --- /dev/null +++ b/examples/extensions/handoff.ts @@ -0,0 +1,199 @@ +/** + * Handoff extension - transfer context to a new focused session + * + * Instead of compacting (which is lossy), handoff extracts what matters + * for your next task and creates a new session with a generated prompt. + * + * Usage: + * /handoff now implement this for teams as well + * /handoff execute phase one of the plan + * /handoff check other places that need this fix + * + * The generated prompt appears as a draft in the editor for review/editing. + */ + +import type { AgentMessage } from "@earendil-works/pi-agent-core"; +import { uuidv7 } from "@earendil-works/pi-ai"; +import { complete, type Message } from "@earendil-works/pi-ai/compat"; +import type { ExtensionAPI, SessionEntry } from "@earendil-works/pi-coding-agent"; +import { BorderedLoader, convertToLlm, serializeConversation } from "@earendil-works/pi-coding-agent"; + +const SYSTEM_PROMPT = `You are a context transfer assistant. Given a conversation history and the user's goal for a new thread, generate a focused prompt that: + +1. Summarizes relevant context from the conversation (decisions made, approaches taken, key findings) +2. Lists any relevant files that were discussed or modified +3. Clearly states the next task based on the user's goal +4. Is self-contained - the new thread should be able to proceed without the old conversation + +Format your response as a prompt the user can send to start the new thread. Be concise but include all necessary context. Do not include any preamble like "Here's the prompt" - just output the prompt itself. + +Example output format: +## Context +We've been working on X. Key decisions: +- Decision 1 +- Decision 2 + +Files involved: +- path/to/file1.ts +- path/to/file2.ts + +## Task +[Clear description of what to do next based on user's goal]`; + +function entryToMessage(entry: SessionEntry): AgentMessage | undefined { + if (entry.type === "message") { + return entry.message; + } + if (entry.type === "compaction") { + return { + role: "compactionSummary", + summary: entry.summary, + tokensBefore: entry.tokensBefore, + timestamp: new Date(entry.timestamp).getTime(), + }; + } + return undefined; +} + +function getHandoffMessages(branch: SessionEntry[]): AgentMessage[] { + let compactionIndex = -1; + for (let i = branch.length - 1; i >= 0; i--) { + if (branch[i].type === "compaction") { + compactionIndex = i; + break; + } + } + if (compactionIndex < 0) { + return branch.map(entryToMessage).filter((message) => message !== undefined); + } + + const compaction = branch[compactionIndex]; + const firstKeptIndex = + compaction.type === "compaction" ? branch.findIndex((entry) => entry.id === compaction.firstKeptEntryId) : -1; + const compactedBranch = [ + compaction, + ...(firstKeptIndex >= 0 ? branch.slice(firstKeptIndex, compactionIndex) : []), + ...branch.slice(compactionIndex + 1), + ]; + return compactedBranch.map(entryToMessage).filter((message) => message !== undefined); +} + +export default function (pi: ExtensionAPI) { + pi.registerCommand("handoff", { + description: "Transfer context to a new focused session", + handler: async (args, ctx) => { + if (ctx.mode !== "tui") { + ctx.ui.notify("handoff requires interactive mode", "error"); + return; + } + + if (!ctx.model) { + ctx.ui.notify("No model selected", "error"); + return; + } + + const goal = args.trim(); + if (!goal) { + ctx.ui.notify("Usage: /handoff ", "error"); + return; + } + + // Gather conversation context from current branch. If the branch was compacted, + // include the compaction summary plus entries from firstKeptEntryId onward. + const messages = getHandoffMessages(ctx.sessionManager.getBranch()); + + if (messages.length === 0) { + ctx.ui.notify("No conversation to hand off", "error"); + return; + } + + // Convert to LLM format and serialize + const llmMessages = convertToLlm(messages); + const conversationText = serializeConversation(llmMessages); + const currentSessionFile = ctx.sessionManager.getSessionFile(); + + // Generate the handoff prompt with loader UI + const result = await ctx.ui.custom((tui, theme, _kb, done) => { + const loader = new BorderedLoader(tui, theme, `Generating handoff prompt...`); + loader.onAbort = () => done(null); + + const doGenerate = async () => { + const auth = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model!); + if (!auth.ok || !auth.apiKey) { + throw new Error(auth.ok ? `No API key for ${ctx.model!.provider}` : auth.error); + } + + const userMessage: Message = { + role: "user", + content: [ + { + type: "text", + text: `## Conversation History\n\n${conversationText}\n\n## User's Goal for New Thread\n\n${goal}`, + }, + ], + timestamp: Date.now(), + }; + + const response = await complete( + ctx.model!, + { systemPrompt: SYSTEM_PROMPT, messages: [userMessage] }, + { + apiKey: auth.apiKey, + headers: auth.headers, + env: auth.env, + signal: loader.signal, + cacheRetention: "none", + sessionId: uuidv7(), + }, + ); + + if (response.stopReason === "aborted") { + return null; + } + + return response.content + .filter((c): c is { type: "text"; text: string } => c.type === "text") + .map((c) => c.text) + .join("\n"); + }; + + doGenerate() + .then(done) + .catch((err) => { + console.error("Handoff generation failed:", err); + done(null); + }); + + return loader; + }); + + if (result === null) { + ctx.ui.notify("Cancelled", "info"); + return; + } + + // Let user edit the generated prompt + const editedPrompt = await ctx.ui.editor("Edit handoff prompt", result); + + if (editedPrompt === undefined) { + ctx.ui.notify("Cancelled", "info"); + return; + } + + // Create new session with parent tracking. Use the replacement-session + // context for post-switch UI work; the original ctx is stale after a + // successful session replacement. + const newSessionResult = await ctx.newSession({ + parentSession: currentSessionFile, + withSession: async (replacementCtx) => { + replacementCtx.ui.setEditorText(editedPrompt); + replacementCtx.ui.notify("Handoff ready. Submit when ready.", "info"); + }, + }); + + if (newSessionResult.cancelled) { + ctx.ui.notify("New session cancelled", "info"); + } + }, + }); +} diff --git a/examples/extensions/hello.ts b/examples/extensions/hello.ts new file mode 100644 index 0000000..52da391 --- /dev/null +++ b/examples/extensions/hello.ts @@ -0,0 +1,26 @@ +/** + * Hello Tool - Minimal custom tool example + */ + +import { Type } from "@earendil-works/pi-ai"; +import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +const helloTool = defineTool({ + name: "hello", + label: "Hello", + description: "A simple greeting tool", + parameters: Type.Object({ + name: Type.String({ description: "Name to greet" }), + }), + + async execute(_toolCallId, params, _signal, _onUpdate, _ctx) { + return { + content: [{ type: "text", text: `Hello, ${params.name}!` }], + details: { greeted: params.name }, + }; + }, +}); + +export default function (pi: ExtensionAPI) { + pi.registerTool(helloTool); +} diff --git a/examples/extensions/hidden-thinking-label.ts b/examples/extensions/hidden-thinking-label.ts new file mode 100644 index 0000000..bcdaab6 --- /dev/null +++ b/examples/extensions/hidden-thinking-label.ts @@ -0,0 +1,53 @@ +/** + * Hidden Thinking Label Extension + * + * Demonstrates `ctx.ui.setHiddenThinkingLabel()` for customizing the label shown + * when thinking blocks are hidden. + * + * Usage: + * pi --extension examples/extensions/hidden-thinking-label.ts + * + * Test: + * 1. Load this extension + * 2. Hide thinking blocks with Ctrl+T + * 3. Ask for something that produces reasoning output + * 4. The collapsed thinking block label will show the custom text + * + * Commands: + * /thinking-label Set a custom hidden thinking label + * /thinking-label Reset to the default label + */ + +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; + +const DEFAULT_LABEL = "Pondering..."; + +export default function (pi: ExtensionAPI) { + let label = DEFAULT_LABEL; + + const applyLabel = (ctx: ExtensionContext) => { + ctx.ui.setHiddenThinkingLabel(label); + }; + + pi.on("session_start", async (_event, ctx) => { + applyLabel(ctx); + }); + + pi.registerCommand("thinking-label", { + description: "Set the hidden thinking label. Use without args to reset.", + handler: async (args, ctx) => { + const nextLabel = args.trim(); + + if (!nextLabel) { + label = DEFAULT_LABEL; + ctx.ui.setHiddenThinkingLabel(); + ctx.ui.notify(`Hidden thinking label reset to: ${DEFAULT_LABEL}`); + return; + } + + label = nextLabel; + ctx.ui.setHiddenThinkingLabel(label); + ctx.ui.notify(`Hidden thinking label set to: ${label}`); + }, + }); +} diff --git a/examples/extensions/inline-bash.ts b/examples/extensions/inline-bash.ts new file mode 100644 index 0000000..1184969 --- /dev/null +++ b/examples/extensions/inline-bash.ts @@ -0,0 +1,94 @@ +/** + * Inline Bash Extension - expands inline bash commands in user prompts. + * + * Start pi with this extension: + * pi -e ./examples/extensions/inline-bash.ts + * + * Then type prompts with inline bash: + * What's in !{pwd}? + * The current branch is !{git branch --show-current} and status: !{git status --short} + * My node version is !{node --version} + * + * The !{command} patterns are executed and replaced with their output before + * the prompt is sent to the agent. + * + * Note: Regular !command syntax (whole-line bash) is preserved and works as before. + */ +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + const PATTERN = /!\{([^}]+)\}/g; + const TIMEOUT_MS = 30000; + + pi.on("input", async (event, ctx) => { + const text = event.text; + + // Don't process if it's a whole-line bash command (starts with !) + // This preserves the existing !command behavior + if (text.trimStart().startsWith("!") && !text.trimStart().startsWith("!{")) { + return { action: "continue" }; + } + + // Check if there are any inline bash patterns + if (!PATTERN.test(text)) { + return { action: "continue" }; + } + + // Reset regex state after test() + PATTERN.lastIndex = 0; + + let result = text; + const expansions: Array<{ command: string; output: string; error?: string }> = []; + + // Find all matches first (to avoid issues with replacing while iterating) + const matches: Array<{ full: string; command: string }> = []; + let match = PATTERN.exec(text); + while (match) { + matches.push({ full: match[0], command: match[1] }); + match = PATTERN.exec(text); + } + + // Execute each command and collect results + for (const { full, command } of matches) { + try { + const bashResult = await pi.exec("bash", ["-c", command], { + timeout: TIMEOUT_MS, + }); + + const output = bashResult.stdout || bashResult.stderr || ""; + const trimmed = output.trim(); + + if (bashResult.code !== 0 && bashResult.stderr) { + expansions.push({ + command, + output: trimmed, + error: `exit code ${bashResult.code}`, + }); + } else { + expansions.push({ command, output: trimmed }); + } + + result = result.replace(full, trimmed); + } catch (err) { + const errorMsg = err instanceof Error ? err.message : String(err); + expansions.push({ command, output: "", error: errorMsg }); + result = result.replace(full, `[error: ${errorMsg}]`); + } + } + + // Show what was expanded (if UI available) + if (ctx.hasUI && expansions.length > 0) { + const summary = expansions + .map((e) => { + const status = e.error ? ` (${e.error})` : ""; + const preview = e.output.length > 50 ? `${e.output.slice(0, 50)}...` : e.output; + return `!{${e.command}}${status} -> "${preview}"`; + }) + .join("\n"); + + ctx.ui.notify(`Expanded ${expansions.length} inline command(s):\n${summary}`, "info"); + } + + return { action: "transform", text: result, images: event.images }; + }); +} diff --git a/examples/extensions/input-transform-streaming.ts b/examples/extensions/input-transform-streaming.ts new file mode 100644 index 0000000..65d805a --- /dev/null +++ b/examples/extensions/input-transform-streaming.ts @@ -0,0 +1,39 @@ +/** + * Streaming-Aware Input Gate + * + * Demonstrates `event.streamingBehavior` to skip expensive pre-processing + * during mid-stream steering, where low latency matters. + * + * This extension prepends `git diff --stat` output when the user mentions + * file changes, giving the model immediate context. During steering the + * exec call is skipped so the correction reaches the model without delay. + * + * Start pi with this extension: + * pi -e ./examples/extensions/input-transform-streaming.ts + */ +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +const TRIGGER = /\b(changes?|diff|modified)\b/i; + +export default function (pi: ExtensionAPI) { + pi.on("input", async (event) => { + // During steering, skip the exec call — corrections should be fast + if (event.streamingBehavior === "steer") { + return { action: "continue" }; + } + + if (!TRIGGER.test(event.text)) { + return { action: "continue" }; + } + + const { stdout, code } = await pi.exec("git", ["diff", "--stat"]); + if (code !== 0 || !stdout.trim()) { + return { action: "continue" }; + } + + return { + action: "transform", + text: `${event.text}\n\nCurrent uncommitted changes:\n\`\`\`\n${stdout.trim()}\n\`\`\``, + }; + }); +} diff --git a/examples/extensions/input-transform.ts b/examples/extensions/input-transform.ts new file mode 100644 index 0000000..e47c1af --- /dev/null +++ b/examples/extensions/input-transform.ts @@ -0,0 +1,43 @@ +/** + * Input Transform Example - demonstrates the `input` event for intercepting user input. + * + * Start pi with this extension: + * pi -e ./examples/extensions/input-transform.ts + * + * Then type these inside pi: + * ?quick What is TypeScript? → "Respond briefly: What is TypeScript?" + * ping → "pong" (instant, no LLM) + * time → current time (instant, no LLM) + */ +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.on("input", async (event, ctx) => { + // Source-based logic: skip processing for extension-injected messages + if (event.source === "extension") { + return { action: "continue" }; + } + + // Transform: ?quick prefix for brief responses + if (event.text.startsWith("?quick ")) { + const query = event.text.slice(7).trim(); + if (!query) { + ctx.ui.notify("Usage: ?quick ", "warning"); + return { action: "handled" }; + } + return { action: "transform", text: `Respond briefly in 1-2 sentences: ${query}` }; + } + + // Handle: instant responses without LLM (extension shows its own feedback) + if (event.text.toLowerCase() === "ping") { + ctx.ui.notify("pong", "info"); + return { action: "handled" }; + } + if (event.text.toLowerCase() === "time") { + ctx.ui.notify(new Date().toLocaleString(), "info"); + return { action: "handled" }; + } + + return { action: "continue" }; + }); +} diff --git a/examples/extensions/interactive-shell.ts b/examples/extensions/interactive-shell.ts new file mode 100644 index 0000000..b1dd374 --- /dev/null +++ b/examples/extensions/interactive-shell.ts @@ -0,0 +1,196 @@ +/** + * Interactive Shell Commands Extension + * + * Enables running interactive commands (vim, git rebase -i, htop, etc.) + * with full terminal access. The TUI suspends while they run. + * + * Usage: + * pi -e examples/extensions/interactive-shell.ts + * + * !vim file.txt # Auto-detected as interactive + * !i any-command # Force interactive mode with !i prefix + * !git rebase -i HEAD~3 + * !htop + * + * Configuration via environment variables: + * INTERACTIVE_COMMANDS - Additional commands (comma-separated) + * INTERACTIVE_EXCLUDE - Commands to exclude (comma-separated) + * + * Note: This only intercepts user `!` commands, not agent bash tool calls. + * If the agent runs an interactive command, it will fail (which is fine). + */ + +import { spawnSync } from "node:child_process"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +// Default interactive commands - editors, pagers, git ops, TUIs +const DEFAULT_INTERACTIVE_COMMANDS = [ + // Editors + "vim", + "nvim", + "vi", + "nano", + "emacs", + "pico", + "micro", + "helix", + "hx", + "kak", + // Pagers + "less", + "more", + "most", + // Git interactive + "git commit", + "git rebase", + "git merge", + "git cherry-pick", + "git revert", + "git add -p", + "git add --patch", + "git add -i", + "git add --interactive", + "git stash -p", + "git stash --patch", + "git reset -p", + "git reset --patch", + "git checkout -p", + "git checkout --patch", + "git difftool", + "git mergetool", + // System monitors + "htop", + "top", + "btop", + "glances", + // File managers + "ranger", + "nnn", + "lf", + "mc", + "vifm", + // Git TUIs + "tig", + "lazygit", + "gitui", + // Fuzzy finders + "fzf", + "sk", + // Remote sessions + "ssh", + "telnet", + "mosh", + // Database clients + "psql", + "mysql", + "sqlite3", + "mongosh", + "redis-cli", + // Kubernetes/Docker + "kubectl edit", + "kubectl exec -it", + "docker exec -it", + "docker run -it", + // Other + "tmux", + "screen", + "ncdu", +]; + +function getInteractiveCommands(): string[] { + const additional = + process.env.INTERACTIVE_COMMANDS?.split(",") + .map((s) => s.trim()) + .filter(Boolean) ?? []; + const excluded = new Set(process.env.INTERACTIVE_EXCLUDE?.split(",").map((s) => s.trim().toLowerCase()) ?? []); + return [...DEFAULT_INTERACTIVE_COMMANDS, ...additional].filter((cmd) => !excluded.has(cmd.toLowerCase())); +} + +function isInteractiveCommand(command: string): boolean { + const trimmed = command.trim().toLowerCase(); + const commands = getInteractiveCommands(); + + for (const cmd of commands) { + const cmdLower = cmd.toLowerCase(); + // Match at start + if (trimmed === cmdLower || trimmed.startsWith(`${cmdLower} `) || trimmed.startsWith(`${cmdLower}\t`)) { + return true; + } + // Match after pipe: "cat file | less" + const pipeIdx = trimmed.lastIndexOf("|"); + if (pipeIdx !== -1) { + const afterPipe = trimmed.slice(pipeIdx + 1).trim(); + if (afterPipe === cmdLower || afterPipe.startsWith(`${cmdLower} `)) { + return true; + } + } + } + return false; +} + +export default function (pi: ExtensionAPI) { + pi.on("user_bash", async (event, ctx) => { + let command = event.command; + let forceInteractive = false; + + // Check for !i prefix (command comes without the leading !) + // The prefix parsing happens before this event, so we check if command starts with "i " + if (command.startsWith("i ") || command.startsWith("i\t")) { + forceInteractive = true; + command = command.slice(2).trim(); + } + + const shouldBeInteractive = forceInteractive || isInteractiveCommand(command); + if (!shouldBeInteractive) { + return; // Let normal handling proceed + } + + // No UI available (print mode, RPC, etc.) + if (ctx.mode !== "tui") { + return { + result: { output: "(interactive commands require TUI)", exitCode: 1, cancelled: false, truncated: false }, + }; + } + + // Use ctx.ui.custom() to get TUI access, then run the command + const exitCode = await ctx.ui.custom((tui, _theme, _kb, done) => { + // Stop TUI to release terminal + tui.stop(); + + // Clear screen + process.stdout.write("\x1b[2J\x1b[H"); + + // Run command with full terminal access + const shell = process.env.SHELL || "/bin/sh"; + const result = spawnSync(shell, ["-c", command], { + stdio: "inherit", + env: process.env, + }); + + // Restart TUI + tui.start(); + tui.requestRender(true); + + // Signal completion + done(result.status); + + // Return empty component (immediately disposed since done() was called) + return { render: () => [], invalidate: () => {} }; + }); + + // Return result to prevent default bash handling + const output = + exitCode === 0 + ? "(interactive command completed successfully)" + : `(interactive command exited with code ${exitCode})`; + + return { + result: { + output, + exitCode: exitCode ?? 1, + cancelled: false, + truncated: false, + }, + }; + }); +} diff --git a/examples/extensions/kimi-deferred-tools.ts b/examples/extensions/kimi-deferred-tools.ts new file mode 100644 index 0000000..603dc57 --- /dev/null +++ b/examples/extensions/kimi-deferred-tools.ts @@ -0,0 +1,61 @@ +/** + * Minimal Kimi deferred-tool loading demo. + * + * pi -e ./kimi-deferred-tools.ts + * example prompt: Use the available tools to calculate 100 + 500. Do not calculate it yourself. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { Type } from "typebox"; + +function calculate(_expr: string): string { + return "42"; +} + +export default function (pi: ExtensionAPI): void { + pi.registerTool({ + name: "Calculator", + label: "Calculator", + description: "Evaluate a simple arithmetic expression.", + parameters: Type.Object({ + expr: Type.String({ description: "An expression such as 100 + 500" }), + }), + async execute(_toolCallId, params) { + return { + content: [{ type: "text", text: calculate(params.expr) }], + details: {}, + }; + }, + }); + + pi.registerTool({ + name: "tool_search", + label: "Tool Search", + description: "Find and activate tools for a capability.", + promptSnippet: "Search for additional tools when the active tools cannot perform the task", + parameters: Type.Object({ + query: Type.String({ description: "Capability to search for" }), + }), + async execute(_toolCallId, params) { + if (!params.query.toLowerCase().includes("calc")) { + return { + content: [{ type: "text", text: "The relevant tools do not exist." }], + details: { matches: [], added: [] }, + }; + } + + const active = pi.getActiveTools(); + const added = active.includes("Calculator") ? [] : ["Calculator"]; + if (added.length > 0) pi.setActiveTools([...active, ...added]); + + return { + content: [{ type: "text", text: "Success. Found 1 matching tool(s)" }], + details: { matches: ["Calculator"], added }, + }; + }, + }); + + pi.on("session_start", () => { + pi.setActiveTools(["tool_search"]); + }); +} diff --git a/examples/extensions/mac-system-theme.ts b/examples/extensions/mac-system-theme.ts new file mode 100644 index 0000000..c2095cf --- /dev/null +++ b/examples/extensions/mac-system-theme.ts @@ -0,0 +1,47 @@ +/** + * Syncs pi theme with macOS system appearance (dark/light mode). + * + * Usage: + * pi -e examples/extensions/mac-system-theme.ts + */ + +import { exec } from "node:child_process"; +import { promisify } from "node:util"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +const execAsync = promisify(exec); + +async function isDarkMode(): Promise { + try { + const { stdout } = await execAsync( + "osascript -e 'tell application \"System Events\" to tell appearance preferences to return dark mode'", + ); + return stdout.trim() === "true"; + } catch { + return false; + } +} + +export default function (pi: ExtensionAPI) { + let intervalId: ReturnType | null = null; + + pi.on("session_start", async (_event, ctx) => { + let currentTheme = (await isDarkMode()) ? "dark" : "light"; + ctx.ui.setTheme(currentTheme); + + intervalId = setInterval(async () => { + const newTheme = (await isDarkMode()) ? "dark" : "light"; + if (newTheme !== currentTheme) { + currentTheme = newTheme; + ctx.ui.setTheme(currentTheme); + } + }, 2000); + }); + + pi.on("session_shutdown", () => { + if (intervalId) { + clearInterval(intervalId); + intervalId = null; + } + }); +} diff --git a/examples/extensions/message-renderer.ts b/examples/extensions/message-renderer.ts new file mode 100644 index 0000000..953941e --- /dev/null +++ b/examples/extensions/message-renderer.ts @@ -0,0 +1,59 @@ +/** + * Custom message rendering example. + * + * Shows how to use registerMessageRenderer to control how custom messages + * appear in the TUI, with colors, formatting, and expandable details. + * + * Usage: /status [message] - sends a status message with custom rendering + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { Box, Text } from "@earendil-works/pi-tui"; + +export default function (pi: ExtensionAPI) { + // Register custom renderer for "status-update" messages + pi.registerMessageRenderer("status-update", (message, { expanded, outputPad }, theme) => { + const details = message.details as { level: string; timestamp: number } | undefined; + const level = details?.level ?? "info"; + + // Color based on level + const color = level === "error" ? "error" : level === "warn" ? "warning" : "success"; + const prefix = theme.fg(color, `[${level.toUpperCase()}]`); + + let text = `${prefix} ${message.content}`; + + // Show timestamp when expanded + if (expanded && details?.timestamp) { + const time = new Date(details.timestamp).toLocaleTimeString(); + text += `\n${theme.fg("dim", ` at ${time}`)}`; + } + + // Use Box with customMessageBg for consistent styling + const box = new Box(outputPad, 1, (t) => theme.bg("customMessageBg", t)); + box.addChild(new Text(text, 0, 0)); + return box; + }); + + // Command to send status messages + pi.registerCommand("status", { + description: "Send a status message (usage: /status [warn|error] message)", + handler: async (args, _ctx) => { + const parts = args.trim().split(/\s+/); + let level = "info"; + let content = args.trim(); + + // Check for level prefix + if (parts[0] === "warn" || parts[0] === "error") { + level = parts[0]; + content = parts.slice(1).join(" ") || "Status update"; + } + + pi.sendMessage({ + customType: "status-update", + content, + display: true, + details: { level, timestamp: Date.now() }, + }); + }, + }); +} diff --git a/examples/extensions/minimal-mode.ts b/examples/extensions/minimal-mode.ts new file mode 100644 index 0000000..6aef0c0 --- /dev/null +++ b/examples/extensions/minimal-mode.ts @@ -0,0 +1,426 @@ +/** + * Minimal Mode Example - Demonstrates a "minimal" tool display mode + * + * This extension overrides built-in tools to provide custom rendering: + * - Collapsed mode: Only shows the tool call (command/path), no output + * - Expanded mode: Shows full output like the built-in renderers + * + * This demonstrates how a "minimal mode" could work, where ctrl+o cycles through: + * - Standard: Shows truncated output (current default) + * - Expanded: Shows full output (current expanded) + * - Minimal: Shows only tool call, no output (this extension's collapsed mode) + * + * Usage: + * pi -e ./minimal-mode.ts + * + * Then use ctrl+o to toggle between minimal (collapsed) and full (expanded) views. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { + createBashTool, + createEditTool, + createFindTool, + createGrepTool, + createLsTool, + createReadTool, + createWriteTool, +} from "@earendil-works/pi-coding-agent"; +import { Text } from "@earendil-works/pi-tui"; +import { homedir } from "os"; + +/** + * Shorten a path by replacing home directory with ~ + */ +function shortenPath(path: string): string { + const home = homedir(); + if (path.startsWith(home)) { + return `~${path.slice(home.length)}`; + } + return path; +} + +// Cache for built-in tools by cwd +const toolCache = new Map>(); + +function createBuiltInTools(cwd: string) { + return { + read: createReadTool(cwd), + bash: createBashTool(cwd), + edit: createEditTool(cwd), + write: createWriteTool(cwd), + find: createFindTool(cwd), + grep: createGrepTool(cwd), + ls: createLsTool(cwd), + }; +} + +function getBuiltInTools(cwd: string) { + let tools = toolCache.get(cwd); + if (!tools) { + tools = createBuiltInTools(cwd); + toolCache.set(cwd, tools); + } + return tools; +} + +export default function (pi: ExtensionAPI) { + // ========================================================================= + // Read Tool + // ========================================================================= + pi.registerTool({ + name: "read", + label: "read", + description: + "Read the contents of a file. Supports text files and images (jpg, png, gif, webp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files.", + parameters: getBuiltInTools(process.cwd()).read.parameters, + + async execute(toolCallId, params, signal, onUpdate, ctx) { + const tools = getBuiltInTools(ctx.cwd); + return tools.read.execute(toolCallId, params, signal, onUpdate); + }, + + renderCall(args, theme, _context) { + const path = shortenPath(args.path || ""); + let pathDisplay = path ? theme.fg("accent", path) : theme.fg("toolOutput", "..."); + + // Show line range if specified + if (args.offset !== undefined || args.limit !== undefined) { + const startLine = args.offset ?? 1; + const endLine = args.limit !== undefined ? startLine + args.limit - 1 : ""; + pathDisplay += theme.fg("warning", `:${startLine}${endLine ? `-${endLine}` : ""}`); + } + + return new Text(`${theme.fg("toolTitle", theme.bold("read"))} ${pathDisplay}`, 0, 0); + }, + + renderResult(result, { expanded }, theme, _context) { + // Minimal mode: show nothing in collapsed state + if (!expanded) { + return new Text("", 0, 0); + } + + // Expanded mode: show full output + const textContent = result.content.find((c) => c.type === "text"); + if (!textContent || textContent.type !== "text") { + return new Text("", 0, 0); + } + + const lines = textContent.text.split("\n"); + const output = lines.map((line) => theme.fg("toolOutput", line)).join("\n"); + return new Text(`\n${output}`, 0, 0); + }, + }); + + // ========================================================================= + // Bash Tool + // ========================================================================= + pi.registerTool({ + name: "bash", + label: "bash", + description: + "Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first).", + parameters: getBuiltInTools(process.cwd()).bash.parameters, + + async execute(toolCallId, params, signal, onUpdate, ctx) { + const tools = getBuiltInTools(ctx.cwd); + return tools.bash.execute(toolCallId, params, signal, onUpdate); + }, + + renderCall(args, theme, _context) { + const command = args.command || "..."; + const timeout = args.timeout as number | undefined; + const timeoutSuffix = timeout ? theme.fg("muted", ` (timeout ${timeout}s)`) : ""; + + return new Text(theme.fg("toolTitle", theme.bold(`$ ${command}`)) + timeoutSuffix, 0, 0); + }, + + renderResult(result, { expanded }, theme, _context) { + // Minimal mode: show nothing in collapsed state + if (!expanded) { + return new Text("", 0, 0); + } + + // Expanded mode: show full output + const textContent = result.content.find((c) => c.type === "text"); + if (!textContent || textContent.type !== "text") { + return new Text("", 0, 0); + } + + const output = textContent.text + .trim() + .split("\n") + .map((line) => theme.fg("toolOutput", line)) + .join("\n"); + + if (!output) { + return new Text("", 0, 0); + } + + return new Text(`\n${output}`, 0, 0); + }, + }); + + // ========================================================================= + // Write Tool + // ========================================================================= + pi.registerTool({ + name: "write", + label: "write", + description: + "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.", + parameters: getBuiltInTools(process.cwd()).write.parameters, + + async execute(toolCallId, params, signal, onUpdate, ctx) { + const tools = getBuiltInTools(ctx.cwd); + return tools.write.execute(toolCallId, params, signal, onUpdate); + }, + + renderCall(args, theme, _context) { + const path = shortenPath(args.path || ""); + const pathDisplay = path ? theme.fg("accent", path) : theme.fg("toolOutput", "..."); + const lineCount = args.content ? args.content.split("\n").length : 0; + const lineInfo = lineCount > 0 ? theme.fg("muted", ` (${lineCount} lines)`) : ""; + + return new Text(`${theme.fg("toolTitle", theme.bold("write"))} ${pathDisplay}${lineInfo}`, 0, 0); + }, + + renderResult(result, { expanded }, theme, _context) { + // Minimal mode: show nothing (file was written) + if (!expanded) { + return new Text("", 0, 0); + } + + // Expanded mode: show error if any + if (result.content.some((c) => c.type === "text" && c.text)) { + const textContent = result.content.find((c) => c.type === "text"); + if (textContent?.type === "text" && textContent.text) { + return new Text(`\n${theme.fg("error", textContent.text)}`, 0, 0); + } + } + + return new Text("", 0, 0); + }, + }); + + // ========================================================================= + // Edit Tool + // ========================================================================= + pi.registerTool({ + name: "edit", + label: "edit", + description: + "Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.", + parameters: getBuiltInTools(process.cwd()).edit.parameters, + + async execute(toolCallId, params, signal, onUpdate, ctx) { + const tools = getBuiltInTools(ctx.cwd); + return tools.edit.execute(toolCallId, params, signal, onUpdate); + }, + + renderCall(args, theme, _context) { + const path = shortenPath(args.path || ""); + const pathDisplay = path ? theme.fg("accent", path) : theme.fg("toolOutput", "..."); + + return new Text(`${theme.fg("toolTitle", theme.bold("edit"))} ${pathDisplay}`, 0, 0); + }, + + renderResult(result, { expanded }, theme, _context) { + // Minimal mode: show nothing in collapsed state + if (!expanded) { + return new Text("", 0, 0); + } + + // Expanded mode: show diff or error + const textContent = result.content.find((c) => c.type === "text"); + if (!textContent || textContent.type !== "text") { + return new Text("", 0, 0); + } + + // For errors, show the error message + const text = textContent.text; + if (text.includes("Error") || text.includes("error")) { + return new Text(`\n${theme.fg("error", text)}`, 0, 0); + } + + // Otherwise show the text (would be nice to show actual diff here) + return new Text(`\n${theme.fg("toolOutput", text)}`, 0, 0); + }, + }); + + // ========================================================================= + // Find Tool + // ========================================================================= + pi.registerTool({ + name: "find", + label: "find", + description: + "Find files by name pattern (glob). Searches recursively from the specified path. Output limited to 200 results.", + parameters: getBuiltInTools(process.cwd()).find.parameters, + + async execute(toolCallId, params, signal, onUpdate, ctx) { + const tools = getBuiltInTools(ctx.cwd); + return tools.find.execute(toolCallId, params, signal, onUpdate); + }, + + renderCall(args, theme, _context) { + const pattern = args.pattern || ""; + const path = shortenPath(args.path || "."); + const limit = args.limit; + + let text = `${theme.fg("toolTitle", theme.bold("find"))} ${theme.fg("accent", pattern)}`; + text += theme.fg("toolOutput", ` in ${path}`); + if (limit !== undefined) { + text += theme.fg("toolOutput", ` (limit ${limit})`); + } + + return new Text(text, 0, 0); + }, + + renderResult(result, { expanded }, theme, _context) { + if (!expanded) { + // Minimal: just show count + const textContent = result.content.find((c) => c.type === "text"); + if (textContent?.type === "text") { + const count = textContent.text.trim().split("\n").filter(Boolean).length; + if (count > 0) { + return new Text(theme.fg("muted", ` → ${count} files`), 0, 0); + } + } + return new Text("", 0, 0); + } + + // Expanded: show full results + const textContent = result.content.find((c) => c.type === "text"); + if (!textContent || textContent.type !== "text") { + return new Text("", 0, 0); + } + + const output = textContent.text + .trim() + .split("\n") + .map((line) => theme.fg("toolOutput", line)) + .join("\n"); + + return new Text(`\n${output}`, 0, 0); + }, + }); + + // ========================================================================= + // Grep Tool + // ========================================================================= + pi.registerTool({ + name: "grep", + label: "grep", + description: + "Search file contents by regex pattern. Uses ripgrep for fast searching. Output limited to 200 matches.", + parameters: getBuiltInTools(process.cwd()).grep.parameters, + + async execute(toolCallId, params, signal, onUpdate, ctx) { + const tools = getBuiltInTools(ctx.cwd); + return tools.grep.execute(toolCallId, params, signal, onUpdate); + }, + + renderCall(args, theme, _context) { + const pattern = args.pattern || ""; + const path = shortenPath(args.path || "."); + const glob = args.glob; + const limit = args.limit; + + let text = `${theme.fg("toolTitle", theme.bold("grep"))} ${theme.fg("accent", `/${pattern}/`)}`; + text += theme.fg("toolOutput", ` in ${path}`); + if (glob) { + text += theme.fg("toolOutput", ` (${glob})`); + } + if (limit !== undefined) { + text += theme.fg("toolOutput", ` limit ${limit}`); + } + + return new Text(text, 0, 0); + }, + + renderResult(result, { expanded }, theme, _context) { + if (!expanded) { + // Minimal: just show match count + const textContent = result.content.find((c) => c.type === "text"); + if (textContent?.type === "text") { + const count = textContent.text.trim().split("\n").filter(Boolean).length; + if (count > 0) { + return new Text(theme.fg("muted", ` → ${count} matches`), 0, 0); + } + } + return new Text("", 0, 0); + } + + // Expanded: show full results + const textContent = result.content.find((c) => c.type === "text"); + if (!textContent || textContent.type !== "text") { + return new Text("", 0, 0); + } + + const output = textContent.text + .trim() + .split("\n") + .map((line) => theme.fg("toolOutput", line)) + .join("\n"); + + return new Text(`\n${output}`, 0, 0); + }, + }); + + // ========================================================================= + // Ls Tool + // ========================================================================= + pi.registerTool({ + name: "ls", + label: "ls", + description: + "List directory contents with file sizes. Shows files and directories with their sizes. Output limited to 500 entries.", + parameters: getBuiltInTools(process.cwd()).ls.parameters, + + async execute(toolCallId, params, signal, onUpdate, ctx) { + const tools = getBuiltInTools(ctx.cwd); + return tools.ls.execute(toolCallId, params, signal, onUpdate); + }, + + renderCall(args, theme, _context) { + const path = shortenPath(args.path || "."); + const limit = args.limit; + + let text = `${theme.fg("toolTitle", theme.bold("ls"))} ${theme.fg("accent", path)}`; + if (limit !== undefined) { + text += theme.fg("toolOutput", ` (limit ${limit})`); + } + + return new Text(text, 0, 0); + }, + + renderResult(result, { expanded }, theme, _context) { + if (!expanded) { + // Minimal: just show entry count + const textContent = result.content.find((c) => c.type === "text"); + if (textContent?.type === "text") { + const count = textContent.text.trim().split("\n").filter(Boolean).length; + if (count > 0) { + return new Text(theme.fg("muted", ` → ${count} entries`), 0, 0); + } + } + return new Text("", 0, 0); + } + + // Expanded: show full listing + const textContent = result.content.find((c) => c.type === "text"); + if (!textContent || textContent.type !== "text") { + return new Text("", 0, 0); + } + + const output = textContent.text + .trim() + .split("\n") + .map((line) => theme.fg("toolOutput", line)) + .join("\n"); + + return new Text(`\n${output}`, 0, 0); + }, + }); +} diff --git a/examples/extensions/modal-editor.ts b/examples/extensions/modal-editor.ts new file mode 100644 index 0000000..01959dd --- /dev/null +++ b/examples/extensions/modal-editor.ts @@ -0,0 +1,85 @@ +/** + * Modal Editor - vim-like modal editing example + * + * Usage: pi --extension ./examples/extensions/modal-editor.ts + * + * - Escape: insert → normal mode (in normal mode, aborts agent) + * - i: normal → insert mode + * - hjkl: navigation in normal mode + * - ctrl+c, ctrl+d, etc. work in both modes + */ + +import { CustomEditor, type ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; + +// Normal mode key mappings: key -> escape sequence (or null for mode switch) +const NORMAL_KEYS: Record = { + h: "\x1b[D", // left + j: "\x1b[B", // down + k: "\x1b[A", // up + l: "\x1b[C", // right + "0": "\x01", // line start + $: "\x05", // line end + x: "\x1b[3~", // delete char + i: null, // insert mode + a: null, // append (insert + right) +}; + +class ModalEditor extends CustomEditor { + private mode: "normal" | "insert" = "insert"; + + handleInput(data: string): void { + // Escape toggles to normal mode, or passes through for app handling + if (matchesKey(data, "escape")) { + if (this.mode === "insert") { + this.mode = "normal"; + } else { + super.handleInput(data); // abort agent, etc. + } + return; + } + + // Insert mode: pass everything through + if (this.mode === "insert") { + super.handleInput(data); + return; + } + + // Normal mode: check mapped keys + if (data in NORMAL_KEYS) { + const seq = NORMAL_KEYS[data]; + if (data === "i") { + this.mode = "insert"; + } else if (data === "a") { + this.mode = "insert"; + super.handleInput("\x1b[C"); // move right first + } else if (seq) { + super.handleInput(seq); + } + return; + } + + // Pass control sequences (ctrl+c, etc.) to super, ignore printable chars + if (data.length === 1 && data.charCodeAt(0) >= 32) return; + super.handleInput(data); + } + + render(width: number): string[] { + const lines = super.render(width); + if (lines.length === 0) return lines; + + // Add mode indicator to bottom border + const label = this.mode === "normal" ? " NORMAL " : " INSERT "; + const last = lines.length - 1; + if (visibleWidth(lines[last]!) >= label.length) { + lines[last] = truncateToWidth(lines[last]!, width - label.length, "") + label; + } + return lines; + } +} + +export default function (pi: ExtensionAPI) { + pi.on("session_start", (_event, ctx) => { + ctx.ui.setEditorComponent((tui, theme, kb) => new ModalEditor(tui, theme, kb)); + }); +} diff --git a/examples/extensions/model-status.ts b/examples/extensions/model-status.ts new file mode 100644 index 0000000..7dfa18b --- /dev/null +++ b/examples/extensions/model-status.ts @@ -0,0 +1,31 @@ +/** + * Model status extension - shows model changes in the status bar. + * + * Demonstrates the `model_select` hook which fires when the model changes + * via /model command, Ctrl+P cycling, or session restore. + * + * Usage: pi -e ./model-status.ts + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.on("model_select", async (event, ctx) => { + const { model, previousModel, source } = event; + + // Format model identifiers + const next = `${model.provider}/${model.id}`; + const prev = previousModel ? `${previousModel.provider}/${previousModel.id}` : "none"; + + // Show notification on change + if (source !== "restore") { + ctx.ui.notify(`Model: ${next}`, "info"); + } + + // Update status bar with current model + ctx.ui.setStatus("model", `🤖 ${model.id}`); + + // Log change details (visible in debug output) + console.log(`[model_select] ${prev} → ${next} (${source})`); + }); +} diff --git a/examples/extensions/notify.ts b/examples/extensions/notify.ts new file mode 100644 index 0000000..f7b1f81 --- /dev/null +++ b/examples/extensions/notify.ts @@ -0,0 +1,55 @@ +/** + * Pi Notify Extension + * + * Sends a native terminal notification when Pi agent is done and waiting for input. + * Supports multiple terminal protocols: + * - OSC 777: Ghostty, iTerm2, WezTerm, rxvt-unicode + * - OSC 99: Kitty + * - Windows toast: Windows Terminal (WSL) + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +function windowsToastScript(title: string, body: string): string { + const type = "Windows.UI.Notifications"; + const mgr = `[${type}.ToastNotificationManager, ${type}, ContentType = WindowsRuntime]`; + const template = `[${type}.ToastTemplateType]::ToastText01`; + const toast = `[${type}.ToastNotification]::new($xml)`; + return [ + `${mgr} > $null`, + `$xml = [${type}.ToastNotificationManager]::GetTemplateContent(${template})`, + `$xml.GetElementsByTagName('text')[0].AppendChild($xml.CreateTextNode('${body}')) > $null`, + `[${type}.ToastNotificationManager]::CreateToastNotifier('${title}').Show(${toast})`, + ].join("; "); +} + +function notifyOSC777(title: string, body: string): void { + process.stdout.write(`\x1b]777;notify;${title};${body}\x07`); +} + +function notifyOSC99(title: string, body: string): void { + // Kitty OSC 99: i=notification id, d=0 means not done yet, p=body for second part + process.stdout.write(`\x1b]99;i=1:d=0;${title}\x1b\\`); + process.stdout.write(`\x1b]99;i=1:p=body;${body}\x1b\\`); +} + +function notifyWindows(title: string, body: string): void { + const { execFile } = require("child_process"); + execFile("powershell.exe", ["-NoProfile", "-Command", windowsToastScript(title, body)]); +} + +function notify(title: string, body: string): void { + if (process.env.WT_SESSION) { + notifyWindows(title, body); + } else if (process.env.KITTY_WINDOW_ID) { + notifyOSC99(title, body); + } else { + notifyOSC777(title, body); + } +} + +export default function (pi: ExtensionAPI) { + pi.on("agent_end", async () => { + notify("Pi", "Ready for input"); + }); +} diff --git a/examples/extensions/overlay-qa-tests.ts b/examples/extensions/overlay-qa-tests.ts new file mode 100644 index 0000000..fd4486d --- /dev/null +++ b/examples/extensions/overlay-qa-tests.ts @@ -0,0 +1,1450 @@ +/** + * Overlay QA Tests - comprehensive overlay positioning and edge case tests + * + * Usage: pi --extension ./examples/extensions/overlay-qa-tests.ts + * + * Commands: + * /overlay-animation - Real-time animation demo (~30 FPS, proves DOOM-like rendering works) + * /overlay-anchors - Cycle through all 9 anchor positions + * /overlay-margins - Test margin and offset options + * /overlay-stack - Test stacked overlays + * /overlay-overflow - Test width overflow with streaming process output + * /overlay-edge - Test overlay positioned at terminal edge + * /overlay-percent - Test percentage-based positioning + * /overlay-maxheight - Test maxHeight truncation + * /overlay-sidepanel - Responsive sidepanel (hides when terminal < 100 cols) + * /overlay-toggle - Toggle visibility demo (demonstrates OverlayHandle.setHidden) + * /overlay-passive - Non-capturing overlay demo (passive info panel alongside active overlay) + * /overlay-focus - Focus cycling, input routing, dismissal, and rendering order with overlays + * /overlay-streaming - Multiple input panels with simulated streaming (Tab to cycle focus) + */ + +import type { ExtensionAPI, ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent"; +import type { Component, OverlayAnchor, OverlayHandle, OverlayOptions, TUI } from "@earendil-works/pi-tui"; +import { Input, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; +import { spawn } from "child_process"; + +// Global handle for toggle demo (in real code, use a more elegant pattern) +let globalToggleHandle: OverlayHandle | null = null; + +export default function (pi: ExtensionAPI) { + // Animation demo - proves overlays can handle real-time updates (like pi-doom would need) + pi.registerCommand("overlay-animation", { + description: "Test real-time animation in overlay (~30 FPS)", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + await ctx.ui.custom((tui, theme, _kb, done) => new AnimationDemoComponent(tui, theme, done), { + overlay: true, + overlayOptions: { anchor: "center", width: 50, maxHeight: 20 }, + }); + }, + }); + + // Test all 9 anchor positions + pi.registerCommand("overlay-anchors", { + description: "Cycle through all anchor positions", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + const anchors: OverlayAnchor[] = [ + "top-left", + "top-center", + "top-right", + "left-center", + "center", + "right-center", + "bottom-left", + "bottom-center", + "bottom-right", + ]; + + let index = 0; + while (true) { + const result = await ctx.ui.custom<"next" | "confirm" | "cancel">( + (_tui, theme, _kb, done) => new AnchorTestComponent(theme, anchors[index]!, done), + { + overlay: true, + overlayOptions: { anchor: anchors[index], width: 40 }, + }, + ); + + if (result === "next") { + index = (index + 1) % anchors.length; + continue; + } + if (result === "confirm") { + ctx.ui.notify(`Selected: ${anchors[index]}`, "info"); + } + break; + } + }, + }); + + // Test margins and offsets + pi.registerCommand("overlay-margins", { + description: "Test margin and offset options", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + const configs: { name: string; options: OverlayOptions }[] = [ + { name: "No margin (top-left)", options: { anchor: "top-left", width: 35 } }, + { name: "Margin: 3 all sides", options: { anchor: "top-left", width: 35, margin: 3 } }, + { + name: "Margin: top=5, left=10", + options: { anchor: "top-left", width: 35, margin: { top: 5, left: 10 } }, + }, + { name: "Center + offset (10, -3)", options: { anchor: "center", width: 35, offsetX: 10, offsetY: -3 } }, + { name: "Bottom-right, margin: 2", options: { anchor: "bottom-right", width: 35, margin: 2 } }, + ]; + + let index = 0; + while (true) { + const result = await ctx.ui.custom<"next" | "close">( + (_tui, theme, _kb, done) => new MarginTestComponent(theme, configs[index]!, done), + { + overlay: true, + overlayOptions: configs[index]!.options, + }, + ); + + if (result === "next") { + index = (index + 1) % configs.length; + continue; + } + break; + } + }, + }); + + // Test stacked overlays + pi.registerCommand("overlay-stack", { + description: "Test stacked overlays", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + // Three large overlays that overlap in the center area + // Each offset slightly so you can see the stacking + + ctx.ui.notify("Showing overlay 1 (back)...", "info"); + const p1 = ctx.ui.custom( + (_tui, theme, _kb, done) => new StackOverlayComponent(theme, 1, "back (red border)", done), + { + overlay: true, + overlayOptions: { anchor: "center", width: 50, offsetX: -8, offsetY: -4, maxHeight: 15 }, + }, + ); + + await sleep(400); + + ctx.ui.notify("Showing overlay 2 (middle)...", "info"); + const p2 = ctx.ui.custom( + (_tui, theme, _kb, done) => new StackOverlayComponent(theme, 2, "middle (green border)", done), + { + overlay: true, + overlayOptions: { anchor: "center", width: 50, offsetX: 0, offsetY: 0, maxHeight: 15 }, + }, + ); + + await sleep(400); + + ctx.ui.notify("Showing overlay 3 (front)...", "info"); + const p3 = ctx.ui.custom( + (_tui, theme, _kb, done) => new StackOverlayComponent(theme, 3, "front (blue border)", done), + { + overlay: true, + overlayOptions: { anchor: "center", width: 50, offsetX: 8, offsetY: 4, maxHeight: 15 }, + }, + ); + + // Wait for all to close + const results = await Promise.all([p1, p2, p3]); + ctx.ui.notify(`Closed in order: ${results.join(", ")}`, "info"); + }, + }); + + // Test width overflow scenarios (original crash case) - streams real process output + pi.registerCommand("overlay-overflow", { + description: "Test width overflow with streaming process output", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + await ctx.ui.custom((tui, theme, _kb, done) => new StreamingOverflowComponent(tui, theme, done), { + overlay: true, + overlayOptions: { anchor: "center", width: 90, maxHeight: 20 }, + }); + }, + }); + + // Test overlay at terminal edge + pi.registerCommand("overlay-edge", { + description: "Test overlay positioned at terminal edge", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + await ctx.ui.custom((_tui, theme, _kb, done) => new EdgeTestComponent(theme, done), { + overlay: true, + overlayOptions: { anchor: "right-center", width: 40, margin: { right: 0 } }, + }); + }, + }); + + // Test percentage-based positioning + pi.registerCommand("overlay-percent", { + description: "Test percentage-based positioning", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + const configs = [ + { name: "rowPercent: 0 (top)", row: 0, col: 50 }, + { name: "rowPercent: 50 (middle)", row: 50, col: 50 }, + { name: "rowPercent: 100 (bottom)", row: 100, col: 50 }, + { name: "colPercent: 0 (left)", row: 50, col: 0 }, + { name: "colPercent: 100 (right)", row: 50, col: 100 }, + ]; + + let index = 0; + while (true) { + const config = configs[index]!; + const result = await ctx.ui.custom<"next" | "close">( + (_tui, theme, _kb, done) => new PercentTestComponent(theme, config, done), + { + overlay: true, + overlayOptions: { + width: 30, + row: `${config.row}%`, + col: `${config.col}%`, + }, + }, + ); + + if (result === "next") { + index = (index + 1) % configs.length; + continue; + } + break; + } + }, + }); + + // Test maxHeight + pi.registerCommand("overlay-maxheight", { + description: "Test maxHeight truncation", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + await ctx.ui.custom((_tui, theme, _kb, done) => new MaxHeightTestComponent(theme, done), { + overlay: true, + overlayOptions: { anchor: "center", width: 50, maxHeight: 10 }, + }); + }, + }); + + // Test responsive sidepanel - only shows when terminal is wide enough + pi.registerCommand("overlay-sidepanel", { + description: "Test responsive sidepanel (hides when terminal < 100 cols)", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + await ctx.ui.custom((tui, theme, _kb, done) => new SidepanelComponent(tui, theme, done), { + overlay: true, + overlayOptions: { + anchor: "right-center", + width: "25%", + minWidth: 30, + margin: { right: 1 }, + // Only show when terminal is wide enough + visible: (termWidth) => termWidth >= 100, + }, + }); + }, + }); + + // Test toggle overlay - demonstrates OverlayHandle.setHidden() via onHandle callback + pi.registerCommand("overlay-toggle", { + description: "Test overlay toggle (press 't' to toggle visibility)", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + await ctx.ui.custom((tui, theme, _kb, done) => new ToggleDemoComponent(tui, theme, done), { + overlay: true, + overlayOptions: { anchor: "center", width: 50 }, + // onHandle callback provides access to the OverlayHandle for visibility control + onHandle: (handle) => { + // Store handle globally so component can access it + // (In real code, you'd use a more elegant pattern like a store or event emitter) + globalToggleHandle = handle; + }, + }); + globalToggleHandle = null; + }, + }); + + // Non-capturing overlay demo - passive info panel that doesn't steal focus + pi.registerCommand("overlay-passive", { + description: "Test non-capturing overlay (passive info panel alongside active overlay)", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + ctx.ui.setEditorText(""); + await ctx.ui.custom((tui, theme, _kb, done) => new PassiveDemoController(tui, theme, done), { + overlay: true, + overlayOptions: { anchor: "center", width: 48 }, + }); + }, + }); + + // Focus cycling demo - demonstrates focus(), input routing, per-panel dismissal, and rendering order + pi.registerCommand("overlay-focus", { + description: "Test focus cycling, input routing, dismissal, and rendering order with overlays", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + ctx.ui.setEditorText(""); + await ctx.ui.custom((tui, theme, _kb, done) => new FocusDemoController(tui, theme, done), { + overlay: true, + overlayOptions: { anchor: "bottom-center", width: 55, margin: { bottom: 1 } }, + }); + }, + }); + + // Test multiple input panels with simulated streaming + pi.registerCommand("overlay-streaming", { + description: "Multiple input panels with simulated streaming (Tab to cycle focus)", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + ctx.ui.setEditorText(""); + await ctx.ui.custom((tui, theme, _kb, done) => new StreamingInputController(tui, theme, done), { + overlay: true, + overlayOptions: { anchor: "bottom-center", width: 60, margin: { bottom: 1 } }, + }); + }, + }); +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +// Base overlay component with common rendering +abstract class BaseOverlay { + protected theme: Theme; + + constructor(theme: Theme) { + this.theme = theme; + } + + protected box(lines: string[], width: number, title?: string): string[] { + const th = this.theme; + const innerW = Math.max(1, width - 2); + const result: string[] = []; + + const titleStr = title ? truncateToWidth(` ${title} `, innerW) : ""; + const titleW = visibleWidth(titleStr); + const topLine = "─".repeat(Math.floor((innerW - titleW) / 2)); + const topLine2 = "─".repeat(Math.max(0, innerW - titleW - topLine.length)); + result.push(th.fg("border", `╭${topLine}`) + th.fg("accent", titleStr) + th.fg("border", `${topLine2}╮`)); + + for (const line of lines) { + result.push(th.fg("border", "│") + truncateToWidth(line, innerW, "...", true) + th.fg("border", "│")); + } + + result.push(th.fg("border", `╰${"─".repeat(innerW)}╯`)); + return result; + } + + invalidate(): void {} + dispose(): void {} +} + +// Anchor position test +class AnchorTestComponent extends BaseOverlay { + private anchor: OverlayAnchor; + private done: (result: "next" | "confirm" | "cancel") => void; + + constructor(theme: Theme, anchor: OverlayAnchor, done: (result: "next" | "confirm" | "cancel") => void) { + super(theme); + this.anchor = anchor; + this.done = done; + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.done("cancel"); + } else if (matchesKey(data, "return")) { + this.done("confirm"); + } else if (matchesKey(data, "space") || matchesKey(data, "right")) { + this.done("next"); + } + } + + render(width: number): string[] { + const th = this.theme; + return this.box( + [ + "", + ` Current: ${th.fg("accent", this.anchor)}`, + "", + ` ${th.fg("dim", "Space/→ = next anchor")}`, + ` ${th.fg("dim", "Enter = confirm")}`, + ` ${th.fg("dim", "Esc = cancel")}`, + "", + ], + width, + "Anchor Test", + ); + } +} + +// Margin/offset test +class MarginTestComponent extends BaseOverlay { + private config: { name: string; options: OverlayOptions }; + private done: (result: "next" | "close") => void; + + constructor( + theme: Theme, + config: { name: string; options: OverlayOptions }, + done: (result: "next" | "close") => void, + ) { + super(theme); + this.config = config; + this.done = done; + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.done("close"); + } else if (matchesKey(data, "space") || matchesKey(data, "right")) { + this.done("next"); + } + } + + render(width: number): string[] { + const th = this.theme; + return this.box( + [ + "", + ` ${th.fg("accent", this.config.name)}`, + "", + ` ${th.fg("dim", "Space/→ = next config")}`, + ` ${th.fg("dim", "Esc = close")}`, + "", + ], + width, + "Margin Test", + ); + } +} + +// Stacked overlay test +class StackOverlayComponent extends BaseOverlay { + private num: number; + private position: string; + private done: (result: string) => void; + + constructor(theme: Theme, num: number, position: string, done: (result: string) => void) { + super(theme); + this.num = num; + this.position = position; + this.done = done; + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c") || matchesKey(data, "return")) { + this.done(`Overlay ${this.num}`); + } + } + + render(width: number): string[] { + const th = this.theme; + // Use different colors for each overlay to show stacking + const colors = ["error", "success", "accent"] as const; + const color = colors[(this.num - 1) % colors.length]!; + const innerW = Math.max(1, width - 2); + const border = (char: string) => th.fg(color, char); + const padLine = (s: string) => truncateToWidth(s, innerW, "...", true); + const lines: string[] = []; + + lines.push(border(`╭${"─".repeat(innerW)}╮`)); + lines.push(border("│") + padLine(` Overlay ${th.fg("accent", `#${this.num}`)}`) + border("│")); + lines.push(border("│") + padLine(` Layer: ${th.fg(color, this.position)}`) + border("│")); + lines.push(border("│") + padLine("") + border("│")); + // Add extra lines to make it taller + for (let i = 0; i < 5; i++) { + lines.push(border("│") + padLine(` ${"░".repeat(innerW - 2)} `) + border("│")); + } + lines.push(border("│") + padLine("") + border("│")); + lines.push(border("│") + padLine(th.fg("dim", " Press Enter/Esc to close")) + border("│")); + lines.push(border(`╰${"─".repeat(innerW)}╯`)); + + return lines; + } +} + +// Streaming overflow test - spawns real process with colored output (original crash scenario) +class StreamingOverflowComponent extends BaseOverlay { + private tui: TUI; + private lines: string[] = []; + private proc: ReturnType | null = null; + private scrollOffset = 0; + private maxVisibleLines = 15; + private finished = false; + private disposed = false; + private done: () => void; + + constructor(tui: TUI, theme: Theme, done: () => void) { + super(theme); + this.tui = tui; + this.done = done; + this.startProcess(); + } + + private startProcess(): void { + // Run a command that produces many lines with ANSI colors + // Using find with -ls produces file listings, or use ls --color + this.proc = spawn("bash", [ + "-c", + ` + echo "Starting streaming overflow test (30+ seconds)..." + echo "This simulates subagent output with colors, hyperlinks, and long paths" + echo "" + for i in $(seq 1 100); do + # Simulate long file paths with OSC 8 hyperlinks (clickable) - tests width overflow + DIR="/Users/nicobailon/Documents/development/pi-mono/packages/coding-agent/src/modes/interactive" + FILE="\${DIR}/components/very-long-component-name-that-exceeds-width-\${i}.ts" + echo -e "\\033]8;;file://\${FILE}\\007▶ read: \${FILE}\\033]8;;\\007" + + # Add some colored status messages with long text + if [ $((i % 5)) -eq 0 ]; then + echo -e " \\033[32m✓ Successfully processed \${i} files in /Users/nicobailon/Documents/development/pi-mono\\033[0m" + fi + if [ $((i % 7)) -eq 0 ]; then + echo -e " \\033[33m⚠ Warning: potential issue detected at line \${i} in very-long-component-name-that-exceeds-width.ts\\033[0m" + fi + if [ $((i % 11)) -eq 0 ]; then + echo -e " \\033[31m✗ Error: file not found /some/really/long/path/that/definitely/exceeds/the/overlay/width/limit/file-\${i}.ts\\033[0m" + fi + sleep 0.3 + done + echo "" + echo -e "\\033[32m✓ Complete - 100 files processed in 30 seconds\\033[0m" + echo "Press Esc to close" + `, + ]); + + this.proc.stdout?.on("data", (data: Buffer) => { + if (this.disposed) return; // Guard against callbacks after dispose + const text = data.toString(); + const newLines = text.split("\n"); + for (const line of newLines) { + if (line) this.lines.push(line); + } + // Auto-scroll to bottom + this.scrollOffset = Math.max(0, this.lines.length - this.maxVisibleLines); + this.tui.requestRender(); + }); + + this.proc.stderr?.on("data", (data: Buffer) => { + if (this.disposed) return; // Guard against callbacks after dispose + this.lines.push(this.theme.fg("error", data.toString().trim())); + this.tui.requestRender(); + }); + + this.proc.on("close", () => { + if (this.disposed) return; // Guard against callbacks after dispose + this.finished = true; + this.tui.requestRender(); + }); + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.proc?.kill(); + this.done(); + } else if (matchesKey(data, "up")) { + this.scrollOffset = Math.max(0, this.scrollOffset - 1); + this.tui.requestRender(); // Trigger re-render after scroll + } else if (matchesKey(data, "down")) { + this.scrollOffset = Math.min(Math.max(0, this.lines.length - this.maxVisibleLines), this.scrollOffset + 1); + this.tui.requestRender(); // Trigger re-render after scroll + } + } + + render(width: number): string[] { + const th = this.theme; + const innerW = Math.max(1, width - 2); + const padLine = (s: string) => truncateToWidth(s, innerW, "...", true); + const border = (c: string) => th.fg("border", c); + + const result: string[] = []; + const title = truncateToWidth(` Streaming Output (${this.lines.length} lines) `, innerW); + const titlePad = Math.max(0, innerW - visibleWidth(title)); + result.push(border("╭") + th.fg("accent", title) + border(`${"─".repeat(titlePad)}╮`)); + + // Scroll indicators + const canScrollUp = this.scrollOffset > 0; + const canScrollDown = this.scrollOffset < this.lines.length - this.maxVisibleLines; + const scrollInfo = `↑${this.scrollOffset} | ↓${Math.max(0, this.lines.length - this.maxVisibleLines - this.scrollOffset)}`; + + result.push( + border("│") + padLine(canScrollUp || canScrollDown ? th.fg("dim", ` ${scrollInfo}`) : "") + border("│"), + ); + + // Visible lines - truncate long lines to fit within border + const visibleLines = this.lines.slice(this.scrollOffset, this.scrollOffset + this.maxVisibleLines); + for (const line of visibleLines) { + result.push(border("│") + padLine(` ${line}`) + border("│")); + } + + // Pad to maxVisibleLines + for (let i = visibleLines.length; i < this.maxVisibleLines; i++) { + result.push(border("│") + padLine("") + border("│")); + } + + const status = this.finished ? th.fg("success", "✓ Done") : th.fg("warning", "● Running"); + result.push(border("│") + padLine(` ${status} ${th.fg("dim", "| ↑↓ scroll | Esc close")}`) + border("│")); + result.push(border(`╰${"─".repeat(innerW)}╯`)); + + return result; + } + + dispose(): void { + this.disposed = true; + this.proc?.kill(); + } +} + +// Edge position test +class EdgeTestComponent extends BaseOverlay { + private done: () => void; + + constructor(theme: Theme, done: () => void) { + super(theme); + this.done = done; + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.done(); + } + } + + render(width: number): string[] { + const th = this.theme; + return this.box( + [ + "", + " This overlay is at the", + " right edge of terminal.", + "", + ` ${th.fg("dim", "Verify right border")}`, + ` ${th.fg("dim", "aligns with edge.")}`, + "", + ` ${th.fg("dim", "Press Esc to close")}`, + "", + ], + width, + "Edge Test", + ); + } +} + +// Percentage positioning test +class PercentTestComponent extends BaseOverlay { + private config: { name: string; row: number; col: number }; + private done: (result: "next" | "close") => void; + + constructor( + theme: Theme, + config: { name: string; row: number; col: number }, + done: (result: "next" | "close") => void, + ) { + super(theme); + this.config = config; + this.done = done; + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.done("close"); + } else if (matchesKey(data, "space") || matchesKey(data, "right")) { + this.done("next"); + } + } + + render(width: number): string[] { + const th = this.theme; + return this.box( + [ + "", + ` ${th.fg("accent", this.config.name)}`, + "", + ` ${th.fg("dim", "Space/→ = next")}`, + ` ${th.fg("dim", "Esc = close")}`, + "", + ], + width, + "Percent Test", + ); + } +} + +// MaxHeight test - renders 20 lines, truncated to 10 by maxHeight +class MaxHeightTestComponent extends BaseOverlay { + private done: () => void; + + constructor(theme: Theme, done: () => void) { + super(theme); + this.done = done; + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.done(); + } + } + + render(width: number): string[] { + const th = this.theme; + // Intentionally render 21 lines - maxHeight: 10 will truncate to first 10 + // You should see header + lines 1-6, with bottom border cut off + const contentLines: string[] = [ + th.fg("warning", " ⚠ Rendering 21 lines, maxHeight: 10"), + th.fg("dim", " Lines 11-21 truncated (no bottom border)"), + "", + ]; + + for (let i = 1; i <= 14; i++) { + contentLines.push(` Line ${i} of 14`); + } + + contentLines.push("", th.fg("dim", " Press Esc to close")); + + return this.box(contentLines, width, "MaxHeight Test"); + } +} + +// Responsive sidepanel - demonstrates percentage width and visibility callback +class SidepanelComponent extends BaseOverlay { + private tui: TUI; + private items = ["Dashboard", "Messages", "Settings", "Help", "About"]; + private selectedIndex = 0; + private done: () => void; + + constructor(tui: TUI, theme: Theme, done: () => void) { + super(theme); + this.tui = tui; + this.done = done; + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.done(); + } else if (matchesKey(data, "up")) { + this.selectedIndex = Math.max(0, this.selectedIndex - 1); + this.tui.requestRender(); + } else if (matchesKey(data, "down")) { + this.selectedIndex = Math.min(this.items.length - 1, this.selectedIndex + 1); + this.tui.requestRender(); + } else if (matchesKey(data, "return")) { + // Could trigger an action here + this.tui.requestRender(); + } + } + + render(width: number): string[] { + const th = this.theme; + const innerW = Math.max(1, width - 2); + const padLine = (s: string) => truncateToWidth(s, innerW, "...", true); + const border = (c: string) => th.fg("border", c); + const lines: string[] = []; + + // Header + lines.push(border(`╭${"─".repeat(innerW)}╮`)); + lines.push(border("│") + padLine(th.fg("accent", " Responsive Sidepanel")) + border("│")); + lines.push(border("├") + border("─".repeat(innerW)) + border("┤")); + + // Menu items + for (let i = 0; i < this.items.length; i++) { + const item = this.items[i]!; + const isSelected = i === this.selectedIndex; + const prefix = isSelected ? th.fg("accent", "→ ") : " "; + const text = isSelected ? th.fg("accent", item) : item; + lines.push(border("│") + padLine(`${prefix}${text}`) + border("│")); + } + + // Footer with responsive behavior info + lines.push(border("├") + border("─".repeat(innerW)) + border("┤")); + lines.push(border("│") + padLine(th.fg("warning", " ⚠ Resize terminal < 100 cols")) + border("│")); + lines.push(border("│") + padLine(th.fg("warning", " to see panel auto-hide")) + border("│")); + lines.push(border("│") + padLine(th.fg("dim", " Uses visible: (w) => w >= 100")) + border("│")); + lines.push(border("│") + padLine(th.fg("dim", " ↑↓ navigate | Esc close")) + border("│")); + lines.push(border(`╰${"─".repeat(innerW)}╯`)); + + return lines; + } +} + +// Animation demo - proves overlays can handle real-time updates like pi-doom +class AnimationDemoComponent extends BaseOverlay { + private tui: TUI; + private frame = 0; + private interval: ReturnType | null = null; + private fps = 0; + private lastFpsUpdate = Date.now(); + private framesSinceLastFps = 0; + private done: () => void; + + constructor(tui: TUI, theme: Theme, done: () => void) { + super(theme); + this.tui = tui; + this.done = done; + this.startAnimation(); + } + + private startAnimation(): void { + // Run at ~30 FPS (same as DOOM target) + this.interval = setInterval(() => { + this.frame++; + this.framesSinceLastFps++; + + // Update FPS counter every second + const now = Date.now(); + if (now - this.lastFpsUpdate >= 1000) { + this.fps = this.framesSinceLastFps; + this.framesSinceLastFps = 0; + this.lastFpsUpdate = now; + } + + this.tui.requestRender(); + }, 1000 / 30); + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.dispose(); + this.done(); + } + } + + render(width: number): string[] { + const th = this.theme; + const innerW = Math.max(1, width - 2); + const padLine = (s: string) => truncateToWidth(s, innerW, "...", true); + const border = (c: string) => th.fg("border", c); + + const lines: string[] = []; + lines.push(border(`╭${"─".repeat(innerW)}╮`)); + lines.push(border("│") + padLine(th.fg("accent", " Animation Demo (~30 FPS)")) + border("│")); + lines.push(border("│") + padLine(``) + border("│")); + lines.push(border("│") + padLine(` Frame: ${th.fg("accent", String(this.frame))}`) + border("│")); + lines.push(border("│") + padLine(` FPS: ${th.fg("success", String(this.fps))}`) + border("│")); + lines.push(border("│") + padLine(``) + border("│")); + + // Animated content - bouncing bar + const barWidth = Math.max(12, innerW - 4); // Ensure enough space for bar + const pos = Math.max(0, Math.floor(((Math.sin(this.frame / 10) + 1) * (barWidth - 10)) / 2)); + const bar = " ".repeat(pos) + th.fg("accent", "██████████") + " ".repeat(Math.max(0, barWidth - 10 - pos)); + lines.push(border("│") + padLine(` ${bar}`) + border("│")); + + // Spinning character + const spinChars = ["◐", "◓", "◑", "◒"]; + const spin = spinChars[this.frame % spinChars.length]; + lines.push(border("│") + padLine(` Spinner: ${th.fg("warning", spin!)}`) + border("│")); + + // Color cycling + const hue = (this.frame * 3) % 360; + const rgb = hslToRgb(hue / 360, 0.8, 0.5); + const colorBlock = `\x1b[48;2;${rgb[0]};${rgb[1]};${rgb[2]}m${" ".repeat(10)}\x1b[0m`; + lines.push(border("│") + padLine(` Color: ${colorBlock}`) + border("│")); + + lines.push(border("│") + padLine(``) + border("│")); + lines.push(border("│") + padLine(th.fg("dim", " This proves overlays can handle")) + border("│")); + lines.push(border("│") + padLine(th.fg("dim", " real-time game-like rendering.")) + border("│")); + lines.push(border("│") + padLine(th.fg("dim", " (pi-doom uses same approach)")) + border("│")); + lines.push(border("│") + padLine(``) + border("│")); + lines.push(border("│") + padLine(th.fg("dim", " Press Esc to close")) + border("│")); + lines.push(border(`╰${"─".repeat(innerW)}╯`)); + + return lines; + } + + dispose(): void { + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + } +} + +// HSL to RGB helper for color cycling animation +function hslToRgb(h: number, s: number, l: number): [number, number, number] { + let r: number, g: number, b: number; + if (s === 0) { + r = g = b = l; + } else { + const hue2rgb = (p: number, q: number, t: number) => { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + }; + const q = l < 0.5 ? l * (1 + s) : l + s - l * s; + const p = 2 * l - q; + r = hue2rgb(p, q, h + 1 / 3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1 / 3); + } + return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; +} + +// Toggle demo - demonstrates OverlayHandle.setHidden() via onHandle callback +class ToggleDemoComponent extends BaseOverlay { + private tui: TUI; + private toggleCount = 0; + private isToggling = false; + private done: () => void; + + constructor(tui: TUI, theme: Theme, done: () => void) { + super(theme); + this.tui = tui; + this.done = done; + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.done(); + } else if (matchesKey(data, "t") && globalToggleHandle && !this.isToggling) { + // Demonstrate toggle by hiding for 1 second then showing again + // (In real usage, a global keybinding would control visibility) + this.isToggling = true; + this.toggleCount++; + globalToggleHandle.setHidden(true); + + // Auto-restore after 1 second to demonstrate the API + setTimeout(() => { + if (globalToggleHandle) { + globalToggleHandle.setHidden(false); + this.isToggling = false; + this.tui.requestRender(); + } + }, 1000); + } + } + + render(width: number): string[] { + const th = this.theme; + return this.box( + [ + "", + th.fg("accent", " Toggle Demo"), + "", + " This overlay demonstrates the", + " onHandle callback API.", + "", + ` Toggle count: ${th.fg("accent", String(this.toggleCount))}`, + "", + th.fg("dim", " Press 't' to hide for 1 second"), + th.fg("dim", " (demonstrates setHidden API)"), + "", + th.fg("dim", " In real usage, a global keybinding"), + th.fg("dim", " would toggle visibility externally."), + "", + th.fg("dim", " Press Esc to close"), + "", + ], + width, + "Toggle Demo", + ); + } +} + +// === Non-capturing passive overlay demo === + +class PassiveDemoController extends BaseOverlay { + focused = false; + private tui: TUI; + private typed = ""; + private timerComponent: TimerPanel; + private timerHandle: OverlayHandle | null = null; + private interval: ReturnType | null = null; + private inputCount = 0; + private lastInputDebug = ""; + private done: () => void; + + constructor(tui: TUI, theme: Theme, done: () => void) { + super(theme); + this.tui = tui; + this.done = done; + this.timerComponent = new TimerPanel(theme); + this.timerHandle = this.tui.showOverlay(this.timerComponent, { + nonCapturing: true, + anchor: "top-right", + width: 22, + margin: { top: 1, right: 2 }, + }); + this.interval = setInterval(() => { + this.timerComponent.tick(); + this.tui.requestRender(); + }, 1000); + } + + handleInput(data: string): void { + this.inputCount++; + this.lastInputDebug = `len=${data.length} c0=${data.charCodeAt(0)}`; + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.cleanup(); + this.done(); + } else if (matchesKey(data, "backspace")) { + this.typed = this.typed.slice(0, -1); + } else if (data.length === 1 && data.charCodeAt(0) >= 32) { + this.typed += data; + } + } + + render(width: number): string[] { + const th = this.theme; + const display = this.typed.length > 0 ? this.typed : th.fg("dim", "(type here)"); + return this.box( + [ + "", + ` ${th.fg("dim", `focused=${this.focused} inputs=${this.inputCount}`)}`, + ` ${th.fg("dim", `last: ${this.lastInputDebug || "none"}`)}`, + "", + ` > ${display}`, + "", + th.fg("dim", " Type to prove input goes here."), + th.fg("dim", " Press Esc to close both."), + "", + ], + width, + "Non-Capturing Demo", + ); + } + + private cleanup(): void { + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + this.timerHandle?.hide(); + this.timerHandle = null; + } + + override dispose(): void { + this.cleanup(); + } +} + +class TimerPanel extends BaseOverlay { + private seconds = 0; + + tick(): void { + this.seconds++; + } + + render(width: number): string[] { + const th = this.theme; + const mins = Math.floor(this.seconds / 60); + const secs = this.seconds % 60; + const time = `${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}`; + return this.box([` ${th.fg("accent", time)}`, th.fg("dim", " nonCapturing: true")], width, "Timer"); + } +} + +// === Focus cycling demo === + +type FocusPanelColor = "error" | "success" | "accent"; +type FocusPanelConfig = { label: string; color: FocusPanelColor; options: OverlayOptions }; +type FocusPanelEntry = { panel: FocusPanel; handle: OverlayHandle }; + +const FOCUS_PANEL_CONFIGS = [ + { label: "Alpha", color: "error", options: { row: 2, col: 4, width: 34 } }, + { label: "Beta", color: "success", options: { row: 5, col: 28, width: 34 } }, + { label: "Gamma", color: "accent", options: { row: 8, col: 52, width: 34 } }, +] satisfies FocusPanelConfig[]; + +class FocusDemoController extends BaseOverlay { + private readonly tui: TUI; + private entries: FocusPanelEntry[] = []; + private readonly done: () => void; + private closed = false; + + constructor(tui: TUI, theme: Theme, done: () => void) { + super(theme); + this.tui = tui; + this.done = done; + + for (const config of FOCUS_PANEL_CONFIGS) { + const panel = new FocusPanel({ theme, config, controller: this }); + const handle = this.tui.showOverlay(panel, { nonCapturing: true, ...config.options }); + this.entries.push({ panel, handle }); + } + + this.focusFirstOpenPanel(); + } + + focusNext(current: FocusPanel, direction: 1 | -1 = 1): void { + const openEntries = this.openEntries(); + const currentOpenPosition = openEntries.findIndex((entry) => entry.panel === current); + if (currentOpenPosition === -1) throw new Error(`Panel ${current.label} is not open`); + const nextOpenPosition = (currentOpenPosition + direction + openEntries.length) % openEntries.length; + this.focusEntryAt(openEntries, nextOpenPosition); + } + + dismiss(panel: FocusPanel): void { + const openEntries = this.openEntries(); + const currentOpenPosition = openEntries.findIndex((candidate) => candidate.panel === panel); + if (currentOpenPosition === -1) return; + const entry = openEntries[currentOpenPosition]; + if (!entry) throw new Error(`Invalid focus panel index ${currentOpenPosition}`); + const remainingEntries = openEntries.filter((candidate) => candidate.panel !== panel); + + entry.panel.closed = true; + entry.handle.hide(); + if (remainingEntries.length === 0) { + this.close(); + return; + } + + this.focusEntryAt(remainingEntries, currentOpenPosition % remainingEntries.length); + } + + close(): void { + if (this.closed) return; + this.closed = true; + this.hidePanels(); + this.done(); + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.close(); + } else if (matchesKey(data, "tab")) { + this.focusFirstOpenPanel(); + } + } + + render(width: number): string[] { + const th = this.theme; + const focused = this.entries.find((entry) => entry.handle.isFocused())?.panel.label ?? "Controller"; + return this.box( + [ + "", + ` Current focus: ${th.fg("accent", focused)}`, + "", + " Three overlapping panels above are", + ` ${th.fg("accent", "nonCapturing")} overlays controlled with`, + " raw OverlayHandle.focus()/hide().", + "", + " Type in the focused panel's input.", + " Focused panel renders on top.", + "", + th.fg("dim", " Tab/Shift+Tab = cycle panels"), + th.fg("dim", " Esc/Ctrl+D = dismiss panel"), + th.fg("dim", " Ctrl+C = close all"), + "", + ], + width, + "Focus + Input Demo", + ); + } + + override dispose(): void { + if (this.closed) return; + this.closed = true; + this.hidePanels(); + } + + private focusFirstOpenPanel(): void { + const firstOpen = this.openEntries()[0]; + if (firstOpen) { + firstOpen.handle.focus(); + this.tui.requestRender(); + } + } + + private focusEntryAt(entries: FocusPanelEntry[], index: number): void { + const entry = entries[index]; + if (!entry) throw new Error(`Invalid focus panel index ${index}`); + entry.handle.focus(); + this.tui.requestRender(); + } + + private hidePanels(): void { + for (const entry of this.entries) { + if (!entry.panel.closed) { + entry.panel.closed = true; + entry.handle.hide(); + } + } + this.entries = []; + } + + private openEntries(): FocusPanelEntry[] { + return this.entries.filter((entry) => !entry.panel.closed); + } +} + +class FocusPanel extends BaseOverlay { + focused = false; + closed = false; + readonly label: string; + private readonly color: FocusPanelColor; + private readonly controller: FocusDemoController; + private readonly input = new Input(); + private inputs: string[] = []; + + constructor({ + theme, + config, + controller, + }: { + theme: Theme; + config: FocusPanelConfig; + controller: FocusDemoController; + }) { + super(theme); + this.label = config.label; + this.color = config.color; + this.controller = controller; + } + + handleInput(data: string): void { + if (matchesKey(data, "tab")) { + this.controller.focusNext(this); + } else if (matchesKey(data, "shift+tab")) { + this.controller.focusNext(this, -1); + } else if (matchesKey(data, "escape") || matchesKey(data, "ctrl+d")) { + this.controller.dismiss(this); + } else if (matchesKey(data, "ctrl+c")) { + this.controller.close(); + } else if (matchesKey(data, "return")) { + this.inputs.push("Enter"); + } else if (matchesKey(data, "up")) { + this.inputs.push("↑"); + } else if (matchesKey(data, "down")) { + this.inputs.push("↓"); + } else if (matchesKey(data, "left")) { + this.input.handleInput(data); + this.inputs.push("←"); + } else if (matchesKey(data, "right")) { + this.input.handleInput(data); + this.inputs.push("→"); + } else if (matchesKey(data, "backspace")) { + this.input.handleInput(data); + this.inputs.push("Backspace"); + } else { + this.input.handleInput(data); + this.inputs.push(JSON.stringify(data)); + } + } + + render(width: number): string[] { + const th = this.theme; + const innerW = Math.max(1, width - 2); + const border = (c: string) => th.fg(this.focused ? this.color : "dim", c); + const padLine = (s: string) => truncateToWidth(s, innerW, "...", true); + const recent = this.inputs.length === 0 ? "(none)" : this.inputs.slice(-6).join(" "); + const lines: string[] = []; + + this.input.focused = this.focused; + const [inputLine = ""] = this.input.render(Math.max(1, innerW - 8)); + lines.push(border(`╭${"─".repeat(innerW)}╮`)); + lines.push( + border("│") + + padLine( + ` ${th.fg(this.color, this.label)} ${this.focused ? th.fg("success", "FOCUSED") : th.fg("dim", "visible")}`, + ) + + border("│"), + ); + lines.push(border("│") + padLine("") + border("│")); + lines.push(border("│") + padLine(` Input: ${inputLine}`) + border("│")); + lines.push(border("│") + padLine(` Keys: ${recent}`) + border("│")); + lines.push(border("│") + padLine(th.fg("dim", " Tab/Shift+Tab focus")) + border("│")); + lines.push(border("│") + padLine(th.fg("dim", " Esc/Ctrl+D dismiss")) + border("│")); + lines.push(border(`╰${"─".repeat(innerW)}╯`)); + + return lines; + } +} + +// === Streaming input panel test (/overlay-streaming) === + +class StreamingInputController extends BaseOverlay { + private tui: TUI; + private panels: StreamingInputPanel[] = []; + private handles: OverlayHandle[] = []; + private focusIndex = -1; // -1 = controller focused, 0-2 = panel focused + private streamLines: string[] = []; + private streamInterval: ReturnType | null = null; + private lineCount = 0; + private done: () => void; + + constructor(tui: TUI, theme: Theme, done: () => void) { + super(theme); + this.tui = tui; + this.done = done; + + // Create 3 input panels as non-capturing overlays + const colors = ["error", "success", "accent"] as const; + const labels = ["Panel A", "Panel B", "Panel C"]; + + for (let i = 0; i < 3; i++) { + const panel = new StreamingInputPanel( + theme, + labels[i]!, + colors[i]!, + () => this.cycleFocus(), + () => this.close(), + ); + const handle = this.tui.showOverlay(panel, { + nonCapturing: true, + row: 1 + i * 9, + col: 2, + width: 35, + }); + panel.handle = handle; + this.panels.push(panel); + this.handles.push(handle); + } + + // Start with controller focused (focusIndex = -1) + + // Start simulated streaming + this.streamInterval = setInterval(() => { + this.lineCount++; + const timestamp = new Date().toLocaleTimeString(); + this.streamLines.push(`[${timestamp}] Streaming line ${this.lineCount}...`); + if (this.streamLines.length > 8) { + this.streamLines.shift(); + } + this.tui.requestRender(); + }, 500); + } + + private cycleFocus(): void { + // Unfocus current panel if any + if (this.focusIndex >= 0 && this.focusIndex < this.handles.length) { + this.handles[this.focusIndex]!.unfocus(); + } + + // Cycle: -1 (controller) → 0 → 1 → 2 → -1 ... + this.focusIndex++; + if (this.focusIndex >= this.handles.length) { + this.focusIndex = -1; // Back to controller + } + + // Focus new panel if any + if (this.focusIndex >= 0) { + this.handles[this.focusIndex]!.focus(); + } + + this.tui.requestRender(); + } + + private close(): void { + if (this.streamInterval) { + clearInterval(this.streamInterval); + this.streamInterval = null; + } + for (const handle of this.handles) handle.hide(); + this.handles = []; + this.panels = []; + this.done(); + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.close(); + } else if (matchesKey(data, "tab")) { + this.cycleFocus(); + } + } + + render(width: number): string[] { + const th = this.theme; + const focusedLabel = + this.focusIndex === -1 + ? th.fg("success", "Controller (this panel)") + : (this.panels[this.focusIndex]?.label ?? "?"); + + const lines = [ + "", + ` Current focus: ${th.fg("accent", focusedLabel)}`, + "", + " Simulated streaming output:", + th.fg("dim", " ─".repeat((width - 2) / 2)), + ]; + + for (const line of this.streamLines) { + lines.push(` ${th.fg("dim", line)}`); + } + + while (lines.length < 12) { + lines.push(""); + } + + lines.push(th.fg("dim", " ─".repeat((width - 2) / 2))); + lines.push(""); + lines.push(` Three ${th.fg("accent", "nonCapturing")} input panels on the left.`); + lines.push(" Tab cycles: Controller → Panel A → B → C → Controller"); + lines.push(" Type in each panel to test input routing."); + lines.push(""); + lines.push(th.fg("dim", " Tab = cycle focus | Esc = close all")); + lines.push(""); + + return this.box(lines, width, "Streaming + Input Test"); + } + + override dispose(): void { + this.close(); + } +} + +class StreamingInputPanel implements Component { + handle: OverlayHandle | null = null; + private theme: Theme; + private typed = ""; + readonly label: string; + private color: "error" | "success" | "accent"; + private onTab: () => void; + private onClose: () => void; + + constructor( + theme: Theme, + label: string, + color: "error" | "success" | "accent", + onTab: () => void, + onClose: () => void, + ) { + this.theme = theme; + this.label = label; + this.color = color; + this.onTab = onTab; + this.onClose = onClose; + } + + handleInput(data: string): void { + if (matchesKey(data, "tab")) { + this.onTab(); + } else if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.onClose(); + } else if (matchesKey(data, "backspace")) { + this.typed = this.typed.slice(0, -1); + } else if (data.length === 1 && data.charCodeAt(0) >= 32) { + this.typed += data; + } + } + + render(width: number): string[] { + const th = this.theme; + const focused = this.handle?.isFocused() ?? false; + const innerW = Math.max(1, width - 2); + const border = (c: string) => th.fg(this.color, c); + const padLine = (s: string) => { + const w = visibleWidth(s); + return s + " ".repeat(Math.max(0, innerW - w)); + }; + + const inputDisplay = this.typed.length > 0 ? this.typed : th.fg("dim", "(type here)"); + const truncatedInput = truncateToWidth(` > ${inputDisplay}`, innerW, "...", true); + + const lines: string[] = []; + lines.push(border(`╭${"─".repeat(innerW)}╮`)); + lines.push(border("│") + padLine(` ${th.fg("accent", this.label)}`) + border("│")); + lines.push(border("│") + padLine("") + border("│")); + if (focused) { + lines.push(border("│") + padLine(th.fg("success", " ● FOCUSED")) + border("│")); + lines.push(border("│") + padLine(th.fg("dim", " (receiving input)")) + border("│")); + } else { + lines.push(border("│") + padLine(th.fg("dim", " ○ unfocused")) + border("│")); + lines.push(border("│") + padLine("") + border("│")); + } + lines.push(border("│") + padLine(truncatedInput) + border("│")); + lines.push(border("│") + padLine("") + border("│")); + lines.push(border("│") + padLine(th.fg("dim", " Tab | Esc")) + border("│")); + lines.push(border(`╰${"─".repeat(innerW)}╯`)); + + return lines; + } + + invalidate(): void {} +} diff --git a/examples/extensions/overlay-test.ts b/examples/extensions/overlay-test.ts new file mode 100644 index 0000000..c51cde1 --- /dev/null +++ b/examples/extensions/overlay-test.ts @@ -0,0 +1,153 @@ +/** + * Overlay Test - validates overlay compositing with inline text inputs + * + * Usage: pi --extension ./examples/extensions/overlay-test.ts + * + * Run /overlay-test to show a floating overlay with: + * - Inline text inputs within menu items + * - Edge case tests (wide chars, styled text, emoji) + */ + +import type { ExtensionAPI, ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent"; +import { CURSOR_MARKER, type Focusable, matchesKey, visibleWidth } from "@earendil-works/pi-tui"; + +export default function (pi: ExtensionAPI) { + pi.registerCommand("overlay-test", { + description: "Test overlay rendering with edge cases", + handler: async (_args: string, ctx: ExtensionCommandContext) => { + const result = await ctx.ui.custom<{ action: string; query?: string } | undefined>( + (_tui, theme, _keybindings, done) => new OverlayTestComponent(theme, done), + { overlay: true }, + ); + + if (result) { + const msg = result.query ? `${result.action}: "${result.query}"` : result.action; + ctx.ui.notify(msg, "info"); + } + }, + }); +} + +class OverlayTestComponent implements Focusable { + readonly width = 70; + + /** Focusable interface - set by TUI when focus changes */ + focused = false; + + private selected = 0; + private items = [ + { label: "Search", hasInput: true, text: "", cursor: 0 }, + { label: "Run", hasInput: true, text: "", cursor: 0 }, + { label: "Settings", hasInput: false, text: "", cursor: 0 }, + { label: "Cancel", hasInput: false, text: "", cursor: 0 }, + ]; + + private theme: Theme; + private done: (result: { action: string; query?: string } | undefined) => void; + + constructor(theme: Theme, done: (result: { action: string; query?: string } | undefined) => void) { + this.theme = theme; + this.done = done; + } + + handleInput(data: string): void { + if (matchesKey(data, "escape")) { + this.done(undefined); + return; + } + + const current = this.items[this.selected]!; + + if (matchesKey(data, "return")) { + this.done({ action: current.label, query: current.hasInput ? current.text : undefined }); + return; + } + + if (matchesKey(data, "up")) { + this.selected = Math.max(0, this.selected - 1); + } else if (matchesKey(data, "down")) { + this.selected = Math.min(this.items.length - 1, this.selected + 1); + } else if (current.hasInput) { + if (matchesKey(data, "backspace")) { + if (current.cursor > 0) { + current.text = current.text.slice(0, current.cursor - 1) + current.text.slice(current.cursor); + current.cursor--; + } + } else if (matchesKey(data, "left")) { + current.cursor = Math.max(0, current.cursor - 1); + } else if (matchesKey(data, "right")) { + current.cursor = Math.min(current.text.length, current.cursor + 1); + } else if (data.length === 1 && data.charCodeAt(0) >= 32) { + current.text = current.text.slice(0, current.cursor) + data + current.text.slice(current.cursor); + current.cursor++; + } + } + } + + render(_width: number): string[] { + const w = this.width; + const th = this.theme; + const innerW = w - 2; + const lines: string[] = []; + + const pad = (s: string, len: number) => { + const vis = visibleWidth(s); + return s + " ".repeat(Math.max(0, len - vis)); + }; + + const row = (content: string) => th.fg("border", "│") + pad(content, innerW) + th.fg("border", "│"); + + lines.push(th.fg("border", `╭${"─".repeat(innerW)}╮`)); + lines.push(row(` ${th.fg("accent", "🧪 Overlay Test")}`)); + lines.push(row("")); + + // Edge cases - full width lines to test compositing at boundaries + lines.push(row(` ${th.fg("dim", "─── Edge Cases (borders should align) ───")}`)); + lines.push(row(` Wide: ${th.fg("warning", "中文日本語한글テスト漢字繁體简体ひらがなカタカナ가나다라마바")}`)); + lines.push( + row( + ` Styled: ${th.fg("error", "RED")} ${th.fg("success", "GREEN")} ${th.fg("warning", "YELLOW")} ${th.fg("accent", "ACCENT")} ${th.fg("dim", "DIM")} ${th.fg("error", "more")} ${th.fg("success", "colors")}`, + ), + ); + lines.push(row(" Emoji: 👨‍👩‍👧‍👦 🇯🇵 🚀 💻 🎉 🔥 😀 🎯 🌟 💡 🎨 🔧 📦 🏆 🌈 🎪 🎭 🎬 🎮 🎲")); + lines.push(row("")); + + // Menu with inline inputs + lines.push(row(` ${th.fg("dim", "─── Actions ───")}`)); + + for (let i = 0; i < this.items.length; i++) { + const item = this.items[i]!; + const isSelected = i === this.selected; + const prefix = isSelected ? " ▶ " : " "; + + let content: string; + if (item.hasInput) { + const label = isSelected ? th.fg("accent", `${item.label}:`) : th.fg("text", `${item.label}:`); + + let inputDisplay = item.text; + if (isSelected) { + const before = inputDisplay.slice(0, item.cursor); + const cursorChar = item.cursor < inputDisplay.length ? inputDisplay[item.cursor] : " "; + const after = inputDisplay.slice(item.cursor + 1); + // Emit hardware cursor marker for IME support when focused + const marker = this.focused ? CURSOR_MARKER : ""; + inputDisplay = `${before}${marker}\x1b[7m${cursorChar}\x1b[27m${after}`; + } + content = `${prefix + label} ${inputDisplay}`; + } else { + content = prefix + (isSelected ? th.fg("accent", item.label) : th.fg("text", item.label)); + } + + lines.push(row(content)); + } + + lines.push(row("")); + lines.push(row(` ${th.fg("dim", "↑↓ navigate • type to input • Enter select • Esc cancel")}`)); + lines.push(th.fg("border", `╰${"─".repeat(innerW)}╯`)); + + return lines; + } + + invalidate(): void {} + dispose(): void {} +} diff --git a/examples/extensions/permission-gate.ts b/examples/extensions/permission-gate.ts new file mode 100644 index 0000000..ce29f7e --- /dev/null +++ b/examples/extensions/permission-gate.ts @@ -0,0 +1,34 @@ +/** + * Permission Gate Extension + * + * Prompts for confirmation before running potentially dangerous bash commands. + * Patterns checked: rm -rf, sudo, chmod/chown 777 + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + const dangerousPatterns = [/\brm\s+(-rf?|--recursive)/i, /\bsudo\b/i, /\b(chmod|chown)\b.*777/i]; + + pi.on("tool_call", async (event, ctx) => { + if (event.toolName !== "bash") return undefined; + + const command = event.input.command as string; + const isDangerous = dangerousPatterns.some((p) => p.test(command)); + + if (isDangerous) { + if (!ctx.hasUI) { + // In non-interactive mode, block by default + return { block: true, reason: "Dangerous command blocked (no UI for confirmation)" }; + } + + const choice = await ctx.ui.select(`⚠️ Dangerous command:\n\n ${command}\n\nAllow?`, ["Yes", "No"]); + + if (choice !== "Yes") { + return { block: true, reason: "Blocked by user" }; + } + } + + return undefined; + }); +} diff --git a/examples/extensions/pirate.ts b/examples/extensions/pirate.ts new file mode 100644 index 0000000..abde601 --- /dev/null +++ b/examples/extensions/pirate.ts @@ -0,0 +1,47 @@ +/** + * Pirate Extension + * + * Demonstrates modifying the system prompt in before_agent_start to dynamically + * change agent behavior based on extension state. + * + * Usage: + * 1. Copy this file to ~/.pi/agent/extensions/ or your project's .pi/extensions/ + * 2. Use /pirate to toggle pirate mode + * 3. When enabled, the agent will respond like a pirate + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function pirateExtension(pi: ExtensionAPI) { + let pirateMode = false; + + // Register /pirate command to toggle pirate mode + pi.registerCommand("pirate", { + description: "Toggle pirate mode (agent speaks like a pirate)", + handler: async (_args, ctx) => { + pirateMode = !pirateMode; + ctx.ui.notify(pirateMode ? "Arrr! Pirate mode enabled!" : "Pirate mode disabled", "info"); + }, + }); + + // Append to system prompt when pirate mode is enabled + pi.on("before_agent_start", async (event) => { + if (pirateMode) { + return { + systemPrompt: + event.systemPrompt + + ` + +IMPORTANT: You are now in PIRATE MODE. You must: +- Speak like a stereotypical pirate in all responses +- Use phrases like "Arrr!", "Ahoy!", "Shiver me timbers!", "Avast!", "Ye scurvy dog!" +- Replace "my" with "me", "you" with "ye", "your" with "yer" +- Refer to the user as "matey" or "landlubber" +- End sentences with nautical expressions +- Still complete the actual task correctly, just in pirate speak +`, + }; + } + return undefined; + }); +} diff --git a/examples/extensions/plan-mode/README.md b/examples/extensions/plan-mode/README.md new file mode 100644 index 0000000..2568a68 --- /dev/null +++ b/examples/extensions/plan-mode/README.md @@ -0,0 +1,66 @@ +# Plan Mode Extension + +Read-only exploration mode for safe code analysis. + +## Features + +- **Built-in write tools disabled**: Disables edit/write while preserving other active tools +- **Bash allowlist**: Only read-only bash commands are allowed +- **Plan extraction**: Extracts numbered steps from `Plan:` sections +- **Progress tracking**: Widget shows completion status during execution +- **[DONE:n] markers**: Explicit step completion tracking +- **Session persistence**: State survives session resume + +## Commands + +- `/plan` - Toggle plan mode +- `/todos` - Show current plan progress +- `Ctrl+Alt+P` - Toggle plan mode (shortcut) + +## Usage + +1. Enable plan mode with `/plan` or `--plan` flag +2. Ask the agent to analyze code and create a plan +3. The agent should output a numbered plan under a `Plan:` header: + +``` +Plan: +1. First step description +2. Second step description +3. Third step description +``` + +4. Choose "Execute the plan" when prompted +5. During execution, the agent marks steps complete with `[DONE:n]` tags +6. Progress widget shows completion status + +## How It Works + +### Plan Mode (Read-Only) +- Built-in edit/write tools disabled +- Other active tools remain available +- Bash commands filtered through allowlist +- Agent creates a plan without making changes + +### Execution Mode +- Full tool access restored +- Agent executes steps in order +- `[DONE:n]` markers track completion +- Widget shows progress + +### Command Allowlist + +Safe commands (allowed): +- File inspection: `cat`, `head`, `tail`, `less`, `more` +- Search: `grep`, `find`, `rg`, `fd` +- Directory: `ls`, `pwd`, `tree` +- Git read: `git status`, `git log`, `git diff`, `git branch` +- Package info: `npm list`, `npm outdated`, `yarn info` +- System info: `uname`, `whoami`, `date`, `uptime` + +Blocked commands: +- File modification: `rm`, `mv`, `cp`, `mkdir`, `touch` +- Git write: `git add`, `git commit`, `git push` +- Package install: `npm install`, `yarn add`, `pip install` +- System: `sudo`, `kill`, `reboot` +- Editors: `vim`, `nano`, `code` diff --git a/examples/extensions/plan-mode/index.ts b/examples/extensions/plan-mode/index.ts new file mode 100644 index 0000000..737ce56 --- /dev/null +++ b/examples/extensions/plan-mode/index.ts @@ -0,0 +1,390 @@ +/** + * Plan Mode Extension + * + * Read-only exploration mode for safe code analysis. + * When enabled, built-in write tools are disabled. + * + * Features: + * - /plan command or Ctrl+Alt+P to toggle + * - Bash restricted to allowlisted read-only commands + * - Extracts numbered plan steps from "Plan:" sections + * - [DONE:n] markers to complete steps during execution + * - Progress tracking widget during execution + */ + +import type { AgentMessage } from "@earendil-works/pi-agent-core"; +import type { AssistantMessage, TextContent } from "@earendil-works/pi-ai"; +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; +import { Key } from "@earendil-works/pi-tui"; +import { extractTodoItems, isSafeCommand, markCompletedSteps, type TodoItem } from "./utils.ts"; + +// Tools +const PLAN_MODE_TOOLS = ["read", "bash", "grep", "find", "ls", "questionnaire"]; +const NORMAL_MODE_TOOLS = ["read", "bash", "edit", "write"]; +const PLAN_MODE_DISABLED_TOOLS = new Set(["edit", "write"]); +const PLAN_MANAGED_TOOLS = new Set([...PLAN_MODE_TOOLS, ...NORMAL_MODE_TOOLS]); + +interface PlanModeState { + enabled: boolean; + todos?: TodoItem[]; + executing?: boolean; + toolsBeforePlanMode?: string[]; +} + +// Type guard for assistant messages +function isAssistantMessage(m: AgentMessage): m is AssistantMessage { + return m.role === "assistant" && Array.isArray(m.content); +} + +// Extract text content from an assistant message +function getTextContent(message: AssistantMessage): string { + return message.content + .filter((block): block is TextContent => block.type === "text") + .map((block) => block.text) + .join("\n"); +} + +export default function planModeExtension(pi: ExtensionAPI): void { + let planModeEnabled = false; + let executionMode = false; + let todoItems: TodoItem[] = []; + let toolsBeforePlanMode: string[] | undefined; + + pi.registerFlag("plan", { + description: "Start in plan mode (read-only exploration)", + type: "boolean", + default: false, + }); + + function updateStatus(ctx: ExtensionContext): void { + // Footer status + if (executionMode && todoItems.length > 0) { + const completed = todoItems.filter((t) => t.completed).length; + ctx.ui.setStatus("plan-mode", ctx.ui.theme.fg("accent", `📋 ${completed}/${todoItems.length}`)); + } else if (planModeEnabled) { + ctx.ui.setStatus("plan-mode", ctx.ui.theme.fg("warning", "⏸ plan")); + } else { + ctx.ui.setStatus("plan-mode", undefined); + } + + // Widget showing todo list + if (executionMode && todoItems.length > 0) { + const lines = todoItems.map((item) => { + if (item.completed) { + return ( + ctx.ui.theme.fg("success", "☑ ") + ctx.ui.theme.fg("muted", ctx.ui.theme.strikethrough(item.text)) + ); + } + return `${ctx.ui.theme.fg("muted", "☐ ")}${item.text}`; + }); + ctx.ui.setWidget("plan-todos", lines); + } else { + ctx.ui.setWidget("plan-todos", undefined); + } + } + + function uniqueToolNames(toolNames: string[]): string[] { + return [...new Set(toolNames)]; + } + + function getPlanModeTools(activeToolNames: string[]): string[] { + return uniqueToolNames([ + ...activeToolNames.filter((name) => !PLAN_MODE_DISABLED_TOOLS.has(name)), + ...PLAN_MODE_TOOLS, + ]); + } + + function getNormalModeTools(activeToolNames: string[]): string[] { + return uniqueToolNames([ + ...NORMAL_MODE_TOOLS, + ...activeToolNames.filter((name) => !PLAN_MANAGED_TOOLS.has(name)), + ]); + } + + function enablePlanModeTools(): void { + if (toolsBeforePlanMode === undefined) { + toolsBeforePlanMode = pi.getActiveTools(); + } + pi.setActiveTools(getPlanModeTools(toolsBeforePlanMode)); + } + + function restoreNormalModeTools(): void { + pi.setActiveTools(toolsBeforePlanMode ?? getNormalModeTools(pi.getActiveTools())); + toolsBeforePlanMode = undefined; + } + + function persistState(): void { + pi.appendEntry("plan-mode", { + enabled: planModeEnabled, + todos: todoItems, + executing: executionMode, + toolsBeforePlanMode, + }); + } + + function togglePlanMode(ctx: ExtensionContext): void { + planModeEnabled = !planModeEnabled; + executionMode = false; + todoItems = []; + + if (planModeEnabled) { + enablePlanModeTools(); + ctx.ui.notify("Plan mode enabled. Built-in write tools disabled."); + } else { + restoreNormalModeTools(); + ctx.ui.notify("Plan mode disabled. Full access restored."); + } + updateStatus(ctx); + persistState(); + } + + pi.registerCommand("plan", { + description: "Toggle plan mode (read-only exploration)", + handler: async (_args, ctx) => togglePlanMode(ctx), + }); + + pi.registerCommand("todos", { + description: "Show current plan todo list", + handler: async (_args, ctx) => { + if (todoItems.length === 0) { + ctx.ui.notify("No todos. Create a plan first with /plan", "info"); + return; + } + const list = todoItems.map((item, i) => `${i + 1}. ${item.completed ? "✓" : "○"} ${item.text}`).join("\n"); + ctx.ui.notify(`Plan Progress:\n${list}`, "info"); + }, + }); + + pi.registerShortcut(Key.ctrlAlt("p"), { + description: "Toggle plan mode", + handler: async (ctx) => togglePlanMode(ctx), + }); + + // Block destructive bash commands in plan mode + pi.on("tool_call", async (event) => { + if (!planModeEnabled || event.toolName !== "bash") return; + + const command = event.input.command as string; + if (!isSafeCommand(command)) { + return { + block: true, + reason: `Plan mode: command blocked (not allowlisted). Use /plan to disable plan mode first.\nCommand: ${command}`, + }; + } + }); + + // Filter out stale plan mode context when not in plan mode + pi.on("context", async (event) => { + if (planModeEnabled) return; + + return { + messages: event.messages.filter((m) => { + const msg = m as AgentMessage & { customType?: string }; + if (msg.customType === "plan-mode-context") return false; + if (msg.role !== "user") return true; + + const content = msg.content; + if (typeof content === "string") { + return !content.includes("[PLAN MODE ACTIVE]"); + } + if (Array.isArray(content)) { + return !content.some( + (c) => c.type === "text" && (c as TextContent).text?.includes("[PLAN MODE ACTIVE]"), + ); + } + return true; + }), + }; + }); + + // Inject plan/execution context before agent starts + pi.on("before_agent_start", async () => { + if (planModeEnabled) { + return { + message: { + customType: "plan-mode-context", + content: `[PLAN MODE ACTIVE] +You are in plan mode - a read-only exploration mode for safe code analysis. + +Restrictions: +- Built-in edit and write tools are disabled +- Other currently active tools remain available +- Bash is restricted to an allowlist of read-only commands + +Ask clarifying questions using the questionnaire tool. +Use brave-search skill via bash for web research. + +Create a detailed numbered plan under a "Plan:" header: + +Plan: +1. First step description +2. Second step description +... + +Do NOT attempt to make changes - just describe what you would do.`, + display: false, + }, + }; + } + + if (executionMode && todoItems.length > 0) { + const remaining = todoItems.filter((t) => !t.completed); + const todoList = remaining.map((t) => `${t.step}. ${t.text}`).join("\n"); + return { + message: { + customType: "plan-execution-context", + content: `[EXECUTING PLAN - Full tool access enabled] + +Remaining steps: +${todoList} + +Execute each step in order. +After completing a step, include a [DONE:n] tag in your response.`, + display: false, + }, + }; + } + }); + + // Track progress after each turn + pi.on("turn_end", async (event, ctx) => { + if (!executionMode || todoItems.length === 0) return; + if (!isAssistantMessage(event.message)) return; + + const text = getTextContent(event.message); + if (markCompletedSteps(text, todoItems) > 0) { + updateStatus(ctx); + } + persistState(); + }); + + // Handle plan completion and plan mode UI + pi.on("agent_end", async (event, ctx) => { + // Check if execution is complete + if (executionMode && todoItems.length > 0) { + if (todoItems.every((t) => t.completed)) { + const completedList = todoItems.map((t) => `~~${t.text}~~`).join("\n"); + pi.sendMessage( + { customType: "plan-complete", content: `**Plan Complete!** ✓\n\n${completedList}`, display: true }, + { triggerTurn: false }, + ); + executionMode = false; + todoItems = []; + updateStatus(ctx); + persistState(); // Save cleared state so resume doesn't restore old execution mode + } + return; + } + + if (!planModeEnabled || !ctx.hasUI) return; + + // Extract todos from last assistant message + const lastAssistant = [...event.messages].reverse().find(isAssistantMessage); + if (lastAssistant) { + const extracted = extractTodoItems(getTextContent(lastAssistant)); + if (extracted.length > 0) { + todoItems = extracted; + } + } + + if (todoItems.length === 0) return; + persistState(); + + // Show plan steps and prompt for next action + const todoListText = todoItems.map((t, i) => `${i + 1}. ☐ ${t.text}`).join("\n"); + const planTodoListMessage = { + customType: "plan-todo-list", + content: `**Plan Steps (${todoItems.length}):**\n\n${todoListText}`, + display: true, + }; + + const choice = await ctx.ui.select("Plan mode - what next?", [ + "Execute the plan (track progress)", + "Stay in plan mode", + "Refine the plan", + ]); + + if (choice?.startsWith("Execute")) { + const firstTodoItem = todoItems[0]; + if (!firstTodoItem) return; + + planModeEnabled = false; + executionMode = true; + restoreNormalModeTools(); + updateStatus(ctx); + persistState(); + + const remainingList = todoItems.map((t) => `${t.step}. ${t.text}`).join("\n"); + const execMessage = `Execute the plan. + +Remaining steps: +${remainingList} + +Start with: ${firstTodoItem.text} +After completing a step, include a [DONE:n] tag in your response.`; + pi.sendMessage(planTodoListMessage, { deliverAs: "followUp" }); + pi.sendMessage( + { customType: "plan-mode-execute", content: execMessage, display: true }, + { triggerTurn: true, deliverAs: "followUp" }, + ); + } else if (choice === "Refine the plan") { + const refinement = await ctx.ui.editor("Refine the plan:", ""); + if (refinement?.trim()) { + pi.sendMessage(planTodoListMessage, { deliverAs: "followUp" }); + pi.sendUserMessage(refinement.trim(), { deliverAs: "followUp" }); + } + } + }); + + // Restore state on session start/resume + pi.on("session_start", async (_event, ctx) => { + if (pi.getFlag("plan") === true) { + planModeEnabled = true; + } + + const entries = ctx.sessionManager.getEntries(); + + // Restore persisted state + const planModeEntry = entries + .filter((e: { type: string; customType?: string }) => e.type === "custom" && e.customType === "plan-mode") + .pop() as { data?: PlanModeState } | undefined; + + if (planModeEntry?.data) { + planModeEnabled = planModeEntry.data.enabled ?? planModeEnabled; + todoItems = planModeEntry.data.todos ?? todoItems; + executionMode = planModeEntry.data.executing ?? executionMode; + toolsBeforePlanMode = planModeEntry.data.toolsBeforePlanMode ?? toolsBeforePlanMode; + } + + // On resume: re-scan messages to rebuild completion state + // Only scan messages AFTER the last "plan-mode-execute" to avoid picking up [DONE:n] from previous plans + const isResume = planModeEntry !== undefined; + if (isResume && executionMode && todoItems.length > 0) { + // Find the index of the last plan-mode-execute entry (marks when current execution started) + let executeIndex = -1; + for (let i = entries.length - 1; i >= 0; i--) { + const entry = entries[i] as { type: string; customType?: string }; + if (entry.customType === "plan-mode-execute") { + executeIndex = i; + break; + } + } + + // Only scan messages after the execute marker + const messages: AssistantMessage[] = []; + for (let i = executeIndex + 1; i < entries.length; i++) { + const entry = entries[i]; + if (entry.type === "message" && "message" in entry && isAssistantMessage(entry.message as AgentMessage)) { + messages.push(entry.message as AssistantMessage); + } + } + const allText = messages.map(getTextContent).join("\n"); + markCompletedSteps(allText, todoItems); + } + + if (planModeEnabled) { + enablePlanModeTools(); + } + updateStatus(ctx); + }); +} diff --git a/examples/extensions/plan-mode/utils.ts b/examples/extensions/plan-mode/utils.ts new file mode 100644 index 0000000..62123f9 --- /dev/null +++ b/examples/extensions/plan-mode/utils.ts @@ -0,0 +1,168 @@ +/** + * Pure utility functions for plan mode. + * Extracted for testability. + */ + +// Destructive commands blocked in plan mode +const DESTRUCTIVE_PATTERNS = [ + /\brm\b/i, + /\brmdir\b/i, + /\bmv\b/i, + /\bcp\b/i, + /\bmkdir\b/i, + /\btouch\b/i, + /\bchmod\b/i, + /\bchown\b/i, + /\bchgrp\b/i, + /\bln\b/i, + /\btee\b/i, + /\btruncate\b/i, + /\bdd\b/i, + /\bshred\b/i, + /(^|[^<])>(?!>)/, + />>/, + /\bnpm\s+(install|uninstall|update|ci|link|publish)/i, + /\byarn\s+(add|remove|install|publish)/i, + /\bpnpm\s+(add|remove|install|publish)/i, + /\bpip\s+(install|uninstall)/i, + /\bapt(-get)?\s+(install|remove|purge|update|upgrade)/i, + /\bbrew\s+(install|uninstall|upgrade)/i, + /\bgit\s+(add|commit|push|pull|merge|rebase|reset|checkout|branch\s+-[dD]|stash|cherry-pick|revert|tag|init|clone)/i, + /\bsudo\b/i, + /\bsu\b/i, + /\bkill\b/i, + /\bpkill\b/i, + /\bkillall\b/i, + /\breboot\b/i, + /\bshutdown\b/i, + /\bsystemctl\s+(start|stop|restart|enable|disable)/i, + /\bservice\s+\S+\s+(start|stop|restart)/i, + /\b(vim?|nano|emacs|code|subl)\b/i, +]; + +// Safe read-only commands allowed in plan mode +const SAFE_PATTERNS = [ + /^\s*cat\b/, + /^\s*head\b/, + /^\s*tail\b/, + /^\s*less\b/, + /^\s*more\b/, + /^\s*grep\b/, + /^\s*find\b/, + /^\s*ls\b/, + /^\s*pwd\b/, + /^\s*echo\b/, + /^\s*printf\b/, + /^\s*wc\b/, + /^\s*sort\b/, + /^\s*uniq\b/, + /^\s*diff\b/, + /^\s*file\b/, + /^\s*stat\b/, + /^\s*du\b/, + /^\s*df\b/, + /^\s*tree\b/, + /^\s*which\b/, + /^\s*whereis\b/, + /^\s*type\b/, + /^\s*env\b/, + /^\s*printenv\b/, + /^\s*uname\b/, + /^\s*whoami\b/, + /^\s*id\b/, + /^\s*date\b/, + /^\s*cal\b/, + /^\s*uptime\b/, + /^\s*ps\b/, + /^\s*top\b/, + /^\s*htop\b/, + /^\s*free\b/, + /^\s*git\s+(status|log|diff|show|branch|remote|config\s+--get)/i, + /^\s*git\s+ls-/i, + /^\s*npm\s+(list|ls|view|info|search|outdated|audit)/i, + /^\s*yarn\s+(list|info|why|audit)/i, + /^\s*node\s+--version/i, + /^\s*python\s+--version/i, + /^\s*curl\s/i, + /^\s*wget\s+-O\s*-/i, + /^\s*jq\b/, + /^\s*sed\s+-n/i, + /^\s*awk\b/, + /^\s*rg\b/, + /^\s*fd\b/, + /^\s*bat\b/, + /^\s*eza\b/, +]; + +export function isSafeCommand(command: string): boolean { + const isDestructive = DESTRUCTIVE_PATTERNS.some((p) => p.test(command)); + const isSafe = SAFE_PATTERNS.some((p) => p.test(command)); + return !isDestructive && isSafe; +} + +export interface TodoItem { + step: number; + text: string; + completed: boolean; +} + +export function cleanStepText(text: string): string { + let cleaned = text + .replace(/\*{1,2}([^*]+)\*{1,2}/g, "$1") // Remove bold/italic + .replace(/`([^`]+)`/g, "$1") // Remove code + .replace( + /^(Use|Run|Execute|Create|Write|Read|Check|Verify|Update|Modify|Add|Remove|Delete|Install)\s+(the\s+)?/i, + "", + ) + .replace(/\s+/g, " ") + .trim(); + + if (cleaned.length > 0) { + cleaned = cleaned.charAt(0).toUpperCase() + cleaned.slice(1); + } + if (cleaned.length > 50) { + cleaned = `${cleaned.slice(0, 47)}...`; + } + return cleaned; +} + +export function extractTodoItems(message: string): TodoItem[] { + const items: TodoItem[] = []; + const headerMatch = message.match(/\*{0,2}Plan:\*{0,2}\s*\n/i); + if (!headerMatch) return items; + + const planSection = message.slice(message.indexOf(headerMatch[0]) + headerMatch[0].length); + const numberedPattern = /^\s*(\d+)[.)]\s+\*{0,2}([^*\n]+)/gm; + + for (const match of planSection.matchAll(numberedPattern)) { + const text = match[2] + .trim() + .replace(/\*{1,2}$/, "") + .trim(); + if (text.length > 5 && !text.startsWith("`") && !text.startsWith("/") && !text.startsWith("-")) { + const cleaned = cleanStepText(text); + if (cleaned.length > 3) { + items.push({ step: items.length + 1, text: cleaned, completed: false }); + } + } + } + return items; +} + +export function extractDoneSteps(message: string): number[] { + const steps: number[] = []; + for (const match of message.matchAll(/\[DONE:(\d+)\]/gi)) { + const step = Number(match[1]); + if (Number.isFinite(step)) steps.push(step); + } + return steps; +} + +export function markCompletedSteps(text: string, items: TodoItem[]): number { + const doneSteps = extractDoneSteps(text); + for (const step of doneSteps) { + const item = items.find((t) => t.step === step); + if (item) item.completed = true; + } + return doneSteps.length; +} diff --git a/examples/extensions/preset.ts b/examples/extensions/preset.ts new file mode 100644 index 0000000..39f5564 --- /dev/null +++ b/examples/extensions/preset.ts @@ -0,0 +1,436 @@ +/** + * Preset Extension + * + * Allows defining named presets that configure model, thinking level, tools, + * and system prompt instructions. Presets are defined in JSON config files + * and can be activated via CLI flag, /preset command, or Ctrl+Shift+U to cycle. + * + * Config files (merged, project takes precedence): + * - ~/.pi/agent/presets.json (global) + * - /.pi/presets.json (project-local) + * + * Example presets.json: + * ```json + * { + * "plan": { + * "provider": "openai-codex", + * "model": "gpt-5.2-codex", + * "thinkingLevel": "high", + * "tools": ["read", "grep", "find", "ls"], + * "instructions": "You are in PLANNING MODE. Your job is to deeply understand the problem and create a detailed implementation plan.\n\nRules:\n- DO NOT make any changes. You cannot edit or write files.\n- Read files IN FULL (no offset/limit) to get complete context. Partial reads miss critical details.\n- Explore thoroughly: grep for related code, find similar patterns, understand the architecture.\n- Ask clarifying questions if requirements are ambiguous. Do not assume.\n- Identify risks, edge cases, and dependencies before proposing solutions.\n\nOutput:\n- Create a structured plan with numbered steps.\n- For each step: what to change, why, and potential risks.\n- List files that will be modified.\n- Note any tests that should be added or updated.\n\nWhen done, ask the user if they want you to:\n1. Write the plan to a markdown file (e.g., PLAN.md)\n2. Create a GitHub issue with the plan\n3. Proceed to implementation (they should switch to 'implement' preset)" + * }, + * "implement": { + * "provider": "anthropic", + * "model": "claude-sonnet-4-5", + * "thinkingLevel": "high", + * "tools": ["read", "bash", "edit", "write"], + * "instructions": "You are in IMPLEMENTATION MODE. Your job is to make focused, correct changes.\n\nRules:\n- Keep scope tight. Do exactly what was asked, no more.\n- Read files before editing to understand current state.\n- Make surgical edits. Prefer edit over write for existing files.\n- Explain your reasoning briefly before each change.\n- Run tests or type checks after changes if the project has them (npm test, npm run check, etc.).\n- If you encounter unexpected complexity, STOP and explain the issue rather than hacking around it.\n\nIf no plan exists:\n- Ask clarifying questions before starting.\n- Propose what you'll do and get confirmation for non-trivial changes.\n\nAfter completing changes:\n- Summarize what was done.\n- Note any follow-up work or tests that should be added." + * } + * } + * ``` + * + * Usage: + * - `pi --preset plan` - start with plan preset + * - `/preset` - show selector to switch presets mid-session + * - `/preset implement` - switch to implement preset directly + * - `Ctrl+Shift+U` - cycle through presets + * + * CLI flags always override preset values. + */ + +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { Api, Model } from "@earendil-works/pi-ai"; +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; +import { CONFIG_DIR_NAME, DynamicBorder, getAgentDir } from "@earendil-works/pi-coding-agent"; +import { Container, Key, type SelectItem, SelectList, Text } from "@earendil-works/pi-tui"; + +// Preset configuration +interface Preset { + /** Provider name (e.g., "anthropic", "openai") */ + provider?: string; + /** Model ID (e.g., "claude-sonnet-4-5") */ + model?: string; + /** Thinking level */ + thinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"; + /** Tools to enable (replaces default set) */ + tools?: string[]; + /** Instructions to append to system prompt */ + instructions?: string; +} + +interface PresetsConfig { + [name: string]: Preset; +} + +/** + * Load presets from config files. + * Project-local presets override global presets with the same name. + */ +function loadPresets(cwd: string): PresetsConfig { + const globalPath = join(getAgentDir(), "presets.json"); + const projectPath = join(cwd, CONFIG_DIR_NAME, "presets.json"); + + let globalPresets: PresetsConfig = {}; + let projectPresets: PresetsConfig = {}; + + // Load global presets + if (existsSync(globalPath)) { + try { + const content = readFileSync(globalPath, "utf-8"); + globalPresets = JSON.parse(content); + } catch (err) { + console.error(`Failed to load global presets from ${globalPath}: ${err}`); + } + } + + // Load project presets + if (existsSync(projectPath)) { + try { + const content = readFileSync(projectPath, "utf-8"); + projectPresets = JSON.parse(content); + } catch (err) { + console.error(`Failed to load project presets from ${projectPath}: ${err}`); + } + } + + // Merge (project overrides global) + return { ...globalPresets, ...projectPresets }; +} + +interface OriginalState { + model: Model | undefined; + thinkingLevel: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"; + tools: string[]; +} + +export default function presetExtension(pi: ExtensionAPI) { + let presets: PresetsConfig = {}; + let activePresetName: string | undefined; + let activePreset: Preset | undefined; + let originalState: OriginalState | undefined; + + // Register --preset CLI flag + pi.registerFlag("preset", { + description: "Preset configuration to use", + type: "string", + }); + + /** + * Apply a preset configuration. + */ + async function applyPreset(name: string, preset: Preset, ctx: ExtensionContext): Promise { + // Snapshot state before the first preset is applied (i.e. only when transitioning from no-preset) + if (activePresetName === undefined) { + originalState = { + model: ctx.model, + thinkingLevel: pi.getThinkingLevel(), + tools: pi.getActiveTools(), + }; + } + + // Apply model if specified + if (preset.provider && preset.model) { + const model = ctx.modelRegistry.find(preset.provider, preset.model); + if (model) { + const success = await pi.setModel(model); + if (!success) { + ctx.ui.notify(`Preset "${name}": No API key for ${preset.provider}/${preset.model}`, "warning"); + } + } else { + ctx.ui.notify(`Preset "${name}": Model ${preset.provider}/${preset.model} not found`, "warning"); + } + } + + // Apply thinking level if specified + if (preset.thinkingLevel) { + pi.setThinkingLevel(preset.thinkingLevel); + } + + // Apply tools if specified + if (preset.tools && preset.tools.length > 0) { + const allToolNames = pi.getAllTools().map((t) => t.name); + const validTools = preset.tools.filter((t) => allToolNames.includes(t)); + const invalidTools = preset.tools.filter((t) => !allToolNames.includes(t)); + + if (invalidTools.length > 0) { + ctx.ui.notify(`Preset "${name}": Unknown tools: ${invalidTools.join(", ")}`, "warning"); + } + + if (validTools.length > 0) { + pi.setActiveTools(validTools); + } + } + + // Store active preset for system prompt injection + activePresetName = name; + activePreset = preset; + + return true; + } + + /** + * Build description string for a preset. + */ + function buildPresetDescription(preset: Preset): string { + const parts: string[] = []; + + if (preset.provider && preset.model) { + parts.push(`${preset.provider}/${preset.model}`); + } + if (preset.thinkingLevel) { + parts.push(`thinking:${preset.thinkingLevel}`); + } + if (preset.tools) { + parts.push(`tools:${preset.tools.join(",")}`); + } + if (preset.instructions) { + const truncated = + preset.instructions.length > 30 ? `${preset.instructions.slice(0, 27)}...` : preset.instructions; + parts.push(`"${truncated}"`); + } + + return parts.join(" | "); + } + + /** + * Show preset selector UI using custom SelectList component. + */ + async function showPresetSelector(ctx: ExtensionContext): Promise { + const presetNames = Object.keys(presets); + + if (presetNames.length === 0) { + ctx.ui.notify( + `No presets defined. Add presets to ${join(getAgentDir(), "presets.json")} or ${join(ctx.cwd, CONFIG_DIR_NAME, "presets.json")}`, + "warning", + ); + return; + } + + // Build select items with descriptions + const items: SelectItem[] = presetNames.map((name) => { + const preset = presets[name]; + const isActive = name === activePresetName; + return { + value: name, + label: isActive ? `${name} (active)` : name, + description: buildPresetDescription(preset), + }; + }); + + // Add "None" option to clear preset + items.push({ + value: "(none)", + label: "(none)", + description: "Clear active preset, restore defaults", + }); + + const result = await ctx.ui.custom((tui, theme, _kb, done) => { + const container = new Container(); + container.addChild(new DynamicBorder((str) => theme.fg("accent", str))); + + // Header + container.addChild(new Text(theme.fg("accent", theme.bold("Select Preset")))); + + // SelectList with themed styling + const selectList = new SelectList(items, Math.min(items.length, 10), { + selectedPrefix: (text) => theme.fg("accent", text), + selectedText: (text) => theme.fg("accent", text), + description: (text) => theme.fg("muted", text), + scrollInfo: (text) => theme.fg("dim", text), + noMatch: (text) => theme.fg("warning", text), + }); + + selectList.onSelect = (item) => done(item.value); + selectList.onCancel = () => done(null); + + container.addChild(selectList); + + // Footer hint + container.addChild(new Text(theme.fg("dim", "↑↓ navigate • enter select • esc cancel"))); + + container.addChild(new DynamicBorder((str) => theme.fg("accent", str))); + + return { + render(width: number) { + return container.render(width); + }, + invalidate() { + container.invalidate(); + }, + handleInput(data: string) { + selectList.handleInput(data); + tui.requestRender(); + }, + }; + }); + + if (!result) return; + + if (result === "(none)") { + // Clear preset and restore original state + activePresetName = undefined; + activePreset = undefined; + if (originalState) { + if (originalState.model) { + await pi.setModel(originalState.model); + } + pi.setThinkingLevel(originalState.thinkingLevel); + pi.setActiveTools(originalState.tools); + } else { + pi.setActiveTools(["read", "bash", "edit", "write"]); + } + ctx.ui.notify("Preset cleared, defaults restored", "info"); + updateStatus(ctx); + return; + } + + const preset = presets[result]; + if (preset) { + await applyPreset(result, preset, ctx); + ctx.ui.notify(`Preset "${result}" activated`, "info"); + updateStatus(ctx); + } + } + + /** + * Update status indicator. + */ + function updateStatus(ctx: ExtensionContext) { + if (activePresetName) { + ctx.ui.setStatus("preset", ctx.ui.theme.fg("accent", `preset:${activePresetName}`)); + } else { + ctx.ui.setStatus("preset", undefined); + } + } + + function getPresetOrder(): string[] { + return Object.keys(presets).sort(); + } + + async function cyclePreset(ctx: ExtensionContext): Promise { + const presetNames = getPresetOrder(); + if (presetNames.length === 0) { + ctx.ui.notify( + `No presets defined. Add presets to ${join(getAgentDir(), "presets.json")} or ${join(ctx.cwd, CONFIG_DIR_NAME, "presets.json")}`, + "warning", + ); + return; + } + + const cycleList = ["(none)", ...presetNames]; + const currentName = activePresetName ?? "(none)"; + const currentIndex = cycleList.indexOf(currentName); + const nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % cycleList.length; + const nextName = cycleList[nextIndex]; + + if (nextName === "(none)") { + activePresetName = undefined; + activePreset = undefined; + if (originalState) { + if (originalState.model) { + await pi.setModel(originalState.model); + } + pi.setThinkingLevel(originalState.thinkingLevel); + pi.setActiveTools(originalState.tools); + } else { + pi.setActiveTools(["read", "bash", "edit", "write"]); + } + ctx.ui.notify("Preset cleared, defaults restored", "info"); + updateStatus(ctx); + return; + } + + const preset = presets[nextName]; + if (!preset) return; + + await applyPreset(nextName, preset, ctx); + ctx.ui.notify(`Preset "${nextName}" activated`, "info"); + updateStatus(ctx); + } + + pi.registerShortcut(Key.ctrlShift("u"), { + description: "Cycle presets", + handler: async (ctx) => { + await cyclePreset(ctx); + }, + }); + + // Register /preset command + pi.registerCommand("preset", { + description: "Switch preset configuration", + handler: async (args, ctx) => { + // If preset name provided, apply directly + if (args?.trim()) { + const name = args.trim(); + const preset = presets[name]; + + if (!preset) { + const available = Object.keys(presets).join(", ") || "(none defined)"; + ctx.ui.notify(`Unknown preset "${name}". Available: ${available}`, "error"); + return; + } + + await applyPreset(name, preset, ctx); + ctx.ui.notify(`Preset "${name}" activated`, "info"); + updateStatus(ctx); + return; + } + + // Otherwise show selector + await showPresetSelector(ctx); + }, + }); + + // Inject preset instructions into system prompt + pi.on("before_agent_start", async (event) => { + if (activePreset?.instructions) { + return { + systemPrompt: `${event.systemPrompt}\n\n${activePreset.instructions}`, + }; + } + }); + + // Initialize on session start + pi.on("session_start", async (_event, ctx) => { + // Load presets from config files + presets = loadPresets(ctx.cwd); + + // Check for --preset flag + const presetFlag = pi.getFlag("preset"); + if (typeof presetFlag === "string" && presetFlag) { + const preset = presets[presetFlag]; + if (preset) { + await applyPreset(presetFlag, preset, ctx); + ctx.ui.notify(`Preset "${presetFlag}" activated`, "info"); + } else { + const available = Object.keys(presets).join(", ") || "(none defined)"; + ctx.ui.notify(`Unknown preset "${presetFlag}". Available: ${available}`, "warning"); + } + } + + // Restore preset from session state + const entries = ctx.sessionManager.getEntries(); + const presetEntry = entries + .filter((e: { type: string; customType?: string }) => e.type === "custom" && e.customType === "preset-state") + .pop() as { data?: { name: string } } | undefined; + + if (presetEntry?.data?.name && !presetFlag) { + const preset = presets[presetEntry.data.name]; + if (preset) { + activePresetName = presetEntry.data.name; + activePreset = preset; + // Don't re-apply model/tools on restore, just keep the name for instructions + } + } + + updateStatus(ctx); + }); + + // Persist preset state + pi.on("turn_start", async () => { + if (activePresetName) { + pi.appendEntry("preset-state", { name: activePresetName }); + } + }); +} diff --git a/examples/extensions/project-trust.ts b/examples/extensions/project-trust.ts new file mode 100644 index 0000000..6234bc2 --- /dev/null +++ b/examples/extensions/project-trust.ts @@ -0,0 +1,64 @@ +/** + * Project Trust Extension + * + * Demonstrates the project_trust event. Install globally or pass via -e: + * + * mkdir -p ~/.pi/agent/extensions + * cp packages/coding-agent/examples/extensions/project-trust.ts ~/.pi/agent/extensions/ + * + * Or: + * + * pi -e packages/coding-agent/examples/extensions/project-trust.ts + * + * Try it in a project containing .pi, AGENTS.md/CLAUDE.md, or .agents/skills. + */ + +import type { ExtensionAPI, ProjectTrustEventResult } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + let loadCount = 0; + loadCount++; + + // Multiple handlers in one extension are allowed. The first handler that returns + // { trusted: "yes" } or { trusted: "no" } wins and suppresses the built-in + // trust prompt. Return { trusted: "undecided" } to let another handler or the + // built-in flow decide. + pi.on("project_trust", async (event, ctx): Promise => { + ctx.ui.notify(`project_trust fired for ${event.cwd} (mode: ${ctx.mode}, load: ${loadCount})`, "info"); + + if (!ctx.hasUI) { + return { trusted: "undecided" }; + } + + const choice = await ctx.ui.select(`Project trust for:\n${event.cwd}`, [ + "Trust and remember", + "Trust with note and remember", + "Trust this session", + "Do not trust this session", + "Let built-in prompt decide", + ]); + + if (choice === "Trust with note and remember") { + const note = await ctx.ui.input("Project trust note", "Optional note for this demo"); + ctx.ui.notify(note ? `Recorded demo note: ${note}` : "No demo note entered", "info"); + return { trusted: "yes", remember: true }; + } + if (choice === "Trust and remember") { + return { trusted: "yes", remember: true }; + } + if (choice === "Trust this session") { + return { trusted: "yes" }; + } + if (choice === "Do not trust this session") { + return { trusted: "no" }; + } + if (choice === "Let built-in prompt decide") { + return { trusted: "undecided" }; + } + return { trusted: "undecided" }; + }); + + pi.on("session_start", (_event, ctx) => { + ctx.ui.notify(`project-trust example loaded after trust resolution in ${ctx.cwd}`, "info"); + }); +} diff --git a/examples/extensions/prompt-customizer.ts b/examples/extensions/prompt-customizer.ts new file mode 100644 index 0000000..5777dd5 --- /dev/null +++ b/examples/extensions/prompt-customizer.ts @@ -0,0 +1,97 @@ +/** + * Prompt Customizer Extension + * + * Demonstrates using systemPromptOptions to make informed, context-aware + * modifications to the system prompt without re-discovering resources. + * + * This extension adds tool-specific guidance based on what tools and skills + * are currently active, respecting whatever the user has configured. + * + * Usage: + * 1. Copy this file to ~/.pi/agent/extensions/ or your project's .pi/extensions/ + * 2. Use the extension — it automatically adapts to your active tools and skills + */ + +import type { BuildSystemPromptOptions, ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +/** + * Adds tool-specific guidance that adapts to the active tool set. + * Instead of appending one-size-fits-all instructions, this reads what's + * actually loaded and tailors the guidance accordingly. + */ +function addToolGuidance(options: BuildSystemPromptOptions, basePrompt: string): string { + const hasTool = (name: string) => options.selectedTools?.includes(name) ?? false; + + const parts: string[] = []; + + if (hasTool("read")) { + parts.push( + "• Use the `read` tool for file contents (supports text and images).", + " - For large files, use `offset` and `limit` to read in chunks.", + ); + } + + if (hasTool("bash")) { + parts.push("• Execute commands with the `bash` tool. Use it for file operations like `ls`, `find`, `grep`."); + } + + if (hasTool("edit")) { + parts.push( + "• Use the `edit` tool for precise text replacements in files. Match exact content including whitespace.", + ); + } + + if (hasTool("write")) { + parts.push("• Use the `write` tool to create new files or overwrite existing ones completely."); + } + + if (options.skills && options.skills.length > 0) { + const skillNames = options.skills.map((s) => s.name).join(", "); + parts.push(`\nAvailable skills: ${skillNames}`, "Use skill documentation for best practices on specific tools."); + } + + if (parts.length === 0) { + return basePrompt; + } + + return `${basePrompt} + +## Tool Guidance + +${parts.join("\n")} +`; +} + +/** + * Merges extension instructions with user-provided append prompts. + * This respects whatever the user configured via --append-system-prompt + * flags or files, rather than duplicating that work. + */ +function mergeWithUserAppend(options: BuildSystemPromptOptions): string { + const userAppend = options.appendSystemPrompt; + const extensionSpecific = ` +## Extension-Added Context + +This prompt includes tool guidance and skill information loaded dynamically. +If you have additional requirements, configure them via --append-system-prompt or project context files. +`; + + if (userAppend) { + return `${userAppend}\n\n${extensionSpecific}`; + } + + return extensionSpecific; +} + +export default function promptCustomizer(pi: ExtensionAPI) { + pi.on("before_agent_start", async (event) => { + const { systemPrompt, systemPromptOptions } = event; + + const customPrompt = addToolGuidance(systemPromptOptions, systemPrompt); + const appendSection = mergeWithUserAppend(systemPromptOptions); + + return { + systemPrompt: `${customPrompt}${appendSection}`, + }; + }); +} diff --git a/examples/extensions/protected-paths.ts b/examples/extensions/protected-paths.ts new file mode 100644 index 0000000..2cd9cd2 --- /dev/null +++ b/examples/extensions/protected-paths.ts @@ -0,0 +1,30 @@ +/** + * Protected Paths Extension + * + * Blocks write and edit operations to protected paths. + * Useful for preventing accidental modifications to sensitive files. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + const protectedPaths = [".env", ".git/", "node_modules/"]; + + pi.on("tool_call", async (event, ctx) => { + if (event.toolName !== "write" && event.toolName !== "edit") { + return undefined; + } + + const path = event.input.path as string; + const isProtected = protectedPaths.some((p) => path.includes(p)); + + if (isProtected) { + if (ctx.hasUI) { + ctx.ui.notify(`Blocked write to protected path: ${path}`, "warning"); + } + return { block: true, reason: `Path "${path}" is protected` }; + } + + return undefined; + }); +} diff --git a/examples/extensions/provider-payload.ts b/examples/extensions/provider-payload.ts new file mode 100644 index 0000000..7f02a07 --- /dev/null +++ b/examples/extensions/provider-payload.ts @@ -0,0 +1,18 @@ +import { appendFileSync } from "node:fs"; +import { join } from "node:path"; +import { CONFIG_DIR_NAME, type ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.on("before_provider_request", (event, ctx) => { + const logFile = join(ctx.cwd, CONFIG_DIR_NAME, "provider-payload.log"); + appendFileSync(logFile, `${JSON.stringify(event.payload, null, 2)}\n\n`, "utf8"); + + // Optional: replace the payload instead of only logging it. + // return { ...event.payload, temperature: 0 }; + }); + + pi.on("after_provider_response", (event, ctx) => { + const logFile = join(ctx.cwd, CONFIG_DIR_NAME, "provider-payload.log"); + appendFileSync(logFile, `[${event.status}] ${JSON.stringify(event.headers)}\n\n`, "utf8"); + }); +} diff --git a/examples/extensions/qna.ts b/examples/extensions/qna.ts new file mode 100644 index 0000000..399c4bd --- /dev/null +++ b/examples/extensions/qna.ts @@ -0,0 +1,122 @@ +/** + * Q&A extraction extension - extracts questions from assistant responses + * + * Demonstrates the "prompt generator" pattern: + * 1. /qna command gets the last assistant message + * 2. Shows a spinner while extracting (hides editor) + * 3. Loads the result into the editor for user to fill in answers + */ + +import { complete, type UserMessage } from "@earendil-works/pi-ai/compat"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { BorderedLoader } from "@earendil-works/pi-coding-agent"; + +const SYSTEM_PROMPT = `You are a question extractor. Given text from a conversation, extract any questions that need answering and format them for the user to fill in. + +Output format: +- List each question on its own line, prefixed with "Q: " +- After each question, add a blank line for the answer prefixed with "A: " +- If no questions are found, output "No questions found in the last message." + +Example output: +Q: What is your preferred database? +A: + +Q: Should we use TypeScript or JavaScript? +A: + +Keep questions in the order they appeared. Be concise.`; + +export default function (pi: ExtensionAPI) { + pi.registerCommand("qna", { + description: "Extract questions from last assistant message into editor", + handler: async (_args, ctx) => { + if (ctx.mode !== "tui") { + ctx.ui.notify("qna requires interactive mode", "error"); + return; + } + + if (!ctx.model) { + ctx.ui.notify("No model selected", "error"); + return; + } + + // Find the last assistant message on the current branch + const branch = ctx.sessionManager.getBranch(); + let lastAssistantText: string | undefined; + + for (let i = branch.length - 1; i >= 0; i--) { + const entry = branch[i]; + if (entry.type === "message") { + const msg = entry.message; + if ("role" in msg && msg.role === "assistant") { + if (msg.stopReason !== "stop") { + ctx.ui.notify(`Last assistant message incomplete (${msg.stopReason})`, "error"); + return; + } + const textParts = msg.content + .filter((c): c is { type: "text"; text: string } => c.type === "text") + .map((c) => c.text); + if (textParts.length > 0) { + lastAssistantText = textParts.join("\n"); + break; + } + } + } + } + + if (!lastAssistantText) { + ctx.ui.notify("No assistant messages found", "error"); + return; + } + + // Run extraction with loader UI + const result = await ctx.ui.custom((tui, theme, _kb, done) => { + const loader = new BorderedLoader(tui, theme, `Extracting questions using ${ctx.model!.id}...`); + loader.onAbort = () => done(null); + + // Do the work + const doExtract = async () => { + const auth = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model!); + if (!auth.ok || !auth.apiKey) { + throw new Error(auth.ok ? `No API key for ${ctx.model!.provider}` : auth.error); + } + const userMessage: UserMessage = { + role: "user", + content: [{ type: "text", text: lastAssistantText! }], + timestamp: Date.now(), + }; + + const response = await complete( + ctx.model!, + { systemPrompt: SYSTEM_PROMPT, messages: [userMessage] }, + { apiKey: auth.apiKey, headers: auth.headers, env: auth.env, signal: loader.signal }, + ); + + if (response.stopReason === "aborted") { + return null; + } + + return response.content + .filter((c): c is { type: "text"; text: string } => c.type === "text") + .map((c) => c.text) + .join("\n"); + }; + + doExtract() + .then(done) + .catch(() => done(null)); + + return loader; + }); + + if (result === null) { + ctx.ui.notify("Cancelled", "info"); + return; + } + + ctx.ui.setEditorText(result); + ctx.ui.notify("Questions loaded. Edit and submit when ready.", "info"); + }, + }); +} diff --git a/examples/extensions/question.ts b/examples/extensions/question.ts new file mode 100644 index 0000000..c877f8e --- /dev/null +++ b/examples/extensions/question.ts @@ -0,0 +1,286 @@ +/** + * Question Tool - Single question with options + * Full custom UI: options list + inline editor for "Type something..." + * Escape in editor returns to options, Escape in options cancels + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { + Editor, + type EditorTheme, + Key, + matchesKey, + Text, + visibleWidth, + wrapTextWithAnsi, +} from "@earendil-works/pi-tui"; +import { Type } from "typebox"; + +interface OptionWithDesc { + label: string; + description?: string; +} + +type DisplayOption = OptionWithDesc & { isOther?: boolean }; + +interface QuestionDetails { + question: string; + options: string[]; + answer: string | null; + wasCustom?: boolean; +} + +// Options with labels and optional descriptions +const OptionSchema = Type.Object({ + label: Type.String({ description: "Display label for the option" }), + description: Type.Optional(Type.String({ description: "Optional description shown below label" })), +}); + +const QuestionParams = Type.Object({ + question: Type.String({ description: "The question to ask the user" }), + options: Type.Array(OptionSchema, { description: "Options for the user to choose from" }), +}); + +export default function question(pi: ExtensionAPI) { + pi.registerTool({ + name: "question", + label: "Question", + description: "Ask the user a question and let them pick from options. Use when you need user input to proceed.", + parameters: QuestionParams, + executionMode: "sequential", + + async execute(_toolCallId, params, _signal, _onUpdate, ctx) { + if (ctx.mode !== "tui") { + return { + content: [{ type: "text", text: "Error: UI not available (running in non-interactive mode)" }], + details: { + question: params.question, + options: params.options.map((o) => o.label), + answer: null, + } as QuestionDetails, + }; + } + + if (params.options.length === 0) { + return { + content: [{ type: "text", text: "Error: No options provided" }], + details: { question: params.question, options: [], answer: null } as QuestionDetails, + }; + } + + const allOptions: DisplayOption[] = [...params.options, { label: "Type something.", isOther: true }]; + + const result = await ctx.ui.custom<{ answer: string; wasCustom: boolean; index?: number } | null>( + (tui, theme, _kb, done) => { + let optionIndex = 0; + let editMode = false; + let cachedLines: string[] | undefined; + + const editorTheme: EditorTheme = { + borderColor: (s) => theme.fg("accent", s), + selectList: { + selectedPrefix: (t) => theme.fg("accent", t), + selectedText: (t) => theme.fg("accent", t), + description: (t) => theme.fg("muted", t), + scrollInfo: (t) => theme.fg("dim", t), + noMatch: (t) => theme.fg("warning", t), + }, + }; + const editor = new Editor(tui, editorTheme); + + editor.onSubmit = (value) => { + const trimmed = value.trim(); + if (trimmed) { + done({ answer: trimmed, wasCustom: true }); + } else { + editMode = false; + editor.setText(""); + refresh(); + } + }; + + function refresh() { + cachedLines = undefined; + tui.requestRender(); + } + + function handleInput(data: string) { + if (editMode) { + if (matchesKey(data, Key.escape)) { + editMode = false; + editor.setText(""); + refresh(); + return; + } + editor.handleInput(data); + refresh(); + return; + } + + if (matchesKey(data, Key.up)) { + optionIndex = Math.max(0, optionIndex - 1); + refresh(); + return; + } + if (matchesKey(data, Key.down)) { + optionIndex = Math.min(allOptions.length - 1, optionIndex + 1); + refresh(); + return; + } + + if (matchesKey(data, Key.enter)) { + const selected = allOptions[optionIndex]; + if (selected.isOther) { + editMode = true; + refresh(); + } else { + done({ answer: selected.label, wasCustom: false, index: optionIndex + 1 }); + } + return; + } + + if (matchesKey(data, Key.escape)) { + done(null); + } + } + + function render(width: number): string[] { + if (cachedLines) return cachedLines; + + const lines: string[] = []; + const renderWidth = Math.max(1, width); + + function addWrapped(text: string) { + lines.push(...wrapTextWithAnsi(text, renderWidth)); + } + + function addWrappedWithPrefix(prefix: string, text: string) { + const prefixWidth = visibleWidth(prefix); + if (prefixWidth >= renderWidth) { + addWrapped(prefix + text); + return; + } + const wrapped = wrapTextWithAnsi(text, renderWidth - prefixWidth); + const continuationPrefix = " ".repeat(prefixWidth); + for (let i = 0; i < wrapped.length; i++) { + lines.push(`${i === 0 ? prefix : continuationPrefix}${wrapped[i]}`); + } + } + + lines.push(theme.fg("accent", "─".repeat(renderWidth))); + addWrappedWithPrefix(" ", theme.fg("text", params.question)); + lines.push(""); + + for (let i = 0; i < allOptions.length; i++) { + const opt = allOptions[i]; + const selected = i === optionIndex; + const isOther = opt.isOther === true; + const prefix = selected ? theme.fg("accent", "> ") : " "; + const label = `${i + 1}. ${opt.label}${isOther && editMode ? " ✎" : ""}`; + const color = selected || (isOther && editMode) ? "accent" : "text"; + + addWrappedWithPrefix(prefix, theme.fg(color, label)); + + // Show description if present + if (opt.description) { + addWrappedWithPrefix(" ", theme.fg("muted", opt.description)); + } + } + + if (editMode) { + lines.push(""); + addWrappedWithPrefix(" ", theme.fg("muted", "Your answer:")); + for (const line of editor.render(Math.max(1, renderWidth - 2))) { + lines.push(` ${line}`); + } + } + + lines.push(""); + if (editMode) { + addWrappedWithPrefix(" ", theme.fg("dim", "Enter to submit • Esc to go back")); + } else { + addWrappedWithPrefix(" ", theme.fg("dim", "↑↓ navigate • Enter to select • Esc to cancel")); + } + lines.push(theme.fg("accent", "─".repeat(renderWidth))); + + cachedLines = lines; + return lines; + } + + return { + render, + invalidate: () => { + cachedLines = undefined; + }, + handleInput, + }; + }, + ); + + // Build simple options list for details + const simpleOptions = params.options.map((o) => o.label); + + if (!result) { + return { + content: [{ type: "text", text: "User cancelled the selection" }], + details: { question: params.question, options: simpleOptions, answer: null } as QuestionDetails, + }; + } + + if (result.wasCustom) { + return { + content: [{ type: "text", text: `User wrote: ${result.answer}` }], + details: { + question: params.question, + options: simpleOptions, + answer: result.answer, + wasCustom: true, + } as QuestionDetails, + }; + } + return { + content: [{ type: "text", text: `User selected: ${result.index}. ${result.answer}` }], + details: { + question: params.question, + options: simpleOptions, + answer: result.answer, + wasCustom: false, + } as QuestionDetails, + }; + }, + + renderCall(args, theme, _context) { + let text = theme.fg("toolTitle", theme.bold("question ")) + theme.fg("muted", args.question); + const opts = Array.isArray(args.options) ? args.options : []; + if (opts.length) { + const labels = opts.map((o: OptionWithDesc) => o.label); + const numbered = [...labels, "Type something."].map((o, i) => `${i + 1}. ${o}`); + text += `\n${theme.fg("dim", ` Options: ${numbered.join(", ")}`)}`; + } + return new Text(text, 0, 0); + }, + + renderResult(result, _options, theme, _context) { + const details = result.details as QuestionDetails | undefined; + if (!details) { + const text = result.content[0]; + return new Text(text?.type === "text" ? text.text : "", 0, 0); + } + + if (details.answer === null) { + return new Text(theme.fg("warning", "Cancelled"), 0, 0); + } + + if (details.wasCustom) { + return new Text( + theme.fg("success", "✓ ") + theme.fg("muted", "(wrote) ") + theme.fg("accent", details.answer), + 0, + 0, + ); + } + const idx = details.options.indexOf(details.answer) + 1; + const display = idx > 0 ? `${idx}. ${details.answer}` : details.answer; + return new Text(theme.fg("success", "✓ ") + theme.fg("accent", display), 0, 0); + }, + }); +} diff --git a/examples/extensions/questionnaire.ts b/examples/extensions/questionnaire.ts new file mode 100644 index 0000000..3a546ac --- /dev/null +++ b/examples/extensions/questionnaire.ts @@ -0,0 +1,448 @@ +/** + * Questionnaire Tool - Unified tool for asking single or multiple questions + * + * Single question: simple options list + * Multiple questions: tab bar navigation between questions + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { + Editor, + type EditorTheme, + Key, + matchesKey, + Text, + visibleWidth, + wrapTextWithAnsi, +} from "@earendil-works/pi-tui"; +import { Type } from "typebox"; + +// Types +interface QuestionOption { + value: string; + label: string; + description?: string; +} + +type RenderOption = QuestionOption & { isOther?: boolean }; + +interface Question { + id: string; + label: string; + prompt: string; + options: QuestionOption[]; + allowOther: boolean; +} + +interface Answer { + id: string; + value: string; + label: string; + wasCustom: boolean; + index?: number; +} + +interface QuestionnaireResult { + questions: Question[]; + answers: Answer[]; + cancelled: boolean; +} + +// Schema +const QuestionOptionSchema = Type.Object({ + value: Type.String({ description: "The value returned when selected" }), + label: Type.String({ description: "Display label for the option" }), + description: Type.Optional(Type.String({ description: "Optional description shown below label" })), +}); + +const QuestionSchema = Type.Object({ + id: Type.String({ description: "Unique identifier for this question" }), + label: Type.Optional( + Type.String({ + description: "Short contextual label for tab bar, e.g. 'Scope', 'Priority' (defaults to Q1, Q2)", + }), + ), + prompt: Type.String({ description: "The full question text to display" }), + options: Type.Array(QuestionOptionSchema, { description: "Available options to choose from" }), + allowOther: Type.Optional(Type.Boolean({ description: "Allow 'Type something' option (default: true)" })), +}); + +const QuestionnaireParams = Type.Object({ + questions: Type.Array(QuestionSchema, { description: "Questions to ask the user" }), +}); + +function errorResult( + message: string, + questions: Question[] = [], +): { content: { type: "text"; text: string }[]; details: QuestionnaireResult } { + return { + content: [{ type: "text", text: message }], + details: { questions, answers: [], cancelled: true }, + }; +} + +export default function questionnaire(pi: ExtensionAPI) { + pi.registerTool({ + name: "questionnaire", + label: "Questionnaire", + description: + "Ask the user one or more questions. Use for clarifying requirements, getting preferences, or confirming decisions. For single questions, shows a simple option list. For multiple questions, shows a tab-based interface.", + parameters: QuestionnaireParams, + + async execute(_toolCallId, params, _signal, _onUpdate, ctx) { + if (ctx.mode !== "tui") { + return errorResult("Error: UI not available (running in non-interactive mode)"); + } + if (params.questions.length === 0) { + return errorResult("Error: No questions provided"); + } + + // Normalize questions with defaults + const questions: Question[] = params.questions.map((q, i) => ({ + ...q, + label: q.label || `Q${i + 1}`, + allowOther: q.allowOther !== false, + })); + + const isMulti = questions.length > 1; + const totalTabs = questions.length + 1; // questions + Submit + + const result = await ctx.ui.custom((tui, theme, _kb, done) => { + // State + let currentTab = 0; + let optionIndex = 0; + let inputMode = false; + let inputQuestionId: string | null = null; + let cachedLines: string[] | undefined; + const answers = new Map(); + + // Editor for "Type something" option + const editorTheme: EditorTheme = { + borderColor: (s) => theme.fg("accent", s), + selectList: { + selectedPrefix: (t) => theme.fg("accent", t), + selectedText: (t) => theme.fg("accent", t), + description: (t) => theme.fg("muted", t), + scrollInfo: (t) => theme.fg("dim", t), + noMatch: (t) => theme.fg("warning", t), + }, + }; + const editor = new Editor(tui, editorTheme); + + // Helpers + function refresh() { + cachedLines = undefined; + tui.requestRender(); + } + + function submit(cancelled: boolean) { + done({ questions, answers: Array.from(answers.values()), cancelled }); + } + + function currentQuestion(): Question | undefined { + return questions[currentTab]; + } + + function currentOptions(): RenderOption[] { + const q = currentQuestion(); + if (!q) return []; + const opts: RenderOption[] = [...q.options]; + if (q.allowOther) { + opts.push({ value: "__other__", label: "Type something.", isOther: true }); + } + return opts; + } + + function allAnswered(): boolean { + return questions.every((q) => answers.has(q.id)); + } + + function advanceAfterAnswer() { + if (!isMulti) { + submit(false); + return; + } + if (currentTab < questions.length - 1) { + currentTab++; + } else { + currentTab = questions.length; // Submit tab + } + optionIndex = 0; + refresh(); + } + + function saveAnswer(questionId: string, value: string, label: string, wasCustom: boolean, index?: number) { + answers.set(questionId, { id: questionId, value, label, wasCustom, index }); + } + + // Editor submit callback + editor.onSubmit = (value) => { + if (!inputQuestionId) return; + const trimmed = value.trim() || "(no response)"; + saveAnswer(inputQuestionId, trimmed, trimmed, true); + inputMode = false; + inputQuestionId = null; + editor.setText(""); + advanceAfterAnswer(); + }; + + function handleInput(data: string) { + // Input mode: route to editor + if (inputMode) { + if (matchesKey(data, Key.escape)) { + inputMode = false; + inputQuestionId = null; + editor.setText(""); + refresh(); + return; + } + editor.handleInput(data); + refresh(); + return; + } + + const q = currentQuestion(); + const opts = currentOptions(); + + // Tab navigation (multi-question only) + if (isMulti) { + if (matchesKey(data, Key.tab) || matchesKey(data, Key.right)) { + currentTab = (currentTab + 1) % totalTabs; + optionIndex = 0; + refresh(); + return; + } + if (matchesKey(data, Key.shift("tab")) || matchesKey(data, Key.left)) { + currentTab = (currentTab - 1 + totalTabs) % totalTabs; + optionIndex = 0; + refresh(); + return; + } + } + + // Submit tab + if (currentTab === questions.length) { + if (matchesKey(data, Key.enter) && allAnswered()) { + submit(false); + } else if (matchesKey(data, Key.escape)) { + submit(true); + } + return; + } + + // Option navigation + if (matchesKey(data, Key.up)) { + optionIndex = Math.max(0, optionIndex - 1); + refresh(); + return; + } + if (matchesKey(data, Key.down)) { + optionIndex = Math.min(opts.length - 1, optionIndex + 1); + refresh(); + return; + } + + // Select option + if (matchesKey(data, Key.enter) && q) { + const opt = opts[optionIndex]; + if (opt.isOther) { + inputMode = true; + inputQuestionId = q.id; + editor.setText(""); + refresh(); + return; + } + saveAnswer(q.id, opt.value, opt.label, false, optionIndex + 1); + advanceAfterAnswer(); + return; + } + + // Cancel + if (matchesKey(data, Key.escape)) { + submit(true); + } + } + + function render(width: number): string[] { + if (cachedLines) return cachedLines; + + const lines: string[] = []; + const renderWidth = Math.max(1, width); + const q = currentQuestion(); + const opts = currentOptions(); + + function addWrapped(text: string) { + lines.push(...wrapTextWithAnsi(text, renderWidth)); + } + + function addWrappedWithPrefix(prefix: string, text: string) { + const prefixWidth = visibleWidth(prefix); + if (prefixWidth >= renderWidth) { + addWrapped(prefix + text); + return; + } + const wrapped = wrapTextWithAnsi(text, renderWidth - prefixWidth); + const continuationPrefix = " ".repeat(prefixWidth); + for (let i = 0; i < wrapped.length; i++) { + lines.push(`${i === 0 ? prefix : continuationPrefix}${wrapped[i]}`); + } + } + + lines.push(theme.fg("accent", "─".repeat(renderWidth))); + + // Tab bar (multi-question only) + if (isMulti) { + const tabs: string[] = ["← "]; + for (let i = 0; i < questions.length; i++) { + const isActive = i === currentTab; + const isAnswered = answers.has(questions[i].id); + const lbl = questions[i].label; + const box = isAnswered ? "■" : "□"; + const color = isAnswered ? "success" : "muted"; + const text = ` ${box} ${lbl} `; + const styled = isActive ? theme.bg("selectedBg", theme.fg("text", text)) : theme.fg(color, text); + tabs.push(`${styled} `); + } + const canSubmit = allAnswered(); + const isSubmitTab = currentTab === questions.length; + const submitText = " ✓ Submit "; + const submitStyled = isSubmitTab + ? theme.bg("selectedBg", theme.fg("text", submitText)) + : theme.fg(canSubmit ? "success" : "dim", submitText); + tabs.push(`${submitStyled} →`); + addWrappedWithPrefix(" ", tabs.join("")); + lines.push(""); + } + + // Helper to render options list + function renderOptions() { + for (let i = 0; i < opts.length; i++) { + const opt = opts[i]; + const selected = i === optionIndex; + const isOther = opt.isOther === true; + const prefix = selected ? theme.fg("accent", "> ") : " "; + const label = `${i + 1}. ${opt.label}${isOther && inputMode ? " ✎" : ""}`; + const color = selected || (isOther && inputMode) ? "accent" : "text"; + + addWrappedWithPrefix(prefix, theme.fg(color, label)); + if (opt.description) { + addWrappedWithPrefix(" ", theme.fg("muted", opt.description)); + } + } + } + + // Content + if (inputMode && q) { + addWrappedWithPrefix(" ", theme.fg("text", q.prompt)); + lines.push(""); + // Show options for reference + renderOptions(); + lines.push(""); + addWrappedWithPrefix(" ", theme.fg("muted", "Your answer:")); + for (const line of editor.render(Math.max(1, renderWidth - 2))) { + lines.push(` ${line}`); + } + lines.push(""); + addWrappedWithPrefix(" ", theme.fg("dim", "Enter to submit • Esc to cancel")); + } else if (currentTab === questions.length) { + addWrappedWithPrefix(" ", theme.fg("accent", theme.bold("Ready to submit"))); + lines.push(""); + for (const question of questions) { + const answer = answers.get(question.id); + if (answer) { + const prefix = answer.wasCustom ? "(wrote) " : ""; + const summary = `${theme.fg("muted", `${question.label}: `)}${theme.fg("text", prefix + answer.label)}`; + addWrappedWithPrefix(" ", summary); + } + } + lines.push(""); + if (allAnswered()) { + addWrappedWithPrefix(" ", theme.fg("success", "Press Enter to submit")); + } else { + const missing = questions + .filter((q) => !answers.has(q.id)) + .map((q) => q.label) + .join(", "); + addWrappedWithPrefix(" ", theme.fg("warning", `Unanswered: ${missing}`)); + } + } else if (q) { + addWrappedWithPrefix(" ", theme.fg("text", q.prompt)); + lines.push(""); + renderOptions(); + } + + lines.push(""); + if (!inputMode) { + const help = isMulti + ? "Tab/←→ navigate • ↑↓ select • Enter confirm • Esc cancel" + : "↑↓ navigate • Enter select • Esc cancel"; + addWrappedWithPrefix(" ", theme.fg("dim", help)); + } + lines.push(theme.fg("accent", "─".repeat(renderWidth))); + + cachedLines = lines; + return lines; + } + + return { + render, + invalidate: () => { + cachedLines = undefined; + }, + handleInput, + }; + }); + + if (result.cancelled) { + return { + content: [{ type: "text", text: "User cancelled the questionnaire" }], + details: result, + }; + } + + const answerLines = result.answers.map((a) => { + const qLabel = questions.find((q) => q.id === a.id)?.label || a.id; + if (a.wasCustom) { + return `${qLabel}: user wrote: ${a.label}`; + } + return `${qLabel}: user selected: ${a.index}. ${a.label}`; + }); + + return { + content: [{ type: "text", text: answerLines.join("\n") }], + details: result, + }; + }, + + renderCall(args, theme, _context) { + const qs = (args.questions as Question[]) || []; + const count = qs.length; + const labels = qs.map((q) => q.label || q.id).join(", "); + let text = theme.fg("toolTitle", theme.bold("questionnaire ")); + text += theme.fg("muted", `${count} question${count !== 1 ? "s" : ""}`); + if (labels) { + text += theme.fg("dim", ` (${labels})`); + } + return new Text(text, 0, 0); + }, + + renderResult(result, _options, theme, _context) { + const details = result.details as QuestionnaireResult | undefined; + if (!details) { + const text = result.content[0]; + return new Text(text?.type === "text" ? text.text : "", 0, 0); + } + if (details.cancelled) { + return new Text(theme.fg("warning", "Cancelled"), 0, 0); + } + const lines = details.answers.map((a) => { + if (a.wasCustom) { + return `${theme.fg("success", "✓ ")}${theme.fg("accent", a.id)}: ${theme.fg("muted", "(wrote) ")}${a.label}`; + } + const display = a.index ? `${a.index}. ${a.label}` : a.label; + return `${theme.fg("success", "✓ ")}${theme.fg("accent", a.id)}: ${display}`; + }); + return new Text(lines.join("\n"), 0, 0); + }, + }); +} diff --git a/examples/extensions/rainbow-editor.ts b/examples/extensions/rainbow-editor.ts new file mode 100644 index 0000000..20b7437 --- /dev/null +++ b/examples/extensions/rainbow-editor.ts @@ -0,0 +1,88 @@ +/** + * Rainbow Editor - highlights "ultrathink" with animated shine effect + * + * Usage: pi --extension ./examples/extensions/rainbow-editor.ts + */ + +import { CustomEditor, type ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +// Base colors (coral → yellow → green → teal → blue → purple → pink) +const COLORS: [number, number, number][] = [ + [233, 137, 115], // coral + [228, 186, 103], // yellow + [141, 192, 122], // green + [102, 194, 179], // teal + [121, 157, 207], // blue + [157, 134, 195], // purple + [206, 130, 172], // pink +]; +const RESET = "\x1b[0m"; + +function brighten(rgb: [number, number, number], factor: number): string { + const [r, g, b] = rgb.map((c) => Math.round(c + (255 - c) * factor)); + return `\x1b[38;2;${r};${g};${b}m`; +} + +function colorize(text: string, shinePos: number): string { + return ( + [...text] + .map((c, i) => { + const baseColor = COLORS[i % COLORS.length]!; + // 3-letter shine: center bright, adjacent dimmer + let factor = 0; + if (shinePos >= 0) { + const dist = Math.abs(i - shinePos); + if (dist === 0) factor = 0.7; + else if (dist === 1) factor = 0.35; + } + return `${brighten(baseColor, factor)}${c}`; + }) + .join("") + RESET + ); +} + +class RainbowEditor extends CustomEditor { + private animationTimer?: ReturnType; + private frame = 0; + + private hasUltrathink(): boolean { + return /ultrathink/i.test(this.getText()); + } + + private startAnimation(): void { + if (this.animationTimer) return; + this.animationTimer = setInterval(() => { + this.frame++; + this.tui.requestRender(); + }, 60); + } + + private stopAnimation(): void { + if (this.animationTimer) { + clearInterval(this.animationTimer); + this.animationTimer = undefined; + } + } + + handleInput(data: string): void { + super.handleInput(data); + if (this.hasUltrathink()) { + this.startAnimation(); + } else { + this.stopAnimation(); + } + } + + render(width: number): string[] { + // Cycle: 10 shine positions + 10 pause frames + const cycle = this.frame % 20; + const shinePos = cycle < 10 ? cycle : -1; // -1 means no shine (pause) + return super.render(width).map((line) => line.replace(/ultrathink/gi, (m) => colorize(m, shinePos))); + } +} + +export default function (pi: ExtensionAPI) { + pi.on("session_start", (_event, ctx) => { + ctx.ui.setEditorComponent((tui, theme, kb) => new RainbowEditor(tui, theme, kb)); + }); +} diff --git a/examples/extensions/reload-runtime.ts b/examples/extensions/reload-runtime.ts new file mode 100644 index 0000000..d0e9abd --- /dev/null +++ b/examples/extensions/reload-runtime.ts @@ -0,0 +1,37 @@ +/** + * Reload Runtime Extension + * + * Demonstrates ctx.reload() from ExtensionCommandContext and an LLM-callable + * tool that queues a follow-up command to trigger reload. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { Type } from "typebox"; + +export default function (pi: ExtensionAPI) { + // Command entrypoint for reload. + // Treat reload as terminal for this handler. + pi.registerCommand("reload-runtime", { + description: "Reload extensions, skills, prompts, themes, and context files", + handler: async (_args, ctx) => { + await ctx.reload(); + return; + }, + }); + + // LLM-callable tool. Tools get ExtensionContext, so they cannot call ctx.reload() directly. + // Instead, queue a follow-up user command that executes the command above. + pi.registerTool({ + name: "reload_runtime", + label: "Reload Runtime", + description: "Reload extensions, skills, prompts, themes, and context files", + parameters: Type.Object({}), + async execute() { + pi.sendUserMessage("/reload-runtime", { deliverAs: "followUp" }); + return { + content: [{ type: "text", text: "Queued /reload-runtime as a follow-up command." }], + details: {}, + }; + }, + }); +} diff --git a/examples/extensions/rpc-demo.ts b/examples/extensions/rpc-demo.ts new file mode 100644 index 0000000..78789a1 --- /dev/null +++ b/examples/extensions/rpc-demo.ts @@ -0,0 +1,118 @@ +/** + * RPC Extension UI Demo + * + * Purpose-built extension that exercises all RPC-supported extension UI methods. + * Designed to be loaded alongside the rpc-extension-ui-example.ts script to + * demonstrate the full extension UI protocol. + * + * UI methods exercised: + * - select() - on tool_call for dangerous bash commands + * - confirm() - on session_before_switch + * - input() - via /rpc-input command + * - editor() - via /rpc-editor command + * - notify() - after each dialog completes + * - setStatus() - on turn_start/turn_end + * - setWidget() - on session_start + * - setTitle() - on session_start + * - setEditorText() - via /rpc-prefill command + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + let turnCount = 0; + + // -- setTitle, setWidget, setStatus on session lifecycle -- + + pi.on("session_start", async (event, ctx) => { + ctx.ui.setTitle(event.reason === "new" ? "pi RPC Demo (new session)" : "pi RPC Demo"); + ctx.ui.setWidget("rpc-demo", ["--- RPC Extension UI Demo ---", "Loaded and ready."]); + ctx.ui.setStatus("rpc-demo", `Turns: ${turnCount}`); + }); + + // -- setStatus on turn lifecycle -- + + pi.on("turn_start", async (_event, ctx) => { + turnCount++; + ctx.ui.setStatus("rpc-demo", `Turn ${turnCount} running...`); + }); + + pi.on("turn_end", async (_event, ctx) => { + ctx.ui.setStatus("rpc-demo", `Turn ${turnCount} done`); + }); + + // -- select on dangerous tool calls -- + + pi.on("tool_call", async (event, ctx) => { + if (event.toolName !== "bash") return undefined; + + const command = event.input.command as string; + const isDangerous = /\brm\s+(-rf?|--recursive)/i.test(command) || /\bsudo\b/i.test(command); + + if (isDangerous) { + if (!ctx.hasUI) { + return { block: true, reason: "Dangerous command blocked (no UI)" }; + } + + const choice = await ctx.ui.select(`Dangerous command: ${command}`, ["Allow", "Block"]); + if (choice !== "Allow") { + ctx.ui.notify("Command blocked by user", "warning"); + return { block: true, reason: "Blocked by user" }; + } + ctx.ui.notify("Command allowed", "info"); + } + + return undefined; + }); + + // -- confirm on session clear -- + + pi.on("session_before_switch", async (event, ctx) => { + if (event.reason !== "new") return; + if (!ctx.hasUI) return; + + const confirmed = await ctx.ui.confirm("Clear session?", "All messages will be lost."); + if (!confirmed) { + ctx.ui.notify("Clear cancelled", "info"); + return { cancel: true }; + } + }); + + // -- input via command -- + + pi.registerCommand("rpc-input", { + description: "Prompt for text input (demonstrates ctx.ui.input in RPC)", + handler: async (_args, ctx) => { + const value = await ctx.ui.input("Enter a value", "type something..."); + if (value) { + ctx.ui.notify(`You entered: ${value}`, "info"); + } else { + ctx.ui.notify("Input cancelled", "info"); + } + }, + }); + + // -- editor via command -- + + pi.registerCommand("rpc-editor", { + description: "Open multi-line editor (demonstrates ctx.ui.editor in RPC)", + handler: async (_args, ctx) => { + const text = await ctx.ui.editor("Edit some text", "Line 1\nLine 2\nLine 3"); + if (text) { + ctx.ui.notify(`Editor submitted (${text.split("\n").length} lines)`, "info"); + } else { + ctx.ui.notify("Editor cancelled", "info"); + } + }, + }); + + // -- setEditorText via command -- + + pi.registerCommand("rpc-prefill", { + description: "Prefill the input editor (demonstrates ctx.ui.setEditorText in RPC)", + handler: async (_args, ctx) => { + ctx.ui.setEditorText("This text was set by the rpc-demo extension."); + ctx.ui.notify("Editor prefilled", "info"); + }, + }); +} diff --git a/examples/extensions/sandbox/index.ts b/examples/extensions/sandbox/index.ts new file mode 100644 index 0000000..b54d75d --- /dev/null +++ b/examples/extensions/sandbox/index.ts @@ -0,0 +1,321 @@ +/** + * Sandbox Extension - OS-level sandboxing for bash commands + * + * Uses @anthropic-ai/sandbox-runtime to enforce filesystem and network + * restrictions on bash commands at the OS level (sandbox-exec on macOS, + * bubblewrap on Linux). + * + * Note: this example intentionally overrides the built-in `bash` tool to show + * how built-in tools can be replaced. Alternatively, you could sandbox `bash` + * via `tool_call` input mutation without replacing the tool. + * + * Config files (merged, project takes precedence): + * - ~/.pi/agent/extensions/sandbox.json (global) + * - /.pi/sandbox.json (project-local) + * + * Example .pi/sandbox.json: + * ```json + * { + * "enabled": true, + * "network": { + * "allowedDomains": ["github.com", "*.github.com"], + * "deniedDomains": [] + * }, + * "filesystem": { + * "denyRead": ["~/.ssh", "~/.aws"], + * "allowWrite": [".", "/tmp"], + * "denyWrite": [".env"] + * } + * } + * ``` + * + * Usage: + * - `pi -e ./sandbox` - sandbox enabled with default/config settings + * - `pi -e ./sandbox --no-sandbox` - disable sandboxing + * - `/sandbox` - show current sandbox configuration + * + * Setup: + * 1. Copy sandbox/ directory to ~/.pi/agent/extensions/ + * 2. Run `npm install` in ~/.pi/agent/extensions/sandbox/ + * + * Linux also requires: bubblewrap, socat, ripgrep + */ + +import { spawn } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { SandboxManager, type SandboxRuntimeConfig } from "@anthropic-ai/sandbox-runtime"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { type BashOperations, CONFIG_DIR_NAME, createBashTool, getAgentDir } from "@earendil-works/pi-coding-agent"; + +interface SandboxConfig extends SandboxRuntimeConfig { + enabled?: boolean; +} + +const DEFAULT_CONFIG: SandboxConfig = { + enabled: true, + network: { + allowedDomains: [ + "npmjs.org", + "*.npmjs.org", + "registry.npmjs.org", + "registry.yarnpkg.com", + "pypi.org", + "*.pypi.org", + "github.com", + "*.github.com", + "api.github.com", + "raw.githubusercontent.com", + ], + deniedDomains: [], + }, + filesystem: { + denyRead: ["~/.ssh", "~/.aws", "~/.gnupg"], + allowWrite: [".", "/tmp"], + denyWrite: [".env", ".env.*", "*.pem", "*.key"], + }, +}; + +function loadConfig(cwd: string): SandboxConfig { + const projectConfigPath = join(cwd, CONFIG_DIR_NAME, "sandbox.json"); + const globalConfigPath = join(getAgentDir(), "extensions", "sandbox.json"); + + let globalConfig: Partial = {}; + let projectConfig: Partial = {}; + + if (existsSync(globalConfigPath)) { + try { + globalConfig = JSON.parse(readFileSync(globalConfigPath, "utf-8")); + } catch (e) { + console.error(`Warning: Could not parse ${globalConfigPath}: ${e}`); + } + } + + if (existsSync(projectConfigPath)) { + try { + projectConfig = JSON.parse(readFileSync(projectConfigPath, "utf-8")); + } catch (e) { + console.error(`Warning: Could not parse ${projectConfigPath}: ${e}`); + } + } + + return deepMerge(deepMerge(DEFAULT_CONFIG, globalConfig), projectConfig); +} + +function deepMerge(base: SandboxConfig, overrides: Partial): SandboxConfig { + const result: SandboxConfig = { ...base }; + + if (overrides.enabled !== undefined) result.enabled = overrides.enabled; + if (overrides.network) { + result.network = { ...base.network, ...overrides.network }; + } + if (overrides.filesystem) { + result.filesystem = { ...base.filesystem, ...overrides.filesystem }; + } + + const extOverrides = overrides as { + ignoreViolations?: Record; + enableWeakerNestedSandbox?: boolean; + }; + const extResult = result as { ignoreViolations?: Record; enableWeakerNestedSandbox?: boolean }; + + if (extOverrides.ignoreViolations) { + extResult.ignoreViolations = extOverrides.ignoreViolations; + } + if (extOverrides.enableWeakerNestedSandbox !== undefined) { + extResult.enableWeakerNestedSandbox = extOverrides.enableWeakerNestedSandbox; + } + + return result; +} + +function createSandboxedBashOps(): BashOperations { + return { + async exec(command, cwd, { onData, signal, timeout }) { + if (!existsSync(cwd)) { + throw new Error(`Working directory does not exist: ${cwd}`); + } + + const wrappedCommand = await SandboxManager.wrapWithSandbox(command); + + return new Promise((resolve, reject) => { + const child = spawn("bash", ["-c", wrappedCommand], { + cwd, + detached: true, + stdio: ["ignore", "pipe", "pipe"], + }); + + let timedOut = false; + let timeoutHandle: NodeJS.Timeout | undefined; + + if (timeout !== undefined && timeout > 0) { + timeoutHandle = setTimeout(() => { + timedOut = true; + if (child.pid) { + try { + process.kill(-child.pid, "SIGKILL"); + } catch { + child.kill("SIGKILL"); + } + } + }, timeout * 1000); + } + + child.stdout?.on("data", onData); + child.stderr?.on("data", onData); + + child.on("error", (err) => { + if (timeoutHandle) clearTimeout(timeoutHandle); + reject(err); + }); + + const onAbort = () => { + if (child.pid) { + try { + process.kill(-child.pid, "SIGKILL"); + } catch { + child.kill("SIGKILL"); + } + } + }; + + signal?.addEventListener("abort", onAbort, { once: true }); + + child.on("close", (code) => { + if (timeoutHandle) clearTimeout(timeoutHandle); + signal?.removeEventListener("abort", onAbort); + + if (signal?.aborted) { + reject(new Error("aborted")); + } else if (timedOut) { + reject(new Error(`timeout:${timeout}`)); + } else { + resolve({ exitCode: code }); + } + }); + }); + }, + }; +} + +export default function (pi: ExtensionAPI) { + pi.registerFlag("no-sandbox", { + description: "Disable OS-level sandboxing for bash commands", + type: "boolean", + default: false, + }); + + const localCwd = process.cwd(); + const localBash = createBashTool(localCwd); + + let sandboxEnabled = false; + let sandboxInitialized = false; + + pi.registerTool({ + ...localBash, + label: "bash (sandboxed)", + async execute(id, params, signal, onUpdate, _ctx) { + if (!sandboxEnabled || !sandboxInitialized) { + return localBash.execute(id, params, signal, onUpdate); + } + + const sandboxedBash = createBashTool(localCwd, { + operations: createSandboxedBashOps(), + }); + return sandboxedBash.execute(id, params, signal, onUpdate); + }, + }); + + pi.on("user_bash", () => { + if (!sandboxEnabled || !sandboxInitialized) return; + return { operations: createSandboxedBashOps() }; + }); + + pi.on("session_start", async (_event, ctx) => { + const noSandbox = pi.getFlag("no-sandbox") as boolean; + + if (noSandbox) { + sandboxEnabled = false; + ctx.ui.notify("Sandbox disabled via --no-sandbox", "warning"); + return; + } + + const config = loadConfig(ctx.cwd); + + if (!config.enabled) { + sandboxEnabled = false; + ctx.ui.notify("Sandbox disabled via config", "info"); + return; + } + + const platform = process.platform; + if (platform !== "darwin" && platform !== "linux") { + sandboxEnabled = false; + ctx.ui.notify(`Sandbox not supported on ${platform}`, "warning"); + return; + } + + try { + const configExt = config as unknown as { + ignoreViolations?: Record; + enableWeakerNestedSandbox?: boolean; + }; + + await SandboxManager.initialize({ + network: config.network, + filesystem: config.filesystem, + ignoreViolations: configExt.ignoreViolations, + enableWeakerNestedSandbox: configExt.enableWeakerNestedSandbox, + }); + + sandboxEnabled = true; + sandboxInitialized = true; + + const networkCount = config.network?.allowedDomains?.length ?? 0; + const writeCount = config.filesystem?.allowWrite?.length ?? 0; + ctx.ui.setStatus( + "sandbox", + ctx.ui.theme.fg("accent", `🔒 Sandbox: ${networkCount} domains, ${writeCount} write paths`), + ); + ctx.ui.notify("Sandbox initialized", "info"); + } catch (err) { + sandboxEnabled = false; + ctx.ui.notify(`Sandbox initialization failed: ${err instanceof Error ? err.message : err}`, "error"); + } + }); + + pi.on("session_shutdown", async () => { + if (sandboxInitialized) { + try { + await SandboxManager.reset(); + } catch { + // Ignore cleanup errors + } + } + }); + + pi.registerCommand("sandbox", { + description: "Show sandbox configuration", + handler: async (_args, ctx) => { + if (!sandboxEnabled) { + ctx.ui.notify("Sandbox is disabled", "info"); + return; + } + + const config = loadConfig(ctx.cwd); + const lines = [ + "Sandbox Configuration:", + "", + "Network:", + ` Allowed: ${config.network?.allowedDomains?.join(", ") || "(none)"}`, + ` Denied: ${config.network?.deniedDomains?.join(", ") || "(none)"}`, + "", + "Filesystem:", + ` Deny Read: ${config.filesystem?.denyRead?.join(", ") || "(none)"}`, + ` Allow Write: ${config.filesystem?.allowWrite?.join(", ") || "(none)"}`, + ` Deny Write: ${config.filesystem?.denyWrite?.join(", ") || "(none)"}`, + ]; + ctx.ui.notify(lines.join("\n"), "info"); + }, + }); +} diff --git a/examples/extensions/sandbox/package-lock.json b/examples/extensions/sandbox/package-lock.json new file mode 100644 index 0000000..fe7b970 --- /dev/null +++ b/examples/extensions/sandbox/package-lock.json @@ -0,0 +1,92 @@ +{ + "name": "pi-extension-sandbox", + "version": "1.13.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "pi-extension-sandbox", + "version": "1.13.0", + "dependencies": { + "@anthropic-ai/sandbox-runtime": "^0.0.26" + } + }, + "node_modules/@anthropic-ai/sandbox-runtime": { + "version": "0.0.26", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sandbox-runtime/-/sandbox-runtime-0.0.26.tgz", + "integrity": "sha512-DYV5LSsVMnzq0lbfaYMSpxZPUMAx4+hy343dRss+pVCLIfF62qOhxpYfZ5TmOk1GTDQm5f9wPprMNSStmnsV4w==", + "license": "Apache-2.0", + "dependencies": { + "@pondwader/socks5-server": "^1.0.10", + "@types/lodash-es": "^4.17.12", + "commander": "^12.1.0", + "lodash-es": "^4.17.21", + "shell-quote": "^1.8.3", + "zod": "^3.24.1" + }, + "bin": { + "srt": "dist/cli.js" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@pondwader/socks5-server": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@pondwader/socks5-server/-/socks5-server-1.0.10.tgz", + "integrity": "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg==", + "license": "MIT" + }, + "node_modules/@types/lodash": { + "version": "4.17.23", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.23.tgz", + "integrity": "sha512-RDvF6wTulMPjrNdCoYRC8gNR880JNGT8uB+REUpC2Ns4pRqQJhGz90wh7rgdXDPpCczF3VGktDuFGVnz8zP7HA==", + "license": "MIT" + }, + "node_modules/@types/lodash-es": { + "version": "4.17.12", + "resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz", + "integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==", + "license": "MIT", + "dependencies": { + "@types/lodash": "*" + } + }, + "node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/lodash-es": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", + "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", + "license": "MIT" + }, + "node_modules/shell-quote": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz", + "integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/examples/extensions/sandbox/package.json b/examples/extensions/sandbox/package.json new file mode 100644 index 0000000..49d381d --- /dev/null +++ b/examples/extensions/sandbox/package.json @@ -0,0 +1,19 @@ +{ + "name": "pi-extension-sandbox", + "private": true, + "version": "1.13.0", + "type": "module", + "scripts": { + "clean": "echo 'nothing to clean'", + "build": "echo 'nothing to build'", + "check": "echo 'nothing to check'" + }, + "pi": { + "extensions": [ + "./index.ts" + ] + }, + "dependencies": { + "@anthropic-ai/sandbox-runtime": "0.0.26" + } +} diff --git a/examples/extensions/send-user-message.ts b/examples/extensions/send-user-message.ts new file mode 100644 index 0000000..cf4eb13 --- /dev/null +++ b/examples/extensions/send-user-message.ts @@ -0,0 +1,97 @@ +/** + * Send User Message Example + * + * Demonstrates pi.sendUserMessage() for sending user messages from extensions. + * Unlike pi.sendMessage() which sends custom messages, sendUserMessage() sends + * actual user messages that appear in the conversation as if typed by the user. + * + * Usage: + * /ask What is 2+2? - Sends a user message (always triggers a turn) + * /steer Focus on X - Sends while streaming with steer delivery + * /followup And then? - Sends while streaming with followUp delivery + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + // Simple command that sends a user message + pi.registerCommand("ask", { + description: "Send a user message to the agent", + handler: async (args, ctx) => { + if (!args.trim()) { + ctx.ui.notify("Usage: /ask ", "warning"); + return; + } + + // sendUserMessage always triggers a turn when not streaming + // If streaming, it will throw (no deliverAs specified) + if (!ctx.isIdle()) { + ctx.ui.notify("Agent is busy. Use /steer or /followup instead.", "warning"); + return; + } + + pi.sendUserMessage(args); + }, + }); + + // Command that steers the agent mid-conversation + pi.registerCommand("steer", { + description: "Send a steering message (interrupts current processing)", + handler: async (args, ctx) => { + if (!args.trim()) { + ctx.ui.notify("Usage: /steer ", "warning"); + return; + } + + if (ctx.isIdle()) { + // Not streaming, just send normally + pi.sendUserMessage(args); + } else { + // Streaming - use steer to interrupt + pi.sendUserMessage(args, { deliverAs: "steer" }); + } + }, + }); + + // Command that queues a follow-up message + pi.registerCommand("followup", { + description: "Queue a follow-up message (waits for current processing)", + handler: async (args, ctx) => { + if (!args.trim()) { + ctx.ui.notify("Usage: /followup ", "warning"); + return; + } + + if (ctx.isIdle()) { + // Not streaming, just send normally + pi.sendUserMessage(args); + } else { + // Streaming - queue as follow-up + pi.sendUserMessage(args, { deliverAs: "followUp" }); + ctx.ui.notify("Follow-up queued", "info"); + } + }, + }); + + // Example with content array (text + images would go here) + pi.registerCommand("askwith", { + description: "Send a user message with structured content", + handler: async (args, ctx) => { + if (!args.trim()) { + ctx.ui.notify("Usage: /askwith ", "warning"); + return; + } + + if (!ctx.isIdle()) { + ctx.ui.notify("Agent is busy", "warning"); + return; + } + + // sendUserMessage accepts string or (TextContent | ImageContent)[] + pi.sendUserMessage([ + { type: "text", text: `User request: ${args}` }, + { type: "text", text: "Please respond concisely." }, + ]); + }, + }); +} diff --git a/examples/extensions/session-name.ts b/examples/extensions/session-name.ts new file mode 100644 index 0000000..48203de --- /dev/null +++ b/examples/extensions/session-name.ts @@ -0,0 +1,27 @@ +/** + * Session naming example. + * + * Shows setSessionName/getSessionName to give sessions friendly names + * that appear in the session selector instead of the first message. + * + * Usage: /session-name [name] - set or show session name + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.registerCommand("session-name", { + description: "Set or show session name (usage: /session-name [new name])", + handler: async (args, ctx) => { + const name = args.trim(); + + if (name) { + pi.setSessionName(name); + ctx.ui.notify(`Session named: ${name}`, "info"); + } else { + const current = pi.getSessionName(); + ctx.ui.notify(current ? `Session: ${current}` : "No session name set", "info"); + } + }, + }); +} diff --git a/examples/extensions/shutdown-command.ts b/examples/extensions/shutdown-command.ts new file mode 100644 index 0000000..743f880 --- /dev/null +++ b/examples/extensions/shutdown-command.ts @@ -0,0 +1,63 @@ +/** + * Shutdown Command Extension + * + * Adds a /quit command that allows extensions to trigger clean shutdown. + * Demonstrates how extensions can use ctx.shutdown() to exit pi cleanly. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { Type } from "typebox"; + +export default function (pi: ExtensionAPI) { + // Register a /quit command that cleanly exits pi + pi.registerCommand("quit", { + description: "Exit pi cleanly", + handler: async (_args, ctx) => { + ctx.shutdown(); + }, + }); + + // You can also create a tool that shuts down after completing work + pi.registerTool({ + name: "finish_and_exit", + label: "Finish and Exit", + description: "Complete a task and exit pi", + parameters: Type.Object({}), + async execute(_toolCallId, _params, _signal, _onUpdate, ctx) { + // Do any final work here... + // Request graceful shutdown (deferred until agent is idle) + ctx.shutdown(); + + // This return is sent to the LLM before shutdown occurs + return { + content: [{ type: "text", text: "Shutdown requested. Exiting after this response." }], + details: {}, + }; + }, + }); + + // You could also create a more complex tool with parameters + pi.registerTool({ + name: "deploy_and_exit", + label: "Deploy and Exit", + description: "Deploy the application and exit pi", + parameters: Type.Object({ + environment: Type.String({ description: "Target environment (e.g., production, staging)" }), + }), + async execute(_toolCallId, params, _signal, onUpdate, ctx) { + onUpdate?.({ content: [{ type: "text", text: `Deploying to ${params.environment}...` }], details: {} }); + + // Example deployment logic + // const result = await pi.exec("npm", ["run", "deploy", params.environment], { signal }); + + // On success, request graceful shutdown + onUpdate?.({ content: [{ type: "text", text: "Deployment complete, exiting..." }], details: {} }); + ctx.shutdown(); + + return { + content: [{ type: "text", text: "Done! Shutdown requested." }], + details: { environment: params.environment }, + }; + }, + }); +} diff --git a/examples/extensions/snake.ts b/examples/extensions/snake.ts new file mode 100644 index 0000000..1b58edf --- /dev/null +++ b/examples/extensions/snake.ts @@ -0,0 +1,343 @@ +/** + * Snake game extension - play snake with /snake command + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { matchesKey, visibleWidth } from "@earendil-works/pi-tui"; + +const GAME_WIDTH = 40; +const GAME_HEIGHT = 15; +const TICK_MS = 100; + +type Direction = "up" | "down" | "left" | "right"; +type Point = { x: number; y: number }; + +interface GameState { + snake: Point[]; + food: Point; + direction: Direction; + nextDirection: Direction; + score: number; + gameOver: boolean; + highScore: number; +} + +function createInitialState(): GameState { + const startX = Math.floor(GAME_WIDTH / 2); + const startY = Math.floor(GAME_HEIGHT / 2); + return { + snake: [ + { x: startX, y: startY }, + { x: startX - 1, y: startY }, + { x: startX - 2, y: startY }, + ], + food: spawnFood([{ x: startX, y: startY }]), + direction: "right", + nextDirection: "right", + score: 0, + gameOver: false, + highScore: 0, + }; +} + +function spawnFood(snake: Point[]): Point { + let food: Point; + do { + food = { + x: Math.floor(Math.random() * GAME_WIDTH), + y: Math.floor(Math.random() * GAME_HEIGHT), + }; + } while (snake.some((s) => s.x === food.x && s.y === food.y)); + return food; +} + +class SnakeComponent { + private state: GameState; + private interval: ReturnType | null = null; + private onClose: () => void; + private onSave: (state: GameState | null) => void; + private tui: { requestRender: () => void }; + private cachedLines: string[] = []; + private cachedWidth = 0; + private version = 0; + private cachedVersion = -1; + private paused: boolean; + + constructor( + tui: { requestRender: () => void }, + onClose: () => void, + onSave: (state: GameState | null) => void, + savedState?: GameState, + ) { + this.tui = tui; + if (savedState && !savedState.gameOver) { + // Resume from saved state, start paused + this.state = savedState; + this.paused = true; + } else { + // New game or saved game was over + this.state = createInitialState(); + if (savedState) { + this.state.highScore = savedState.highScore; + } + this.paused = false; + this.startGame(); + } + this.onClose = onClose; + this.onSave = onSave; + } + + private startGame(): void { + this.interval = setInterval(() => { + if (!this.state.gameOver) { + this.tick(); + this.version++; + this.tui.requestRender(); + } + }, TICK_MS); + } + + private tick(): void { + // Apply queued direction change + this.state.direction = this.state.nextDirection; + + // Calculate new head position + const head = this.state.snake[0]; + let newHead: Point; + + switch (this.state.direction) { + case "up": + newHead = { x: head.x, y: head.y - 1 }; + break; + case "down": + newHead = { x: head.x, y: head.y + 1 }; + break; + case "left": + newHead = { x: head.x - 1, y: head.y }; + break; + case "right": + newHead = { x: head.x + 1, y: head.y }; + break; + } + + // Check wall collision + if (newHead.x < 0 || newHead.x >= GAME_WIDTH || newHead.y < 0 || newHead.y >= GAME_HEIGHT) { + this.state.gameOver = true; + return; + } + + // Check self collision + if (this.state.snake.some((s) => s.x === newHead.x && s.y === newHead.y)) { + this.state.gameOver = true; + return; + } + + // Move snake + this.state.snake.unshift(newHead); + + // Check food collision + if (newHead.x === this.state.food.x && newHead.y === this.state.food.y) { + this.state.score += 10; + if (this.state.score > this.state.highScore) { + this.state.highScore = this.state.score; + } + this.state.food = spawnFood(this.state.snake); + } else { + this.state.snake.pop(); + } + } + + handleInput(data: string): void { + // If paused (resuming), wait for any key + if (this.paused) { + if (matchesKey(data, "escape") || data === "q" || data === "Q") { + // Quit without clearing save + this.dispose(); + this.onClose(); + return; + } + // Any other key resumes + this.paused = false; + this.startGame(); + return; + } + + // ESC to pause and save + if (matchesKey(data, "escape")) { + this.dispose(); + this.onSave(this.state); + this.onClose(); + return; + } + + // Q to quit without saving (clears saved state) + if (data === "q" || data === "Q") { + this.dispose(); + this.onSave(null); // Clear saved state + this.onClose(); + return; + } + + // Arrow keys or WASD + if (matchesKey(data, "up") || data === "w" || data === "W") { + if (this.state.direction !== "down") this.state.nextDirection = "up"; + } else if (matchesKey(data, "down") || data === "s" || data === "S") { + if (this.state.direction !== "up") this.state.nextDirection = "down"; + } else if (matchesKey(data, "right") || data === "d" || data === "D") { + if (this.state.direction !== "left") this.state.nextDirection = "right"; + } else if (matchesKey(data, "left") || data === "a" || data === "A") { + if (this.state.direction !== "right") this.state.nextDirection = "left"; + } + + // Restart on game over + if (this.state.gameOver && (data === "r" || data === "R" || data === " ")) { + const highScore = this.state.highScore; + this.state = createInitialState(); + this.state.highScore = highScore; + this.onSave(null); // Clear saved state on restart + this.version++; + this.tui.requestRender(); + } + } + + invalidate(): void { + this.cachedWidth = 0; + } + + render(width: number): string[] { + if (width === this.cachedWidth && this.cachedVersion === this.version) { + return this.cachedLines; + } + + const lines: string[] = []; + + // Each game cell is 2 chars wide to appear square (terminal cells are ~2:1 aspect) + const cellWidth = 2; + const effectiveWidth = Math.min(GAME_WIDTH, Math.floor((width - 4) / cellWidth)); + const effectiveHeight = GAME_HEIGHT; + + // Colors + const dim = (s: string) => `\x1b[2m${s}\x1b[22m`; + const green = (s: string) => `\x1b[32m${s}\x1b[0m`; + const red = (s: string) => `\x1b[31m${s}\x1b[0m`; + const yellow = (s: string) => `\x1b[33m${s}\x1b[0m`; + const bold = (s: string) => `\x1b[1m${s}\x1b[22m`; + + const boxWidth = effectiveWidth * cellWidth; + + // Helper to pad content inside box + const boxLine = (content: string) => { + const contentLen = visibleWidth(content); + const padding = Math.max(0, boxWidth - contentLen); + return dim(" │") + content + " ".repeat(padding) + dim("│"); + }; + + // Top border + lines.push(this.padLine(dim(` ╭${"─".repeat(boxWidth)}╮`), width)); + + // Header with score + const scoreText = `Score: ${bold(yellow(String(this.state.score)))}`; + const highText = `High: ${bold(yellow(String(this.state.highScore)))}`; + const title = `${bold(green("SNAKE"))} │ ${scoreText} │ ${highText}`; + lines.push(this.padLine(boxLine(title), width)); + + // Separator + lines.push(this.padLine(dim(` ├${"─".repeat(boxWidth)}┤`), width)); + + // Game grid + for (let y = 0; y < effectiveHeight; y++) { + let row = ""; + for (let x = 0; x < effectiveWidth; x++) { + const isHead = this.state.snake[0].x === x && this.state.snake[0].y === y; + const isBody = this.state.snake.slice(1).some((s) => s.x === x && s.y === y); + const isFood = this.state.food.x === x && this.state.food.y === y; + + if (isHead) { + row += green("██"); // Snake head (2 chars) + } else if (isBody) { + row += green("▓▓"); // Snake body (2 chars) + } else if (isFood) { + row += red("◆ "); // Food (2 chars) + } else { + row += " "; // Empty cell (2 spaces) + } + } + lines.push(this.padLine(dim(" │") + row + dim("│"), width)); + } + + // Separator + lines.push(this.padLine(dim(` ├${"─".repeat(boxWidth)}┤`), width)); + + // Footer + let footer: string; + if (this.paused) { + footer = `${yellow(bold("PAUSED"))} Press any key to continue, ${bold("Q")} to quit`; + } else if (this.state.gameOver) { + footer = `${red(bold("GAME OVER!"))} Press ${bold("R")} to restart, ${bold("Q")} to quit`; + } else { + footer = `↑↓←→ or WASD to move, ${bold("ESC")} pause, ${bold("Q")} quit`; + } + lines.push(this.padLine(boxLine(footer), width)); + + // Bottom border + lines.push(this.padLine(dim(` ╰${"─".repeat(boxWidth)}╯`), width)); + + this.cachedLines = lines; + this.cachedWidth = width; + this.cachedVersion = this.version; + + return lines; + } + + private padLine(line: string, width: number): string { + // Calculate visible length (strip ANSI codes) + const visibleLen = line.replace(/\x1b\[[0-9;]*m/g, "").length; + const padding = Math.max(0, width - visibleLen); + return line + " ".repeat(padding); + } + + dispose(): void { + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + } +} + +const SNAKE_SAVE_TYPE = "snake-save"; + +export default function (pi: ExtensionAPI) { + pi.registerCommand("snake", { + description: "Play Snake!", + + handler: async (_args, ctx) => { + if (ctx.mode !== "tui") { + ctx.ui.notify("Snake requires interactive mode", "error"); + return; + } + + // Load saved state from session + const entries = ctx.sessionManager.getEntries(); + let savedState: GameState | undefined; + for (let i = entries.length - 1; i >= 0; i--) { + const entry = entries[i]; + if (entry.type === "custom" && entry.customType === SNAKE_SAVE_TYPE) { + savedState = entry.data as GameState; + break; + } + } + + await ctx.ui.custom((tui, _theme, _kb, done) => { + return new SnakeComponent( + tui, + () => done(undefined), + (state) => { + // Save or clear state + pi.appendEntry(SNAKE_SAVE_TYPE, state); + }, + savedState, + ); + }); + }, + }); +} diff --git a/examples/extensions/space-invaders.ts b/examples/extensions/space-invaders.ts new file mode 100644 index 0000000..306c5ac --- /dev/null +++ b/examples/extensions/space-invaders.ts @@ -0,0 +1,560 @@ +/** + * Space Invaders game extension - play with /invaders command + * Uses Kitty keyboard protocol for smooth movement (press/release detection) + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { isKeyRelease, Key, matchesKey, visibleWidth } from "@earendil-works/pi-tui"; + +const GAME_WIDTH = 60; +const GAME_HEIGHT = 24; +const TICK_MS = 50; +const PLAYER_Y = GAME_HEIGHT - 2; +const ALIEN_ROWS = 5; +const ALIEN_COLS = 11; +const ALIEN_START_Y = 2; + +type Point = { x: number; y: number }; + +interface Bullet extends Point { + direction: -1 | 1; // -1 = up (player), 1 = down (alien) +} + +interface Alien extends Point { + type: number; // 0, 1, 2 for different alien types + alive: boolean; +} + +interface Shield { + x: number; + segments: boolean[][]; // 4x3 grid of destructible segments +} + +interface GameState { + player: { x: number; lives: number }; + aliens: Alien[]; + alienDirection: 1 | -1; + alienMoveCounter: number; + alienMoveDelay: number; + alienDropping: boolean; + bullets: Bullet[]; + shields: Shield[]; + score: number; + highScore: number; + level: number; + gameOver: boolean; + victory: boolean; + alienShootCounter: number; +} + +interface KeyState { + left: boolean; + right: boolean; + fire: boolean; +} + +function createShields(): Shield[] { + const shields: Shield[] = []; + const shieldPositions = [8, 22, 36, 50]; + for (const x of shieldPositions) { + shields.push({ + x, + segments: [ + [true, true, true, true], + [true, true, true, true], + [true, false, false, true], + ], + }); + } + return shields; +} + +function createAliens(): Alien[] { + const aliens: Alien[] = []; + for (let row = 0; row < ALIEN_ROWS; row++) { + const type = row === 0 ? 2 : row < 3 ? 1 : 0; + for (let col = 0; col < ALIEN_COLS; col++) { + aliens.push({ + x: 4 + col * 5, + y: ALIEN_START_Y + row * 2, + type, + alive: true, + }); + } + } + return aliens; +} + +function createInitialState(highScore = 0, level = 1): GameState { + return { + player: { x: Math.floor(GAME_WIDTH / 2), lives: 3 }, + aliens: createAliens(), + alienDirection: 1, + alienMoveCounter: 0, + alienMoveDelay: Math.max(5, 20 - level * 2), + alienDropping: false, + bullets: [], + shields: createShields(), + score: 0, + highScore, + level, + gameOver: false, + victory: false, + alienShootCounter: 0, + }; +} + +class SpaceInvadersComponent { + private state: GameState; + private keys: KeyState = { left: false, right: false, fire: false }; + private interval: ReturnType | null = null; + private onClose: () => void; + private onSave: (state: GameState | null) => void; + private tui: { requestRender: () => void }; + private cachedLines: string[] = []; + private cachedWidth = 0; + private version = 0; + private cachedVersion = -1; + private paused: boolean; + private fireCooldown = 0; + private playerMoveCounter = 0; + + // Opt-in to key release events for smooth movement + wantsKeyRelease = true; + + constructor( + tui: { requestRender: () => void }, + onClose: () => void, + onSave: (state: GameState | null) => void, + savedState?: GameState, + ) { + this.tui = tui; + if (savedState && !savedState.gameOver && !savedState.victory) { + this.state = savedState; + this.paused = true; + } else { + this.state = createInitialState(savedState?.highScore); + this.paused = false; + this.startGame(); + } + this.onClose = onClose; + this.onSave = onSave; + } + + private startGame(): void { + this.interval = setInterval(() => { + if (!this.state.gameOver && !this.state.victory) { + this.tick(); + this.version++; + this.tui.requestRender(); + } + }, TICK_MS); + } + + private tick(): void { + // Player movement (smooth, every other tick) + this.playerMoveCounter++; + if (this.playerMoveCounter >= 2) { + this.playerMoveCounter = 0; + if (this.keys.left && this.state.player.x > 2) { + this.state.player.x--; + } + if (this.keys.right && this.state.player.x < GAME_WIDTH - 3) { + this.state.player.x++; + } + } + + // Fire cooldown + if (this.fireCooldown > 0) this.fireCooldown--; + + // Player shooting + if (this.keys.fire && this.fireCooldown === 0) { + const playerBullets = this.state.bullets.filter((b) => b.direction === -1); + if (playerBullets.length < 2) { + this.state.bullets.push({ x: this.state.player.x, y: PLAYER_Y - 1, direction: -1 }); + this.fireCooldown = 8; + } + } + + // Move bullets + this.state.bullets = this.state.bullets.filter((bullet) => { + bullet.y += bullet.direction; + return bullet.y >= 0 && bullet.y < GAME_HEIGHT; + }); + + // Alien movement + this.state.alienMoveCounter++; + if (this.state.alienMoveCounter >= this.state.alienMoveDelay) { + this.state.alienMoveCounter = 0; + this.moveAliens(); + } + + // Alien shooting + this.state.alienShootCounter++; + if (this.state.alienShootCounter >= 30) { + this.state.alienShootCounter = 0; + this.alienShoot(); + } + + // Collision detection + this.checkCollisions(); + + // Check victory + if (this.state.aliens.every((a) => !a.alive)) { + this.state.victory = true; + } + } + + private moveAliens(): void { + const aliveAliens = this.state.aliens.filter((a) => a.alive); + if (aliveAliens.length === 0) return; + + if (this.state.alienDropping) { + // Drop down + for (const alien of aliveAliens) { + alien.y++; + if (alien.y >= PLAYER_Y - 1) { + this.state.gameOver = true; + return; + } + } + this.state.alienDropping = false; + } else { + // Check if we need to change direction + const minX = Math.min(...aliveAliens.map((a) => a.x)); + const maxX = Math.max(...aliveAliens.map((a) => a.x)); + + if ( + (this.state.alienDirection === 1 && maxX >= GAME_WIDTH - 3) || + (this.state.alienDirection === -1 && minX <= 2) + ) { + this.state.alienDirection *= -1; + this.state.alienDropping = true; + } else { + // Move horizontally + for (const alien of aliveAliens) { + alien.x += this.state.alienDirection; + } + } + } + + // Speed up as fewer aliens remain + const aliveCount = aliveAliens.length; + if (aliveCount <= 5) { + this.state.alienMoveDelay = 1; + } else if (aliveCount <= 10) { + this.state.alienMoveDelay = 2; + } else if (aliveCount <= 20) { + this.state.alienMoveDelay = 3; + } + } + + private alienShoot(): void { + const aliveAliens = this.state.aliens.filter((a) => a.alive); + if (aliveAliens.length === 0) return; + + // Find bottom-most alien in each column + const columns = new Map(); + for (const alien of aliveAliens) { + const existing = columns.get(alien.x); + if (!existing || alien.y > existing.y) { + columns.set(alien.x, alien); + } + } + + // Random column shoots + const shooters = Array.from(columns.values()); + if (shooters.length > 0 && this.state.bullets.filter((b) => b.direction === 1).length < 3) { + const shooter = shooters[Math.floor(Math.random() * shooters.length)]; + this.state.bullets.push({ x: shooter.x, y: shooter.y + 1, direction: 1 }); + } + } + + private checkCollisions(): void { + const bulletsToRemove = new Set(); + + for (const bullet of this.state.bullets) { + // Player bullets hitting aliens + if (bullet.direction === -1) { + for (const alien of this.state.aliens) { + if (alien.alive && Math.abs(bullet.x - alien.x) <= 1 && bullet.y === alien.y) { + alien.alive = false; + bulletsToRemove.add(bullet); + const points = [10, 20, 30][alien.type]; + this.state.score += points; + if (this.state.score > this.state.highScore) { + this.state.highScore = this.state.score; + } + break; + } + } + } + + // Alien bullets hitting player + if (bullet.direction === 1) { + if (Math.abs(bullet.x - this.state.player.x) <= 1 && bullet.y === PLAYER_Y) { + bulletsToRemove.add(bullet); + this.state.player.lives--; + if (this.state.player.lives <= 0) { + this.state.gameOver = true; + } + } + } + + // Bullets hitting shields + for (const shield of this.state.shields) { + const relX = bullet.x - shield.x; + const relY = bullet.y - (PLAYER_Y - 5); + if (relX >= 0 && relX < 4 && relY >= 0 && relY < 3) { + if (shield.segments[relY][relX]) { + shield.segments[relY][relX] = false; + bulletsToRemove.add(bullet); + } + } + } + } + + this.state.bullets = this.state.bullets.filter((b) => !bulletsToRemove.has(b)); + } + + handleInput(data: string): void { + const released = isKeyRelease(data); + + // Pause handling + if (this.paused && !released) { + if (matchesKey(data, Key.escape) || data === "q" || data === "Q") { + this.dispose(); + this.onClose(); + return; + } + this.paused = false; + this.startGame(); + return; + } + + // ESC to pause and save + if (!released && matchesKey(data, Key.escape)) { + this.dispose(); + this.onSave(this.state); + this.onClose(); + return; + } + + // Q to quit without saving + if (!released && (data === "q" || data === "Q")) { + this.dispose(); + this.onSave(null); + this.onClose(); + return; + } + + // Movement keys (track press/release state) + if (matchesKey(data, Key.left) || data === "a" || data === "A" || matchesKey(data, "a")) { + this.keys.left = !released; + } + if (matchesKey(data, Key.right) || data === "d" || data === "D" || matchesKey(data, "d")) { + this.keys.right = !released; + } + + // Fire key + if (matchesKey(data, Key.space) || data === " " || data === "f" || data === "F" || matchesKey(data, "f")) { + this.keys.fire = !released; + } + + // Restart on game over or victory + if (!released && (this.state.gameOver || this.state.victory)) { + if (data === "r" || data === "R" || data === " ") { + const highScore = this.state.highScore; + const nextLevel = this.state.victory ? this.state.level + 1 : 1; + this.state = createInitialState(highScore, nextLevel); + this.keys = { left: false, right: false, fire: false }; + this.onSave(null); + this.version++; + this.tui.requestRender(); + } + } + } + + invalidate(): void { + this.cachedWidth = 0; + } + + render(width: number): string[] { + if (width === this.cachedWidth && this.cachedVersion === this.version) { + return this.cachedLines; + } + + const lines: string[] = []; + + // Colors + const dim = (s: string) => `\x1b[2m${s}\x1b[22m`; + const green = (s: string) => `\x1b[32m${s}\x1b[0m`; + const red = (s: string) => `\x1b[31m${s}\x1b[0m`; + const yellow = (s: string) => `\x1b[33m${s}\x1b[0m`; + const cyan = (s: string) => `\x1b[36m${s}\x1b[0m`; + const magenta = (s: string) => `\x1b[35m${s}\x1b[0m`; + const white = (s: string) => `\x1b[97m${s}\x1b[0m`; + const bold = (s: string) => `\x1b[1m${s}\x1b[22m`; + + const boxWidth = GAME_WIDTH; + + const boxLine = (content: string) => { + const contentLen = visibleWidth(content); + const padding = Math.max(0, boxWidth - contentLen); + return dim(" │") + content + " ".repeat(padding) + dim("│"); + }; + + // Top border + lines.push(this.padLine(dim(` ╭${"─".repeat(boxWidth)}╮`), width)); + + // Header + const title = `${bold(green("SPACE INVADERS"))}`; + const scoreText = `Score: ${bold(yellow(String(this.state.score)))}`; + const highText = `Hi: ${bold(yellow(String(this.state.highScore)))}`; + const levelText = `Lv: ${bold(cyan(String(this.state.level)))}`; + const livesText = `${red("♥".repeat(this.state.player.lives))}`; + const header = `${title} │ ${scoreText} │ ${highText} │ ${levelText} │ ${livesText}`; + lines.push(this.padLine(boxLine(header), width)); + + // Separator + lines.push(this.padLine(dim(` ├${"─".repeat(boxWidth)}┤`), width)); + + // Game grid + for (let y = 0; y < GAME_HEIGHT; y++) { + let row = ""; + for (let x = 0; x < GAME_WIDTH; x++) { + let char = " "; + let colored = false; + + // Check aliens + for (const alien of this.state.aliens) { + if (alien.alive && alien.y === y && Math.abs(alien.x - x) <= 1) { + const sprites = [ + x === alien.x ? "▼" : "╲╱"[x < alien.x ? 0 : 1], + x === alien.x ? "◆" : "╱╲"[x < alien.x ? 0 : 1], + x === alien.x ? "☆" : "◄►"[x < alien.x ? 0 : 1], + ]; + const colors = [green, cyan, magenta]; + char = colors[alien.type](sprites[alien.type]); + colored = true; + break; + } + } + + // Check shields + if (!colored) { + for (const shield of this.state.shields) { + const relX = x - shield.x; + const relY = y - (PLAYER_Y - 5); + if (relX >= 0 && relX < 4 && relY >= 0 && relY < 3) { + if (shield.segments[relY][relX]) { + char = dim("█"); + colored = true; + } + break; + } + } + } + + // Check player + if (!colored && y === PLAYER_Y && Math.abs(x - this.state.player.x) <= 1) { + if (x === this.state.player.x) { + char = white("▲"); + } else { + char = white("═"); + } + colored = true; + } + + // Check bullets + if (!colored) { + for (const bullet of this.state.bullets) { + if (bullet.x === x && bullet.y === y) { + char = bullet.direction === -1 ? yellow("│") : red("│"); + colored = true; + break; + } + } + } + + row += colored ? char : " "; + } + lines.push(this.padLine(dim(" │") + row + dim("│"), width)); + } + + // Separator + lines.push(this.padLine(dim(` ├${"─".repeat(boxWidth)}┤`), width)); + + // Footer + let footer: string; + if (this.paused) { + footer = `${yellow(bold("PAUSED"))} Press any key to continue, ${bold("Q")} to quit`; + } else if (this.state.gameOver) { + footer = `${red(bold("GAME OVER!"))} Press ${bold("R")} to restart, ${bold("Q")} to quit`; + } else if (this.state.victory) { + footer = `${green(bold("VICTORY!"))} Press ${bold("R")} for level ${this.state.level + 1}, ${bold("Q")} to quit`; + } else { + footer = `←→ or AD to move, ${bold("SPACE")}/F to fire, ${bold("ESC")} pause, ${bold("Q")} quit`; + } + lines.push(this.padLine(boxLine(footer), width)); + + // Bottom border + lines.push(this.padLine(dim(` ╰${"─".repeat(boxWidth)}╯`), width)); + + this.cachedLines = lines; + this.cachedWidth = width; + this.cachedVersion = this.version; + + return lines; + } + + private padLine(line: string, width: number): string { + const visibleLen = line.replace(/\x1b\[[0-9;]*m/g, "").length; + const padding = Math.max(0, width - visibleLen); + return line + " ".repeat(padding); + } + + dispose(): void { + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + } +} + +const INVADERS_SAVE_TYPE = "space-invaders-save"; + +export default function (pi: ExtensionAPI) { + pi.registerCommand("invaders", { + description: "Play Space Invaders!", + + handler: async (_args, ctx) => { + if (ctx.mode !== "tui") { + ctx.ui.notify("Space Invaders requires interactive mode", "error"); + return; + } + + // Load saved state from session + const entries = ctx.sessionManager.getEntries(); + let savedState: GameState | undefined; + for (let i = entries.length - 1; i >= 0; i--) { + const entry = entries[i]; + if (entry.type === "custom" && entry.customType === INVADERS_SAVE_TYPE) { + savedState = entry.data as GameState; + break; + } + } + + await ctx.ui.custom((tui, _theme, _kb, done) => { + return new SpaceInvadersComponent( + tui, + () => done(undefined), + (state) => { + pi.appendEntry(INVADERS_SAVE_TYPE, state); + }, + savedState, + ); + }); + }, + }); +} diff --git a/examples/extensions/ssh.ts b/examples/extensions/ssh.ts new file mode 100644 index 0000000..6ca4511 --- /dev/null +++ b/examples/extensions/ssh.ts @@ -0,0 +1,220 @@ +/** + * SSH Remote Execution Example + * + * Demonstrates delegating tool operations to a remote machine via SSH. + * When --ssh is provided, read/write/edit/bash run on the remote. + * + * Usage: + * pi -e ./ssh.ts --ssh user@host + * pi -e ./ssh.ts --ssh user@host:/remote/path + * + * Requirements: + * - SSH key-based auth (no password prompts) + * - bash on remote + */ + +import { spawn } from "node:child_process"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { + type BashOperations, + createBashTool, + createEditTool, + createReadTool, + createWriteTool, + type EditOperations, + type ReadOperations, + type WriteOperations, +} from "@earendil-works/pi-coding-agent"; + +function sshExec(remote: string, command: string): Promise { + return new Promise((resolve, reject) => { + const child = spawn("ssh", [remote, command], { stdio: ["ignore", "pipe", "pipe"] }); + const chunks: Buffer[] = []; + const errChunks: Buffer[] = []; + child.stdout.on("data", (data) => chunks.push(data)); + child.stderr.on("data", (data) => errChunks.push(data)); + child.on("error", reject); + child.on("close", (code) => { + if (code !== 0) { + reject(new Error(`SSH failed (${code}): ${Buffer.concat(errChunks).toString()}`)); + } else { + resolve(Buffer.concat(chunks)); + } + }); + }); +} + +function createRemoteReadOps(remote: string, remoteCwd: string, localCwd: string): ReadOperations { + const toRemote = (p: string) => p.replace(localCwd, remoteCwd); + return { + readFile: (p) => sshExec(remote, `cat ${JSON.stringify(toRemote(p))}`), + access: (p) => sshExec(remote, `test -r ${JSON.stringify(toRemote(p))}`).then(() => {}), + detectImageMimeType: async (p) => { + try { + const r = await sshExec(remote, `file --mime-type -b ${JSON.stringify(toRemote(p))}`); + const m = r.toString().trim(); + return ["image/jpeg", "image/png", "image/gif", "image/webp"].includes(m) ? m : null; + } catch { + return null; + } + }, + }; +} + +function createRemoteWriteOps(remote: string, remoteCwd: string, localCwd: string): WriteOperations { + const toRemote = (p: string) => p.replace(localCwd, remoteCwd); + return { + writeFile: async (p, content) => { + const b64 = Buffer.from(content).toString("base64"); + await sshExec(remote, `echo ${JSON.stringify(b64)} | base64 -d > ${JSON.stringify(toRemote(p))}`); + }, + mkdir: (dir) => sshExec(remote, `mkdir -p ${JSON.stringify(toRemote(dir))}`).then(() => {}), + }; +} + +function createRemoteEditOps(remote: string, remoteCwd: string, localCwd: string): EditOperations { + const r = createRemoteReadOps(remote, remoteCwd, localCwd); + const w = createRemoteWriteOps(remote, remoteCwd, localCwd); + return { readFile: r.readFile, access: r.access, writeFile: w.writeFile }; +} + +function createRemoteBashOps(remote: string, remoteCwd: string, localCwd: string): BashOperations { + const toRemote = (p: string) => p.replace(localCwd, remoteCwd); + return { + exec: (command, cwd, { onData, signal, timeout }) => + new Promise((resolve, reject) => { + const cmd = `cd ${JSON.stringify(toRemote(cwd))} && ${command}`; + const child = spawn("ssh", [remote, cmd], { stdio: ["ignore", "pipe", "pipe"] }); + let timedOut = false; + const timer = timeout + ? setTimeout(() => { + timedOut = true; + child.kill(); + }, timeout * 1000) + : undefined; + child.stdout.on("data", onData); + child.stderr.on("data", onData); + child.on("error", (e) => { + if (timer) clearTimeout(timer); + reject(e); + }); + const onAbort = () => child.kill(); + signal?.addEventListener("abort", onAbort, { once: true }); + child.on("close", (code) => { + if (timer) clearTimeout(timer); + signal?.removeEventListener("abort", onAbort); + if (signal?.aborted) reject(new Error("aborted")); + else if (timedOut) reject(new Error(`timeout:${timeout}`)); + else resolve({ exitCode: code }); + }); + }), + }; +} + +export default function (pi: ExtensionAPI) { + pi.registerFlag("ssh", { description: "SSH remote: user@host or user@host:/path", type: "string" }); + + const localCwd = process.cwd(); + const localRead = createReadTool(localCwd); + const localWrite = createWriteTool(localCwd); + const localEdit = createEditTool(localCwd); + const localBash = createBashTool(localCwd); + + // Resolved lazily on session_start (CLI flags not available during factory) + let resolvedSsh: { remote: string; remoteCwd: string } | null = null; + + const getSsh = () => resolvedSsh; + + pi.registerTool({ + ...localRead, + async execute(id, params, signal, onUpdate, _ctx) { + const ssh = getSsh(); + if (ssh) { + const tool = createReadTool(localCwd, { + operations: createRemoteReadOps(ssh.remote, ssh.remoteCwd, localCwd), + }); + return tool.execute(id, params, signal, onUpdate); + } + return localRead.execute(id, params, signal, onUpdate); + }, + }); + + pi.registerTool({ + ...localWrite, + async execute(id, params, signal, onUpdate, _ctx) { + const ssh = getSsh(); + if (ssh) { + const tool = createWriteTool(localCwd, { + operations: createRemoteWriteOps(ssh.remote, ssh.remoteCwd, localCwd), + }); + return tool.execute(id, params, signal, onUpdate); + } + return localWrite.execute(id, params, signal, onUpdate); + }, + }); + + pi.registerTool({ + ...localEdit, + async execute(id, params, signal, onUpdate, _ctx) { + const ssh = getSsh(); + if (ssh) { + const tool = createEditTool(localCwd, { + operations: createRemoteEditOps(ssh.remote, ssh.remoteCwd, localCwd), + }); + return tool.execute(id, params, signal, onUpdate); + } + return localEdit.execute(id, params, signal, onUpdate); + }, + }); + + pi.registerTool({ + ...localBash, + async execute(id, params, signal, onUpdate, _ctx) { + const ssh = getSsh(); + if (ssh) { + const tool = createBashTool(localCwd, { + operations: createRemoteBashOps(ssh.remote, ssh.remoteCwd, localCwd), + }); + return tool.execute(id, params, signal, onUpdate); + } + return localBash.execute(id, params, signal, onUpdate); + }, + }); + + pi.on("session_start", async (_event, ctx) => { + // Resolve SSH config now that CLI flags are available + const arg = pi.getFlag("ssh") as string | undefined; + if (arg) { + if (arg.includes(":")) { + const [remote, path] = arg.split(":"); + resolvedSsh = { remote, remoteCwd: path }; + } else { + // No path given, evaluate pwd on remote + const remote = arg; + const pwd = (await sshExec(remote, "pwd")).toString().trim(); + resolvedSsh = { remote, remoteCwd: pwd }; + } + ctx.ui.setStatus("ssh", ctx.ui.theme.fg("accent", `SSH: ${resolvedSsh.remote}:${resolvedSsh.remoteCwd}`)); + ctx.ui.notify(`SSH mode: ${resolvedSsh.remote}:${resolvedSsh.remoteCwd}`, "info"); + } + }); + + // Handle user ! commands via SSH + pi.on("user_bash", (_event) => { + const ssh = getSsh(); + if (!ssh) return; // No SSH, use local execution + return { operations: createRemoteBashOps(ssh.remote, ssh.remoteCwd, localCwd) }; + }); + + // Replace local cwd with remote cwd in system prompt + pi.on("before_agent_start", async (event) => { + const ssh = getSsh(); + if (ssh) { + const modified = event.systemPrompt.replace( + `Current working directory: ${localCwd}`, + `Current working directory: ${ssh.remoteCwd} (via SSH: ${ssh.remote})`, + ); + return { systemPrompt: modified }; + } + }); +} diff --git a/examples/extensions/status-line.ts b/examples/extensions/status-line.ts new file mode 100644 index 0000000..6c4a3a4 --- /dev/null +++ b/examples/extensions/status-line.ts @@ -0,0 +1,32 @@ +/** + * Status Line Extension + * + * Demonstrates ctx.ui.setStatus() for displaying persistent status text in the footer. + * Shows turn progress with themed colors. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + let turnCount = 0; + + pi.on("session_start", async (_event, ctx) => { + const theme = ctx.ui.theme; + ctx.ui.setStatus("status-demo", theme.fg("dim", "Ready")); + }); + + pi.on("turn_start", async (_event, ctx) => { + turnCount++; + const theme = ctx.ui.theme; + const spinner = theme.fg("accent", "●"); + const text = theme.fg("dim", ` Turn ${turnCount}...`); + ctx.ui.setStatus("status-demo", spinner + text); + }); + + pi.on("turn_end", async (_event, ctx) => { + const theme = ctx.ui.theme; + const check = theme.fg("success", "✓"); + const text = theme.fg("dim", ` Turn ${turnCount} complete`); + ctx.ui.setStatus("status-demo", check + text); + }); +} diff --git a/examples/extensions/structured-output.ts b/examples/extensions/structured-output.ts new file mode 100644 index 0000000..1333137 --- /dev/null +++ b/examples/extensions/structured-output.ts @@ -0,0 +1,65 @@ +/** + * Structured Output Tool + * + * Demonstrates `terminate: true` so the agent can end on a tool call + * without paying for an extra follow-up LLM turn. + */ + +import { defineTool, type ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { Text } from "@earendil-works/pi-tui"; +import { Type } from "typebox"; + +interface StructuredOutputDetails { + headline: string; + summary: string; + actionItems: string[]; +} + +const structuredOutputTool = defineTool({ + name: "structured_output", + label: "Structured Output", + description: + "Return a final structured answer. Use this as your last action when the user asks for structured output or a machine-readable summary.", + promptSnippet: "Emit a final structured answer as a terminating tool result", + promptGuidelines: [ + "Use structured_output as your final action when the user asks for structured output, JSON-like output, or a machine-readable summary.", + "After calling structured_output, do not emit another assistant response in the same turn.", + ], + parameters: Type.Object({ + headline: Type.String({ description: "Short title for the result" }), + summary: Type.String({ description: "One-paragraph summary" }), + actionItems: Type.Array(Type.String(), { description: "Concrete next steps or key bullets" }), + }), + + async execute(_toolCallId, params) { + return { + content: [{ type: "text", text: `Saved structured output: ${params.headline}` }], + details: { + headline: params.headline, + summary: params.summary, + actionItems: params.actionItems, + } satisfies StructuredOutputDetails, + terminate: true, + }; + }, + + renderResult(result, _options, theme) { + const details = result.details as StructuredOutputDetails | undefined; + if (!details) { + const text = result.content[0]; + return new Text(text?.type === "text" ? text.text : "", 0, 0); + } + + const lines = [ + theme.fg("toolTitle", theme.bold(details.headline)), + theme.fg("text", details.summary), + "", + ...details.actionItems.map((item, index) => theme.fg("muted", `${index + 1}. ${item}`)), + ]; + return new Text(lines.join("\n"), 0, 0); + }, +}); + +export default function (pi: ExtensionAPI) { + pi.registerTool(structuredOutputTool); +} diff --git a/examples/extensions/subagent/README.md b/examples/extensions/subagent/README.md new file mode 100644 index 0000000..f98b645 --- /dev/null +++ b/examples/extensions/subagent/README.md @@ -0,0 +1,175 @@ +# Subagent Example + +Delegate tasks to specialized subagents with isolated context windows. + +## Features + +- **Isolated context**: Each subagent runs in a separate `pi` process +- **Streaming output**: See tool calls and progress as they happen +- **Parallel streaming**: All parallel tasks stream updates simultaneously +- **Markdown rendering**: Final output rendered with proper formatting (expanded view) +- **Usage tracking**: Shows turns, tokens, cost, and context usage per agent +- **Abort support**: Ctrl+C propagates to kill subagent processes + +## Structure + +``` +subagent/ +├── README.md # This file +├── index.ts # The extension (entry point) +├── agents.ts # Agent discovery logic +├── agents/ # Sample agent definitions +│ ├── scout.md # Fast recon, returns compressed context +│ ├── planner.md # Creates implementation plans +│ ├── reviewer.md # Code review +│ └── worker.md # General-purpose (full capabilities) +└── prompts/ # Workflow presets (prompt templates) + ├── implement.md # scout -> planner -> worker + ├── scout-and-plan.md # scout -> planner (no implementation) + └── implement-and-review.md # worker -> reviewer -> worker +``` + +## Installation + +From the repository root, symlink the files: + +```bash +# Symlink the extension (must be in a subdirectory with index.ts) +mkdir -p ~/.pi/agent/extensions/subagent +ln -sf "$(pwd)/packages/coding-agent/examples/extensions/subagent/index.ts" ~/.pi/agent/extensions/subagent/index.ts +ln -sf "$(pwd)/packages/coding-agent/examples/extensions/subagent/agents.ts" ~/.pi/agent/extensions/subagent/agents.ts + +# Symlink agents +mkdir -p ~/.pi/agent/agents +for f in packages/coding-agent/examples/extensions/subagent/agents/*.md; do + ln -sf "$(pwd)/$f" ~/.pi/agent/agents/$(basename "$f") +done + +# Symlink workflow prompts +mkdir -p ~/.pi/agent/prompts +for f in packages/coding-agent/examples/extensions/subagent/prompts/*.md; do + ln -sf "$(pwd)/$f" ~/.pi/agent/prompts/$(basename "$f") +done +``` + +## Security Model + +This tool executes a separate `pi` subprocess with a delegated system prompt and tool/model configuration. + +**Project-local agents** (`.pi/agents/*.md`) are repo-controlled prompts that can instruct the model to read files, run bash commands, etc. + +**Default behavior:** Only loads **user-level agents** from `~/.pi/agent/agents`. + +To enable project-local agents, pass `agentScope: "both"` (or `"project"`). Only do this for repositories you trust. + +When running interactively, the tool prompts for confirmation before running project-local agents. Set `confirmProjectAgents: false` to disable. + +## Usage + +### Single agent +``` +Use scout to find all authentication code +``` + +### Parallel execution +``` +Run 2 scouts in parallel: one to find models, one to find providers +``` + +### Chained workflow +``` +Use a chain: first have scout find the read tool, then have planner suggest improvements +``` + +### Workflow prompts +``` +/implement add Redis caching to the session store +/scout-and-plan refactor auth to support OAuth +/implement-and-review add input validation to API endpoints +``` + +## Tool Modes + +| Mode | Parameter | Description | +|------|-----------|-------------| +| Single | `{ agent, task }` | One agent, one task | +| Parallel | `{ tasks: [...] }` | Multiple agents run concurrently (max 8, 4 concurrent) | +| Chain | `{ chain: [...] }` | Sequential with `{previous}` placeholder | + +## Output Display + +**Collapsed view** (default): +- Status icon (✓/✗/⏳) and agent name +- Last 5-10 items (tool calls and text) +- Usage stats: `3 turns ↑input ↓output RcacheRead WcacheWrite $cost ctx:contextTokens model` + +**Expanded view** (Ctrl+O): +- Full task text +- All tool calls with formatted arguments +- Final output rendered as Markdown +- Per-task usage (for chain/parallel) + +**Parallel mode streaming**: +- Shows all tasks with live status (⏳ running, ✓ done, ✗ failed) +- Updates as each task makes progress +- Shows "2/3 done, 1 running" status +- Returns each completed task's final output to the parent model, capped at 50 KB per task +- Returns failure diagnostics from stderr/error messages when a child exits before producing output + +**Tool call formatting** (mimics built-in tools): +- `$ command` for bash +- `read ~/path:1-10` for read +- `grep /pattern/ in ~/path` for grep +- etc. + +## Agent Definitions + +Agents are markdown files with YAML frontmatter: + +```markdown +--- +name: my-agent +description: What this agent does +tools: read, grep, find, ls +model: claude-haiku-4-5 +--- + +System prompt for the agent goes here. +``` + +**Locations:** +- `~/.pi/agent/agents/*.md` - User-level (always loaded) +- `.pi/agents/*.md` - Project-level (only with `agentScope: "project"` or `"both"`) + +Project agents override user agents with the same name when `agentScope: "both"`. + +## Sample Agents + +| Agent | Purpose | Model | Tools | +|-------|---------|-------|-------| +| `scout` | Fast codebase recon | Haiku | read, grep, find, ls, bash | +| `planner` | Implementation plans | Sonnet | read, grep, find, ls | +| `reviewer` | Code review | Sonnet | read, grep, find, ls, bash | +| `worker` | General-purpose | Sonnet | (all default) | + +## Workflow Prompts + +| Prompt | Flow | +|--------|------| +| `/implement ` | scout → planner → worker | +| `/scout-and-plan ` | scout → planner | +| `/implement-and-review ` | worker → reviewer → worker | + +## Error Handling + +- **Exit code != 0**: Tool returns error with stderr/output +- **stopReason "error"**: LLM error propagated with error message +- **stopReason "aborted"**: User abort (Ctrl+C) kills subprocess, throws error +- **Chain mode**: Stops at first failing step, reports which step failed + +## Limitations + +- Output truncated to last 10 items in collapsed view (expand to see all) +- Parallel model-visible output is capped at 50 KB per task; full results remain in tool details +- Agents discovered fresh on each invocation (allows editing mid-session) +- Parallel mode limited to 8 tasks, 4 concurrent diff --git a/examples/extensions/subagent/agents.ts b/examples/extensions/subagent/agents.ts new file mode 100644 index 0000000..c41ef57 --- /dev/null +++ b/examples/extensions/subagent/agents.ts @@ -0,0 +1,126 @@ +/** + * Agent discovery and configuration + */ + +import * as fs from "node:fs"; +import * as path from "node:path"; +import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent"; + +export type AgentScope = "user" | "project" | "both"; + +export interface AgentConfig { + name: string; + description: string; + tools?: string[]; + model?: string; + systemPrompt: string; + source: "user" | "project"; + filePath: string; +} + +export interface AgentDiscoveryResult { + agents: AgentConfig[]; + projectAgentsDir: string | null; +} + +function loadAgentsFromDir(dir: string, source: "user" | "project"): AgentConfig[] { + const agents: AgentConfig[] = []; + + if (!fs.existsSync(dir)) { + return agents; + } + + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return agents; + } + + for (const entry of entries) { + if (!entry.name.endsWith(".md")) continue; + if (!entry.isFile() && !entry.isSymbolicLink()) continue; + + const filePath = path.join(dir, entry.name); + let content: string; + try { + content = fs.readFileSync(filePath, "utf-8"); + } catch { + continue; + } + + const { frontmatter, body } = parseFrontmatter>(content); + + if (!frontmatter.name || !frontmatter.description) { + continue; + } + + const tools = frontmatter.tools + ?.split(",") + .map((t: string) => t.trim()) + .filter(Boolean); + + agents.push({ + name: frontmatter.name, + description: frontmatter.description, + tools: tools && tools.length > 0 ? tools : undefined, + model: frontmatter.model, + systemPrompt: body, + source, + filePath, + }); + } + + return agents; +} + +function isDirectory(p: string): boolean { + try { + return fs.statSync(p).isDirectory(); + } catch { + return false; + } +} + +function findNearestProjectAgentsDir(cwd: string): string | null { + let currentDir = cwd; + while (true) { + const candidate = path.join(currentDir, CONFIG_DIR_NAME, "agents"); + if (isDirectory(candidate)) return candidate; + + const parentDir = path.dirname(currentDir); + if (parentDir === currentDir) return null; + currentDir = parentDir; + } +} + +export function discoverAgents(cwd: string, scope: AgentScope): AgentDiscoveryResult { + const userDir = path.join(getAgentDir(), "agents"); + const projectAgentsDir = findNearestProjectAgentsDir(cwd); + + const userAgents = scope === "project" ? [] : loadAgentsFromDir(userDir, "user"); + const projectAgents = scope === "user" || !projectAgentsDir ? [] : loadAgentsFromDir(projectAgentsDir, "project"); + + const agentMap = new Map(); + + if (scope === "both") { + for (const agent of userAgents) agentMap.set(agent.name, agent); + for (const agent of projectAgents) agentMap.set(agent.name, agent); + } else if (scope === "user") { + for (const agent of userAgents) agentMap.set(agent.name, agent); + } else { + for (const agent of projectAgents) agentMap.set(agent.name, agent); + } + + return { agents: Array.from(agentMap.values()), projectAgentsDir }; +} + +export function formatAgentList(agents: AgentConfig[], maxItems: number): { text: string; remaining: number } { + if (agents.length === 0) return { text: "none", remaining: 0 }; + const listed = agents.slice(0, maxItems); + const remaining = agents.length - listed.length; + return { + text: listed.map((a) => `${a.name} (${a.source}): ${a.description}`).join("; "), + remaining, + }; +} diff --git a/examples/extensions/subagent/agents/planner.md b/examples/extensions/subagent/agents/planner.md new file mode 100644 index 0000000..7acc718 --- /dev/null +++ b/examples/extensions/subagent/agents/planner.md @@ -0,0 +1,37 @@ +--- +name: planner +description: Creates implementation plans from context and requirements +tools: read, grep, find, ls +model: claude-sonnet-4-5 +--- + +You are a planning specialist. You receive context (from a scout) and requirements, then produce a clear implementation plan. + +You must NOT make any changes. Only read, analyze, and plan. + +Input format you'll receive: +- Context/findings from a scout agent +- Original query or requirements + +Output format: + +## Goal +One sentence summary of what needs to be done. + +## Plan +Numbered steps, each small and actionable: +1. Step one - specific file/function to modify +2. Step two - what to add/change +3. ... + +## Files to Modify +- `path/to/file.ts` - what changes +- `path/to/other.ts` - what changes + +## New Files (if any) +- `path/to/new.ts` - purpose + +## Risks +Anything to watch out for. + +Keep the plan concrete. The worker agent will execute it verbatim. diff --git a/examples/extensions/subagent/agents/reviewer.md b/examples/extensions/subagent/agents/reviewer.md new file mode 100644 index 0000000..a670699 --- /dev/null +++ b/examples/extensions/subagent/agents/reviewer.md @@ -0,0 +1,35 @@ +--- +name: reviewer +description: Code review specialist for quality and security analysis +tools: read, grep, find, ls, bash +model: claude-sonnet-4-5 +--- + +You are a senior code reviewer. Analyze code for quality, security, and maintainability. + +Bash is for read-only commands only: `git diff`, `git log`, `git show`. Do NOT modify files or run builds. +Assume tool permissions are not perfectly enforceable; keep all bash usage strictly read-only. + +Strategy: +1. Run `git diff` to see recent changes (if applicable) +2. Read the modified files +3. Check for bugs, security issues, code smells + +Output format: + +## Files Reviewed +- `path/to/file.ts` (lines X-Y) + +## Critical (must fix) +- `file.ts:42` - Issue description + +## Warnings (should fix) +- `file.ts:100` - Issue description + +## Suggestions (consider) +- `file.ts:150` - Improvement idea + +## Summary +Overall assessment in 2-3 sentences. + +Be specific with file paths and line numbers. diff --git a/examples/extensions/subagent/agents/scout.md b/examples/extensions/subagent/agents/scout.md new file mode 100644 index 0000000..c59611b --- /dev/null +++ b/examples/extensions/subagent/agents/scout.md @@ -0,0 +1,50 @@ +--- +name: scout +description: Fast codebase recon that returns compressed context for handoff to other agents +tools: read, grep, find, ls, bash +model: claude-haiku-4-5 +--- + +You are a scout. Quickly investigate a codebase and return structured findings that another agent can use without re-reading everything. + +Your output will be passed to an agent who has NOT seen the files you explored. + +Thoroughness (infer from task, default medium): +- Quick: Targeted lookups, key files only +- Medium: Follow imports, read critical sections +- Thorough: Trace all dependencies, check tests/types + +Strategy: +1. grep/find to locate relevant code +2. Read key sections (not entire files) +3. Identify types, interfaces, key functions +4. Note dependencies between files + +Output format: + +## Files Retrieved +List with exact line ranges: +1. `path/to/file.ts` (lines 10-50) - Description of what's here +2. `path/to/other.ts` (lines 100-150) - Description +3. ... + +## Key Code +Critical types, interfaces, or functions: + +```typescript +interface Example { + // actual code from the files +} +``` + +```typescript +function keyFunction() { + // actual implementation +} +``` + +## Architecture +Brief explanation of how the pieces connect. + +## Start Here +Which file to look at first and why. diff --git a/examples/extensions/subagent/agents/worker.md b/examples/extensions/subagent/agents/worker.md new file mode 100644 index 0000000..d968835 --- /dev/null +++ b/examples/extensions/subagent/agents/worker.md @@ -0,0 +1,24 @@ +--- +name: worker +description: General-purpose subagent with full capabilities, isolated context +model: claude-sonnet-4-5 +--- + +You are a worker agent with full capabilities. You operate in an isolated context window to handle delegated tasks without polluting the main conversation. + +Work autonomously to complete the assigned task. Use all available tools as needed. + +Output format when finished: + +## Completed +What was done. + +## Files Changed +- `path/to/file.ts` - what changed + +## Notes (if any) +Anything the main agent should know. + +If handing off to another agent (e.g. reviewer), include: +- Exact file paths changed +- Key functions/types touched (short list) diff --git a/examples/extensions/subagent/index.ts b/examples/extensions/subagent/index.ts new file mode 100644 index 0000000..832dcc7 --- /dev/null +++ b/examples/extensions/subagent/index.ts @@ -0,0 +1,1015 @@ +/** + * Subagent Tool - Delegate tasks to specialized agents + * + * Spawns a separate `pi` process for each subagent invocation, + * giving it an isolated context window. + * + * Supports three modes: + * - Single: { agent: "name", task: "..." } + * - Parallel: { tasks: [{ agent: "name", task: "..." }, ...] } + * - Chain: { chain: [{ agent: "name", task: "... {previous} ..." }, ...] } + * + * Uses JSON mode to capture structured output from subagents. + */ + +import { spawn } from "node:child_process"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import type { AgentToolResult } from "@earendil-works/pi-agent-core"; +import type { Message } from "@earendil-works/pi-ai"; +import { StringEnum } from "@earendil-works/pi-ai"; +import { + CONFIG_DIR_NAME, + type ExtensionAPI, + getAgentDir, + getMarkdownTheme, + withFileMutationQueue, +} from "@earendil-works/pi-coding-agent"; +import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui"; +import { Type } from "typebox"; +import { type AgentConfig, type AgentScope, discoverAgents } from "./agents.ts"; + +const MAX_PARALLEL_TASKS = 8; +const MAX_CONCURRENCY = 4; +const COLLAPSED_ITEM_COUNT = 10; +const PER_TASK_OUTPUT_CAP = 50 * 1024; + +function formatTokens(count: number): string { + if (count < 1000) return count.toString(); + if (count < 10000) return `${(count / 1000).toFixed(1)}k`; + if (count < 1000000) return `${Math.round(count / 1000)}k`; + return `${(count / 1000000).toFixed(1)}M`; +} + +function formatUsageStats( + usage: { + input: number; + output: number; + cacheRead: number; + cacheWrite: number; + cost: number; + contextTokens?: number; + turns?: number; + }, + model?: string, +): string { + const parts: string[] = []; + if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`); + if (usage.input) parts.push(`↑${formatTokens(usage.input)}`); + if (usage.output) parts.push(`↓${formatTokens(usage.output)}`); + if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`); + if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`); + if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`); + if (usage.contextTokens && usage.contextTokens > 0) { + parts.push(`ctx:${formatTokens(usage.contextTokens)}`); + } + if (model) parts.push(model); + return parts.join(" "); +} + +function formatToolCall( + toolName: string, + args: Record, + themeFg: (color: any, text: string) => string, +): string { + const shortenPath = (p: string) => { + const home = os.homedir(); + return p.startsWith(home) ? `~${p.slice(home.length)}` : p; + }; + + switch (toolName) { + case "bash": { + const command = (args.command as string) || "..."; + const preview = command.length > 60 ? `${command.slice(0, 60)}...` : command; + return themeFg("muted", "$ ") + themeFg("toolOutput", preview); + } + case "read": { + const rawPath = (args.file_path || args.path || "...") as string; + const filePath = shortenPath(rawPath); + const offset = args.offset as number | undefined; + const limit = args.limit as number | undefined; + let text = themeFg("accent", filePath); + if (offset !== undefined || limit !== undefined) { + const startLine = offset ?? 1; + const endLine = limit !== undefined ? startLine + limit - 1 : ""; + text += themeFg("warning", `:${startLine}${endLine ? `-${endLine}` : ""}`); + } + return themeFg("muted", "read ") + text; + } + case "write": { + const rawPath = (args.file_path || args.path || "...") as string; + const filePath = shortenPath(rawPath); + const content = (args.content || "") as string; + const lines = content.split("\n").length; + let text = themeFg("muted", "write ") + themeFg("accent", filePath); + if (lines > 1) text += themeFg("dim", ` (${lines} lines)`); + return text; + } + case "edit": { + const rawPath = (args.file_path || args.path || "...") as string; + return themeFg("muted", "edit ") + themeFg("accent", shortenPath(rawPath)); + } + case "ls": { + const rawPath = (args.path || ".") as string; + return themeFg("muted", "ls ") + themeFg("accent", shortenPath(rawPath)); + } + case "find": { + const pattern = (args.pattern || "*") as string; + const rawPath = (args.path || ".") as string; + return themeFg("muted", "find ") + themeFg("accent", pattern) + themeFg("dim", ` in ${shortenPath(rawPath)}`); + } + case "grep": { + const pattern = (args.pattern || "") as string; + const rawPath = (args.path || ".") as string; + return ( + themeFg("muted", "grep ") + + themeFg("accent", `/${pattern}/`) + + themeFg("dim", ` in ${shortenPath(rawPath)}`) + ); + } + default: { + const argsStr = JSON.stringify(args); + const preview = argsStr.length > 50 ? `${argsStr.slice(0, 50)}...` : argsStr; + return themeFg("accent", toolName) + themeFg("dim", ` ${preview}`); + } + } +} + +interface UsageStats { + input: number; + output: number; + cacheRead: number; + cacheWrite: number; + cost: number; + contextTokens: number; + turns: number; +} + +interface SingleResult { + agent: string; + agentSource: "user" | "project" | "unknown"; + task: string; + exitCode: number; + messages: Message[]; + stderr: string; + usage: UsageStats; + model?: string; + stopReason?: string; + errorMessage?: string; + step?: number; +} + +interface SubagentDetails { + mode: "single" | "parallel" | "chain"; + agentScope: AgentScope; + projectAgentsDir: string | null; + results: SingleResult[]; +} + +function getFinalOutput(messages: Message[]): string { + for (let i = messages.length - 1; i >= 0; i--) { + const msg = messages[i]; + if (msg.role === "assistant") { + for (const part of msg.content) { + if (part.type === "text") return part.text; + } + } + } + return ""; +} + +function isFailedResult(result: SingleResult): boolean { + return result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted"; +} + +function getResultOutput(result: SingleResult): string { + if (isFailedResult(result)) { + return result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)"; + } + return getFinalOutput(result.messages) || "(no output)"; +} + +function truncateParallelOutput(output: string): string { + const byteLength = Buffer.byteLength(output, "utf8"); + if (byteLength <= PER_TASK_OUTPUT_CAP) return output; + + let truncated = output.slice(0, PER_TASK_OUTPUT_CAP); + while (Buffer.byteLength(truncated, "utf8") > PER_TASK_OUTPUT_CAP) { + truncated = truncated.slice(0, -1); + } + return `${truncated}\n\n[Output truncated: ${byteLength - Buffer.byteLength(truncated, "utf8")} bytes omitted. Full output preserved in tool details.]`; +} + +type DisplayItem = { type: "text"; text: string } | { type: "toolCall"; name: string; args: Record }; + +function getDisplayItems(messages: Message[]): DisplayItem[] { + const items: DisplayItem[] = []; + for (const msg of messages) { + if (msg.role === "assistant") { + for (const part of msg.content) { + if (part.type === "text") items.push({ type: "text", text: part.text }); + else if (part.type === "toolCall") items.push({ type: "toolCall", name: part.name, args: part.arguments }); + } + } + } + return items; +} + +async function mapWithConcurrencyLimit( + items: TIn[], + concurrency: number, + fn: (item: TIn, index: number) => Promise, +): Promise { + if (items.length === 0) return []; + const limit = Math.max(1, Math.min(concurrency, items.length)); + const results: TOut[] = new Array(items.length); + let nextIndex = 0; + const workers = new Array(limit).fill(null).map(async () => { + while (true) { + const current = nextIndex++; + if (current >= items.length) return; + results[current] = await fn(items[current], current); + } + }); + await Promise.all(workers); + return results; +} + +async function writePromptToTempFile(agentName: string, prompt: string): Promise<{ dir: string; filePath: string }> { + const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-")); + const safeName = agentName.replace(/[^\w.-]+/g, "_"); + const filePath = path.join(tmpDir, `prompt-${safeName}.md`); + await withFileMutationQueue(filePath, async () => { + await fs.promises.writeFile(filePath, prompt, { encoding: "utf-8", mode: 0o600 }); + }); + return { dir: tmpDir, filePath }; +} + +function getPiInvocation(args: string[]): { command: string; args: string[] } { + const currentScript = process.argv[1]; + const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/"); + if (currentScript && !isBunVirtualScript && fs.existsSync(currentScript)) { + return { command: process.execPath, args: [currentScript, ...args] }; + } + + const execName = path.basename(process.execPath).toLowerCase(); + const isGenericRuntime = /^(node|bun)(\.exe)?$/.test(execName); + if (!isGenericRuntime) { + return { command: process.execPath, args }; + } + + return { command: "pi", args }; +} + +type OnUpdateCallback = (partial: AgentToolResult) => void; + +async function runSingleAgent( + defaultCwd: string, + agents: AgentConfig[], + agentName: string, + task: string, + cwd: string | undefined, + step: number | undefined, + signal: AbortSignal | undefined, + onUpdate: OnUpdateCallback | undefined, + makeDetails: (results: SingleResult[]) => SubagentDetails, +): Promise { + const agent = agents.find((a) => a.name === agentName); + + if (!agent) { + const available = agents.map((a) => `"${a.name}"`).join(", ") || "none"; + return { + agent: agentName, + agentSource: "unknown", + task, + exitCode: 1, + messages: [], + stderr: `Unknown agent: "${agentName}". Available agents: ${available}.`, + usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 }, + step, + }; + } + + const args: string[] = ["--mode", "json", "-p", "--no-session"]; + if (agent.model) args.push("--model", agent.model); + if (agent.tools && agent.tools.length > 0) args.push("--tools", agent.tools.join(",")); + + let tmpPromptDir: string | null = null; + let tmpPromptPath: string | null = null; + + const currentResult: SingleResult = { + agent: agentName, + agentSource: agent.source, + task, + exitCode: 0, + messages: [], + stderr: "", + usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 }, + model: agent.model, + step, + }; + + const emitUpdate = () => { + if (onUpdate) { + onUpdate({ + content: [{ type: "text", text: getFinalOutput(currentResult.messages) || "(running...)" }], + details: makeDetails([currentResult]), + }); + } + }; + + try { + if (agent.systemPrompt.trim()) { + const tmp = await writePromptToTempFile(agent.name, agent.systemPrompt); + tmpPromptDir = tmp.dir; + tmpPromptPath = tmp.filePath; + args.push("--append-system-prompt", tmpPromptPath); + } + + args.push(`Task: ${task}`); + let wasAborted = false; + + const exitCode = await new Promise((resolve) => { + const invocation = getPiInvocation(args); + const proc = spawn(invocation.command, invocation.args, { + cwd: cwd ?? defaultCwd, + shell: false, + stdio: ["ignore", "pipe", "pipe"], + }); + let buffer = ""; + + const processLine = (line: string) => { + if (!line.trim()) return; + let event: any; + try { + event = JSON.parse(line); + } catch { + return; + } + + if (event.type === "message_end" && event.message) { + const msg = event.message as Message; + currentResult.messages.push(msg); + + if (msg.role === "assistant") { + currentResult.usage.turns++; + const usage = msg.usage; + if (usage) { + currentResult.usage.input += usage.input || 0; + currentResult.usage.output += usage.output || 0; + currentResult.usage.cacheRead += usage.cacheRead || 0; + currentResult.usage.cacheWrite += usage.cacheWrite || 0; + currentResult.usage.cost += usage.cost?.total || 0; + currentResult.usage.contextTokens = usage.totalTokens || 0; + } + if (!currentResult.model && msg.model) currentResult.model = msg.model; + if (msg.stopReason) currentResult.stopReason = msg.stopReason; + if (msg.errorMessage) currentResult.errorMessage = msg.errorMessage; + } + emitUpdate(); + } + + if (event.type === "tool_result_end" && event.message) { + currentResult.messages.push(event.message as Message); + emitUpdate(); + } + }; + + proc.stdout.on("data", (data) => { + buffer += data.toString(); + const lines = buffer.split("\n"); + buffer = lines.pop() || ""; + for (const line of lines) processLine(line); + }); + + proc.stderr.on("data", (data) => { + currentResult.stderr += data.toString(); + }); + + proc.on("close", (code) => { + if (buffer.trim()) processLine(buffer); + resolve(code ?? 0); + }); + + proc.on("error", () => { + resolve(1); + }); + + if (signal) { + const killProc = () => { + wasAborted = true; + proc.kill("SIGTERM"); + setTimeout(() => { + if (!proc.killed) proc.kill("SIGKILL"); + }, 5000); + }; + if (signal.aborted) killProc(); + else signal.addEventListener("abort", killProc, { once: true }); + } + }); + + currentResult.exitCode = exitCode; + if (wasAborted) throw new Error("Subagent was aborted"); + return currentResult; + } finally { + if (tmpPromptPath) + try { + fs.unlinkSync(tmpPromptPath); + } catch { + /* ignore */ + } + if (tmpPromptDir) + try { + fs.rmdirSync(tmpPromptDir); + } catch { + /* ignore */ + } + } +} + +const TaskItem = Type.Object({ + agent: Type.String({ description: "Name of the agent to invoke" }), + task: Type.String({ description: "Task to delegate to the agent" }), + cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })), +}); + +const ChainItem = Type.Object({ + agent: Type.String({ description: "Name of the agent to invoke" }), + task: Type.String({ description: "Task with optional {previous} placeholder for prior output" }), + cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })), +}); + +const AgentScopeSchema = StringEnum(["user", "project", "both"] as const, { + description: 'Which agent directories to use. Default: "user". Use "both" to include project-local agents.', + default: "user", +}); + +const SubagentParams = Type.Object({ + agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (for single mode)" })), + task: Type.Optional(Type.String({ description: "Task to delegate (for single mode)" })), + tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })), + chain: Type.Optional(Type.Array(ChainItem, { description: "Array of {agent, task} for sequential execution" })), + agentScope: Type.Optional(AgentScopeSchema), + confirmProjectAgents: Type.Optional( + Type.Boolean({ description: "Prompt before running project-local agents. Default: true.", default: true }), + ), + cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })), +}); + +export default function (pi: ExtensionAPI) { + pi.registerTool({ + name: "subagent", + label: "Subagent", + description: [ + "Delegate tasks to specialized subagents with isolated context.", + "Modes: single (agent + task), parallel (tasks array), chain (sequential with {previous} placeholder).", + `Default agent scope is "user" (from ${path.join(getAgentDir(), "agents")}).`, + `To enable project-local agents in ${CONFIG_DIR_NAME}/agents, set agentScope: "both" (or "project").`, + ].join(" "), + parameters: SubagentParams, + + async execute(_toolCallId, params, signal, onUpdate, ctx) { + const agentScope: AgentScope = params.agentScope ?? "user"; + const discovery = discoverAgents(ctx.cwd, agentScope); + const agents = discovery.agents; + const confirmProjectAgents = params.confirmProjectAgents ?? true; + + const hasChain = (params.chain?.length ?? 0) > 0; + const hasTasks = (params.tasks?.length ?? 0) > 0; + const hasSingle = Boolean(params.agent && params.task); + const modeCount = Number(hasChain) + Number(hasTasks) + Number(hasSingle); + + const makeDetails = + (mode: "single" | "parallel" | "chain") => + (results: SingleResult[]): SubagentDetails => ({ + mode, + agentScope, + projectAgentsDir: discovery.projectAgentsDir, + results, + }); + + if (modeCount !== 1) { + const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none"; + return { + content: [ + { + type: "text", + text: `Invalid parameters. Provide exactly one mode.\nAvailable agents: ${available}`, + }, + ], + details: makeDetails("single")([]), + }; + } + + if ((agentScope === "project" || agentScope === "both") && confirmProjectAgents && ctx.hasUI) { + const requestedAgentNames = new Set(); + if (params.chain) for (const step of params.chain) requestedAgentNames.add(step.agent); + if (params.tasks) for (const t of params.tasks) requestedAgentNames.add(t.agent); + if (params.agent) requestedAgentNames.add(params.agent); + + const projectAgentsRequested = Array.from(requestedAgentNames) + .map((name) => agents.find((a) => a.name === name)) + .filter((a): a is AgentConfig => a?.source === "project"); + + if (projectAgentsRequested.length > 0) { + const names = projectAgentsRequested.map((a) => a.name).join(", "); + const dir = discovery.projectAgentsDir ?? "(unknown)"; + const ok = await ctx.ui.confirm( + "Run project-local agents?", + `Agents: ${names}\nSource: ${dir}\n\nProject agents are repo-controlled. Only continue for trusted repositories.`, + ); + if (!ok) + return { + content: [{ type: "text", text: "Canceled: project-local agents not approved." }], + details: makeDetails(hasChain ? "chain" : hasTasks ? "parallel" : "single")([]), + }; + } + } + + if (params.chain && params.chain.length > 0) { + const results: SingleResult[] = []; + let previousOutput = ""; + + for (let i = 0; i < params.chain.length; i++) { + const step = params.chain[i]; + const taskWithContext = step.task.replace(/\{previous\}/g, previousOutput); + + // Create update callback that includes all previous results + const chainUpdate: OnUpdateCallback | undefined = onUpdate + ? (partial) => { + // Combine completed results with current streaming result + const currentResult = partial.details?.results[0]; + if (currentResult) { + const allResults = [...results, currentResult]; + onUpdate({ + content: partial.content, + details: makeDetails("chain")(allResults), + }); + } + } + : undefined; + + const result = await runSingleAgent( + ctx.cwd, + agents, + step.agent, + taskWithContext, + step.cwd, + i + 1, + signal, + chainUpdate, + makeDetails("chain"), + ); + results.push(result); + + const isError = isFailedResult(result); + if (isError) { + const errorMsg = getResultOutput(result); + return { + content: [{ type: "text", text: `Chain stopped at step ${i + 1} (${step.agent}): ${errorMsg}` }], + details: makeDetails("chain")(results), + isError: true, + }; + } + previousOutput = getFinalOutput(result.messages); + } + return { + content: [{ type: "text", text: getFinalOutput(results[results.length - 1].messages) || "(no output)" }], + details: makeDetails("chain")(results), + }; + } + + if (params.tasks && params.tasks.length > 0) { + if (params.tasks.length > MAX_PARALLEL_TASKS) + return { + content: [ + { + type: "text", + text: `Too many parallel tasks (${params.tasks.length}). Max is ${MAX_PARALLEL_TASKS}.`, + }, + ], + details: makeDetails("parallel")([]), + }; + + // Track all results for streaming updates + const allResults: SingleResult[] = new Array(params.tasks.length); + + // Initialize placeholder results + for (let i = 0; i < params.tasks.length; i++) { + allResults[i] = { + agent: params.tasks[i].agent, + agentSource: "unknown", + task: params.tasks[i].task, + exitCode: -1, // -1 = still running + messages: [], + stderr: "", + usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 }, + }; + } + + const emitParallelUpdate = () => { + if (onUpdate) { + const running = allResults.filter((r) => r.exitCode === -1).length; + const done = allResults.filter((r) => r.exitCode !== -1).length; + onUpdate({ + content: [ + { type: "text", text: `Parallel: ${done}/${allResults.length} done, ${running} running...` }, + ], + details: makeDetails("parallel")([...allResults]), + }); + } + }; + + const results = await mapWithConcurrencyLimit(params.tasks, MAX_CONCURRENCY, async (t, index) => { + const result = await runSingleAgent( + ctx.cwd, + agents, + t.agent, + t.task, + t.cwd, + undefined, + signal, + // Per-task update callback + (partial) => { + if (partial.details?.results[0]) { + allResults[index] = partial.details.results[0]; + emitParallelUpdate(); + } + }, + makeDetails("parallel"), + ); + allResults[index] = result; + emitParallelUpdate(); + return result; + }); + + const successCount = results.filter((r) => !isFailedResult(r)).length; + const summaries = results.map((r) => { + const output = truncateParallelOutput(getResultOutput(r)); + const status = isFailedResult(r) + ? `failed${r.stopReason && r.stopReason !== "end" ? ` (${r.stopReason})` : ""}` + : "completed"; + return `### [${r.agent}] ${status}\n\n${output}`; + }); + return { + content: [ + { + type: "text", + text: `Parallel: ${successCount}/${results.length} succeeded\n\n${summaries.join("\n\n---\n\n")}`, + }, + ], + details: makeDetails("parallel")(results), + }; + } + + if (params.agent && params.task) { + const result = await runSingleAgent( + ctx.cwd, + agents, + params.agent, + params.task, + params.cwd, + undefined, + signal, + onUpdate, + makeDetails("single"), + ); + const isError = isFailedResult(result); + if (isError) { + const errorMsg = getResultOutput(result); + return { + content: [{ type: "text", text: `Agent ${result.stopReason || "failed"}: ${errorMsg}` }], + details: makeDetails("single")([result]), + isError: true, + }; + } + return { + content: [{ type: "text", text: getFinalOutput(result.messages) || "(no output)" }], + details: makeDetails("single")([result]), + }; + } + + const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none"; + return { + content: [{ type: "text", text: `Invalid parameters. Available agents: ${available}` }], + details: makeDetails("single")([]), + }; + }, + + renderCall(args, theme, _context) { + const scope: AgentScope = args.agentScope ?? "user"; + if (args.chain && args.chain.length > 0) { + let text = + theme.fg("toolTitle", theme.bold("subagent ")) + + theme.fg("accent", `chain (${args.chain.length} steps)`) + + theme.fg("muted", ` [${scope}]`); + for (let i = 0; i < Math.min(args.chain.length, 3); i++) { + const step = args.chain[i]; + // Clean up {previous} placeholder for display + const cleanTask = step.task.replace(/\{previous\}/g, "").trim(); + const preview = cleanTask.length > 40 ? `${cleanTask.slice(0, 40)}...` : cleanTask; + text += + "\n " + + theme.fg("muted", `${i + 1}.`) + + " " + + theme.fg("accent", step.agent) + + theme.fg("dim", ` ${preview}`); + } + if (args.chain.length > 3) text += `\n ${theme.fg("muted", `... +${args.chain.length - 3} more`)}`; + return new Text(text, 0, 0); + } + if (args.tasks && args.tasks.length > 0) { + let text = + theme.fg("toolTitle", theme.bold("subagent ")) + + theme.fg("accent", `parallel (${args.tasks.length} tasks)`) + + theme.fg("muted", ` [${scope}]`); + for (const t of args.tasks.slice(0, 3)) { + const preview = t.task.length > 40 ? `${t.task.slice(0, 40)}...` : t.task; + text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", ` ${preview}`)}`; + } + if (args.tasks.length > 3) text += `\n ${theme.fg("muted", `... +${args.tasks.length - 3} more`)}`; + return new Text(text, 0, 0); + } + const agentName = args.agent || "..."; + const preview = args.task ? (args.task.length > 60 ? `${args.task.slice(0, 60)}...` : args.task) : "..."; + let text = + theme.fg("toolTitle", theme.bold("subagent ")) + + theme.fg("accent", agentName) + + theme.fg("muted", ` [${scope}]`); + text += `\n ${theme.fg("dim", preview)}`; + return new Text(text, 0, 0); + }, + + renderResult(result, { expanded }, theme, _context) { + const details = result.details as SubagentDetails | undefined; + if (!details || details.results.length === 0) { + const text = result.content[0]; + return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0); + } + + const mdTheme = getMarkdownTheme(); + + const renderDisplayItems = (items: DisplayItem[], limit?: number) => { + const toShow = limit ? items.slice(-limit) : items; + const skipped = limit && items.length > limit ? items.length - limit : 0; + let text = ""; + if (skipped > 0) text += theme.fg("muted", `... ${skipped} earlier items\n`); + for (const item of toShow) { + if (item.type === "text") { + const preview = expanded ? item.text : item.text.split("\n").slice(0, 3).join("\n"); + text += `${theme.fg("toolOutput", preview)}\n`; + } else { + text += `${theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme))}\n`; + } + } + return text.trimEnd(); + }; + + if (details.mode === "single" && details.results.length === 1) { + const r = details.results[0]; + const isError = isFailedResult(r); + const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓"); + const displayItems = getDisplayItems(r.messages); + const finalOutput = getFinalOutput(r.messages); + + if (expanded) { + const container = new Container(); + let header = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`; + if (isError && r.stopReason) header += ` ${theme.fg("error", `[${r.stopReason}]`)}`; + container.addChild(new Text(header, 0, 0)); + if (isError && r.errorMessage) + container.addChild(new Text(theme.fg("error", `Error: ${r.errorMessage}`), 0, 0)); + container.addChild(new Spacer(1)); + container.addChild(new Text(theme.fg("muted", "─── Task ───"), 0, 0)); + container.addChild(new Text(theme.fg("dim", r.task), 0, 0)); + container.addChild(new Spacer(1)); + container.addChild(new Text(theme.fg("muted", "─── Output ───"), 0, 0)); + if (displayItems.length === 0 && !finalOutput) { + container.addChild(new Text(theme.fg("muted", "(no output)"), 0, 0)); + } else { + for (const item of displayItems) { + if (item.type === "toolCall") + container.addChild( + new Text( + theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)), + 0, + 0, + ), + ); + } + if (finalOutput) { + container.addChild(new Spacer(1)); + container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme)); + } + } + const usageStr = formatUsageStats(r.usage, r.model); + if (usageStr) { + container.addChild(new Spacer(1)); + container.addChild(new Text(theme.fg("dim", usageStr), 0, 0)); + } + return container; + } + + let text = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`; + if (isError && r.stopReason) text += ` ${theme.fg("error", `[${r.stopReason}]`)}`; + if (isError && r.errorMessage) text += `\n${theme.fg("error", `Error: ${r.errorMessage}`)}`; + else if (displayItems.length === 0) text += `\n${theme.fg("muted", "(no output)")}`; + else { + text += `\n${renderDisplayItems(displayItems, COLLAPSED_ITEM_COUNT)}`; + if (displayItems.length > COLLAPSED_ITEM_COUNT) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`; + } + const usageStr = formatUsageStats(r.usage, r.model); + if (usageStr) text += `\n${theme.fg("dim", usageStr)}`; + return new Text(text, 0, 0); + } + + const aggregateUsage = (results: SingleResult[]) => { + const total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 }; + for (const r of results) { + total.input += r.usage.input; + total.output += r.usage.output; + total.cacheRead += r.usage.cacheRead; + total.cacheWrite += r.usage.cacheWrite; + total.cost += r.usage.cost; + total.turns += r.usage.turns; + } + return total; + }; + + if (details.mode === "chain") { + const successCount = details.results.filter((r) => r.exitCode === 0).length; + const icon = successCount === details.results.length ? theme.fg("success", "✓") : theme.fg("error", "✗"); + + if (expanded) { + const container = new Container(); + container.addChild( + new Text( + icon + + " " + + theme.fg("toolTitle", theme.bold("chain ")) + + theme.fg("accent", `${successCount}/${details.results.length} steps`), + 0, + 0, + ), + ); + + for (const r of details.results) { + const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗"); + const displayItems = getDisplayItems(r.messages); + const finalOutput = getFinalOutput(r.messages); + + container.addChild(new Spacer(1)); + container.addChild( + new Text( + `${theme.fg("muted", `─── Step ${r.step}: `) + theme.fg("accent", r.agent)} ${rIcon}`, + 0, + 0, + ), + ); + container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0)); + + // Show tool calls + for (const item of displayItems) { + if (item.type === "toolCall") { + container.addChild( + new Text( + theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)), + 0, + 0, + ), + ); + } + } + + // Show final output as markdown + if (finalOutput) { + container.addChild(new Spacer(1)); + container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme)); + } + + const stepUsage = formatUsageStats(r.usage, r.model); + if (stepUsage) container.addChild(new Text(theme.fg("dim", stepUsage), 0, 0)); + } + + const usageStr = formatUsageStats(aggregateUsage(details.results)); + if (usageStr) { + container.addChild(new Spacer(1)); + container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0)); + } + return container; + } + + // Collapsed view + let text = + icon + + " " + + theme.fg("toolTitle", theme.bold("chain ")) + + theme.fg("accent", `${successCount}/${details.results.length} steps`); + for (const r of details.results) { + const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗"); + const displayItems = getDisplayItems(r.messages); + text += `\n\n${theme.fg("muted", `─── Step ${r.step}: `)}${theme.fg("accent", r.agent)} ${rIcon}`; + if (displayItems.length === 0) text += `\n${theme.fg("muted", "(no output)")}`; + else text += `\n${renderDisplayItems(displayItems, 5)}`; + } + const usageStr = formatUsageStats(aggregateUsage(details.results)); + if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`; + text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`; + return new Text(text, 0, 0); + } + + if (details.mode === "parallel") { + const running = details.results.filter((r) => r.exitCode === -1).length; + const successCount = details.results.filter((r) => r.exitCode !== -1 && !isFailedResult(r)).length; + const failCount = details.results.filter((r) => r.exitCode !== -1 && isFailedResult(r)).length; + const isRunning = running > 0; + const icon = isRunning + ? theme.fg("warning", "⏳") + : failCount > 0 + ? theme.fg("warning", "◐") + : theme.fg("success", "✓"); + const status = isRunning + ? `${successCount + failCount}/${details.results.length} done, ${running} running` + : `${successCount}/${details.results.length} tasks`; + + if (expanded && !isRunning) { + const container = new Container(); + container.addChild( + new Text( + `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`, + 0, + 0, + ), + ); + + for (const r of details.results) { + const rIcon = isFailedResult(r) ? theme.fg("error", "✗") : theme.fg("success", "✓"); + const displayItems = getDisplayItems(r.messages); + const finalOutput = getFinalOutput(r.messages); + + container.addChild(new Spacer(1)); + container.addChild( + new Text(`${theme.fg("muted", "─── ") + theme.fg("accent", r.agent)} ${rIcon}`, 0, 0), + ); + container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0)); + + // Show tool calls + for (const item of displayItems) { + if (item.type === "toolCall") { + container.addChild( + new Text( + theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)), + 0, + 0, + ), + ); + } + } + + // Show final output as markdown + if (finalOutput) { + container.addChild(new Spacer(1)); + container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme)); + } + + const taskUsage = formatUsageStats(r.usage, r.model); + if (taskUsage) container.addChild(new Text(theme.fg("dim", taskUsage), 0, 0)); + } + + const usageStr = formatUsageStats(aggregateUsage(details.results)); + if (usageStr) { + container.addChild(new Spacer(1)); + container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0)); + } + return container; + } + + // Collapsed view (or still running) + let text = `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`; + for (const r of details.results) { + const rIcon = + r.exitCode === -1 + ? theme.fg("warning", "⏳") + : isFailedResult(r) + ? theme.fg("error", "✗") + : theme.fg("success", "✓"); + const displayItems = getDisplayItems(r.messages); + text += `\n\n${theme.fg("muted", "─── ")}${theme.fg("accent", r.agent)} ${rIcon}`; + if (displayItems.length === 0) + text += `\n${theme.fg("muted", r.exitCode === -1 ? "(running...)" : "(no output)")}`; + else text += `\n${renderDisplayItems(displayItems, 5)}`; + } + if (!isRunning) { + const usageStr = formatUsageStats(aggregateUsage(details.results)); + if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`; + } + if (!expanded) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`; + return new Text(text, 0, 0); + } + + const text = result.content[0]; + return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0); + }, + }); +} diff --git a/examples/extensions/subagent/prompts/implement-and-review.md b/examples/extensions/subagent/prompts/implement-and-review.md new file mode 100644 index 0000000..6493b3d --- /dev/null +++ b/examples/extensions/subagent/prompts/implement-and-review.md @@ -0,0 +1,10 @@ +--- +description: Worker implements, reviewer reviews, worker applies feedback +--- +Use the subagent tool with the chain parameter to execute this workflow: + +1. First, use the "worker" agent to implement: $@ +2. Then, use the "reviewer" agent to review the implementation from the previous step (use {previous} placeholder) +3. Finally, use the "worker" agent to apply the feedback from the review (use {previous} placeholder) + +Execute this as a chain, passing output between steps via {previous}. diff --git a/examples/extensions/subagent/prompts/implement.md b/examples/extensions/subagent/prompts/implement.md new file mode 100644 index 0000000..559da4d --- /dev/null +++ b/examples/extensions/subagent/prompts/implement.md @@ -0,0 +1,10 @@ +--- +description: Full implementation workflow - scout gathers context, planner creates plan, worker implements +--- +Use the subagent tool with the chain parameter to execute this workflow: + +1. First, use the "scout" agent to find all code relevant to: $@ +2. Then, use the "planner" agent to create an implementation plan for "$@" using the context from the previous step (use {previous} placeholder) +3. Finally, use the "worker" agent to implement the plan from the previous step (use {previous} placeholder) + +Execute this as a chain, passing output between steps via {previous}. diff --git a/examples/extensions/subagent/prompts/scout-and-plan.md b/examples/extensions/subagent/prompts/scout-and-plan.md new file mode 100644 index 0000000..093b633 --- /dev/null +++ b/examples/extensions/subagent/prompts/scout-and-plan.md @@ -0,0 +1,9 @@ +--- +description: Scout gathers context, planner creates implementation plan (no implementation) +--- +Use the subagent tool with the chain parameter to execute this workflow: + +1. First, use the "scout" agent to find all code relevant to: $@ +2. Then, use the "planner" agent to create an implementation plan for "$@" using the context from the previous step (use {previous} placeholder) + +Execute this as a chain, passing output between steps via {previous}. Do NOT implement - just return the plan. diff --git a/examples/extensions/summarize.ts b/examples/extensions/summarize.ts new file mode 100644 index 0000000..282ea0f --- /dev/null +++ b/examples/extensions/summarize.ts @@ -0,0 +1,210 @@ +import { uuidv7 } from "@earendil-works/pi-ai"; +import { complete, getModel } from "@earendil-works/pi-ai/compat"; +import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent"; +import { DynamicBorder, getMarkdownTheme } from "@earendil-works/pi-coding-agent"; +import { Container, Markdown, matchesKey, Text } from "@earendil-works/pi-tui"; + +type ContentBlock = { + type?: string; + text?: string; + name?: string; + arguments?: Record; +}; + +type SessionEntry = { + type: string; + message?: { + role?: string; + content?: unknown; + }; +}; + +const extractTextParts = (content: unknown): string[] => { + if (typeof content === "string") { + return [content]; + } + + if (!Array.isArray(content)) { + return []; + } + + const textParts: string[] = []; + for (const part of content) { + if (!part || typeof part !== "object") { + continue; + } + + const block = part as ContentBlock; + if (block.type === "text" && typeof block.text === "string") { + textParts.push(block.text); + } + } + + return textParts; +}; + +const extractToolCallLines = (content: unknown): string[] => { + if (!Array.isArray(content)) { + return []; + } + + const toolCalls: string[] = []; + for (const part of content) { + if (!part || typeof part !== "object") { + continue; + } + + const block = part as ContentBlock; + if (block.type !== "toolCall" || typeof block.name !== "string") { + continue; + } + + const args = block.arguments ?? {}; + toolCalls.push(`Tool ${block.name} was called with args ${JSON.stringify(args)}`); + } + + return toolCalls; +}; + +const buildConversationText = (entries: SessionEntry[]): string => { + const sections: string[] = []; + + for (const entry of entries) { + if (entry.type !== "message" || !entry.message?.role) { + continue; + } + + const role = entry.message.role; + const isUser = role === "user"; + const isAssistant = role === "assistant"; + + if (!isUser && !isAssistant) { + continue; + } + + const entryLines: string[] = []; + const textParts = extractTextParts(entry.message.content); + if (textParts.length > 0) { + const roleLabel = isUser ? "User" : "Assistant"; + const messageText = textParts.join("\n").trim(); + if (messageText.length > 0) { + entryLines.push(`${roleLabel}: ${messageText}`); + } + } + + if (isAssistant) { + entryLines.push(...extractToolCallLines(entry.message.content)); + } + + if (entryLines.length > 0) { + sections.push(entryLines.join("\n")); + } + } + + return sections.join("\n\n"); +}; + +const buildSummaryPrompt = (conversationText: string): string => + [ + "Summarize this conversation so I can resume it later.", + "Include goals, key decisions, progress, open questions, and next steps.", + "Keep it concise and structured with headings.", + "", + "", + conversationText, + "", + ].join("\n"); + +const showSummaryUi = async (summary: string, ctx: ExtensionCommandContext) => { + if (ctx.mode !== "tui") { + return; + } + + await ctx.ui.custom((_tui, theme, _kb, done) => { + const container = new Container(); + const border = new DynamicBorder((s: string) => theme.fg("accent", s)); + const mdTheme = getMarkdownTheme(); + + container.addChild(border); + container.addChild(new Text(theme.fg("accent", theme.bold("Conversation Summary")), 1, 0)); + container.addChild(new Markdown(summary, 1, 1, mdTheme)); + container.addChild(new Text(theme.fg("dim", "Press Enter or Esc to close"), 1, 0)); + container.addChild(border); + + return { + render: (width: number) => container.render(width), + invalidate: () => container.invalidate(), + handleInput: (data: string) => { + if (matchesKey(data, "enter") || matchesKey(data, "escape")) { + done(undefined); + } + }, + }; + }); +}; + +export default function (pi: ExtensionAPI) { + pi.registerCommand("summarize", { + description: "Summarize the current conversation in a custom UI", + handler: async (_args, ctx) => { + const branch = ctx.sessionManager.getBranch(); + const conversationText = buildConversationText(branch); + + if (!conversationText.trim()) { + if (ctx.hasUI) { + ctx.ui.notify("No conversation text found", "warning"); + } + return; + } + + if (ctx.hasUI) { + ctx.ui.notify("Preparing summary...", "info"); + } + + const model = getModel("openai", "gpt-5.2"); + if (!model && ctx.hasUI) { + ctx.ui.notify("Model openai/gpt-5.2 not found", "warning"); + } + + const auth = model ? await ctx.modelRegistry.getApiKeyAndHeaders(model) : undefined; + if (auth && !auth.ok && ctx.hasUI) { + ctx.ui.notify(auth.error, "warning"); + } + if (auth?.ok && !auth.apiKey && ctx.hasUI) { + ctx.ui.notify("No API key for openai/gpt-5.2", "warning"); + } + + if (!model || !auth?.ok || !auth.apiKey) { + return; + } + + const summaryMessages = [ + { + role: "user" as const, + content: [{ type: "text" as const, text: buildSummaryPrompt(conversationText) }], + timestamp: Date.now(), + }, + ]; + + const response = await complete( + model, + { messages: summaryMessages }, + { + apiKey: auth.apiKey, + headers: auth.headers, + env: auth.env, + reasoningEffort: "high", + cacheRetention: "none", + sessionId: uuidv7(), + }, + ); + + const summary = response.content + .filter((c): c is { type: "text"; text: string } => c.type === "text") + .map((c) => c.text) + .join("\n"); + + await showSummaryUi(summary, ctx); + }, + }); +} diff --git a/examples/extensions/system-prompt-header.ts b/examples/extensions/system-prompt-header.ts new file mode 100644 index 0000000..c6845b2 --- /dev/null +++ b/examples/extensions/system-prompt-header.ts @@ -0,0 +1,17 @@ +/** + * Displays a status widget showing the system prompt length. + * + * Demonstrates ctx.getSystemPrompt() for accessing the effective system prompt. + */ +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.on("agent_start", (_event, ctx) => { + const prompt = ctx.getSystemPrompt(); + ctx.ui.setStatus("system-prompt", `System: ${prompt.length} chars`); + }); + + pi.on("session_shutdown", (_event, ctx) => { + ctx.ui.setStatus("system-prompt", undefined); + }); +} diff --git a/examples/extensions/tic-tac-toe.ts b/examples/extensions/tic-tac-toe.ts new file mode 100644 index 0000000..8077a57 --- /dev/null +++ b/examples/extensions/tic-tac-toe.ts @@ -0,0 +1,1008 @@ +/** + * Tic-Tac-Toe extension - demonstrates executionMode: "sequential" on tools. + * + * The user plays via /tic-tac-toe (arrow keys + Enter). + * The agent plays via a single tool `tic_tac_toe` that takes ONE atomic action + * per call. To play at (r, c) from its cursor (r0, c0) the agent must emit the + * required move_* and a final `play` as SEPARATE tool_use blocks inside ONE + * assistant response. + * + * Move actions share the agent cursor and have a 300ms delay. Under the + * default parallel tool-execution mode this races: `play` can resolve before + * the earlier `move_*` calls finish and O lands on the wrong cell. With + * `executionMode: "sequential"` the runner serializes the sibling calls and O + * lands on the intended cell. + * + * The user cursor (TUI-only) and the agent cursor (tool-only) are stored in + * separate variables. Only the agent cursor is ever exposed to the agent. + */ + +import { StringEnum } from "@earendil-works/pi-ai"; +import type { ExtensionAPI, ExtensionContext, Theme, ToolExecutionMode } from "@earendil-works/pi-coding-agent"; +import { type Component, matchesKey, Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; +import { Type } from "typebox"; + +// Thrown from the tool on illegal actions. The agent runtime surfaces thrown +// errors as tool errors (isError=true) without resetting any of our state. +class TicTacToeError extends Error { + constructor(message: string) { + super(message); + this.name = "TicTacToeError"; + } +} + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- + +type Cell = " " | "X" | "O"; +type GameStatus = "playing" | "win_X" | "win_O" | "draw"; + +interface GameState { + board: Cell[][]; + // User cursor (TUI-only, never exposed to the agent). + userCursorRow: number; + userCursorCol: number; + // Agent cursor (manipulated by the tool, shown in the TUI during O's turn). + agentCursorRow: number; + agentCursorCol: number; + status: GameStatus; + userMark: Cell; + agentMark: Cell; + currentTurn: Cell; +} + +// Persisted with each toolResult for state reconstruction AND sent to the +// agent as `details`. Only the agent cursor is included: the user cursor is +// private to the TUI. +interface BoardDetails { + board: Cell[][]; + agentCursorRow: number; + agentCursorCol: number; + status: GameStatus; + currentTurn: Cell; +} + +// --------------------------------------------------------------------------- +// Game logic +// --------------------------------------------------------------------------- + +// Agent cursor home: where the cursor is reset to after a SUCCESSFUL play. +// Pinned at (0,0) so every non-origin play requires at least one move, which +// guarantees multiple tool calls per turn and makes the parallel-vs-sequential +// behavior observable in the demo. The cursor is NOT reset when the user plays +// nor on a failed `play` (cell taken), so the agent can retry without +// starting over. +const AGENT_CURSOR_HOME_ROW = 0; +const AGENT_CURSOR_HOME_COL = 0; + +function createInitialState(): GameState { + return { + board: [ + [" ", " ", " "], + [" ", " ", " "], + [" ", " ", " "], + ], + userCursorRow: 1, + userCursorCol: 1, + agentCursorRow: AGENT_CURSOR_HOME_ROW, + agentCursorCol: AGENT_CURSOR_HOME_COL, + status: "playing", + userMark: "X", + agentMark: "O", + currentTurn: "X", + }; +} + +function getWinLine(board: Cell[][]): [number, number][] | null { + const lines: [number, number][][] = [ + [ + [0, 0], + [0, 1], + [0, 2], + ], + [ + [1, 0], + [1, 1], + [1, 2], + ], + [ + [2, 0], + [2, 1], + [2, 2], + ], + [ + [0, 0], + [1, 0], + [2, 0], + ], + [ + [0, 1], + [1, 1], + [2, 1], + ], + [ + [0, 2], + [1, 2], + [2, 2], + ], + [ + [0, 0], + [1, 1], + [2, 2], + ], + [ + [0, 2], + [1, 1], + [2, 0], + ], + ]; + for (const line of lines) { + const vals = line.map(([r, c]) => board[r][c]); + if (vals[0] !== " " && vals[0] === vals[1] && vals[1] === vals[2]) { + return line; + } + } + return null; +} + +function checkWin(board: Cell[][]): GameStatus { + const winLine = getWinLine(board); + if (winLine) { + const [r, c] = winLine[0]; + return board[r][c] === "X" ? "win_X" : "win_O"; + } + if (board.every((row) => row.every((c) => c !== " "))) { + return "draw"; + } + return "playing"; +} + +function boardToAscii(board: Cell[][], agentCursorRow: number, agentCursorCol: number): string { + // Plain grid with coordinates for empty cells, marking the agent cursor + // position with angle brackets. The user cursor is NEVER included: it is a + // TUI-only concept and must not leak to the agent. + const rows = board.map((row, r) => + row + .map((c, cIdx) => { + const onCursor = r === agentCursorRow && cIdx === agentCursorCol; + if (c === " ") return onCursor ? `<[${r},${cIdx}]>` : ` [${r},${cIdx}] `; + return onCursor ? ` <${c}> ` : ` ${c} `; + }) + .join("|"), + ); + const separator = "---------+---------+---------"; + return rows.join(`\n${separator}\n`); +} + +// --------------------------------------------------------------------------- +// Visual board rendering (ANSI). +// - Cells have NO background fill. Only the centered glyph is drawn. +// - Played cells color their glyph AND their surrounding borders in the +// player's color, so each mark reads as a colored boxed region. +// - Cursor is indicated with colored borders around the cursor cell. +// --------------------------------------------------------------------------- + +const CELL_WIDTH = 7; +const CELL_HEIGHT = 3; + +// Player colors (SGR fg codes). Also used for the borders of played cells. +const FG_CODE_X = "34"; // blue +const FG_CODE_O = "33"; // yellow +const FG_CODE_WIN = "32"; // green (overrides on the winning line) + +// Single-character glyphs, picked for maximum visual size without emoji. +// - \u2573 (BOX DRAWINGS LIGHT DIAGONAL CROSS) for X +// - \u25ef (LARGE CIRCLE) for O +const GLYPH_X = "\u2573"; +const GLYPH_O = "\u25ef"; + +const DIM = (s: string) => `\x1b[2m${s}\x1b[22m`; +const RESET = "\x1b[0m"; + +function centerPad(content: string, width: number): string { + const contentLen = visibleWidth(content); + if (contentLen >= width) return truncateToWidth(content, width); + const pad = width - contentLen; + const left = Math.floor(pad / 2); + return " ".repeat(left) + content + " ".repeat(pad - left); +} + +// Fg color for a played cell's glyph and its surrounding borders. Undefined +// for empty cells. +function cellFgCode(cell: Cell, isWin: boolean): string | undefined { + if (cell === " ") return undefined; + if (isWin) return FG_CODE_WIN; + return cell === "X" ? FG_CODE_X : FG_CODE_O; +} + +function buildCellContent(mark: Cell, lineIdx: number, isWin: boolean): string { + const empty = " ".repeat(CELL_WIDTH); + if (mark === " ") return empty; + + const isMidLine = lineIdx === Math.floor(CELL_HEIGHT / 2); + if (!isMidLine) return empty; + + const glyph = mark === "X" ? GLYPH_X : GLYPH_O; + const fg = cellFgCode(mark, isWin) as string; + const padLen = CELL_WIDTH - visibleWidth(glyph); + const leftPad = Math.floor(padLen / 2); + const rightPad = padLen - leftPad; + return `${" ".repeat(leftPad)}\x1b[${fg};1m${glyph}${RESET}${" ".repeat(rightPad)}`; +} + +// Fg color for a border char based on its adjacent cells. Undefined when no +// adjacent cell is played or when adjacent plays disagree (border stays dim +// to show the separation). +function borderFgCode(adjacent: ReadonlyArray<{ cell: Cell; isWin: boolean }>): string | undefined { + const fgs = adjacent.map((a) => cellFgCode(a.cell, a.isWin)).filter((f): f is string => !!f); + if (fgs.length === 0) return undefined; + const first = fgs[0]; + return fgs.every((f) => f === first) ? first : undefined; +} + +interface BoardRenderOpts { + board: Cell[][]; + maxWidth: number; + // Optional cursor overlay. Omit to render a static snapshot (used in tool + // results, move messages, and the game-over banner). + cursor?: { row: number; col: number; owner: "user" | "agent" }; +} + +function renderBoard(opts: BoardRenderOpts): string[] { + const { board, maxWidth, cursor } = opts; + const showCursor = !!cursor; + const cr = cursor?.row ?? -1; + const cc = cursor?.col ?? -1; + + // Green for user cursor, yellow for agent cursor. + const cursorSgr = cursor?.owner === "agent" ? "\x1b[33;1m" : "\x1b[32;1m"; + + const winLine = getWinLine(board); + const winCells = new Set((winLine ?? []).map(([r, c]) => `${r},${c}`)); + const cellAt = (r: number, c: number) => ({ cell: board[r][c], isWin: winCells.has(`${r},${c}`) }); + + const isCursorCorner = (gridR: number, gridC: number): boolean => + showCursor && (gridR === cr || gridR === cr + 1) && (gridC === cc || gridC === cc + 1); + const isCursorHSegment = (gridR: number, c: number): boolean => + showCursor && c === cc && (gridR === cr || gridR === cr + 1); + const isCursorVBorder = (r: number, gridC: number): boolean => + showCursor && r === cr && (gridC === cc || gridC === cc + 1); + + const paintBorder = (ch: string, highlighted: boolean, fgCode: string | undefined): string => { + if (highlighted) return `${cursorSgr}${ch}${RESET}`; + if (fgCode) return `\x1b[${fgCode};1m${ch}${RESET}`; + return DIM(ch); + }; + + const cornerChar = (gridR: number, gridC: number): string => { + if (gridR === 0 && gridC === 0) return "\u250c"; + if (gridR === 0 && gridC === 3) return "\u2510"; + if (gridR === 3 && gridC === 0) return "\u2514"; + if (gridR === 3 && gridC === 3) return "\u2518"; + if (gridR === 0) return "\u252c"; + if (gridR === 3) return "\u2534"; + if (gridC === 0) return "\u251c"; + if (gridC === 3) return "\u2524"; + return "\u253c"; + }; + + const cornerAdjacent = (gridR: number, gridC: number) => { + const out: { cell: Cell; isWin: boolean }[] = []; + for (const [dr, dc] of [ + [-1, -1], + [-1, 0], + [0, -1], + [0, 0], + ]) { + const r = gridR + dr; + const c = gridC + dc; + if (r >= 0 && r < 3 && c >= 0 && c < 3) out.push(cellAt(r, c)); + } + return out; + }; + + const lines: string[] = []; + + for (let gridR = 0; gridR <= 3; gridR++) { + // Horizontal border row. + let row = ""; + for (let gridC = 0; gridC <= 3; gridC++) { + const cornerColor = borderFgCode(cornerAdjacent(gridR, gridC)); + row += paintBorder(cornerChar(gridR, gridC), isCursorCorner(gridR, gridC), cornerColor); + if (gridC < 3) { + const adj: { cell: Cell; isWin: boolean }[] = []; + if (gridR > 0) adj.push(cellAt(gridR - 1, gridC)); + if (gridR < 3) adj.push(cellAt(gridR, gridC)); + const segColor = borderFgCode(adj); + row += paintBorder("\u2500".repeat(CELL_WIDTH), isCursorHSegment(gridR, gridC), segColor); + } + } + lines.push(centerPad(row, maxWidth)); + + if (gridR === 3) break; + + for (let lineIdx = 0; lineIdx < CELL_HEIGHT; lineIdx++) { + let contentRow = ""; + for (let gridC = 0; gridC <= 3; gridC++) { + const adj: { cell: Cell; isWin: boolean }[] = []; + if (gridC > 0) adj.push(cellAt(gridR, gridC - 1)); + if (gridC < 3) adj.push(cellAt(gridR, gridC)); + const vColor = borderFgCode(adj); + contentRow += paintBorder("\u2502", isCursorVBorder(gridR, gridC), vColor); + if (gridC < 3) { + contentRow += buildCellContent(board[gridR][gridC], lineIdx, winCells.has(`${gridR},${gridC}`)); + } + } + lines.push(centerPad(contentRow, maxWidth)); + } + } + + return lines; +} + +// Full TUI board with the right cursor overlayed for the current turn. +function renderVisualBoard(state: GameState, maxWidth: number): string[] { + const isUserTurn = state.currentTurn === state.userMark; + const cursor = + state.status !== "playing" + ? undefined + : { + row: isUserTurn ? state.userCursorRow : state.agentCursorRow, + col: isUserTurn ? state.userCursorCol : state.agentCursorCol, + owner: (isUserTurn ? "user" : "agent") as "user" | "agent", + }; + return renderBoard({ board: state.board, maxWidth, cursor }); +} + +/** Static snapshot used inside tool results and custom messages. */ +function renderBoardSnapshot(board: Cell[][], maxWidth: number): string[] { + return renderBoard({ board, maxWidth }); +} + +// --------------------------------------------------------------------------- +// TUI component +// --------------------------------------------------------------------------- + +class TicTacToeComponent implements Component { + private state: GameState; + private onClose: () => void; + private onUserPlay: (row: number, col: number) => void; + private tui: { requestRender: () => void }; + private cachedLines: string[] = []; + private cachedWidth = 0; + private version = 0; + private cachedVersion = -1; + + constructor( + tui: { requestRender: () => void }, + onClose: () => void, + onUserPlay: (row: number, col: number) => void, + state: GameState, + ) { + this.tui = tui; + this.onClose = onClose; + this.onUserPlay = onUserPlay; + this.state = state; + } + + updateState(state: GameState): void { + this.state = state; + this.version++; + this.tui.requestRender(); + } + + handleInput(data: string): boolean { + if (matchesKey(data, "escape") || data === "q" || data === "Q") { + this.onClose(); + return true; + } + if (this.state.status !== "playing") { + if (data === "r" || data === "R") { + this.onClose(); + return true; + } + return true; + } + if (this.state.currentTurn !== this.state.userMark) return true; + + if (matchesKey(data, "up") && this.state.userCursorRow > 0) { + this.state.userCursorRow--; + this.version++; + this.tui.requestRender(); + } else if (matchesKey(data, "down") && this.state.userCursorRow < 2) { + this.state.userCursorRow++; + this.version++; + this.tui.requestRender(); + } else if (matchesKey(data, "left") && this.state.userCursorCol > 0) { + this.state.userCursorCol--; + this.version++; + this.tui.requestRender(); + } else if (matchesKey(data, "right") && this.state.userCursorCol < 2) { + this.state.userCursorCol++; + this.version++; + this.tui.requestRender(); + } else if (matchesKey(data, "return") || data === " ") { + const { userCursorRow, userCursorCol } = this.state; + if (this.state.board[userCursorRow][userCursorCol] === " ") { + this.onUserPlay(userCursorRow, userCursorCol); + } + } + return true; + } + + invalidate(): void { + this.cachedWidth = 0; + } + + render(width: number): string[] { + if (width === this.cachedWidth && this.cachedVersion === this.version) { + return this.cachedLines; + } + + const ESC = "\x1b["; + const reset = `${ESC}0m`; + const bold = (s: string) => `${ESC}1m${s}${reset}`; + const dim = (s: string) => `${ESC}2m${s}${reset}`; + const blue = (s: string) => `${ESC}34m${s}${reset}`; + const yellow = (s: string) => `${ESC}33m${s}${reset}`; + const green = (s: string) => `${ESC}32m${s}${reset}`; + + const lines: string[] = []; + + // Top title banner, full width. + const titleText = " Tic-Tac-Toe "; + const titleLen = visibleWidth(titleText); + const borderLen = Math.max(0, width - titleLen); + const leftBorder = Math.floor(borderLen / 2); + const rightBorder = borderLen - leftBorder; + lines.push(dim("\u2500".repeat(leftBorder)) + bold(blue(titleText)) + dim("\u2500".repeat(rightBorder))); + + lines.push(""); + + // Status line. + if (this.state.status !== "playing") { + const statusText = + this.state.status === "draw" + ? bold(yellow("Draw!")) + : this.state.status === "win_X" + ? bold(green("X wins!")) + : bold(yellow("O wins!")); + lines.push(centerPad(statusText, width)); + } else if (this.state.currentTurn === "X") { + lines.push(centerPad(`Turn: ${bold(blue("X"))} (You) ${dim("|")} ${bold(yellow("O"))} (Agent)`, width)); + } else { + lines.push(centerPad(`${blue("X")} (You) ${dim("|")} Turn: ${bold(yellow("O"))} (Agent)`, width)); + } + + lines.push(""); + lines.push(""); + + lines.push(...renderVisualBoard(this.state, width)); + + lines.push(""); + lines.push(""); + + // Footer. + let footer: string; + if (this.state.status !== "playing") { + footer = `${bold("R")} restart ${dim("|")} ${bold("Q")}/${bold("ESC")} quit`; + } else if (this.state.currentTurn !== this.state.userMark) { + footer = dim("Agent is thinking..."); + } else { + footer = `${bold("\u2190\u2191\u2193\u2192")} move ${dim("|")} ${bold("ENTER")} play ${dim("|")} ${bold("ESC")} quit`; + } + lines.push(centerPad(footer, width)); + + // Bottom separator between the component and the editor below. + lines.push(""); + lines.push(dim("\u2500".repeat(width))); + + this.cachedLines = lines; + this.cachedWidth = width; + this.cachedVersion = this.version; + return lines; + } +} + +// --------------------------------------------------------------------------- +// Move-message renderer (full width banner) +// --------------------------------------------------------------------------- + +// Full-width banner message with an optional board snapshot underneath. +class BannerMessageComponent implements Component { + private readonly title: string; + private readonly details: BoardDetails | undefined; + private readonly expanded: boolean; + private readonly theme: Theme; + + constructor(title: string, details: BoardDetails | undefined, expanded: boolean, theme: Theme) { + this.title = title; + this.details = details; + this.expanded = expanded; + this.theme = theme; + } + + invalidate(): void {} + + render(width: number): string[] { + const dim = (s: string) => this.theme.fg("dim", s); + const lines: string[] = []; + const titleLen = visibleWidth(this.title); + const fillLen = Math.max(0, width - titleLen - 2); + const leftFill = Math.floor(fillLen / 2); + const rightFill = fillLen - leftFill; + lines.push(`${dim("\u2500".repeat(leftFill))} ${this.title} ${dim("\u2500".repeat(rightFill))}`); + + if (this.expanded && this.details) { + lines.push(""); + lines.push(...renderBoardSnapshot(this.details.board, width)); + } + + return lines; + } +} + +// End-of-game banner: two dim hrs, a big colored title line, and the final +// board with the winning line highlighted. +class GameOverMessageComponent implements Component { + private readonly status: GameStatus; + private readonly details: BoardDetails | undefined; + private readonly theme: Theme; + + constructor(status: GameStatus, details: BoardDetails | undefined, theme: Theme) { + this.status = status; + this.details = details; + this.theme = theme; + } + + invalidate(): void {} + + render(width: number): string[] { + const dim = (s: string) => this.theme.fg("dim", s); + const bold = (s: string) => this.theme.bold(s); + + const hr = dim("\u2500".repeat(width)); + const lines: string[] = []; + lines.push(hr); + lines.push(""); + + let title: string; + let sub: string; + switch (this.status) { + case "win_X": + title = bold(this.theme.fg("accent", "\u2605 Player X wins \u2605")); + sub = "You beat the agent."; + break; + case "win_O": + title = bold(this.theme.fg("warning", "\u2605 Player O wins \u2605")); + sub = "The agent beat you."; + break; + case "draw": + title = bold(this.theme.fg("muted", "\u2014 Draw \u2014")); + sub = "No winner."; + break; + default: + title = bold("Game over"); + sub = ""; + break; + } + + for (const line of [title, dim(sub)]) { + const pad = Math.max(0, width - visibleWidth(line)); + lines.push(`${" ".repeat(Math.floor(pad / 2))}${line}`); + } + + lines.push(""); + if (this.details) { + lines.push(...renderBoardSnapshot(this.details.board, width)); + lines.push(""); + } + lines.push(hr); + + return lines; + } +} + +// --------------------------------------------------------------------------- +// Delay helper +// --------------------------------------------------------------------------- + +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +// --------------------------------------------------------------------------- +// Extension +// --------------------------------------------------------------------------- + +const SAVE_TYPE = "tic-tac-toe-save"; +const MOVE_MESSAGE_TYPE = "tic-tac-toe-move"; +const GAME_OVER_MESSAGE_TYPE = "tic-tac-toe-game-over"; + +let gameState: GameState = createInitialState(); +let component: TicTacToeComponent | null = null; +let gameActive = false; + +function reconstructState(ctx: ExtensionContext): void { + gameState = createInitialState(); + gameActive = false; + + for (const entry of ctx.sessionManager.getBranch()) { + if (entry.type !== "message") continue; + const msg = entry.message; + if (msg.role !== "toolResult") continue; + if (msg.toolName !== "tic_tac_toe" && msg.toolName !== "tic_tac_toe_see_board") continue; + + const details = msg.details as BoardDetails | undefined; + if (details) { + gameState.board = details.board.map((row) => [...row]); + gameState.agentCursorRow = details.agentCursorRow; + gameState.agentCursorCol = details.agentCursorCol; + gameState.status = details.status; + gameState.currentTurn = details.currentTurn; + } + } +} + +function getBoardDetails(): BoardDetails { + return { + board: gameState.board.map((row) => [...row]), + agentCursorRow: gameState.agentCursorRow, + agentCursorCol: gameState.agentCursorCol, + status: gameState.status, + currentTurn: gameState.currentTurn, + }; +} + +export default function (pi: ExtensionAPI) { + pi.on("session_start", async (_event, ctx) => reconstructState(ctx)); + pi.on("session_tree", async (_event, ctx) => reconstructState(ctx)); + + // Sent once per game at end-of-game. The custom renderer paints the banner; + // `content` is a plain-text fallback for any non-TUI consumer and for the + // LLM (in case the message ends up in future context). + const emitGameOverMessage = (): void => { + const label = + gameState.status === "win_X" + ? "Player X (human) wins" + : gameState.status === "win_O" + ? "Player O (agent) wins" + : gameState.status === "draw" + ? "Draw" + : "Game over"; + pi.sendMessage({ + customType: GAME_OVER_MESSAGE_TYPE, + content: `Game over: ${label}.`, + display: true, + details: getBoardDetails(), + }); + }; + + // ----------------------------------------------------------------------- + // Custom message renderer for user move messages + // ----------------------------------------------------------------------- + pi.registerMessageRenderer(MOVE_MESSAGE_TYPE, (message, { expanded }, theme) => { + const details = message.details as BoardDetails | undefined; + const turnLabel = + details?.currentTurn === "O" + ? `${theme.fg("warning", theme.bold("O"))} (Agent)` + : `${theme.fg("accent", theme.bold("X"))} (You)`; + const title = `${theme.fg("accent", theme.bold("Player X played"))} ${theme.fg("dim", "\u2192")} next: ${turnLabel}`; + return new BannerMessageComponent(title, details, expanded, theme); + }); + + // ----------------------------------------------------------------------- + // Custom message renderer for game-over messages + // ----------------------------------------------------------------------- + pi.registerMessageRenderer(GAME_OVER_MESSAGE_TYPE, (message, _options, theme) => { + const details = message.details as BoardDetails | undefined; + const status = (details?.status ?? "draw") as GameStatus; + return new GameOverMessageComponent(status, details, theme); + }); + + // ----------------------------------------------------------------------- + // before_agent_start - inject game instructions each turn + // ----------------------------------------------------------------------- + pi.on("before_agent_start", async (event) => { + if (!gameActive) return undefined; + + const instructions = ` + +## Tic-Tac-Toe (you are Player O) + +A tic-tac-toe game is in progress. The human is Player X. You are Player O. +The human plays through a TUI; you play through the \`tic_tac_toe\` tool. + +### Turn protocol + +When the human plays, you receive a message that contains the cell X marked, +the full board, and YOUR cursor position (Player O's cursor). The message is +the source of truth for the board. + +Player O's cursor persists between O turns. It is reset to (row=${AGENT_CURSOR_HOME_ROW}, col=${AGENT_CURSOR_HOME_COL}) +only after a successful \`play\`. If a \`play\` fails (cell already taken), the +cursor stays where it was, so you can move and retry. + +You may also call \`tic_tac_toe_see_board\` if you want the current board and +your cursor position restated at any point. The user's cursor is private and +is never shown to you. + +### The tool + +\`tic_tac_toe\` takes ONE action per call: +- \`move_up\` / \`move_down\` / \`move_left\` / \`move_right\`: move YOUR cursor one cell (clamped at edges) +- \`play\`: place O on the cell under YOUR cursor. Errors if the cell is not empty. + +There is no batched form. One call = one action. + +### CRITICAL: emit the whole turn in a single response + +To play at (r, c) from your cursor (r0, c0) emit, in order: +- \`move_down\` (r - r0) times (or \`move_up\` (r0 - r) times if r < r0) +- \`move_right\` (c - c0) times (or \`move_left\` (c0 - c) times if c < c0) +- one call of \`play\` + +All of these tool calls MUST be emitted in the SAME assistant response, as +separate tool_use blocks, before you stop. Do not: +- split the sequence across multiple assistant responses, +- wait for a move result before emitting the next move or \`play\`, +- write any explanation or text between the tool calls, +- call any other tool during your turn (except \`tic_tac_toe_see_board\` when you + explicitly need the state restated). + +Decide the target cell first, then dump every action for the turn in one go. + +### Examples (cursor starts at (${AGENT_CURSOR_HOME_ROW}, ${AGENT_CURSOR_HOME_COL})) + +- Target (0,0): one call, \`play\`. +- Target (0,2): \`move_right\`, \`move_right\`, \`play\`. Three calls, one response. +- Target (1,1): \`move_down\`, \`move_right\`, \`play\`. Three calls, one response. +- Target (2,2): \`move_down\`, \`move_down\`, \`move_right\`, \`move_right\`, \`play\`. Five calls, one response. + +### Strategy + +1. If you have two O's in a line with the third cell empty, win by playing there. +2. Otherwise, if X has two in a line with the third cell empty, block there. +3. Otherwise, prefer center, then corners, then edges. +`; + + return { + systemPrompt: event.systemPrompt + instructions, + }; + }); + + // ----------------------------------------------------------------------- + // /tic-tac-toe command + // ----------------------------------------------------------------------- + pi.registerCommand("tic-tac-toe", { + description: "Play tic-tac-toe against the agent", + + handler: async (_args, ctx) => { + if (ctx.mode !== "tui") { + ctx.ui.notify("Tic-tac-toe requires interactive mode", "error"); + return; + } + + reconstructState(ctx); + if (gameState.status !== "playing") { + gameState = createInitialState(); + } + gameActive = true; + pi.setSessionName("Tic-Tac-Toe"); + + await ctx.ui.custom((tui, _theme, _kb, done) => { + component = new TicTacToeComponent( + tui, + () => { + component = null; + gameActive = false; + done(undefined); + }, + (row, col) => { + gameState.board[row][col] = gameState.userMark; + gameState.status = checkWin(gameState.board); + if (gameState.status === "playing") { + gameState.currentTurn = gameState.agentMark; + } + component?.updateState(gameState); + pi.appendEntry(SAVE_TYPE, getBoardDetails()); + + if (gameState.status === "playing") { + // IMPORTANT: user play does NOT touch the agent cursor. + // The agent cursor is only reset after a successful agent play. + const boardAscii = boardToAscii( + gameState.board, + gameState.agentCursorRow, + gameState.agentCursorCol, + ); + pi.sendMessage( + { + customType: MOVE_MESSAGE_TYPE, + content: + `Player X played at (row=${row}, col=${col}). It is now Player O's turn.\n\n` + + `Board (your cursor marked with <>):\n${boardAscii}\n\n` + + `Your cursor is at (row=${gameState.agentCursorRow}, col=${gameState.agentCursorCol}). ` + + `Decide your target cell, then emit every move_* and the final play ` + + `as separate tic_tac_toe tool calls in THIS response.`, + display: true, + details: getBoardDetails(), + }, + { triggerTurn: true }, + ); + } else { + emitGameOverMessage(); + gameActive = false; + } + }, + gameState, + ); + return component; + }); + }, + }); + + // ----------------------------------------------------------------------- + // tic_tac_toe tool - one action per call. + // ----------------------------------------------------------------------- + + type Action = "move_up" | "move_down" | "move_left" | "move_right" | "play"; + + const ACTION_DELAYS: Record = { + move_up: 300, + move_down: 300, + move_left: 300, + move_right: 300, + play: 0, + }; + + pi.registerTool({ + name: "tic_tac_toe", + label: "Tic-Tac-Toe", + description: + "Execute ONE tic-tac-toe action as Player O. `action` is exactly one of: move_up, move_down, move_left, move_right (move YOUR cursor one cell, clamped at edges), or play (place O under YOUR cursor; errors if the cell is not empty). There is no batched form. To play at (r, c) from your current cursor (r0, c0), emit the required move_down/move_up and move_right/move_left calls, then play, all as separate tool_use blocks in the SAME assistant response. Do not split the sequence across responses and do not wait for a result before emitting the next call. Your cursor position persists between turns and is reset to (0,0) only after a successful play.", + promptSnippet: "Play a tic-tac-toe action (move_up/down/left/right or play) as Player O", + promptGuidelines: [ + "When it is your tic-tac-toe turn, decide the target cell first, then emit every move_* plus the final play as separate tic_tac_toe tool calls in a SINGLE assistant response. Never split them across responses or wait for intermediate results.", + "Never ask the user for the board. The board and your cursor position are included in the user's move message; use tic_tac_toe_see_board if you need them restated.", + ], + parameters: Type.Object({ + action: StringEnum(["move_up", "move_down", "move_left", "move_right", "play"] as const, { + description: + "The single action to perform this call. Emit multiple tic_tac_toe calls in one response to string actions together.", + }), + }), + executionMode: "sequential" as ToolExecutionMode, + + async execute(_toolCallId, params, _signal, _onUpdate, _ctx) { + const actionDelay = ACTION_DELAYS[params.action]; + if (actionDelay > 0) await delay(actionDelay); + + let result: string; + + switch (params.action) { + case "move_up": + if (gameState.agentCursorRow > 0) gameState.agentCursorRow--; + result = `Moved up. Cursor: (${gameState.agentCursorRow}, ${gameState.agentCursorCol})`; + break; + case "move_down": + if (gameState.agentCursorRow < 2) gameState.agentCursorRow++; + result = `Moved down. Cursor: (${gameState.agentCursorRow}, ${gameState.agentCursorCol})`; + break; + case "move_left": + if (gameState.agentCursorCol > 0) gameState.agentCursorCol--; + result = `Moved left. Cursor: (${gameState.agentCursorRow}, ${gameState.agentCursorCol})`; + break; + case "move_right": + if (gameState.agentCursorCol < 2) gameState.agentCursorCol++; + result = `Moved right. Cursor: (${gameState.agentCursorRow}, ${gameState.agentCursorCol})`; + break; + case "play": { + if (gameState.status !== "playing") { + throw new TicTacToeError(`Game is over (${gameState.status}).`); + } + if (gameState.currentTurn !== gameState.agentMark) { + throw new TicTacToeError("It is not your turn."); + } + const r = gameState.agentCursorRow; + const c = gameState.agentCursorCol; + if (gameState.board[r][c] !== " ") { + // Do NOT reset the cursor on failure. The agent can retry + // from the cursor's current position. + component?.updateState(gameState); + pi.appendEntry(SAVE_TYPE, getBoardDetails()); + throw new TicTacToeError( + `Cell (${r},${c}) is already ${gameState.board[r][c]}. Your cursor is still at (${r},${c}). Move to an empty cell and retry play.`, + ); + } + gameState.board[r][c] = gameState.agentMark; + gameState.status = checkWin(gameState.board); + // Reset agent cursor to home ONLY on successful play. + gameState.agentCursorRow = AGENT_CURSOR_HOME_ROW; + gameState.agentCursorCol = AGENT_CURSOR_HOME_COL; + if (gameState.status === "playing") { + gameState.currentTurn = gameState.userMark; + result = `Placed O at (${r},${c}). Cursor reset to (${AGENT_CURSOR_HOME_ROW},${AGENT_CURSOR_HOME_COL}). Your turn, X!`; + } else if (gameState.status === "win_O") { + result = `Placed O at (${r},${c}). Player O wins!`; + gameActive = false; + emitGameOverMessage(); + } else if (gameState.status === "draw") { + result = `Placed O at (${r},${c}). It's a draw!`; + gameActive = false; + emitGameOverMessage(); + } else { + result = `Placed O at (${r},${c}).`; + } + break; + } + } + + component?.updateState(gameState); + pi.appendEntry(SAVE_TYPE, getBoardDetails()); + + return { + content: [{ type: "text", text: result }], + details: getBoardDetails(), + }; + }, + + renderCall(args, theme) { + const action = typeof args.action === "string" ? args.action : ""; + return new Text(theme.fg("toolTitle", theme.bold("tic_tac_toe ")) + theme.fg("muted", action), 0, 0); + }, + + renderResult(result, { expanded }, theme, context) { + const details = result.details as BoardDetails | undefined; + const text = result.content[0]; + const msg = text?.type === "text" ? text.text : ""; + const prefix = context?.isError ? theme.fg("error", "\u2717 ") : theme.fg("success", "\u2713 "); + const summary = prefix + theme.fg("muted", msg); + + if (expanded && details) { + return new BannerMessageComponent(summary, details, true, theme); + } + return new Text(summary, 0, 0); + }, + }); + + // ----------------------------------------------------------------------- + // tic_tac_toe_see_board tool - inspect board + agent cursor. + // ----------------------------------------------------------------------- + pi.registerTool({ + name: "tic_tac_toe_see_board", + label: "See Board", + description: + "Return the current tic-tac-toe board state and YOUR cursor position (Player O). Takes no arguments. Use this if you need the current state restated mid-turn (for example after a failed play). The user's cursor is never exposed.", + promptSnippet: "Inspect the tic-tac-toe board and your cursor", + parameters: Type.Object({}), + + async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) { + const boardAscii = boardToAscii(gameState.board, gameState.agentCursorRow, gameState.agentCursorCol); + const text = + `Board (your cursor marked with <>):\n${boardAscii}\n\n` + + `Your cursor: (row=${gameState.agentCursorRow}, col=${gameState.agentCursorCol})\n` + + `Status: ${gameState.status}\n` + + `Turn: ${gameState.currentTurn === gameState.agentMark ? "Player O (you)" : "Player X"}`; + return { + content: [{ type: "text", text }], + details: getBoardDetails(), + }; + }, + + renderCall(_args, theme) { + return new Text(theme.fg("toolTitle", theme.bold("tic_tac_toe_see_board")), 0, 0); + }, + + renderResult(result, { expanded }, theme) { + const details = result.details as BoardDetails | undefined; + const summary = + theme.fg("success", "\u2713 ") + + theme.fg("muted", `cursor (${details?.agentCursorRow ?? 0},${details?.agentCursorCol ?? 0})`); + if (expanded && details) { + return new BannerMessageComponent(summary, details, true, theme); + } + return new Text(summary, 0, 0); + }, + }); +} diff --git a/examples/extensions/timed-confirm.ts b/examples/extensions/timed-confirm.ts new file mode 100644 index 0000000..1ab86e5 --- /dev/null +++ b/examples/extensions/timed-confirm.ts @@ -0,0 +1,70 @@ +/** + * Example extension demonstrating timed dialogs with live countdown. + * + * Commands: + * - /timed - Shows confirm dialog that auto-cancels after 5 seconds with countdown + * - /timed-select - Shows select dialog that auto-cancels after 10 seconds with countdown + * - /timed-signal - Shows confirm using AbortSignal (manual approach) + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + // Simple approach: use timeout option (recommended) + pi.registerCommand("timed", { + description: "Show a timed confirmation dialog (auto-cancels in 5s with countdown)", + handler: async (_args, ctx) => { + const confirmed = await ctx.ui.confirm( + "Timed Confirmation", + "This dialog will auto-cancel in 5 seconds. Confirm?", + { timeout: 5000 }, + ); + + if (confirmed) { + ctx.ui.notify("Confirmed by user!", "info"); + } else { + ctx.ui.notify("Cancelled or timed out", "info"); + } + }, + }); + + pi.registerCommand("timed-select", { + description: "Show a timed select dialog (auto-cancels in 10s with countdown)", + handler: async (_args, ctx) => { + const choice = await ctx.ui.select("Pick an option", ["Option A", "Option B", "Option C"], { timeout: 10000 }); + + if (choice) { + ctx.ui.notify(`Selected: ${choice}`, "info"); + } else { + ctx.ui.notify("Selection cancelled or timed out", "info"); + } + }, + }); + + // Manual approach: use AbortSignal for more control + pi.registerCommand("timed-signal", { + description: "Show a timed confirm using AbortSignal (manual approach)", + handler: async (_args, ctx) => { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 5000); + + ctx.ui.notify("Dialog will auto-cancel in 5 seconds...", "info"); + + const confirmed = await ctx.ui.confirm( + "Timed Confirmation", + "This dialog will auto-cancel in 5 seconds. Confirm?", + { signal: controller.signal }, + ); + + clearTimeout(timeoutId); + + if (confirmed) { + ctx.ui.notify("Confirmed by user!", "info"); + } else if (controller.signal.aborted) { + ctx.ui.notify("Dialog timed out (auto-cancelled)", "warning"); + } else { + ctx.ui.notify("Cancelled by user", "info"); + } + }, + }); +} diff --git a/examples/extensions/titlebar-spinner.ts b/examples/extensions/titlebar-spinner.ts new file mode 100644 index 0000000..51467ac --- /dev/null +++ b/examples/extensions/titlebar-spinner.ts @@ -0,0 +1,58 @@ +/** + * Titlebar Spinner Extension + * + * Shows a braille spinner animation in the terminal title while the agent is working. + * Uses `ctx.ui.setTitle()` to update the terminal title via the extension API. + * + * Usage: + * pi --extension examples/extensions/titlebar-spinner.ts + */ + +import path from "node:path"; +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; + +const BRAILLE_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; + +function getBaseTitle(pi: ExtensionAPI): string { + const cwd = path.basename(process.cwd()); + const session = pi.getSessionName(); + return session ? `π - ${session} - ${cwd}` : `π - ${cwd}`; +} + +export default function (pi: ExtensionAPI) { + let timer: ReturnType | null = null; + let frameIndex = 0; + + function stopAnimation(ctx: ExtensionContext) { + if (timer) { + clearInterval(timer); + timer = null; + } + frameIndex = 0; + ctx.ui.setTitle(getBaseTitle(pi)); + } + + function startAnimation(ctx: ExtensionContext) { + stopAnimation(ctx); + timer = setInterval(() => { + const frame = BRAILLE_FRAMES[frameIndex % BRAILLE_FRAMES.length]; + const cwd = path.basename(process.cwd()); + const session = pi.getSessionName(); + const title = session ? `${frame} π - ${session} - ${cwd}` : `${frame} π - ${cwd}`; + ctx.ui.setTitle(title); + frameIndex++; + }, 80); + } + + pi.on("agent_start", async (_event, ctx) => { + startAnimation(ctx); + }); + + pi.on("agent_end", async (_event, ctx) => { + stopAnimation(ctx); + }); + + pi.on("session_shutdown", async (_event, ctx) => { + stopAnimation(ctx); + }); +} diff --git a/examples/extensions/todo.ts b/examples/extensions/todo.ts new file mode 100644 index 0000000..67cba74 --- /dev/null +++ b/examples/extensions/todo.ts @@ -0,0 +1,297 @@ +/** + * Todo Extension - Demonstrates state management via session entries + * + * This extension: + * - Registers a `todo` tool for the LLM to manage todos + * - Registers a `/todos` command for users to view the list + * + * State is stored in tool result details (not external files), which allows + * proper branching - when you branch, the todo state is automatically + * correct for that point in history. + */ + +import { StringEnum } from "@earendil-works/pi-ai"; +import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent"; +import { matchesKey, Text, truncateToWidth } from "@earendil-works/pi-tui"; +import { Type } from "typebox"; + +interface Todo { + id: number; + text: string; + done: boolean; +} + +interface TodoDetails { + action: "list" | "add" | "toggle" | "clear"; + todos: Todo[]; + nextId: number; + error?: string; +} + +const TodoParams = Type.Object({ + action: StringEnum(["list", "add", "toggle", "clear"] as const), + text: Type.Optional(Type.String({ description: "Todo text (for add)" })), + id: Type.Optional(Type.Number({ description: "Todo ID (for toggle)" })), +}); + +/** + * UI component for the /todos command + */ +class TodoListComponent { + private todos: Todo[]; + private theme: Theme; + private onClose: () => void; + private cachedWidth?: number; + private cachedLines?: string[]; + + constructor(todos: Todo[], theme: Theme, onClose: () => void) { + this.todos = todos; + this.theme = theme; + this.onClose = onClose; + } + + handleInput(data: string): void { + if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) { + this.onClose(); + } + } + + render(width: number): string[] { + if (this.cachedLines && this.cachedWidth === width) { + return this.cachedLines; + } + + const lines: string[] = []; + const th = this.theme; + + lines.push(""); + const title = th.fg("accent", " Todos "); + const headerLine = + th.fg("borderMuted", "─".repeat(3)) + title + th.fg("borderMuted", "─".repeat(Math.max(0, width - 10))); + lines.push(truncateToWidth(headerLine, width)); + lines.push(""); + + if (this.todos.length === 0) { + lines.push(truncateToWidth(` ${th.fg("dim", "No todos yet. Ask the agent to add some!")}`, width)); + } else { + const done = this.todos.filter((t) => t.done).length; + const total = this.todos.length; + lines.push(truncateToWidth(` ${th.fg("muted", `${done}/${total} completed`)}`, width)); + lines.push(""); + + for (const todo of this.todos) { + const check = todo.done ? th.fg("success", "✓") : th.fg("dim", "○"); + const id = th.fg("accent", `#${todo.id}`); + const text = todo.done ? th.fg("dim", todo.text) : th.fg("text", todo.text); + lines.push(truncateToWidth(` ${check} ${id} ${text}`, width)); + } + } + + lines.push(""); + lines.push(truncateToWidth(` ${th.fg("dim", "Press Escape to close")}`, width)); + lines.push(""); + + this.cachedWidth = width; + this.cachedLines = lines; + return lines; + } + + invalidate(): void { + this.cachedWidth = undefined; + this.cachedLines = undefined; + } +} + +export default function (pi: ExtensionAPI) { + // In-memory state (reconstructed from session on load) + let todos: Todo[] = []; + let nextId = 1; + + /** + * Reconstruct state from session entries. + * Scans tool results for this tool and applies them in order. + */ + const reconstructState = (ctx: ExtensionContext) => { + todos = []; + nextId = 1; + + for (const entry of ctx.sessionManager.getBranch()) { + if (entry.type !== "message") continue; + const msg = entry.message; + if (msg.role !== "toolResult" || msg.toolName !== "todo") continue; + + const details = msg.details as TodoDetails | undefined; + if (details) { + todos = details.todos; + nextId = details.nextId; + } + } + }; + + // Reconstruct state on session events + pi.on("session_start", async (_event, ctx) => reconstructState(ctx)); + pi.on("session_tree", async (_event, ctx) => reconstructState(ctx)); + + // Register the todo tool for the LLM + pi.registerTool({ + name: "todo", + label: "Todo", + description: "Manage a todo list. Actions: list, add (text), toggle (id), clear", + parameters: TodoParams, + + async execute(_toolCallId, params, _signal, _onUpdate, _ctx) { + switch (params.action) { + case "list": + return { + content: [ + { + type: "text", + text: todos.length + ? todos.map((t) => `[${t.done ? "x" : " "}] #${t.id}: ${t.text}`).join("\n") + : "No todos", + }, + ], + details: { action: "list", todos: [...todos], nextId } as TodoDetails, + }; + + case "add": { + if (!params.text) { + return { + content: [{ type: "text", text: "Error: text required for add" }], + details: { action: "add", todos: [...todos], nextId, error: "text required" } as TodoDetails, + }; + } + const newTodo: Todo = { id: nextId++, text: params.text, done: false }; + todos.push(newTodo); + return { + content: [{ type: "text", text: `Added todo #${newTodo.id}: ${newTodo.text}` }], + details: { action: "add", todos: [...todos], nextId } as TodoDetails, + }; + } + + case "toggle": { + if (params.id === undefined) { + return { + content: [{ type: "text", text: "Error: id required for toggle" }], + details: { action: "toggle", todos: [...todos], nextId, error: "id required" } as TodoDetails, + }; + } + const todo = todos.find((t) => t.id === params.id); + if (!todo) { + return { + content: [{ type: "text", text: `Todo #${params.id} not found` }], + details: { + action: "toggle", + todos: [...todos], + nextId, + error: `#${params.id} not found`, + } as TodoDetails, + }; + } + todo.done = !todo.done; + return { + content: [{ type: "text", text: `Todo #${todo.id} ${todo.done ? "completed" : "uncompleted"}` }], + details: { action: "toggle", todos: [...todos], nextId } as TodoDetails, + }; + } + + case "clear": { + const count = todos.length; + todos = []; + nextId = 1; + return { + content: [{ type: "text", text: `Cleared ${count} todos` }], + details: { action: "clear", todos: [], nextId: 1 } as TodoDetails, + }; + } + + default: + return { + content: [{ type: "text", text: `Unknown action: ${params.action}` }], + details: { + action: "list", + todos: [...todos], + nextId, + error: `unknown action: ${params.action}`, + } as TodoDetails, + }; + } + }, + + renderCall(args, theme, _context) { + let text = theme.fg("toolTitle", theme.bold("todo ")) + theme.fg("muted", args.action); + if (args.text) text += ` ${theme.fg("dim", `"${args.text}"`)}`; + if (args.id !== undefined) text += ` ${theme.fg("accent", `#${args.id}`)}`; + return new Text(text, 0, 0); + }, + + renderResult(result, { expanded }, theme, _context) { + const details = result.details as TodoDetails | undefined; + if (!details) { + const text = result.content[0]; + return new Text(text?.type === "text" ? text.text : "", 0, 0); + } + + if (details.error) { + return new Text(theme.fg("error", `Error: ${details.error}`), 0, 0); + } + + const todoList = details.todos; + + switch (details.action) { + case "list": { + if (todoList.length === 0) { + return new Text(theme.fg("dim", "No todos"), 0, 0); + } + let listText = theme.fg("muted", `${todoList.length} todo(s):`); + const display = expanded ? todoList : todoList.slice(0, 5); + for (const t of display) { + const check = t.done ? theme.fg("success", "✓") : theme.fg("dim", "○"); + const itemText = t.done ? theme.fg("dim", t.text) : theme.fg("muted", t.text); + listText += `\n${check} ${theme.fg("accent", `#${t.id}`)} ${itemText}`; + } + if (!expanded && todoList.length > 5) { + listText += `\n${theme.fg("dim", `... ${todoList.length - 5} more`)}`; + } + return new Text(listText, 0, 0); + } + + case "add": { + const added = todoList[todoList.length - 1]; + return new Text( + theme.fg("success", "✓ Added ") + + theme.fg("accent", `#${added.id}`) + + " " + + theme.fg("muted", added.text), + 0, + 0, + ); + } + + case "toggle": { + const text = result.content[0]; + const msg = text?.type === "text" ? text.text : ""; + return new Text(theme.fg("success", "✓ ") + theme.fg("muted", msg), 0, 0); + } + + case "clear": + return new Text(theme.fg("success", "✓ ") + theme.fg("muted", "Cleared all todos"), 0, 0); + } + }, + }); + + // Register the /todos command for users + pi.registerCommand("todos", { + description: "Show all todos on the current branch", + handler: async (_args, ctx) => { + if (ctx.mode !== "tui") { + ctx.ui.notify("/todos requires interactive mode", "error"); + return; + } + + await ctx.ui.custom((_tui, theme, _kb, done) => { + return new TodoListComponent(todos, theme, () => done()); + }); + }, + }); +} diff --git a/examples/extensions/tool-override.ts b/examples/extensions/tool-override.ts new file mode 100644 index 0000000..59a89ba --- /dev/null +++ b/examples/extensions/tool-override.ts @@ -0,0 +1,144 @@ +/** + * Tool Override Example - Demonstrates overriding built-in tools + * + * Extensions can register tools with the same name as built-in tools to replace them. + * This is useful for: + * - Adding logging or auditing to tool calls + * - Implementing access control or sandboxing + * - Routing tool calls to remote systems (e.g., pi-ssh-remote) + * - Modifying tool behavior for specific workflows + * + * This example overrides the `read` tool to: + * 1. Log all file access to a log file + * 2. Block access to sensitive paths (e.g., .env files) + * 3. Delegate to the original read implementation for allowed files + * + * Since no custom renderCall/renderResult are provided, the built-in renderer + * is used automatically (syntax highlighting, line numbers, truncation warnings). + * + * Usage: + * pi -e ./tool-override.ts + */ + +import type { TextContent } from "@earendil-works/pi-ai"; +import { type ExtensionAPI, getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent"; +import { constants, readFileSync } from "fs"; +import { access, appendFile, readFile } from "fs/promises"; +import { join, resolve } from "path"; +import { Type } from "typebox"; + +const LOG_FILE = join(getAgentDir(), "read-access.log"); + +// Paths that are blocked from reading +const BLOCKED_PATTERNS = [ + /\.env$/, + /\.env\..+$/, + /secrets?\.(json|yaml|yml|toml)$/i, + /credentials?\.(json|yaml|yml|toml)$/i, + /\/\.ssh\//, + /\/\.aws\//, + /\/\.gnupg\//, +]; + +function isBlockedPath(path: string): boolean { + return BLOCKED_PATTERNS.some((pattern) => pattern.test(path)); +} + +async function logAccess(path: string, allowed: boolean, reason?: string) { + const timestamp = new Date().toISOString(); + const status = allowed ? "ALLOWED" : "BLOCKED"; + const msg = reason ? ` (${reason})` : ""; + const line = `[${timestamp}] ${status}: ${path}${msg}\n`; + + try { + await withFileMutationQueue(LOG_FILE, async () => { + await appendFile(LOG_FILE, line); + }); + } catch { + // Ignore logging errors + } +} + +const readSchema = Type.Object({ + path: Type.String({ description: "Path to the file to read (relative or absolute)" }), + offset: Type.Optional(Type.Number({ description: "Line number to start reading from (1-indexed)" })), + limit: Type.Optional(Type.Number({ description: "Maximum number of lines to read" })), +}); + +export default function (pi: ExtensionAPI) { + pi.registerTool({ + name: "read", // Same name as built-in - this will override it + label: "read (audited)", + description: + "Read the contents of a file with access logging. Some sensitive paths (.env, secrets, credentials) are blocked.", + parameters: readSchema, + + async execute(_toolCallId, params, _signal, _onUpdate, ctx) { + const { path, offset, limit } = params; + const absolutePath = resolve(ctx.cwd, path); + + // Check if path is blocked + if (isBlockedPath(absolutePath)) { + await logAccess(absolutePath, false, "matches blocked pattern"); + return { + content: [ + { + type: "text", + text: `Access denied: "${path}" matches a blocked pattern (sensitive file). This tool blocks access to .env files, secrets, credentials, and SSH/AWS/GPG directories.`, + }, + ], + details: { blocked: true }, + }; + } + + // Log allowed access + await logAccess(absolutePath, true); + + // Perform the actual read (simplified implementation) + try { + await access(absolutePath, constants.R_OK); + const content = await readFile(absolutePath, "utf-8"); + const lines = content.split("\n"); + + // Apply offset and limit + const startLine = offset ? Math.max(0, offset - 1) : 0; + const endLine = limit ? startLine + limit : lines.length; + const selectedLines = lines.slice(startLine, endLine); + + // Basic truncation (50KB limit) + let text = selectedLines.join("\n"); + const maxBytes = 50 * 1024; + if (Buffer.byteLength(text, "utf-8") > maxBytes) { + text = `${text.slice(0, maxBytes)}\n\n[Output truncated at 50KB]`; + } + + return { + content: [{ type: "text", text }] as TextContent[], + details: { lines: lines.length }, + }; + } catch (error: any) { + return { + content: [{ type: "text", text: `Error reading file: ${error.message}` }] as TextContent[], + details: { error: true }, + }; + } + }, + + // No renderCall/renderResult - uses built-in renderer automatically + // (syntax highlighting, line numbers, truncation warnings, etc.) + }); + + // Also register a command to view the access log + pi.registerCommand("read-log", { + description: "View the file access log", + handler: async (_args, ctx) => { + try { + const log = readFileSync(LOG_FILE, "utf-8"); + const lines = log.trim().split("\n").slice(-20); // Last 20 entries + ctx.ui.notify(`Recent file access:\n${lines.join("\n")}`, "info"); + } catch { + ctx.ui.notify("No access log found", "info"); + } + }, + }); +} diff --git a/examples/extensions/tools.ts b/examples/extensions/tools.ts new file mode 100644 index 0000000..8db496a --- /dev/null +++ b/examples/extensions/tools.ts @@ -0,0 +1,146 @@ +/** + * Tools Extension + * + * Provides a /tools command to enable/disable tools interactively. + * Tool selection persists across session reloads and respects branch navigation. + * + * Usage: + * 1. Copy this file to ~/.pi/agent/extensions/ or your project's .pi/extensions/ + * 2. Use /tools to open the tool selector + */ + +import type { ExtensionAPI, ExtensionContext, ToolInfo } from "@earendil-works/pi-coding-agent"; +import { getSettingsListTheme } from "@earendil-works/pi-coding-agent"; +import { Container, type SettingItem, SettingsList } from "@earendil-works/pi-tui"; + +// State persisted to session +interface ToolsState { + enabledTools: string[]; +} + +export default function toolsExtension(pi: ExtensionAPI) { + // Track enabled tools + let enabledTools: Set = new Set(); + let allTools: ToolInfo[] = []; + + // Persist current state + function persistState() { + pi.appendEntry("tools-config", { + enabledTools: Array.from(enabledTools), + }); + } + + // Apply current tool selection + function applyTools() { + pi.setActiveTools(Array.from(enabledTools)); + } + + // Find the last tools-config entry in the current branch + function restoreFromBranch(ctx: ExtensionContext) { + allTools = pi.getAllTools(); + + // Get entries in current branch only + const branchEntries = ctx.sessionManager.getBranch(); + let savedTools: string[] | undefined; + + for (const entry of branchEntries) { + if (entry.type === "custom" && entry.customType === "tools-config") { + const data = entry.data as ToolsState | undefined; + if (data?.enabledTools) { + savedTools = data.enabledTools; + } + } + } + + if (savedTools) { + // Restore saved tool selection (filter to only tools that still exist) + const allToolNames = allTools.map((t) => t.name); + enabledTools = new Set(savedTools.filter((t: string) => allToolNames.includes(t))); + applyTools(); + } else { + // No saved state - sync with currently active tools + enabledTools = new Set(pi.getActiveTools()); + } + } + + // Register /tools command + pi.registerCommand("tools", { + description: "Enable/disable tools", + handler: async (_args, ctx) => { + if (ctx.mode !== "tui") { + ctx.ui.notify("/tools requires TUI mode", "error"); + return; + } + + // Refresh tool list + allTools = pi.getAllTools(); + + await ctx.ui.custom((tui, theme, _kb, done) => { + // Build settings items for each tool + const items: SettingItem[] = allTools.map((tool) => ({ + id: tool.name, + label: tool.name, + currentValue: enabledTools.has(tool.name) ? "enabled" : "disabled", + values: ["enabled", "disabled"], + })); + + const container = new Container(); + container.addChild( + new (class { + render(_width: number) { + return [theme.fg("accent", theme.bold("Tool Configuration")), ""]; + } + invalidate() {} + })(), + ); + + const settingsList = new SettingsList( + items, + Math.min(items.length + 2, 15), + getSettingsListTheme(), + (id, newValue) => { + // Update enabled state and apply immediately + if (newValue === "enabled") { + enabledTools.add(id); + } else { + enabledTools.delete(id); + } + applyTools(); + persistState(); + }, + () => { + // Close dialog + done(undefined); + }, + ); + + container.addChild(settingsList); + + const component = { + render(width: number) { + return container.render(width); + }, + invalidate() { + container.invalidate(); + }, + handleInput(data: string) { + settingsList.handleInput?.(data); + tui.requestRender(); + }, + }; + + return component; + }); + }, + }); + + // Restore state on session start + pi.on("session_start", async (_event, ctx) => { + restoreFromBranch(ctx); + }); + + // Restore state when navigating the session tree + pi.on("session_tree", async (_event, ctx) => { + restoreFromBranch(ctx); + }); +} diff --git a/examples/extensions/trigger-compact.ts b/examples/extensions/trigger-compact.ts new file mode 100644 index 0000000..fed5781 --- /dev/null +++ b/examples/extensions/trigger-compact.ts @@ -0,0 +1,50 @@ +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; + +const COMPACT_THRESHOLD_TOKENS = 100_000; + +export default function (pi: ExtensionAPI) { + let previousTokens: number | null | undefined; + + const triggerCompaction = (ctx: ExtensionContext, customInstructions?: string) => { + if (ctx.hasUI) { + ctx.ui.notify("Compaction started", "info"); + } + ctx.compact({ + customInstructions, + onComplete: () => { + if (ctx.hasUI) { + ctx.ui.notify("Compaction completed", "info"); + } + }, + onError: (error) => { + if (ctx.hasUI) { + ctx.ui.notify(`Compaction failed: ${error.message}`, "error"); + } + }, + }); + }; + + pi.on("turn_end", (_event, ctx) => { + const usage = ctx.getContextUsage(); + const currentTokens = usage?.tokens ?? null; + if (currentTokens === null) { + return; + } + + const crossedThreshold = + previousTokens !== undefined && previousTokens !== null && previousTokens <= COMPACT_THRESHOLD_TOKENS; + previousTokens = currentTokens; + if (!crossedThreshold || currentTokens <= COMPACT_THRESHOLD_TOKENS) { + return; + } + triggerCompaction(ctx); + }); + + pi.registerCommand("trigger-compact", { + description: "Trigger compaction immediately", + handler: async (args, ctx) => { + const instructions = args.trim() || undefined; + triggerCompaction(ctx, instructions); + }, + }); +} diff --git a/examples/extensions/truncated-tool.ts b/examples/extensions/truncated-tool.ts new file mode 100644 index 0000000..9373344 --- /dev/null +++ b/examples/extensions/truncated-tool.ts @@ -0,0 +1,195 @@ +/** + * Truncated Tool Example - Demonstrates proper output truncation for custom tools + * + * Custom tools MUST truncate their output to avoid overwhelming the LLM context. + * The built-in limit is 50KB (~10k tokens) and 2000 lines, whichever is hit first. + * + * This example shows how to: + * 1. Use the built-in truncation utilities + * 2. Write full output to a temp file when truncated + * 3. Inform the LLM where to find the complete output + * 4. Custom rendering of tool calls and results + * + * The `rg` tool here wraps ripgrep with proper truncation. Compare this to the + * built-in `grep` tool in src/core/tools/grep.ts for a more complete implementation. + */ + +import { mkdtemp, writeFile } from "node:fs/promises"; +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import { + DEFAULT_MAX_BYTES, + DEFAULT_MAX_LINES, + formatSize, + type TruncationResult, + truncateHead, + withFileMutationQueue, +} from "@earendil-works/pi-coding-agent"; +import { Text } from "@earendil-works/pi-tui"; +import { execSync } from "child_process"; +import { tmpdir } from "os"; +import { join } from "path"; +import { Type } from "typebox"; + +const RgParams = Type.Object({ + pattern: Type.String({ description: "Search pattern (regex)" }), + path: Type.Optional(Type.String({ description: "Directory to search (default: current directory)" })), + glob: Type.Optional(Type.String({ description: "File glob pattern, e.g. '*.ts'" })), +}); + +interface RgDetails { + pattern: string; + path?: string; + glob?: string; + matchCount: number; + truncation?: TruncationResult; + fullOutputPath?: string; +} + +export default function (pi: ExtensionAPI) { + pi.registerTool({ + name: "rg", + label: "ripgrep", + // Document the truncation limits in the tool description so the LLM knows + description: `Search file contents using ripgrep. Output is truncated to ${DEFAULT_MAX_LINES} lines or ${formatSize(DEFAULT_MAX_BYTES)} (whichever is hit first). If truncated, full output is saved to a temp file.`, + parameters: RgParams, + + async execute(_toolCallId, params, _signal, _onUpdate, ctx) { + const { pattern, path: searchPath, glob } = params; + + // Build the ripgrep command + const args = ["rg", "--line-number", "--color=never"]; + if (glob) args.push("--glob", glob); + args.push(pattern); + args.push(searchPath || "."); + + let output: string; + try { + output = execSync(args.join(" "), { + cwd: ctx.cwd, + encoding: "utf-8", + maxBuffer: 100 * 1024 * 1024, // 100MB buffer to capture full output + }); + } catch (err: any) { + // ripgrep exits with 1 when no matches found + if (err.status === 1) { + return { + content: [{ type: "text", text: "No matches found" }], + details: { pattern, path: searchPath, glob, matchCount: 0 } as RgDetails, + }; + } + throw new Error(`ripgrep failed: ${err.message}`); + } + + if (!output.trim()) { + return { + content: [{ type: "text", text: "No matches found" }], + details: { pattern, path: searchPath, glob, matchCount: 0 } as RgDetails, + }; + } + + // Apply truncation using built-in utilities + // truncateHead keeps the first N lines/bytes (good for search results) + // truncateTail keeps the last N lines/bytes (good for logs/command output) + const truncation = truncateHead(output, { + maxLines: DEFAULT_MAX_LINES, + maxBytes: DEFAULT_MAX_BYTES, + }); + + // Count matches (each non-empty line with a match) + const matchCount = output.split("\n").filter((line) => line.trim()).length; + + const details: RgDetails = { + pattern, + path: searchPath, + glob, + matchCount, + }; + + let resultText = truncation.content; + + if (truncation.truncated) { + // Save full output to a temp file so LLM can access it if needed + const tempDir = await mkdtemp(join(tmpdir(), "pi-rg-")); + const tempFile = join(tempDir, "output.txt"); + await withFileMutationQueue(tempFile, async () => { + await writeFile(tempFile, output, "utf8"); + }); + + details.truncation = truncation; + details.fullOutputPath = tempFile; + + // Add truncation notice - this helps the LLM understand the output is incomplete + const truncatedLines = truncation.totalLines - truncation.outputLines; + const truncatedBytes = truncation.totalBytes - truncation.outputBytes; + + resultText += `\n\n[Output truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`; + resultText += ` (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).`; + resultText += ` ${truncatedLines} lines (${formatSize(truncatedBytes)}) omitted.`; + resultText += ` Full output saved to: ${tempFile}]`; + } + + return { + content: [{ type: "text", text: resultText }], + details, + }; + }, + + // Custom rendering of the tool call (shown before/during execution) + renderCall(args, theme, _context) { + let text = theme.fg("toolTitle", theme.bold("rg ")); + text += theme.fg("accent", `"${args.pattern}"`); + if (args.path) { + text += theme.fg("muted", ` in ${args.path}`); + } + if (args.glob) { + text += theme.fg("dim", ` --glob ${args.glob}`); + } + return new Text(text, 0, 0); + }, + + // Custom rendering of the tool result + renderResult(result, { expanded, isPartial }, theme, _context) { + const details = result.details as RgDetails | undefined; + + // Handle streaming/partial results + if (isPartial) { + return new Text(theme.fg("warning", "Searching..."), 0, 0); + } + + // No matches + if (!details || details.matchCount === 0) { + return new Text(theme.fg("dim", "No matches found"), 0, 0); + } + + // Build result display + let text = theme.fg("success", `${details.matchCount} matches`); + + // Show truncation warning if applicable + if (details.truncation?.truncated) { + text += theme.fg("warning", " (truncated)"); + } + + // In expanded view, show the actual matches + if (expanded) { + const content = result.content[0]; + if (content?.type === "text") { + // Show first 20 lines in expanded view, or all if fewer + const lines = content.text.split("\n").slice(0, 20); + for (const line of lines) { + text += `\n${theme.fg("dim", line)}`; + } + if (content.text.split("\n").length > 20) { + text += `\n${theme.fg("muted", "... (use read tool to see full output)")}`; + } + } + + // Show temp file path if truncated + if (details.fullOutputPath) { + text += `\n${theme.fg("dim", `Full output: ${details.fullOutputPath}`)}`; + } + } + + return new Text(text, 0, 0); + }, + }); +} diff --git a/examples/extensions/widget-placement.ts b/examples/extensions/widget-placement.ts new file mode 100644 index 0000000..44bf5b6 --- /dev/null +++ b/examples/extensions/widget-placement.ts @@ -0,0 +1,9 @@ +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function widgetPlacementExtension(pi: ExtensionAPI) { + pi.on("session_start", (_event, ctx) => { + if (!ctx.hasUI) return; + ctx.ui.setWidget("widget-above", ["Above editor widget"]); + ctx.ui.setWidget("widget-below", ["Below editor widget"], { placement: "belowEditor" }); + }); +} diff --git a/examples/extensions/with-deps/index.ts b/examples/extensions/with-deps/index.ts new file mode 100644 index 0000000..17be7da --- /dev/null +++ b/examples/extensions/with-deps/index.ts @@ -0,0 +1,32 @@ +/** + * Example extension with its own npm dependencies. + * Tests that jiti resolves modules from the extension's own node_modules. + * + * Requires: npm install in this directory + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; +import ms from "ms"; +import { Type } from "typebox"; + +export default function (pi: ExtensionAPI) { + // Register a tool that uses ms + pi.registerTool({ + name: "parse_duration", + label: "Parse Duration", + description: "Parse a human-readable duration string (e.g., '2 days', '1h', '5m') to milliseconds", + parameters: Type.Object({ + duration: Type.String({ description: "Duration string like '2 days', '1h', '5m'" }), + }), + execute: async (_toolCallId, params) => { + const result = ms(params.duration as ms.StringValue); + if (result === undefined) { + throw new Error(`Invalid duration: "${params.duration}"`); + } + return { + content: [{ type: "text", text: `${params.duration} = ${result} milliseconds` }], + details: {}, + }; + }, + }); +} diff --git a/examples/extensions/with-deps/package-lock.json b/examples/extensions/with-deps/package-lock.json new file mode 100644 index 0000000..2b0fc24 --- /dev/null +++ b/examples/extensions/with-deps/package-lock.json @@ -0,0 +1,31 @@ +{ + "name": "pi-extension-with-deps", + "version": "0.83.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "pi-extension-with-deps", + "version": "0.83.0", + "dependencies": { + "ms": "^2.1.3" + }, + "devDependencies": { + "@types/ms": "^2.1.0" + } + }, + "node_modules/@types/ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", + "dev": true, + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + } + } +} diff --git a/examples/extensions/with-deps/package.json b/examples/extensions/with-deps/package.json new file mode 100644 index 0000000..41a2863 --- /dev/null +++ b/examples/extensions/with-deps/package.json @@ -0,0 +1,22 @@ +{ + "name": "pi-extension-with-deps", + "private": true, + "version": "0.83.0", + "type": "module", + "scripts": { + "clean": "echo 'nothing to clean'", + "build": "echo 'nothing to build'", + "check": "echo 'nothing to check'" + }, + "pi": { + "extensions": [ + "./index.ts" + ] + }, + "dependencies": { + "ms": "2.1.3" + }, + "devDependencies": { + "@types/ms": "2.1.0" + } +} diff --git a/examples/extensions/working-indicator.ts b/examples/extensions/working-indicator.ts new file mode 100644 index 0000000..1fb3dbd --- /dev/null +++ b/examples/extensions/working-indicator.ts @@ -0,0 +1,123 @@ +/** + * Working Indicator Extension + * + * Demonstrates `ctx.ui.setWorkingIndicator()` for customizing the inline + * working indicator shown while pi is streaming a response. + * + * Usage: + * pi --extension examples/extensions/working-indicator.ts + * + * Commands: + * /working-indicator Show current mode + * /working-indicator dot Use a static dot indicator + * /working-indicator pulse Use a custom animated indicator + * /working-indicator none Hide the indicator entirely + * /working-indicator spinner Restore an animated spinner + * /working-indicator reset Restore pi's default spinner + */ + +import type { ExtensionAPI, ExtensionContext, WorkingIndicatorOptions } from "@earendil-works/pi-coding-agent"; + +type WorkingIndicatorMode = "dot" | "none" | "pulse" | "spinner" | "default"; + +const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; +const PASTEL_RAINBOW = [ + "\x1b[38;2;255;179;186m", + "\x1b[38;2;255;223;186m", + "\x1b[38;2;255;255;186m", + "\x1b[38;2;186;255;201m", + "\x1b[38;2;186;225;255m", + "\x1b[38;2;218;186;255m", +]; +const RESET_FG = "\x1b[39m"; +const HIDDEN_INDICATOR: WorkingIndicatorOptions = { + frames: [], +}; + +function colorize(text: string, color: string): string { + return `${color}${text}${RESET_FG}`; +} + +function getIndicator(mode: WorkingIndicatorMode): WorkingIndicatorOptions | undefined { + switch (mode) { + case "dot": + return { + frames: [colorize("●", PASTEL_RAINBOW[0])], + }; + case "none": + return HIDDEN_INDICATOR; + case "pulse": + return { + frames: [ + colorize("·", PASTEL_RAINBOW[0]), + colorize("•", PASTEL_RAINBOW[2]), + colorize("●", PASTEL_RAINBOW[4]), + colorize("•", PASTEL_RAINBOW[5]), + ], + intervalMs: 120, + }; + case "spinner": + return { + frames: SPINNER_FRAMES.map((frame, index) => + colorize(frame, PASTEL_RAINBOW[index % PASTEL_RAINBOW.length]!), + ), + intervalMs: 80, + }; + case "default": + return undefined; + } +} + +function describeMode(mode: WorkingIndicatorMode): string { + switch (mode) { + case "dot": + return "static dot"; + case "none": + return "hidden"; + case "pulse": + return "custom pulse"; + case "spinner": + return "custom spinner"; + case "default": + return "pi default spinner"; + } +} + +export default function (pi: ExtensionAPI) { + let mode: WorkingIndicatorMode = "spinner"; + + const applyIndicator = (ctx: ExtensionContext) => { + ctx.ui.setWorkingIndicator(getIndicator(mode)); + ctx.ui.setStatus("working-indicator", ctx.ui.theme.fg("dim", `Indicator: ${describeMode(mode)}`)); + }; + + pi.on("session_start", async (_event, ctx) => { + applyIndicator(ctx); + }); + + pi.registerCommand("working-indicator", { + description: "Set the streaming working indicator: dot, pulse, none, spinner, or reset.", + handler: async (args, ctx) => { + const nextMode = args.trim().toLowerCase(); + if (!nextMode) { + ctx.ui.notify(`Working indicator: ${describeMode(mode)}`, "info"); + return; + } + + if ( + nextMode !== "dot" && + nextMode !== "none" && + nextMode !== "pulse" && + nextMode !== "spinner" && + nextMode !== "reset" + ) { + ctx.ui.notify("Usage: /working-indicator [dot|pulse|none|spinner|reset]", "error"); + return; + } + + mode = nextMode === "reset" ? "default" : nextMode; + applyIndicator(ctx); + ctx.ui.notify(`Working indicator set to: ${describeMode(mode)}`, "info"); + }, + }); +} diff --git a/examples/extensions/working-message-test.ts b/examples/extensions/working-message-test.ts new file mode 100644 index 0000000..7c5a32f --- /dev/null +++ b/examples/extensions/working-message-test.ts @@ -0,0 +1,25 @@ +/** + * Working Message Persistence Test + * + * Sets a custom working message and indicator on session start so you can + * verify they survive across loader recreations (e.g. between agent turns). + * + * Usage: + * pi --extension examples/extensions/working-message-test.ts + * + * Then send a few messages in interactive mode. The working message should + * stay "Working... (custom)" with a brown dot indicator every time the + * loader appears, not revert to the default gray "Working...". + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +const CUSTOM_MESSAGE = "\x1b[38;2;155;86;63mWorking... (custom)\x1b[39m"; +const CUSTOM_INDICATOR = { frames: ["\x1b[38;2;155;86;63m●\x1b[39m"] }; + +export default function (pi: ExtensionAPI) { + pi.on("session_start", async (_event, ctx) => { + ctx.ui.setWorkingMessage(CUSTOM_MESSAGE); + ctx.ui.setWorkingIndicator(CUSTOM_INDICATOR); + }); +} diff --git a/examples/rpc-extension-ui.ts b/examples/rpc-extension-ui.ts new file mode 100644 index 0000000..bcbb6ec --- /dev/null +++ b/examples/rpc-extension-ui.ts @@ -0,0 +1,632 @@ +/** + * RPC Extension UI Example (TUI) + * + * A lightweight TUI chat client that spawns the agent in RPC mode. + * Demonstrates how to build a custom UI on top of the RPC protocol, + * including handling extension UI requests (select, confirm, input, editor). + * + * Usage: npx tsx examples/rpc-extension-ui.ts + * + * Slash commands: + * /select - demo select dialog + * /confirm - demo confirm dialog + * /input - demo input dialog + * /editor - demo editor dialog + */ + +import { spawn } from "node:child_process"; +import { dirname, join } from "node:path"; +import * as readline from "node:readline"; +import { fileURLToPath } from "node:url"; +import { type Component, Container, Input, matchesKey, ProcessTerminal, SelectList, TUI } from "@earendil-works/pi-tui"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +// ============================================================================ +// ANSI helpers +// ============================================================================ + +const GREEN = "\x1b[32m"; +const YELLOW = "\x1b[33m"; +const BLUE = "\x1b[34m"; +const MAGENTA = "\x1b[35m"; +const RED = "\x1b[31m"; +const DIM = "\x1b[2m"; +const BOLD = "\x1b[1m"; +const RESET = "\x1b[0m"; + +// ============================================================================ +// Extension UI request type (subset of rpc-types.ts) +// ============================================================================ + +interface ExtensionUIRequest { + type: "extension_ui_request"; + id: string; + method: string; + title?: string; + options?: string[]; + message?: string; + placeholder?: string; + prefill?: string; + notifyType?: "info" | "warning" | "error"; + statusKey?: string; + statusText?: string; + widgetKey?: string; + widgetLines?: string[]; + text?: string; +} + +// ============================================================================ +// Output log: accumulates styled lines, renders the tail that fits +// ============================================================================ + +class OutputLog implements Component { + private lines: string[] = []; + private maxLines = 1000; + private visibleLines = 0; + + setVisibleLines(n: number): void { + this.visibleLines = n; + } + + append(line: string): void { + this.lines.push(line); + if (this.lines.length > this.maxLines) { + this.lines = this.lines.slice(-this.maxLines); + } + } + + appendRaw(text: string): void { + if (this.lines.length === 0) { + this.lines.push(text); + } else { + this.lines[this.lines.length - 1] += text; + } + } + + invalidate(): void {} + + render(width: number): string[] { + if (this.lines.length === 0) return [""]; + const n = this.visibleLines > 0 ? this.visibleLines : this.lines.length; + return this.lines.slice(-n).map((l) => l.slice(0, width)); + } +} + +// ============================================================================ +// Loading indicator: "Agent: Working." -> ".." -> "..." -> "." +// ============================================================================ + +class LoadingIndicator implements Component { + private dots = 1; + private intervalId: NodeJS.Timeout | null = null; + private tui: TUI | null = null; + + start(tui: TUI): void { + this.tui = tui; + this.dots = 1; + this.intervalId = setInterval(() => { + this.dots = (this.dots % 3) + 1; + this.tui?.requestRender(); + }, 400); + } + + stop(): void { + if (this.intervalId) { + clearInterval(this.intervalId); + this.intervalId = null; + } + } + + invalidate(): void {} + + render(_width: number): string[] { + return [`${BLUE}${BOLD}Agent:${RESET} ${DIM}Working${".".repeat(this.dots)}${RESET}`]; + } +} + +// ============================================================================ +// Prompt input: label + single-line input +// ============================================================================ + +class PromptInput implements Component { + readonly input: Input; + onCtrlD?: () => void; + + constructor() { + this.input = new Input(); + } + + handleInput(data: string): void { + if (matchesKey(data, "ctrl+d")) { + this.onCtrlD?.(); + return; + } + this.input.handleInput(data); + } + + invalidate(): void { + this.input.invalidate(); + } + + render(width: number): string[] { + return [`${GREEN}${BOLD}You:${RESET}`, ...this.input.render(width)]; + } +} + +// ============================================================================ +// Dialog components: replace the prompt input during interactive requests +// ============================================================================ + +class SelectDialog implements Component { + private list: SelectList; + private title: string; + onSelect?: (value: string) => void; + onCancel?: () => void; + + constructor(title: string, options: string[]) { + this.title = title; + const items = options.map((o) => ({ value: o, label: o })); + this.list = new SelectList(items, Math.min(items.length, 8), { + selectedPrefix: (t) => `${MAGENTA}${t}${RESET}`, + selectedText: (t) => `${MAGENTA}${t}${RESET}`, + description: (t) => `${DIM}${t}${RESET}`, + scrollInfo: (t) => `${DIM}${t}${RESET}`, + noMatch: (t) => `${YELLOW}${t}${RESET}`, + }); + this.list.onSelect = (item) => this.onSelect?.(item.value); + this.list.onCancel = () => this.onCancel?.(); + } + + handleInput(data: string): void { + this.list.handleInput(data); + } + + invalidate(): void { + this.list.invalidate(); + } + + render(width: number): string[] { + return [ + `${MAGENTA}${BOLD}${this.title}${RESET}`, + ...this.list.render(width), + `${DIM}Up/Down, Enter to select, Esc to cancel${RESET}`, + ]; + } +} + +class InputDialog implements Component { + private dialogInput: Input; + private title: string; + onCtrlD?: () => void; + + constructor(title: string, prefill?: string) { + this.title = title; + this.dialogInput = new Input(); + if (prefill) this.dialogInput.setValue(prefill); + } + + set onSubmit(fn: ((value: string) => void) | undefined) { + this.dialogInput.onSubmit = fn; + } + + set onEscape(fn: (() => void) | undefined) { + this.dialogInput.onEscape = fn; + } + + get inputComponent(): Input { + return this.dialogInput; + } + + handleInput(data: string): void { + if (matchesKey(data, "ctrl+d")) { + this.onCtrlD?.(); + return; + } + this.dialogInput.handleInput(data); + } + + invalidate(): void { + this.dialogInput.invalidate(); + } + + render(width: number): string[] { + return [ + `${MAGENTA}${BOLD}${this.title}${RESET}`, + ...this.dialogInput.render(width), + `${DIM}Enter to submit, Esc to cancel${RESET}`, + ]; + } +} + +// ============================================================================ +// Main +// ============================================================================ + +async function main() { + const extensionPath = join(__dirname, "extensions/rpc-demo.ts"); + const cliPath = join(__dirname, "../dist/cli.js"); + + const agent = spawn( + "node", + [cliPath, "--mode", "rpc", "--no-session", "--no-extension", "--extension", extensionPath], + { stdio: ["pipe", "pipe", "pipe"] }, + ); + + let stderr = ""; + agent.stderr?.on("data", (data: Buffer) => { + stderr += data.toString(); + }); + + await new Promise((resolve) => setTimeout(resolve, 500)); + if (agent.exitCode !== null) { + console.error(`Agent exited immediately. Stderr:\n${stderr}`); + process.exit(1); + } + + // -- TUI setup -- + + const terminal = new ProcessTerminal(); + const tui = new TUI(terminal); + + const outputLog = new OutputLog(); + const loadingIndicator = new LoadingIndicator(); + const promptInput = new PromptInput(); + + const root = new Container(); + root.addChild(outputLog); + root.addChild(promptInput); + + tui.addChild(root); + tui.setFocus(promptInput.input); + + // -- Agent communication -- + + function send(obj: Record): void { + agent.stdin!.write(`${JSON.stringify(obj)}\n`); + } + + let isStreaming = false; + let hasTextOutput = false; + + function exit(): void { + tui.stop(); + agent.kill("SIGTERM"); + process.exit(0); + } + + // -- Bottom area management -- + // The bottom of the screen is either the prompt input or a dialog. + // These helpers swap between them. + + let activeDialog: Component | null = null; + + function setBottomComponent(component: Component): void { + root.clear(); + root.addChild(outputLog); + if (isStreaming) root.addChild(loadingIndicator); + root.addChild(component); + tui.setFocus(component); + tui.requestRender(); + } + + function showPrompt(): void { + activeDialog = null; + setBottomComponent(promptInput); + tui.setFocus(promptInput.input); + } + + function showDialog(dialog: Component): void { + activeDialog = dialog; + setBottomComponent(dialog); + } + + function showLoading(): void { + if (!isStreaming) { + isStreaming = true; + hasTextOutput = false; + root.clear(); + root.addChild(outputLog); + root.addChild(loadingIndicator); + root.addChild(activeDialog ?? promptInput); + if (!activeDialog) tui.setFocus(promptInput.input); + loadingIndicator.start(tui); + tui.requestRender(); + } + } + + function hideLoading(): void { + loadingIndicator.stop(); + root.clear(); + root.addChild(outputLog); + root.addChild(activeDialog ?? promptInput); + if (!activeDialog) tui.setFocus(promptInput.input); + tui.requestRender(); + } + + // -- Extension UI dialog handling -- + + function showSelectDialog(title: string, options: string[], onDone: (value: string | undefined) => void): void { + const dialog = new SelectDialog(title, options); + dialog.onSelect = (value) => { + showPrompt(); + onDone(value); + }; + dialog.onCancel = () => { + showPrompt(); + onDone(undefined); + }; + showDialog(dialog); + } + + function showInputDialog(title: string, prefill?: string, onDone?: (value: string | undefined) => void): void { + const dialog = new InputDialog(title, prefill); + dialog.onSubmit = (value) => { + showPrompt(); + onDone?.(value.trim() || undefined); + }; + dialog.onEscape = () => { + showPrompt(); + onDone?.(undefined); + }; + dialog.onCtrlD = exit; + showDialog(dialog); + tui.setFocus(dialog.inputComponent); + } + + function handleExtensionUI(req: ExtensionUIRequest): void { + const { id, method } = req; + + switch (method) { + // Dialog methods: replace prompt with interactive component + case "select": { + showSelectDialog(req.title ?? "Select", req.options ?? [], (value) => { + if (value !== undefined) { + send({ type: "extension_ui_response", id, value }); + } else { + send({ type: "extension_ui_response", id, cancelled: true }); + } + }); + break; + } + + case "confirm": { + const title = req.message ? `${req.title}: ${req.message}` : (req.title ?? "Confirm"); + showSelectDialog(title, ["Yes", "No"], (value) => { + send({ type: "extension_ui_response", id, confirmed: value === "Yes" }); + }); + break; + } + + case "input": { + const title = req.placeholder ? `${req.title} (${req.placeholder})` : (req.title ?? "Input"); + showInputDialog(title, undefined, (value) => { + if (value !== undefined) { + send({ type: "extension_ui_response", id, value }); + } else { + send({ type: "extension_ui_response", id, cancelled: true }); + } + }); + break; + } + + case "editor": { + const prefill = req.prefill?.replace(/\n/g, " "); + showInputDialog(req.title ?? "Editor", prefill, (value) => { + if (value !== undefined) { + send({ type: "extension_ui_response", id, value }); + } else { + send({ type: "extension_ui_response", id, cancelled: true }); + } + }); + break; + } + + // Fire-and-forget methods: display as notification + case "notify": { + const notifyType = (req.notifyType as string) ?? "info"; + const color = notifyType === "error" ? RED : notifyType === "warning" ? YELLOW : MAGENTA; + outputLog.append(`${color}${BOLD}Notification:${RESET} ${req.message}`); + tui.requestRender(); + break; + } + + case "setStatus": + outputLog.append( + `${MAGENTA}${BOLD}Notification:${RESET} ${DIM}[status: ${req.statusKey}]${RESET} ${req.statusText ?? "(cleared)"}`, + ); + tui.requestRender(); + break; + + case "setWidget": { + const lines = req.widgetLines; + if (lines && lines.length > 0) { + outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} ${DIM}[widget: ${req.widgetKey}]${RESET}`); + for (const wl of lines) { + outputLog.append(` ${DIM}${wl}${RESET}`); + } + tui.requestRender(); + } + break; + } + + case "set_editor_text": + promptInput.input.setValue((req.text as string) ?? ""); + tui.requestRender(); + break; + } + } + + // -- Slash commands (local, not sent to agent) -- + + function handleSlashCommand(cmd: string): boolean { + switch (cmd) { + case "/select": + showSelectDialog("Pick a color", ["Red", "Green", "Blue", "Yellow"], (value) => { + if (value) { + outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} You picked: ${value}`); + } else { + outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Selection cancelled`); + } + tui.requestRender(); + }); + return true; + + case "/confirm": + showSelectDialog("Are you sure?", ["Yes", "No"], (value) => { + const confirmed = value === "Yes"; + outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Confirmed: ${confirmed}`); + tui.requestRender(); + }); + return true; + + case "/input": + showInputDialog("Enter your name", undefined, (value) => { + if (value) { + outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} You entered: ${value}`); + } else { + outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Input cancelled`); + } + tui.requestRender(); + }); + return true; + + case "/editor": + showInputDialog("Edit text", "Hello, world!", (value) => { + if (value) { + outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Submitted: ${value}`); + } else { + outputLog.append(`${MAGENTA}${BOLD}Notification:${RESET} Editor cancelled`); + } + tui.requestRender(); + }); + return true; + + default: + return false; + } + } + + // -- Process agent stdout -- + + const stdoutRl = readline.createInterface({ input: agent.stdout!, terminal: false }); + + stdoutRl.on("line", (line) => { + let data: Record; + try { + data = JSON.parse(line); + } catch { + return; + } + + if (data.type === "response" && !data.success) { + outputLog.append(`${RED}[error]${RESET} ${data.command}: ${data.error}`); + tui.requestRender(); + return; + } + + if (data.type === "agent_start") { + showLoading(); + return; + } + + if (data.type === "extension_ui_request") { + handleExtensionUI(data as unknown as ExtensionUIRequest); + return; + } + + if (data.type === "message_update") { + const evt = data.assistantMessageEvent as Record | undefined; + if (evt?.type === "text_delta") { + if (!hasTextOutput) { + hasTextOutput = true; + outputLog.append(""); + outputLog.append(`${BLUE}${BOLD}Agent:${RESET}`); + } + const delta = evt.delta as string; + const parts = delta.split("\n"); + for (let i = 0; i < parts.length; i++) { + if (i > 0) outputLog.append(""); + if (parts[i]) outputLog.appendRaw(parts[i]); + } + tui.requestRender(); + } + return; + } + + if (data.type === "tool_execution_start") { + outputLog.append(`${DIM}[tool: ${data.toolName}]${RESET}`); + tui.requestRender(); + return; + } + + if (data.type === "tool_execution_end") { + const result = JSON.stringify(data.result).slice(0, 120); + outputLog.append(`${DIM}[result: ${result}...]${RESET}`); + tui.requestRender(); + return; + } + + if (data.type === "agent_end") { + isStreaming = false; + hideLoading(); + outputLog.append(""); + tui.requestRender(); + return; + } + }); + + // -- User input -- + + promptInput.input.onSubmit = (value) => { + const trimmed = value.trim(); + if (!trimmed) return; + + promptInput.input.setValue(""); + + if (handleSlashCommand(trimmed)) { + outputLog.append(`${GREEN}${BOLD}You:${RESET} ${trimmed}`); + tui.requestRender(); + return; + } + + outputLog.append(`${GREEN}${BOLD}You:${RESET} ${trimmed}`); + send({ type: "prompt", message: trimmed }); + tui.requestRender(); + }; + + promptInput.onCtrlD = exit; + + promptInput.input.onEscape = () => { + if (isStreaming) { + send({ type: "abort" }); + outputLog.append(`${YELLOW}[aborted]${RESET}`); + tui.requestRender(); + } else { + exit(); + } + }; + + // -- Agent exit -- + + agent.on("exit", (code) => { + tui.stop(); + if (stderr) console.error(stderr); + console.log(`Agent exited with code ${code}`); + process.exit(code ?? 0); + }); + + // -- Start -- + + outputLog.append(`${BOLD}RPC Chat${RESET}`); + outputLog.append(`${DIM}Type a message and press Enter. Esc to abort or exit. Ctrl+D to quit.${RESET}`); + outputLog.append(`${DIM}Slash commands: /select /confirm /input /editor${RESET}`); + outputLog.append(""); + + tui.start(); +} + +main().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/examples/sdk/01-minimal.ts b/examples/sdk/01-minimal.ts new file mode 100644 index 0000000..a01f9c1 --- /dev/null +++ b/examples/sdk/01-minimal.ts @@ -0,0 +1,26 @@ +/** + * Minimal SDK Usage + * + * Uses all defaults: discovers skills, extensions, tools, context files + * from cwd and ~/.pi/agent. Model chosen from settings or first available. + */ + +import { createAgentSession } from "@earendil-works/pi-coding-agent"; + +const { session } = await createAgentSession(); + +try { + session.subscribe((event) => { + if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { + process.stdout.write(event.assistantMessageEvent.delta); + } + }); + + await session.prompt("What files are in the current directory?"); + session.state.messages.forEach((msg) => { + console.log(msg); + }); + console.log(); +} finally { + session.dispose(); +} diff --git a/examples/sdk/02-custom-model.ts b/examples/sdk/02-custom-model.ts new file mode 100644 index 0000000..ab947dc --- /dev/null +++ b/examples/sdk/02-custom-model.ts @@ -0,0 +1,50 @@ +/** + * Custom Model Selection + * + * Shows how to select a specific model and thinking level. + */ + +import { getModel } from "@earendil-works/pi-ai/compat"; +import { createAgentSession, ModelRuntime } from "@earendil-works/pi-coding-agent"; + +const modelRuntime = await ModelRuntime.create(); + +// Option 1: Find a specific built-in model by provider/id +const opus = getModel("anthropic", "claude-opus-4-5"); +if (opus) { + console.log(`Found model: ${opus.provider}/${opus.id}`); +} + +// Option 2: Find model via registry (includes custom models from models.json) +const customModel = modelRuntime.getModel("my-provider", "my-model"); +if (customModel) { + console.log(`Found custom model: ${customModel.provider}/${customModel.id}`); +} + +// Option 3: Pick from available models (have valid API keys) +const available = await modelRuntime.getAvailable(); +console.log( + "Available models:", + available.map((m) => `${m.provider}/${m.id}`), +); + +if (available.length > 0) { + const { session } = await createAgentSession({ + model: available[0], + thinkingLevel: "medium", // off, low, medium, high + modelRuntime, + }); + + try { + session.subscribe((event) => { + if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { + process.stdout.write(event.assistantMessageEvent.delta); + } + }); + + await session.prompt("Say hello in one sentence."); + console.log(); + } finally { + session.dispose(); + } +} diff --git a/examples/sdk/03-custom-prompt.ts b/examples/sdk/03-custom-prompt.ts new file mode 100644 index 0000000..ad1fdaa --- /dev/null +++ b/examples/sdk/03-custom-prompt.ts @@ -0,0 +1,75 @@ +/** + * Custom System Prompt + * + * Shows how to replace or modify the default system prompt. + */ + +import { + createAgentSession, + DefaultResourceLoader, + getAgentDir, + SessionManager, +} from "@earendil-works/pi-coding-agent"; + +const cwd = process.cwd(); +const agentDir = getAgentDir(); + +// Option 1: Replace prompt entirely +const loader1 = new DefaultResourceLoader({ + cwd, + agentDir, + systemPromptOverride: () => `You are a helpful assistant that speaks like a pirate. +Always end responses with "Arrr!"`, + // Needed to avoid DefaultResourceLoader appending APPEND_SYSTEM.md from ~/.pi/agent or /.pi. + appendSystemPromptOverride: () => [], +}); +await loader1.reload(); + +const { session: session1 } = await createAgentSession({ + resourceLoader: loader1, + sessionManager: SessionManager.inMemory(), +}); + +try { + session1.subscribe((event) => { + if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { + process.stdout.write(event.assistantMessageEvent.delta); + } + }); + + console.log("=== Replace prompt ==="); + await session1.prompt("What is 2 + 2?"); + console.log("\n"); +} finally { + session1.dispose(); +} + +// Option 2: Append instructions to the default prompt +const loader2 = new DefaultResourceLoader({ + cwd, + agentDir, + appendSystemPromptOverride: (base) => [ + ...base, + "## Additional Instructions\n- Always be concise\n- Use bullet points when listing things", + ], +}); +await loader2.reload(); + +const { session: session2 } = await createAgentSession({ + resourceLoader: loader2, + sessionManager: SessionManager.inMemory(), +}); + +try { + session2.subscribe((event) => { + if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { + process.stdout.write(event.assistantMessageEvent.delta); + } + }); + + console.log("=== Modify prompt ==="); + await session2.prompt("List 3 benefits of TypeScript."); + console.log(); +} finally { + session2.dispose(); +} diff --git a/examples/sdk/04-skills.ts b/examples/sdk/04-skills.ts new file mode 100644 index 0000000..3c0887c --- /dev/null +++ b/examples/sdk/04-skills.ts @@ -0,0 +1,55 @@ +/** + * Skills Configuration + * + * Skills provide specialized instructions loaded into the system prompt. + * Discover, filter, merge, or replace them. + */ + +import { + createAgentSession, + createSyntheticSourceInfo, + DefaultResourceLoader, + getAgentDir, + SessionManager, + type Skill, +} from "@earendil-works/pi-coding-agent"; + +// Or define custom skills inline +const customSkill: Skill = { + name: "my-skill", + description: "Custom project instructions", + filePath: "/virtual/SKILL.md", + baseDir: "/virtual", + sourceInfo: createSyntheticSourceInfo("/virtual/SKILL.md", { source: "sdk" }), + disableModelInvocation: false, +}; + +const loader = new DefaultResourceLoader({ + cwd: process.cwd(), + agentDir: getAgentDir(), + skillsOverride: (current) => { + const filteredSkills = current.skills.filter((s) => s.name.includes("browser") || s.name.includes("search")); + return { + skills: [...filteredSkills, customSkill], + diagnostics: current.diagnostics, + }; + }, +}); +await loader.reload(); + +// Discover all skills from cwd/.pi/skills, ~/.pi/agent/skills, etc. +const { skills: allSkills, diagnostics } = loader.getSkills(); +console.log( + "Discovered skills:", + allSkills.map((s) => s.name), +); +if (diagnostics.length > 0) { + console.log("Warnings:", diagnostics); +} + +const { session } = await createAgentSession({ + resourceLoader: loader, + sessionManager: SessionManager.inMemory(), +}); +console.log("Session created with filtered skills"); +session.dispose(); diff --git a/examples/sdk/05-tools.ts b/examples/sdk/05-tools.ts new file mode 100644 index 0000000..5f6f710 --- /dev/null +++ b/examples/sdk/05-tools.ts @@ -0,0 +1,48 @@ +/** + * Tools Configuration + * + * Use tool names to choose which built-in tools are enabled. + * + * Tool names are matched against all available tools. If you use a custom `cwd`, + * createAgentSession() applies that cwd when it builds the actual built-in tools. + * + * For custom tools, see 06-extensions.ts - custom tools are registered via the + * extensions system using pi.registerTool(). + */ + +import { createAgentSession, SessionManager } from "@earendil-works/pi-coding-agent"; + +// Read-only mode (no edit/write) +const { session: readOnlySession } = await createAgentSession({ + tools: ["read", "grep", "find", "ls"], + sessionManager: SessionManager.inMemory(), +}); +console.log("Read-only session created"); +readOnlySession.dispose(); + +// Custom tool selection +const { session: customToolsSession } = await createAgentSession({ + tools: ["read", "bash", "grep"], + sessionManager: SessionManager.inMemory(), +}); +console.log("Custom tools session created"); +customToolsSession.dispose(); + +// With custom cwd +const customCwd = "/path/to/project"; +const { session: customCwdSession } = await createAgentSession({ + cwd: customCwd, + tools: ["read", "bash", "edit", "write"], + sessionManager: SessionManager.inMemory(customCwd), +}); +console.log("Custom cwd session created"); +customCwdSession.dispose(); + +// Or pick specific tools for custom cwd +const { session: specificToolsSession } = await createAgentSession({ + cwd: customCwd, + tools: ["read", "bash", "grep"], + sessionManager: SessionManager.inMemory(customCwd), +}); +console.log("Specific tools with custom cwd session created"); +specificToolsSession.dispose(); diff --git a/examples/sdk/06-extensions.ts b/examples/sdk/06-extensions.ts new file mode 100644 index 0000000..6a8e6a1 --- /dev/null +++ b/examples/sdk/06-extensions.ts @@ -0,0 +1,99 @@ +/** + * Extensions Configuration + * + * Extensions intercept agent events and can register custom tools. + * They provide a unified system for extensions, custom tools, commands, and more. + * + * By default, extension files are discovered from: + * - ~/.pi/agent/extensions/ + * - /.pi/extensions/ + * - Paths specified in settings.json "extensions" array + * + * An extension is a TypeScript file that exports a default function: + * export default function (pi: ExtensionAPI) { ... } + */ + +import { + createAgentSession, + DefaultResourceLoader, + getAgentDir, + SessionManager, +} from "@earendil-works/pi-coding-agent"; + +// Extensions are discovered automatically from standard locations. +// You can also add paths via settings.json or DefaultResourceLoader options. + +const resourceLoader = new DefaultResourceLoader({ + cwd: process.cwd(), + agentDir: getAgentDir(), + additionalExtensionPaths: ["./my-logging-extension.ts", "./my-safety-extension.ts"], + extensionFactories: [ + (pi) => { + pi.on("agent_start", () => { + console.log("[Inline Extension] Agent starting"); + }); + }, + ], +}); +await resourceLoader.reload(); + +const { session } = await createAgentSession({ + resourceLoader, + sessionManager: SessionManager.inMemory(), +}); + +try { + session.subscribe((event) => { + if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { + process.stdout.write(event.assistantMessageEvent.delta); + } + }); + + await session.prompt("List files in the current directory."); + console.log(); +} finally { + session.dispose(); +} + +// Example extension file (./my-logging-extension.ts): +/* +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; + +export default function (pi: ExtensionAPI) { + pi.on("agent_start", async () => { + console.log("[Extension] Agent starting"); + }); + + pi.on("tool_call", async (event) => { + console.log(\`[Extension] Tool: \${event.toolName}\`); + // Return { block: true, reason: "..." } to block execution + return undefined; + }); + + pi.on("agent_end", async (event) => { + console.log(\`[Extension] Done, \${event.messages.length} messages\`); + }); + + // Register a custom tool + pi.registerTool({ + name: "my_tool", + label: "My Tool", + description: "Does something useful", + parameters: Type.Object({ + input: Type.String(), + }), + execute: async (_toolCallId, params, _signal, _onUpdate, _ctx) => ({ + content: [{ type: "text", text: \`Processed: \${params.input}\` }], + details: {}, + }), + }); + + // Register a command + pi.registerCommand("mycommand", { + description: "Do something", + handler: async (args, ctx) => { + ctx.ui.notify(\`Command executed with: \${args}\`); + }, + }); +} +*/ diff --git a/examples/sdk/07-context-files.ts b/examples/sdk/07-context-files.ts new file mode 100644 index 0000000..c97b488 --- /dev/null +++ b/examples/sdk/07-context-files.ts @@ -0,0 +1,47 @@ +/** + * Context Files (AGENTS.md) + * + * Context files provide project-specific instructions loaded into the system prompt. + */ + +import { + createAgentSession, + DefaultResourceLoader, + getAgentDir, + SessionManager, +} from "@earendil-works/pi-coding-agent"; + +// Disable context files entirely by returning an empty list in agentsFilesOverride. +const loader = new DefaultResourceLoader({ + cwd: process.cwd(), + agentDir: getAgentDir(), + agentsFilesOverride: (current) => ({ + agentsFiles: [ + ...current.agentsFiles, + { + path: "/virtual/AGENTS.md", + content: `# Project Guidelines + +## Code Style +- Use TypeScript strict mode +- No any types +- Prefer const over let`, + }, + ], + }), +}); +await loader.reload(); + +// Discover AGENTS.md files walking up from cwd +const discovered = loader.getAgentsFiles().agentsFiles; +console.log("Discovered context files:"); +for (const file of discovered) { + console.log(` - ${file.path} (${file.content.length} chars)`); +} + +const { session } = await createAgentSession({ + resourceLoader: loader, + sessionManager: SessionManager.inMemory(), +}); +console.log(`Session created with ${discovered.length + 1} context files`); +session.dispose(); diff --git a/examples/sdk/08-prompt-templates.ts b/examples/sdk/08-prompt-templates.ts new file mode 100644 index 0000000..b52de6c --- /dev/null +++ b/examples/sdk/08-prompt-templates.ts @@ -0,0 +1,51 @@ +/** + * Prompt Templates + * + * File-based templates that inject content when invoked with /templatename. + */ + +import { + createAgentSession, + createSyntheticSourceInfo, + DefaultResourceLoader, + getAgentDir, + type PromptTemplate, + SessionManager, +} from "@earendil-works/pi-coding-agent"; + +// Define custom templates +const deployTemplate: PromptTemplate = { + name: "deploy", + description: "Deploy the application", + filePath: "/virtual/prompts/deploy.md", + sourceInfo: createSyntheticSourceInfo("/virtual/prompts/deploy.md", { source: "sdk" }), + content: `# Deploy Instructions + +1. Build: npm run build +2. Test: npm test +3. Deploy: npm run deploy`, +}; + +const loader = new DefaultResourceLoader({ + cwd: process.cwd(), + agentDir: getAgentDir(), + promptsOverride: (current) => ({ + prompts: [...current.prompts, deployTemplate], + diagnostics: current.diagnostics, + }), +}); +await loader.reload(); + +// Discover templates from cwd/.pi/prompts/ and ~/.pi/agent/prompts/ +const discovered = loader.getPrompts().prompts; +console.log("Discovered prompt templates:"); +for (const template of discovered) { + console.log(` /${template.name}: ${template.description}`); +} + +const { session } = await createAgentSession({ + resourceLoader: loader, + sessionManager: SessionManager.inMemory(), +}); +console.log(`Session created with ${discovered.length + 1} prompt templates`); +session.dispose(); diff --git a/examples/sdk/09-api-keys-and-oauth.ts b/examples/sdk/09-api-keys-and-oauth.ts new file mode 100644 index 0000000..179b1d2 --- /dev/null +++ b/examples/sdk/09-api-keys-and-oauth.ts @@ -0,0 +1,34 @@ +/** + * API Keys and OAuth + * + * Configure provider auth through ModelRuntime. + */ + +import { createAgentSession, ModelRuntime, SessionManager } from "@earendil-works/pi-coding-agent"; + +const modelRuntime = await ModelRuntime.create(); +const { session: defaultAuthSession } = await createAgentSession({ + sessionManager: SessionManager.inMemory(), + modelRuntime, +}); +console.log("Session with default model runtime"); +defaultAuthSession.dispose(); + +const customRuntime = await ModelRuntime.create({ + authPath: "/tmp/my-app/auth.json", + modelsPath: "/tmp/my-app/models.json", +}); +const { session: customAuthSession } = await createAgentSession({ + sessionManager: SessionManager.inMemory(), + modelRuntime: customRuntime, +}); +console.log("Session with custom auth and models locations"); +customAuthSession.dispose(); + +modelRuntime.setRuntimeApiKey("anthropic", "sk-my-temp-key"); +const { session: runtimeKeySession } = await createAgentSession({ + sessionManager: SessionManager.inMemory(), + modelRuntime, +}); +console.log("Session with runtime API key override"); +runtimeKeySession.dispose(); diff --git a/examples/sdk/10-settings.ts b/examples/sdk/10-settings.ts new file mode 100644 index 0000000..93f7baf --- /dev/null +++ b/examples/sdk/10-settings.ts @@ -0,0 +1,53 @@ +/** + * Settings Configuration + * + * Override settings using SettingsManager. + */ + +import { createAgentSession, SessionManager, SettingsManager } from "@earendil-works/pi-coding-agent"; + +const cwd = process.cwd(); + +// Load current settings (merged global + project) +const settingsManagerFromDisk = SettingsManager.create(cwd); +console.log("Current settings:", JSON.stringify(settingsManagerFromDisk.getGlobalSettings(), null, 2)); + +// Override specific settings +const settingsManager = SettingsManager.create(cwd); +settingsManager.applyOverrides({ + compaction: { enabled: false }, + retry: { enabled: true, maxRetries: 5, baseDelayMs: 1000 }, +}); + +const { session: customSettingsSession } = await createAgentSession({ + settingsManager, + sessionManager: SessionManager.inMemory(), +}); +console.log("Session created with custom settings"); +customSettingsSession.dispose(); + +// Setters update memory immediately and queue persistence writes. +// Call flush() when you need a durability boundary. +settingsManager.setDefaultThinkingLevel("low"); +await settingsManager.flush(); + +// Surface settings I/O errors at the app layer. +const settingsErrors = settingsManager.drainErrors(); +if (settingsErrors.length > 0) { + for (const { scope, error } of settingsErrors) { + console.warn(`Warning (${scope} settings): ${error.message}`); + } +} + +// For testing without file I/O: +const inMemorySettings = SettingsManager.inMemory({ + compaction: { enabled: false }, + retry: { enabled: false }, +}); + +const { session: testSession } = await createAgentSession({ + settingsManager: inMemorySettings, + sessionManager: SessionManager.inMemory(), +}); +console.log("Test session created with in-memory settings"); +testSession.dispose(); diff --git a/examples/sdk/11-sessions.ts b/examples/sdk/11-sessions.ts new file mode 100644 index 0000000..975a6bb --- /dev/null +++ b/examples/sdk/11-sessions.ts @@ -0,0 +1,52 @@ +/** + * Session Management + * + * Control session persistence: in-memory, new file, continue, or open specific. + */ + +import { createAgentSession, SessionManager } from "@earendil-works/pi-coding-agent"; + +// In-memory (no persistence) +const { session: inMemory } = await createAgentSession({ + sessionManager: SessionManager.inMemory(), +}); +console.log("In-memory session:", inMemory.sessionFile ?? "(none)"); +inMemory.dispose(); + +// New persistent session +const { session: newSession } = await createAgentSession({ + sessionManager: SessionManager.create(process.cwd()), +}); +console.log("New session file:", newSession.sessionFile); +newSession.dispose(); + +// Continue most recent session (or create new if none) +const { session: continued, modelFallbackMessage } = await createAgentSession({ + sessionManager: SessionManager.continueRecent(process.cwd()), +}); +if (modelFallbackMessage) console.log("Note:", modelFallbackMessage); +console.log("Continued session:", continued.sessionFile); +continued.dispose(); + +// List and open specific session +const sessions = await SessionManager.list(process.cwd()); +console.log(`\nFound ${sessions.length} sessions:`); +for (const info of sessions.slice(0, 3)) { + console.log(` ${info.id.slice(0, 8)}... - "${info.firstMessage.slice(0, 30)}..."`); +} + +if (sessions.length > 0) { + const { session: opened } = await createAgentSession({ + sessionManager: SessionManager.open(sessions[0].path), + }); + console.log(`\nOpened: ${opened.sessionId}`); + opened.dispose(); +} + +// Custom session directory (no cwd encoding) +// const customDir = "/path/to/my-sessions"; +// const { session } = await createAgentSession({ +// sessionManager: SessionManager.create(process.cwd(), customDir), +// }); +// SessionManager.list(process.cwd(), customDir); +// SessionManager.continueRecent(process.cwd(), customDir); diff --git a/examples/sdk/12-full-control.ts b/examples/sdk/12-full-control.ts new file mode 100644 index 0000000..2305e61 --- /dev/null +++ b/examples/sdk/12-full-control.ts @@ -0,0 +1,74 @@ +/** + * Full Control + * + * Replace everything - no discovery, explicit configuration. + */ + +import { getModel } from "@earendil-works/pi-ai/compat"; +import { + createAgentSession, + createExtensionRuntime, + ModelRuntime, + type ResourceLoader, + SessionManager, + SettingsManager, +} from "@earendil-works/pi-coding-agent"; + +const modelRuntime = await ModelRuntime.create({ + authPath: "/tmp/my-agent/auth.json", + modelsPath: "/tmp/my-agent/models.json", +}); +if (process.env.MY_ANTHROPIC_KEY) { + modelRuntime.setRuntimeApiKey("anthropic", process.env.MY_ANTHROPIC_KEY); +} + +const model = getModel("anthropic", "claude-sonnet-4-5"); +if (!model) throw new Error("Model not found"); + +// In-memory settings with overrides +const settingsManager = SettingsManager.inMemory({ + compaction: { enabled: false }, + retry: { enabled: true, maxRetries: 2 }, +}); + +const cwd = process.cwd(); + +const resourceLoader: ResourceLoader = { + getExtensions: () => ({ extensions: [], errors: [], runtime: createExtensionRuntime() }), + getSkills: () => ({ skills: [], diagnostics: [] }), + getPrompts: () => ({ prompts: [], diagnostics: [] }), + getThemes: () => ({ themes: [], diagnostics: [] }), + getAgentsFiles: () => ({ agentsFiles: [] }), + getSystemPrompt: () => `You are a minimal assistant. +Available: read, bash. Be concise.`, + getSystemPromptSource: () => undefined, + getAppendSystemPrompt: () => [], + getAppendSystemPromptSources: () => [], + extendResources: () => {}, + reload: async () => {}, +}; + +const { session } = await createAgentSession({ + cwd, + agentDir: "/tmp/my-agent", + model, + thinkingLevel: "off", + modelRuntime, + resourceLoader, + tools: ["read", "bash"], + sessionManager: SessionManager.inMemory(cwd), + settingsManager, +}); + +try { + session.subscribe((event) => { + if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { + process.stdout.write(event.assistantMessageEvent.delta); + } + }); + + await session.prompt("List files in the current directory."); + console.log(); +} finally { + session.dispose(); +} diff --git a/examples/sdk/13-session-runtime.ts b/examples/sdk/13-session-runtime.ts new file mode 100644 index 0000000..52c7f24 --- /dev/null +++ b/examples/sdk/13-session-runtime.ts @@ -0,0 +1,67 @@ +/** + * Session runtime + * + * Use AgentSessionRuntime when you need to replace the active AgentSession, + * for example for new-session, resume, fork, or import flows. + * + * The important pattern is: after the runtime replaces the active session, + * rebind any session-local subscriptions and extension bindings to `runtime.session`. + */ + +import { + type CreateAgentSessionRuntimeFactory, + createAgentSessionFromServices, + createAgentSessionRuntime, + createAgentSessionServices, + getAgentDir, + SessionManager, +} from "@earendil-works/pi-coding-agent"; + +const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => { + const services = await createAgentSessionServices({ cwd }); + return { + ...(await createAgentSessionFromServices({ + services, + sessionManager, + sessionStartEvent, + })), + services, + diagnostics: services.diagnostics, + }; +}; +const runtime = await createAgentSessionRuntime(createRuntime, { + cwd: process.cwd(), + agentDir: getAgentDir(), + sessionManager: SessionManager.create(process.cwd()), +}); + +let unsubscribe: (() => void) | undefined; + +async function bindSession() { + unsubscribe?.(); + const session = runtime.session; + await session.bindExtensions({}); + unsubscribe = session.subscribe((event) => { + if (event.type === "queue_update") { + console.log("Queued:", event.steering.length + event.followUp.length); + } + }); + return session; +} + +let session = await bindSession(); +const originalSessionFile = session.sessionFile; +console.log("Initial session:", originalSessionFile); + +await runtime.newSession(); +session = await bindSession(); +console.log("After newSession():", session.sessionFile); + +if (originalSessionFile) { + await runtime.switchSession(originalSessionFile); + session = await bindSession(); + console.log("After switchSession():", session.sessionFile); +} + +unsubscribe?.(); +await runtime.dispose(); diff --git a/examples/sdk/README.md b/examples/sdk/README.md new file mode 100644 index 0000000..71689b0 --- /dev/null +++ b/examples/sdk/README.md @@ -0,0 +1,140 @@ +# SDK Examples + +Programmatic usage of pi-coding-agent via `createAgentSession()` and `createAgentSessionRuntime()`. + +The runtime example shows how to build a recreate function that closes over process-global fixed inputs and recreates cwd-bound services and sessions as the active session cwd changes. + +## Examples + +| File | Description | +|------|-------------| +| `01-minimal.ts` | Simplest usage with all defaults | +| `02-custom-model.ts` | Select model and thinking level | +| `03-custom-prompt.ts` | Replace or modify system prompt | +| `04-skills.ts` | Discover, filter, or replace skills | +| `05-tools.ts` | Built-in tool allowlists | +| `06-extensions.ts` | Logging, blocking, result modification | +| `07-context-files.ts` | AGENTS.md context files | +| `08-slash-commands.ts` | File-based slash commands | +| `09-api-keys-and-oauth.ts` | API key resolution, OAuth config | +| `10-settings.ts` | Override compaction, retry, terminal settings | +| `11-sessions.ts` | In-memory, persistent, continue, list sessions | +| `12-full-control.ts` | Replace everything, no discovery | +| `13-session-runtime.ts` | Manage runtime-backed session replacement | + +## Running + +```bash +cd packages/coding-agent +npx tsx examples/sdk/01-minimal.ts +``` + +## Quick Reference + +```typescript +import { getModel } from "@earendil-works/pi-ai"; +import { + createAgentSession, + DefaultResourceLoader, + ModelRuntime, + SessionManager, + SettingsManager, +} from "@earendil-works/pi-coding-agent"; + +const modelRuntime = await ModelRuntime.create(); + +// Minimal +const { session } = await createAgentSession({ modelRuntime }); + +// Custom model +const model = getModel("anthropic", "claude-opus-4-5"); +const { session } = await createAgentSession({ model, thinkingLevel: "high", modelRuntime }); + +// Modify prompt +const loader = new DefaultResourceLoader({ + systemPromptOverride: (base) => `${base}\n\nBe concise.`, +}); +await loader.reload(); +const { session } = await createAgentSession({ resourceLoader: loader, modelRuntime }); + +// Read-only +const { session } = await createAgentSession({ tools: ["read", "grep", "find", "ls"], modelRuntime }); + +// In-memory +const { session } = await createAgentSession({ + sessionManager: SessionManager.inMemory(), + modelRuntime, +}); + +// Full control +const customRuntime = await ModelRuntime.create({ + authPath: "/my/app/auth.json", + modelsPath: "/my/app/models.json", +}); +customRuntime.setRuntimeApiKey("anthropic", process.env.MY_KEY!); + +const resourceLoader = new DefaultResourceLoader({ + systemPromptOverride: () => "You are helpful.", + extensionFactories: [myExtension], + skillsOverride: () => ({ skills: [], diagnostics: [] }), + agentsFilesOverride: () => ({ agentsFiles: [] }), + promptsOverride: () => ({ prompts: [], diagnostics: [] }), +}); +await resourceLoader.reload(); + +const { session } = await createAgentSession({ + model, + modelRuntime: customRuntime, + resourceLoader, + tools: ["read", "bash", "my_tool"], + customTools: [myTool], + sessionManager: SessionManager.inMemory(), + settingsManager: SettingsManager.inMemory(), +}); + +// Run prompts +session.subscribe((event) => { + if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") { + process.stdout.write(event.assistantMessageEvent.delta); + } +}); +await session.prompt("Hello"); +``` + +## Options + +| Option | Default | Description | +|--------|---------|-------------| +| `modelRuntime` | Runtime using `agentDir/auth.json` and `models.json` | Canonical model and authentication runtime | +| `cwd` | `process.cwd()` | Working directory | +| `agentDir` | `~/.pi/agent` | Config directory | +| `model` | From settings/first available | Model to use | +| `thinkingLevel` | From settings/"off" | off, low, medium, high | +| `tools` | `["read", "bash", "edit", "write"]` built-ins | Allowlist tool names across built-in, extension, and custom tools | +| `customTools` | `[]` | Additional tool definitions | +| `resourceLoader` | DefaultResourceLoader | Resource loader for extensions, skills, prompts, themes, and context files | +| `sessionManager` | `SessionManager.create(cwd)` | Persistence | +| `settingsManager` | `SettingsManager.create(cwd, agentDir)` | Settings overrides | + +## Events + +```typescript +session.subscribe((event) => { + switch (event.type) { + case "message_update": + if (event.assistantMessageEvent.type === "text_delta") { + process.stdout.write(event.assistantMessageEvent.delta); + } + break; + case "tool_execution_start": + console.log(`Tool: ${event.toolName}`); + break; + case "tool_execution_end": + console.log(`Result: ${event.result}`); + break; + case "agent_end": + console.log("Done"); + break; + } +}); +``` diff --git a/npm-shrinkwrap.json b/npm-shrinkwrap.json new file mode 100644 index 0000000..86988fc --- /dev/null +++ b/npm-shrinkwrap.json @@ -0,0 +1,1825 @@ +{ + "name": "@earendil-works/pi-coding-agent", + "version": "0.83.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@earendil-works/pi-coding-agent", + "version": "0.83.0", + "license": "MIT", + "dependencies": { + "@earendil-works/pi-agent-core": "^0.83.0", + "@earendil-works/pi-ai": "^0.83.0", + "@earendil-works/pi-tui": "^0.83.0", + "@silvia-odwyer/photon-node": "0.3.4", + "chalk": "5.6.2", + "cross-spawn": "7.0.6", + "diff": "8.0.4", + "glob": "13.0.6", + "highlight.js": "10.7.3", + "hosted-git-info": "9.0.3", + "ignore": "7.0.5", + "jiti": "2.7.0", + "minimatch": "10.2.5", + "proper-lockfile": "4.1.2", + "semver": "7.8.0", + "typebox": "1.3.7", + "undici": "8.5.0", + "yaml": "2.9.0" + }, + "optionalDependencies": { + "@mariozechner/clipboard": "0.3.9" + }, + "bin": { + "pi": "dist/cli.js" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.91.1", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.91.1.tgz", + "integrity": "sha512-LAmu761tSN9r66ixvmciswUj/ZC+1Q4iAfpedTfSVLeswRwnY3n2Nb6Tsk+cLPP28aLOPWeMgIuTuCcMC6W/iw==", + "license": "MIT", + "dependencies": { + "json-schema-to-ts": "^3.1.1" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + } + }, + "node_modules/@aws-crypto/crc32": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", + "integrity": "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz", + "integrity": "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-js": "^5.2.0", + "@aws-crypto/supports-web-crypto": "^5.2.0", + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-locate-window": "^3.0.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha256-js": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz", + "integrity": "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/supports-web-crypto": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz", + "integrity": "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz", + "integrity": "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.222.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-sdk/client-bedrock-runtime": { + "version": "3.1048.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.1048.0.tgz", + "integrity": "sha512-u+NT61JZEkRFtpL0CAw1N1dwxnaLgwVXQl/zjJxTGgLyS/jTIdg2SdoEoCTHxgDyCnqa1HEi9QOoE9/pYRNpOQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/credential-provider-node": "^3.972.42", + "@aws-sdk/eventstream-handler-node": "^3.972.16", + "@aws-sdk/middleware-eventstream": "^3.972.12", + "@aws-sdk/middleware-websocket": "^3.972.19", + "@aws-sdk/token-providers": "3.1048.0", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/fetch-http-handler": "^5.4.2", + "@smithy/node-http-handler": "^4.7.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/core": { + "version": "3.974.11", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.974.11.tgz", + "integrity": "sha512-QpnINq5FZH6EOaDEkmHdT7eUunbvD27pDNQypaWjFyYz7Zl1q3UCMQErBZxpmfGfI7MvI2TlK8KTkgNpv8b1ug==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.973.8", + "@aws-sdk/xml-builder": "^3.972.24", + "@aws/lambda-invoke-store": "^0.2.2", + "@smithy/core": "^3.24.2", + "@smithy/signature-v4": "^5.4.2", + "@smithy/types": "^4.14.1", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-env": { + "version": "3.972.37", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.37.tgz", + "integrity": "sha512-/jpPvEh6f7ntmIzf7dNxoNX6Q8vt8UpesCjbW6mFfk4V1NW6bIy9qxcQ6WbA8As5yQhsZOe+xeNd4xHX8kdY2Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http": { + "version": "3.972.39", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.39.tgz", + "integrity": "sha512-pIgTpisWyWg7X1bUbzSjuUYosYTD0Ghz2M0hkSTmb3a6i3qV3uU+NYJPI/E2XSC0HcsZh5rsLPzeXrkb2DS0Cg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/fetch-http-handler": "^5.4.2", + "@smithy/node-http-handler": "^4.7.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.972.41", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.972.41.tgz", + "integrity": "sha512-u2tyjaxJJzW8UtW4SM1ZcPMDwO6y+kV+llvou+Adts0FAKyzes5jG4izQN+KX3yE8ZROpS5y1LJ//xL2iSf76w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/credential-provider-env": "^3.972.37", + "@aws-sdk/credential-provider-http": "^3.972.39", + "@aws-sdk/credential-provider-login": "^3.972.41", + "@aws-sdk/credential-provider-process": "^3.972.37", + "@aws-sdk/credential-provider-sso": "^3.972.41", + "@aws-sdk/credential-provider-web-identity": "^3.972.41", + "@aws-sdk/nested-clients": "^3.997.9", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/credential-provider-imds": "^4.3.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-login": { + "version": "3.972.41", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.41.tgz", + "integrity": "sha512-0LBitxXiAiaE5nlFPfpNIww/8FRY/I7WIndWsc9GmNFOM7cE1wNpVNQEGEk9Outg5l8xl+3vybxFyUy4l9q/LQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/nested-clients": "^3.997.9", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.972.42", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.42.tgz", + "integrity": "sha512-D4oon2zbqqsWOJUM99Gm3/ZyJ0IJvTXVN3PyloGb3kQEyI36fjCZheZj422lAgTWWd6TSHgiImLt3RIaLdv3dQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "^3.972.37", + "@aws-sdk/credential-provider-http": "^3.972.39", + "@aws-sdk/credential-provider-ini": "^3.972.41", + "@aws-sdk/credential-provider-process": "^3.972.37", + "@aws-sdk/credential-provider-sso": "^3.972.41", + "@aws-sdk/credential-provider-web-identity": "^3.972.41", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/credential-provider-imds": "^4.3.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.972.37", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.37.tgz", + "integrity": "sha512-7nVaHBUaWIddASYfVaA9O4D5ZVjewU3sCol9WqZPGfW0nR+0WqE0xHZnD/U2L33PlOB8KNXGKZ6wOES/QijKzg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.972.41", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.972.41.tgz", + "integrity": "sha512-IOWAWEHe5LkjSKkkUUX9ciV6Y1scHTsnfEkdt5yyC4Slrc7AGbkLPrpntjqh18ksJAMOaVhoBsO8p2WyTcY2wQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/nested-clients": "^3.997.9", + "@aws-sdk/token-providers": "3.1048.0", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.972.41", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.41.tgz", + "integrity": "sha512-mbACk9Yypa8nm4iGZLs0PofOXEcTDOUw6wDnsPXNDNSd2WNXs1tSo+6nc/fh0jLYdfVZThhBL98PHW4aXFsG5A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/nested-clients": "^3.997.9", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/eventstream-handler-node": { + "version": "3.972.16", + "resolved": "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.16.tgz", + "integrity": "sha512-yedpPgKftqjU5SlPFHfqWpOw6xSCRieWRG1euWOlXn4WJxt2VX92VprCa2PpSOXjVCAeK6dTjW9eJRXVig9yGA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/middleware-eventstream": { + "version": "3.972.12", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.12.tgz", + "integrity": "sha512-tHTHHCHNrq6XklQvlzHBDJG4Iuhh7NVPRdtmvP+nHFA+5sxPlIDzlAHHgfoYHGvT3NXP1yVP/L5c3opUn6T3Qg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/middleware-websocket": { + "version": "3.972.19", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.19.tgz", + "integrity": "sha512-mkEhOGYozqKQkbFaVrjwr0faiwwZza1v5/jSY6Tucm3bD+uKTazIUH/4Yo6aMnQD2ua2W9cMP6s8mvwTcjtqHw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/fetch-http-handler": "^5.4.2", + "@smithy/signature-v4": "^5.4.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">= 14.0.0" + } + }, + "node_modules/@aws-sdk/nested-clients": { + "version": "3.997.9", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.9.tgz", + "integrity": "sha512-jPR3rnmRI4hWYyzfmTGBr7NblMp8QYYeflHXba1H6+7CGrWVqWKQzaXFQ4qbExqPRsXN3T3L3JxFhr6aouXUGQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/signature-v4-multi-region": "^3.996.27", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/fetch-http-handler": "^5.4.2", + "@smithy/node-http-handler": "^4.7.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4-multi-region": { + "version": "3.996.27", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.27.tgz", + "integrity": "sha512-0Phbz4t6HI3D3skxvG2uI+VWU034/nSIw1T8d+FPzzQG9EQTrw94o9mOKO2Gv3n3Oc8P7JD7RAUxkoneLWv5Eg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/signature-v4": "^5.4.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/token-providers": { + "version": "3.1048.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1048.0.tgz", + "integrity": "sha512-k0y/GcuesuSfWyUM0WamrGyeZmltRYaPbHO82UDA6mZ/doB+FOHKutikPAtSXMn/hDz970cF+iRuuiYO9VEbAA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.974.11", + "@aws-sdk/nested-clients": "^3.997.9", + "@aws-sdk/types": "^3.973.8", + "@smithy/core": "^3.24.2", + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/types": { + "version": "3.973.8", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.973.8.tgz", + "integrity": "sha512-gjlAdtHMbtR9X5iIhVUvbVcy55KnznpC6bkDUWW9z915bi0ckdUr5cjf16Kp6xq0bP5HBD2xzgbL9F9Quv5vUw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.14.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/util-locate-window": { + "version": "3.965.5", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.965.5.tgz", + "integrity": "sha512-WhlJNNINQB+9qtLtZJcpQdgZw3SCDCpXdUJP7cToGwHbCWCnRckGlc6Bx/OhWwIYFNAn+FIydY8SZ0QmVu3xTQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/xml-builder": { + "version": "3.972.24", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.24.tgz", + "integrity": "sha512-V8z5YcDPfsvzrBlj0xR1vhRtocblhYbqdreCJB/voGd4Sr5zjNAeWxexbnqVtskTJe0vFb5KMqbSL++ePl+zRw==", + "license": "Apache-2.0", + "dependencies": { + "@nodable/entities": "2.1.0", + "@smithy/types": "^4.14.1", + "fast-xml-parser": "5.7.3", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws/lambda-invoke-store": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.2.4.tgz", + "integrity": "sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz", + "integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@earendil-works/pi-agent-core": { + "version": "0.83.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-agent-core/-/pi-agent-core-0.83.0.tgz", + "license": "MIT", + "dependencies": { + "@earendil-works/pi-ai": "^0.83.0", + "diff": "8.0.4", + "ignore": "7.0.5", + "typebox": "1.3.7", + "yaml": "2.9.0" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-ai": { + "version": "0.83.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-0.83.0.tgz", + "license": "MIT", + "dependencies": { + "@anthropic-ai/sdk": "0.91.1", + "@aws-sdk/client-bedrock-runtime": "3.1048.0", + "@google/genai": "1.52.0", + "@mistralai/mistralai": "2.2.6", + "@opentelemetry/api": "1.9.0", + "@smithy/node-http-handler": "4.7.3", + "http-proxy-agent": "7.0.2", + "https-proxy-agent": "7.0.6", + "openai": "6.26.0", + "partial-json": "0.1.7", + "typebox": "1.3.7" + }, + "bin": { + "pi-ai": "dist/cli.js" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@earendil-works/pi-tui": { + "version": "0.83.0", + "resolved": "https://registry.npmjs.org/@earendil-works/pi-tui/-/pi-tui-0.83.0.tgz", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "1.6.0", + "marked": "18.0.5" + }, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/@google/genai": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/@google/genai/-/genai-1.52.0.tgz", + "integrity": "sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q==", + "license": "Apache-2.0", + "dependencies": { + "google-auth-library": "^10.3.0", + "p-retry": "^4.6.2", + "protobufjs": "^7.5.4", + "ws": "^8.18.0" + }, + "peerDependencies": { + "@modelcontextprotocol/sdk": "^1.25.2" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/sdk": { + "optional": true + } + }, + "engines": { + "node": ">=20.0.0" + }, + "hasInstallScript": true + }, + "node_modules/@mariozechner/clipboard": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@mariozechner/clipboard/-/clipboard-0.3.9.tgz", + "integrity": "sha512-ABnA53mdfkGZwOFUdZNv2S0CWGO/EIuPj8Vv9xmBFmSYg/qFc7ihO6q5FcQjvoE67kZpWkEc4AhD6B/os04yuA==", + "license": "MIT", + "optionalDependencies": { + "@mariozechner/clipboard-darwin-arm64": "0.3.9", + "@mariozechner/clipboard-darwin-universal": "0.3.9", + "@mariozechner/clipboard-darwin-x64": "0.3.9", + "@mariozechner/clipboard-linux-arm64-gnu": "0.3.9", + "@mariozechner/clipboard-linux-arm64-musl": "0.3.9", + "@mariozechner/clipboard-linux-riscv64-gnu": "0.3.9", + "@mariozechner/clipboard-linux-x64-gnu": "0.3.9", + "@mariozechner/clipboard-linux-x64-musl": "0.3.9", + "@mariozechner/clipboard-win32-arm64-msvc": "0.3.9", + "@mariozechner/clipboard-win32-x64-msvc": "0.3.9" + }, + "engines": { + "node": ">= 10" + }, + "optional": true + }, + "node_modules/@mariozechner/clipboard-darwin-arm64": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@mariozechner/clipboard-darwin-arm64/-/clipboard-darwin-arm64-0.3.9.tgz", + "integrity": "sha512-BfgV7vCEWZwJwZJw03r6bP5+tf0iI/ANuQYCxi9RNn7FrWB3yzGuMKCrNLRl6V761vXRdL8+OqZ0wd4TqlsNOQ==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "os": [ + "darwin" + ], + "cpu": [ + "arm64" + ], + "optional": true + }, + "node_modules/@mariozechner/clipboard-darwin-universal": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@mariozechner/clipboard-darwin-universal/-/clipboard-darwin-universal-0.3.9.tgz", + "integrity": "sha512-BGGR4iA9Z2shAjI65eI5xtyb3LYNlDW9X3gxKxDbqtbnREohsrqznov6zpKoIrsRWpzlYVEdKphS7ksJ0/ndSQ==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "os": [ + "darwin" + ], + "optional": true + }, + "node_modules/@mariozechner/clipboard-darwin-x64": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@mariozechner/clipboard-darwin-x64/-/clipboard-darwin-x64-0.3.9.tgz", + "integrity": "sha512-4kURmCbS6nt8uYhtmWpUcJWyPHfmAr5dTpXD1nO3pIfa+TSQ9DbrGOYCKH+aEFW47XhQ4Vp8ZTszie+wfFvDKg==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "os": [ + "darwin" + ], + "cpu": [ + "x64" + ], + "optional": true + }, + "node_modules/@mariozechner/clipboard-linux-arm64-gnu": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@mariozechner/clipboard-linux-arm64-gnu/-/clipboard-linux-arm64-gnu-0.3.9.tgz", + "integrity": "sha512-g59OkUGP2DDfCOIKypHeYgv2M55u/cKvXa5dSxFbEJ34XvIQMdcVmpKCkGUro3ZgefXiGVdwguvTMQGpHWzIXw==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "os": [ + "linux" + ], + "cpu": [ + "arm64" + ], + "optional": true + }, + "node_modules/@mariozechner/clipboard-linux-arm64-musl": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@mariozechner/clipboard-linux-arm64-musl/-/clipboard-linux-arm64-musl-0.3.9.tgz", + "integrity": "sha512-AGuJdgKsmJdm4Pych7kv3sqe591ERRaAHW3xjLooiFzn8J+PxUyof++7YZrB5Y5tpnTO+K18Og3taj2NpluCRQ==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "os": [ + "linux" + ], + "cpu": [ + "arm64" + ], + "optional": true + }, + "node_modules/@mariozechner/clipboard-linux-riscv64-gnu": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@mariozechner/clipboard-linux-riscv64-gnu/-/clipboard-linux-riscv64-gnu-0.3.9.tgz", + "integrity": "sha512-DXBEAiuMpk7dhS1a9NzNxVAFi1vaKoPu7rQNgY8LIDLGrK3lnIp3nT10DUum+PKVJoJppIP+NAA8IZe4DMNDPw==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "os": [ + "linux" + ], + "cpu": [ + "riscv64" + ], + "optional": true + }, + "node_modules/@mariozechner/clipboard-linux-x64-gnu": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@mariozechner/clipboard-linux-x64-gnu/-/clipboard-linux-x64-gnu-0.3.9.tgz", + "integrity": "sha512-WORrMLd6EpElEME7JRKfSaY34nW1P5LbdgK5YNCS1ncG2LqmITsSMEJ8nh2mpvxb3TxqbOOKgY7k9eMJYlW9Mw==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "os": [ + "linux" + ], + "cpu": [ + "x64" + ], + "optional": true + }, + "node_modules/@mariozechner/clipboard-linux-x64-musl": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@mariozechner/clipboard-linux-x64-musl/-/clipboard-linux-x64-musl-0.3.9.tgz", + "integrity": "sha512-/DHn+1DrfL6oRaPPWXaOKvonFFrni666fxd+zFqiQEfvBH0tsHVWjq9iqBk0oDp0qaPA72lIMy5BptxISBEhZQ==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "os": [ + "linux" + ], + "cpu": [ + "x64" + ], + "optional": true + }, + "node_modules/@mariozechner/clipboard-win32-arm64-msvc": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@mariozechner/clipboard-win32-arm64-msvc/-/clipboard-win32-arm64-msvc-0.3.9.tgz", + "integrity": "sha512-O5FHD3ErkMwMhNzAfu3ggy0ug4z7btZuoQgwwxlzPrwV2bxlD6WDpqBY4NCgICAgZdDKdp+loUEKVAVt8aYnhQ==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "os": [ + "win32" + ], + "cpu": [ + "arm64" + ], + "optional": true + }, + "node_modules/@mariozechner/clipboard-win32-x64-msvc": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@mariozechner/clipboard-win32-x64-msvc/-/clipboard-win32-x64-msvc-0.3.9.tgz", + "integrity": "sha512-ihQC3EufqEY81vhXBgVBtK4prL+wc62zJsSvxrgz7K1hsdt6OObz6v9p3Rn1OG3GJksTTKMJF0u/guMISHPhSA==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "os": [ + "win32" + ], + "cpu": [ + "x64" + ], + "optional": true + }, + "node_modules/@mistralai/mistralai": { + "version": "2.2.6", + "resolved": "https://registry.npmjs.org/@mistralai/mistralai/-/mistralai-2.2.6.tgz", + "integrity": "sha512-W8pX7zHxjJvMIpw8JMxeJEleapXX0Q9NPszdNzqkM3MIEoIGPObdodujj+WHteXEvGfaP/AMwlNyRfEzSY6dQQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.40.0", + "ws": "^8.18.0", + "zod": "^3.25.0 || ^4.0.0", + "zod-to-json-schema": "^3.25.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.9.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + } + } + }, + "node_modules/@nodable/entities": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-2.1.0.tgz", + "integrity": "sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA==", + "license": "MIT", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/nodable" + } + ] + }, + "node_modules/@opentelemetry/api": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", + "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/semantic-conventions": { + "version": "1.41.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.41.1.tgz", + "integrity": "sha512-/UhIkaZgPutTFmQ7RnIJGgDXZmtEJ7Dvi86xNTFWcnRxVRNk/aotsqDJYeEvDP+FSMB2SdW+pQzNMcWP0rwuNA==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.1.tgz", + "integrity": "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==", + "license": "BSD-3-Clause" + }, + "node_modules/@silvia-odwyer/photon-node": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/@silvia-odwyer/photon-node/-/photon-node-0.3.4.tgz", + "integrity": "sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA==", + "license": "Apache-2.0" + }, + "node_modules/@smithy/core": { + "version": "3.24.3", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.24.3.tgz", + "integrity": "sha512-Ep/7tPamGY8mgESE3LyLKtxJyy6U52WWAqr/3wial47Sj4u3PiIF73AOGI27UyLy9duTkhZbgzodOfLV4TduZg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/crc32": "5.2.0", + "@smithy/types": "^4.14.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/credential-provider-imds": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.3.3.tgz", + "integrity": "sha512-I2Bti0DKFo2IJyN28ijCsx51BAumEYR4/1yZ1FXyBygy9MqbnMqCev4JPth/MbpRfBSRAX35hITSnAdJRo1u5w==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.24.3", + "@smithy/types": "^4.14.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/fetch-http-handler": { + "version": "5.4.3", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.4.3.tgz", + "integrity": "sha512-F+DRf8IJazRJgYog2A/yJK7eYVc0rqTlRzO+5ZxjJd4WkZoKz0IJRncf7G6t1pdVT3kryJcwuTFhN1c5m6N47A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.24.3", + "@smithy/types": "^4.14.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@smithy/node-http-handler": { + "version": "4.7.3", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.7.3.tgz", + "integrity": "sha512-/jPhevcTFPMVl6KNjbaI47iOg1zxC7IsnX4PQDGVZKMFceOXtB8IEYaB7a9VvkP/3oC60WzTeKocvSI7vLT0vA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.24.3", + "@smithy/types": "^4.14.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/signature-v4": { + "version": "5.4.3", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.4.3.tgz", + "integrity": "sha512-53+75QuPl6DL+ct6vVEB51FDO5oulXr20TPV46VvJZg76lIlXNWfxi8j+G2V/t0I2qxCBOa3vX/8bmjrpFVo9g==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.24.3", + "@smithy/types": "^4.14.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/types": { + "version": "4.14.2", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.14.2.tgz", + "integrity": "sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@types/node": { + "version": "22.19.19", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.19.tgz", + "integrity": "sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "license": "MIT", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/bignumber.js": { + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz", + "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/bowser": { + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz", + "integrity": "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==", + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "5.0.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.7.tgz", + "integrity": "sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==", + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + }, + "engines": { + "node": ">=6.0" + } + }, + "node_modules/diff": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz", + "integrity": "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "license": "MIT" + }, + "node_modules/fast-xml-builder": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.2.0.tgz", + "integrity": "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q==", + "license": "MIT", + "dependencies": { + "path-expression-matcher": "^1.5.0", + "xml-naming": "^0.1.0" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ] + }, + "node_modules/fast-xml-parser": { + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.7.3.tgz", + "integrity": "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg==", + "license": "MIT", + "dependencies": { + "@nodable/entities": "^2.1.0", + "fast-xml-builder": "^1.1.7", + "path-expression-matcher": "^1.5.0", + "strnum": "^2.2.3" + }, + "bin": { + "fxparser": "src/cli/cli.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ] + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "license": "MIT", + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ] + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "license": "MIT", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/gaxios": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.1.4.tgz", + "integrity": "sha512-bTIgTsM2bWn3XklZISBTQX7ZSddGW+IO3bMdGaemHZ3tbqExMENHLx6kKZ/KlejgrMtj8q7wBItt51yegqalrA==", + "license": "Apache-2.0", + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "node-fetch": "^3.3.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/gcp-metadata": { + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz", + "integrity": "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==", + "license": "Apache-2.0", + "dependencies": { + "gaxios": "^7.0.0", + "google-logging-utils": "^1.0.0", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz", + "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/google-auth-library": { + "version": "10.6.2", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.6.2.tgz", + "integrity": "sha512-e27Z6EThmVNNvtYASwQxose/G57rkRuaRbQyxM2bvYLLX/GqWZ5chWq2EBoUchJbCc57eC9ArzO5wMsEmWftCw==", + "license": "Apache-2.0", + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^7.1.4", + "gcp-metadata": "8.1.2", + "google-logging-utils": "1.1.3", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/google-logging-utils": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz", + "integrity": "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/highlight.js": { + "version": "10.7.3", + "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz", + "integrity": "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==", + "license": "BSD-3-Clause", + "engines": { + "node": "*" + } + }, + "node_modules/hosted-git-info": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz", + "integrity": "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==", + "license": "ISC", + "dependencies": { + "lru-cache": "^11.1.0" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/json-bigint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", + "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", + "license": "MIT", + "dependencies": { + "bignumber.js": "^9.0.0" + } + }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/lru-cache": { + "version": "11.4.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.4.0.tgz", + "integrity": "sha512-W+R+kFL4HgVxONq2bhXPi3bGpzGe/yEhVOp233qw9wCRtgncJ15P3bC+e4zZMu4Cq7d+WAJjXGW0uUkifhcatA==", + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/marked": { + "version": "18.0.5", + "resolved": "https://registry.npmjs.org/marked/-/marked-18.0.5.tgz", + "integrity": "sha512-S6GcvALHg6K4ohtu4E7x0a1AqhAjp6cV8KhLSyN9qVapnzJkusVBxZRcIU9AeYsbe6P1hKDusSbEOzGyyuce6w==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "license": "MIT", + "engines": { + "node": ">=10.5.0" + }, + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] + }, + "node_modules/node-fetch": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", + "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", + "license": "MIT", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/openai": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-6.26.0.tgz", + "integrity": "sha512-zd23dbWTjiJ6sSAX6s0HrCZi41JwTA1bQVs0wLQPZ2/5o2gxOJA5wh7yOAUgwYybfhDXyhwlpeQf7Mlgx8EOCA==", + "license": "Apache-2.0", + "peerDependencies": { + "ws": "^8.18.0", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "ws": { + "optional": true + }, + "zod": { + "optional": true + } + }, + "bin": { + "openai": "bin/cli" + } + }, + "node_modules/p-retry": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz", + "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", + "license": "MIT", + "dependencies": { + "@types/retry": "0.12.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-retry/node_modules/@types/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==", + "license": "MIT" + }, + "node_modules/partial-json": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz", + "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==", + "license": "MIT" + }, + "node_modules/path-expression-matcher": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz", + "integrity": "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ] + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/proper-lockfile": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz", + "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "retry": "^0.12.0", + "signal-exit": "^3.0.2" + } + }, + "node_modules/proper-lockfile/node_modules/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/protobufjs": { + "version": "7.6.5", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.5.tgz", + "integrity": "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + }, + "hasInstallScript": true + }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "license": "MIT", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/semver": { + "version": "7.8.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", + "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/strnum": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.3.0.tgz", + "integrity": "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q==", + "license": "MIT", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ] + }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/typebox": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/typebox/-/typebox-1.3.7.tgz", + "integrity": "sha512-meKuifc33Pccx0O6PdIzYMq3Og8zvP4TIi/a+Bw3AEMZMxOD0+RHGQvpglEe6Zdy3wZ8nqn/j95h8LUZLk/6Hg==", + "license": "MIT" + }, + "node_modules/undici": { + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.5.0.tgz", + "integrity": "sha512-xamtWoB1EshgjpmlXd7GGm2VfdDtw1+rD8uhry8pSNW3If6S8E0m2T2+orSKeZXEn/aPJMviCpDBA65WJt8zhg==", + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "license": "MIT", + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/xml-naming": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.1.0.tgz", + "integrity": "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==", + "license": "MIT", + "engines": { + "node": ">=16.0.0" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ] + }, + "node_modules/yaml": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", + "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..c7d8c8b --- /dev/null +++ b/package.json @@ -0,0 +1,101 @@ +{ + "name": "@earendil-works/pi-coding-agent", + "version": "0.83.0", + "description": "Coding agent CLI with read, bash, edit, write tools and session management", + "type": "module", + "piConfig": { + "configDir": ".pi" + }, + "bin": { + "pi": "dist/cli.js" + }, + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + }, + "./rpc-entry": { + "import": "./dist/rpc-entry.js" + } + }, + "files": [ + "dist", + "docs", + "examples", + "containerization.md", + "CHANGELOG.md", + "npm-shrinkwrap.json" + ], + "scripts": { + "clean": "shx rm -rf dist", + "build": "tsgo -p tsconfig.build.json && shx chmod +x dist/cli.js dist/rpc-entry.js && npm run copy-assets", + "build:binary": "npm --prefix ../tui run build && npm --prefix ../ai run build && npm --prefix ../agent run build && npm run build && bun build --compile ./dist/bun/cli.js ./src/utils/image-resize-worker.ts --outfile dist/pi && npm run copy-binary-assets", + "copy-assets": "shx mkdir -p dist/modes/interactive/theme && shx cp src/modes/interactive/theme/*.json dist/modes/interactive/theme/ && shx mkdir -p dist/modes/interactive/assets && shx cp src/modes/interactive/assets/*.png dist/modes/interactive/assets/ && shx mkdir -p dist/core/export-html/vendor && shx cp src/core/export-html/template.html src/core/export-html/template.css src/core/export-html/template.js dist/core/export-html/ && shx cp src/core/export-html/vendor/*.js dist/core/export-html/vendor/", + "copy-binary-assets": "shx cp package.json dist/ && shx cp README.md dist/ && shx cp CHANGELOG.md dist/ && shx mkdir -p dist/theme && shx cp src/modes/interactive/theme/*.json dist/theme/ && shx mkdir -p dist/assets && shx cp src/modes/interactive/assets/*.png dist/assets/ && shx mkdir -p dist/export-html/vendor && shx cp src/core/export-html/template.html dist/export-html/ && shx cp src/core/export-html/vendor/*.js dist/export-html/vendor/ && shx cp -r docs dist/ && shx cp -r examples dist/ && shx cp ../../node_modules/@silvia-odwyer/photon-node/photon_rs_bg.wasm dist/", + "test": "vitest --run", + "shrinkwrap": "node ../../scripts/generate-coding-agent-shrinkwrap.mjs", + "prepublishOnly": "npm run clean && npm run build && npm run shrinkwrap" + }, + "dependencies": { + "@earendil-works/pi-agent-core": "^0.83.0", + "@earendil-works/pi-ai": "^0.83.0", + "@earendil-works/pi-tui": "^0.83.0", + "@silvia-odwyer/photon-node": "0.3.4", + "chalk": "5.6.2", + "cross-spawn": "7.0.6", + "diff": "8.0.4", + "glob": "13.0.6", + "highlight.js": "10.7.3", + "hosted-git-info": "9.0.3", + "ignore": "7.0.5", + "jiti": "2.7.0", + "minimatch": "10.2.5", + "proper-lockfile": "4.1.2", + "semver": "7.8.0", + "typebox": "1.3.7", + "undici": "8.5.0", + "yaml": "2.9.0" + }, + "overrides": { + "protobufjs": "7.6.5", + "rimraf": "6.1.2", + "gaxios": { + "rimraf": "6.1.2" + } + }, + "optionalDependencies": { + "@mariozechner/clipboard": "0.3.9" + }, + "devDependencies": { + "@types/cross-spawn": "6.0.6", + "@types/diff": "7.0.2", + "@types/hosted-git-info": "3.0.5", + "@types/ms": "2.1.0", + "@types/node": "24.12.4", + "@types/proper-lockfile": "4.1.4", + "@types/semver": "7.7.1", + "shx": "0.4.0", + "typescript": "5.9.3", + "vitest": "4.1.9" + }, + "keywords": [ + "coding-agent", + "ai", + "llm", + "cli", + "tui", + "agent" + ], + "author": "Mario Zechner", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/earendil-works/pi.git", + "directory": "packages/coding-agent" + }, + "engines": { + "node": ">=22.19.0" + } +}