A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
correct outdated prime agent documentation (#492)
kt36307ca40d62
diff --git a/README.md b/README.mdindex 011da71e23..0201eb4aba 100644--- a/README.md+++ b/README.md@@ -29,7 +29,9 @@ Prime Agent: RLM-native Coding and Research Harness## Overview-Prime Agent is a fork of [pi-mono](https://github.com/badlogic/pi-mono) rebuilt around an RLM-native coding and research workflow. The TypeScript host keeps the original terminal UI, provider layer, session tree, slash commands, and extension system. The model-facing runtime is centered on a persistent IPython kernel with recursive subagents exposed through a small `rlm` API.+Prime Agent is an RLM-native coding and research harness.++The model-facing runtime is centered on a persistent IPython kernel with recursive subagents exposed through a small `rlm` API. The TypeScript host owns model calls, tools, sessions, scheduling, and child-agent execution while Python provides a durable control environment for composing that functionality.Prime Agent is designed for workflows where the model should work inside a durable Python state, compose tools through code, and delegate independent subtasks to child agents without leaving the same harness.@@ -77,6 +79,8 @@ Authenticate in the TUI with:/login```+Public releases are currently installed from versioned release artifacts through these installer scripts. The repository still contains inherited npm workspace identifiers for source compatibility; they are not the user-facing Prime Agent install path.+## Common Commands```bash@@ -87,3 +91,15 @@ prime-agent doctor [--fix] # Inspect or repair background servicesprime-agent update [--force] # Update Prime Agentprime-agent shutdown [--force] # Stop every agent, worker, and background service```++## Documentation++- [Documentation index](packages/coding-agent/docs/index.md)+- [Quickstart](packages/coding-agent/docs/quickstart.md)+- [Usage and CLI reference](packages/coding-agent/docs/usage.md)+- [Provider setup](packages/coding-agent/docs/providers.md)+- [Development](packages/coding-agent/docs/development.md)++## Upstream and License++Prime Agent is licensed under the MIT License. The root [LICENSE](LICENSE) preserves attribution for pi-mono by Mario Zechner and identifies Prime Intellect's subsequent work.diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.mdindex 5cc5d9925b..0f016a6d4a 100644--- a/packages/coding-agent/README.md+++ b/packages/coding-agent/README.md@@ -10,10 +10,10 @@<h1 align="center">Prime Agent CLI</h1><p align="center">- Terminal coding harness.+ RLM-native terminal coding and research harness.</p>-This workspace still keeps an inherited source package name internally. The distributed release package and command are branded as `prime-agent`.+Prime Agent began as a hard fork of [pi-mono](https://github.com/badlogic/pi-mono), but it is now developed and distributed independently. This workspace retains inherited `@earendil-works/pi-*` source package identifiers, the `pi` package manifest key, and a source-package `pi` bin entry for internal compatibility. Public releases are currently versioned tarball artifacts installed by the scripts below; release packaging rewrites the application package and command to `prime-agent`. Do not use the inherited npm package as the Prime Agent install path.## Table of Contents@@ -177,9 +177,9 @@ See `/hotkeys` for the full list. Customize via `~/.prime/agent/keybindings.json| Key | Action ||-----|--------|-| Ctrl+C | Clear editor |-| Ctrl+C twice | Quit |-| Escape | Cancel/abort |+| Ctrl+C | Interrupt active work, or show the exit hint when idle |+| Ctrl+C twice | Exit while the exit hint is visible |+| Escape | Clear the input without interrupting active work || Escape twice | Open `/tree` || Ctrl+L | Open model selector || Ctrl+P / Shift+Ctrl+P | Cycle scoped models forward/backward |@@ -192,7 +192,8 @@ Submit messages while the agent is 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 only after the agent finishes all work-- **Escape** aborts and restores queued messages to editor+- **Ctrl+C** interrupts active work and restores queued messages to the editor+- **Escape** clears the input without interrupting active work- **Alt+Up** retrieves queued messages back to editorOn Windows Terminal, `Alt+Enter` is fullscreen by default. Remap it in [docs/terminal-setup.md](docs/terminal-setup.md) so Prime Agent can receive the follow-up shortcut.@@ -205,7 +206,7 @@ Sessions are stored as JSONL files with a tree structure. Each entry has an `id`### Management-Sessions auto-save to `~/.prime/agent/sessions/` organized by working directory.+Sessions auto-save as flat JSONL files under `~/.prime/agent/sessions/`. Each session header records its working directory, which the session picker uses for project-scoped views.```bashprime-agent -c # Continue most recent session@@ -335,7 +336,7 @@ Credentials are stored once in `~/.prime/agent/auth.json` (under `mcp:<name>`);**Add your own server.** Declare it under `mcpServers` in settings, then ship a tiny Python skill package that subclasses `McpIntegration`:```jsonc-// ~/.prime/settings.json+// ~/.prime/agent/settings.json{"mcpServers": {"acme": { "type": "http", "url": "https://mcp.acme.com/mcp", "oauth": true }@@ -379,7 +380,7 @@ The default export can also be `async`. Prime Agent waits for async extension fa**What's possible:**- Custom tools (or replace built-in tools entirely)-- Sub-agents and plan mode+- Additional orchestration workflows and plan modes- Custom compaction and summarization- Permission gates and path protection- Custom editors and UI components@@ -651,7 +652,8 @@ prime-agent --thinking high "Solve this complex problem"| Variable | Description ||----------|-------------|| `PRIME_AGENT_CODING_AGENT_DIR` | Override config directory (default: `~/.prime/agent`) |-| `PRIME_AGENT_CODING_AGENT_SESSION_DIR` | Override session storage directory (overridden by `--session-dir`) |+| `PRIME_AGENT_SESSION_DIR` | Override session storage directory (overridden by `--session-dir`) |+| `PRIME_AGENT_CODING_AGENT_SESSION_DIR` | Legacy alias for `PRIME_AGENT_SESSION_DIR` || `PI_PACKAGE_DIR` | Override package directory (useful for Nix/Guix where store paths tokenize poorly) || `PI_OFFLINE` | Disable startup network operations, including update checks and package update checks || `PI_SKIP_VERSION_CHECK` | Skip the Prime Agent version update check at startup. This prevents the release manifest request |@@ -663,6 +665,8 @@ prime-agent --thinking high "Solve this complex problem"| `PRIME_AGENT_KERNEL_PYTHON` | Use an existing Python environment with `ipykernel` instead of auto-bootstrapping `~/.prime/agent/kernel-venv` || `VISUAL`, `EDITOR` | External editor for Ctrl+G |+The remaining `PI_*` variables in this table are compatibility names still read by the current runtime. They do not change the application name, command, or default `~/.prime/agent` configuration path.+## Contributing & DevelopmentSee [docs/development.md](docs/development.md) for setup and debugging.diff --git a/packages/coding-agent/docs/agent-connection-readme.md b/packages/coding-agent/docs/agent-connection-readme.mdindex b377e4f177..b2959eccab 100644--- a/packages/coding-agent/docs/agent-connection-readme.md+++ b/packages/coding-agent/docs/agent-connection-readme.md@@ -1,1196 +1,166 @@-# AgentConnection Architecture README+# AgentConnection Architecture-This document explains the PR #79 interactive-mode decoupling work. It is intentionally detailed because this is a boundary-setting change: the goal is not to build the hosted gateway yet, but to make sure the TUI no longer owns agent execution and can evolve toward daemon and gateway transports without another large TUI rewrite.+`AgentConnection` is the client-side boundary between an interactive user interface and the process that owns agent execution. It lets the terminal UI remain transport-agnostic while normal local sessions run in daemon workers.-## Short Version--Interactive mode used to be both the UI and the execution owner. It received an `AgentSessionRuntime`, reached into `AgentSession`, subscribed to session events directly, read session/model/settings state directly, and called methods such as `prompt()`, `steer()`, `followUp()`, `abort()`, `newSession()`, `switchSession()`, and `fork()` on runtime/session objects.--PR #79 changes that shape. `InteractiveMode` now consumes an injected `AgentConnection` for execution-facing behavior. Normal local interactive startup creates or reuses the local daemon, asks that daemon to own the runtime, attaches a `DaemonAgentConnection`, and gives that connection to the TUI.--The intended local path is now:--```text-TUI -> DaemonAgentConnection -> local daemon socket -> daemon -> AgentSessionRuntime -> AgentSession-```--The future hosted path should be able to become:--```text-web/TUI client -> GatewayAgentConnection -> realtime gateway -> sandbox daemon -> AgentSessionRuntime -> AgentSession-```--The important distinction is this:--```text-AgentConnection is the client-side interaction boundary.-It is not the final remote wire protocol.-```--That means PR #79 moves ownership boundaries and call sites. It does not need to solve sequence numbers, replay, command lifecycle envelopes, artifact handles, hosted auth, or gateway control-plane design.--## Design Goals--The decoupling has five concrete goals.--1. `InteractiveMode` must not own or construct `AgentSessionRuntime`.-2. `InteractiveMode` must not call `AgentSession` methods for execution.-3. `InteractiveMode` must consume execution state, events, and commands through `AgentConnection`.-4. Local-only behavior must be isolated behind adapter and service surfaces, not mixed into the generic connection contract.-5. The current connection types must be honest about what is transitional and what is intended as a stable client boundary.--The result should let local daemon-backed interactive mode preserve user-visible behavior while giving future gateway work a clear adapter target.--## Non-Goals--PR #79 deliberately does not build the remote gateway.--It also deliberately does not solve:--- event sequence numbers-- replay from last seen event-- command lifecycle phases beyond request/response-- stable remote DTOs for every transcript/event shape-- hosted artifact handles-- hosted auth or model setup control plane-- multi-client conflict resolution-- web-specific rendering-- network reconnection semantics-- remote file upload/download APIs--Those are follow-up protocol and product design tasks. The merge bar for PR #79 is that the TUI no longer owns agent execution and that the boundary is clean enough to evolve.--## Why This Was Necessary--The old interactive mode had a simple local shape:+The normal interactive path is:```text-InteractiveMode -> AgentSessionRuntime -> AgentSession+InteractiveMode+ -> AgentConnection+ -> DaemonAgentConnection+ -> local daemon protocol+ -> session worker+ -> AgentSessionRuntime+ -> AgentSession```-That was easy to understand but it made the TUI responsible for too much:+Explicit fallback and embedding paths may use `InProcessAgentConnection`, but `InteractiveMode` still talks to the same interface.-- constructing or holding the runtime-- reading session state-- reading messages-- subscribing to in-process session events-- binding local extension UI callbacks-- reading session manager state-- switching and forking sessions-- calling model/queue/compaction/session methods directly+`AgentConnection` is not the daemon wire protocol and is not a hosted gateway protocol. It expresses client intent in TypeScript. Each transport adapter is responsible for framing, versioning, recovery, and translation at its own boundary.-That shape cannot become a hosted architecture without making the UI aware of things it should never see, such as:+## Responsibilities-- runtime objects-- session objects-- `SessionManager`-- local filesystem paths as control objects-- daemon Unix sockets-- in-process event emitters-- JavaScript callback functions from extensions+The connection exposes client operations for:-The hosted architecture needs a client that can say "prompt this session", "render this event", "show this UI request", or "switch model", without knowing whether the owner is an in-process runtime, a local daemon, or a sandbox daemon behind a gateway.+- prompting, steering, follow-up, abort, and idle waiting;+- model, service tier, thinking, transport, and queue settings;+- compaction, retry, refinement, and session navigation;+- session state, transcript, tree, context, statistics, and queues;+- model and resource catalogs;+- saved-session and import/export operations;+- serializable extension UI requests; and+- RLM child snapshots, agent messaging, schedules, and heartbeats.-## Core Concepts+The execution owner remains responsible for provider calls, tools, kernels, queues, compaction, scheduling, persistence, and RLM descendants.-### AgentConnection--`AgentConnection` is the interface `InteractiveMode` uses for execution-facing interaction.--The interface lives in:--```text-packages/coding-agent/src/modes/agent-connection/types.ts-```--It contains methods for:--- subscribing to connection events-- reading session state and messages-- reading slash command metadata-- reading resource snapshots-- reading available models-- reading session stats and context-- reading and clearing queues-- responding to extension UI requests-- prompting, steering, following up, and aborting-- switching model, thinking level, transport, and queue modes-- compacting and aborting compaction-- reloading, creating, switching, forking, and navigating sessions-- import/export-- saved-session rename/delete-- disposing the connection--The important rule is that `AgentConnection` describes what the client wants to do. It does not describe how the runtime performs the work.--### InProcessAgentConnection--`InProcessAgentConnection` is a compatibility adapter for fallback local paths. It wraps an `AgentSessionRuntime` and implements `AgentConnection`.--It lives in:--```text-packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts-```--This adapter is allowed to know about `AgentSessionRuntime` and `AgentSession`, because it is an adapter. `InteractiveMode` is not allowed to know those objects for execution.--This matters because the in-process path still exists for explicit fallbacks:--- startup benchmark-- `--no-session`-- `--help`-- `prime-agent model list`-- other non-interactive modes that are not daemon-backed TUI clients--The adapter preserves local behavior without preserving the old TUI ownership model.+## Implementations### DaemonAgentConnection-`DaemonAgentConnection` implements `AgentConnection` over the local daemon JSONL socket protocol.--It lives in:--```text-packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts-```--It owns:--- `DaemonClient`-- active daemon session id-- socket request/response calls-- daemon outbound event translation-- daemon error rehydration-- daemon detach/dispose behavior--`InteractiveMode` should not import `DaemonAgentConnection`, `DaemonClient`, `defaultDaemonSocketPath`, or daemon protocol types. Startup code composes those objects and injects only `AgentConnection`.--### Daemon Protocol--The local daemon protocol lives in:--```text-packages/coding-agent/src/modes/daemon/daemon-protocol.ts-```--It is a JSONL protocol over a local socket. It is not the final remote gateway protocol.--It currently provides:--- local daemon commands-- local daemon responses-- local daemon outbound events-- local daemon error info-- local daemon saved-session wire rows--The command `id` fields are request/response correlation ids. They are not stable user command ids, not replay cursors, and not command lifecycle ids.--### InteractiveModeUiServices--`InteractiveModeUiServices` groups local UI services that are intentionally not execution ownership.--It lives in:--```text-packages/coding-agent/src/modes/interactive/interactive-mode-services.ts-```--It includes local services such as:--- settings manager-- model registry for local auth/model browsing-- initial cwd fallback-- initial session name fallback-- registered themes--These are local TUI concerns. They are not the agent execution boundary.--Why keep them local? Because the terminal client still owns local preferences, keybindings, local theme registration, and local credential setup flows. A web client or hosted gateway will need a separate settings/auth/control-plane design. That is not part of PR #79.--### InteractiveModeLocalSessionHost--`InteractiveModeLocalSessionHost` is an in-process compatibility hook for local-only extension behavior.--It also lives in:--```text-packages/coding-agent/src/modes/interactive/interactive-mode-services.ts-```--It can expose:--- local extension runner-- local extension binding-- local session manager for legacy shortcut context-- local callback-bearing `newSession`, `fork`, and `switchSession`-- local tool render callbacks-- local system prompt and abort signal for in-process extension contexts--This host is deliberately not part of `AgentConnection`.--Daemon-backed and future gateway-backed `InteractiveMode` instances should run with:--```text-bindLocalSessionExtensions: false-localSessionHost: undefined-```--The reason is that local JavaScript functions, extension callbacks, and renderer functions are not transportable. They can exist in the in-process fallback adapter, but they must not become a generic client protocol dependency.--## Important Files--### Boundary and Adapters--```text-packages/coding-agent/src/modes/agent-connection/types.ts-packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts-packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts-packages/coding-agent/src/modes/agent-connection/snapshot.ts-packages/coding-agent/src/modes/agent-connection/tool-definition.ts-packages/coding-agent/src/modes/agent-connection/index.ts-```--### Interactive Mode--```text-packages/coding-agent/src/modes/interactive/interactive-mode.ts-packages/coding-agent/src/modes/interactive/interactive-mode-services.ts-```--### Daemon--```text-packages/coding-agent/src/modes/daemon/daemon-mode.ts-packages/coding-agent/src/modes/daemon/daemon-client.ts-packages/coding-agent/src/modes/daemon/daemon-protocol.ts-packages/coding-agent/src/modes/daemon/daemon-extension-binding.ts-packages/coding-agent/src/modes/daemon/active-session-state.ts-packages/coding-agent/src/modes/daemon/daemon-session-list.ts-packages/coding-agent/src/modes/daemon/daemon-session-id.ts-packages/coding-agent/src/modes/daemon/daemon-socket.ts-```--### Startup Composition--```text-packages/coding-agent/src/main.ts-```--`main.ts` is allowed to know about daemon sockets, daemon clients, session managers, runtime factories, and in-process fallback construction. It is the composition root. The TUI class should not own those details.--### Tests--```text-packages/coding-agent/test/agent-connection-daemon.test.ts-packages/coding-agent/test/agent-connection-in-process.test.ts-packages/coding-agent/test/interactive-mode-boundary.test.ts-packages/coding-agent/test/main-interactive-routing.test.ts-packages/coding-agent/test/daemon-client.test.ts-packages/coding-agent/test/daemon-extension-binding.test.ts-```--## Startup Flows--### Normal Interactive Startup--For normal interactive startup, the code should choose daemon-backed mode.--The routing helper is:--```text-shouldUseDaemonInteractive()-```--Normal interactive startup does this:--1. Parse CLI args.-2. Prepare local UI services and config.-3. Start or reuse the local daemon.-4. Ask the daemon to create or attach an active session.-5. Wrap that active session with `DaemonAgentConnection`.-6. Create `InteractiveMode` with:--```text-agentConnection: DaemonAgentConnection-uiServices: createInteractiveModeUiServicesFromServices(...)-bindLocalSessionExtensions: false-```--The TUI does not construct a local `AgentSessionRuntime` for the execution session on this path.--### In-Process Fallback Startup--Some flows still intentionally use in-process runtime construction.--Current explicit fallbacks include:--- `PI_STARTUP_BENCHMARK`-- `--no-session`-- `--help`-- `prime-agent model list`--In this path, startup creates the runtime and wraps it:--```text-new InProcessAgentConnection(runtime)-```--It also passes:--```text-localSessionHost: createInteractiveModeLocalSessionHost(runtime)-bindLocalSessionExtensions: true-```--This preserves local extension behavior without making it part of the generic connection contract.--### Rich TUI Attach to Active Daemon Sessions--PR #79 also supports rich TUI attach to existing active daemon sessions.--The user-facing shape is:--```bash-./prime-agent.sh attach <selector>-```--If `<selector>` names a live active daemon session, startup attaches the rich TUI to that active session instead of opening the session file locally.--## Execution Surface--### Prompt--The TUI calls:--```typescript-agentConnection.prompt(message, options)-```--The daemon adapter sends:--```text-prompt-```--to the local daemon.--Important behavior:--- The daemon owns the actual `session.prompt()` call.-- The TUI does not call `AgentSession.prompt()`.-- The daemon can acknowledge prompt preflight before the whole assistant turn completes.-- Stream progress arrives as connection events.--For future gateway work, this means the current `prompt()` promise is a client convenience, not a full command lifecycle contract. A remote protocol should add accepted/running/completed/failed command phases separately.--### Steer and Follow-Up--The TUI calls:--```typescript-agentConnection.steer(message, images)-agentConnection.followUp(message, images)-```--Those map to daemon-owned session queue behavior.--The TUI keeps a local queue snapshot only for rendering. The queue itself belongs to the execution owner.--### Abort--The TUI calls:--```typescript-agentConnection.abort()-```--The daemon or adapter owns the actual abort behavior.--The TUI should not reach for an `AbortSignal` from the live session except through the in-process local-session-host compatibility path used by local extensions.--### Wait For Idle--The TUI calls:--```typescript-agentConnection.waitForIdle()-```--This replaces the old shape where interactive mode could call into `session.agent.waitForIdle()` directly.--### Compaction and Retry--The TUI calls:--```typescript-agentConnection.compact(...)-agentConnection.abortCompaction()-agentConnection.abortRetry()-agentConnection.abortBranchSummary()-```--Compaction status is rendered from connection state and connection events.--### Session Creation, Switching, Forking, and Tree Navigation--The TUI calls:--```typescript-agentConnection.newSession(...)-agentConnection.switchSession(...)-agentConnection.fork(...)-agentConnection.navigateTree(...)-```--If an in-process extension supplies callback-bearing options such as `withSession`, the local-session-host path can still run that callback locally. That is intentionally isolated. Daemon and gateway clients should not receive JavaScript callbacks through `AgentConnection`.--## State Surface--### AgentConnectionState--`AgentConnectionState` is the TUI's live execution-state snapshot.--It includes:--- active session id-- cwd-- model-- thinking level-- available thinking levels-- streaming status-- compaction status-- retry attempt-- queue modes-- session file-- session id-- session name-- session dir-- leaf id-- auto-compaction flag-- message count-- pending message count-- compaction count-- goal state-- scoped models-- active tool names-- context usage--The TUI uses this as its cache for state that used to come directly from `AgentSession`.--### Messages--The TUI calls:--```typescript-agentConnection.getMessages()-```--for full message history when needed, such as debug rendering and initial state rendering.--Current limitation:--- This still returns `AgentMessage[]`.-- That is transitional.-- A future gateway protocol should define stable transcript DTOs.--### Session Context--The TUI calls:--```typescript-agentConnection.getSessionContext()-```--This returns:--- messages-- thinking level-- model reference--Current limitation:--- It still carries `AgentMessage[]`.-- It avoids importing `SessionContext` from `SessionManager`, but it is not yet a final network transcript DTO.--### Session Tree--The TUI calls:--```typescript-agentConnection.getSessionTree()-```--The tree nodes use connection-owned wrapper types. This avoids making tree rendering depend directly on `SessionManager` types.--Current limitation:--- Some entry payloads still contain `AgentMessage`.-- The future gateway should define stable tree entry DTOs if this becomes a network API.--### Session Stats--The TUI calls:--```typescript-agentConnection.getSessionStats()-```--`SessionStats` moved into a focused module:--```text-packages/coding-agent/src/core/session-stats.ts-```--That avoids importing the whole session module for stats.--Current limitation:--- Stats still include local session file information.-- Hosted clients may need a presentation-oriented stats DTO.--## Event Surface--`AgentConnection` emits:--```typescript-type AgentConnectionEvent =- | { type: "session_event"; event: AgentConnectionSessionEvent }- | { type: "session_replaced"; state: AgentConnectionState; messages: AgentMessage[] }- | { type: "extension_ui_request"; request: AgentConnectionExtensionUiRequest }- | { type: "closed"; error?: string };-```--### session_event--This carries streaming and execution updates.--Current behavior:--- It includes core `AgentEvent` shapes.-- It also includes Prime Agent session events such as queue, compaction, retry, child-agent, and goal updates.--Current limitation:--- This is not a final gateway event DTO.-- It has no sequence number.-- It has no replay cursor.-- It has no formal event version.--That is acceptable for PR #79 because the goal is to move the TUI behind a boundary. It must be replaced or wrapped before becoming a remote network protocol.--### session_replaced--This tells the TUI that the underlying execution session changed.--The TUI should respond by:--1. Applying the new connection state.-2. Rebinding local UI services if it has an in-process local host.-3. Refreshing connection catalog data.-4. Re-rendering the current session state.--The TUI should not manually rewire `AgentSession` event subscriptions. The adapter owns that.--### extension_ui_request--Daemon-owned extensions can request client UI.--The request shape is:--```typescript-interface AgentConnectionExtensionUiRequest {- id: string;- method: string;- payload: Record<string, unknown>;-}-```--The TUI validates the payload at the boundary and responds with:--```typescript-type AgentConnectionExtensionUiResponse =- | { value: string }- | { confirmed: boolean }- | { cancelled: true };-```--Supported methods include:--- `select`-- `confirm`-- `input`-- `editor`-- `notify`-- `setStatus`-- `setWorkingMessage`-- `setWorkingVisible`-- `setWorkingIndicator`-- `setHiddenThinkingLabel`-- `setWidget`-- `setTitle`-- `setEditorText`--Current limitation:--- The method names and payload schemas are loose.-- There is no formal client capability negotiation.-- There is no multi-client ownership model.--That is acceptable for local daemon-backed TUI work. Hosted clients should formalize this before relying on it broadly.--### closed--The connection can report closure with an optional error string.--Current limitation:--- There is no reconnect policy in `AgentConnection`.-- There is no replay support.-- There is no structured close code taxonomy.--Those belong in later gateway work.--## Resource and Command Surface--### Slash Commands--The TUI calls:--```typescript-agentConnection.getCommands()-```--This returns `AgentConnectionSlashCommand[]`, including:--- name-- registered name-- description-- argument hint-- source-- source info--Sources include:--- extension-- prompt-- skill--The TUI uses this data for autocomplete and routing.--Important distinction:--- Command metadata is transportable.-- Local argument completion callbacks are not.--In-process mode can still attach local extension argument completers through `InteractiveModeLocalSessionHost`. Daemon-backed and future gateway-backed clients should not receive executable completion callbacks through `AgentConnection`.--### Resource Snapshot--The TUI calls:--```typescript-agentConnection.getResourceSnapshot()-```--The snapshot can include:--- context files-- skills-- prompts-- extensions-- themes-- diagnostics--The goal is to show daemon-owned loaded resources without having the TUI inspect the daemon runtime.--Current limitation:--- Some resource metadata includes local paths.-- Hosted clients may need package ids, resource ids, or sandbox-relative labels instead of raw paths.--### Tool Definitions--The TUI calls:--```typescript-agentConnection.getToolDefinition(name)-```--The returned `AgentConnectionToolDefinition` is metadata only:--- name-- label-- description-- prompt snippet-- prompt guidelines-- parameters-- render shell hint--It intentionally excludes:--- `execute`-- `prepareArguments`-- `renderCall`-- `renderResult`--Why? Because those are functions. They cannot be sent through a daemon or gateway protocol safely.--In-process local extensions can still provide renderer callbacks through:--```text-InteractiveModeLocalSessionHost.getToolRendererDefinition()-```--That keeps local custom rendering local.--## Model and Settings Surface--### Model Availability--The TUI asks the connection for session-relevant model candidates:--```typescript-agentConnection.getAvailableModels()-```--This matters because the execution owner determines what models are actually available for a session.--The TUI still uses local model registry and settings services for:--- provider setup-- login/logout-- local credential warnings-- persisted default model settings-- provider display-- local `models.json` errors--That split is intentional for PR #79.--### Model Switching--The TUI changes the active execution model through:--```typescript-agentConnection.setModel(provider, modelId)-agentConnection.cycleModel(direction)-agentConnection.setScopedModels(scopedModels)-```--The TUI should only persist local default model settings after the connection accepts the execution change.--### Thinking Level--The TUI changes thinking level through:--```typescript-agentConnection.setThinkingLevel(level)-agentConnection.cycleThinkingLevel()-```--Thinking level state comes from connection state and events.--### Settings--Settings are not part of `AgentConnection`.--That is intentional. Settings currently remain local TUI state. Future hosted clients need a separate control-plane design for account settings, model setup, credentials, and user preferences.--## Session Registry and File-Like Operations--The TUI uses `AgentConnection` for saved-session operations:--```typescript-agentConnection.listSavedSessions(scope)-agentConnection.renameSavedSession(sessionPath, name)-agentConnection.deleteSavedSession(sessionPath)-```--It also uses:--```typescript-agentConnection.importFromJsonl(inputPath, cwdOverride)-agentConnection.exportToHtml(outputPath)-agentConnection.exportToJsonl(outputPath)-```--This keeps current local behavior working through daemon-backed interactive mode.--Current limitation:--- These APIs are path-based.-- Saved-session rows contain `Date` objects.-- Exports return file paths.--That is not remote-safe. It is accepted in PR #79 because local TUI behavior currently needs it and the goal is not to build hosted artifact semantics yet.--Rule for future work:--```text-Do not add new generic AgentConnection features that require local paths, Date objects, or local filesystem semantics.-```--Gateway work should introduce:--- opaque session ids-- artifact ids-- download handles-- upload handles-- string timestamps-- sandbox-relative display paths when needed--## Subagent Runtime Model--The daemon owns primary and subagent runtimes.--Relevant files:--```text-packages/coding-agent/src/modes/daemon/daemon-mode.ts-packages/coding-agent/src/modes/daemon/daemon-session-list.ts-packages/coding-agent/src/core/agent-session-runtime.ts-```--Daemon session summaries can include:--- runtime kind-- parent active session id-- parent session id-- parent session path-- RLM child id-- RLM parent node id--The TUI also receives RLM child-agent snapshot events through `AgentConnectionSessionEvent`.--Current limitation:--- The protocol does not yet formalize `sandboxId`, `primaryRuntimeId`, or a stable runtime graph.-- The daemon can hold multiple active sessions.-- The hosted target of "one primary agent per sandbox plus daemon-owned subagent runtimes" is represented operationally, but not yet as a stable gateway identity model.--That identity model belongs in a follow-up protocol PR.--## What Is Local By Design--The following are local UI concerns in PR #79:--- terminal rendering-- keyboard input-- keybindings-- local settings manager-- local theme registration-- local model registry browsing-- local credential setup and login/logout UI-- local package update checks-- local clipboard behavior-- local path autocomplete-- local changelog display-- local TUI smoke tooling--These can be used by the terminal client without violating the execution boundary.--The key test is:--```text-Does this local thing control agent execution, or is it local UI chrome?-```--If it controls agent execution, it should go through `AgentConnection`.--If it is local UI chrome, it can remain in `InteractiveModeUiServices` or another local UI service.--## What Must Not Leak Into InteractiveMode Execution--`InteractiveMode` should not depend on:--- `AgentSessionRuntime`-- `AgentSession`-- `SessionManager`-- `DaemonClient`-- `defaultDaemonSocketPath`-- daemon protocol command types-- in-process event emitters-- executable tool callbacks through `AgentConnection`-- extension runner callbacks through `AgentConnection`-- local daemon socket paths-- local filesystem-backed session internals for execution--The regression test `interactive-mode-boundary.test.ts` checks the most important import-level version of this rule.--## Transitional Types--The current `AgentConnection` type surface still uses some core package types:--- `AgentEvent`-- `AgentMessage`-- `Model`-- `ImageContent`-- `TextContent`-- `UserMessage`-- `AssistantMessage`-- `Usage`-- `ThinkingLevel`-- `Transport`-- `CompactionResult`-- `GoalState`-- `SessionStats`-- `DeleteSessionFileResult`--Not all of these are equally risky.+`DaemonAgentConnection` is the standard local interactive adapter. It owns a `DaemonClient`, an active-session ID, the latest snapshot, the last event cursor, streamed snapshot assembly, and reconnect behavior.-Plain data types such as model metadata, image content, usage, and thinking levels are structurally close to wire DTOs today, but they are still imported package types rather than versioned protocol types.--The highest-risk transitional types are:--- `AgentEvent`-- `AgentMessage`-- saved-session `Date` fields-- local session paths-- arbitrary tool args/results-- custom message payloads--Why keep them for PR #79?--Because replacing every transcript, event, renderer, and session tree shape in the same PR would be a much larger and riskier migration. PR #79 moves the architectural boundary first. A follow-up can replace the DTOs once the TUI is already consuming a boundary.--The important rule is:--```text-Do not call the current AgentConnection type surface the final remote protocol.-```--## Error Handling--The local daemon has structured recoverable errors for some interactive recovery flows.--Examples:--- missing session cwd-- missing import file--Those are rehydrated by `DaemonAgentConnection` so existing interactive recovery flows still work.--Current limitation:--- Most errors are still strings.-- There is no complete error code taxonomy.-- There is no transport-level retry/reconnect model.--That is acceptable for PR #79. Hosted work should define structured error codes and retryability semantics.--## Testing Strategy--The tests are focused on preserving current behavior while enforcing the new boundary.--### Boundary Test--```text-packages/coding-agent/test/interactive-mode-boundary.test.ts-```--This verifies:--- `interactive-mode.ts` does not import core runtime/session/session-manager modules.-- `interactive-mode.ts` does not import daemon transports.-- `interactive-mode.ts` does not import concrete connection adapters.-- generic connection types do not import core runtime/session/session-manager modules.-- generic connection types document the transitional protocol distinction.--This is not a full architecture proof. It is a practical guardrail against the easiest regression.--### Daemon Connection Adapter Tests+On attach it advertises supported capabilities and receives a coherent session snapshot. Large transcripts are transferred as begin/chunk/end records. Live events carry generation-aware cursors:```text-packages/coding-agent/test/agent-connection-daemon.test.ts+{ generation, sequence }```-These verify daemon adapter behavior such as:+The adapter rejects duplicate or retired-generation events. After a transient socket loss it reconnects with the same client identity and last cursor, reattaches, and emits a resynchronized snapshot. If incremental replay is unavailable, the session snapshot is the source of truth.-- loading connection state through daemon commands-- forwarding session replacement snapshots-- forwarding session events only for the attached active session-- forwarding extension UI requests and responses-- queue commands-- resource snapshots-- session context-- session tree-- tool metadata-- saved-session list/rename/delete-- recoverable error rehydration-- owning-client disposal+Current implementation:-### In-Process Adapter Tests+- `src/modes/agent-connection/daemon-agent-connection.ts`+- `src/modes/daemon/daemon-client.ts`+- `src/modes/daemon/daemon-protocol.ts`-```text-packages/coding-agent/test/agent-connection-in-process.test.ts-```--These verify:--- tool metadata strips executable callbacks-- session context comes through the connection boundary-- replacement snapshots are emitted-- old session listeners are unsubscribed-- new session listeners are subscribed-- runtime callbacks are cleared during dispose--### Startup Routing Tests--```text-packages/coding-agent/test/main-interactive-routing.test.ts-```--These verify:--- normal interactive startup uses daemon-backed mode-- explicit fallback paths remain in-process-- `prime-agent attach` resolves active agents through the rich TUI path--### Daemon Extension Binding Tests--```text-packages/coding-agent/test/daemon-extension-binding.test.ts-```--These verify daemon-side extension binding and replacement behavior.--## How To Test Manually--### Normal Daemon-Backed TUI--Run:--```bash-./prime-agent.sh-```--Expected behavior:--- the TUI opens normally-- a local daemon is started or reused-- interactive mode is backed by `DaemonAgentConnection`-- user-visible behavior should match normal interactive use+### InProcessAgentConnection-### Active Agent List+`InProcessAgentConnection` wraps an `AgentSessionRuntime` for SDK compatibility and explicit local fallbacks. It may access runtime and session objects because it is an adapter; the UI may not.-Run:+In-process startup can also provide `InteractiveModeLocalSessionHost` for local callback-bearing extension behavior. JavaScript functions and render callbacks never cross the generic connection boundary.-```bash-./prime-agent.sh list-```+Current implementation:-### Rich TUI Attach+- `src/modes/agent-connection/in-process-agent-connection.ts`+- `src/modes/interactive/interactive-mode-services.ts`-Start or find an active daemon session id, then run:+## State, Events, and Snapshots-```bash-./prime-agent.sh attach <active-session-id>-```+`AgentConnectionState` is the UI's cached view of execution state. It includes the active session, model and thinking configuration, stream and compaction status, queue modes, session identity, goals, tools, and context usage.-Expected behavior:+An initial or replacement snapshot combines:-- rich TUI opens-- it attaches to the existing active daemon session-- it does not create a new local in-process runtime for the TUI+- connection state;+- transcript messages;+- session context;+- the last event sequence and cursor;+- active RLM child snapshots; and+- an in-progress assistant message when one exists.-## Common Misunderstandings+Connection events cover session events, replacement and resynchronization snapshots, extension UI requests, connection status, and terminal closure. The adapter updates its cache before notifying the UI.-### "Does AgentConnection mean the remote protocol is done?"+Some connection types still reuse internal `AgentMessage`, `AgentEvent`, and model types. Those are local TypeScript contracts, not promises of a stable public network schema.-No.+## Reconnect and Replay-`AgentConnection` is the client-side interaction boundary. The remote protocol still needs its own envelopes, versions, replay model, command lifecycle, artifact handles, auth/control-plane story, and stable DTOs.+The local protocol already implements the recovery mechanisms that the original boundary design left for later work:-### "Why keep in-process mode at all?"+1. Commands use a stable client ID and command ID.+2. Mutations are journaled by `clientId + commandId`.+3. Events carry a cursor with a worker generation and monotonic sequence.+4. Attach accepts a resume cursor.+5. Reconnect retries supervisor recovery for a bounded interval.+6. Attach returns replay status and a coherent snapshot, streamed in chunks when necessary.+7. The UI receives `session_resynced` after recovery.-Because some paths are explicit local fallbacks or non-daemon modes. The goal is not to delete local execution immediately. The goal is to stop the TUI from owning execution directly.+Generation changes matter: a sequence number is only meaningful inside its generation. A client must not compare bare sequence values across worker generations.-### "Why are there still local paths in AgentConnection?"+The protocol does not promise that every historical event remains replayable. Durable session state and a fresh snapshot are the recovery baseline; replay is an optimization for the interval the server can still cover.-Because current local session management and import/export behavior are path-based. PR #79 preserves behavior. The important guardrail is that future generic connection features should not deepen the path dependency.+## Command Lifecycle and Idempotency-### "Why are AgentEvent and AgentMessage still used?"+The public daemon protocol is JSONL-framed and currently at protocol v4. Commands may be sent in versioned envelopes containing protocol metadata, client ID, and command ID.-Because rewriting the entire transcript/event renderer would make this PR much larger. They are documented as transitional. The follow-up DTO PR should replace or wrap them after the boundary is in place.+Mutating commands are recorded before dispatch. A repeated completed command returns its recorded result. A command known to have been received but lacking a durable result is reported as uncertain instead of being replayed blindly. Clients acknowledge durable results so old journal entries can be compacted.-### "Does daemon-backed TUI still support extension UI?"+The `AgentConnection` method promise is a client convenience. It should not be treated as a general accepted/running/completed remote workflow API.-Yes, for daemon-originated extension UI requests that can be represented as serializable method/payload messages.+## Session Replacement-Local callback-bearing extension hooks remain in the in-process local-session-host path only.+New, switch, fork, import, and tree-navigation operations may replace the runtime behind an active connection. The adapter owns rebinding and emits a replacement snapshot. The UI applies the new state and transcript; it does not rewire `AgentSession` listeners directly.-### "Why remove live bash shortcut support?"+When switching to a session already owned by another resident worker, a non-owned client can reattach to that active session. Client-owned headless workers do not silently transfer ownership.-The migration intentionally does not expand the boundary for bash-specific session operations. Historical bash messages still render, but new live shell work should go through IPython for this architecture slice.+## Extension UI Boundary-## Review Checklist+Daemon-owned extensions can request serializable UI operations such as select, confirm, input, editor, notification, status, widget, title, and editor-text updates. The client validates the payload and returns a serializable response.-Use this checklist when reviewing future changes near interactive mode.+Executable callbacks are deliberately excluded:-### InteractiveMode+- tool `execute`, argument preparation, and custom renderer functions;+- extension runner callbacks;+- local completion functions; and+- session-manager or runtime objects.-- Does `interactive-mode.ts` avoid importing `AgentSessionRuntime`?-- Does it avoid importing `AgentSession`?-- Does it avoid importing `SessionManager`?-- Does it avoid importing daemon sockets or daemon clients?-- Does it receive execution behavior through `AgentConnection`?-- Are local-only hooks guarded by `bindLocalSessionExtensions` or local UI services?+Those stay inside the process that loaded the extension. Local extensions are trusted code and run with the user's process permissions.-### AgentConnection+## Local UI Services-- Does a new method describe client intent instead of runtime internals?-- Does it avoid executable callbacks?-- Does it avoid exposing daemon socket details?-- Does it avoid exposing `SessionManager` objects?-- Does it avoid adding new local path dependencies?-- If it reuses core DTOs, is that clearly transitional?+Terminal rendering, keyboard handling, keybindings, themes, clipboard access, local credential setup, and persisted UI preferences are client concerns. They belong in `InteractiveModeUiServices` or another client service, not in the execution protocol.-### Daemon Adapter+The decision rule is simple: if an action changes agent execution or persisted session state, it goes through `AgentConnection`. If it changes only terminal presentation or local preference UI, it stays client-side.-- Does daemon-specific transport logic stay inside `DaemonAgentConnection` or daemon modules?-- Are daemon errors translated before reaching TUI recovery flows?-- Are only events for the attached active session forwarded?-- Does dispose detach cleanly?+## Local-Only Data-### In-Process Adapter+Several operations intentionally preserve local filesystem semantics, including saved-session paths and import/export paths. Do not extend these shapes into a remote API. A hosted transport should use opaque session and artifact IDs, string timestamps, and explicit upload/download handles.-- Is runtime/session access contained inside the adapter?-- Are executable tool callbacks stripped from connection-facing metadata?-- Are session replacement listeners correctly rebound?-- Are old subscriptions cleaned up?+## Boundary Invariants-### Docs and Tests+`InteractiveMode` must not depend on:-- Does new behavior have a focused regression test?-- Does the boundary test still pass?-- Is any transitional surface documented rather than implied?-- Are local-only behaviors called out as local-only?+- `AgentSessionRuntime` or `AgentSession`;+- `SessionManager`;+- daemon socket paths, clients, or command types;+- in-process execution event emitters; or+- executable runtime callbacks delivered through `AgentConnection`.-## Follow-Up Work+Startup code is the composition root and may know about concrete adapters, daemon startup, local settings, and fallback runtime construction.-The next protocol-focused PRs should address:+## Testing-1. Stable network DTOs for messages, events, session entries, stats, resources, and errors.-2. A versioned gateway envelope.-3. Event sequence numbers.-4. Replay from last seen event.-5. Snapshot plus cursor semantics.-6. Command ids that survive reconnect.-7. Command accepted/running/completed/failed phases.-8. Structured error codes and retryability.-9. Artifact handles for import/export/files/images.-10. Hosted auth and model setup control plane.-11. Stable sandbox and runtime identity, such as `sandboxId`, `primaryRuntimeId`, and `parentRuntimeId`.-12. Client capability negotiation for extension UI.-13. Pagination or range loading for large session histories.-14. Multi-client ownership and conflict semantics.+Focused tests enforce the boundary and recovery behavior:-These follow-ups should not require another broad TUI refactor if PR #79 keeps the current boundary clean.+- `test/interactive-mode-boundary.test.ts`+- `test/agent-connection-daemon.test.ts`+- `test/agent-connection-in-process.test.ts`+- `test/daemon-client.test.ts`+- `test/daemon-protocol.test.ts`+- `test/main-interactive-routing.test.ts`-## The Most Important Rule+When changing the connection or wire surface, classify the change as backward-compatible, capability-gated, or incompatible. Update protocol/schema metadata and both old-client/new-daemon and new-client/old-daemon coverage for every wire change.-The TUI can be rich, local, and terminal-specific.+## Relationship to Hosted Execution-The TUI cannot be the execution owner.+The local boundary is suitable for another adapter, but it does not define a hosted control plane. A hosted system still needs explicit authentication, authorization, sandbox identity, artifact transfer, stable public DTOs, multi-client ownership, and network-level compatibility policy.-If a change requires the TUI to know about `AgentSessionRuntime`, `AgentSession`, `SessionManager`, daemon sockets, local event emitters, or executable runtime callbacks, it probably belongs in an adapter, daemon module, or future control-plane service instead.+The durable architectural rule is narrower and already enforced: the UI can be rich and client-specific, but it cannot own agent execution.diff --git a/packages/coding-agent/docs/compaction.md b/packages/coding-agent/docs/compaction.mdindex 4cd91b29fb..11f2837cfe 100644--- a/packages/coding-agent/docs/compaction.md+++ b/packages/coding-agent/docs/compaction.md@@ -1,19 +1,19 @@# 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.+LLMs have limited context windows. When conversations grow too long, Prime Agent 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+**Source files:**+- [`compaction.ts`](../src/core/compaction/compaction.ts) - Auto-compaction logic+- [`branch-summarization.ts`](../src/core/compaction/branch-summarization.ts) - Branch summarization+- [`utils.ts`](../src/core/compaction/utils.ts) - Shared utilities (file tracking, serialization)+- [`session-manager.ts`](../src/core/session-manager.ts) - Entry types (`CompactionEntry`, `BranchSummaryEntry`)+- [`extensions/types.ts`](../src/core/extensions/types.ts) - Extension event typesFor TypeScript definitions in your project, inspect `node_modules/@earendil-works/pi-coding-agent/dist/`.## Overview-Pi has two summarization mechanisms:+Prime Agent has two summarization mechanisms:| Mechanism | Trigger | Purpose ||-----------|---------|---------|@@ -32,13 +32,13 @@ Auto-compaction triggers when:contextTokens > contextWindow - reserveTokens```-By default, `reserveTokens` is 16384 tokens (configurable in `~/.pi/agent/settings.json` or `<project-dir>/.pi/settings.json`). This leaves room for the LLM's response.+By default, `reserveTokens` is 16384 tokens (configurable in `~/.prime/agent/settings.json` or `<project-dir>/.prime/agent/settings.json`). This leaves room for the LLM's response.You can also trigger manually with `/compact [instructions]`, where optional instructions focus the summary — for example `/compact focus on the auth refactor, remember the exact migration command`. The instructions are passed to the summarization prompt with high priority, persisted on the `CompactionEntry`, and shown on the `[compaction]` message in the TUI.### 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 `<project-dir>/.pi/settings.json`) is reached+1. **Find cut point**: Walk backwards from newest message, accumulating token estimates until `keepRecentTokens` (default 20k, configurable in `~/.prime/agent/settings.json` or `<project-dir>/.prime/agent/settings.json`) is reached2. **Extract messages**: Collect messages from the previous kept boundary (or session start) up to the cut point3. **Generate summary**: Call LLM to summarize with structured format, passing the previous summary as iterative context when present4. **Append entry**: Save `CompactionEntry` with summary and `firstKeptEntryId`@@ -76,7 +76,7 @@ What the LLM sees: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.+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. Prime Agent 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@@ -102,7 +102,7 @@ Split turn (one huge turn exceeds budget):turnPrefixMessages = [usr, ass, tool, ass, tool, tool]```-For split turns, pi generates two summaries and merges them:+For split turns, Prime Agent generates two summaries and merges them:1. **History summary**: Previous context (if any)2. **Turn prefix summary**: The early part of the split turn@@ -118,7 +118,7 @@ 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):+Defined in [`session-manager.ts`](../src/core/session-manager.ts):```typescriptinterface CompactionEntry<T = unknown> {@@ -143,13 +143,13 @@ interface CompactionDetails {Extensions can store any JSON-serializable data in `details`. The default compaction tracks file operations, but custom extension implementations can use their own structure.-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.+See [`prepareCompaction()` and `compact()`](../src/core/compaction/compaction.ts) for the implementation.## 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.+When you use `/tree` to navigate to a different branch, Prime Agent offers to summarize the work you're leaving. This injects context from the left branch into the new branch.### How It Works@@ -178,7 +178,7 @@ After navigation with summary:### Cumulative File Tracking-Both compaction and branch summarization track files cumulatively. When generating a summary, pi extracts file operations from:+Both compaction and branch summarization track files cumulatively. When generating a summary, Prime Agent extracts file operations from:- Tool calls in the messages being summarized- Previous compaction or branch summary `details` (if any)@@ -186,7 +186,7 @@ This means file tracking accumulates across multiple compactions or nested branc### BranchSummaryEntry Structure-Defined in [`session-manager.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/session-manager.ts):+Defined in [`session-manager.ts`](../src/core/session-manager.ts):```typescriptinterface BranchSummaryEntry<T = unknown> {@@ -209,7 +209,7 @@ interface BranchSummaryDetails {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.+See [`collectEntriesForBranchSummary()`, `prepareBranchEntries()`, and `generateBranchSummary()`](../src/core/compaction/branch-summarization.ts) for the implementation.## Summary Format@@ -253,7 +253,7 @@ 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):+Before summarization, messages are serialized to text via [`serializeConversation()`](../src/core/compaction/utils.ts):```[User]: What they said@@ -269,7 +269,7 @@ Tool results are truncated to 2000 characters during serialization. Content beyo## 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.+Extensions can intercept and customize both compaction and branch summarization. See [`extensions/types.ts`](../src/core/extensions/types.ts) for event type definitions.### session_before_compact@@ -374,7 +374,7 @@ See `SessionBeforeTreeEvent` and `TreePreparation` in the types file.## Settings-Configure compaction in `~/.pi/agent/settings.json` or `<project-dir>/.pi/settings.json`:+Configure compaction in `~/.prime/agent/settings.json` or `<project-dir>/.prime/agent/settings.json`:```json{diff --git a/packages/coding-agent/docs/custom-provider.md b/packages/coding-agent/docs/custom-provider.mdindex a21e92eeff..920c6c341b 100644--- a/packages/coding-agent/docs/custom-provider.md+++ b/packages/coding-agent/docs/custom-provider.md@@ -59,7 +59,7 @@ export default function (pi: ExtensionAPI) {}```-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 `prime-agent model list`.+The extension factory can also be `async`. For dynamic model discovery, fetch and register models in the factory instead of `session_start`. Prime Agent waits for the factory before startup continues, so the provider is available during interactive startup and to `prime-agent model list`.## Override Existing Provider@@ -208,7 +208,7 @@ models: [{id: "custom-model",// ...reasoning: true,- thinkingLevelMap: { // map pi levels to provider values; null hides unsupported levels+ thinkingLevelMap: { // map Prime Agent levels to provider values; null hides unsupported levelsminimal: null,low: null,medium: null,@@ -330,7 +330,7 @@ interface OAuthLoginCallbacks {### OAuthCredentials-Credentials are persisted in `~/.pi/agent/auth.json`:+Credentials are persisted in `~/.prime/agent/auth.json`:```typescriptinterface OAuthCredentials {@@ -345,12 +345,12 @@ interface OAuthCredentials {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+- [anthropic.ts](../../ai/src/providers/anthropic.ts) - Anthropic Messages API+- [mistral.ts](../../ai/src/providers/mistral.ts) - Mistral Conversations API+- [openai-completions.ts](../../ai/src/providers/openai-completions.ts) - OpenAI Chat Completions+- [openai-responses.ts](../../ai/src/providers/openai-responses.ts) - OpenAI Responses API+- [google.ts](../../ai/src/providers/google.ts) - Google Generative AI+- [amazon-bedrock.ts](../../ai/src/providers/amazon-bedrock.ts) - AWS Bedrock### Stream Pattern@@ -522,7 +522,7 @@ pi.registerProvider("my-provider", {## 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 your provider against the same test suites used by built-in providers. Copy and adapt the test files in [`packages/ai/test/`](../../ai/test/):| Test | Purpose ||------|---------|@@ -602,7 +602,7 @@ interface ProviderModelConfig {/** Whether the model supports extended thinking. */reasoning: boolean;- /** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */+ /** Maps Prime Agent thinking levels to provider/model-specific values; null marks a level unsupported. */thinkingLevelMap?: Partial<Record<"off" | "minimal" | "low" | "medium" | "high" | "xhigh", string | null>>;/** Supported input types. */diff --git a/packages/coding-agent/docs/daemon-implementation-summary.md b/packages/coding-agent/docs/daemon-implementation-summary.mdindex 2581dab70c..84b2d4dc2a 100644--- a/packages/coding-agent/docs/daemon-implementation-summary.md+++ b/packages/coding-agent/docs/daemon-implementation-summary.md@@ -1,6 +1,6 @@# Daemon and Session Worker Architecture-Prime Agent isolates each persistent root session tree in its own process. Process isolation is internal: interactive, print, JSON, RPC, piped-stdin, and `--no-session` invocations keep their existing commands and public I/O contracts.+Prime Agent isolates each active root session tree in its own process. The daemon is internal infrastructure: interactive, print, JSON, RPC, piped-stdin, and `--no-session` describe client behavior and retain their public I/O contracts.## Process Topology@@ -15,87 +15,87 @@ interactive / print / JSON / RPC clients`- client-owned worker: hidden root + RLM descendants + kernels```-The supervisor owns public sockets, client attachments, routing, global agent-message routing, worker health, and update coordination. Each resident worker owns scheduling and execution for its root tree. The supervisor does not execute providers, tools, compaction, bash, kernels, session schedules, or session-history scans.+The supervisor owns public sockets, client attachments, routing, global agent-message delivery, worker health, command journals, and coordinated updates. It does not execute providers, tools, compaction, bash, kernels, schedules, or transcript scans.-Each worker owns one root `AgentSessionRuntime` and every RLM descendant below it. New, switch, fork, and import operations replace the root runtime inside that worker while preserving the root active-session ID.+The catalog subprocess owns saved-session scans and inactive-session file operations. A catalog failure can fail a catalog request without interrupting active workers.-The catalog subprocess owns saved-session scans and inactive-session file operations. A catalog failure can make a catalog request fail, but cannot interrupt active workers.+Each worker owns one root `AgentSessionRuntime`, its root `AgentSession`, scheduler, kernels, and every RLM descendant below that root. New, switch, fork, and import operations replace the root runtime inside the worker while preserving the public active-session ID.## Resident WorkersNormal interactive sessions use resident workers:-- The supervisor dynamically starts one detached process group per root tree.+- The supervisor starts one detached process group per active root tree.- Closing the TUI detaches the client; it does not stop the worker.-- Worker descriptors, authentication tokens, active-session IDs, session paths, and recovery journals are stored with mode `0600` below the agent directory.+- Worker descriptors, authentication tokens, active-session IDs, session paths, and recovery journals are written with owner-only permissions under the agent directory.- Workers monitor the public supervisor socket. If it disappears, one worker acquires an atomic launch lease and starts a replacement supervisor.-- A replacement supervisor adopts the existing worker PIDs and active-session IDs.-- A worker crash affects only its root tree. Recovery retries after 250 ms, 1 second, and 5 seconds; three failed attempts mark that root failed.-- The agents view can retry a failed root through the internal supervisor protocol.-- Supervisor replacement adopts workers automatically.-- `prime-agent shutdown` stops every worker and supervisor; `--force` also sends `SIGKILL` to unresponsive workers and their tracked child processes.+- A replacement supervisor adopts live workers and their active-session IDs.+- A worker crash affects one root tree. Recovery retries after 250 ms, 1 second, and 5 seconds; three failures mark that root failed.+- `prime-agent shutdown` stops the supervisor and all workers; `--force` also terminates unresponsive worker process groups and tracked children.-There are no session, worker, client, or workload caps in this layer.+There is no fixed session, worker, client, or workload cap in this layer.## Client-Owned Workers-Headless and ephemeral clients use the same supervisor, worker process, `AgentSessionRuntime`, extension binding, scheduler, RLM host, and kernel lifecycle as interactive clients. Their workers have a client-owned lifecycle:+Headless and ephemeral clients use the same worker runtime as interactive clients but give the worker a client-owned lifecycle:-- `prime-agent -p`, piped stdin, and JSON mode remain one-shot clients and return their existing output and exit status.-- RPC retains strict LF-delimited JSONL framing, accepts repeated prompts until EOF, and preserves every public command, response, event, and extension-UI shape.-- Interactive `--no-session` uses a client-owned in-memory session.-- Normal completion or RPC EOF explicitly removes the worker without archiving its session. `SIGTERM` and `SIGHUP` retain their existing exit codes.-- Unexpected client loss starts a bounded cleanup grace period. Reconnection with the same stable protocol client ID cancels cleanup and reattaches to the same worker.-- The supervisor can recover a crashed client-owned worker while the owner remains connected. After supervisor replacement, the owner resupplies its launch environment before a dead worker is restarted.-- Default session listings, the agents view, global peer routing, and global schedule aggregation omit client-owned workers. Owner-scoped heartbeat and cron operations still reach the hidden worker.-- The full launch environment is held only in supervisor memory and is never written to the worker descriptor.-- Direct SDK calls to `runPrintMode(runtime, ...)` and `runRpcMode(runtime)` remain in-process and source-compatible. Non-serializable extension factories therefore continue to work for embedders.+- print, piped stdin, and JSON mode remain one-shot;+- RPC keeps LF-delimited JSONL framing and accepts prompts until EOF;+- interactive `--no-session` uses an in-memory session;+- normal completion explicitly removes the worker without archiving it;+- unexpected client loss starts a bounded cleanup grace period;+- reconnect with the same stable client identity cancels cleanup; and+- default lists, global schedules, and peer routing omit client-owned workers unless the owner explicitly addresses them.-The daemon is infrastructure, not a client mode. `interactive`, `print`, `json`, and `rpc` describe client behavior; the retained `--mode daemon` command is the compatible internal process entrypoint used to start the supervisor and session workers.+The full launch environment remains in supervisor memory and is not written to the worker descriptor. Direct SDK calls to print and RPC modes remain in-process so embedders can pass non-serializable extension factories.-## Session Ownership+## Session Ownership and Leases-Persisted sessions use process-safe leases keyed by canonical JSONL path. Resident and client-owned workers both acquire leases.+Every persisted session is protected by a process-safe lease keyed by canonical JSONL path.-- Workers acquire a target lease before opening an existing session and acquire the replacement lease before switching runtimes.-- The previous lease is released only after replacement succeeds.+- A worker acquires a target lease before opening a session.+- Runtime replacement acquires the new lease before releasing the old one.- Concurrent opens return `session_already_active` with the owning active-session ID.-- Concurrent daemon creates for the same path share one worker launch.+- Concurrent creates for the same path converge on one worker launch.-This prevents a script and resident daemon worker from writing the same session concurrently.+This prevents daemon workers and one-shot clients from writing the same transcript concurrently.-## Scheduled Jobs+## Scheduling-Each worker runs one scheduler for the root and RLM descendant sessions it owns. Schedule state is persisted per session at `session-artifacts/<session-id>/scheduled-jobs.json`; workers never scan or write a shared global cron file.+Each worker runs one scheduler for its root and descendants. Jobs are persisted per session in `session-artifacts/<session-id>/scheduled-jobs.json`; workers do not share a global cron file.-- Creating or changing a heartbeat writes its session store and wakes the same worker's scheduler.-- Due ticks are claimed and advanced durably before prompt delivery, so a crash never replays an uncertain prompt.-- The timer loop dispatches different target sessions independently and does not wait for complete model or tool turns before scheduling its next pass.-- A still-active claim coalesces later missed ticks instead of accumulating a backlog.-- Supervisor replacement does not pause timers or scheduled work because resident workers remain alive.-- Worker recovery marks uncertain claims interrupted, preserves the advanced schedule, and resumes only future ticks.-- The supervisor routes cron commands to workers and merges their job summaries for global listing.+Due ticks are claimed and advanced before prompt delivery. A crash therefore does not replay an uncertain prompt. Different target sessions dispatch independently, and a still-active claim coalesces later missed ticks instead of building an unbounded backlog.-The first worker-owned release migrates the legacy global `cron-jobs.json` into the corresponding session artifact directories before adopting workers. Archived, deleted, or descriptorless sessions are cancelled rather than revived.+Resident workers keep scheduling across supervisor replacement. Worker recovery marks uncertain claims interrupted, keeps the advanced schedule, and resumes future ticks only. The supervisor routes schedule commands and merges worker summaries for global listing.-## Public Protocol v3+## Public Daemon Protocol v4-The public daemon socket remains JSONL-framed. Versions 2 and 3 add:+The public local socket is JSONL-framed. The current protocol provides:-- stable command envelopes carrying protocol version, client ID, and command ID;+- versioned command envelopes with stable client and command IDs;+- capability negotiation and per-command compatibility metadata;- generation-aware event cursors `{ generation, sequence }`;-- worker states `starting`, `ready`, `recovering`, and `failed` in session summaries;-- reconnectable clients that retain their stable identity and cursor;-- attach acknowledgement followed by `session_snapshot_begin`, `session_snapshot_chunk`, and `session_snapshot_end`;-- 512 KiB target transcript chunks;-- file-backed transcript caches above 4 MiB.-- client-owned worker creation, completion, and promotion;-- owner-scoped recovery with in-memory launch environments;-- daemon-side headless completion, session-header, synchronous bash, and retry-setting commands.+- reconnect with a stable identity and resume cursor;+- attach acknowledgment plus coherent snapshots;+- begin/chunk/end snapshot streaming with a 512 KiB target chunk size;+- file-backed transcript caches above 4 MiB;+- resident and client-owned worker lifecycle commands;+- daemon-side headless completion, session-header, bash, and retry operations; and+- structured errors for recoverable cases such as an already-active session or uncertain mutation result.-The one-release v1 update handoff uses raw v1 requests only to prepare and stop the old daemon. Busy older daemons that cannot produce a recovery manifest are left running.+Protocol version and schema revision are independent. A compatible addition can be capability-gated or require a schema revision; an incompatible wire change requires a protocol bump.-JSON mode and RPC never expose daemon greetings, envelopes, lifecycle messages, snapshot records, or connection metadata.+Protocol v1 is retained only for the one-release update handoff that prepares and stops an older daemon. A busy older daemon that cannot produce a recovery manifest is left running.++JSON and RPC client modes do not expose daemon greetings, envelopes, snapshot records, lifecycle events, or connection metadata.++## Reconnect, Replay, and Snapshots++Every sequenced event belongs to a worker generation. Clients retain the last `{ generation, sequence }` cursor and present it on attach. The server reports whether the requested interval is complete, partial, or unavailable.++A generation change invalidates comparison with the old sequence. Missing replay is not fatal: the attach snapshot is the durable recovery baseline. `DaemonAgentConnection` applies the snapshot, ignores duplicate or retired-generation events, and reports a resynchronized session to the UI.++Large snapshots are encoded in the worker and streamed as opaque chunks through a bounded supervisor cache. The supervisor never constructs a history-sized object.## Private Worker Transport@@ -108,46 +108,47 @@ small JSON routing headeropaque payload bytes```-Workers serialize an outbound public event once. The supervisor reads the routing header and writes the same payload buffer to every eligible client.+Workers serialize a public event once. The supervisor reads only the routing header and forwards the same payload buffer to eligible clients.-Assistant streaming uses compact start/delta/end payloads on the private channel. The supervisor reconstructs the existing full public `message_update` once per delta. A growing assistant message is therefore not serialized or transferred in full for every token.+Assistant streaming uses compact start/delta/end payloads privately. The supervisor reconstructs the existing public `message_update` once per delta, so the full growing assistant message is not repeatedly transferred from worker to supervisor.-Transcript snapshots are encoded in the worker, not the supervisor. The worker streams opaque chunks to a bounded supervisor cache. The supervisor forwards chunks while they arrive and never parses a history-sized JSON object.+Private worker connections authenticate with per-worker tokens and are fenced to the current supervisor generation. This prevents an obsolete replacement supervisor from continuing to command an adopted worker. It is process coordination, not a sandbox boundary: all processes still run as the same OS user.## BackpressureBackpressure is attachment-local:-- A blocked client stops receiving incremental events.-- Other clients and workers continue normally.-- The supervisor retains no unbounded per-client event queue.-- On drain, that attachment receives a cursor catch-up or a new chunked snapshot.-- Finalized transcript caching is separate from live partial-message reconstruction.+- a blocked client stops receiving incremental events;+- other clients and workers continue;+- the supervisor retains no unbounded per-client queue; and+- after drain, the attachment catches up from its cursor or receives a fresh snapshot.++Final transcript caching is separate from live partial-message reconstruction.-## Recovery and Idempotency+## Idempotency and Crash RecoveryMutating commands are keyed by `clientId + commandId` and recorded before dispatch in an append-only journal.-- A repeated completed command returns its stored result.-- A received command with no durable result is reported as uncertain and is not replayed.-- Read and mutation envelopes survive transient supervisor reconnects with the same command ID.-- Clients durably acknowledge completed mutations, allowing acknowledged journal entries to be compacted away.+- Repeating a completed command returns the stored result.+- A received command without a durable result is reported as uncertain and is not replayed.+- Reconnect retains the same command ID.+- Clients acknowledge completed mutations so journal entries can be compacted.-Workers journal operation transitions and detached subprocess identities. After a crash, the supervisor reaps the old process group plus tracked detached bash trees, appends a visible recovery marker to the persisted transcript, restores the root under the same active-session ID, and holds uncertain side effects rather than replaying them.+Workers journal operation transitions and detached subprocess identities. After a worker crash, recovery reaps its old process group and tracked detached bash trees, appends a visible recovery marker to the transcript, restores the root under the same active-session ID, and does not replay uncertain side effects.## Coordinated UpdatesUpdate preparation is two-phase:-1. Every resident worker creates a non-destructive checkpoint in parallel.+1. Resident workers create non-destructive checkpoints in parallel.2. The supervisor validates and atomically persists the aggregate manifest.-3. Only after all prepares and validation succeed does it commit and stop workers.+3. Only after every prepare succeeds does it commit and stop workers.-If any prepare or manifest validation fails, prepared workers are released and all roots keep running.+If preparation or manifest validation fails, prepared workers are released and all roots continue running.-## Performance Benchmark+## Benchmarks-Run from `packages/coding-agent`:+From `packages/coding-agent`:```shnpx tsx test/daemon-multiclient-bench.ts@@ -157,4 +158,4 @@ npx tsx test/daemon-multiclient-bench.ts --session-file /path/to/session.jsonlPRIME_AGENT_STRESS_WORKERS=50 npx tsx ../../node_modules/vitest/dist/cli.js --run test/daemon-supervisor-process.test.ts -t "hosts resident roots"```-The benchmark reports legacy and v2 fanout/attach paths side by side, including serialization count, elapsed time, throughput, and sampled RSS growth. The process stress case starts the requested number of resident roots, gives every root a simultaneous heartbeat while its own session is busy, and verifies that all schedules advance independently.+The benchmark compares fanout and attach paths, including serialization count, throughput, elapsed time, and sampled RSS. The stress case starts many resident roots and verifies that their schedules advance independently while sessions are busy.diff --git a/packages/coding-agent/docs/development.md b/packages/coding-agent/docs/development.mdindex 5d4340fc61..56aa1a74a4 100644--- a/packages/coding-agent/docs/development.md+++ b/packages/coding-agent/docs/development.md@@ -1,9 +1,11 @@# Development-See [AGENTS.md](../../../AGENTS.md) for additional guidelines.+See the repository [AGENTS.md](../../../AGENTS.md) for the current contribution rules and required validation.## Setup+Prime Agent requires Node.js 22.8.0 or newer.+```bashgit clone https://github.com/PrimeIntellect-ai/prime-agentcd prime-agent@@ -16,44 +18,66 @@ Run from source:/path/to/prime-agent/prime-agent.sh```-The script can be run from any directory. Prime Agent keeps the caller's current working directory.+The script can be called from any directory and preserves the caller's working directory. Use that behavior to run a source checkout against a separate test project.++## Product and Source Names++Prime Agent is the product, public CLI, release artifact, and repository name. The monorepo still retains inherited `@earendil-works/pi-*` npm workspace names, a source-package `pi` bin entry, the `pi` package manifest key, and some `PI_*` compatibility environment variables. These names are source and compatibility details, not a signal that contributors should install or develop against pi-mono.++Public releases are currently versioned tarball artifacts installed by the stable and beta installer scripts. `scripts/pack-prime-agent-release.mjs` rewrites the coding-agent package name, executable, config metadata, and internal dependency URLs for that distribution. Do not document the inherited npm workspace package as the public Prime Agent install path.## Local Configuration-User configuration lives under `~/.prime/agent/`. Project-local settings, prompts, themes, extensions, and skills live under `.prime/agent/` in the project root. Override the user config directory with `PRIME_AGENT_CODING_AGENT_DIR`.+User configuration lives under `~/.prime/agent/`. Project-local settings, prompts, themes, extensions, skills, and system-prompt files live under `.prime/agent/` in the project root. Override the user config directory with `PRIME_AGENT_CODING_AGENT_DIR` and the session directory with `PRIME_AGENT_SESSION_DIR`.++Use an isolated config directory when manually exercising daemon behavior so development sessions do not collide with normal sessions:++```bash+PRIME_AGENT_CODING_AGENT_DIR=/tmp/prime-agent-dev /path/to/prime-agent/prime-agent.sh+```++## Daemon Protocol Changes-## Path Resolution+Classify every daemon command, event, or response-shape change as backward-compatible, capability-gated, or incompatible. Optional behavior must be negotiated and degrade locally. Follow the protocol-version, schema-revision, compatibility-map, and cross-version test requirements in the root `AGENTS.md` before changing the wire contract.-Three execution modes: npm install, standalone binary, tsx from source.+## Package Asset Resolution-**Always use `src/config.ts`** for package assets:+Prime Agent runs from source, Node.js package output, and standalone release artifacts. Always use `src/config.ts` helpers for package assets:```typescriptimport { getPackageDir, getThemeDir } from "./config.js";```-Never use `__dirname` directly for package assets.+Do not resolve packaged assets directly from `__dirname`.-## Debug Command+## Debugging-`/debug` (hidden) writes to `~/.prime/agent/prime-agent-debug.log`:-- Rendered TUI lines with ANSI codes-- Last messages sent to the LLM+The hidden `/debug` command writes `~/.prime/agent/prime-agent-debug.log` with rendered TUI lines, their visible widths, and the current agent messages. Daemon, worker, client, and provider diagnostic logs live under `~/.prime/agent/logs/`.-## Testing+Useful service commands:```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+prime-agent status+prime-agent doctor+prime-agent doctor --fix+prime-agent shutdown```-## Project Structure+## Validation++After code changes, run the repository check from the root:+```bash+npm run check```-packages/- ai/ # LLM provider abstraction- agent/ # Agent loop and message types- tui/ # Terminal UI components- coding-agent/ # CLI and interactive mode++This performs formatting, linting, type checking, installer rendering checks, and the browser smoke check. It does not run the test suite.++Run focused tests from the package root. For example:++```bash+cd packages/coding-agent+npx tsx ../../node_modules/vitest/dist/cli.js --run test/specific.test.ts```++If you create or modify a test file, run that file and iterate until it passes. Coding-agent suite regressions belong under `test/suite/regressions/` and use the suite harness and faux provider rather than live provider credentials.diff --git a/packages/coding-agent/docs/extensions.md b/packages/coding-agent/docs/extensions.mdindex bf482e969d..0ea5626666 100644--- a/packages/coding-agent/docs/extensions.md+++ b/packages/coding-agent/docs/extensions.md@@ -1,10 +1,10 @@-> pi can create extensions. Ask it to build one for your use case.+> Prime Agent 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.+Extensions are TypeScript modules that extend Prime Agent'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`.+> **Placement for /reload:** Put extensions in `~/.prime/agent/extensions/` (global) or `.prime/agent/extensions/` (project-local) for auto-discovery. Use `prime-agent -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()`@@ -54,7 +54,7 @@ See [examples/extensions/](../examples/extensions/) for working implementations.## Quick Start-Create `~/.pi/agent/extensions/my-extension.ts`:+Create `~/.prime/agent/extensions/my-extension.ts`:```typescriptimport type { ExtensionAPI } from "@earendil-works/pi-coding-agent";@@ -102,7 +102,7 @@ export default function (pi: ExtensionAPI) {Test with `--extension` (or `-e`) flag:```bash-pi -e ./my-extension.ts+prime-agent -e ./my-extension.ts```## Extension Locations@@ -113,10 +113,10 @@ Extensions are auto-discovered from:| 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) |+| `~/.prime/agent/extensions/*.ts` | Global (all projects) |+| `~/.prime/agent/extensions/*/index.ts` | Global (subdirectory) |+| `.prime/agent/extensions/*.ts` | Project-local |+| `.prime/agent/extensions/*/index.ts` | Project-local (subdirectory) |Additional paths via `settings.json`:@@ -133,7 +133,7 @@ Additional paths via `settings.json`:}```-To share extensions via npm or git as pi packages, see [packages.md](packages.md).+To share extensions via npm or git as Prime Agent packages, see [packages.md](packages.md).## Available Imports@@ -146,7 +146,7 @@ To share extensions via npm or git as pi packages, see [packages.md](packages.mdnpm 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.+For distributed Prime Agent packages installed with `prime-agent package install` (npm or git), runtime dependencies 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.@@ -177,7 +177,7 @@ export default function (pi: ExtensionAPI) {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.+If the factory returns a `Promise`, Prime Agent 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@@ -221,14 +221,14 @@ This pattern makes the fetched models available during normal startup and to `pr**Single file** - simplest, for small extensions:```-~/.pi/agent/extensions/+~/.prime/agent/extensions/└── my-extension.ts```**Directory with index.ts** - for multi-file extensions:```-~/.pi/agent/extensions/+~/.prime/agent/extensions/└── my-extension/├── index.ts # Entry point (exports default function)├── tools.ts # Helper module@@ -238,7 +238,7 @@ This pattern makes the fetched models available during normal startup and to `pr**Package with dependencies** - for extensions that need npm packages:```-~/.pi/agent/extensions/+~/.prime/agent/extensions/└── my-extension/├── package.json # Declares dependencies and entry points├── package-lock.json@@ -268,7 +268,7 @@ Run `npm install` in the extension directory, then imports from `node_modules/`### Lifecycle Overview```-pi starts+Prime Agent starts│├─► session_start { reason: "startup" }└─► resources_discover { reason: "startup" }@@ -385,7 +385,7 @@ pi.on("session_before_switch", async (event, ctx) => {});```-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`.+After a successful switch or new-session action, Prime Agent 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@@ -402,7 +402,7 @@ pi.on("session_before_fork", async (event, ctx) => {});```-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`.+After a successful fork or clone, Prime Agent 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@@ -496,7 +496,7 @@ pi.on("before_agent_start", async (event, ctx) => {});```-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.+The `systemPromptOptions` field gives extensions access to the same structured data Prime Agent uses to build the system prompt. This lets you inspect what Prime Agent 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.@@ -602,7 +602,7 @@ pi.on("context", async (event, ctx) => {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.+This hook can rewrite provider-level system instructions or remove them entirely. Those payload-level changes are not reflected by `ctx.getSystemPrompt()`, which reports Prime Agent's system prompt string rather than the final serialized provider payload.```typescriptpi.on("before_provider_request", (event, ctx) => {@@ -675,7 +675,7 @@ Use this to update extension UI when `pi.setThinkingLevel()`, model changes, orFired 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.+Before `tool_call` runs, Prime Agent 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`.@@ -786,7 +786,7 @@ pi.on("user_bash", (event, ctx) => {// Option 1: Provide custom operations (e.g., SSH)return { operations: remoteBashOps };- // Option 2: Wrap pi's built-in local bash backend+ // Option 2: Wrap Prime Agent's built-in local bash backendconst local = createLocalBashOperations();return {operations: {@@ -891,7 +891,7 @@ Use this for abort-aware nested work started by extension handlers, for example:- 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.+It is usually `undefined` in idle or non-turn contexts such as session events, extension commands, and shortcuts fired while Prime Agent is idle.```typescriptpi.on("tool_result", async (event, ctx) => {@@ -912,7 +912,7 @@ Control flow helpers.### ctx.shutdown()-Request a graceful shutdown of pi.+Request a graceful shutdown of Prime Agent.- **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).@@ -957,7 +957,7 @@ ctx.compact({### ctx.getSystemPrompt()-Returns Pi's current system prompt string.+Returns Prime Agent'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.@@ -1374,7 +1374,7 @@ Labels persist in the session and survive restarts. Use them to mark important pRegister 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`.+If multiple extensions register the same command name, Prime Agent keeps them all and assigns numeric invocation suffixes in load order, for example `/review:1` and `/review:2`.```typescriptpi.registerCommand("stats", {@@ -1545,7 +1545,7 @@ Register or override a model provider dynamically. Useful for proxies, custom enCalls 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`.-If you need to discover models from a remote endpoint, prefer an async extension factory over deferring the fetch to `session_start`. pi waits for the factory before startup continues, so the registered models are available immediately, including to `prime-agent model list`.+If you need to discover models from a remote endpoint, prefer an async extension factory over deferring the fetch to `session_start`. Prime Agent waits for the factory before startup continues, so the registered models are available immediately, including to `prime-agent model list`.```typescript// Register a new provider with custom models@@ -1775,7 +1775,7 @@ async execute(toolCallId, params) {**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.+**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 Prime Agent 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 }]`.@@ -1828,13 +1828,13 @@ Extensions can override built-in tools (`ipython`, `bash`, `edit`) by registerin```bash# Extension's ipython tool replaces built-in ipython-pi -e ./tool-override.ts+prime-agent -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+prime-agent --no-builtin-tools -e ./my-extension.ts```See [examples/extensions/tool-override.ts](../examples/extensions/tool-override.ts) for a complete override example.@@ -1847,8 +1847,8 @@ See [examples/extensions/tool-override.ts](../examples/extensions/tool-override.Built-in tool implementations:- [ipython.ts](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/tools/ipython.ts) - `IpythonToolDetails`-- [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)+- [bash.ts](../src/core/tools/bash.ts) - `BashToolDetails`+- [edit.ts](../src/core/tools/edit.ts)### Remote Execution@@ -1878,7 +1878,7 @@ pi.registerTool({**Operations interfaces:** `EditOperations`, `BashOperations`-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.+For `user_bash`, extensions can reuse Prime Agent'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:@@ -1968,7 +1968,7 @@ export default function (pi: ExtensionAPI) {### 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.+Tools can provide `renderCall` and `renderResult` for custom TUI display. See [tui.md](tui.md) for the full component API and [tool-execution.ts](../src/modes/interactive/components/tool-execution.ts) for how tool rows are composed.By default, tool output is wrapped in a tool panel: a `label · status` header line (e.g. `my_tool · running`) followed by the slot components, every line indented and drawn on the `toolPanelBg` background so the block reads as one unit. 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.@@ -2217,7 +2217,7 @@ ctx.ui.setFooter((tui, theme) => ({ctx.ui.setFooter(undefined); // Restore built-in footer// Terminal title-ctx.ui.setTitle("pi - my-project");+ctx.ui.setTitle("Prime Agent - my-project");// Editor textctx.ui.setEditorText("Prefill text");diff --git a/packages/coding-agent/docs/index.md b/packages/coding-agent/docs/index.mdindex 776332cabb..50bca1f465 100644--- a/packages/coding-agent/docs/index.md+++ b/packages/coding-agent/docs/index.md@@ -1,35 +1,30 @@-# Pi Documentation+# Prime Agent 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.+Prime Agent is an RLM-native coding and research harness built around a persistent IPython kernel, recursive subagents, durable sessions, and a multi-process local runtime. It began as a hard fork of pi-mono, but Prime Agent is now the product, CLI, install source, and development repository.-## Quick start+## Quick Start-On linux or mac you can install Pi with curl:+Install the latest stable release on Linux or macOS:```bash-curl -fsSL https://pi.dev/install.sh | sh-```--Or alternatively with npm:--```bash-npm install -g @earendil-works/pi-coding-agent+curl -fsSL https://pub-728493de92a943e2a9b2d17b4719f318.r2.dev/install.sh | sh```Then run it in a project directory:```bash-pi+cd /path/to/project+prime-agent```-Authenticate with `/login` for subscription providers, or set an API key such as `ANTHROPIC_API_KEY` before starting pi.+Authenticate with `/login` for subscription or stored API-key providers, or set an environment variable such as `ANTHROPIC_API_KEY` before launch. See the [Quickstart](quickstart.md) for the complete first-run flow.-For the full first-run flow, see [Quickstart](quickstart.md).+Public releases are currently installed from versioned release artifacts. The inherited npm workspace names in the source tree are implementation details, not the public install path.-## Start here+## 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.+- [Using Prime Agent](usage.md) - interactive mode, RLM subagents, slash commands, context files, and CLI reference.- [Providers](providers.md) - subscription and API-key setup for built-in providers.- [Settings](settings.md) - global and project settings.- [Keybindings](keybindings.md) - default shortcuts and custom keybindings.@@ -39,16 +34,17 @@ For the full first-run flow, see [Quickstart](quickstart.md).## Customization- [Extensions](extensions.md) - TypeScript modules for tools, commands, events, and custom UI.-- [Skills](skills.md) - Agent Skills for reusable on-demand capabilities.+- [Skills](skills.md) - Agent Skills and Python packages exposed in the persistent kernel.+- [MCP integrations](mcp-integrations.md) - use MCP servers through Python skills without expanding the model's tool surface.- [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.+- [Prime Agent 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+## Programmatic Usage-- [SDK](sdk.md) - embed pi in Node.js applications.+- [SDK](sdk.md) - embed Prime Agent 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.@@ -56,8 +52,9 @@ For the full first-run flow, see [Quickstart](quickstart.md).## Reference- [Session format](session-format.md) - JSONL session file format, entry types, and SessionManager API.+- [CLI package reference](../README.md) - complete user and CLI reference.-## Platform setup+## Platform Setup- [Windows](windows.md)- [Termux on Android](termux.md)@@ -67,7 +64,7 @@ For the full first-run flow, see [Quickstart](quickstart.md).## Development-- [Development](development.md) - local setup, project structure, and debugging.-- [AgentConnection Architecture](agent-connection-readme.md) - daemon-first interactive mode, connection boundaries, local-only hooks, and gateway follow-up work.-- [Kernel and RLM Recursion](kernel-and-rlm-recursion.md) - ZeroMQ kernel transport and recursive sub-agent execution.-- [/refine verification log](refine-verification-log.md) - manual benchmark checks for continual harness refinement.+- [Development](development.md) - local setup, configuration, debugging, and validation.+- [Daemon and Session Worker Architecture](daemon-implementation-summary.md) - supervisor, catalog, worker, lifecycle, and recovery details.+- [AgentConnection Architecture](agent-connection-readme.md) - client/runtime connection boundary.+- [Kernel and RLM Recursion](kernel-and-rlm-recursion.md) - ZeroMQ kernel transport and recursive subagent execution.diff --git a/packages/coding-agent/docs/json.md b/packages/coding-agent/docs/json.mdindex e9a48cbdeb..a8b22b4754 100644--- a/packages/coding-agent/docs/json.md+++ b/packages/coding-agent/docs/json.md@@ -1,14 +1,14 @@# JSON Event Stream Mode```bash-pi --mode json "Your prompt"+prime-agent --mode json "Your prompt"```-Outputs all session events as JSON lines to stdout. Useful for integrating pi into other tools or custom UIs.+Outputs all session events as JSON lines to stdout. Useful for integrating Prime Agent 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):+Events are defined in [`AgentSessionEvent`](../src/core/agent-session.ts):```typescripttype AgentSessionEvent =@@ -22,7 +22,7 @@ type AgentSessionEvent =`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):+Base events from [`AgentEvent`](../../agent/src/types.ts):```typescripttype AgentEvent =@@ -44,12 +44,12 @@ type AgentEvent =## 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):+Base messages from [`packages/ai/src/types.ts`](../../ai/src/types.ts):- `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):+Extended messages from [`packages/coding-agent/src/core/messages.ts`](../src/core/messages.ts):- `BashExecutionMessage` (line 29)- `CustomMessage` (line 46)- `BranchSummaryMessage` (line 55)@@ -78,5 +78,5 @@ Followed by events as they occur:## Example```bash-pi --mode json "List files" 2>/dev/null | jq -c 'select(.type == "message_end")'+prime-agent --mode json "List files" 2>/dev/null | jq -c 'select(.type == "message_end")'```diff --git a/packages/coding-agent/docs/kernel-and-rlm-recursion.md b/packages/coding-agent/docs/kernel-and-rlm-recursion.mdindex f05e831eaf..15e6510a22 100644--- a/packages/coding-agent/docs/kernel-and-rlm-recursion.md+++ b/packages/coding-agent/docs/kernel-and-rlm-recursion.md@@ -1,226 +1,73 @@# Kernel and RLM Recursion-This document explains the IPython kernel transport and the recursive `rlm` sub-agent bridge.+Prime Agent gives each agent session a persistent IPython kernel and a native recursive sub-agent interface. The Python `rlm` package is a model-facing shim; the TypeScript host owns child execution, persistence, usage accounting, and lifecycle.-The important design constraint is that the Python `rlm` package in the kernel is only a shim. It preserves the model-facing API from `rlm-harness`, but it does not run a child agent loop in Python. Child agents are run by the TypeScript host through the same `AgentSession` machinery as the parent.--The same comm transport doubles as a generic host bridge: kernel-side Python (skills such as the bundled `goal` skill) can call `rlm.host_request("<type>", {...})` and the TypeScript host dispatches the typed request to a registered handler. `rlm.run` is just the first registered request type.--## High-Level Shape+## Architecture```textAgentSession (TypeScript)|- | owns an ipython tool+ | owns the ipython tool and host request handlersvKernelManager (TypeScript)|- | ZeroMQ Jupyter protocol+ | ZeroMQ / Jupyter protocolvIPython kernel process (Python)|- | has prime-agent-runtime installed as module "rlm"+ | prime-agent-runtime installed as module "rlm"vmodel-executed Python code```-When the model calls recursion:+When the model delegates work:```python-result = await rlm.run("subtask")+result = await rlm("inspect the API", name="api-reviewer")print(result.answer)```-the flow becomes:--```text-Python rlm shim- |- | Jupyter comm target "host.request", payload type "rlm.run"- v-KernelManager comm handler- |- | calls parent AgentSession.runRlmChild(prompt)- v-child AgentSession- |- | same TS agent loop, providers, tools, skills, session storage- v-final assistant text- |- | Jupyter comm reply- v-Python RLMResult-```--## Files--```text-packages/coding-agent/src/core/kernel/index.ts- ZeroMQ connection setup, Jupyter wire encoding, execute_request handling,- comm_open / comm_msg handling for the "host.request" bridge, dispatching- typed requests (rlm.run, goal.*) to registered host handlers.--packages/coding-agent/src/core/tools/ipython.ts- Tool wrapper around KernelManager. Starts the kernel and bootstraps the- rlm object into the user namespace.--packages/coding-agent/src/core/agent-session.ts- Parent session owns recursion settings and implements runRlmChild().--packages/coding-agent/src/core/rlm-runtime.ts- TypeScript request/result types for rlm.run, rlm.find_models,- rlm.list_subagents, and rlm.delete_subagent plus their typed host request- handlers.--prime-agent-runtime/src/rlm/__init__.py- Python shim installed into ~/.prime/agent/kernel-venv. Exposes rlm, rlm.run(),- rlm.find_models(), rlm.list_subagents(), rlm.delete_subagent(),- host_request(), RLMResult, RLMModel, RLMSubagent, TokenUsage, and the- session-backed harness state helper.--prime-agent-runtime/src/rlm/harness.py- Session-backed JSON store for reset-free harness refinement notes: prompt- notes, memory entries, reusable skill descriptions, subagent specs, and- refinement events.--packages/coding-agent/skills/goal- Bundled Python skill exposing goal.get / goal.create / goal.complete in the- kernel. A thin wrapper over host_request; all goal state stays in the host.--scripts/setup-kernel-venv.sh- Thin wrapper around the automatic kernel bootstrap.-```--## Continual Harness State+the call travels through a Jupyter comm target named `host.request`. `KernelManager` dispatches request type `rlm.run` to the parent `AgentSession`, which starts a child through the same TypeScript agent machinery as the parent. The final answer and usage return over the comm as an `RLMResult`.-Prime Agent exposes a lightweight continual-harness state store in the kernel:+The same bridge supports other typed host requests. Bundled Python skills such as `goal` call `rlm.host_request("goal.get", ...)`; state and policy remain in the TypeScript host.-```python-import rlm+## Component Ownership-rlm.harness.remember(- "Validation failure",- "The package import only matters when run through the project environment.",- path="repo/testing",-)-rlm.harness.upsert_skill(- "Run native Python import checks",- "Use `uv run python -c ...` or the repo's documented interpreter.",-)-rlm.harness.upsert_subagent(- "Focused reviewer",- "Review the current patch for regressions and missing focused tests.",-)-rlm.harness.record_refinement(- "Repeated import-check confusion",- ["added repo/testing memory", "added native import-check skill"],- evidence="two failed checks were run in the IPython kernel instead of the repo env",-)-print(rlm.harness.overview())-```+| Component | Responsibility |+|---|---|+| `src/core/kernel/index.ts` | ZeroMQ sockets, Jupyter framing, execution, comm dispatch, interrupt, and shutdown. |+| `src/core/tools/ipython.ts` | Agent tool wrapper, lazy kernel provisioning, namespace bootstrap, and output shaping. |+| `src/core/agent-session.ts` | RLM policy, child creation, registry, usage attribution, cancellation, and goal handlers. |+| `src/core/rlm-runtime.ts` | Typed request/result validation for `rlm.run`, model discovery, list, and delete. |+| `prime-agent-runtime/src/rlm/` | Python shim, result types, callable `rlm`, and session-backed harness state. |-The store writes `harness_state.json` in the session-local harness directory by-default (`RLM_HARNESS_STATE_DIR`, falling back to `RLM_SESSION_DIR/harness`), so-learned state stays with the session. Explicitly global edits go to the global-agent harness directory (`RLM_GLOBAL_HARNESS_STATE_DIR`, e.g.-`~/.prime/agent/harness/`), which is shared across sessions. Because the-long-lived kernel and the host `/refine`-command write the same file from separate processes, the kernel-side store-reloads the file whenever its on-disk mtime changes before reading or mutating,-so concurrent host edits are merged rather than clobbered. It is intentionally a-state ledger, not a second execution engine: child-agent execution still uses-`await rlm(...)`, installed Python skills still use the configured skill surface,-and file/code edits still go through the normal Prime Agent tools.--This mirrors the useful, domain-independent part of Continual Harness: the agent-can make small online updates to its prompt notes, memory, skill descriptions,-and subagent specs after observing trajectory evidence, then record the outcome-without resetting the run.--The same state can be updated from the TUI or RPC with `/refine`. The command-runs a dedicated refiner prompt over the current trajectory, existing harness-state, and prior refinement history, then applies JSON Create/Update/Delete-edits to the editable components only:+The Python side does not call providers or implement an agent loop.-```text-/refine-/refine focus on improving validation behavior-/refine rollback refine_20260608142312-```+## Kernel Lifecycle-Rollback uses the before/after snapshots stored for each refinement. Because the-harness state is global, the snapshots are appended to a global-`refinements.jsonl` log in the harness directory (in addition to a-`prime-agent.refinement` custom entry in the originating session), so a-refinement applied in one session can be rolled back from any later session. The-base system prompt remains immutable; `/refine` can only create or update-supplemental prompt notes.--## ZeroMQ Jupyter Kernel Setup--### Connection File--`KernelManager` creates a temporary Jupyter connection file before spawning the kernel.--The file contains local TCP ports and signing settings:--```json-{- "ip": "127.0.0.1",- "transport": "tcp",- "shell_port": 50000,- "iopub_port": 50001,- "stdin_port": 50002,- "control_port": 50003,- "hb_port": 50004,- "signature_scheme": "hmac-sha256",- "key": "...",- "kernel_name": "python3"-}-```+The kernel is created lazily on first IPython use. Python resolution is:-The current implementation picks a random high port range, writes the file under a temp directory, and starts:+1. `PRIME_AGENT_KERNEL_PYTHON`, when it can import `ipykernel`;+2. `~/.prime/agent/kernel-venv/bin/python`, bootstrapped with `uv`; or+3. the XDG data location when `~/.prime` is not writable.-```bash-python -m ipykernel_launcher -f /tmp/prime-agent-kernel-.../connection.json-```+The managed environment includes Python 3.11, `ipykernel`, and `prime-agent-runtime`. A bootstrap marker detects stale environments.-The kernel process inherits:+Startup creates a temporary Jupyter connection file with loopback TCP ports and an HMAC key, starts `python -m ipykernel_launcher`, connects shell, IOPub, and control sockets, waits for subscription propagation, and probes readiness with `kernel_info_request`.-- `cwd`: the agent session working directory.-- `env`: the process environment plus kernel-specific overrides such as `RLM_DEPTH`, `RLM_MAX_DEPTH`, and `RLM_SESSION_DIR`.+The manager owns the child process, connection directory, ZeroMQ sockets, and a bounded stderr tail. Shutdown sends `shutdown_request`, closes sockets, terminates the process as a fallback, and removes temporary connection data. Persistent sessions may snapshot the kernel namespace into their session artifact directory for revival.-### Channels Used+## Jupyter Transport-Jupyter defines several channels. Prime Agent currently uses three:+Prime Agent uses three channels:```text-shell channel- request/reply channel for execute_request and kernel_info_request--iopub channel- publish/subscribe channel for stdout, stderr, execute_result, errors,- status changes, and comm_open messages from the kernel--control channel- request/reply channel for interrupt_request, shutdown_request, and rlm- comm replies that must be delivered while execute_request is still active+shell execute_request, execute_reply, kernel_info_request+iopub stdout, stderr, results, errors, status, comm_open+control interrupt, shutdown, and host-request replies during execution```-The code creates:--```text-shell -> ZeroMQ Dealer-iopub -> ZeroMQ Subscriber-control -> ZeroMQ Dealer-```--The Subscriber subscribes to the empty topic, which means it receives all IOPub messages.--### Jupyter Message Encoding--Each Jupyter message is sent as multipart ZeroMQ frames:+Messages use normal Jupyter multipart framing:```text<IDS|MSG>@@ -231,161 +78,32 @@ metadatacontent```-`KernelManager.encode()` serializes the JSON parts and signs them with HMAC-SHA256 using the connection file key. `decode()` finds the `<IDS|MSG>` delimiter and parses the four JSON frames after the signature.--The header includes:--```json-{- "msg_id": "...",- "session": "...",- "username": "prime-agent",- "date": "...",- "msg_type": "execute_request",- "version": "5.3"-}-```--The `msg_id` is important because IOPub is shared. For ordinary execution output, the host only accepts messages whose `parent_header.msg_id` matches the active `execute_request`.--### Kernel Startup--Startup sequence:--```text-KernelManager.start()- |- | ensureKernelPython()- | bootstraps ~/.prime/agent/kernel-venv with uv if needed- v-resolved python with ipykernel and prime-agent-runtime- |- v-makeConnection()- |- | writes connection.json- v-spawn python -m ipykernel_launcher -f connection.json- |- v-connect shell, iopub, control sockets- |- v-subscribe to iopub- |- v-sleep briefly for ZeroMQ slow-joiner behavior- |- v-start persistent iopub pump- |- v-probeReady()- |- | sends kernel_info_request on shell- | waits for kernel_info_reply- v-state = "running"-```--The startup probe catches a common failure mode: the Python process starts but the kernel never binds or responds. If the probe times out, the manager shuts down and includes the kernel stderr tail in the error.--### Executing Code--The ipython tool calls:--```typescript-KernelManager.execute(code, opts)-```--`execute()` serializes calls with `executionQueue`. This matters because the shell channel is a request/reply channel and the IPython kernel user namespace is shared. Two ordinary IPython cells should not execute concurrently in one kernel.--Execution sequence:--```text-execute(code)- |- v-send execute_request on shell- |- v-wait for persistent iopub pump to finish active execution- |- | stream -> stdout / stderr- | execute_result -> final expression repr- | error -> traceback- | status idle -> cell is complete- v-return ExecuteResult-```--The returned shape is:--```typescript-{- stdout: string;- stderr: string;- result?: string;- status: "ok" | "error" | "aborted";- error?: { ename: string; evalue: string; traceback: string[] };- durationMs: number;-}-```--Abort handling sends `interrupt_request` on the control channel. The execute call then marks the result as aborted if the `AbortSignal` fired.--### Kernel Restart And Cleanup--`KernelManager.shutdown()` sends `shutdown_request` on the control channel, waits briefly, closes sockets, kills the child process as a fallback, removes the temp connection directory, and clears `startPromise`.--`KernelManager.restart()` serializes behind any active execute call, shuts down, resets state to idle, clears stderr, and starts again.--Process-wide cleanup is registered through `registerSessionResourceCleanup()`. Kernel managers carry an owner session id, so `cleanupSessionResources(sessionId)` only disposes kernels for that session.--## IPython Tool Bootstrapping--The ipython tool constructs a `KernelManager` lazily on first use. `KernelManager.start()` resolves Python in this order:--```text-PRIME_AGENT_KERNEL_PYTHON, if set and able to import ipykernel-~/.prime/agent/kernel-venv/bin/python, bootstrapped by uv if needed-$XDG_DATA_HOME/prime/agent/kernel-venv/bin/python, only if ~/.prime is not writable-```--The automatic bootstrap installs Python 3.11, `ipykernel`, and `prime-agent-runtime`, then writes `.bootstrap-version` in the venv. Missing or stale markers cause a rebuild.+JSON frames are signed with HMAC-SHA256. Ordinary output is accepted only when `parent_header.msg_id` matches the active execution. Comm messages are handled before that filter because asynchronous Python tasks can open comms after their scheduling cell returns to idle.-After the kernel starts, the tool bootstraps `rlm` into the user namespace:+Calls to `KernelManager.execute()` are serialized. One kernel has one shared namespace and does not run two ordinary IPython cells concurrently. RLM child agents can still run concurrently because each delegation uses a distinct comm and child runtime.-```python-try:- import rlm as _prime_agent_rlm_module- rlm = _prime_agent_rlm_module.rlm-except Exception:- rlm = _PrimeAgentMissingRlm()-```+## Why Replies Use the Control Channel-This puts the callable `rlm` object in the global IPython namespace. The model can use either:+A running cell can await a host request:```pythonawait rlm("subtask")-await rlm.run("subtask")```-Both delegate to the same shim implementation.--If `prime-agent-runtime` is missing from the kernel environment, startup remains non-fatal. The fallback `rlm` object raises a clear `RuntimeError` only when code actually calls `rlm.run(...)` or `rlm(...)`.+IPython processes shell messages serially. Sending the reply on the shell channel would deadlock: the active `execute_request` cannot finish until the reply arrives, while the kernel will not process that shell reply until the request finishes.-## Python RLM Shim+The Python shim therefore registers comm handlers on the control channel, and the host sends replies there. Future completion is scheduled with `loop.call_soon_threadsafe()` because the control handler may run on another thread.-The Python shim lives in `prime-agent-runtime` and installs as import namespace `rlm`.+## Python API-It exports:+`prime-agent-runtime` exports:```pythonrlmrun(prompt: str, **kwargs)find_models(query: str = "", limit: int = 8)list_subagents()+delete_subagent(selector)host_request(request_type: str, payload: dict | None = None)RLMResultRLMModel@@ -393,496 +111,138 @@ RLMSubagentTokenUsage```-`RLMResult` matches the model-visible shape from `rlm-harness`:--```python-result.answer # str-result.usage # TokenUsage-result.turns # int-result.session_dir # pathlib.Path | None-result.model # exact provider/model selector-result.warning # fallback notice to surface to the user, or None-```--The shim also makes the module callable so `import rlm; await rlm("...")` can work, but the ipython tool normally injects the callable object directly as `rlm`.--### Depth Check--Before opening a comm, the shim reads:--```text-RLM_DEPTH-RLM_MAX_DEPTH-```--Default max depth is 1. If `RLM_DEPTH >= RLM_MAX_DEPTH`, it raises:--```text-RLM recursion depth limit reached (RLM_DEPTH=1, RLM_MAX_DEPTH=1)-```--This prevents depth-1 children from spawning grandchildren in v1.--### Comm Open--For an allowed call:+The IPython bootstrap places the callable `rlm` object in the user namespace, so these are equivalent:```python+await rlm("subtask")await rlm.run("subtask")```-the shim:+`RLMResult` contains the final answer, token usage, assistant-turn count, child session directory, exact selected model, and an optional fallback warning.-```text-creates asyncio Future-creates Jupyter Comm target "host.request"-registers on_msg callback-opens the comm with:- {- "type": "rlm.run",- "prompt": "subtask",- "kwargs": {}- }-awaits the Future-```+Supported `rlm.run` options are:-The callback strips the reply's `status` field and converts the payload into `RLMResult`, or raises `RuntimeError` when the host reports an error. The comm-open/await machinery is the public `host_request()`; `run()` is a typed wrapper around it, and other kernel-side skills reuse `host_request()` for their own request types.+- `name`: a unique readable child session name; and+- `model`: an exact `provider/model` selector from `rlm.find_models()`.-The shim accepts `**kwargs` and includes them in the comm payload. The TypeScript host supports `name="..."` for an orchestrator-chosen child session name and `model="provider/model"` for an exact model selection; all other kwargs are rejected with a clear error instead of being ignored. `find_models()` searches a bounded catalog containing only models backed by active, non-expired credentials and returns `provider`, `id`, `name`, and exact `selector` fields.+Unknown options fail instead of being ignored. Model search is bounded to active, non-expired credentials. If an exact selection is unavailable or fails auth preflight, the child falls back to the parent model and returns the actual model plus a warning that the parent must surface.-### Why Control-Channel Comm Replies Exist+## Child Execution-IPython handles shell-channel messages serially. While a cell is running:+`AgentSession.runRlmChild()` performs the following sequence:-```python-await rlm.run("subtask")-```+1. Check `RLM_DEPTH < RLM_MAX_DEPTH`.+2. Resolve the requested model or inherit the parent model.+3. Create a `sub-xxxxxxxx` child directory under the parent artifact directory.+4. Create a child `SessionManager`, `Agent`, and `AgentSession`.+5. Reuse provider hooks, resource loader, model registry, tools, transport, retry settings, and thinking configuration.+6. Start `child.prompt()` and wait for the child to become idle.+7. Return the final assistant text and usage.+8. Attribute child usage to the parent assistant turn and persist the attribution.-the kernel is still inside the active `execute_request` handler. If the TypeScript host replies with a normal shell-channel `comm_msg`, the kernel may not dispatch that message until the current execute request finishes. But the execute request cannot finish because it is awaiting the comm reply.+Children receive incremented `RLM_DEPTH`, the inherited maximum depth, and their own `RLM_SESSION_DIR`. The default maximum depth is 1, so root sessions may create children and those children may not create grandchildren unless the limit is configured higher.-That is a deadlock.+## Parallel and Background Delegation-The shim fixes the kernel side by registering `comm_msg` and `comm_close` handlers on the kernel control channel. The TypeScript host sends recursion replies over the control channel. The control channel can be processed while shell execution is still awaiting.--Because control handlers may wake the Future from a different thread, the shim resolves with:+Normal Python async patterns provide concurrency:```python-loop.call_soon_threadsafe(...)-```--## TypeScript Comm Handling--`KernelManager` starts a persistent IOPub pump when the kernel starts. Comm messages are handled before the active execution `msg_id` filter:--```text-for each iopub message:- if msg_type is comm_open / comm_msg / comm_close:- handleCommMessage(incoming)- continue-- if no active execution:- ignore+import asyncio- if parent_header.msg_id != active execute_request:- ignore+task = asyncio.create_task(rlm("slow independent audit"))- handle stdout / stderr / result / error / idle-```--This matters because `comm_open` messages may not use the active execute request as their parent, and Python `asyncio` tasks can open RLM comms after the scheduling cell has already returned to idle.--The comm handler tracks:--```text-commTargets: comm_id -> target_name-handledHostRequestCommIds: comm ids already started-```--For target `host.request`, it starts work asynchronously and dispatches on the payload `type`:--```text-comm_open target "host.request"- |- v-startHostRequestFromComm(comm_id, data)- |- v-handleHostRequest(data)- |- v-options.hostHandlers[data.type](data)- |- v-sendCommMessage(comm_id, { status: "ok", ...result })-```--The RLM handlers include `rlm.run` for child creation, `rlm.find_models` for bounded authenticated model discovery, and `rlm.list_subagents` for the current parent session's automatic child registry.--Unknown types fail with `host request type "<type>" is not available in this session`.--Errors are returned as:--```json-{- "status": "error",- "error": "message"-}-```--The send path uses `control` if available, then falls back to `shell`.--## Child AgentSession Execution--The root `AgentSession` registers typed handlers into the root kernel:--```typescript-hostHandlers: {- "rlm.run": createRlmRunHostHandler(({ prompt, kwargs }) => this.runRlmChild(prompt, kwargs)),- "goal.get": ..., // only when goals are enabled- "goal.create": ...,- "goal.complete": ...,-}-```--`runRlmChild()` is the TypeScript owner of actual recursion.--Sequence:--```text-runRlmChild(prompt, kwargs)- |- | check current depth < max depth- | resolve an exact optional model selector against authenticated models- | fall back to the parent model with a user-facing warning if unavailable- | otherwise inherit the parent model- v-create child session dir- |- | <parent rlm session dir>/sub-xxxxxxxx- v-create child SessionManager- |- | append selected model change- | append thinking level change- v-create child Agent- |- | copies parent streamFn, convertToLlm, provider hooks,- | transport settings, thinking budgets, retry settings- v-create child AgentSession- |- | own KernelManager- | same tools by name- | same resource loader and model registry- | RLM_DEPTH = parent depth + 1- | RLM_MAX_DEPTH = parent max depth- | RLM_SESSION_DIR = child dir- v-child.prompt(prompt)- |- v-wait for idle- |- v-return final assistant text as answer-```--The child returns:--```typescript-{- answer: string;- usage: {- prompt_tokens: number;- completion_tokens: number;- };- turns: number;- session_dir: string | null;- model: string;- warning?: string;-}-```--Usage is aggregated from assistant message usage:+results = await asyncio.gather(+ rlm("review the API"),+ rlm("review the tests"),+)-```text-prompt_tokens = input + cacheRead + cacheWrite-completion_tokens = output+background_result = await task```-Turns are counted as assistant messages in the child transcript.+The root kernel still executes one cell. Each `rlm` call opens a separate comm, and the host starts an independent child `AgentSession`. Daemon-backed children can be retained as independently addressable session workers.-The answer is the child's final assistant text. This matches the RLM-1 training surface: the model stops calling tools and the final assistant text is the answer.+## Parent-Scoped Sub-Agent Registry-By default, a child inherits the parent's current model. When a user or skill-requests a different model, the orchestrator first searches the bounded-authenticated catalog, chooses a candidate, and passes its exact selector:+The TypeScript parent maintains the authoritative direct-child registry. `await rlm.list_subagents()` returns stable child IDs, active-session IDs when daemon-backed, session IDs, names, directories, and running/completed status.-```python-matches = await rlm.find_models("DeepSeek V4 Flash")-result = await rlm(- "Check the API",- model=matches[0].selector,-)-```+This registry survives kernel restart, compaction, and parent restore. Successfully completed daemon-backed children are rehydrated from the parent artifact registry. Inline children remain inspectable in the current process but have no active-session ID.-`find_models()` returns up to eight matches by default and never more than 20.-Each match exposes `provider`, `id`, `name`, and the exact `provider/model`-`selector`; only models backed by active, non-expired credentials are included.-The full catalog is never injected into the system prompt.+The parent can continue a retained daemon child with agent messaging. `rlm.delete_subagent()` accepts an exact child ID, active-session ID, session ID, or unique name. Deletion cancels or closes the runtime, writes a durable tombstone, and removes the child from messaging and observation. It does not erase the transcript or artifacts on disk.-`rlm.run(model=...)` intentionally accepts only an exact selector. If that-selector is unknown, unauthenticated, expired, unavailable, or fails auth-preflight, the child uses the parent model and the result returns the actual-`.model` plus a `.warning` that the parent must surface to the user. A selected-model is persisted with the child and remains active on later turns; changing-the parent model does not update existing children.+Registry scope follows the parent transcript. An unrelated new parent session does not inherit children.-### Parent-Scoped Subagent Registry+## Usage and Cost Attribution-The host exposes the current parent session's direct children without relying on-Python task handles or a model-maintained file:+`RLMResult.usage` reports the child's own aggregate prompt and completion tokens. Prime Agent also folds the child's assistant usage and cost into the parent assistant turn that launched it.-```python-children = await rlm.list_subagents()-for child in children:- print(- child.rlm_child_id,- child.active_session_id,- child.session_id,- child.session_name,- child.session_dir,- child.status,- )-```+The parent transcript persists a `child_usage_attributed` entry containing:-Entries have status `running` while the initial `rlm()` call is active and-`completed` after a successful call returns. Every child also gets a readable,-collision-resistant default `session_name` derived from its task and child ID,-for example `subagent-check-the-http-api-a1b2c3d4`. The orchestrator can choose-an exact name at spawn time with `await rlm("Check the API", name="api-reviewer")`;-empty, overlong, or already-addressable names are rejected. Users and-orchestrators can rename it later without changing the child ID. Failed or-cancelled children are-removed. Because the registry is owned by the TypeScript parent session, it-remains available after kernel restart, state restore, or compaction even if the-original Python `asyncio.Task` handle was lost.--In daemon mode `active_session_id` identifies the retained child session. The-same parent/orchestrator can continue it directly:+- the target parent assistant message ID;+- the child usage being attributed; and+- the resulting aggregate usage.-```python-children = await rlm.list_subagents()-child = next((item for item in children if item.active_session_id), None)-if child is not None:- await agent_message.send(child.session_name, "Check the latest change.")-```+On reload, the aggregate is reapplied to the parent message. Context-tree reporting subtracts attributed child usage when showing each node's own usage, so tree-wide own usage and root aggregate totals remain reconcilable. Child work increases billable session totals but does not inflate the parent model's context-window measurement.-That message starts an ordinary follow-up turn in the existing child context; it-does not reopen or alter the completed `rlm()` result. Inline and in-process-children have `active_session_id=None`, so they remain inspectable but are not-addressable through daemon agent messaging.--Delete a direct child by passing its registry entry or any exact registry-identifier (`session_name`, `rlm_child_id`, `session_id`, or-`active_session_id`):--```python-child = (await rlm.list_subagents())[0]-deleted = await rlm.delete_subagent(child)-# Equivalent when the child has a chosen name:-# deleted = await rlm.delete_subagent("api-reviewer")-```--Deletion cancels a running child and waits for its runtime to close. A completed-retained child closes immediately. In both cases it is removed from-`rlm.list_subagents()` and, in daemon mode, from agent messaging and observation.-Deletion does not erase the child's session transcript or artifacts on disk.-Only direct children in the current parent registry can be selected; unknown or-ambiguous selectors raise an error. The returned `RLMSubagent` is the deleted-entry's final registry snapshot.--Together these APIs provide the parent-scoped lifecycle operations: create with-`rlm(...)`, read with `rlm.list_subagents()` and `agent_observe`, continue/update-with `agent_message.send(...)`, and delete with `rlm.delete_subagent(...)`.+## Continual Harness State-The registry is scoped to the parent session transcript. Closing or replacing a-daemon runtime cascades cleanup to its resident children; reopening that same-parent session rehydrates its successfully completed children from the-parent's artifact registry so they remain listable, messageable, and deletable.-An unrelated new parent session inherits nothing, and inline children are not-rehydrated. Deletion writes a durable tombstone before it reports success, so a-deleted child stays removed while its transcript and artifacts remain on disk.-There is no task/result migration or general cross-session reopen API.+`rlm.harness` is a persisted state ledger for prompt notes, memories, reusable skill descriptions, sub-agent specifications, and refinement events. It is not a second execution engine.-### Cost Accounting+Session-local state lives in the session artifact directory under `harness/harness_state.json`. Explicitly global entries live under `~/.prime/agent/harness/`. The Python store reloads after external modification so host-side `/refine` writes and kernel writes do not overwrite each other.-`RLMResult.usage` reports the child session's token usage. The parent session's displayed usage and cost do not currently fold child usage into the parent assistant-message totals. Child cost is independent in v1 and should be read from the child result or child session until parent aggregation is added.+`/refine` runs a dedicated review over the current trajectory and applies small create/update/delete edits. Rollback uses recorded before/after snapshots. The base system prompt remains immutable; refinements are supplemental state.-## Goal Skill Over the Host Bridge+## Goal Requests-Goals are not harness tools. The model's only built-in tool is `ipython`; the goal feature is exposed as the bundled Python skill `goal`, which the kernel bootstrap imports into the user namespace like any other Python skill:+The bundled `goal` Python skill is a thin host-bridge client:```pythonawait goal.get()-await goal.create("ship the release notes", token_budget=200000)+await goal.create("ship the release", token_budget=200000)await goal.complete()```-Each call is a thin wrapper over `rlm.host_request("goal.<op>", {...})`. All goal state — status transitions, token/wall-clock accounting, persistence, continuation re-prompting — lives in the TypeScript `AgentSession`:--```text-model runs `await goal.complete()` inside an ipython cell- |- | comm target "host.request", payload { "type": "goal.complete" }- v-KernelManager dispatches to hostHandlers["goal.complete"]- |- v-AgentSession.handleGoalHostRequest("goal.complete")- | flips goal state to complete, marks the run for usage accounting,- | emits goal_update to connected clients- v-comm reply { status: "ok", goal: {...}, completion_budget_report: ... }-```--Replies use snake_case keys (`tokens_used`, `remaining_tokens`, `completion_budget_report`) since they are a Python-facing API.--The re-prompting loop is unchanged and entirely host-side: while a goal is active the session injects `goal_context` continuation messages after each turn, steers a budget-limit context when the token budget is exhausted, and stops continuing once `goal.complete` arrives over the bridge (or the user pauses/clears the goal). Because completion arrives mid-cell rather than as a detectable tool call, the session records that completion was requested during the run so the completing turn's tokens still count toward the goal budget.--When goals are disabled for a session (`includeGoals: false`), the goal skill is filtered out of the kernel and the system prompt, and the `goal.*` handlers are not registered — calls fail with the unknown-type error above.--## Session Directory Layout+Goal state, persistence, token and wall-clock accounting, and continuation prompting live in `AgentSession`. When goals are disabled, the skill and `goal.*` host handlers are not registered.-For a persisted root session:--```text-~/.prime/agent/sessions/<project>/- 2026-..._<root-session-id>.jsonl- 2026-..._<root-session-id>/- sub-dccb69c8/- 2026-..._<child-session-id>.jsonl- sub-.../-```--The root RLM session dir is derived from the root JSONL session file path by removing `.jsonl`. Child directories are named `sub-xxxxxxxx`, matching the `rlm-harness` child directory convention.--Each child kernel sees:--```text-RLM_DEPTH=1-RLM_MAX_DEPTH=1-RLM_SESSION_DIR=<root session dir>/sub-xxxxxxxx-```--With the default max depth, a child attempting another `rlm.run()` fails before opening a comm.--## Parallel Sub-Agents--Python parallelism uses normal asyncio:--```python-results = await asyncio.gather(- rlm("capital of Japan"),- rlm("capital of Brazil"),- rlm("capital of Egypt"),-)-print([r.answer for r in results])-```+## Session Artifacts-The flow is:+For a persisted root session, the relevant layout is:```text-one IPython execute_request- |- v-three Python rlm calls- |- | each opens its own comm_id- v-KernelManager starts three runRlmChild() promises- |- v-three independent child AgentSessions- |- v-three comm replies- |- v-asyncio.gather resolves in the IPython cell+~/.prime/agent/+ sessions/+ <root-session-id>.jsonl+ session-artifacts/+ <root-session-id>/+ kernel-state.dill+ kernel-state.json+ scheduled-jobs.json+ harness/+ harness_state.json+ sub-xxxxxxxx/+ <child-session-id>.jsonl+ sub-yyyyyyyy/```-The root kernel still executes one cell. The concurrency comes from multiple comms and multiple child `AgentSession` instances, each with its own kernel.--## What This Deliberately Does Not Do+Exact artifact files are created only when their features are used. Non-persistent sessions place RLM directories under the OS temporary directory and do not gain revivable session artifacts.-The runtime does not import or subprocess `rlm-harness`.+## Trust Boundary-The Python shim does not:+IPython executes model-generated Python and shell-magics with the worker's OS permissions. The kernel boundary isolates protocol and lifecycle concerns; it is not a security sandbox. Installed Python packages, skills, and extensions are trusted code. Use an external sandbox or restricted execution environment when the workspace or generated code is untrusted.-- create child sessions itself-- call model providers-- run an agent loop-- know about TUI state-- know about skills beyond being importable in the kernel-- do cost tracking--Those stay in TypeScript so children share the parent harness implementation:--- `AgentSession`-- `KernelManager`-- provider registry and auth-- session storage-- cost and usage accounting-- skills loader-- slash-command and extension environment+Provider credentials are resolved by the TypeScript host. The bounded model catalog crosses into Python as metadata; the full auth store does not.## Failure Modes-Common failures and where they surface:--```text-prime-agent-runtime missing from the kernel environment- -> kernel startup succeeds- -> rlm.run raises RuntimeError with rebuild or PRIME_AGENT_KERNEL_PYTHON instructions when called+| Failure | Behavior |+|---|---|+| Managed runtime is missing | Kernel bootstrap rebuilds it; a custom Python without `rlm` fails clearly when recursion is called. |+| Depth limit reached | Python raises before opening a comm; the host checks again. |+| Unsupported options | Host rejects the request. |+| Requested model unavailable | Child uses the parent model and returns a warning. |+| Shell-channel comm reply | Deadlock risk; current replies use control. |+| Child cancellation | Host aborts the child and removes failed/cancelled registry entries. |+| Parent teardown | Active descendants are cancelled and their runtimes are closed. |-RLM_DEPTH >= RLM_MAX_DEPTH- -> Python RuntimeError before comm_open+## Focused Validation-no selected model- -> TS runRlmChild throws, Python receives RuntimeError--unsupported rlm.run kwargs- -> TS runRlmChild throws "Unsupported rlm.run kwargs: ..."--unknown, unauthenticated, expired, or unavailable rlm.run model- -> TS runRlmChild uses the parent model and returns RLMResult.warning--child provider error- -> child agent final error behavior is reflected in its final assistant state--kernel comm reply sent on shell channel- -> deadlock risk while execute_request is awaiting- -> current implementation replies over control channel-```--## Validation Commands--Single child:--```bash-./prime-agent.sh -p 'use the ipython tool to run `print((await rlm.run('"'"'What is the capital of Japan?'"'"')).answer)`'-```--Parallel children:--```bash-./prime-agent.sh -p 'use the ipython tool with asyncio.gather to call rlm.run() three times in parallel for: capital of Japan, capital of Brazil, capital of Egypt. Print only the three answers as a Python list.'-```--Depth cap:--```bash-./prime-agent.sh -p 'use the ipython tool to run `result = await rlm.run("use the ipython tool to execute this exact Python code and print the exception message: try:\n await rlm.run('\''nested'\'')\nexcept Exception as e:\n print(type(e).__name__, str(e))")\nprint(result.answer)`'-```+From the repository root, the implementation is covered by focused kernel, recursion, context-tree, daemon RLM, and runtime tests. When changing child creation or accounting, include `agent-session-recursion.test.ts`; when changing comm transport, include the kernel comm tests; when changing daemon retention, include the daemon RLM lifecycle tests.diff --git a/packages/coding-agent/docs/keybindings.md b/packages/coding-agent/docs/keybindings.mdindex dfbd5347a1..b94b1e1633 100644--- a/packages/coding-agent/docs/keybindings.md+++ b/packages/coding-agent/docs/keybindings.md@@ -1,12 +1,12 @@# Keybindings-All keyboard shortcuts can be customized via `~/.pi/agent/keybindings.json`. Each action can be bound to one or more keys.+All keyboard shortcuts can be customized via `~/.prime/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.+The config file uses the same namespaced keybinding ids that Prime Agent 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.+After editing `keybindings.json`, run `/reload` in Prime Agent to apply the changes without restarting the session.## Key Format@@ -165,7 +165,7 @@ Used inside the scoped models selector (opened via `/scoped-models`).## Custom Configuration-Create `~/.pi/agent/keybindings.json`:+Create `~/.prime/agent/keybindings.json`:```json{@@ -177,7 +177,7 @@ Create `~/.pi/agent/keybindings.json`: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.+On native Windows, `app.suspend` has no default binding because Windows terminals do not support Unix job control. If you bind it manually, Prime Agent shows a status message instead of suspending. In WSL, the normal Linux `ctrl+z`/`fg` behavior still applies.### Emacs Examplediff --git a/packages/coding-agent/docs/models.md b/packages/coding-agent/docs/models.mdindex cb35340ffd..3f6f720194 100644--- a/packages/coding-agent/docs/models.md+++ b/packages/coding-agent/docs/models.md@@ -1,6 +1,6 @@# Custom Models-Add custom providers and models (Ollama, vLLM, LM Studio, proxies) via `~/.pi/agent/models.json`.+Add custom providers and models (Ollama, vLLM, LM Studio, proxies) via `~/.prime/agent/models.json`.## Table of Contents@@ -36,7 +36,7 @@ For local models (Ollama, LM Studio, vLLM), only `id` is required per model:The `apiKey` is required but Ollama ignores it, so any value works.-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.+Some OpenAI-compatible servers do not understand the `developer` role used for reasoning-capable models. For those providers, set `compat.supportsDeveloperRole` to `false` so Prime Agent 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.@@ -159,7 +159,7 @@ The `apiKey` and `headers` fields support three formats:"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.+For `models.json`, shell commands are resolved at request time. Prime Agent intentionally does not apply built-in TTL, stale reuse, or recovery logic for arbitrary commands. Different commands need different caching and failure strategies, and Prime Agent 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.@@ -192,7 +192,7 @@ If your command is slow, expensive, rate-limited, or should keep using a previou| `name` | No | `id` | Human-readable model label. Used for matching (`--model` patterns) and shown in model details/status 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) |+| `thinkingLevelMap` | No | omitted | Maps Prime Agent 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 |@@ -205,7 +205,7 @@ Current behavior:### 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`.+Use `thinkingLevelMap` on a model to describe model-specific thinking controls. Keys are Prime Agent thinking levels: `off`, `minimal`, `low`, `medium`, `high`, `xhigh`.Values are tristate:@@ -317,7 +317,7 @@ Behavior notes:For providers or proxies using `api: "anthropic-messages"`, use `compat.supportsEagerToolInputStreaming` to control Anthropic fine-grained tool streaming 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.+By default Prime Agent sends per-tool `eager_input_streaming: true`. If a proxy or Anthropic-compatible backend rejects that field, set `supportsEagerToolInputStreaming` to `false`. Prime Agent will omit `tools[].eager_input_streaming` and send the legacy `fine-grained-tool-streaming-2025-05-14` beta header for tool-enabled requests instead.```json{diff --git a/packages/coding-agent/docs/packages.md b/packages/coding-agent/docs/packages.mdindex 93bca7f72d..e5fc166b21 100644--- a/packages/coding-agent/docs/packages.md+++ b/packages/coding-agent/docs/packages.md@@ -1,14 +1,14 @@-> pi can help you create pi packages. Ask it to bundle your extensions, skills, prompt templates, or themes.+> Prime Agent can help you create resource packages. Ask it to bundle your extensions, skills, prompt templates, or themes.-# Pi Packages+# Prime Agent 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.+Prime Agent packages bundle extensions, skills, prompt templates, and themes so you can share them through npm or git. For compatibility with the inherited extension ecosystem, a package declares resources in `package.json` under the `pi` key, or uses conventional directories.## Table of Contents- [Install and Manage](#install-and-manage)- [Package Sources](#package-sources)-- [Creating a Pi Package](#creating-a-pi-package)+- [Creating a Prime Agent Package](#creating-a-prime-agent-package)- [Package Structure](#package-structure)- [Dependencies](#dependencies)- [Package Filtering](#package-filtering)@@ -17,7 +17,7 @@ Pi packages bundle extensions, skills, prompt templates, and themes so you can s## 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.+> **Security:** Prime Agent 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.```bashprime-agent package install npm:@foo/[email protected]@@ -34,13 +34,13 @@ prime-agent update # update Prime Agentprime-agent update --force # reinstall Prime Agent even if current```-By default, `package install` and `package remove` write to global settings (`~/.pi/agent/settings.json`). Use `--local` to write to project settings (`.pi/settings.json`) instead. Project settings can be shared with your team, and Prime Agent installs any missing packages automatically on startup.+By default, `package install` and `package remove` write to global settings (`~/.prime/agent/settings.json`). Use `--local` to write to project settings (`.prime/agent/settings.json`) instead. Project settings can be shared with your team, and Prime Agent installs any missing packages automatically on startup.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+prime-agent -e npm:@foo/bar+prime-agent -e git:github.com/user/repo```## Package Sources@@ -56,7 +56,7 @@ npm:pkg- Versioned specs are pinned and skipped by `prime-agent package update`.- Global installs use `npm install -g`.-- Project installs go under `.pi/npm/`.+- Project installs go under `.prime/agent/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:@@ -82,7 +82,7 @@ ssh://[email protected]/user/repo@v1- 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 pin the package and skip `prime-agent package update`.-- Cloned to `~/.pi/agent/git/<host>/<path>` (global) or `.pi/git/<host>/<path>` (project).+- Cloned to `~/.prime/agent/git/<host>/<path>` (global) or `.prime/agent/git/<host>/<path>` (project).- Runs `npm install` after clone or pull if `package.json` exists.**SSH examples:**@@ -104,9 +104,9 @@ prime-agent package install git:[email protected]:user/[email protected]./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.+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, Prime Agent loads resources using package rules.-## Creating a Pi Package+## Creating a Prime Agent PackageAdd a `pi` manifest to `package.json` or use conventional directories. Include the `pi-package` keyword for discoverability.@@ -127,7 +127,7 @@ Paths are relative to the package root. Arrays support glob patterns and `!exclu### Gallery Metadata-The [package gallery](https://pi.dev/packages) displays packages tagged with `pi-package`. Add `video` or `image` fields to show a preview:+The inherited `pi-package` keyword and optional `video` or `image` fields remain available as package metadata:```json{@@ -141,8 +141,8 @@ The [package gallery](https://pi.dev/packages) displays packages tagged with `pi}```-- **video**: MP4 only. On desktop, autoplays on hover. Clicking opens a fullscreen player.-- **image**: PNG, JPEG, GIF, or WebP. Displayed as a static preview.+- **video**: URL for an MP4 preview.+- **image**: URL for a PNG, JPEG, GIF, or WebP preview.If both are set, video takes precedence.@@ -150,7 +150,7 @@ If both are set, video takes precedence.### Convention Directories-If no `pi` manifest is present, pi auto-discovers resources from these directories:+If no `pi` manifest is present, Prime Agent 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@@ -161,9 +161,9 @@ If no `pi` manifest is present, pi auto-discovers resources from these directoriThird 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 Prime Agent 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`.+Prime Agent bundles core packages for extensions and skills. The workspace still publishes these inherited package names; if you import any of them, 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.+Other resource packages must be bundled in your tarball. Add them to `dependencies` and `bundledDependencies`, then reference their resources through `node_modules/` paths. Prime Agent loads packages with separate module roots, so separate installs do not collide or share modules.Example:@@ -210,7 +210,7 @@ Filter what a package loads using the object form in settings:## Enable and Disable Resources-Use `prime-agent config` to enable or disable extensions, skills, prompt templates, and themes from installed packages and local directories. Works for both global (`~/.pi/agent`) and project (`.pi/`) scopes.+Use `prime-agent config` to enable or disable extensions, skills, prompt templates, and themes from installed packages and local directories. This works for both global (`~/.prime/agent`) and project (`.prime/agent/`) scopes.## Scope and Deduplicationdiff --git a/packages/coding-agent/docs/prompt-templates.md b/packages/coding-agent/docs/prompt-templates.mdindex 056d2c9ac2..48f086b283 100644--- a/packages/coding-agent/docs/prompt-templates.md+++ b/packages/coding-agent/docs/prompt-templates.md@@ -1,4 +1,4 @@-> pi can create prompt templates. Ask it to build one for your workflow.+> Prime Agent can create prompt templates. Ask it to build one for your workflow.# Prompt Templates@@ -6,10 +6,10 @@ Prompt templates are Markdown snippets that expand into full prompts. Type `/nam## Locations-Pi loads prompt templates from:+Prime Agent loads prompt templates from:-- Global: `~/.pi/agent/prompts/*.md`-- Project: `.pi/prompts/*.md`+- Global: `~/.prime/agent/prompts/*.md`+- Project: `.prime/agent/prompts/*.md`- Packages: `prompts/` directories or `pi.prompts` entries in `package.json`- Settings: `prompts` array with files or directories- CLI: `--prompt-template <path>` (repeatable)diff --git a/packages/coding-agent/docs/providers.md b/packages/coding-agent/docs/providers.mdindex cab196e912..e013a85405 100644--- a/packages/coding-agent/docs/providers.md+++ b/packages/coding-agent/docs/providers.md@@ -1,6 +1,6 @@# Providers-Pi supports subscription-based providers via OAuth and API key providers via environment variables or auth file. For each provider, pi knows all available models. The list is updated with every pi release.+Prime Agent supports subscription-based providers via OAuth and API key providers via environment variables or the auth file. Its built-in model catalog is updated with each Prime Agent release.## Table of Contents@@ -19,7 +19,7 @@ Use `/login` in interactive mode, then select a provider:- Claude Pro/Max- GitHub Copilot-Use `/logout` to clear credentials. Tokens are stored in `~/.pi/agent/auth.json` and auto-refresh when expired.+Use `/logout` to clear credentials. Tokens are stored in `~/.prime/agent/auth.json` and auto-refresh when expired.### OpenAI Codex@@ -43,7 +43,7 @@ Use `/login` in interactive mode and select a provider to store an API key in `a```bashexport ANTHROPIC_API_KEY=sk-ant-...-pi+prime-agent```| Provider | Environment Variable | `auth.json` key |@@ -75,11 +75,11 @@ pi| 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).+Reference for environment variables and `auth.json` keys: [`env-api-keys.ts`](../../ai/src/env-api-keys.ts).#### Auth File-Store credentials in `~/.pi/agent/auth.json`:+Store credentials in `~/.prime/agent/auth.json`:```json{@@ -160,14 +160,14 @@ export AWS_REGION=us-west-2Also 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+prime-agent --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:```bashexport AWS_BEDROCK_FORCE_CACHE=1-pi --provider amazon-bedrock --model arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123+prime-agent --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:@@ -191,7 +191,7 @@ export AWS_BEDROCK_FORCE_HTTP1=1export CLOUDFLARE_API_KEY=... # or use /loginexport 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"+prime-agent --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`.@@ -205,7 +205,7 @@ AI Gateway authentication uses `CLOUDFLARE_API_KEY` as `cf-aig-authorization`. U| 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.+For normal Prime Agent 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@@ -214,10 +214,10 @@ For normal pi usage, prefer unified billing or stored BYOK. Inline BYOK requires```bashexport CLOUDFLARE_API_KEY=... # or use /loginexport CLOUDFLARE_ACCOUNT_ID=...-pi --provider cloudflare-workers-ai --model "@cf/moonshotai/kimi-k2.6"+prime-agent --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.+Prime Agent automatically sets `x-session-affinity` for [prefix caching](https://developers.cloudflare.com/workers-ai/features/prompt-caching/) discounts.### Google Vertex AIdiff --git a/packages/coding-agent/docs/quickstart.md b/packages/coding-agent/docs/quickstart.mdindex c9a6a58443..c6d6ae5c2d 100644--- a/packages/coding-agent/docs/quickstart.md+++ b/packages/coding-agent/docs/quickstart.md@@ -1,29 +1,48 @@# Quickstart-This page gets you from install to a useful first pi session.+This page gets you from install to a useful first Prime Agent session.## Install-Pi is distributed as an npm package:+Install the latest stable release on Linux or macOS:```bash-npm install -g @earendil-works/pi-coding-agent+curl -fsSL https://pub-728493de92a943e2a9b2d17b4719f318.r2.dev/install.sh | sh```-Then start pi in the project directory you want it to work on:+To try the latest beta built from `main`:++```bash+curl -fsSL https://pub-728493de92a943e2a9b2d17b4719f318.r2.dev/install-beta.sh | sh+```++Both installers fetch versioned Prime Agent release artifacts and install the `prime-agent` command. The inherited npm workspace identifiers in the source tree are not the public install path.++Then start Prime Agent in the project directory you want it to work on:```bashcd /path/to/project-pi+prime-agent+```++To run a source checkout instead, use Node.js 22.8.0 or newer:++```bash+git clone https://github.com/PrimeIntellect-ai/prime-agent+cd prime-agent+npm ci+./prime-agent.sh```+The source runner preserves the directory from which it is invoked, so you can also call `/path/to/prime-agent/prime-agent.sh` from another project.+## Authenticate-Pi can use subscription providers through `/login`, or API-key providers through environment variables or the auth file.+Prime Agent can use subscription providers through `/login`, or API-key providers through environment variables or its auth file.-### Option 1: subscription login+### Option 1: Subscription Login-Start pi and run:+Start Prime Agent and run:```text/login@@ -31,36 +50,46 @@ Start pi and run:Then select a provider. Built-in subscription logins include Claude Pro/Max, ChatGPT Plus/Pro (Codex), and GitHub Copilot.-### Option 2: API key+### Option 2: API Key-Set an API key before launching pi:+Set an API key before launching Prime Agent:```bashexport ANTHROPIC_API_KEY=sk-ant-...-pi+prime-agent```-You can also run `/login` and select an API-key provider to store the key in `~/.pi/agent/auth.json`.+You can also run `/login` and select an API-key provider to store the key in `~/.prime/agent/auth.json`.See [Providers](providers.md) for all supported providers, environment variables, and cloud-provider setup.-## First session+## First Session-Once pi starts, type a request and press Enter:+Once Prime Agent starts, type a request and press Enter:```textSummarize this repository and tell me how to run its checks.```-By default, pi gives the model one tool:+Prime Agent gives the model one built-in tool, `ipython`. The long-lived kernel is a control environment for reading and editing files, running project commands, inspecting data, retaining Python state, and invoking installed skills. The kernel runtime is bootstrapped automatically on first use; set `PRIME_AGENT_KERNEL_PYTHON` to use an existing Python environment with `ipykernel`.++Prime Agent runs in your current working directory and can modify files there. Use git or another checkpointing workflow if you want easy rollback.++## Recursive Subagents-- `ipython` - run Python in a persistent kernel+Recursive subagents are a built-in Prime Agent capability. The model can delegate independent work from IPython with `await rlm("subtask")`, run several children with `asyncio.gather(...)`, or start background work with `asyncio.create_task(...)`. Child agents use the same TypeScript agent runtime, providers, tools, skills, and session machinery as the parent.++You can prompt the model to use that capability directly:++```text+Review authentication and test coverage as independent subtasks. Run them in parallel, then synthesize the findings.+```-Additional built-in tools (`bash`, `edit`) 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.+See [Kernel and RLM Recursion](kernel-and-rlm-recursion.md) for the API and execution model.-## Give pi project instructions+## Give Prime Agent Project Instructions-Pi loads context files at startup. Add an `AGENTS.md` file to tell it how to work in a project:+Prime Agent loads context files at startup. Add an `AGENTS.md` file to tell it how to work in a project:```markdown# Project Instructions@@ -70,27 +99,27 @@ Pi loads context files at startup. Add an `AGENTS.md` file to tell it how to wor- Keep responses concise.```-Pi loads:+Prime Agent loads:-- `~/.pi/agent/AGENTS.md` for global instructions+- `~/.prime/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.+Restart Prime Agent, or run `/reload`, after changing context files.-## Common things to try+## Common Things to Try-### Reference files+### Reference FilesType `@` 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"+prime-agent @README.md "Summarize this"+prime-agent @src/app.ts @src/app.test.ts "Review these together"```Images can be pasted with Ctrl+V (Alt+V on Windows) or dragged into supported terminals.-### Run shell commands+### Run Shell CommandsIn interactive mode:@@ -98,41 +127,41 @@ In interactive mode:!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.+The command output is sent to the model. Use `!!command` to run a command without adding its output to model context. During agent work, the model normally runs project commands from the IPython control environment with a `%%bash` cell.-### Switch models+### Switch Models-Use `/model` or Ctrl+L to choose a model. Use `/effort` to set the reasoning/thinking level. Use Ctrl+P / Shift+Ctrl+P to cycle through scoped models.+Use `/model` or Ctrl+L to choose a model. Use `/effort` to set the reasoning level. Use Ctrl+P / Shift+Ctrl+P to cycle through scoped models.-### Continue later+### Continue Later-Sessions are saved automatically:+Sessions are saved automatically under `~/.prime/agent/sessions/`:```bash-pi -c # Continue most recent session-pi -r [path|id] # Browse previous sessions or open a specific session+prime-agent -c # Continue the most recent session+prime-agent -r [path|id] # Browse sessions or open a specific session```-Inside pi, use `/resume`, `/new`, `/tree`, `/fork`, and `/clone` to manage sessions.+Inside Prime Agent, use `/resume`, `/new`, `/tree`, `/fork`, and `/clone` to manage sessions. Persistent sessions run in worker processes, so closing the TUI detaches from the agent rather than necessarily stopping it. Use `prime-agent agents` to inspect or reattach to active work.-### Non-interactive mode+### Non-Interactive ModeFor 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?"+prime-agent -p "Summarize this codebase"+cat README.md | prime-agent -p "Summarize this text"+prime-agent -p @screenshot.png "What's in this image?"```Use `--mode json` for JSON event output or `--mode rpc` for process integration.-## Next steps+## Next Steps-- [Using Pi](usage.md) - interactive mode, slash commands, sessions, context files, and CLI reference.+- [Using Prime Agent](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.+- [Prime Agent 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/packages/coding-agent/docs/refine-verification-log.md b/packages/coding-agent/docs/refine-verification-log.mdindex b2384a68ab..5d3dc2acaa 100644--- a/packages/coding-agent/docs/refine-verification-log.md+++ b/packages/coding-agent/docs/refine-verification-log.md@@ -1,6 +1,6 @@# /refine verification log-This log records manual benchmark-verification checks for PrimeAgent continual+This log records manual benchmark-verification checks for Prime Agent continualharness features. It is intentionally artifact-oriented so later benchmark runscan replay the same surfaces.@@ -23,13 +23,14 @@ The model-facing `rlm.harness` API uses explicit `create_*`, `update_*`, and- Repo: `/Users/milkkarten/Research/prime-agent`- CLI launch: `./prime-agent.sh` in tmux session `PrimeAgentCLI`- Model shown by CLI: `openai/gpt-5.5`-- Session file:+- Legacy session file (before sessions moved to the flat session store):`/Users/milkkarten/.prime/agent/sessions/--Users-milkkarten-Research-prime-agent--/2026-06-08T19-08-33-915Z_019ea8a2-fafa-741b-902a-c00b6b8b997d.jsonl`- Harness state file:`/Users/milkkarten/.prime/agent/sessions/--Users-milkkarten-Research-prime-agent--/2026-06-08T19-08-33-915Z_019ea8a2-fafa-741b-902a-c00b6b8b997d/harness_state.json`Historical note: this manual run happened before the harness store was switched-from session-backed to global-by-default persistence.+from session-backed to global-by-default persistence and before session JSONL+files moved to `~/.prime/agent/sessions/<session-id>.jsonl`.### Harness availability@@ -69,7 +70,7 @@ Observed result:- Pass. Created `manual_cli_test_prompt`, `manual_cli_test_memory`,`manual_cli_test_skill`, `manual_cli_test_subagent`, and `refine_0001`.- Defect found: `record_refinement(..., "single change")` stored a character- list because the helper called `list(changes)`. Patched runtime helper to+ list because the helper called `list(changes)`. The runtime helper was patched tonormalize a single string into a one-item list and added a Python unit test.### `/refine` create, update, deletediff --git a/packages/coding-agent/docs/rpc.md b/packages/coding-agent/docs/rpc.mdindex 4b8a34c545..f04bce1330 100644--- a/packages/coding-agent/docs/rpc.md+++ b/packages/coding-agent/docs/rpc.md@@ -7,7 +7,7 @@ RPC mode enables headless operation of the coding agent via a JSON protocol over## Starting RPC Mode```bash-pi --mode rpc [options]+prime-agent --mode rpc [options]```Common options:@@ -754,9 +754,9 @@ Response:"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"}+ {"name": "session-name", "description": "Set or clear session name", "source": "extension", "path": "/home/user/.prime/agent/extensions/session.ts"},+ {"name": "fix-tests", "description": "Fix failing tests", "source": "prompt", "location": "project", "path": "/home/user/myproject/.prime/agent/prompts/fix-tests.md"},+ {"name": "skill:brave-search", "description": "Web search via Brave API", "source": "skill", "location": "user", "path": "/home/user/.prime/agent/skills/brave-search/SKILL.md"}]}}@@ -770,8 +770,8 @@ Each command has:- `"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/`)+ - `"user"`: User-level (`~/.prime/agent/`)+ - `"project"`: Project-level (`./.prime/agent/`)- `"path"`: Explicit path via CLI or settings- `path`: Absolute file path to the command source (optional)@@ -1172,7 +1172,7 @@ Set the terminal window/tab title. Fire-and-forget."type": "extension_ui_request","id": "uuid-8","method": "setTitle",- "title": "pi - my project"+ "title": "Prime Agent - my project"}```@@ -1359,7 +1359,7 @@ import subprocessimport jsonproc = subprocess.Popen(- ["pi", "--mode", "rpc", "--no-session"],+ ["prime-agent", "--mode", "rpc", "--no-session"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,text=True@@ -1398,7 +1398,7 @@ For a complete example of handling the extension UI protocol, see [`examples/rpcconst { spawn } = require("child_process");const { StringDecoder } = require("string_decoder");-const agent = spawn("pi", ["--mode", "rpc", "--no-session"]);+const agent = spawn("prime-agent", ["--mode", "rpc", "--no-session"]);function attachJsonlReader(stream, onLine) {const decoder = new StringDecoder("utf8");diff --git a/packages/coding-agent/docs/sdk.md b/packages/coding-agent/docs/sdk.mdindex 9229e6f51d..1f02cec9e3 100644--- a/packages/coding-agent/docs/sdk.md+++ b/packages/coding-agent/docs/sdk.md@@ -1,8 +1,8 @@-> pi can help you use the SDK. Ask it to build an integration for your use case.+> Prime Agent 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.+The SDK provides programmatic access to Prime Agent's capabilities. Use it to embed Prime Agent in other applications, build custom interfaces, or integrate with automated workflows.**Example use cases:**- Build a custom UI (web, desktop, mobile)@@ -338,23 +338,23 @@ const { session } = await createAgentSession({cwd: process.cwd(), // default// Global config directory- agentDir: "~/.pi/agent", // default (expands ~)+ agentDir: "~/.prime/agent", // default (expands ~)});````cwd` is used by `DefaultResourceLoader` for:-- Project extensions (`.pi/extensions/`)+- Project extensions (`.prime/agent/extensions/`)- Project skills:- - `.pi/skills/`+ - `.prime/agent/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/`)+- Project prompts (`.prime/agent/prompts/`)- Context files (`AGENTS.md` walking up from cwd)-- Session directory naming+- Session storage resolution`agentDir` is used by `DefaultResourceLoader` for:- Global extensions (`extensions/`)- Global skills:- - `skills/` under `agentDir` (for example `~/.pi/agent/skills/`)+ - `skills/` under `agentDir` (for example `~/.prime/agent/skills/`)- `~/.agents/skills/`- Global prompts (`prompts/`)- Global context file (`AGENTS.md`)@@ -418,7 +418,7 @@ API key resolution priority (handled by AuthStorage):```typescriptimport { AuthStorage, ModelRegistry } from "@earendil-works/pi-coding-agent";-// Default: uses ~/.pi/agent/auth.json and ~/.pi/agent/models.json+// Default: uses ~/.prime/agent/auth.json and ~/.prime/agent/models.jsonconst authStorage = AuthStorage.create();const modelRegistry = ModelRegistry.create(authStorage);@@ -502,7 +502,7 @@ const { session } = await createAgentSession({```**When you don't need factories:**-- If you omit `tools`, pi automatically creates them with the correct `cwd`+- If you omit `tools`, Prime Agent automatically creates them with the correct `cwd`- If you use `process.cwd()` as your `cwd`, the pre-built instances work fine**When you must use factories:**@@ -544,7 +544,7 @@ Custom tools passed via `customTools` are combined with extension-registered too### Extensions-Extensions are loaded by the `ResourceLoader`. `DefaultResourceLoader` discovers extensions from `~/.pi/agent/extensions/`, `.pi/extensions/`, and settings.json extension sources.+Extensions are loaded by the `ResourceLoader`. `DefaultResourceLoader` discovers extensions from `~/.prime/agent/extensions/`, `.prime/agent/extensions/`, and `settings.json` extension sources.```typescriptimport { createAgentSession, DefaultResourceLoader } from "@earendil-works/pi-coding-agent";@@ -802,8 +802,8 @@ const { session } = await createAgentSession({**Project-specific settings:**Settings load from two locations and merge:-1. Global: `~/.pi/agent/settings.json`-2. Project: `<cwd>/.pi/settings.json`+1. Global: `~/.prime/agent/settings.json`+2. Project: `<cwd>/.prime/agent/settings.json`Project overrides global. Nested objects merge keys. Setters modify global settings by default.@@ -1063,7 +1063,7 @@ See [RPC documentation](rpc.md) for the JSON protocol.For subprocess-based integration without building with the SDK, use the CLI directly:```bash-pi --mode rpc --no-session+prime-agent --mode rpc --no-session```See [RPC documentation](rpc.md) for the JSON protocol.diff --git a/packages/coding-agent/docs/session-format.md b/packages/coding-agent/docs/session-format.mdindex 0104123574..7437e65acb 100644--- a/packages/coding-agent/docs/session-format.md+++ b/packages/coding-agent/docs/session-format.md@@ -5,16 +5,16 @@ Sessions are stored as JSONL (JSON Lines) files. Each line is a JSON object with## File Location```-~/.pi/agent/sessions/--<path>--/<timestamp>_<uuid>.jsonl+~/.prime/agent/sessions/<session-id>.jsonl```-Where `<path>` is the working directory with `/` replaced by `-`.+The header records the working directory. Current releases keep sessions in a flat directory; older per-project directories are migrated automatically.## Deleting Sessions-Sessions can be removed by deleting their `.jsonl` files under `~/.pi/agent/sessions/`.+Sessions can be removed by deleting their `.jsonl` files under `~/.prime/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.+Prime Agent also supports deleting sessions interactively from `/resume` (select a session and press `Ctrl+D`, then confirm). When available, Prime Agent uses the `trash` CLI to avoid permanent deletion.## Session Version@@ -28,11 +28,10 @@ Existing sessions are automatically migrated to the current version (v3) when lo## 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+- [`session-manager.ts`](../src/core/session-manager.ts) - Session entry types and `SessionManager`+- [`messages.ts`](../src/core/messages.ts) - Extended message types (`BashExecutionMessage`, `CustomMessage`, and others)+- [`packages/ai/src/types.ts`](../../ai/src/types.ts) - Base message types (`UserMessage`, `AssistantMessage`, `ToolResultMessage`)+- [`packages/agent/src/types.ts`](../../agent/src/types.ts) - `AgentMessage` union typeFor TypeScript definitions in your project, inspect `node_modules/@earendil-works/pi-coding-agent/dist/` and `node_modules/@earendil-works/pi-ai/dist/`.@@ -69,7 +68,7 @@ interface ToolCall {}```-### Base Message Types (from pi-ai)+### Base Message Types (from Prime Agent AI)```typescriptinterface UserMessage {@@ -116,7 +115,7 @@ interface Usage {}```-### Extended Message Types (from pi-coding-agent)+### Extended Message Types (from Prime Agent Coding Agent)```typescriptinterface BashExecutionMessage {@@ -223,6 +222,14 @@ Emitted when the user changes the thinking/reasoning level.{"type":"thinking_level_change","id":"e5f6g7h8","parentId":"d4e5f6g7","timestamp":"2024-12-03T14:06:00.000Z","thinkingLevel":"high"}```+### ServiceTierChangeEntry++Emitted when the user changes provider service tier.++```json+{"type":"service_tier_change","id":"e6f7g8h9","parentId":"e5f6g7h8","timestamp":"2024-12-03T14:07:00.000Z","serviceTier":"priority"}+```+### CompactionEntryCreated when context is compacted. Stores a summary of earlier messages.@@ -233,7 +240,7 @@ Created when context is compacted. Stores a summary of earlier messages.Optional fields:- `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)+- `fromHook`: `true` if generated by an extension, `false`/`undefined` if generated by Prime Agent (legacy field name)### BranchSummaryEntry@@ -245,7 +252,7 @@ Created when switching branches via `/tree` with an LLM generated summary of theOptional fields:- `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)+- `fromHook`: `true` if generated by an extension, `false`/`undefined` if generated by Prime Agent (legacy field name)### CustomEntry@@ -257,6 +264,21 @@ Extension state persistence. Does NOT participate in LLM context.Use `customType` to identify your extension's entries on reload.+### ChildUsageAttributionEntry++Records RLM child usage folded into a parent assistant message. This entry is daemon bookkeeping and does not enter model context.++```typescript+interface ChildUsageAttributionEntry extends SessionEntryBase {+ type: "child_usage_attributed";+ targetId: string; // Parent assistant message entry+ childUsage: Usage; // Usage added by one child+ aggregateUsage: Usage; // Updated parent aggregate+}+```++Reload applies `aggregateUsage` to the target assistant message. Context-tree accounting can then subtract `childUsage` when reporting the parent node's own usage.+### CustomMessageEntryExtension-injected messages that DO participate in LLM context.@@ -290,6 +312,18 @@ Session metadata (e.g., user-defined display name). Set via `/name` command or `The session name is displayed in the session selector (`/resume`) instead of the first message when set.+### SessionStateEntry++Stores daemon-managed lifecycle state. Current persisted states are `active`, `archived`, and legacy `crash`; older `sleep` values normalize to `archived` when read.++### AgentStatusEntry++Stores the latest short agent status shown in the agents view, including its summary, optional task state, and source message count. It does not enter model context.++### GitStateEntry++Stores an append-only repository-state snapshot for agent status and recovery views. It does not enter model context.+## Tree StructureEntries form a tree:@@ -316,6 +350,8 @@ Entries form a tree:- Then messages after compaction4. Converts `BranchSummaryEntry` and `CustomMessageEntry` to appropriate message formats+Bookkeeping entries such as child usage attribution, session lifecycle, agent status, and git state are ignored when building model context.+## Parsing Example```typescript@@ -383,10 +419,15 @@ Key methods for working with sessions programmatically.### Instance Methods - Appending (all return entry ID)- `appendMessage(message)` - Add message- `appendThinkingLevelChange(level)` - Record thinking change+- `appendServiceTierChange(tier)` - Record provider service-tier change- `appendModelChange(provider, modelId)` - Record model change-- `appendCompaction(summary, firstKeptEntryId, tokensBefore, details?, fromHook?)` - Add compaction+- `appendCompaction(summary, firstKeptEntryId, tokensBefore, details?, fromHook?, customInstructions?)` - Add compaction- `appendCustomEntry(customType, data?)` - Extension state (not in context)+- `appendChildUsageAttribution(targetId, childUsage, aggregateUsage)` - Persist RLM child usage folded into a parent assistant message- `appendSessionInfo(name)` - Set session display name+- `appendSessionState(state)` - Record daemon-managed lifecycle state+- `appendAgentStatus(status)` - Record an agents-view status summary+- `appendGitState(git)` - Record repository state- `appendCustomMessageEntry(customType, content, display, details?)` - Extension message (in context)- `appendLabelChange(targetId, label)` - Set/clear labeldiff --git a/packages/coding-agent/docs/sessions.md b/packages/coding-agent/docs/sessions.mdindex 8ded8104ea..c86b94ac52 100644--- a/packages/coding-agent/docs/sessions.md+++ b/packages/coding-agent/docs/sessions.md@@ -1,16 +1,16 @@# Sessions-Pi saves conversations as sessions so you can continue work, branch from earlier turns, and revisit previous paths.+Prime Agent 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.+Sessions auto-save to `~/.prime/agent/sessions/`. Each session is a JSONL file with a tree structure.```bash-pi -c # Continue most recent session-pi -r [path|id] # Browse past sessions or resume one directly-pi --no-session # Ephemeral mode; do not save-pi --fork <path|id> # Fork a session file or partial session ID into a new session+prime-agent --continue # Continue the most recent session+prime-agent --resume [path|id] # Browse past sessions or resume one directly+prime-agent --no-session # Ephemeral mode; do not save+prime-agent --fork <path|id> # 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, and message count. Use `/usage` for token, cost, and context usage.@@ -35,9 +35,9 @@ For the JSONL file format and SessionManager API, see [Session Format](session-f## Resuming and Deleting Sessions-`/resume` opens an interactive session picker for the current project. `pi -r` opens the same picker at startup, and `pi -r <path|id>` resumes a specific session.+`/resume` opens an interactive session picker for the current project. `prime-agent --resume` opens the same picker at startup, and `prime-agent --resume <path|id>` resumes a specific session.-An invalid ID exits with the closest unambiguous session ID when one is available. To open the picker and send an initial prompt after selecting a session, separate the prompt with `--`: `pi -r -- "continue this work"`.+An invalid ID exits with the closest unambiguous session ID when one is available. To open the picker and send an initial prompt after selecting a session, separate the prompt with `--`: `prime-agent --resume -- "continue this work"`.In the picker you can:@@ -48,7 +48,7 @@ In the picker you can:- rename with Ctrl+R- delete with Ctrl+D, then confirm-When available, pi uses the `trash` CLI for deletion instead of permanently removing files.+When available, Prime Agent uses the `trash` CLI for deletion instead of permanently removing files.## Naming Sessions@@ -58,7 +58,7 @@ Use `/name <name>` to set a human-readable session name:/name Refactor auth module```-Named sessions are easier to find in `/resume` and `pi -r`.+Named sessions are easier to find in `/resume` and `prime-agent --resume`.## Branching with `/tree`@@ -122,7 +122,7 @@ Use `/tree` when you want to keep alternatives together. Use `/fork` or `/clone`## 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 `/tree` switches away from one branch to another, Prime Agent 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:diff --git a/packages/coding-agent/docs/settings.md b/packages/coding-agent/docs/settings.mdindex b136ba99e5..5aaca59feb 100644--- a/packages/coding-agent/docs/settings.md+++ b/packages/coding-agent/docs/settings.md@@ -1,11 +1,11 @@# Settings-Pi uses JSON settings files with project settings overriding global settings.+Prime Agent 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) |+| `~/.prime/agent/settings.json` | Global (all projects) |+| `.prime/agent/settings.json` | Project (current directory) |Edit directly or use `/settings` for common options.@@ -173,10 +173,10 @@ Normally the package manager's global modules location is queried using `root -g| `sessionDir` | string | - | Directory where session files are stored. Accepts absolute or relative paths, plus `~`. |```json-{ "sessionDir": ".pi/sessions" }+{ "sessionDir": ".prime/agent/sessions" }```-When multiple sources specify a session directory, precedence is `--session-dir`, `PI_CODING_AGENT_SESSION_DIR`, then `sessionDir` in settings.json.+When multiple sources specify a session directory, precedence is `--session-dir`, `PRIME_AGENT_SESSION_DIR`, the legacy `PRIME_AGENT_CODING_AGENT_SESSION_DIR`, then `sessionDir` in `settings.json`.### Model Cycling@@ -200,7 +200,7 @@ When multiple sources specify a session directory, precedence is `--session-dir`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.+Paths in `~/.prime/agent/settings.json` resolve relative to `~/.prime/agent`. Paths in `.prime/agent/settings.json` resolve relative to `.prime/agent`. Absolute paths and `~` are supported.| Setting | Type | Default | Description ||---------|------|---------|-------------|@@ -278,16 +278,16 @@ See [packages.md](packages.md) for package management details.## Project Overrides-Project settings (`.pi/settings.json`) override global settings. Nested objects are merged:+Project settings (`.prime/agent/settings.json`) override global settings. Nested objects are merged:```json-// ~/.pi/agent/settings.json (global)+// ~/.prime/agent/settings.json (global){"theme": "dark","compaction": { "enabled": true, "reserveTokens": 16384 }}-// .pi/settings.json (project)+// .prime/agent/settings.json (project){"compaction": { "reserveTokens": 8192 }}diff --git a/packages/coding-agent/docs/shell-aliases.md b/packages/coding-agent/docs/shell-aliases.mdindex af0cd25f19..95f7fbe20d 100644--- a/packages/coding-agent/docs/shell-aliases.md+++ b/packages/coding-agent/docs/shell-aliases.md@@ -1,8 +1,8 @@# Shell Aliases-Pi runs bash in non-interactive mode (`bash -c`), which doesn't expand aliases by default.+Prime Agent 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`:+To enable your shell aliases, add to `~/.prime/agent/settings.json`:```json{diff --git a/packages/coding-agent/docs/terminal-setup.md b/packages/coding-agent/docs/terminal-setup.mdindex 74b0df2a9e..8f823d3c54 100644--- a/packages/coding-agent/docs/terminal-setup.md+++ b/packages/coding-agent/docs/terminal-setup.md@@ -1,6 +1,6 @@# 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.+Prime Agent 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@@ -20,11 +20,11 @@ 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.+That mapping sends a raw linefeed byte. Inside Prime Agent, that is indistinguishable from `Ctrl+J`, so tmux and Prime Agent 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.-If you want `Shift+Enter` to keep working in tmux via that remap, add `ctrl+j` to your pi `newLine` keybinding in `~/.pi/agent/keybindings.json`:+If you want `Shift+Enter` to keep working in tmux via that remap, add `ctrl+j` to your Prime Agent `newLine` keybinding in `~/.prime/agent/keybindings.json`:```json{@@ -63,7 +63,7 @@ Add to `keybindings.json` to enable `Shift+Enter` for multi-line input:## Windows Terminal-Add to `settings.json` (Ctrl+Shift+, or Settings → Open JSON file) to forward the modified Enter keys pi uses:+Add to `settings.json` (Ctrl+Shift+, or Settings → Open JSON file) to forward the modified Enter keys Prime Agent uses:```json{@@ -81,8 +81,8 @@ Add to `settings.json` (Ctrl+Shift+, or Settings → Open JSON file) to forward```- `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.+- Windows Terminal binds `Alt+Enter` to fullscreen by default. That prevents Prime Agent from receiving `Alt+Enter` for follow-up queueing.+- Remapping `Alt+Enter` to `sendInput` forwards the real key chord to Prime Agent 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.@@ -101,6 +101,6 @@ For the best experience, use a terminal that supports the Kitty keyboard protocoThe 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).+If you want the hardware cursor visible, set `PI_HARDWARE_CURSOR=1` before running `prime-agent` (disabled by default for compatibility).Consider using a dedicated terminal emulator for the best experience.diff --git a/packages/coding-agent/docs/termux.md b/packages/coding-agent/docs/termux.mdindex b89bb771aa..c43eab4122 100644--- a/packages/coding-agent/docs/termux.md+++ b/packages/coding-agent/docs/termux.md@@ -1,6 +1,6 @@# Termux (Android) Setup-Pi runs on Android via [Termux](https://termux.dev/), a terminal emulator and Linux environment for Android.+Prime Agent runs on Android via [Termux](https://termux.dev/), a terminal emulator and Linux environment for Android.## Prerequisites@@ -16,14 +16,13 @@ pkg update && pkg upgrade# Install dependenciespkg install nodejs termux-api git ripgrep-# Install pi-npm install -g @earendil-works/pi-coding-agent+# Clone and install Prime Agent from source+git clone https://github.com/PrimeIntellect-ai/prime-agent.git+cd prime-agent+npm ci-# Create config directory-mkdir -p ~/.pi/agent--# Run pi-pi+# Run Prime Agent+./prime-agent.sh```## Clipboard Support@@ -34,7 +33,7 @@ Image clipboard is not supported on Termux (the `ctrl+v` image paste feature wil## Example AGENTS.md for Termux-Create `~/.pi/agent/AGENTS.md` to help the agent understand the Termux environment:+Create `~/.prime/agent/AGENTS.md` to help the agent understand the Termux environment:```markdown# Agent Environment: Termux on Androiddiff --git a/packages/coding-agent/docs/themes.md b/packages/coding-agent/docs/themes.mdindex 8945539fed..44b8f108e5 100644--- a/packages/coding-agent/docs/themes.md+++ b/packages/coding-agent/docs/themes.md@@ -1,4 +1,4 @@-> pi can create themes. Ask it to build one for your setup.+> Prime Agent can create themes. Ask it to build one for your setup.# Themes@@ -16,11 +16,11 @@ Themes are JSON files that define colors for the TUI.## Locations-Pi loads themes from:+Prime Agent loads themes from:- Built-in: `dark`, `light`-- Global: `~/.pi/agent/themes/*.json`-- Project: `.pi/themes/*.json`+- Global: `~/.prime/agent/themes/*.json`+- Project: `.prime/agent/themes/*.json`- Packages: `themes/` directories or `pi.themes` entries in `package.json`- Settings: `themes` array with files or directories- CLI: `--theme <path>` (repeatable)@@ -37,22 +37,22 @@ Select a theme via `/settings` or in `settings.json`:}```-On first run, pi detects your terminal background and defaults to `dark` or `light`.+On first run, Prime Agent detects your terminal background and defaults to `dark` or `light`.## Creating a Custom Theme1. Create a theme file:```bash-mkdir -p ~/.pi/agent/themes-vim ~/.pi/agent/themes/my-theme.json+mkdir -p ~/.prime/agent/themes+vim ~/.prime/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-mono/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",+ "$schema": "https://raw.githubusercontent.com/PrimeIntellect-ai/prime-agent/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json","name": "my-theme","vars": {"primary": "#00aaff",@@ -117,13 +117,13 @@ vim ~/.pi/agent/themes/my-theme.json3. Select the theme via `/settings`.-**Hot reload:** When you edit the currently active custom theme file, pi reloads it automatically for immediate visual feedback.+**Hot reload:** When you edit the currently active custom theme file, Prime Agent reloads it automatically for immediate visual feedback.## Theme Format```json{- "$schema": "https://raw.githubusercontent.com/earendil-works/pi-mono/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",+ "$schema": "https://raw.githubusercontent.com/PrimeIntellect-ai/prime-agent/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json","name": "my-theme","vars": {"blue": "#0066cc",@@ -270,7 +270,7 @@ Four formats are supported:### 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.+Prime Agent 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, Prime Agent falls back to the nearest approximation.Check truecolor support:diff --git a/packages/coding-agent/docs/tmux.md b/packages/coding-agent/docs/tmux.mdindex efe6ab571b..9b1cca7602 100644--- a/packages/coding-agent/docs/tmux.md+++ b/packages/coding-agent/docs/tmux.md@@ -1,6 +1,6 @@# 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`.+Prime Agent 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@@ -18,7 +18,7 @@ tmux kill-servertmux```-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.+Prime Agent 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.## Why `csi-u` Is Recommended@@ -40,7 +40,7 @@ With `extended-keys-format csi-u`, the same keys are forwarded as:- `Ctrl+D` → `\x1b[100;5u`- `Ctrl+Enter` → `\x1b[13;5u`-Pi supports both formats, but `csi-u` is the recommended tmux setup.+Prime Agent supports both formats, but `csi-u` is the recommended tmux setup.## What This Fixesdiff --git a/packages/coding-agent/docs/tui.md b/packages/coding-agent/docs/tui.mdindex 2872ac4b74..5e9c371255 100644--- a/packages/coding-agent/docs/tui.md+++ b/packages/coding-agent/docs/tui.md@@ -1,10 +1,10 @@-> pi can create TUI components. Ask it to build one for your use case.+> Prime Agent can create TUI components. Ask it to build one for your use case.# TUI ComponentsExtensions 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)+**Source:** [`packages/tui`](../../tui/)## Component Interface@@ -733,11 +733,11 @@ ctx.ui.setStatus("my-ext", ctx.ui.theme.fg("accent", "● active"));ctx.ui.setStatus("my-ext", undefined);```-**Examples:** [status-line.ts](../examples/extensions/status-line.ts), [plan-mode.ts](../examples/extensions/plan-mode.ts), [preset.ts](../examples/extensions/preset.ts)+**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.+Customize the inline working indicator shown while Prime Agent is streaming a response.```typescript// Static indicator@@ -757,7 +757,7 @@ ctx.ui.setWorkingIndicator({// Hide the indicator entirelyctx.ui.setWorkingIndicator({ frames: [] });-// Restore pi's default spinner+// Restore Prime Agent's default spinnerctx.ui.setWorkingIndicator();```@@ -793,7 +793,7 @@ ctx.ui.setWidget("my-widget", (_tui, theme) => {ctx.ui.setWidget("my-widget", undefined);```-**Examples:** [plan-mode.ts](../examples/extensions/plan-mode.ts)+**Examples:** [widget-placement.ts](../examples/extensions/widget-placement.ts), [plan-mode/index.ts](../examples/extensions/plan-mode/index.ts)### Pattern 6: Custom Footer@@ -910,7 +910,8 @@ export default function (pi: ExtensionAPI) {- **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.ts](../examples/extensions/plan-mode.ts) - setStatus and setWidget+- **Status indicators**: [examples/extensions/status-line.ts](../examples/extensions/status-line.ts) - `setStatus`+- **Editor widgets**: [examples/extensions/widget-placement.ts](../examples/extensions/widget-placement.ts) - `setWidget` placement- **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 editingdiff --git a/packages/coding-agent/docs/usage.md b/packages/coding-agent/docs/usage.mdindex 999734533d..392a33297e 100644--- a/packages/coding-agent/docs/usage.md+++ b/packages/coding-agent/docs/usage.md@@ -1,7 +1,9 @@-# Using Pi+# Using Prime AgentThis page collects day-to-day usage details that do not fit on the quickstart page.+Prime Agent is built around one model-facing tool: a persistent IPython kernel. The kernel retains Python state across turns and acts as a control environment for file operations, project commands, installed Python skills, MCP-backed skills, and recursive subagents. The TypeScript host remains responsible for provider calls, session state, tool execution, scheduling, and child-agent lifecycles.+## Interactive Mode<p align="center"><img src="images/interactive-mode.png" alt="Interactive Mode" width="600"></p>@@ -37,18 +39,20 @@ Type `/` in the editor to open command completion. Extensions can register custo|---------|-------------|| `/login`, `/logout` | Manage OAuth or API-key credentials || `/model` | Switch models |+| `/effort` | Set the reasoning/thinking level || `/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 <name>` | Set session display name || `/session` | Show session file, ID, and message counts |-| `/traces [status\|on\|off\|upload\|login]` | Manage opt-in Prime Agent trace sharing |-| `/usage` | Show token, cost, and context usage |+| `/traces [status\|on\|off\|preview\|upload-current\|upload-all\|login]` | Preview, upload, or manage opt-in trace sharing |+| `/usage`, `/context` | Show the parent and subagent context, token, and cost breakdown || `/tree` | Jump to any point in the session and continue from there || `/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 |+| `/refine [instructions]` | Refine or roll back session-backed harness state || `/copy` | Copy last assistant message to clipboard || `/btw <question>`, `/side <question>` | Ask one inline side question without adding it to the session || `/export [file]` | Export session to HTML |@@ -56,7 +60,7 @@ Type `/` in the editor to open command completion. Extensions can register custo| `/reload` | Reload keybindings, extensions, skills, prompts, and context files || `/hotkeys` | Show all keyboard shortcuts || `/changelog` | Display version history |-| `/quit` | Quit pi |+| `/quit` | Quit Prime Agent |## Message Queue@@ -68,19 +72,19 @@ You can submit messages while the agent is still working:- **Escape** clears the input bar without interrupting the agent.- **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.+On Windows Terminal, Alt+Enter is fullscreen by default. Remap it as described in [Terminal setup](terminal-setup.md) if you want Prime Agent 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.+Sessions are saved automatically as flat JSONL files under `~/.prime/agent/sessions/`. Each session header records its working directory, which the session picker uses for project-scoped views.```bash-pi -c # Continue most recent session-pi -r [path|id] # Browse sessions or resume one directly-pi --no-session # Ephemeral mode; do not save-pi --fork <path|id> # Fork a session into a new session file+prime-agent -c # Continue most recent session+prime-agent -r [path|id] # Browse sessions or resume one directly+prime-agent --no-session # Ephemeral mode; do not save+prime-agent --fork <path|id> # Fork a session into a new session file```Useful session commands:@@ -94,11 +98,36 @@ Useful session commands:See [Sessions](sessions.md) and [Compaction](compaction.md) for details.+## Agents and Recursive Subagents++Normal interactive sessions are persistent agents backed by isolated worker processes. Closing the TUI detaches the client; use `prime-agent agents`, `prime-agent list`, or `prime-agent attach <agent>` to find and reattach to running work. `prime-agent stop <agent>` stops one root agent, while `prime-agent shutdown` stops all workers and the local supervisor.++Within a session, the model can delegate through the `rlm` callable already available in IPython:++```python+# Return one child result immediately.+review = await rlm("Review the authentication flow for security issues.", name="auth-reviewer")+print(review.answer)++# Run independent children in parallel.+tests, docs = await asyncio.gather(+ rlm("Find missing regression tests."),+ rlm("Find stale public documentation."),+)++# Start background work and collect it later.+task = asyncio.create_task(rlm("Run focused checks and report failures.", name="checks"))+children = await rlm.list_subagents()+result = await task+```++Children inherit the parent model unless the user requests another model. They run as TypeScript `AgentSession` instances under the same root worker and can use the same provider, tools, skills, session storage, and scheduling system. See [Kernel and RLM Recursion](kernel-and-rlm-recursion.md).+## Context Files-Pi loads `AGENTS.md` or `CLAUDE.md` at startup from:+Prime Agent loads `AGENTS.md` or `CLAUDE.md` at startup from:-- `~/.pi/agent/AGENTS.md` for global instructions+- `~/.prime/agent/AGENTS.md` for global instructions- parent directories, walking up from the current working directory- the current directory@@ -108,8 +137,8 @@ Use context files for project conventions, commands, safety rules, and preferencReplace the default system prompt with:-- `.pi/SYSTEM.md` for a project-- `~/.pi/agent/SYSTEM.md` globally+- `.prime/agent/SYSTEM.md` for a project+- `~/.prime/agent/SYSTEM.md` globallyAppend to the default prompt without replacing it with `APPEND_SYSTEM.md` in either location.@@ -119,12 +148,10 @@ 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...]+prime-agent [options] [@files...] [messages...]```### Shell Commands@@ -149,7 +176,7 @@ prime-agent update [--force]prime-agent config```-See [Pi Packages](packages.md) for package sources and security notes.+See [Prime Agent Packages](packages.md) for package sources and security notes.### Modes@@ -160,10 +187,10 @@ See [Pi Packages](packages.md) for package sources and security notes.| `--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) |-In print mode, pi also reads piped stdin and merges it into the initial prompt:+In print mode, Prime Agent also reads piped stdin and merges it into the initial prompt:```bash-cat README.md | pi -p "Summarize this text"+cat README.md | prime-agent -p "Summarize this text"```### Model Options@@ -217,7 +244,7 @@ Built-in tools: `ipython`.Combine `--no-*` with explicit flags to load exactly what you need, ignoring settings. Example:```bash-pi --no-extensions -e ./my-extension.ts+prime-agent --no-extensions -e ./my-extension.ts```### Autonomous Options@@ -251,58 +278,65 @@ pi --no-extensions -e ./my-extension.tsPrefix 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"+prime-agent @prompt.md "Answer this"+prime-agent -p @screenshot.png "What's in this image?"+prime-agent @code.ts @test.ts "Review these files"```### Examples```bash# Interactive with initial prompt-pi "List all .ts files in src/"+prime-agent "List all .ts files in src/"# Non-interactive-pi -p "Summarize this codebase"+prime-agent -p "Summarize this codebase"# Non-interactive with piped stdin-cat README.md | pi -p "Summarize this text"+cat README.md | prime-agent -p "Summarize this text"# Different model-pi --provider openai --model gpt-4o "Help me refactor"+prime-agent --provider openai --model gpt-4o "Help me refactor"# Model with provider prefix-pi --model openai/gpt-4o "Help me refactor"+prime-agent --model openai/gpt-4o "Help me refactor"# Model with thinking level shorthand-pi --model sonnet:high "Solve this complex problem"+prime-agent --model sonnet:high "Solve this complex problem"# Limit model cycling-pi --models "claude-*,gpt-4o"+prime-agent --models "claude-*,gpt-4o"# Restrict to the built-in IPython tool-pi --tools ipython -p "Review the code"+prime-agent --tools ipython -p "Review the code"```### Environment Variables| Variable | Description ||----------|-------------|-| `PI_CODING_AGENT_DIR` | Override config directory; default is `~/.pi/agent` |-| `PI_CODING_AGENT_SESSION_DIR` | Override session storage directory; overridden by `--session-dir` |+| `PRIME_AGENT_CODING_AGENT_DIR` | Override config directory; default is `~/.prime/agent` |+| `PRIME_AGENT_SESSION_DIR` | Override session storage directory; overridden by `--session-dir` |+| `PRIME_AGENT_CODING_AGENT_SESSION_DIR` | Legacy alias for `PRIME_AGENT_SESSION_DIR` || `PI_PACKAGE_DIR` | Override package directory, useful for Nix/Guix store paths || `PI_OFFLINE` | Disable startup network operations, including update checks and package update checks || `PI_SKIP_VERSION_CHECK` | Skip the Prime Agent version update check at startup. This prevents the release manifest request || `PRIME_AGENT_DOWNLOAD_BASE_URL` | Override the Prime Agent release manifest and tarball base URL || `PI_CACHE_RETENTION` | Set to `long` for extended prompt cache where supported |+| `PRIME_API_KEY` | Prime Inference API key; also used for trace sharing when it has `agent_traces` scope || `PRIME_AGENT_TRACES_API_KEY` | Prime API key used only for opt-in trace sharing || `PRIME_AGENT_TRACES_BASE_URL` | Override the Prime Agent trace upload API base URL |+| `PRIME_AGENT_KERNEL_PYTHON` | Use an existing Python environment with `ipykernel` instead of bootstrapping `~/.prime/agent/kernel-venv` || `VISUAL`, `EDITOR` | External editor for Ctrl+G |+The remaining `PI_*` variables are compatibility names still read by the current runtime. They do not change the application name, command, or default `~/.prime/agent` configuration path.+## Design Principles-Pi keeps the core small and pushes workflow-specific behavior into extensions, skills, prompt templates, and packages.+Prime Agent keeps the model-facing tool surface small while making the IPython runtime powerful and composable. The built-in `ipython` tool provides durable state, project command execution, Python skills, MCP-backed integrations, and the native `rlm` delegation API without presenting each capability as a separate model tool.++Recursive subagents are a core capability, not an optional extension. The TypeScript host owns every parent and child agent loop so recursion uses the same provider, session, tool, skill, scheduling, usage-accounting, and recovery infrastructure. The Python `rlm` package is a thin host bridge rather than a separate agent implementation.-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.+Extensions, skills, prompt templates, themes, and Prime Agent packages remain the primary customization surfaces. They can add project-specific workflows, custom tools and UI, permission policies, provider integrations, and orchestration patterns around the built-in runtime.-For the full rationale, read the [blog post](https://mariozechner.at/posts/2025-11-30-pi-coding-agent/).+Prime Agent preserves MIT attribution to pi-mono for its upstream lineage, but upstream Pi product claims and limitations do not describe the current Prime Agent architecture.diff --git a/packages/coding-agent/docs/windows.md b/packages/coding-agent/docs/windows.mdindex 007f649c12..3f7da6c61d 100644--- a/packages/coding-agent/docs/windows.md+++ b/packages/coding-agent/docs/windows.md@@ -1,8 +1,8 @@# Windows Setup-Pi requires a bash shell on Windows. Checked locations (in order):+Prime Agent requires a bash shell on Windows. Checked locations (in order):-1. Custom path from `~/.pi/agent/settings.json`+1. Custom path from `~/.prime/agent/settings.json`2. Git Bash (`C:\Program Files\Git\bin\bash.exe`)3. `bash.exe` on PATH (Cygwin, MSYS2, WSL)diff --git a/packages/coding-agent/examples/README.md b/packages/coding-agent/examples/README.mdindex 875051843a..c3ba7fafce 100644--- a/packages/coding-agent/examples/README.md+++ b/packages/coding-agent/examples/README.md@@ -1,6 +1,6 @@# Examples-Example code for pi-coding-agent SDK and extensions.+Example code for the Prime Agent SDK and extension system.## Directoriesdiff --git a/packages/coding-agent/examples/extensions/README.md b/packages/coding-agent/examples/extensions/README.mdindex 01c7d44b4a..3caef7deec 100644--- a/packages/coding-agent/examples/extensions/README.md+++ b/packages/coding-agent/examples/extensions/README.md@@ -1,15 +1,15 @@# Extension Examples-Example extensions for pi-coding-agent.+Example extensions for Prime Agent.## Usage```bash-# Load an extension with --extension flag-pi --extension examples/extensions/permission-gate.ts+# From the repository root, load an extension with --extension+./prime-agent.sh --extension packages/coding-agent/examples/extensions/permission-gate.ts# Or copy to extensions directory for auto-discovery-cp permission-gate.ts ~/.pi/agent/extensions/+cp permission-gate.ts ~/.prime/agent/extensions/```## Examples@@ -96,7 +96,7 @@ cp permission-gate.ts ~/.pi/agent/extensions/| Extension | Description ||-----------|-------------|-| `mac-system-theme.ts` | Syncs pi theme with macOS dark/light mode |+| `mac-system-theme.ts` | Syncs the Prime Agent theme with macOS dark/light mode |### Resources@@ -123,7 +123,7 @@ cp permission-gate.ts ~/.pi/agent/extensions/| 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 |+| `custom-provider-gitlab-duo/` | GitLab Duo provider using the inherited `@earendil-works/pi-ai` streaming API through a proxy |### External Dependenciesdiff --git a/packages/coding-agent/examples/extensions/subagent/README.md b/packages/coding-agent/examples/extensions/subagent/README.mdindex c5b7e85b74..d6a79f83d6 100644--- a/packages/coding-agent/examples/extensions/subagent/README.md+++ b/packages/coding-agent/examples/extensions/subagent/README.md@@ -1,10 +1,14 @@# Subagent Example-Delegate tasks to specialized subagents with isolated context windows.+Delegate tasks to specialized subprocess agents with isolated context windows.++Prime Agent also provides native recursive delegation through `rlm.call()` and+`rlm.run_async()`. This extension is a separate example for users who want+file-defined agent profiles and explicit single, parallel, or chained workflows.## Features-- **Isolated context**: Each subagent runs in a separate `pi` process+- **Isolated context**: Each subagent runs in a separate Prime Agent 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)@@ -35,30 +39,30 @@ 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+mkdir -p ~/.prime/agent/extensions/subagent+ln -sf "$(pwd)/packages/coding-agent/examples/extensions/subagent/index.ts" ~/.prime/agent/extensions/subagent/index.ts+ln -sf "$(pwd)/packages/coding-agent/examples/extensions/subagent/agents.ts" ~/.prime/agent/extensions/subagent/agents.ts# Symlink agents-mkdir -p ~/.pi/agent/agents+mkdir -p ~/.prime/agent/agentsfor f in packages/coding-agent/examples/extensions/subagent/agents/*.md; do- ln -sf "$(pwd)/$f" ~/.pi/agent/agents/$(basename "$f")+ ln -sf "$(pwd)/$f" ~/.prime/agent/agents/$(basename "$f")done# Symlink workflow prompts-mkdir -p ~/.pi/agent/prompts+mkdir -p ~/.prime/agent/promptsfor f in packages/coding-agent/examples/extensions/subagent/prompts/*.md; do- ln -sf "$(pwd)/$f" ~/.pi/agent/prompts/$(basename "$f")+ ln -sf "$(pwd)/$f" ~/.prime/agent/prompts/$(basename "$f")done```## Security Model-This tool executes a separate `pi` subprocess with a delegated system prompt and tool/model configuration.+This tool executes a separate Prime Agent 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 run ipython, bash commands, etc.+**Project-local agents** (`.prime/agent/agents/*.md`) are repo-controlled prompts that can instruct the model to run IPython, shell commands, and other tools.-**Default behavior:** Only loads **user-level agents** from `~/.pi/agent/agents`.+**Default behavior:** Only loads **user-level agents** from `~/.prime/agent/agents`.To enable project-local agents, pass `agentScope: "both"` (or `"project"`). Only do this for repositories you trust.@@ -135,8 +139,8 @@ 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"`)+- `~/.prime/agent/agents/*.md` - User-level (always loaded)+- `.prime/agent/agents/*.md` - Project-level (only with `agentScope: "project"` or `"both"`)Project agents override user agents with the same name when `agentScope: "both"`.diff --git a/packages/coding-agent/examples/sdk/README.md b/packages/coding-agent/examples/sdk/README.mdindex 9564748499..aac8b4ea6b 100644--- a/packages/coding-agent/examples/sdk/README.md+++ b/packages/coding-agent/examples/sdk/README.md@@ -1,6 +1,10 @@# SDK Examples-Programmatic usage of pi-coding-agent via `createAgentSession()` and `createAgentSessionRuntime()`.+Programmatic usage of the Prime Agent SDK via `createAgentSession()` and `createAgentSessionRuntime()`.++The published TypeScript packages still use inherited `@earendil-works/pi-*`+identifiers. Those identifiers are API names, not a dependency on the upstream+Pi monorepo.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.@@ -111,7 +115,7 @@ await session.prompt("Hello");| `authStorage` | `AuthStorage.create()` | Credential storage || `modelRegistry` | `ModelRegistry.create(authStorage)` | Model registry || `cwd` | `process.cwd()` | Working directory |-| `agentDir` | `~/.pi/agent` | Config directory |+| `agentDir` | `~/.prime/agent` | Config directory || `model` | From settings/first available | Model to use || `thinkingLevel` | From settings/"off" | off, low, medium, high || `tools` | `["ipython"]` | Built-in tools |