Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: LLMLarge Language Model. ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. Abstraction
Overview
pi-ai provides a single unified API for chat and image generation across 30+ LLMLarge Language Model. providers, abstracting away differences in wire protocols, authentication, streaming formats, tool-calling schemas, and token/cost accounting.
Consumers (the agent runtime, the coding agent, and third-party SDKSoftware Development Kit (the embeddable programmatic API). users) program against one ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection and one event-stream contract instead of per-provider SDKs.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Agent runtime (pi-agent-core) | A stable StreamFn contract and message types to drive the agent loop |
| Coding agent (pi-coding-agent) | Broad provider coverage, automatic auth resolution, and a model catalog |
| SDKSoftware Development Kit (the embeddable programmatic API). / extension authors | A clean public API to register custom providers and models |
| End users | Access to their chosen model and subscription with minimal setup |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-01MustThe system shall expose a `ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.` collection that routes model lookups and streams by owning provider. | Must | The system shall expose a ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection that routes model lookups and streams by owning provider. |
| FRFunctional Requirement.-02MustThe system shall support the major wire protocols: Anthropic Messages, OpenAI Responses, OpenAI Completions, Google Generative AI, Google Vertex, Mistral Conversations, Bedrock Converse Stream, Azure OpenAI Responses, OpenAI Codex Responses, PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. Messages, Cloudflare Workers AI, Typesafe System-One, OpenRouter Images, and llama.cpp classification. | Must | The system shall support the major wire protocols: Anthropic Messages, OpenAI Responses, OpenAI Completions, Google Generative AI, Google Vertex, Mistral Conversations, Bedrock Converse Stream, Azure OpenAI Responses, OpenAI Codex Responses, PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. Messages, Cloudflare Workers AI, Typesafe System-One, OpenRouter Images, and llama.cpp classification. |
| FRFunctional Requirement.-03MustThe system shall stream assistant responses as an async-iterable event stream emitting `start`, text/thinking/toolcall deltas, `done`, and `error` events. | Must | The system shall stream assistant responses as an async-iterable event stream emitting start, text/thinking/toolcall deltas, done, and error events. |
| FRFunctional Requirement.-04Must"aborted"` and never throw out of a stream. | Must | The system shall encode all stream failures as terminal events with stopReason: "error" \ | "aborted" and never throw out of a stream. |
| FRFunctional Requirement.-05MustThe system shall resolve provider authentication via a credential store first (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). or API keyApplication Programming Interface key (ambient provider authentication).), falling back to ambient env-var resolution only when nothing is stored. | Must | The system shall resolve provider authentication via a credential store first (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). or API keyApplication Programming Interface key (ambient provider authentication).), falling back to ambient env-var resolution only when nothing is stored. |
| FRFunctional Requirement.-06MustThe system shall support OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flows (PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). and device code) for subscription-based providers. | Must | The system shall support OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flows (PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). and device code) for subscription-based providers. |
| FRFunctional Requirement.-07MustThe system shall represent tool definitions and tool calls using TypeBox schemas that are serializable and self-validating. | Must | The system shall represent tool definitions and tool calls using TypeBox schemas that are serializable and self-validating. |
| FRFunctional Requirement.-08MustThe system shall lazily load provider SDKs on first request rather than at import time. | Must | The system shall lazily load provider SDKs on first request rather than at import time. |
| FRFunctional Requirement.-09MustThe system shall generate its model catalog (`models.generated.ts`) from live upstream sources (models.dev, OpenRouter, Vercel AI Gateway), filtering to tool-capable models. | Must | The system shall generate its model catalog (models.generated.ts) from live upstream sources (models.dev, OpenRouter, Vercel AI Gateway), filtering to tool-capable models. |
| FRFunctional Requirement.-10ShouldThe system shall track token usage and cost per request. | Should | The system shall track token usage and cost per request. |
| FRFunctional Requirement.-11ShouldThe system shall support cross-provider handoffs, converting thinking blocks from foreign providers into tagged text. | Should | The system shall support cross-provider handoffs, converting thinking blocks from foreign providers into tagged text. |
| FRFunctional Requirement.-12ShouldThe system shall provide per-provider compatibility flags (e.g. `OpenAICompletionsCompat`) auto-detected from baseUrl and overridable per model. | Should | The system shall provide per-provider compatibility flags (e.g. OpenAICompletionsCompat) auto-detected from baseUrl and overridable per model. |
| FRFunctional Requirement.-13ShouldThe system shall provide a `faux` in-memory provider for deterministic testing. | Should | The system shall provide a faux in-memory provider for deterministic testing. |
| FRFunctional Requirement.-14MayThe system shall provide an image-generation API (`ImagesModels`) parallel to the chat API. | May | The system shall provide an image-generation API (ImagesModels) parallel to the chat API. |
| FRFunctional Requirement.-15MayThe system shall preserve a deprecated `/compat` entrypoint for the legacy global API during migration. | May | The system shall preserve a deprecated /compat entrypoint for the legacy global API during migration. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-01MustThe root `index.ts` shall be side-effect free. | Must | Compatibility | The root index.ts shall be side-effect free. |
| NFRNon-Functional Requirement.-02MustSynchronous model reads (`getModels`, `getModel`) shall return last-known data without awaiting; `refresh()` shall be the explicit async verb. | Must | Performance | Synchronous model reads (getModels, getModel) shall return last-known data without awaiting; refresh() shall be the explicit async verb. |
| NFRNon-Functional Requirement.-03MustOAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). token refresh shall use double-checked locking so concurrent requests refresh at most once. | Must | Reliability | OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). token refresh shall use double-checked locking so concurrent requests refresh at most once. |
| NFRNon-Functional Requirement.-04MustThe system shall not silently fall back to ambient auth after a failed stored-credential refresh. | Must | Security | The system shall not silently fall back to ambient auth after a failed stored-credential refresh. |
| NFRNon-Functional Requirement.-05ShouldSDKSoftware Development Kit (the embeddable programmatic API). loading shall not block stream creation; setup may run behind a lazily returned stream. | Should | Performance | SDKSoftware Development Kit (the embeddable programmatic API). loading shall not block stream creation; setup may run behind a lazily returned stream. |
| NFRNon-Functional Requirement.-06ShouldProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. factories shall be thin wrappers over a shared `createProvider` helper. | Should | Maintainability | ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. factories shall be thin wrappers over a shared createProvider helper. |
Constraints
- Only tool-call-capable models are cataloged.
- Generated files (
models.generated.ts,*.models.ts) must never be hand-edited. - Erasable TypeScript syntax only; ESM only; Node
>=22.19.0.
Acceptance Criteria
Every FRFunctional Requirement. and NFRNon-Functional Requirement. shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FRFunctional Requirement.-01MustThe system shall expose a `ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.` collection that routes model lookups and streams by owning provider.
- Given a
ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.collection with multiple registered providers - When a consumer requests a model by
provider/id - Then the owning provider resolves the model and its stream behavior.
- Given a
- FRFunctional Requirement.-03MustThe system shall stream assistant responses as an async-iterable event stream emitting `start`, text/thinking/toolcall deltas, `done`, and `error` events.
- Given a configured provider and a prompt
- When the consumer calls the stream function
- Then it receives an
AssistantMessageEventStreamyielding ordered text/thinking/toolcall deltas and a terminaldoneevent.
- FRFunctional Requirement.-04Must"aborted"` and never throw out of a stream.
- Given a provider request that fails mid-stream
- When the failure occurs
- Then the stream emits an
errorevent with partial content and astopReasonoferrororabortedinstead of throwing.
- FRFunctional Requirement.-05MustThe system shall resolve provider authentication via a credential store first (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). or API keyApplication Programming Interface key (ambient provider authentication).), falling back to ambient env-var resolution only when nothing is stored.
- Given a provider with both a stored credential and an ambient env var
- When auth is resolved
- Then the stored credential is used and the env var is ignored.
- FRFunctional Requirement.-07MustThe system shall represent tool definitions and tool calls using TypeBox schemas that are serializable and self-validating.
- Given a tool defined with a TypeBox parameter schema
- When the provider returns a tool call
- Then the arguments are parsed and available for validation without provider-specific handling.
- FRFunctional Requirement.-08MustThe system shall lazily load provider SDKs on first request rather than at import time.
- Given a fresh process importing the root entrypoint
- When no request has been made
- Then no provider SDKSoftware Development Kit (the embeddable programmatic API). (
@anthropic-ai/sdk,openai, etc.) is loaded.
- FRFunctional Requirement.-09MustThe system shall generate its model catalog (`models.generated.ts`) from live upstream sources (models.dev, OpenRouter, Vercel AI Gateway), filtering to tool-capable models.
- Given the model generator
- When run via
npm run generate-models - Then per-provider
*.models.tsfiles and the aggregatormodels.generated.tsare written, containing only tool-capable models.
- NFRNon-Functional Requirement.-01MustThe root `index.ts` shall be side-effect free.
- Given a consumer importing the root
index.ts - When the import completes
- Then no provider factories, generated catalogs, or OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). implementations have executed as side effects.
- Given a consumer importing the root
- NFRNon-Functional Requirement.-03MustOAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). token refresh shall use double-checked locking so concurrent requests refresh at most once.
- Given an expired OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). token and concurrent requests
- When both attempt to refresh
- Then exactly one network refresh occurs and both requests use the refreshed token.
Conflicts
None identified yet.
Open Questions
- What is the timeline and completion criteria for retiring the
/compatentrypoint once coding-agent'sModelManagermigration finishes? - Which providers, if any, are considered tier-1 (must-ship) versus community-maintained for the purposes of future feature work?
Specification: LLMLarge Language Model. ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. Abstraction
Overview
pi-ai is a provider-centric LLMLarge Language Model. abstraction.
Each provider owns its model catalog, auth, and stream behavior and delegates to one of a small set of shared wire-protocol ("API") implementations.
A ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection routes by provider, streams flow through a unified AssistantMessageEventStream, and SDKs load lazily on first use.
Architecture
Consumer (Agent / SDKSoftware Development Kit (the embeddable programmatic API).)
|
v
+-------------------+ routes by provider id
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection |----+ (createModels / builtinProviders)
+-------------------+ |
v
+-------------------+ owns auth + catalog
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
+---------+---------+
| delegates to
v
+-------------------+ wire protocol
| API impl (lazy) | (anthropic-messages,
+---------+---------+ openai-responses, ...)
| streams
v
+-------------------+
| AssistantMessage |
| EventStream |
+-------------------+
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | string | unique | ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. identifier (e.g. anthropic) |
| name | string | not null | Display name |
| baseUrl | string | optional | API base URL |
| auth | ProviderAuth | not null | API keyApplication Programming Interface key (ambient provider authentication). and/or OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). resolvers |
| models | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.[] | not null | Catalog of models |
| api | ApiFactory | not null | Wire-protocol factory |
ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | string | unique per provider | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. identifier |
| provider | string | FK -> ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models..id | Owning provider |
| contextWindow | number | not null | Max context tokens |
| pricing | object | optional | Input/output/cache cost per million tokens |
| reasoning | object | optional | Supported thinking levels and budgets |
| compat | object | optional | ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. compatibility flags |
AssistantMessageEvent
| Field | Type | Constraints | Description |
|---|---|---|---|
| type | enum | not null | start, text_*, thinking_*, toolcall_*, done, error |
| partial | AssistantMessage | optional | Cumulative message at event time |
| contentIndex | number | optional | Associates delta with a content block |
| stopReason | enum | on done/error | stop, length, toolCall, error, aborted |
Tool
| Field | Type | Constraints | Description |
|---|---|---|---|
| name | string | not null | Tool name |
| description | string | not null | LLMLarge Language Model.-facing description |
| parameters | TSchema (TypeBox) | not null | Serializable, self-validating schema |
API Contracts
ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider..stream(model, context)
Request
| Field | Type | Required | Description |
|---|---|---|---|
| model | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | yes | Target model |
| context | Context | yes | System prompt, messages, tools, reasoning level |
| apiKey | ModelAuth | optional | Explicit auth override |
Response: an AssistantMessageEventStream (async iterable) whose .result() resolves to the final AssistantMessage.
Error contract: failures are encoded as a final event with stopReason: "error" \| "aborted" and errorMessage; the function never throws.
ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider..refresh()
Resolves the latest catalogs/auth; returns a promise. Synchronous readers (getModels/getModel) return last-known data without awaiting.
Sequences
Streaming a prompt
Consumer -> ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.: stream(model, context)
ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. -> ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.: resolve auth (store first, then ambient)
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. -> API impl: lazy-load SDKSoftware Development Kit (the embeddable programmatic API)., open stream
API impl -> Consumer: AssistantMessageEventStream
loop: yield start/text_delta/toolcall_delta ... done|error
Consumer awaits stream.result() -> AssistantMessage
OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). token refresh (double-checked locking)
Request -> resolveStoredOAuth: token expired?
yes -> acquire credentials.modify lock
-> re-check expiry (another request may have refreshed)
-> if still expired: refresh once, persist
-> release lock
no -> use cached token (zero locks)
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Routing unit | ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. (not API) | A provider owns auth + catalog; multiple providers share one wire protocol |
| SDKSoftware Development Kit (the embeddable programmatic API). loading | Lazy via .lazy.ts wrappers |
Keeps import side-effect-free and startup fast |
| Failure model | Encoded in stream | Callers always get a stream object; no try/catch around the call |
| Schema library | TypeBox | JSON-serializable, self-validating, works across providers |
| Sync vs async reads | Sync last-known + explicit refresh() |
Avoids blocking the agent loop on network |
Risks and Unknowns
- The
/compatentrypoint duplicates the provider-centric API; its removal depends on the coding-agentModelManagermigration completing. - Generated catalogs depend on live upstream APIs (models.dev, OpenRouter, Vercel); outages during generation could stall releases.
- ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-specific compatibility quirks (token counting, cache headers, thinking-level support) require ongoing manual overrides in the generator.
Out of Scope
- The agent loop and tool execution (FEAT-0002).
- SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. persistence, compaction, and branching (FEAT-0006).
- The TUITerminal User Interface (the interactive mode, and the `pi-tui` library). and interactive experience (FEAT-0003, FEAT-0004).
Test Plan: LLMLarge Language Model. ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. Abstraction
Scope
Covers pi-ai provider abstraction, streaming, auth, token tracking, model catalog generation, and cross-provider compatibility. Does not cover agent loop, session, or TUITerminal User Interface (the interactive mode, and the `pi-tui` library)..
Unit Tests
Test files under packages/ai/test/ cover:
- ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. factories and auth resolution (providers.test.ts, oauth-auth.test.ts, oauth-device-code.test.ts, env-api-keys.test.ts, google-vertex-api-key-resolution.test.ts)
- Streaming protocol (stream.test.ts, anthropic-sse-parsing.test.ts, openai-completions-.test.ts, openai-responses-.test.ts)
- Tool calling (tool-call-id-normalization.test.ts, tool-call-without-result.test.ts)
- Token/cost tracking (tokens.test.ts, total-tokens.test.ts, cache-retention.test.ts, anthropic-cache-write-1h-cost.test.ts)
- ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. catalog (providers.test.ts, fireworks-models.test.ts, together-models.test.ts, bedrock-models.test.ts, xiaomi-models.test.ts)
- Cross-provider handoff (cross-provider-handoff.test.ts)
- Error handling (error-body.test.ts, provider-error-body-passthrough.test.ts, retry.test.ts, abort.test.ts)
- Image support (image-tool-result.test.ts, images.test.ts, images-models.test.ts)
- Compatibility (compat-env.test.ts, anthropic-eager-tool-input-compat.test.ts, anthropic-temperature-compat.test.ts)
- OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flows (oauth-auth.test.ts, oauth-device-code.test.ts, github-copilot-oauth.test.ts, openai-codex-oauth.test.ts, anthropic-oauth.test.ts)
- Lazy loading (lazy-module-load.test.ts)
- Context overflow (context-overflow.test.ts, overflow.test.ts)
- Thinking/reasoning (anthropic-adaptive-thinking-models.test.ts, anthropic-force-adaptive-thinking.test.ts, max-thinking.test.ts, google-thinking-disable.test.ts, mistral-reasoning-mode.test.ts)
- Various provider-specific compat (bedrock-.test.ts, google-.test.ts, azure-openai-base-url.test.ts, node-http-proxy.test.ts)
Integration Tests
E2E tests with live provider credentials (enabled when env vars are present) cover real streaming, auth, and tool-calling flows (anthropic-eager-tool-input-e2e.test.ts, anthropic-long-cache-retention-e2e.test.ts, openai-responses-reasoning-replay-e2e.test.ts, openai-codex-stream.test.ts, bedrock-thinking-payload.test.ts).
Edge Cases and Failure Scenarios
- Surrogate pairs in messages (unicode-surrogate.test.ts)
- ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. error body passthrough (provider-error-body-passthrough.test.ts, provider-error-body-regression.test.ts)
- Cache retention edge cases (cache-retention.test.ts)
- Empty tool results (openai-responses-empty-tool-result.test.ts)
- Partial JSON cleanup (openai-responses-partial-json-cleanup.test.ts)
- Various compat shims (anthropic-empty-thinking-signature-compat.test.ts, anthropic-tool-name-normalization.test.ts)
Test Infrastructure
- Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. (
providers/faux.ts) for deterministic, network-free testing - Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. with mock/stub providers
- OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). test server for device code and PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). flow testing
Coverage Matrix
| Requirement | Test Files |
|---|---|
| FRFunctional Requirement.-01MustThe system shall expose a `ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.` collection that routes model lookups and streams by owning provider. (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection routing) | providers.test.ts, models-runtime.test.ts |
| FRFunctional Requirement.-02MustThe system shall support the major wire protocols: Anthropic Messages, OpenAI Responses, OpenAI Completions, Google Generative AI, Google Vertex, Mistral Conversations, Bedrock Converse Stream, Azure OpenAI Responses, OpenAI Codex Responses, PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. Messages, Cloudflare Workers AI, Typesafe System-One, OpenRouter Images, and llama.cpp classification. (Wire protocol support) | stream.test.ts, various anthropic/openai/bedrock/google test files |
| FRFunctional Requirement.-03MustThe system shall stream assistant responses as an async-iterable event stream emitting `start`, text/thinking/toolcall deltas, `done`, and `error` events. (Event stream) | stream.test.ts |
| FRFunctional Requirement.-04Must"aborted"` and never throw out of a stream. (Failure encoding) | error-body.test.ts, retry.test.ts, abort.test.ts |
| FRFunctional Requirement.-05MustThe system shall resolve provider authentication via a credential store first (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). or API keyApplication Programming Interface key (ambient provider authentication).), falling back to ambient env-var resolution only when nothing is stored. (Auth resolution) | oauth-auth.test.ts, env-api-keys.test.ts, compat-env.test.ts |
| FRFunctional Requirement.-06MustThe system shall support OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flows (PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). and device code) for subscription-based providers. (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flows) | oauth-auth.test.ts, oauth-device-code.test.ts |
| FRFunctional Requirement.-07MustThe system shall represent tool definitions and tool calls using TypeBox schemas that are serializable and self-validating. (TypeBox tool schemas) | tool-call-id-normalization.test.ts, validation.test.ts |
| FRFunctional Requirement.-08MustThe system shall lazily load provider SDKs on first request rather than at import time. (Lazy SDKSoftware Development Kit (the embeddable programmatic API). loading) | lazy-module-load.test.ts |
| FRFunctional Requirement.-09MustThe system shall generate its model catalog (`models.generated.ts`) from live upstream sources (models.dev, OpenRouter, Vercel AI Gateway), filtering to tool-capable models. (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. catalog generation) | providers.test.ts, bedrock-models.test.ts, fireworks-models.test.ts |
| FRFunctional Requirement.-10ShouldThe system shall track token usage and cost per request. (Token/cost tracking) | tokens.test.ts, total-tokens.test.ts |
| FRFunctional Requirement.-11ShouldThe system shall support cross-provider handoffs, converting thinking blocks from foreign providers into tagged text. (Cross-provider handoff) | cross-provider-handoff.test.ts |
| FRFunctional Requirement.-12ShouldThe system shall provide per-provider compatibility flags (e.g. `OpenAICompletionsCompat`) auto-detected from baseUrl and overridable per model. (Compat flags) | various anthropic/openai compat test files |
| FRFunctional Requirement.-13ShouldThe system shall provide a `faux` in-memory provider for deterministic testing. (Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls.) | faux-provider.test.ts |
| FRFunctional Requirement.-14MayThe system shall provide an image-generation API (`ImagesModels`) parallel to the chat API. (Image generation) | images.test.ts, images-models.test.ts |
| FRFunctional Requirement.-15MayThe system shall preserve a deprecated `/compat` entrypoint for the legacy global API during migration. (/compat entrypoint) | compat-env.test.ts |
| NFRNon-Functional Requirement.-01MustThe root `index.ts` shall be side-effect free. (Side-effect free root) | lazy-module-load.test.ts |
| NFRNon-Functional Requirement.-02MustSynchronous model reads (`getModels`, `getModel`) shall return last-known data without awaiting; `refresh()` shall be the explicit async verb. (Sync reads, async refresh) | models-runtime.test.ts |
| NFRNon-Functional Requirement.-03MustOAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). token refresh shall use double-checked locking so concurrent requests refresh at most once. (Double-checked OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). locking) | oauth-auth.test.ts |
requirements
- What is the timeline and completion criteria for retiring the
/compatentrypoint once coding-agent'sModelManagermigration finishes? - Which providers, if any, are considered tier-1 (must-ship) versus community-maintained for the purposes of future feature work?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Agent Runtime
Overview
pi-agent-core provides the stateful agent runtime that sits between the LLMLarge Language Model. abstraction (pi-ai) and application UIs.
It owns the transcript, runs the prompt-stream-tool-continue loop, executes tools (sequentially or in parallel), and manages message queues (steering and follow-up).
Durable sessions, compaction, skills, system-prompt building, and the NodeExecutionEnv moved to @earendil-works/pi-durable in 1.0.0 and are out of scope for this package.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Coding agent (pi-coding-agent) | A reliable Agent/AgentHarness to drive prompts, tools, and session lifecycle |
| SDKSoftware Development Kit (the embeddable programmatic API). / embedding users | A transport-agnostic runtime they can point at any StreamFn |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. authors | Typed hooks (tool_call, tool_result, before_provider_request, etc.) to observe and mutate behavior |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-01MustThe system shall provide an `Agent` class owning the transcript, tools, model, and thinking level, with `prompt`, `continue`, `abort`, and `subscribe` methods. | Must | The system shall provide an Agent class owning the transcript, tools, model, and thinking level, with prompt, continue, abort, and subscribe methods. |
| FRFunctional Requirement.-02MustThe system shall run an agent loop that streams an assistant response, extracts tool calls, executes them, and continues until no more tool calls or queued messages remain. | Must | The system shall run an agent loop that streams an assistant response, extracts tool calls, executes them, and continues until no more tool calls or queued messages remain. |
| FRFunctional Requirement.-03MustThe system shall call an injectable `StreamFn` (explicit per call, or installed via `setDefaultStreamFn`) to reach the LLMLarge Language Model., keeping the runtime transport-agnostic. | Must | The system shall call an injectable StreamFn (explicit per call, or installed via setDefaultStreamFn) to reach the LLMLarge Language Model., keeping the runtime transport-agnostic. |
| FRFunctional Requirement.-04MustThe system shall execute tool calls either sequentially or in parallel based on config and per-tool `executionMode`, emitting `tool_execution_*` events in completion order while persisting tool results in source order. | Must | The system shall execute tool calls either sequentially or in parallel based on config and per-tool executionMode, emitting tool_execution_* events in completion order while persisting tool results in source order. |
| FRFunctional Requirement.-05MustThe system shall validate tool arguments before execution and support `beforeToolCall`/`afterToolCall` hooks that can block, override, or terminate a tool call. | Must | The system shall validate tool arguments before execution and support beforeToolCall/afterToolCall hooks that can block, override, or terminate a tool call. |
| FRFunctional Requirement.-06MustThe system shall support message queues for steering (delivered after the current tool batch) and follow-up (delivered after the agent stops). | Must | The system shall support message queues for steering (delivered after the current tool batch) and follow-up (delivered after the agent stops). |
| FRFunctional Requirement.-07MustThe system shall support abort via an `AbortController` whose signal flows to `streamFn` and tool `execute`. | Must | The system shall support abort via an AbortController whose signal flows to streamFn and tool execute. |
| FRFunctional Requirement.-08MustThe system shall emit a stable event taxonomy: `agent_start/end`, `turn_start/end`, `message_start/update/end`, `tool_execution_start/update/end`. | Must | The system shall emit a stable event taxonomy: agent_start/end, turn_start/end, message_start/update/end, tool_execution_start/update/end. |
| FRFunctional Requirement.-09MustThe system shall consume durable sessions, compaction, skills, system-prompt building, and provider hooks from `@earendil-works/pi-durable` instead of providing its own `AgentHarness` (removed in 1.0.0). | Must | The system shall consume durable sessions, compaction, skills, system-prompt building, and provider hooks from @earendil-works/pi-durable instead of providing its own AgentHarness (removed in 1.0.0). |
| FRFunctional Requirement.-10MustThe system shall support app-extensible `AgentMessage` types via declaration merging, with `convertToLlm` bridging to pi-ai messages and an optional `transformContext` hook. | Must | The system shall support app-extensible AgentMessage types via declaration merging, with convertToLlm bridging to pi-ai messages and an optional transformContext hook. |
| FRFunctional Requirement.-11ShouldThe system shall provide a `streamProxy` function for routing LLMLarge Language Model. calls through a server with bandwidth-reduced events. | Should | The system shall provide a streamProxy function for routing LLMLarge Language Model. calls through a server with bandwidth-reduced events. |
| FRFunctional Requirement.-12ShouldThe system shall consume compaction utilities from `@earendil-works/pi-durable` instead of providing its own (removed in 1.0.0). | Should | The system shall consume compaction utilities from @earendil-works/pi-durable instead of providing its own (removed in 1.0.0). |
| FRFunctional Requirement.-13ShouldThe system shall consume branch-summarization utilities from `@earendil-works/pi-durable` instead of providing its own (removed in 1.0.0). | Should | The system shall consume branch-summarization utilities from @earendil-works/pi-durable instead of providing its own (removed in 1.0.0). |
| FRFunctional Requirement.-14ShouldThe system shall consume the `NodeExecutionEnv` (filesystem + shell) from `@earendil-works/pi-durable` instead of providing its own `./node` entrypoint (removed in 1.0.0). | Should | The system shall consume the NodeExecutionEnv (filesystem + shell) from @earendil-works/pi-durable instead of providing its own ./node entrypoint (removed in 1.0.0). |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-01MustExactly one active run per `Agent` shall be allowed; concurrent `prompt` calls shall throw. | Must | Reliability | Exactly one active run per Agent shall be allowed; concurrent prompt calls shall throw. |
| NFRNon-Functional Requirement.-02MustRun failures shall be surfaced as a synthetic failure assistant message with `stopReason: "aborted" \ | Must | Reliability | Run failures shall be surfaced as a synthetic failure assistant message with stopReason: "aborted" \ | "error" followed by agent_end. |
| NFRNon-Functional Requirement.-03MustThe run shall not be considered idle until `agent_end` listeners have settled. | Must | Correctness | The run shall not be considered idle until agent_end listeners have settled. |
| NFRNon-Functional Requirement.-04MustCoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. modules shall be platform-agnostic; Node-specific code shall live behind the `./node` entrypoint. | Must | Portability | CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. modules shall be platform-agnostic; Node-specific code shall live behind the ./node entrypoint. |
| NFRNon-Functional Requirement.-05ShouldFallible-operation error taxonomies shall live in `@earendil-works/pi-durable`, while this package surfaces run failures only as synthetic assistant messages per NFRNon-Functional Requirement.-02. | Should | Maintainability | Fallible-operation error taxonomies shall live in @earendil-works/pi-durable, while this package surfaces run failures only as synthetic assistant messages per NFRNon-Functional Requirement.-02MustRun failures shall be surfaced as a synthetic failure assistant message with `stopReason: "aborted" \. |
Constraints
- Built on
pi-aivia theStreamFnboundary; does not import provider SDKs directly. - Erasable TypeScript syntax only; ESM only.
Acceptance Criteria
Every FRFunctional Requirement. and NFRNon-Functional Requirement. shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FRFunctional Requirement.-02MustThe system shall run an agent loop that streams an assistant response, extracts tool calls, executes them, and continues until no more tool calls or queued messages remain.
- Given an agent with tools and a prompt that triggers tool calls
- When the agent loop runs to completion
- Then it streams the response, executes the tool calls, appends results, and continues until there are no more tool calls or queued messages.
- FRFunctional Requirement.-04MustThe system shall execute tool calls either sequentially or in parallel based on config and per-tool `executionMode`, emitting `tool_execution_*` events in completion order while persisting tool results in source order.
- Given a batch of parallel-capable tool calls plus one sequential tool
- When the batch executes
- Then the whole batch runs sequentially and
tool_execution_endevents fire in completion order, while persisted tool-result messages preserve assistant source order.
- FRFunctional Requirement.-05MustThe system shall validate tool arguments before execution and support `beforeToolCall`/`afterToolCall` hooks that can block, override, or terminate a tool call.
- Given a
beforeToolCallhook returning{ block: true } - When the tool is about to execute
- Then the call is blocked and an error tool result is recorded.
- Given a
- FRFunctional Requirement.-06MustThe system shall support message queues for steering (delivered after the current tool batch) and follow-up (delivered after the agent stops).
- Given a streaming agent and an incoming steering message
- When the current tool batch completes
- Then the steering message is delivered to the agent before it stops.
- FRFunctional Requirement.-07MustThe system shall support abort via an `AbortController` whose signal flows to `streamFn` and tool `execute`.
- Given an in-progress run
- When
abort()is called - Then the abort signal propagates to the active stream and executing tools.
- NFRNon-Functional Requirement.-01MustExactly one active run per `Agent` shall be allowed; concurrent `prompt` calls shall throw.
- Given an agent with an active run
- When
promptis called again concurrently - Then the second call throws rather than interleaving.
- NFRNon-Functional Requirement.-02MustRun failures shall be surfaced as a synthetic failure assistant message with `stopReason: "aborted" \
- Given a run that throws unexpectedly
- When the error is caught
- Then a synthetic failure assistant message with an appropriate
stopReasonis emitted, followed byagent_end.
Conflicts
None identified yet.
Open Questions
- Should
streamProxyremain a first-class supported deployment mode, or is it expected to migrate to an extension? - What is the long-term relationship between
AgentHarnessand the coding-agent's ownAgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.(overlap, merge, or distinct layers)?
Specification: Agent Runtime
Overview
pi-agent-core provides the low-level layer (Agent, agentLoop) plus the proxy stream (streamProxy) and shared types.
The low-level layer is transport-agnostic and delegates LLMLarge Language Model. calls to an injectable StreamFn.
Durable session storage, compaction, skills, system prompts, and the provider/session hook surface live in @earendil-works/pi-durable (moved out in 1.0.0).
Architecture
+---------------------------------------------------+
| Agent |
| transcript, tools, model/thinking, message |
| queues, lifecycle (prompt/continue/abort) |
+-------------------------+-------------------------+
| drives
v
+---------------------------------------------------+
| agentLoop |
| stream -> extract tools -> execute -> continue |
+-------------------------+-------------------------+
| calls
v
+---------------------+
| StreamFn (inject) | explicit or setDefaultStreamFn
+---------------------+ alt: streamProxy (server)
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
AgentState
| Field | Type | Constraints | Description |
|---|---|---|---|
| systemPrompt | string | optional | Active system prompt |
| model | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | not null | Active LLMLarge Language Model. model |
| thinkingLevel | ThinkingLevel | not null | Reasoning effort |
| tools | AgentTool[] | not null | Registered tools |
| messages | AgentMessage[] | not null | Transcript (app-extensible) |
| isStreaming | boolean | readonly | True while a run is active |
| streamingMessage | AssistantMessage | readonly | Partial message during stream |
| pendingToolCalls | Set | readonly | Tool calls in flight |
| errorMessage | string | readonly | Last run error, if any |
AgentTool
| Field | Type | Constraints | Description |
|---|---|---|---|
| name | string | not null | Tool name |
| description | string | not null | LLMLarge Language Model.-facing description |
| parameters | TSchema | not null | TypeBox parameter schema |
| label | string | optional | UI label |
| execute | function | not null | (id, args, signal, onUpdate) -> result |
| prepareArguments | function | optional | Pre-execution arg transform |
| executionMode | enum | optional | sequential or parallel |
AgentMessage
A union of pi-ai Message types plus app-injected custom message types via declaration merging.
convertToLlm bridges AgentMessage[] to pi-ai Message[] for the stream; transformContext optionally rewrites the AgentMessage[] before conversion.
AgentEvent
| Type | Emitted | Carries |
|---|---|---|
| agent_start / agent_end | run begin / end | - |
| turn_start / turn_end | each turn | - |
| message_start / update / end | stream lifecycle | partial/full assistant message |
| tool_execution_start / update / end | per tool | tool id, params, progress, result |
API Contracts
Agent.prompt(messages) / Agent.continue()
Request: AgentMessage[] for prompt; none for continue (resumes from current context; last message must be user/toolResult).
Response: a promise that settles after the run and its awaited agent_end listeners settle.
Results arrive via subscribe() events.
Throws if an agent is already running.
StreamFn
| Field | Type | Required | Description |
|---|---|---|---|
| model | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | yes | Target model |
| context | TranscriptContext | yes | Normalized transcript carrying system messages and tool declarations |
| options | SimpleStreamOptions | optional | Auth, signal, transport, budgets, and provider observability hooks |
Response: an AssistantMessageEventStream.
Failures must be encoded as terminal stream events rather than thrown.
Callers pass streamFn explicitly or install one via setDefaultStreamFn.
Sequences
Agent loop (single turn)
turn_start
-> transformContext (AgentMessage[])
-> convertToLlm (-> Message[])
-> StreamFn(context)
-> stream deltas -> message_update events
-> done -> message_end
-> extract tool calls
-> beforeToolCall (can block)
-> execute tools (sequential|parallel) -> tool_execution_* events
-> afterToolCall (can override/terminate)
-> append tool results to context
turn_end
-> drain steering messages? loop
-> else drain follow-up messages? outer loop
agent_end (after listeners settle)
Failure handling
run executor throws
-> handleRunFailure: synthesize assistant message (stopReason: aborted|error)
-> emit message_end, agent_end
-> finishRun: clear runtime state
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Transport boundary | Injectable StreamFn |
Enables direct, proxy, and custom backends without coupling to pi-ai |
| Message extensibility | Declaration-merged AgentMessage |
Apps add custom types without forking; convertToLlm is the bridge |
| Parallel tool execution | Completion-order events, source-order results | Parallelism for speed, deterministic transcript ordering |
| Idle definition | After agent_end listeners settle |
Listeners can perform async cleanup before idle |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. vs durable | HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend., sessions, compaction, skills, and Node fs/shell live in @earendil-works/pi-durable |
Keeps this package platform-agnostic and limited to Agent, the agent loop, the proxy stream, and types |
Risks and Unknowns
- Overlap between
AgentHarnessand coding-agent'sAgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.could lead to duplicated session/compaction logic. - The declaration-merge extensibility model is powerful but can make type errors hard to localize.
- Parallel tool execution ordering semantics are subtle; regressions here are hard to detect without targeted tests.
Out of Scope
- LLMLarge Language Model. provider abstraction and streaming protocol (FEAT-0001).
- Terminal rendering (FEAT-0003).
- Interactive TUITerminal User Interface (the interactive mode, and the `pi-tui` library)., slash commands, and the CLICommand-Line Interface (the `pi` binary). product (FEAT-0004).
- Coding-agent-specific session format and branching UI (FEAT-0006).
Test Plan: Agent Runtime
Scope
Covers pi-agent-core agent loop, tool execution, message queues, abort, events, and proxy streaming.
Durable sessions, compaction, skills, and system prompts are covered in the @earendil-works/pi-durable test suite.
Unit Tests
Test files under packages/agent/test/ cover:
- Agent loop and state machine (agent.test.ts, agent-loop.test.ts)
- Abort and cancellation flow
- Tool execution (sequential/parallel)
- Message queue steering and follow-up
- Proxy streaming (proxy.test.ts)
- End-to-end loop behavior (e2e.test.ts)
- Shared fixtures (utils/)
Test Infrastructure
- Injectable
StreamFnwith controlled behavior (mock stream event sequences) - Direct
Agentconstruction with caller-supplied tools and queue modes
Coverage Matrix
| Requirement | Test Files |
|---|---|
| FRFunctional Requirement.-01MustThe system shall provide an `Agent` class owning the transcript, tools, model, and thinking level, with `prompt`, `continue`, `abort`, and `subscribe` methods. (Agent class) | agent.test.ts |
| FRFunctional Requirement.-02MustThe system shall run an agent loop that streams an assistant response, extracts tool calls, executes them, and continues until no more tool calls or queued messages remain. (Agent loop) | agent-loop.test.ts |
| FRFunctional Requirement.-03MustThe system shall call an injectable `StreamFn` (explicit per call, or installed via `setDefaultStreamFn`) to reach the LLMLarge Language Model., keeping the runtime transport-agnostic. (Injectable StreamFn) | agent-loop.test.ts |
| FRFunctional Requirement.-04MustThe system shall execute tool calls either sequentially or in parallel based on config and per-tool `executionMode`, emitting `tool_execution_*` events in completion order while persisting tool results in source order. (Sequential/parallel tool execution) | agent-loop.test.ts |
| FRFunctional Requirement.-05MustThe system shall validate tool arguments before execution and support `beforeToolCall`/`afterToolCall` hooks that can block, override, or terminate a tool call. (Tool hooks) | agent.test.ts |
| FRFunctional Requirement.-06MustThe system shall support message queues for steering (delivered after the current tool batch) and follow-up (delivered after the agent stops). (Message queues) | agent.test.ts |
| FRFunctional Requirement.-07MustThe system shall support abort via an `AbortController` whose signal flows to `streamFn` and tool `execute`. (Abort) | agent.test.ts |
| FRFunctional Requirement.-08MustThe system shall emit a stable event taxonomy: `agent_start/end`, `turn_start/end`, `message_start/update/end`, `tool_execution_start/update/end`. (Event taxonomy) | agent-loop.test.ts |
| FRFunctional Requirement.-09MustThe system shall consume durable sessions, compaction, skills, system-prompt building, and provider hooks from `@earendil-works/pi-durable` instead of providing its own `AgentHarness` (removed in 1.0.0). (AgentHarness) | (moved to @earendil-works/pi-durable in 1.0.0; covered in its test suite) |
| FRFunctional Requirement.-10MustThe system shall support app-extensible `AgentMessage` types via declaration merging, with `convertToLlm` bridging to pi-ai messages and an optional `transformContext` hook. (Extensible AgentMessage) | agent.test.ts |
| FRFunctional Requirement.-11ShouldThe system shall provide a `streamProxy` function for routing LLMLarge Language Model. calls through a server with bandwidth-reduced events. (Proxy streaming) | proxy.test.ts |
| FRFunctional Requirement.-12ShouldThe system shall consume compaction utilities from `@earendil-works/pi-durable` instead of providing its own (removed in 1.0.0). (CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry.) | (moved to @earendil-works/pi-durable in 1.0.0; covered in its test suite) |
| FRFunctional Requirement.-13ShouldThe system shall consume branch-summarization utilities from `@earendil-works/pi-durable` instead of providing its own (removed in 1.0.0). (Branch summarization) | (covered in pi-durable test suite) |
| FRFunctional Requirement.-14ShouldThe system shall consume the `NodeExecutionEnv` (filesystem + shell) from `@earendil-works/pi-durable` instead of providing its own `./node` entrypoint (removed in 1.0.0). (NodeExecutionEnv) | (moved to @earendil-works/pi-durable in 1.0.0; covered in its test suite) |
| NFRNon-Functional Requirement.-01MustExactly one active run per `Agent` shall be allowed; concurrent `prompt` calls shall throw. (Single concurrent run) | agent.test.ts |
| NFRNon-Functional Requirement.-02MustRun failures shall be surfaced as a synthetic failure assistant message with `stopReason: "aborted" \ (Failure as assistant message) | agent.test.ts |
| NFRNon-Functional Requirement.-04MustCoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. modules shall be platform-agnostic; Node-specific code shall live behind the `./node` entrypoint. (Platform-agnostic core) | (module structure) |
requirements
- Should
streamProxyremain a first-class supported deployment mode, or is it expected to migrate to an extension? - What is the long-term relationship between
AgentHarnessand the coding-agent's ownAgentSession(overlap, merge, or distinct layers)?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Terminal UI Framework
Overview
pi-tui is a minimal terminal UI framework with differential rendering and synchronized output for flicker-free interactive CLICommand-Line Interface (the `pi` binary). applications.
It is custom-built (no React/Ink/VDOM): components are plain classes that return styled strings, and a hand-written renderer diffs the new frame against the previous one and writes minimal escape sequences.
It powers the coding agent's interactive mode and is reusable by any terminal application.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Coding agent interactive mode | Primitive components (editor, text, markdown, lists, overlays) and flicker-free rendering |
| SDKSoftware Development Kit (the embeddable programmatic API). / library users | A terminal-agnostic component framework they can target |
| End users | Smooth, responsive terminal rendering across platforms and terminals |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-01MustThe system shall provide a `Component` model where components implement `render(width): string[]` and optional `handleInput`. | Must | The system shall provide a Component model where components implement render(width): string[] and optional handleInput. |
| FRFunctional Requirement.-02MustThe system shall provide a `TUITerminal User Interface (the interactive mode, and the `pi-tui` library).` manager that composes components, manages focus, overlays, and drives rendering. | Must | The system shall provide a TUITerminal User Interface (the interactive mode, and the `pi-tui` library). manager that composes components, manages focus, overlays, and drives rendering. |
| FRFunctional Requirement.-03MustThe system shall perform differential rendering, writing only changed line ranges between frames. | Must | The system shall perform differential rendering, writing only changed line ranges between frames. |
| FRFunctional Requirement.-04MustThe system shall wrap updates in synchronized output escape sequences for atomic, flicker-free rendering. | Must | The system shall wrap updates in synchronized output escape sequences for atomic, flicker-free rendering. |
| FRFunctional Requirement.-05MustThe system shall throttle rendering to a capped frame rate and coalesce multiple invalidations per tick. | Must | The system shall throttle rendering to a capped frame rate and coalesce multiple invalidations per tick. |
| FRFunctional Requirement.-06MustThe system shall provide reusable components: `Editor`, `Text`, `TruncatedText`, `Input`, `Box`, `Markdown`, `SelectList`, `SettingsList`, `Loader`, `CancellableLoader`, `Image`, `Spacer`. | Must | The system shall provide reusable components: Editor, Text, TruncatedText, Input, Box, Markdown, SelectList, SettingsList, Loader, CancellableLoader, Image, Spacer. |
| FRFunctional Requirement.-07MustThe system shall provide an `Overlay` system with anchor-based, percentage, and absolute positioning, plus focus restore. | Must | The system shall provide an Overlay system with anchor-based, percentage, and absolute positioning, plus focus restore. |
| FRFunctional Requirement.-08MustThe system shall provide key handling with Kitty keyboard protocol negotiation and legacy sequence fallback. | Must | The system shall provide key handling with Kitty keyboard protocol negotiation and legacy sequence fallback. |
| FRFunctional Requirement.-09MustThe system shall provide column-aware string utilities (`visibleWidth`, `truncateToWidth`, `sliceByColumn`, `wrapTextWithAnsi`) handling ANSI codes and wide/CJKChinese, Japanese, Korean (terminal width handling for wide characters). characters. | Must | The system shall provide column-aware string utilities (visibleWidth, truncateToWidth, sliceByColumn, wrapTextWithAnsi) handling ANSI codes and wide/CJKChinese, Japanese, Korean (terminal width handling for wide characters). characters. |
| FRFunctional Requirement.-10MustThe system shall be terminal-agnostic via a `Terminal` interface, with `ProcessTerminal` for production. | Must | The system shall be terminal-agnostic via a Terminal interface, with ProcessTerminal for production. |
| FRFunctional Requirement.-11ShouldThe system shall support terminal image protocols (Kitty and iTerm2 inline images) with capability detection. | Should | The system shall support terminal image protocols (Kitty and iTerm2 inline images) with capability detection. |
| FRFunctional Requirement.-12ShouldThe system shall support IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows by emitting a zero-width cursor marker and positioning the hardware cursor. | Should | The system shall support IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows by emitting a zero-width cursor marker and positioning the hardware cursor. |
| FRFunctional Requirement.-13ShouldThe system shall provide a keybindings manager with default TUITerminal User Interface (the interactive mode, and the `pi-tui` library). keybindings. | Should | The system shall provide a keybindings manager with default TUITerminal User Interface (the interactive mode, and the `pi-tui` library). keybindings. |
| FRFunctional Requirement.-14ShouldThe system shall detect terminal color scheme (light/dark) via OSC 11. | Should | The system shall detect terminal color scheme (light/dark) via OSC 11. |
| FRFunctional Requirement.-15ShouldThe system shall provide fuzzy match/filter and autocomplete providers (slash commands + file paths). | Should | The system shall provide fuzzy match/filter and autocomplete providers (slash commands + file paths). |
| FRFunctional Requirement.-16MayThe system shall ship native addons for win32 and darwin to report modifier-key state. | May | The system shall ship native addons for win32 and darwin to report modifier-key state. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-01MustComponents shall return lines that do not exceed the provided width; the framework shall error otherwise. | Must | Correctness | Components shall return lines that do not exceed the provided width; the framework shall error otherwise. |
| NFRNon-Functional Requirement.-02MustFirst render and full re-render strategies shall clear scrollback correctly; differential updates shall never leave stale content. | Must | Performance | First render and full re-render strategies shall clear scrollback correctly; differential updates shall never leave stale content. |
| NFRNon-Functional Requirement.-03MustEach rendered line shall append a full SGR reset and OSC 8 hyperlink reset so styles do not carry across lines. | Must | Compatibility | Each rendered line shall append a full SGR reset and OSC 8 hyperlink reset so styles do not carry across lines. |
| NFRNon-Functional Requirement.-04ShouldThe framework shall be testable against a virtual terminal (xterm headless) for deterministic render assertions. | Should | Testability | The framework shall be testable against a virtual terminal (xterm headless) for deterministic render assertions. |
| NFRNon-Functional Requirement.-05ShouldRendering shall be capped at approximately 60 fps (`MIN_RENDER_INTERVAL_MS = 16`). | Should | Performance | Rendering shall be capped at approximately 60 fps (MIN_RENDER_INTERVAL_MS = 16). |
Constraints
- No React, no Ink, no virtual DOM; imperative component model.
- Dependencies kept minimal (
get-east-asian-width,marked). - Erasable TypeScript syntax only; ESM only.
Acceptance Criteria
Every FRFunctional Requirement. and NFRNon-Functional Requirement. shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FRFunctional Requirement.-03MustThe system shall perform differential rendering, writing only changed line ranges between frames.
- Given a previous frame and a new frame differing on a contiguous range of lines
- When a render is requested
- Then only the changed range is written, with the cursor moved to the first changed line and clear-to-end applied.
- FRFunctional Requirement.-04MustThe system shall wrap updates in synchronized output escape sequences for atomic, flicker-free rendering.
- Given any render update
- When the update is written to the terminal
- Then the bytes are wrapped in synchronized output (
\x1b[?2026h...\x1b[?2026l).
- FRFunctional Requirement.-07MustThe system shall provide an `Overlay` system with anchor-based, percentage, and absolute positioning, plus focus restore.
- Given a focused overlay that is temporarily replaced by another overlay
- When the replacement releases focus
- Then the original overlay reclaims focus via the focus-restore state machine.
- FRFunctional Requirement.-09MustThe system shall provide column-aware string utilities (`visibleWidth`, `truncateToWidth`, `sliceByColumn`, `wrapTextWithAnsi`) handling ANSI codes and wide/CJKChinese, Japanese, Korean (terminal width handling for wide characters). characters.
- Given a string containing ANSI codes and wide CJKChinese, Japanese, Korean (terminal width handling for wide characters). characters
- When
visibleWidthandtruncateToWidthare applied - Then the visible width and truncation account for display columns, not raw character count.
- NFRNon-Functional Requirement.-01MustComponents shall return lines that do not exceed the provided width; the framework shall error otherwise.
- Given a component that returns a line longer than
width - When rendered
- Then the framework raises an error rather than overflowing the terminal.
- Given a component that returns a line longer than
- NFRNon-Functional Requirement.-03MustEach rendered line shall append a full SGR reset and OSC 8 hyperlink reset so styles do not carry across lines.
- Given consecutive rendered lines with different styling
- When composited
- Then each line resets SGR state so no style leaks into the next line.
Conflicts
None identified yet.
Open Questions
- Is the native modifier-key addon (
native-modifiers.ts) expected to gain a Linux path, or is the protocol fallback sufficient there? - What is the policy for adding new built-in components versus leaving them to consumers?
Specification: Terminal UI Framework
Overview
pi-tui is an imperative terminal UI framework.
Components return arrays of pre-styled strings; the TUITerminal User Interface (the interactive mode, and the `pi-tui` library). manager diffs the new array against the previous frame and emits minimal escape sequences wrapped in synchronized output.
There is no virtual DOM; callers mutate components then request a render.
Architecture
+-------------------+ mutate + requestRender
| Application code |-------------------------+
+-------------------+ |
| uses |
v v
+-------------------+ render(width) +-------------+
| Components |------------------>| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). |
| (Editor, Text, | | (manager) |
| Markdown, ...) | +------+------+
+-------------------+ | composites overlays
| diffs vs previousLines
v
+---------------------+
| differential write |
| (sync output, ~60fps)|
+----------+----------+
|
v
+---------------------+
| Terminal interface |
| (ProcessTerminal / |
| VirtualTerminal) |
+---------------------+
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
Component
| Field | Type | Constraints | Description |
|---|---|---|---|
| render | (width: number) => string[] | required | Returns styled lines, each <= width |
| handleInput | (data) => boolean | optional | Returns true if input consumed |
| wantsKeyRelease | boolean | optional | Claims key release |
| invalidate | () => void | required | Marks the component dirty |
OverlayOptions
| Field | Type | Constraints | Description |
|---|---|---|---|
| anchor | object | optional | Positioning anchor |
| margins | object | optional | Edge margins |
| visible | () => boolean | optional | Visibility callback |
| nonCapturing | boolean | optional | Does not capture focus |
Key
| Field | Type | Constraints | Description |
|---|---|---|---|
| key | string | optional | Logical key name |
| ctrl/alt/shift | boolean | optional | Modifiers |
| paste | boolean | optional | Bracketed paste flag |
API Contracts
TUITerminal User Interface (the interactive mode, and the `pi-tui` library)..start() / TUITerminal User Interface (the interactive mode, and the `pi-tui` library)..stop()
Begins/ends raw mode, Kitty keyboard negotiation, and the render loop.
requestRender() schedules a throttled render; setFocus, showOverlay/hideOverlay manage composition.
Keybindings
matchesKey(keyData, binding) compares parsed keys against configurable bindings.
Defaults live in TUI_KEYBINDINGS; consumers override via setKeybindings.
Sequences
Differential render
application -> component.invalidate() / TUITerminal User Interface (the interactive mode, and the `pi-tui` library)..requestRender()
TUITerminal User Interface (the interactive mode, and the `pi-tui` library). (next tick, if >= MIN_RENDER_INTERVAL_MS):
render each focused component -> lines[]
composite overlays into lines[]
extract cursor marker -> compute hardware cursor position
if first render: output all lines (no scrollback clear)
elif full re-render: clear screen + home + clear scrollback; delete Kitty images
else (differential):
find first/last changed line vs previousLines
move cursor to first changed line; clear to end
write only changed range
wrap all output in synchronized output escapes
handle appended/deleted lines and viewport scroll
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Rendering model | Imperative, string-line diff | No VDOM overhead; minimal escape output |
| Atomicity | Synchronized output (?2026h/l) |
Flicker-free even across slow connections |
| Throttling | ~60fps with nextTick coalescing | Bounding CPU while staying responsive |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). cursor | Zero-width APC marker | Keeps fake cursor while positioning hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). |
| Line resets | Full SGR + OSC 8 reset per line | Prevents style/hyperlink leakage across lines |
| Terminal abstraction | Terminal interface |
ProcessTerminal prod, VirtualTerminal tests |
Risks and Unknowns
- Differential rendering correctness depends on accurate change detection; subtle bugs (Kitty image ranges, overlay compositing above viewport) require regression tests.
- Terminal compatibility variance (Kitty support, synchronized output, color scheme reporting) means fallback paths must be exercised.
- The overlay focus-restore state machine has many states ("eligible"/"blocked") and is a likely source of regressions.
Out of Scope
- LLMLarge Language Model. streaming and provider abstraction (FEAT-0001).
- Agent loop and tool execution (FEAT-0002).
- The interactive coding agent product built on top of this framework (FEAT-0004).
Test Plan: Terminal UI Framework
Scope
Covers pi-tui rendering pipeline, components, key handling, terminal abstraction, overlays, and differential rendering.
Unit Tests
Test files under packages/tui/test/ cover:
- Differential render engine (tui-render.test.ts, tui-shrink.test.ts, tui-cell-size-input.test.ts, tui-overlay-style-leak.test.ts)
- Editor component (editor.test.ts)
- Input handling (input.test.ts, keys.test.ts)
- Keybindings (keybindings.test.ts)
- Markdown rendering (markdown.test.ts)
- SelectList component (select-list.test.ts, truncated-text.test.ts)
- Overlay system (overlay-options.test.ts, overlay-short-content.test.ts, overlay-non-capturing.test.ts)
- Autocomplete (autocomplete.test.ts)
- Fuzzy matching (fuzzy.test.ts)
- Terminal abstraction (terminal.test.ts, terminal-colors.test.ts, terminal-image.test.ts)
- String utilities (truncate-to-width.test.ts, wrap-ansi.test.ts, tab-width.test.ts, word-navigation.test.ts)
- Stdin buffer (stdin-buffer.test.ts)
- Regression tests (regression-overlay-cjk-boundary.test.ts, regression-regional-indicator-width.test.ts, bug-regression-isimageline-startswith-bug.test.ts)
- Additional coverage: alt-screen rendering (tui-alt-screen.test.ts), layout (layout.test.ts), colors/OKLab (colors.test.ts), LaTeX (latex.test.ts), settings list (settings-list.test.ts), mouse components (mouse-components.test.ts), program status (program-status.test.ts), wheel scroll (wheel-scroll.test.ts), IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows)./cell-size input (tui-cell-size-input.test.ts), style-leak (tui-overlay-style-leak.test.ts), shrink (tui-shrink.test.ts), visible width (visible-width.test.ts), slice-by-column ANSI order (regression-slice-by-column-ansi-order.test.ts), SIGWINCH kill EACCES (regression-sigwinch-kill-eacces.test.ts), native platform/module-path/clipboard (native-platform.test.ts, native-module-path.test.ts, native-clipboard-linux.test.ts), editor history keybindings (editor-history-keybindings.test.ts), skill slash autocomplete (autocomplete-skill-slash.test.ts)
Integration Tests
Terminal tests run against VirtualTerminal for deterministic render assertions without a real terminal.
Edge Cases and Failure Scenarios
- CJKChinese, Japanese, Korean (terminal width handling for wide characters). character boundary in overlays
- Regional indicator (flag) width
- Tab width handling
- Image protocol capability detection fallback
- Non-capturing overlay focus management
- Short overlay content positioning
Test Infrastructure
VirtualTerminalfor headless render assertions- Mock terminal color scheme (OSC 11)
- Kitty keyboard protocol negotiation simulation
Coverage Matrix
| Requirement | Test Files |
|---|---|
| FRFunctional Requirement.-01MustThe system shall provide a `Component` model where components implement `render(width): string[]` and optional `handleInput`. (Component model) | editor.test.ts, input.test.ts, markdown.test.ts |
| FRFunctional Requirement.-02MustThe system shall provide a `TUITerminal User Interface (the interactive mode, and the `pi-tui` library).` manager that composes components, manages focus, overlays, and drives rendering. (TUITerminal User Interface (the interactive mode, and the `pi-tui` library). manager) | tui-render.test.ts |
| FRFunctional Requirement.-03MustThe system shall perform differential rendering, writing only changed line ranges between frames. (Differential rendering) | tui-render.test.ts |
| FRFunctional Requirement.-04MustThe system shall wrap updates in synchronized output escape sequences for atomic, flicker-free rendering. (Synchronized output) | tui-render.test.ts |
| FRFunctional Requirement.-05MustThe system shall throttle rendering to a capped frame rate and coalesce multiple invalidations per tick. (Frame throttling) | tui-render.test.ts |
| FRFunctional Requirement.-06MustThe system shall provide reusable components: `Editor`, `Text`, `TruncatedText`, `Input`, `Box`, `Markdown`, `SelectList`, `SettingsList`, `Loader`, `CancellableLoader`, `Image`, `Spacer`. (Built-in components) | editor.test.ts, markdown.test.ts, select-list.test.ts |
| FRFunctional Requirement.-07MustThe system shall provide an `Overlay` system with anchor-based, percentage, and absolute positioning, plus focus restore. (Overlay system) | overlay-*.test.ts |
| FRFunctional Requirement.-08MustThe system shall provide key handling with Kitty keyboard protocol negotiation and legacy sequence fallback. (Key handling) | keys.test.ts, keybindings.test.ts |
| FRFunctional Requirement.-09MustThe system shall provide column-aware string utilities (`visibleWidth`, `truncateToWidth`, `sliceByColumn`, `wrapTextWithAnsi`) handling ANSI codes and wide/CJKChinese, Japanese, Korean (terminal width handling for wide characters). characters. (Column-aware string utils) | truncate-to-width.test.ts, wrap-ansi.test.ts, tab-width.test.ts |
| FRFunctional Requirement.-10MustThe system shall be terminal-agnostic via a `Terminal` interface, with `ProcessTerminal` for production. (Terminal interface) | terminal.test.ts |
| FRFunctional Requirement.-11ShouldThe system shall support terminal image protocols (Kitty and iTerm2 inline images) with capability detection. (Terminal images) | terminal-image.test.ts |
| FRFunctional Requirement.-12ShouldThe system shall support IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows by emitting a zero-width cursor marker and positioning the hardware cursor. (IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). support) | (covered by tui-render cursor positioning) |
| FRFunctional Requirement.-13ShouldThe system shall provide a keybindings manager with default TUITerminal User Interface (the interactive mode, and the `pi-tui` library). keybindings. (Keybindings manager) | keybindings.test.ts |
| FRFunctional Requirement.-14ShouldThe system shall detect terminal color scheme (light/dark) via OSC 11. (Color scheme detection) | terminal-colors.test.ts |
| FRFunctional Requirement.-15ShouldThe system shall provide fuzzy match/filter and autocomplete providers (slash commands + file paths). (Fuzzy match/autocomplete) | fuzzy.test.ts, autocomplete.test.ts |
| FRFunctional Requirement.-16MayThe system shall ship native addons for win32 and darwin to report modifier-key state. (Native addons) | native-platform.test.ts, native-module-path.test.ts, native-clipboard-linux.test.ts |
| NFRNon-Functional Requirement.-01MustComponents shall return lines that do not exceed the provided width; the framework shall error otherwise. (Width validation) | tui-render.test.ts |
| NFRNon-Functional Requirement.-03MustEach rendered line shall append a full SGR reset and OSC 8 hyperlink reset so styles do not carry across lines. (SGR resets per line) | tui-render.test.ts |
| NFRNon-Functional Requirement.-04ShouldThe framework shall be testable against a virtual terminal (xterm headless) for deterministic render assertions. (Virtual terminal testing) | terminal.test.ts |
requirements
- Is the native modifier-key addon (
native-modifiers.ts) expected to gain a Linux path, or is the protocol fallback sufficient there? - What is the policy for adding new built-in components versus leaving them to consumers?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Interactive Coding Agent
Overview
pi-coding-agent is the CLICommand-Line Interface (the `pi` binary). product: a minimal terminal coding harness built around four core tools (read, bash, edit, write), designed to be extended.
It wires pi-ai, pi-agent-core, and pi-tui into an AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. that drives prompts, manages models and thinking levels, executes built-in tools, and renders an interactive TUITerminal User Interface (the interactive mode, and the `pi-tui` library)..
It also exposes print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes plus an embeddable SDKSoftware Development Kit (the embeddable programmatic API)..
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users (developers) | A reliable interactive coding workflow with model choice and responsive UI |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. / SDKSoftware Development Kit (the embeddable programmatic API). authors | A stable SDKSoftware Development Kit (the embeddable programmatic API). surface and clear extension boundaries |
| Maintainers | A minimal core that stays small; features belong in extensions when possible |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-01MustThe system shall provide a `pi` CLICommand-Line Interface (the `pi` binary). with an interactive TUITerminal User Interface (the interactive mode, and the `pi-tui` library). as the default mode. | Must | The system shall provide a pi CLICommand-Line Interface (the `pi` binary). with an interactive TUITerminal User Interface (the interactive mode, and the `pi-tui` library). as the default mode. |
| FRFunctional Requirement.-02MustThe system shall provide four default built-in tools: `read`, `bash`, `edit`, `write`, and a read-only tool set (`read`, `grep`, `find`, `ls`). | Must | The system shall provide four default built-in tools: read, bash, edit, write, and a read-only tool set (read, grep, find, ls). |
| FRFunctional Requirement.-03MustThe system shall provide an `AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.` core that drives the prompt loop, manages model and thinking level, runs compaction, executes bash, and exports HTML. | Must | The system shall provide an AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. core that drives the prompt loop, manages model and thinking level, runs compaction, executes bash, and exports HTML. |
| FRFunctional Requirement.-04MustThe system shall resolve model selection via `provider/id:thinking` patterns, scoped model cycling, and in-TUITerminal User Interface (the interactive mode, and the `pi-tui` library). `/model` and `/scoped-models` commands. | Must | The system shall resolve model selection via provider/id:thinking patterns, scoped model cycling, and in-TUITerminal User Interface (the interactive mode, and the `pi-tui` library). /model and /scoped-models commands. |
| FRFunctional Requirement.-05MustThe system shall provide built-in slash commands (`settings`, `model`, `export`, `fork`, `tree`, `login`, `logout`, `new`, `compact`, `resume`, `reload`, `quit`, and others). | Must | The system shall provide built-in slash commands (settings, model, export, fork, tree, login, logout, new, compact, resume, reload, quit, and others). |
| FRFunctional Requirement.-06MustThe system shall support run modes: interactive (default), print (`-p`), JSON (`--mode json`), RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). (`--mode rpc`), and SDKSoftware Development Kit (the embeddable programmatic API).. | Must | The system shall support run modes: interactive (default), print (-p), JSON (--mode json), RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). (--mode rpc), and SDKSoftware Development Kit (the embeddable programmatic API).. |
| FRFunctional Requirement.-07MustThe system shall provide global and project settings (`~/.pi/agent/settings.json`, `.pi/settings.json`) with file locking and deep merge, plus keybindings. | Must | The system shall provide global and project settings (~/.pi/agent/settings.json, .pi/settings.json) with file locking and deep merge, plus keybindings. |
| FRFunctional Requirement.-08MustThe system shall gate project resources (settings, extensions, context files) behind a project-trust decision. | Must | The system shall gate project resources (settings, extensions, context files) behind a project-trust decision. |
| FRFunctional Requirement.-09MustThe system shall discover and load resources (extensions, skills, prompt templates, themes, AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root./CLAUDE.md) from global, project, and package sources. | Must | The system shall discover and load resources (extensions, skills, prompt templates, themes, AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root./CLAUDE.md) from global, project, and package sources. |
| FRFunctional Requirement.-10MustThe system shall build the system prompt from base prompt, project context, skills, date, and cwd. | Must | The system shall build the system prompt from base prompt, project context, skills, date, and cwd. |
| FRFunctional Requirement.-11ShouldThe system shall support theme loading (JSON themes, light/dark auto, hot-reload). | Should | The system shall support theme loading (JSON themes, light/dark auto, hot-reload). |
| FRFunctional Requirement.-12ShouldThe system shall provide update-check and install-telemetry endpoints, disable-able via env flags or `--offline`. | Should | The system shall provide update-check and install-telemetry endpoints, disable-able via env flags or --offline. |
| FRFunctional Requirement.-13ShouldThe system shall support first-time setup flow (theme + analytics opt-in) behind an experimental flag. | Should | The system shall support first-time setup flow (theme + analytics opt-in) behind an experimental flag. |
| FRFunctional Requirement.-14MayThe system shall provide a `pi install/remove/update/list/config` package manager for pi packages (npm/git). | May | The system shall provide a pi install/remove/update/list/config package manager for pi packages (npm/git). |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-01MustThe package shall target Node `>=22.19.0` and use erasable TypeScript syntax only. | Must | Compatibility | The package shall target Node >=22.19.0 and use erasable TypeScript syntax only. |
| NFRNon-Functional Requirement.-02MustA hot-swap runtime shall tear down and recreate cwd-bound services when switching sessions or cwds. | Must | Reliability | A hot-swap runtime shall tear down and recreate cwd-bound services when switching sessions or cwds. |
| NFRNon-Functional Requirement.-03MustThe system shall not include an in-process sandbox; containerization is delegated to external sandboxes (documented). | Must | Security | The system shall not include an in-process sandbox; containerization is delegated to external sandboxes (documented). |
| NFRNon-Functional Requirement.-04ShouldStartup shall defer non-essential network operations when `--offline` / `PI_OFFLINE=1` is set. | Should | Performance | Startup shall defer non-essential network operations when --offline / PI_OFFLINE=1 is set. |
| NFRNon-Functional Requirement.-05ShouldThe published CLICommand-Line Interface (the `pi` binary). shall include a generated npm shrinkwrap pinning transitive deps. | Should | Maintainability | The published CLICommand-Line Interface (the `pi` binary). shall include a generated npm shrinkwrap pinning transitive deps. |
Constraints
- CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. is minimal: no built-in MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension)., sub-agents, plan mode, or permission popups (extensions provide these).
- Direct dependencies pinned to exact versions; lockfile is ground truth.
- New issues/PRs from new contributors are auto-closed by default (maintainer gate).
Acceptance Criteria
Every FRFunctional Requirement. and NFRNon-Functional Requirement. shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FRFunctional Requirement.-02MustThe system shall provide four default built-in tools: `read`, `bash`, `edit`, `write`, and a read-only tool set (`read`, `grep`, `find`, `ls`).
- Given a default agent session
- When tools are registered
- Then
read,bash,edit,writeare available, and the read-only set restricts toread,grep,find,ls.
- FRFunctional Requirement.-03MustThe system shall provide an `AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.` core that drives the prompt loop, manages model and thinking level, runs compaction, executes bash, and exports HTML.
- Given a user prompt
- When submitted to
AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume..prompt() - Then it expands commands/templates, emits lifecycle events, streams the response, executes tools, handles retries/compaction, and persists entries to the session file.
- FRFunctional Requirement.-06MustThe system shall support run modes: interactive (default), print (`-p`), JSON (`--mode json`), RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). (`--mode rpc`), and SDKSoftware Development Kit (the embeddable programmatic API)..
- Given the CLICommand-Line Interface (the `pi` binary). invoked with
-p,--mode json,--mode rpc, or no flag - When it starts
- Then it runs in print, JSON, RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode)., or interactive mode respectively.
- Given the CLICommand-Line Interface (the `pi` binary). invoked with
- FRFunctional Requirement.-08MustThe system shall gate project resources (settings, extensions, context files) behind a project-trust decision.
- Given an untrusted project
- When the agent starts
- Then project resources are not loaded until a trust decision is recorded (or
--approveis passed non-interactively).
- NFRNon-Functional Requirement.-02MustA hot-swap runtime shall tear down and recreate cwd-bound services when switching sessions or cwds.
- Given an active interactive session
- When the user switches sessions or cwd via
/forkor/tree - Then the runtime tears down and recreates cwd-bound services without leaking state.
Conflicts
None identified yet.
Open Questions
- Should the experimental first-time setup flow graduate to default behavior, and on what timeline?
- What is the policy for promoting a widely-used extension into a built-in tool or command?
Sync drift: 2026-10-13
Full sync vs packages/coding-agent/src. No body edits (status done); deltas recorded here.
- Constraints "no built-in MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension)." is stale. Code ships built-in replaceable
extensions in
src/extensions/:mcp/(mcp/index.ts,config.ts,runtime.ts,tools.ts,resources.ts,oauth.ts,cli.ts,ui.ts),codemode/(tool.ts,execute.ts,worker.ts,renderer.ts), andtool-search/(tool.ts), wired viasrc/extensions/index.tsbuiltInExtensions(llama.cpp, codemode, tool-search, mcp). Sub-agents / plan-mode / permission popups remain extension-provided (seeexamples/extensions/subagent/,plan-mode/,permission-gate.ts), so only the "no built-in MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension)." clause (and by extension codemode/tool-search) drifts. - FRFunctional Requirement.-02MustThe system shall provide four default built-in tools: `read`, `bash`, `edit`, `write`, and a read-only tool set (`read`, `grep`, `find`, `ls`). / Overview miss
codemode,tool_search,mcp__<server>__<tool>. CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. default stays four tools (read,bash,edit,write) plus the read-only set, but sessions additionally expose thecodemodemodel-only tool (QuickJS sandbox batching nested calls), thetool_searchmodel-only BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. discovery tool, MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). tools (mcp__*, default exposurecodemode, plusdeferred/direct/hiddenand per-tooltoolExposure), and MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). resource tools (list_mcp_resources,list_mcp_resource_templates,read_mcp_resource). A future requirements revision should extend FRFunctional Requirement.-02MustThe system shall provide four default built-in tools: `read`, `bash`, `edit`, `write`, and a read-only tool set (`read`, `grep`, `find`, `ls`). or add an FRFunctional Requirement. for built-in MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension)./codemode/tool-search exposure modes. - No PiClient remote-attach drift.
packages/protocol,packages/client,packages/serverdo not exist; artifacts make no remote-session-attach claim. Nothing to correct. - No pi-env integration in scope.
grep pi-env packages/coding-agentreturns no matches; no artifact claims it. Nothing to correct.
Specification: Interactive Coding Agent
Overview
pi-coding-agent composes the three libraries into a CLICommand-Line Interface (the `pi` binary). product.
main() parses args, resolves project trust, builds a SessionManager and AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch., then dispatches to a run mode.
The AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. is the central class shared by all modes; InteractiveMode renders events via pi-tui.
Architecture
cli.ts -> main() -------------------------------+
args parse, migrations, trust resolve |
createSessionManager, createAgentSessionRuntime|
| |
v |
+-------------------+ owns session + |
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | cwd-bound services |
| Runtime | (hot-swap on |
+---------+---------+ fork/switch/tree) |
| |
v |
+-------------------+ delegates to |
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. |----> pi-agent-core Agent |
| (prompt loop, |----> ModelRegistry (auth)|
| compaction, bash,|----> pi-ai streamSimple |
| tools, export) | |
+---------+---------+ |
| events |
v |
+------+------+------+ |
| | | |
v v v |
Interactive Print RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). <-- modes dispatch-+
Mode (pi-tui) (text/json)
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
Settings (excerpt)
| Field | Type | Description |
|---|---|---|
| defaultModel | string | provider/id:thinking |
| transport | enum | sse / websocket / auto |
| compaction | object | Thresholds and behavior |
| extensions/skills/prompts/themes | string[] | Enabled resource globs |
| telemetry/analytics | object | Opt-in/out flags |
| projectTrust | object | Trust defaults |
ResourceLoader sources
| Source | Path | Trust-gated |
|---|---|---|
| Global user | ~/.pi/agent/, ~/.agents/ |
No |
| Project | .pi/, .agents/, AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root., CLAUDE.md |
Yes |
| Package | installed pi packages | Per-source |
Tool sets
| Set | Tools |
|---|---|
| Default (4) | read, bash, edit, write |
| Read-only | read, grep, find, ls |
API Contracts
SDKSoftware Development Kit (the embeddable programmatic API).: createAgentSession()
Factory building an AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. wired with a resource loader, model registry, settings, and extension runner.
Exposes prompt, subscribe, state, abort, setModel, setThinkingLevel, compact, fork.
CLICommand-Line Interface (the `pi` binary). flags (excerpt)
| Flag | Effect |
|---|---|
-p / --prompt |
Print mode (single-shot) |
--mode json / --mode rpc |
JSON event stream / RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol |
-c / -r / --fork / --session |
Continue / resume / fork / specific session |
-t / -xt / -nbt / -nt |
Tool allowlist / exclude / no-builtin / none |
--model / --models |
ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. / scoped cycling set |
--approve / --no-approve |
Non-interactive project trust |
--offline |
Disable startup network ops |
Sequences
Interactive prompt
user input -> AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume..prompt()
-> slash command? extension command or builtin
-> emit input event (extensions may transform/intercept)
-> expand skill/template
-> streaming? queue steer/follow-up
-> validate model + auth
-> check pre-prompt compaction
-> before_agent_start (extensions modify system prompt / inject messages)
-> Agent.prompt() -> agentLoop -> streamFn -> pi-ai
-> stream deltas, execute tools, emit events
-> _handlePostAgentRun: retry/compact/queued messages loop
-> append entries to SessionManager JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol).
InteractiveMode renders events incrementally via pi-tui
Run mode dispatch
main() -> resolveAppMode(args)
interactive -> AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. + InteractiveMode (TUITerminal User Interface (the interactive mode, and the `pi-tui` library).)
print -> runPrintMode (text or json)
rpc -> runRpcMode (JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout)
(SDKSoftware Development Kit (the embeddable programmatic API).) -> createAgentSession() used programmatically
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Central class | AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. shared by all modes |
One code path for prompt lifecycle across modes |
| Runtime hot-swap | AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. recreates services |
Clean state on fork/switch/tree without leaking cwd-bound resources |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. tools | Four only | Minimal core; more tools via extensions |
| No in-process sandbox | Delegate to external sandboxes | CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. stays small; security boundary is the OS/container |
| Resource discovery | Global + project + package, trust-gated | User controls what project code executes |
| Modes | Interactive default; print/json/rpc alternatives | One binary serves TUITerminal User Interface (the interactive mode, and the `pi-tui` library). users, scripts, and embeddings |
Risks and Unknowns
InteractiveModeis a very large module (~193KB); changes there are high-churn and hard to review.- Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. is a security-critical path; regressions could execute untrusted code.
- The package manager and resource discovery span many source locations; collision and precedence rules must stay consistent.
Out of Scope
- ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. abstraction internals (FEAT-0001).
- Agent loop internals (FEAT-0002).
- TUITerminal User Interface (the interactive mode, and the `pi-tui` library). rendering internals (FEAT-0003).
- ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers./skills API surface (FEAT-0005).
- SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. format and branching internals (FEAT-0006).
Sync drift: 2026-10-13
Full sync vs packages/coding-agent/src. No body edits (status done); deltas recorded here.
- Tool sets table incomplete.
| Default (4) | read, bash, edit, write |and read-only set are correct, but sessions also registercodemode(src/extensions/codemode/tool.ts, exposuremodel-only, QuickJS sandbox,// @options:header,store()/load()persisted ascodemode-storeentries),tool_search(src/extensions/tool-search/tool.ts, BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. overcodemode/deferredtools, loads matches into the next model call), MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). toolsmcp__<server>__<tool>with exposurescodemode(default) /deferred/direct/hiddenplustoolExposureoverrides (src/extensions/mcp/tools.ts,config.ts), and MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). resource tools (resources.ts).builtInExtensions(src/extensions/index.ts) lists llama.cpp, codemode, tool-search, mcp as built-in (last three replaceable). - Architecture diagram omits the extension layer. Actual startup is
main()->AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch.+AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.-> extension runner loading built-in (codemode/tool-search/mcp/llama) then project/global/package extensions;before_agent_startgains themcp_serverssystem-prompt section (renderServersSection), andtool_callreadiness waits apply (src/extensions/mcp/index.ts).AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.,AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch.,SessionManager,ModelRegistrypaths verified; modes verified (modes/print-mode.ts,modes/json-event.ts,modes/rpc/,modes/interactive/); SDKSoftware Development Kit (the embeddable programmatic API). factorycreateAgentSession()(core/sdk.ts) plusexamples/sdk/14-codemode-mcp.tsverified. - No PiClient / pi-env drift.
packages/{protocol,client,server}are gone (verified absent) and no spec section claims remote-session attach;grep pi-env packages/coding-agentis empty. Nothing to correct.
Test Plan: Interactive Coding Agent
Scope
Covers the pi-coding-agent CLICommand-Line Interface (the `pi` binary). product: AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume., tools, modes (interactive, print, JSON, RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode).), settings, resource loading, project trust, and the SDKSoftware Development Kit (the embeddable programmatic API)..
Unit Tests
Test files under packages/coding-agent/test/ cover:
- AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. core (agent-session-.test.ts files for retry, concurrent, stats, dynamic-provider, dynamic-tools, runtime-events, auto-compaction-queue)
- Bash execution (bash-close-hang-windows.test.ts, bash-execution-width.test.ts)
- Built-in tools (tools.test.ts, edit-tool-legacy-input.test.ts, edit-tool-no-full-redraw.test.ts)
- CLICommand-Line Interface (the `pi` binary). args (args.test.ts)
- Config/settings (config.test.ts, settings-manager.test.ts, settings-manager-bug.test.ts, config-value-migration.test.ts)
- Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. (resource-loader.test.ts)
- System prompt building (system-prompt.test.ts)
- Run modes (print-mode.test.ts, rpc.test.ts, rpc-jsonl.test.ts, rpc-client-clone.test.ts, rpc-client-process-exit.test.ts, rpc-prompt-response-semantics.test.ts)
- SDKSoftware Development Kit (the embeddable programmatic API). (sdk-session-manager.test.ts, sdk-skills.test.ts, sdk-stream-options.test.ts, sdk-openrouter-attribution.test.ts)
- Trust manager (trust-manager.test.ts, trust-selector.test.ts)
- Theme handling (theme-detection.test.ts, theme-export.test.ts, theme-picker.test.ts, export-html-xss.test.ts)
- Interactive mode (interactive-mode-anthropic-warning.test.ts, interactive-mode-clone-command.test.ts, interactive-mode-compaction.test.ts, interactive-mode-import-command.test.ts, interactive-mode-startup-input.test.ts, interactive-mode-status.test.ts, interactive-mode-suspend.test.ts)
- Image processing (image-process.test.ts, image-processing.test.ts, image-resize-callers.test.ts)
- Clipboard handling (clipboard.test.ts, clipboard-native.test.ts, clipboard-image.test.ts, clipboard-image-bmp-conversion.test.ts)
- Version check (version-check.test.ts, pi-user-agent.test.ts)
- Suite tests (suite/agent-session-.test.ts) using the harness + faux provider
Integration Tests
- Suite tests under
test/suite/use the coding-agent test harness with a faux provider for full prompt-loop testing without real API calls - Issue regression tests under
test/suite/regressions/cover specific bugs and edge cases
Test Infrastructure
- HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. (
test/suite/harness.ts) provides a managed AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. + faux provider - In-memory session manager for deterministic testing
- Controlled bash process lifecycle
Coverage Matrix
| Requirement | Test Files |
|---|---|
| FRFunctional Requirement.-01MustThe system shall provide a `pi` CLICommand-Line Interface (the `pi` binary). with an interactive TUITerminal User Interface (the interactive mode, and the `pi-tui` library). as the default mode. (CLICommand-Line Interface (the `pi` binary). interactive default) | args.test.ts |
| FRFunctional Requirement.-02MustThe system shall provide four default built-in tools: `read`, `bash`, `edit`, `write`, and a read-only tool set (`read`, `grep`, `find`, `ls`). (Built-in tools) | tools.test.ts, edit-tool-*.test.ts |
| FRFunctional Requirement.-03MustThe system shall provide an `AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.` core that drives the prompt loop, manages model and thinking level, runs compaction, executes bash, and exports HTML. (AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. core) | agent-session-.test.ts, suite/agent-session-.test.ts |
| FRFunctional Requirement.-04MustThe system shall resolve model selection via `provider/id:thinking` patterns, scoped model cycling, and in-TUITerminal User Interface (the interactive mode, and the `pi-tui` library). `/model` and `/scoped-models` commands. (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. selection) | model-registry.test.ts, model-resolver.test.ts |
| FRFunctional Requirement.-05MustThe system shall provide built-in slash commands (`settings`, `model`, `export`, `fork`, `tree`, `login`, `logout`, `new`, `compact`, `resume`, `reload`, `quit`, and others). (Slash commands) | tools.test.ts, interactive-mode-*.test.ts |
| FRFunctional Requirement.-06MustThe system shall support run modes: interactive (default), print (`-p`), JSON (`--mode json`), RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). (`--mode rpc`), and SDKSoftware Development Kit (the embeddable programmatic API).. (Run modes) | print-mode.test.ts, rpc.test.ts |
| FRFunctional Requirement.-07MustThe system shall provide global and project settings (`~/.pi/agent/settings.json`, `.pi/settings.json`) with file locking and deep merge, plus keybindings. (Settings) | config.test.ts, settings-manager.test.ts |
| FRFunctional Requirement.-08MustThe system shall gate project resources (settings, extensions, context files) behind a project-trust decision. (Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute.) | trust-manager.test.ts, trust-selector.test.ts |
| FRFunctional Requirement.-09MustThe system shall discover and load resources (extensions, skills, prompt templates, themes, AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root./CLAUDE.md) from global, project, and package sources. (Resource discovery) | resource-loader.test.ts |
| FRFunctional Requirement.-10MustThe system shall build the system prompt from base prompt, project context, skills, date, and cwd. (System prompt building) | system-prompt.test.ts |
| FRFunctional Requirement.-11ShouldThe system shall support theme loading (JSON themes, light/dark auto, hot-reload). (Themes) | theme-detection.test.ts, theme-export.test.ts |
| FRFunctional Requirement.-12ShouldThe system shall provide update-check and install-telemetry endpoints, disable-able via env flags or `--offline`. (Update/telemetry) | version-check.test.ts |
| NFRNon-Functional Requirement.-02MustA hot-swap runtime shall tear down and recreate cwd-bound services when switching sessions or cwds. (Hot-swap runtime) | agent-session-runtime-events.test.ts, suite/agent-session-runtime.test.ts |
Sync drift: 2026-10-13
Full sync vs packages/coding-agent/test. No body edits (status done); deltas recorded here.
- Missing MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). coverage. Not listed but present:
mcp-extension.test.ts,mcp-oauth-store.test.ts,mcp-oauth-refresh.test.ts,mcp-command.test.ts,mcp-manager-view.test.ts, suiteagent-session-mcp.test.ts,agent-session-mcp-oauth.test.ts(+mcp-oauth-server.tshelper), and suite regression10285-mcp-tool-renderers.test.ts. - Missing codemode / tool-search coverage. Not listed but present:
codemode-renderer.test.ts,codemode-worker-config.test.ts,tool-search.test.ts, suiteagent-session-codemode.test.ts, suiteagent-session-tool-orchestration.test.ts, SDKSoftware Development Kit (the embeddable programmatic API). exampleexamples/sdk/14-codemode-mcp.ts. - HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. / regressions description still accurate.
test/suite/harness.ts(managed AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. + faux provider, in-memory session manager) verified;test/suite/regressions/holds ~80 regression files (naming<issue>-<slug>.test.ts), consistent with the artifact's characterization. - Listed RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). files verified present.
rpc.test.ts,rpc-jsonl.test.ts,rpc-client-clone.test.ts,rpc-client-process-exit.test.ts,rpc-prompt-response-semantics.test.tsall exist; no correction needed.
requirements
- Should the experimental first-time setup flow graduate to default behavior, and on what timeline?
- What is the policy for promoting a widely-used extension into a built-in tool or command?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. and Skills Platform
Overview
The extension platform is how pi stays minimal while remaining extensible. TypeScript extensions register custom tools, commands, event handlers, UI primitives, providers, and autocomplete; skills package on-demand capabilities via the Agent Skills standard; prompt templates offer reusable prompt snippets. Together they let users and packages reshape nearly every part of the agent without forking the core.
Stakeholders
| Stakeholder | Interest |
|---|---|
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. authors | A rich, stable ExtensionAPI and clear loading rules |
| Skills authors | A standard SKILL.md format and predictable invocation |
| End users | Safe, discoverable ways to add capabilities (install, trust) |
| Maintainers | A small, well-considered hook surface that does not bloat core |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-01MustThe system shall load TypeScript extensions via a default export `function (pi: ExtensionAPI)` using cached, lazy module loading. | Must | The system shall load TypeScript extensions via a default export function (pi: ExtensionAPI) using cached, lazy module loading. |
| FRFunctional Requirement.-02MustThe system shall allow extensions to register and replace tools (built-ins included). | Must | The system shall allow extensions to register and replace tools (built-ins included). |
| FRFunctional Requirement.-03MustThe system shall allow extensions to register slash commands invoked as `/name`. | Must | The system shall allow extensions to register slash commands invoked as /name. |
| FRFunctional Requirement.-04MustThe system shall provide event handlers for input, tool_call, tool_result, message lifecycle, turn/agent lifecycle, session lifecycle, compaction, provider request/response, project_trust, and resources_discover. | Must | The system shall provide event handlers for input, tool_call, tool_result, message lifecycle, turn/agent lifecycle, session lifecycle, compaction, provider request/response, project_trust, and resources_discover. |
| FRFunctional Requirement.-05MustThe system shall allow extensions to render UI primitives: selectors, confirmations, inputs, notifications, status line, widgets, custom footer/header/editor/overlay, and raw terminal input. | Must | The system shall allow extensions to render UI primitives: selectors, confirmations, inputs, notifications, status line, widgets, custom footer/header/editor/overlay, and raw terminal input. |
| FRFunctional Requirement.-06MustThe system shall allow extensions to define keyboard shortcuts, CLICommand-Line Interface (the `pi` binary). flags, autocomplete providers, and message renderers. | Must | The system shall allow extensions to define keyboard shortcuts, CLICommand-Line Interface (the `pi` binary). flags, autocomplete providers, and message renderers. |
| FRFunctional Requirement.-07MustThe system shall allow extensions to perform session control actions (setActiveTools, setModel, setThinkingLevel, abort, compact, fork). | Must | The system shall allow extensions to perform session control actions (setActiveTools, setModel, setThinkingLevel, abort, compact, fork). |
| FRFunctional Requirement.-08MustThe system shall load Agent Skills from `SKILL.md` files (global, project parent-walk, or packages), invoked as `/skill:name`, injected into the system prompt on demand. | Must | The system shall load Agent Skills from SKILL.md files (global, project parent-walk, or packages), invoked as /skill:name, injected into the system prompt on demand. |
| FRFunctional Requirement.-09MustThe system shall load prompt templates (Markdown with `{{variable}}` expansion) invoked as `/templatename`. | Must | The system shall load prompt templates (Markdown with {{variable}} expansion) invoked as /templatename. |
| FRFunctional Requirement.-10MustThe system shall load resources from global, project, and package sources with project-trust gating. | Must | The system shall load resources from global, project, and package sources with project-trust gating. |
| FRFunctional Requirement.-11ShouldThe system shall support a package manager (`pi install/remove/update/list`) for distributing extensions, skills, prompts, and themes via npm or git. | Should | The system shall support a package manager (pi install/remove/update/list) for distributing extensions, skills, prompts, and themes via npm or git. |
| FRFunctional Requirement.-12ShouldThe system shall support custom providers via `~/.pi/agent/models.json` or extensions for custom APIs/OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot).. | Should | The system shall support custom providers via ~/.pi/agent/models.json or extensions for custom APIs/OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot).. |
| FRFunctional Requirement.-13MayThe system shall allow extensions to register custom compaction and summarization behavior. | May | The system shall allow extensions to register custom compaction and summarization behavior. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-01MustProject-sourced extensions shall not execute until a project-trust decision is recorded. | Must | Security | Project-sourced extensions shall not execute until a project-trust decision is recorded. |
| NFRNon-Functional Requirement.-02MustExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. module loading shall be cached so a module is not re-evaluated per use. | Must | Reliability | ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. module loading shall be cached so a module is not re-evaluated per use. |
| NFRNon-Functional Requirement.-03MustThe legacy pi-ai root API used by extensions shall be aliased to `/compat` at runtime so existing extensions keep working. | Must | Compatibility | The legacy pi-ai root API used by extensions shall be aliased to /compat at runtime so existing extensions keep working. |
| NFRNon-Functional Requirement.-04ShouldThe hook surface shall be well-considered; new hooks require maintainer discussion to avoid unmaintainable complexity. | Should | Maintainability | The hook surface shall be well-considered; new hooks require maintainer discussion to avoid unmaintainable complexity. |
| NFRNon-Functional Requirement.-05ShouldExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. event dispatch shall not block the agent loop on the happy path. | Should | Performance | ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. event dispatch shall not block the agent loop on the happy path. |
Constraints
- Extensions are TypeScript modules loaded via
jiti. - Skills follow the external Agent Skills standard (
agentskills.io). - New hooks that bloat core are rejected; the bar is "well considered and discussed".
Acceptance Criteria
Every FRFunctional Requirement. and NFRNon-Functional Requirement. shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FRFunctional Requirement.-02MustThe system shall allow extensions to register and replace tools (built-ins included).
- Given an extension calling
pi.registerTool(...) - When the agent runs
- Then the custom tool is available and may replace a built-in of the same name.
- Given an extension calling
- FRFunctional Requirement.-04MustThe system shall provide event handlers for input, tool_call, tool_result, message lifecycle, turn/agent lifecycle, session lifecycle, compaction, provider request/response, project_trust, and resources_discover.
- Given an extension with a
tool_callhandler - When a tool is invoked
- Then the handler receives the call and may observe or mutate it.
- Given an extension with a
- FRFunctional Requirement.-08MustThe system shall load Agent Skills from `SKILL.md` files (global, project parent-walk, or packages), invoked as `/skill:name`, injected into the system prompt on demand.
- Given a
SKILL.mdplaced in a discoverable skills directory - When the user invokes
/skill:name - Then the skill content is injected into the system prompt for that session.
- Given a
- FRFunctional Requirement.-10MustThe system shall load resources from global, project, and package sources with project-trust gating.
- Given an untrusted project with
.pi/resources - When the agent starts
- Then project-sourced extensions, skills, and prompts are not loaded until trust is granted.
- Given an untrusted project with
- NFRNon-Functional Requirement.-01MustProject-sourced extensions shall not execute until a project-trust decision is recorded.
- Given a project-sourced extension
- When the project is not trusted
- Then the extension's default export is never executed.
- NFRNon-Functional Requirement.-03MustThe legacy pi-ai root API used by extensions shall be aliased to `/compat` at runtime so existing extensions keep working.
- Given an extension importing from the pi-ai root
- When loaded after the
/compatmigration - Then the import resolves to the compat entrypoint without code changes.
Conflicts
None identified yet.
Open Questions
- What is the stabilization criteria for the
ExtensionAPI(currently documented in extensions.md), and which parts are considered stable versus experimental? - How should extension-provided permissions/sandboxing hooks interact with the documented external-sandbox patterns?
Specification: ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. and Skills Platform
Overview
Three resource types extend pi: extensions (TypeScript modules), skills (SKILL.md packages), and prompt templates ({{var}} Markdown).
DefaultResourceLoader discovers them from global/project/package sources with trust gating; ExtensionRunner dispatches lifecycle and event hooks; skills and templates are injected into the system prompt on demand.
Architecture
DefaultResourceLoader
discover: global (~/.pi/agent, ~/.agents)
project (.pi, .agents, AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root./CLAUDE.md) -- trust gated
packages (installed)
|
v
+--------------------+ cached, lazy (jiti)
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. loader |----> default export (pi: ExtensionAPI)
+---------+----------+
|
v
+--------------------+
| ExtensionRunner | lifecycle + event dispatch
| (on/emit hooks) | (input, tool_call, tool_result,
+--------------------+ message_*, session_*, provider_*, ...)
|
v
AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. / InteractiveMode (consume hooks, expose UI context)
Skills & Prompt Templates
loaded on demand (/skill:name, /templatename)
-> injected into system prompt or expanded into user message
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
ExtensionAPI (excerpt)
| Capability | Method | Description |
|---|---|---|
| Tools | registerTool, defineTool |
Add or replace tools |
| Commands | registerCommand |
Add slash command /name |
| Events | on(event, handler) |
Subscribe to lifecycle hooks |
| UI | ExtensionUIContext |
Selectors, confirmations, inputs, widgets, overlays |
| Shortcuts | ExtensionShortcut |
Register key bindings |
| Flags | ExtensionFlag |
Register CLICommand-Line Interface (the `pi` binary). flags |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. control | ExtensionContextActions |
setActiveTools, setModel, compact, fork, abort |
| Providers | registerProvider, unregisterProvider |
Add or remove LLMLarge Language Model. providers |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | registerMcpServer, unregisterMcpServer |
Add or remove MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers |
| Renderers | registerToolRenderer |
Override tool result rendering |
Built-in extensions (packages/coding-agent/src/extensions/): llama.cpp, plus
replaceable codemode, tool-search, and mcp (a user extension registering the
same tool or /mcp command takes over instead of running alongside the built-in).
Event surface (categories)
| Category | Events |
|---|---|
| Input | input |
| Agent lifecycle | before_agent_start, agent_start/end, turn_start/end |
| Messages | message_start/update/end |
| Tools | tool_call, tool_result |
| Sessions | session_start/shutdown, session_before_compact/compact/fork/switch/tree |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | before_provider_request, after_provider_response |
| Context | context, resources_discover, project_trust, user_bash |
SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`.
| Field | Type | Constraints | Description |
|---|---|---|---|
| name | string | from /skill: invocation |
SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. identifier |
| path | string | file path | Location of SKILL.md |
| frontmatter | object | optional | Metadata |
| body | string | not null | Markdown injected into prompt |
API Contracts
/skill:name
Injects the skill's SKILL.md body into the system prompt context for the session.
/templatename
Expands {{variable}} placeholders in the Markdown template into a user message.
pi.install(name) / pi.remove(name) / pi.update(name)
Package manager operations over npm or git sources, resolving to resource directories (extensions, skills, prompts, themes, models).
Sequences
Tool call through extension hooks
agent -> tool_call event
-> beforeToolCall (extension can {block: true})
-> if not blocked: tool.execute(args)
-> tool_execution_update events (extensions observe)
-> afterToolCall (extension can override content/details/isError/terminate)
-> tool_result event
Resource discovery (trust-gated)
DefaultResourceLoader.discover()
for each source (global, project, package):
if project source and not trusted: skip
collect extensions, skills, prompts, themes, context files
-> resources_discover event (extensions may augment)
-> registry populated
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Language | TypeScript via jiti | Type-safe, cached, lazy |
| Skills standard | Agent Skills (SKILL.md) |
Cross-agent interoperability |
| Hook surface | Curated event taxonomy | Power without unbounded core growth |
| Trust model | Project sources gated | Prevent untrusted code execution by default |
| Compat alias | pi-ai root -> /compat |
Existing extensions keep working |
Risks and Unknowns
- The
ExtensionAPIis large and evolving; breaking changes affect the ecosystem. - Event handler ordering and interaction effects across multiple extensions can be hard to predict.
- Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. bypass (e.g. via a malicious package source) is a security risk to monitor.
Out of Scope
- The core built-in tools and agent loop (FEAT-0002, FEAT-0004).
- SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. persistence and branching (FEAT-0006).
- LLMLarge Language Model. provider auth internals (FEAT-0001).
Test Plan: ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. and Skills Platform
Scope
Covers extension loading, hook dispatch, skills, prompt templates, package manager, and the ExtensionAPI surface.
Unit Tests
Test files under packages/coding-agent/test/ cover:
- Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. (extensions-runner.test.ts, compaction-extensions.test.ts, compaction-extensions-example.test.ts)
- ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. discovery and resource loading (extensions-discovery.test.ts, resource-loader.test.ts, resource-loader-theme.test.ts, trust-manager.test.ts, trust-selector.test.ts)
- ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. input events (extensions-input-event.test.ts)
- Skills (skills.test.ts, sdk-skills.test.ts)
- Prompt templates (prompt-templates.test.ts)
- Package manager (package-manager.test.ts, package-manager-ssh.test.ts, package-command-paths.test.ts, package-distribution.test.ts)
- Git integration (git-update.test.ts, git-ssh-url.test.ts, git-merge-and-resolve-extension.test.ts)
- Plan mode extension (plan-mode-extension.test.ts, plan-mode-utils.test.ts)
- Trigger compact extension (trigger-compact-extension.test.ts)
- Built-in extensions (mcp-extension.test.ts, mcp-command.test.ts, mcp-oauth-.test.ts, llama-extension.test.ts, tool-search.test.ts, codemode-.test.ts, branch-summary-extensions.test.ts)
- Suite regressions (test/suite/regressions/: 6162-extension-active-tools-next-turn, 6260-inline-extension-naming, 5433-extension-oauth-prompt-input, 2835-tools-allowlist-filters-extension-tools, 5080-signal-shutdown-extension-cleanup, plus extension-factory-cache coverage via loader cache tests)
Test Infrastructure
- In-memory extension module loading with mock default exports
- Fake
ExtensionAPIandExtensionUIContextfor dispatch testing - Test extension files in
examples/extensions/
Coverage Matrix
| Requirement | Test Files |
|---|---|
| FRFunctional Requirement.-01MustThe system shall load TypeScript extensions via a default export `function (pi: ExtensionAPI)` using cached, lazy module loading. (ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. loading) | extensions-runner.test.ts |
| FRFunctional Requirement.-02MustThe system shall allow extensions to register and replace tools (built-ins included). (Tool registration/replacement) | extensions-runner.test.ts, 2835-regression |
| FRFunctional Requirement.-03MustThe system shall allow extensions to register slash commands invoked as `/name`. (Slash commands) | extensions-runner.test.ts |
| FRFunctional Requirement.-04MustThe system shall provide event handlers for input, tool_call, tool_result, message lifecycle, turn/agent lifecycle, session lifecycle, compaction, provider request/response, project_trust, and resources_discover. (Event handlers) | extensions-runner.test.ts, extensions-input-event.test.ts |
| FRFunctional Requirement.-05MustThe system shall allow extensions to render UI primitives: selectors, confirmations, inputs, notifications, status line, widgets, custom footer/header/editor/overlay, and raw terminal input. (UI primitives) | (sdk docs) |
| FRFunctional Requirement.-07MustThe system shall allow extensions to perform session control actions (setActiveTools, setModel, setThinkingLevel, abort, compact, fork). (SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. control) | extensions-runner.test.ts |
| FRFunctional Requirement.-08MustThe system shall load Agent Skills from `SKILL.md` files (global, project parent-walk, or packages), invoked as `/skill:name`, injected into the system prompt on demand. (Skills loading) | skills.test.ts, sdk-skills.test.ts |
| FRFunctional Requirement.-09MustThe system shall load prompt templates (Markdown with `{{variable}}` expansion) invoked as `/templatename`. (Prompt templates) | prompt-templates.test.ts |
| FRFunctional Requirement.-10MustThe system shall load resources from global, project, and package sources with project-trust gating. (Resource loading) | extensions-discovery.test.ts, resource-loader.test.ts |
| FRFunctional Requirement.-11ShouldThe system shall support a package manager (`pi install/remove/update/list`) for distributing extensions, skills, prompts, and themes via npm or git. (Package manager) | package-manager.test.ts, package-distribution.test.ts |
| FRFunctional Requirement.-12ShouldThe system shall support custom providers via `~/.pi/agent/models.json` or extensions for custom APIs/OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot).. (Custom providers) | mcp-extension.test.ts, llama-extension.test.ts |
| NFRNon-Functional Requirement.-01MustProject-sourced extensions shall not execute until a project-trust decision is recorded. (Trust-gated extensions) | trust-manager.test.ts, (project trust tests) |
| NFRNon-Functional Requirement.-02MustExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. module loading shall be cached so a module is not re-evaluated per use. (Cached module loading) | loader extensionCache (extension-factory-cache coverage) |
requirements
- What is the stabilization criteria for the
ExtensionAPI(currently documented in extensions.md), and which parts are considered stable versus experimental? - How should extension-provided permissions/sandboxing hooks interact with the documented external-sandbox patterns?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Persistence and BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`).
Overview
Sessions make pi's conversations durable, resumable, and branchable.
SessionManager persists tree-structured JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). logs (messages, model/thinking changes, compaction summaries, branch summaries); users can resume, fork, clone, and navigate session trees; compaction reclaims context lossily while preserving the original log.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | Resume past work, branch explorations without losing history, manage context length |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. authors | SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. lifecycle hooks (compact, fork, switch, tree) to observe and augment |
| Maintainers | A stable, migratable on-disk format with clear versioning |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-01MustThe system shall persist sessions as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). with tree-structured entries (`id`/`parentId` per entry) under a versioned format. | Must | The system shall persist sessions as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). with tree-structured entries (id/parentId per entry) under a versioned format. |
| FRFunctional Requirement.-02MustThe system shall support session entry types: messages, thinking-level changes, model changes, compaction summaries, branch summaries, labels, custom messages, and session info. | Must | The system shall support session entry types: messages, thinking-level changes, model changes, compaction summaries, branch summaries, labels, custom messages, and session info. |
| FRFunctional Requirement.-03MustThe system shall support resume (`-r`, `-c`, `--session`, `/resume`), new (`/new`), fork (`/fork`, `--fork`), clone (`/clone`), and tree navigation (`/tree`). | Must | The system shall support resume (-r, -c, --session, /resume), new (/new), fork (/fork, --fork), clone (/clone), and tree navigation (/tree). |
| FRFunctional Requirement.-04MustThe system shall support branching where forking from a previous user message creates a new session file and the original log is preserved. | Must | The system shall support branching where forking from a previous user message creates a new session file and the original log is preserved. |
| FRFunctional Requirement.-05MustThe system shall support compaction (manual via `/compact [prompt]` or automatic on threshold/overflow) that summarizes older messages while keeping recent ones. | Must | The system shall support compaction (manual via /compact [prompt] or automatic on threshold/overflow) that summarizes older messages while keeping recent ones. |
| FRFunctional Requirement.-06MustThe system shall preserve the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). file through compaction (compaction is lossy but non-destructive to the source log). | Must | The system shall preserve the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). file through compaction (compaction is lossy but non-destructive to the source log). |
| FRFunctional Requirement.-07MustThe system shall hot-swap the runtime when switching sessions or cwds, tearing down and recreating cwd-bound services. | Must | The system shall hot-swap the runtime when switching sessions or cwds, tearing down and recreating cwd-bound services. |
| FRFunctional Requirement.-08MustThe system shall emit session lifecycle hooks (`session_before_compact/compact`, `session_before_fork/fork`, `session_before_switch/switch`, `session_before_tree/tree`) extensions can observe. | Must | The system shall emit session lifecycle hooks (session_before_compact/compact, session_before_fork/fork, session_before_switch/switch, session_before_tree/tree) extensions can observe. |
| FRFunctional Requirement.-09ShouldThe system shall provide compaction post-token estimates and branch summarization. | Should | The system shall provide compaction post-token estimates and branch summarization. |
| FRFunctional Requirement.-10ShouldThe system shall support session export to HTML. | Should | The system shall support session export to HTML. |
| FRFunctional Requirement.-11ShouldThe system shall migrate older session format versions to the current version on load. | Should | The system shall migrate older session format versions to the current version on load. |
| FRFunctional Requirement.-12MayThe system shall support session labels and bookmarks for navigation. | May | The system shall support session labels and bookmarks for navigation. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-01MustThe original session JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). shall never be destructively modified by compaction or branching. | Must | Reliability | The original session JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). shall never be destructively modified by compaction or branching. |
| NFRNon-Functional Requirement.-02MustThe format version shall be explicit (`CURRENT_SESSION_VERSION`) with documented migration steps. | Must | Compatibility | The format version shall be explicit (CURRENT_SESSION_VERSION) with documented migration steps. |
| NFRNon-Functional Requirement.-03ShouldSessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. append and read operations shall remain efficient for large session files. | Should | Performance | SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. append and read operations shall remain efficient for large session files. |
| NFRNon-Functional Requirement.-04ShouldCompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. events shall carry reason and retry metadata for extension consumers. | Should | Observability | CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. events shall carry reason and retry metadata for extension consumers. |
Constraints
- Sessions are local JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). files; no server-side session store.
progress.mdandstate.yml(workflow state) are never committed; session JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). is user data.- CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. is lossy by design.
Acceptance Criteria
Every FRFunctional Requirement. and NFRNon-Functional Requirement. shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FRFunctional Requirement.-01MustThe system shall persist sessions as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). with tree-structured entries (`id`/`parentId` per entry) under a versioned format.
- Given a session with multiple turns and a branch
- When serialized to disk
- Then the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). contains tree-structured entries each with
idandparentIdforming a valid tree.
- FRFunctional Requirement.-05MustThe system shall support compaction (manual via `/compact [prompt]` or automatic on threshold/overflow) that summarizes older messages while keeping recent ones.
- Given a session exceeding the compaction threshold
- When compaction runs
- Then older messages are summarized, recent messages are retained, and a compaction summary entry is appended.
- FRFunctional Requirement.-06MustThe system shall preserve the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). file through compaction (compaction is lossy but non-destructive to the source log).
- Given a session that has been compacted
- When inspecting the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). file
- Then the original message entries remain present alongside the compaction summary.
- FRFunctional Requirement.-07MustThe system shall hot-swap the runtime when switching sessions or cwds, tearing down and recreating cwd-bound services.
- Given an interactive session
- When the user runs
/treeand switches branches - Then the runtime tears down cwd-bound services and recreates them for the target branch without leaking state.
- NFRNon-Functional Requirement.-01MustThe original session JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). shall never be destructively modified by compaction or branching.
- Given any compaction or fork operation
- When it completes
- Then the source session JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). file is byte-for-byte unchanged except for appended entries.
Conflicts
None identified yet.
Open Questions
- Is there a plan to support remote/session-sync, or will sessions remain strictly local files?
- What is the policy for pruning or archiving very large session files over time?
Specification: SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Persistence and BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`).
Overview
Sessions are JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). files with a tree-structured entry stream.
SessionManager owns append/read/migration; AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. hot-swaps the active session and its cwd-bound services on fork/switch/tree navigation; compaction runs in AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. with hooks for extensions.
Architecture
AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.
prompt loop appends entries ------+
compaction summarizes |
branch summarization |
| v
| +-------------------+
+----------------->| SessionManager |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). append/read |
| tree traversal |
| migration (v1->N) |
+---------+---------+
| hot-swap
v
+------------------------+
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| owns active session + |
| cwd-bound services |
| fork()/switch()/ |
| navigate() |
+------------------------+
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry (union, tree-structured)
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | string | required | Unique entry id |
| parentId | string | nullable | Parent entry id (null = root) |
| type | enum | required | message, thinkingChange, modelChange, compaction, branchSummary, label, custom, sessionInfo |
| ... | varies | per type | Type-specific payload |
SessionHeader
| Field | Type | Description |
|---|---|---|
| version | number | Format version (CURRENT_SESSION_VERSION) |
| sessionId | string | Stable session identifier |
| cwd | string | Working directory at creation |
CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. summary entry
| Field | Type | Description |
|---|---|---|
| reason | enum | manual, threshold, overflow, retry |
| willRetry | boolean | Whether compaction will retry |
| summary | string | Summarized older context |
| cutPoint | string | Entry id where cut occurred |
API Contracts
SessionManager.append(entry) / read()
Append appends a JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). line; read loads and indexes the tree for traversal, listing, and migration.
Runtime: fork() / switch(id) / navigate(direction)
Each tears down the current runtime, emits the corresponding session_before_* event, and recreates services bound to the target session/cwd.
/compact [prompt]
Triggers compaction: emits session_before_compact, summarizes older messages, retains recent ones, appends a compaction summary, emits session_compact.
Sequences
CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. flow
threshold exceeded OR /compact
-> session_before_compact event (extensions may modify/inject)
-> findCutPoint (token estimation)
-> summarize messages before cut
-> keep recent messages
-> append compaction summary entry to JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol).
-> post-token estimate
-> session_compact event (with reason, willRetry)
-> if willRetry: agent.continue()
BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). flow
/fork <message-id>
-> session_before_fork event
-> create new session file from entries up to message-id
-> runtime.switch() to new session
-> session_fork event
(original session file unchanged)
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Format | JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol)., tree-structured | Append-only, diff/stream friendly, supports branching |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy, non-destructive | Reclaims context while preserving source history |
| Migration | Explicit version + on-load migration | Supports evolving format without breaking old sessions |
| Hot-swap | Runtime recreation | Clean state across sessions/cwds |
| Hook surface | session_before_*/session_* pairs |
Extensions observe and augment lifecycle |
Risks and Unknowns
- Large session files (multi-MB) affect resume and read performance; pruning policy is undefined.
- Migration logic must handle every prior version; a missed step corrupts old sessions.
- CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. quality (what gets summarized) directly affects agent performance and is hard to evaluate automatically.
Out of Scope
- The interactive TUITerminal User Interface (the interactive mode, and the `pi-tui` library). rendering of sessions (FEAT-0004).
- The agent loop and tool execution (FEAT-0002).
- ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. API internals beyond session hooks (FEAT-0005).
Test Plan: SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Persistence and BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`).
Scope
Covers session format, JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). persistence, tree-structured entries, branching, compaction, migration, export, and session lifecycle.
Unit Tests
Test files under packages/coding-agent/test/ cover:
- SessionManager operations (session-manager/save-entry.test.ts, session-manager/file-operations.test.ts, session-manager/build-context.test.ts, session-manager/labels.test.ts, session-manager/tree-traversal.test.ts, session-manager/migration.test.ts, session-manager/custom-session-id.test.ts)
- SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. branching (agent-session-branching.test.ts)
- SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. compaction (agent-session-compaction.test.ts, compaction.test.ts, compaction-serialization.test.ts, compaction-summary-reasoning.test.ts)
- SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. tree navigation (agent-session-tree-navigation.test.ts, tree-selector.test.ts)
- SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. file handling (session-file-invalid.test.ts, session-id-readonly.test.ts, session-info-modified-timestamp.test.ts, session-cwd.test.ts, session-selector-search.test.ts, session-selector-rename.test.ts, session-selector-path-delete.test.ts)
- SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. lifecycle events (suite/agent-session-queue.test.ts)
- HTML export (export-html-whitespace.test.ts, export-html-skill-block.test.ts)
- Startup session naming (startup-session-name.test.ts)
- First-time setup fork (first-time-setup-fork.test.ts)
- Format resume command (format-resume-command.test.ts)
- Suite regressions (6324-branch-summary-ambient-auth.test.ts, 3686-session-name-event.test.ts, 3688-tree-cancel-compacting.test.ts, 5943-session-start-notify.test.ts, 5996-session-name-newlines.test.ts, 2860-replaced-session-context.test.ts, pre-prompt-compaction-no-continue.test.ts)
Test Infrastructure
- In-memory session storage for deterministic testing
- Simulated session files for migration testing
- Tree-structured JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). helpers
Coverage Matrix
| Requirement | Test Files |
|---|---|
| FRFunctional Requirement.-01MustThe system shall persist sessions as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). with tree-structured entries (`id`/`parentId` per entry) under a versioned format. (JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). tree format) | session-manager/save-entry.test.ts |
| FRFunctional Requirement.-02MustThe system shall support session entry types: messages, thinking-level changes, model changes, compaction summaries, branch summaries, labels, custom messages, and session info. (Entry types) | session-manager/save-entry.test.ts |
| FRFunctional Requirement.-03MustThe system shall support resume (`-r`, `-c`, `--session`, `/resume`), new (`/new`), fork (`/fork`, `--fork`), clone (`/clone`), and tree navigation (`/tree`). (Resume/fork/clone/tree) | agent-session-branching.test.ts, agent-session-tree-navigation.test.ts |
| FRFunctional Requirement.-04MustThe system shall support branching where forking from a previous user message creates a new session file and the original log is preserved. (BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`).) | agent-session-branching.test.ts |
| FRFunctional Requirement.-05MustThe system shall support compaction (manual via `/compact [prompt]` or automatic on threshold/overflow) that summarizes older messages while keeping recent ones. (CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry.) | agent-session-compaction.test.ts, compaction.test.ts, compaction-serialization.test.ts |
| FRFunctional Requirement.-06MustThe system shall preserve the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). file through compaction (compaction is lossy but non-destructive to the source log). (Non-destructive compaction) | compact test files |
| FRFunctional Requirement.-07MustThe system shall hot-swap the runtime when switching sessions or cwds, tearing down and recreating cwd-bound services. (Runtime hot-swap) | agent-session-runtime-events.test.ts |
| FRFunctional Requirement.-08MustThe system shall emit session lifecycle hooks (`session_before_compact/compact`, `session_before_fork/fork`, `session_before_switch/switch`, `session_before_tree/tree`) extensions can observe. (SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. lifecycle hooks) | (suite harness tests) |
| FRFunctional Requirement.-09ShouldThe system shall provide compaction post-token estimates and branch summarization. (CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. estimates) | compaction-summary-reasoning.test.ts |
| FRFunctional Requirement.-10ShouldThe system shall support session export to HTML. (HTML export) | export-html-*.test.ts |
| FRFunctional Requirement.-11ShouldThe system shall migrate older session format versions to the current version on load. (Migration) | session-manager/migration.test.ts |
| NFRNon-Functional Requirement.-01MustThe original session JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). shall never be destructively modified by compaction or branching. (Non-destructive original) | compaction.test.ts |
| NFRNon-Functional Requirement.-04ShouldCompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. events shall carry reason and retry metadata for extension consumers. (CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. observability) | compaction-summary-reasoning.test.ts |
requirements
- Is there a plan to support remote/session-sync, or will sessions remain strictly local files?
- What is the policy for pruning or archiving very large session files over time?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Orchestrator
Overview
@earendil-works/pi-orchestrator is an experimental daemon and CLICommand-Line Interface (the `pi` binary). that manages multiple pi-coding-agent instances as child processes, providing a supervision layer for spawning, monitoring, stopping, and communicating with pi instances via IPC. It supports a Radius presence integration for remote machine registration and an RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). stream bridge for session event forwarding. The package is under active development and its API is not yet stable.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Operators / automation users | Spawn and manage multiple pi instances from scripts or orchestration tooling |
| Maintainers | A supervision layer for multi-instance pi deployments without modifying the coding-agent core |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-01MustThe system shall provide a `serve` daemon command that starts a Unix socket IPC server for managing pi instances. | Must | The system shall provide a serve daemon command that starts a Unix socket IPC server for managing pi instances. |
| FRFunctional Requirement.-02MustThe system shall support spawning new pi-coding-agent RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). instances with a specified cwd and optional label. | Must | The system shall support spawning new pi-coding-agent RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). instances with a specified cwd and optional label. |
| FRFunctional Requirement.-03MustThe system shall support listing all managed instances with their status (starting, online, stopping, stopped, error). | Must | The system shall support listing all managed instances with their status (starting, online, stopping, stopped, error). |
| FRFunctional Requirement.-04MustThe system shall support querying the status of a specific instance by ID. | Must | The system shall support querying the status of a specific instance by ID. |
| FRFunctional Requirement.-05MustThe system shall support stopping a specific instance by ID, cleaning up its resources. | Must | The system shall support stopping a specific instance by ID, cleaning up its resources. |
| FRFunctional Requirement.-06MustThe system shall support sending RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). commands to a running instance and receiving responses. | Must | The system shall support sending RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). commands to a running instance and receiving responses. |
| FRFunctional Requirement.-07MustThe system shall support opening an RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). stream to an instance for bidirectional JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). communication (commands, session events, extension UI requests). | Must | The system shall support opening an RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). stream to an instance for bidirectional JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). communication (commands, session events, extension UI requests). |
| FRFunctional Requirement.-08ShouldThe system shall persist instance records to disk for recovery after restart. | Should | The system shall persist instance records to disk for recovery after restart. |
| FRFunctional Requirement.-09ShouldThe system shall support Radius presence registration for remote machine discovery. | Should | The system shall support Radius presence registration for remote machine discovery. |
| FRFunctional Requirement.-10ShouldThe system shall recover instances on restart by marking previously-online instances as stopped and cleaning up Radius connections. | Should | The system shall recover instances on restart by marking previously-online instances as stopped and cleaning up Radius connections. |
| FRFunctional Requirement.-11ShouldThe system shall support session metadata synchronization (sessionId, sessionFile) after commands that can change the session identity. | Should | The system shall support session metadata synchronization (sessionId, sessionFile) after commands that can change the session identity. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-01MustInstance lifecycle transitions shall be consistent: starting -> online -> stopping -> stopped, with error as a terminal failure state. | Must | Correctness | Instance lifecycle transitions shall be consistent: starting -> online -> stopping -> stopped, with error as a terminal failure state. |
| NFRNon-Functional Requirement.-02MustUnexpected RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). process exit shall mark the instance as error and clean up resources (Radius disconnect, subscriber notification). | Must | Reliability | Unexpected RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). process exit shall mark the instance as error and clean up resources (Radius disconnect, subscriber notification). |
| NFRNon-Functional Requirement.-03ShouldIPC shall use local Unix sockets only; no network exposure by default. | Should | Security | IPC shall use local Unix sockets only; no network exposure by default. |
Constraints
- Experimental; the CLICommand-Line Interface (the `pi` binary)., APIs, and behavior are not yet stable and may change without notice.
- Depends on
@earendil-works/pi-coding-agentfor RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol types and process management. - Unix socket IPC only (no Windows named pipe support at this stage).
Acceptance Criteria
- FRFunctional Requirement.-01MustThe system shall provide a `serve` daemon command that starts a Unix socket IPC server for managing pi instances.
- Given the orchestrator CLICommand-Line Interface (the `pi` binary).
- When
orchestrator serveis run - Then a Unix socket IPC server starts, listening on the configured socket path.
- FRFunctional Requirement.-02MustThe system shall support spawning new pi-coding-agent RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). instances with a specified cwd and optional label.
- Given a running serve daemon
- When
orchestrator spawn --cwd /pathis called - Then a new pi-coding-agent RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). instance is spawned and its ID is returned.
- FRFunctional Requirement.-06MustThe system shall support sending RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). commands to a running instance and receiving responses.
- Given a running instance
- When
orchestrator rpc <id> '{"type":"get_state"}'is called - Then the response from the pi instance is returned.
- NFRNon-Functional Requirement.-02MustUnexpected RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). process exit shall mark the instance as error and clean up resources (Radius disconnect, subscriber notification).
- Given a running instance whose RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). process crashes
- When the exit is detected
- Then the instance status is set to error and persisted.
Conflicts
None identified yet.
Open Questions
- What is the stabilization path for the orchestrator, and should its APIs be aligned with the coding-agent's SDKSoftware Development Kit (the embeddable programmatic API). or be independent?
- Should the orchestrator gain built-in support for non-Unix platforms (Windows named pipes, TCP with auth)?
Specification: Orchestrator
Overview
The orchestrator is a daemon (orchestrator serve) that exposes a Unix socket IPC server. A CLICommand-Line Interface (the `pi` binary). client communicates with the daemon to spawn, list, status-check, stop, and send RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). commands to pi-coding-agent instances. Each instance is a child process running pi --mode rpc. The supervisor persists instance records to JSON and optionally registers with a Radius presence service for remote machine discovery.
Architecture
+-------------------+ +----------------------+
| orchestrator CLICommand-Line Interface (the `pi` binary). | IPC | orchestrator serve |
| (list, spawn, |<-------->| (Unix socket daemon) |
| status, stop, | | |
| rpc, rpc-stream) | +----------+-----------+
+-------------------+ |
| manages
v
+---------------------------+
| OrchestratorSupervisor |
| - spawnInstance() |
| - stopInstance() |
| - handleRpc() |
| - openRpcStream() |
+----+---------------------+
| owns
v
+-----------------------------+
| RpcProcessInstance (child) |
| pi --mode rpc |
| Unix socket IPC |
+-----------------------------+
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
InstanceRecord
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | string | UUID | Unique instance identifier |
| status | InstanceStatus | enum | starting, online, stopping, stopped, error |
| cwd | string | not null | Working directory |
| createdAt | string | ISO 8601 | Creation timestamp |
| lastSeenAt | string | optional | Last update timestamp |
| label | string | optional | Human-readable label |
| sessionId | string | optional | Current pi session ID |
| sessionFile | string | optional | Current pi session file path |
| radiusPiId | string | optional | Radius presence registration ID |
IPC Protocol (excerpt)
| Request type | Payload | Response type |
|---|---|---|
| spawn | cwd, label? | spawn_result |
| list | — | list_result (InstanceSummary[]) |
| status | instanceId | status_result |
| stop | instanceId | stop_result |
| rpc | instanceId, command | rpc_result (RpcResponse) |
| rpc_stream | instanceId | rpc_ready (then bidirectional stream) |
API Contracts
orchestrator serve
Starts the daemon. Recovers persisted instances, starts Radius presence if configured, and listens on a Unix socket.
orchestrator spawn --cwd [--label
Spawns a child pi-coding-agent process in RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode, registers with Radius, and returns the instance ID.
orchestrator rpc
Sends a single RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). command to the instance and returns the response. SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. metadata is refreshed after mutating commands (new_session, switch_session, fork, clone, set_session_name, prompt).
orchestrator rpc-stream
Opens a bidirectional stream: the CLICommand-Line Interface (the `pi` binary). forwards stdin JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). to the instance as RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). commands and extension UI responses, and writes instance events to stdout.
Sequences
Instance spawn flow
orchestrator CLICommand-Line Interface (the `pi` binary). -> serve daemon: spawn {cwd, label}
serve -> supervisor.spawnInstance()
supervisor: create InstanceRecord (status: starting)
supervisor: createRpcProcessInstance (child pi --mode rpc)
supervisor: syncInstanceRecord (get_state)
supervisor: radiusPresence.registerPi()
supervisor: setStatus(online)
serve -> orchestrator CLICommand-Line Interface (the `pi` binary).: spawn_result {instance}
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| IPC transport | Unix socket | Local-only, fast, no network overhead |
| Child process | pi --mode rpc | Reuses existing coding-agent RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol |
| Persistence | JSON file (instances.json) | Simple, portable, no database dependency |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. sync | On-demand after mutating commands | Avoids unnecessary get_state calls on every RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). |
| Experimental status | Explicit disclaimer | Allows API evolution without commitment |
Risks and Unknowns
- Experimental package: the API surface may change or be removed without notice. Consumers should pin a specific version.
- No test suite exists for the orchestrator (no test files found).
- Unix socket only: no Windows support at this stage.
- Radius presence integration depends on an external service; behavior when the service is unreachable needs hardening.
Out of Scope
- The pi-coding-agent RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol itself (FEAT-0004).
- SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. persistence and branching (FEAT-0006).
- ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. API internals (FEAT-0005).
requirements
- What is the stabilization path for the orchestrator, and should its APIs be aligned with the coding-agent's SDK or be independent?
- Should the orchestrator gain built-in support for non-Unix platforms (Windows named pipes, TCP with auth)?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. Sandbox
Overview
ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.-written JavaScript must run with the least possible capability, so the package executes scripts in a QuickJS VM compiled to WebAssembly where calling injected tools is the only capability.
Nested tool calls never enter the LLMLarge Language Model. context, and only the script output and return value do.
The coding agent exposes this sandbox as its built-in codemode tool, and the package has no pi dependencies so any host can expose its own functions to model-written scripts.
Stakeholders
| Stakeholder | Interest |
|---|---|
Coding agent (codemode tool) |
Batch, chain, and filter nested tool calls in one model step without flooding context |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. authors | A small stable script surface (tools, ALL_TOOLS, text, image, exit, store, load) with TypeScript declarations |
| Cloudflare deployers | A non-blocking sandbox Worker plus Durable Object for agent sessions |
| External hosts | A dependency-free sandbox for exposing remote APIs, MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers, or application services to scripts |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-1MustThe system shall execute model-written JavaScript in a fresh QuickJS VM per execution where calling injected tools is the only host capability. | Must | The system shall execute model-written JavaScript in a fresh QuickJS VM per execution where calling injected tools is the only host capability. |
| FRFunctional Requirement.-2MustThe system shall provide one script environment on every sandbox: `tools.<name>(args)` plus `tools["<name>"]`, `ALL_TOOLS`, `text(value)`, `image(urlOrItem)`, `exit()`, `console.*`, `store(key, value)`/`load(key)`, host `globals`, top-level `await`, and `return`. | Must | The system shall provide one script environment on every sandbox: tools.<name>(args) plus tools["<name>"], ALL_TOOLS, text(value), image(urlOrItem), exit(), console.*, store(key, value)/load(key), host globals, top-level await, and return. |
| FRFunctional Requirement.-3MustThe system shall offer three sandboxes with one API, one script environment, and one result format: `CodemodeSandbox` on a worker thread per execution, `RemoteCodemodeSandbox` in another isolate, and `InlineCodemodeSandbox` on the calling thread. | Must | The system shall offer three sandboxes with one API, one script environment, and one result format: CodemodeSandbox on a worker thread per execution, RemoteCodemodeSandbox in another isolate, and InlineCodemodeSandbox on the calling thread. |
| FRFunctional Requirement.-4MustThe system shall accept an optional first-line `// @options:` directive carrying `max_output_tokens` and `timeout_ms`, and reject empty input, invalid JSON, unknown fields, a directive without code, and a directive on any line but the first. | Must | The system shall accept an optional first-line // @options: directive carrying max_output_tokens and timeout_ms, and reject empty input, invalid JSON, unknown fields, a directive without code, and a directive on any line but the first. |
| FRFunctional Requirement.-5MustThe system shall return a `CodemodeResult` that never rejects for script failures, with `ok`, `value` or `error` (`script`, `timeout`, `aborted`, `sandbox`), `output` kept for failed executions, per-call `calls`, and `storeWrites` on success. | Must | The system shall return a CodemodeResult that never rejects for script failures, with ok, value or error (script, timeout, aborted, sandbox), output kept for failed executions, per-call calls, and storeWrites on success. |
| FRFunctional Requirement.-6MustThe system shall implement `store`/`load` as a caller-owned snapshot: the caller passes `options.store`, the script reads copies synchronously, `store(key, undefined)` deletes, and a successful result reports `{ set, delete }`. | Must | The system shall implement store/load as a caller-owned snapshot: the caller passes options.store, the script reads copies synchronously, store(key, undefined) deletes, and a successful result reports { set, delete }. |
| FRFunctional Requirement.-7MustThe system shall render TypeScript declarations for tools and globals from their descriptions and JSON schemas so a model description can embed them. | Must | The system shall render TypeScript declarations for tools and globals from their descriptions and JSON schemas so a model description can embed them. |
| FRFunctional Requirement.-8MustThe system shall support deterministic runs via `start()` with fixed `startedAt`, `seed`, caller-answered calls, ordered result delivery, a VM fingerprint, and a monotonic clock. | Must | The system shall support deterministic runs via start() with fixed startedAt, seed, caller-answered calls, ordered result delivery, a VM fingerprint, and a monotonic clock. |
| FRFunctional Requirement.-9ShouldThe system shall deploy on Cloudflare Workers via a stateless sandbox Durable Object in a separate Worker plus an inline constructor, with server-side caps on interrupt budget and memory. | Should | The system shall deploy on Cloudflare Workers via a stateless sandbox Durable Object in a separate Worker plus an inline constructor, with server-side caps on interrupt budget and memory. |
| FRFunctional Requirement.-10ShouldThe system shall let the coding agent wrap `execute()` as an agent tool whose nested calls run through the agent tool pipeline while only script output reaches the model. | Should | The system shall let the coding agent wrap execute() as an agent tool whose nested calls run through the agent tool pipeline while only script output reaches the model. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-1MustThe system shall isolate scripts so nested tool calls and their results never enter the LLMLarge Language Model. context, and scripts reach no timers, `fetch`, `process`, `require`, modules, or `WebAssembly`. | Must | Security | The system shall isolate scripts so nested tool calls and their results never enter the LLMLarge Language Model. context, and scripts reach no timers, fetch, process, require, modules, or WebAssembly. |
| NFRNon-Functional Requirement.-2MustThe system shall enforce a per-execution deadline (default 300000 ms, `Infinity` disables it) and fail scripts that wait on a promise nothing can settle instead of hanging. | Must | Reliability | The system shall enforce a per-execution deadline (default 300000 ms, Infinity disables it) and fail scripts that wait on a promise nothing can settle instead of hanging. |
| NFRNon-Functional Requirement.-3MustThe system shall bound script output to `MAX_OUTPUT_CHARS` (16 Mi) and `MAX_OUTPUT_ITEMS` (100000), failing with a `RangeError` past either limit. | Must | Capacity | The system shall bound script output to MAX_OUTPUT_CHARS (16 Mi) and MAX_OUTPUT_ITEMS (100000), failing with a RangeError past either limit. |
| NFRNon-Functional Requirement.-4MustThe system shall cap VM heap use via `memoryLimitBytes` (Cloudflare default 32 MiB) and surface overuse inside the script as `InternalError: out of memory`. | Must | Capacity | The system shall cap VM heap use via memoryLimitBytes (Cloudflare default 32 MiB) and surface overuse inside the script as InternalError: out of memory. |
| NFRNon-Functional Requirement.-5MustThe system shall keep zero pi dependencies (only `quickjs-wasi`) and a `/portable` entry with no Node imports for Workers, Durable Objects, and browsers. | Must | Portability | The system shall keep zero pi dependencies (only quickjs-wasi) and a /portable entry with no Node imports for Workers, Durable Objects, and browsers. |
| NFRNon-Functional Requirement.-6ShouldThe system shall keep worker-thread startup including VM creation around 20 ms and keep pure computation interruptible via a poll-counted interrupt budget. | Should | Performance | The system shall keep worker-thread startup including VM creation around 20 ms and keep pure computation interruptible via a poll-counted interrupt budget. |
Constraints
CodemodeSandboxrequires Node or Bun (worker threads plus reading the QuickJS binary from disk).- Cloudflare Workers cannot compile WebAssembly at runtime, so the Cloudflare entry relies on the module Wrangler compiles.
- QuickJS is an interpreter, so heavy pure computation in scripts is slower than in V8.
Acceptance Criteria
Every FRFunctional Requirement. and NFRNon-Functional Requirement. shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
Acceptance criteria verify how a requirement is proven done, they do not restate it.
Write concrete, scenario-based criteria (happy path, edge cases and error states where applicable).
Write each criterion as a fenced gherkin block with a tag matching its requirement ID, so the criteria are parseable and later executable via BDD tooling (pytest-bdd, cucumber).
Multiple scenarios per requirement are allowed; tag each with the requirement ID.
-
FRFunctional Requirement.-1MustThe system shall execute model-written JavaScript in a fresh QuickJS VM per execution where calling injected tools is the only host capability.
gherkin @FRFunctional Requirement.-1MustThe system shall execute model-written JavaScript in a fresh QuickJS VM per execution where calling injected tools is the only host capability. Scenario: Script calls an injected tool and returns a value Given a sandbox with a `read` tool When the script awaits `tools.read` and returns the parsed name Then the result is ok with the tool return value and one call recordedgherkin @FRFunctional Requirement.-1MustThe system shall execute model-written JavaScript in a fresh QuickJS VM per execution where calling injected tools is the only host capability. Scenario: Script cannot reach host capabilities Given a sandbox with default configuration When the script reads `typeof process`, `typeof fetch`, and `typeof require` Then all three are `undefined` and the result is ok -
FRFunctional Requirement.-2MustThe system shall provide one script environment on every sandbox: `tools.<name>(args)` plus `tools["<name>"]`, `ALL_TOOLS`, `text(value)`, `image(urlOrItem)`, `exit()`, `console.*`, `store(key, value)`/`load(key)`, host `globals`, top-level `await`, and `return`.
gherkin @FRFunctional Requirement.-2MustThe system shall provide one script environment on every sandbox: `tools.<name>(args)` plus `tools["<name>"]`, `ALL_TOOLS`, `text(value)`, `image(urlOrItem)`, `exit()`, `console.*`, `store(key, value)`/`load(key)`, host `globals`, top-level `await`, and `return`. Scenario: Output helpers collect ordered items Given a sandbox with no tools When the script calls `text`, `console.log`, and `image` with a base64 data URL then returns Then `result.output` holds the text, console, and image items in ordergherkin @FRFunctional Requirement.-2MustThe system shall provide one script environment on every sandbox: `tools.<name>(args)` plus `tools["<name>"]`, `ALL_TOOLS`, `text(value)`, `image(urlOrItem)`, `exit()`, `console.*`, `store(key, value)`/`load(key)`, host `globals`, top-level `await`, and `return`. Scenario: exit ends the script successfully Given a sandbox with a tool that was never called When the script emits output then calls `exit()` Then the result is ok with `value` undefined and the output keptgherkin @FRFunctional Requirement.-2MustThe system shall provide one script environment on every sandbox: `tools.<name>(args)` plus `tools["<name>"]`, `ALL_TOOLS`, `text(value)`, `image(urlOrItem)`, `exit()`, `console.*`, `store(key, value)`/`load(key)`, host `globals`, top-level `await`, and `return`. Scenario: Tool names map to identifiers Given a tool named `my-tool` When the script calls it as `tools.my_tool` Then the host tool executes and the call is recorded under `my-tool` -
FRFunctional Requirement.-3MustThe system shall offer three sandboxes with one API, one script environment, and one result format: `CodemodeSandbox` on a worker thread per execution, `RemoteCodemodeSandbox` in another isolate, and `InlineCodemodeSandbox` on the calling thread.
gherkin @FRFunctional Requirement.-3MustThe system shall offer three sandboxes with one API, one script environment, and one result format: `CodemodeSandbox` on a worker thread per execution, `RemoteCodemodeSandbox` in another isolate, and `InlineCodemodeSandbox` on the calling thread. Scenario: All sandboxes share one result shape Given the worker, inline, and remote sandboxes with the same tool When the same script runs on each Then every result has `ok`, `output`, `calls`, and the same value -
FRFunctional Requirement.-4MustThe system shall accept an optional first-line `// @options:` directive carrying `max_output_tokens` and `timeout_ms`, and reject empty input, invalid JSON, unknown fields, a directive without code, and a directive on any line but the first.
gherkin @FRFunctional Requirement.-4MustThe system shall accept an optional first-line `// @options:` directive carrying `max_output_tokens` and `timeout_ms`, and reject empty input, invalid JSON, unknown fields, a directive without code, and a directive on any line but the first. Scenario: Options line parses and preserves line numbers Given source starting with `// @options: {"timeout_ms": 30000}` When `parseCodemodeSource` runs Then options carry `timeoutMs` 30000 and the code keeps its line countgherkin @FRFunctional Requirement.-4MustThe system shall accept an optional first-line `// @options:` directive carrying `max_output_tokens` and `timeout_ms`, and reject empty input, invalid JSON, unknown fields, a directive without code, and a directive on any line but the first. Scenario: Misplaced options line is rejected Given source with the options line on line 3 When `parseCodemodeSource` runs Then it throws `CodemodeSourceError` -
FRFunctional Requirement.-5MustThe system shall return a `CodemodeResult` that never rejects for script failures, with `ok`, `value` or `error` (`script`, `timeout`, `aborted`, `sandbox`), `output` kept for failed executions, per-call `calls`, and `storeWrites` on success.
gherkin @FRFunctional Requirement.-5MustThe system shall return a `CodemodeResult` that never rejects for script failures, with `ok`, `value` or `error` (`script`, `timeout`, `aborted`, `sandbox`), `output` kept for failed executions, per-call `calls`, and `storeWrites` on success. Scenario: Thrown script error keeps partial output Given a sandbox with no tools When the script calls `text("part")` then throws Then the result has `ok` false, kind `script`, and the partial outputgherkin @FRFunctional Requirement.-5MustThe system shall return a `CodemodeResult` that never rejects for script failures, with `ok`, `value` or `error` (`script`, `timeout`, `aborted`, `sandbox`), `output` kept for failed executions, per-call `calls`, and `storeWrites` on success. Scenario: Abort reports kind aborted Given a running execution with an abort signal When the signal fires Then the result has `ok` false and kind `aborted` -
FRFunctional Requirement.-6MustThe system shall implement `store`/`load` as a caller-owned snapshot: the caller passes `options.store`, the script reads copies synchronously, `store(key, undefined)` deletes, and a successful result reports `{ set, delete }`.
gherkin @FRFunctional Requirement.-6MustThe system shall implement `store`/`load` as a caller-owned snapshot: the caller passes `options.store`, the script reads copies synchronously, `store(key, undefined)` deletes, and a successful result reports `{ set, delete }`. Scenario: Store round trip reports writes Given a sandbox executed with a store snapshot When the script loads a counter, increments it, and stores it Then the result reports the key under `storeWrites.set`gherkin @FRFunctional Requirement.-6MustThe system shall implement `store`/`load` as a caller-owned snapshot: the caller passes `options.store`, the script reads copies synchronously, `store(key, undefined)` deletes, and a successful result reports `{ set, delete }`. Scenario: Loaded values are copies Given a store holding an object When the script mutates the loaded object without storing Then the result reports no writes for that key -
FRFunctional Requirement.-7MustThe system shall render TypeScript declarations for tools and globals from their descriptions and JSON schemas so a model description can embed them.
gherkin @FRFunctional Requirement.-7MustThe system shall render TypeScript declarations for tools and globals from their descriptions and JSON schemas so a model description can embed them. Scenario: Declarations render tool signatures Given a tool with a description and input and output schemas When `renderDeclarations` runs Then the output declares an async function with a doc comment -
FRFunctional Requirement.-8MustThe system shall support deterministic runs via `start()` with fixed `startedAt`, `seed`, caller-answered calls, ordered result delivery, a VM fingerprint, and a monotonic clock.
gherkin @FRFunctional Requirement.-8MustThe system shall support deterministic runs via `start()` with fixed `startedAt`, `seed`, caller-answered calls, ordered result delivery, a VM fingerprint, and a monotonic clock. Scenario: Same seed and answers replay the same calls Given a script started twice with the same `startedAt` and `seed` When the host answers both runs with the same ordered results Then both runs issue identical calls and output -
FRFunctional Requirement.-9ShouldThe system shall deploy on Cloudflare Workers via a stateless sandbox Durable Object in a separate Worker plus an inline constructor, with server-side caps on interrupt budget and memory.
gherkin @FRFunctional Requirement.-9ShouldThe system shall deploy on Cloudflare Workers via a stateless sandbox Durable Object in a separate Worker plus an inline constructor, with server-side caps on interrupt budget and memory. Scenario: Remote sandbox caps client limits Given a Durable Object with a lower `maxInterruptBudget` than the client asks for When a runaway script executes remotely Then the execution fails as `timeout` at the server cap, not the client value -
FRFunctional Requirement.-10ShouldThe system shall let the coding agent wrap `execute()` as an agent tool whose nested calls run through the agent tool pipeline while only script output reaches the model.
gherkin @FRFunctional Requirement.-10ShouldThe system shall let the coding agent wrap `execute()` as an agent tool whose nested calls run through the agent tool pipeline while only script output reaches the model. Scenario: Nested calls stay out of model context Given the agent `codemode` tool over two nested tools When a script calls both and returns a summary Then the model result holds the summary and output, not the raw nested results -
NFRNon-Functional Requirement.-1MustThe system shall isolate scripts so nested tool calls and their results never enter the LLMLarge Language Model. context, and scripts reach no timers, `fetch`, `process`, `require`, modules, or `WebAssembly`.
gherkin @NFRNon-Functional Requirement.-1MustThe system shall isolate scripts so nested tool calls and their results never enter the LLMLarge Language Model. context, and scripts reach no timers, `fetch`, `process`, `require`, modules, or `WebAssembly`. Scenario: Failed nested call rejects inside the script Given a tool that throws When the script awaits it without catching Then the script fails with kind `script` carrying the tool message -
NFRNon-Functional Requirement.-2MustThe system shall enforce a per-execution deadline (default 300000 ms, `Infinity` disables it) and fail scripts that wait on a promise nothing can settle instead of hanging.
gherkin @NFRNon-Functional Requirement.-2MustThe system shall enforce a per-execution deadline (default 300000 ms, `Infinity` disables it) and fail scripts that wait on a promise nothing can settle instead of hanging. Scenario: Deadline stops a spinning script Given a sandbox with a short `timeoutMs` When the script spins without calling tools Then the result has kind `timeout`gherkin @NFRNon-Functional Requirement.-2MustThe system shall enforce a per-execution deadline (default 300000 ms, `Infinity` disables it) and fail scripts that wait on a promise nothing can settle instead of hanging. Scenario: Stalled await fails fast Given a script awaiting a promise nothing can settle with no tool pending When the VM detects the stall Then the execution fails right away instead of hanging -
NFRNon-Functional Requirement.-3MustThe system shall bound script output to `MAX_OUTPUT_CHARS` (16 Mi) and `MAX_OUTPUT_ITEMS` (100000), failing with a `RangeError` past either limit.
gherkin @NFRNon-Functional Requirement.-3MustThe system shall bound script output to `MAX_OUTPUT_CHARS` (16 Mi) and `MAX_OUTPUT_ITEMS` (100000), failing with a `RangeError` past either limit. Scenario: Output flood fails with RangeError Given a script appending text past `MAX_OUTPUT_CHARS` When it crosses the limit Then the execution fails with a `RangeError` even if the script catches -
NFRNon-Functional Requirement.-4MustThe system shall cap VM heap use via `memoryLimitBytes` (Cloudflare default 32 MiB) and surface overuse inside the script as `InternalError: out of memory`.
gherkin @NFRNon-Functional Requirement.-4MustThe system shall cap VM heap use via `memoryLimitBytes` (Cloudflare default 32 MiB) and surface overuse inside the script as `InternalError: out of memory`. Scenario: Heap overuse fails inside the script Given a sandbox with a tiny `memoryLimitBytes` When the script allocates past it Then the script observes `InternalError: out of memory` -
NFRNon-Functional Requirement.-5MustThe system shall keep zero pi dependencies (only `quickjs-wasi`) and a `/portable` entry with no Node imports for Workers, Durable Objects, and browsers.
gherkin @NFRNon-Functional Requirement.-5MustThe system shall keep zero pi dependencies (only `quickjs-wasi`) and a `/portable` entry with no Node imports for Workers, Durable Objects, and browsers. Scenario: Portable entry imports without Node Given a runtime without `node:*` built-ins When `@earendil-works/pi-codemode/portable` is imported Then the import succeeds and both portable sandboxes construct -
NFRNon-Functional Requirement.-6ShouldThe system shall keep worker-thread startup including VM creation around 20 ms and keep pure computation interruptible via a poll-counted interrupt budget.
gherkin @NFRNon-Functional Requirement.-6ShouldThe system shall keep worker-thread startup including VM creation around 20 ms and keep pure computation interruptible via a poll-counted interrupt budget. Scenario: Runaway compute ends on interrupt budget Given an inline sandbox with a small interrupt budget When the script loops without yielding Then the result has kind `timeout` within the test deadline
Conflicts
None identified yet.
Open Questions
None. The behavior above is reverse-engineered from the shipped implementation, so no open question blocks anything.
Specification: CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. Sandbox
Overview
One host-side execution pipeline drives three VM placements that share a prelude, a JSON message protocol, and a result builder.
CodemodeSandbox runs each execution in a Node or Bun worker thread hosting a fresh QuickJS WASI instance, RemoteCodemodeSandbox moves only the VM behind an RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). exchange while tools stay with the caller, and InlineCodemodeSandbox runs the VM on the calling thread.
Deterministic start() runs fix time, randomness, timezone, and result ordering so a durable host can replay a script from a log of call results.
Architecture
flowchart TB
subgraph host["Host thread"]
SB["CodemodeSandboxBase<br/>(execute/start, timeout, store)"]
T["Injected tools<br/>(JSON round trip)"]
SB <--> T
end
subgraph vm["VM placement"]
W["CodemodeSandbox<br/>worker thread + QuickJS WASI"]
R["RemoteCodemodeSandbox<br/>Durable Object VM + RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). exchange"]
I["InlineCodemodeSandbox<br/>calling-thread VM"]
end
SB --> W
SB --> R
SB --> I
P["Prelude<br/>(tools, ALL_TOOLS, text/image/exit/console, store/load)"]
W --> P
R --> P
I --> P
AG["Agent codemode tool<br/>(packages/coding-agent)"]
AG --> SB
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
CodemodeTool
| Field | Type | Constraints | Description |
|---|---|---|---|
| name | string | required, unique per sandbox | Script calls it as tools[jsName] and tools["name"]. |
| description | string | optional | Doc comment in declarations and ALL_TOOLS entry. |
| inputSchema | CodemodeJsonSchema | optional | Rendered as the parameter type; values are not validated. |
| outputSchema | CodemodeJsonSchema | optional | Rendered as the promise type; values are not validated. |
| spread | boolean | globals only | execute receives all call arguments as an array. |
| signature | string | globals only | Replaces the schema-generated declaration. |
| execute | function | required | Receives JSON-round-tripped args plus { signal }. |
CodemodeResult
| Field | Type | Constraints | Description |
|---|---|---|---|
| ok | boolean | required | True for returned or exit() scripts, false otherwise. |
| value | unknown | ok only | JSON-round-tripped return value (undefined after exit()). |
| error | CodemodeError | !ok only | { kind, name?, message, stack? } with kind script, timeout, aborted, or sandbox. |
| output | CodemodeOutputItem[] | required, ordered | Text, console, and image items, kept for failed executions too. |
| calls | CodemodeCall[] | required | Every tool call with name, status (ok, error, cancelled), and durationMs. |
| storeWrites | CodemodeStoreWrites | ok only | { set, delete } keys the script changed. |
| during | CodemodeDuring | start() runs only | Result seq being processed when a self-ending script ended. |
CodemodeRunOptions / CodemodeRun
| Field | Type | Constraints | Description |
|---|---|---|---|
| startedAt | number | required | VM clock start in ms since the epoch. |
| seed | number | required, uint32 | Seeds Math.random() and other VM randomness. |
| tools | CodemodeDeclaredTool[] | optional | Script-visible { name, jsName?, description } per tool. |
| globals | CodemodeDeclaredGlobal[] | optional | Script-visible { name, spread? } per global. |
| store | Record | optional | Snapshot the script reads with load(). |
| onStarted | callback | optional | Receives the VM fingerprint before the script runs. |
| onCall | callback | required | Host answers each call via run.deliver(seq, now, id, outcome). |
| onIdle | callback | optional | Fires after each processed result with (seq, issued). |
CodemodeExecuteOptions
| Field | Type | Constraints | Description |
|---|---|---|---|
| signal | AbortSignal | optional | Aborts the execution with kind aborted. |
| timeoutMs | number | optional | Overrides the sandbox default (300000 ms) for one execution. |
| store | Record | optional | JSON-serializable snapshot for load(); writes are caller-persisted. |
CodemodeSourceOptions
| Field | Type | Constraints | Description |
|---|---|---|---|
| maxOutputTokens | number | non-negative safe integer | Token budget for output; the caller enforces it. |
| timeoutMs | number | positive integer up to 2147483647 | Hard deadline; the caller enforces it. |
API Contracts
There is no HTTPHypertext Transfer Protocol. surface, so no api.yaml is needed.
The contract is the TypeScript API across the package entries.
| Entry | Export | Purpose |
|---|---|---|
. |
CodemodeSandbox |
Worker-thread sandbox for Node and Bun. |
. |
loadQuickJSWasm |
Loads the QuickJS wasm bytes for bundled hosts. |
./portable |
InlineCodemodeSandbox |
Calling-thread sandbox for any WebAssembly runtime. |
./portable |
RemoteCodemodeSandbox |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode).-client sandbox keeping tools in the caller. |
./portable |
serveCodemodeRemote |
Runs the remote VM end of the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). exchange. |
./source |
parseCodemodeSource |
Splits the // @options: line from code. |
./source |
CODEMODE_SOURCE_GRAMMAR |
Lark grammar for grammar-constrained model input. |
./declarations |
renderDeclarations |
Renders tool and global TypeScript declarations. |
./cloudflare |
CodemodeSandboxDurableObject |
Stateless sandbox Durable Object for the sandbox Worker. |
./cloudflare |
createInlineCodemodeSandbox |
Inline sandbox pre-wired to the Wrangler-compiled module. |
./worker |
worker entry | Entry bundled hosts import for the worker file. |
Error codes shared across sandboxes:
| Kind | Code | Description |
|---|---|---|
| script | script |
The script threw or failed to parse; stack points at codemode.js:<line>. |
| timeout | timeout |
The deadline expired or the interrupt budget ran out; the VM was stopped. |
| aborted | aborted |
The caller signal fired or close() ran; the VM was stopped. |
| sandbox | sandbox |
The VM or transport failed (wasm trap, missing worker file, failed remote). |
Sequences
Worker-thread execute
sequenceDiagram
autonumber
participant H as Host (CodemodeSandbox)
participant W as Worker thread + QuickJS VM
participant T as Injected tool
H->>W: start VM, evaluate prelude + script
W->>H: bridge call(id, name, argsJson)
H->>T: execute(args, { signal })
T-->>H: JSON-serializable value
H->>W: settle(id, ok, payload)
W-->>H: done(ok, valueJson, output, writes)
H-->>H: build CodemodeResult
Remote execute on Cloudflare
sequenceDiagram
autonumber
participant S as SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Worker (RemoteCodemodeSandbox)
participant O as Sandbox Worker (Durable Object VM)
participant T as SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. tool
S->>O: execute(request) over RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode).
O->>S: exchange: tool call messages
S->>T: execute(args, { signal })
T-->>S: value
S->>O: exchange: result messages
O-->>S: execution settles
Deterministic start/run
sequenceDiagram
autonumber
participant H as Durable host
participant V as VM (any placement)
H->>V: start(code, startedAt, seed, declarations)
V->>H: onStarted(fingerprint)
V->>H: onCall(id=1, ...)
H->>V: deliver(seq=1, now, id=1, outcome)
V->>H: onIdle(seq=1, issued)
V-->>H: result (replayable from the delivered log)
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Script engine | QuickJS compiled to WASI WebAssembly (quickjs-wasi) |
Small embeddable interpreter with synchronous execution and no host access beyond declared imports. |
| WASI shim surface | Clock, random, and discarded stdout/stderr plus one host-call entry | The script cannot reach the host except through registered functions. |
| Worker per execution | Fresh worker thread and fresh VM per execute() on Node/Bun |
Keeps synchronous QuickJS execution off the host event loop and isolates runs. |
| Portable export | /portable entry with no node:* imports |
Lets Cloudflare Workers, Durable Objects, and browsers use the same script environment. |
| Prelude closure bridge | Single host bridge hidden in a closure; built-ins frozen read-only | The script cannot call the bridge directly, and eval/Function stay inside the same VM. |
| Cloudflare placement | Separate sandbox Worker Durable Object with tools staying in the session | A computing script in the session object or a Dynamic Worker blocks all its requests; a separate Worker limits the delay to about 50 ms. |
| Compute limits | Poll-counted interrupt budget plus Date.now() frozen on Workers |
No timer can fire while a script computes, so wall-clock timeouts cannot stop it; the budget can. |
| Deterministic runs | Fixed start time, seed, UTC clock, ordered numbered results | A durable host can resume a run after restart and get identical calls and output. |
| Store ownership | Caller-owned snapshot with storeWrites diff |
The sandbox stays stateless and works in Durable Objects that never touch storage. |
Risks and Unknowns
- A remote VM computing at abort time keeps running until its next tool call or budget exhaustion, so abort latency is bounded by the budget rather than instant.
- The interrupt budget is calibrated in polls, so its wall-clock meaning drifts across hardware and needs the cpu_ms ceiling kept in mind on Cloudflare.
- All VMs in one isolate share 128 MB, so concurrent executions on one object compete for memory.
- QuickJS interprets, so scripts doing heavy computation run slower than V8 and should delegate work to tools.
- Schemas shape declarations only and values are never validated, so malformed tool input reaches
executeunchecked.
Out of Scope
- ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. prompting, tool choice, and output token accounting beyond parsing the options line.
- Persistence of
storeWrites(owned by the caller, e.g. session custom entries). - Exporters, sampling, or telemetry for sandbox executions.
- Non-JavaScript guest languages.
Test Plan: CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. Sandbox
Scope
The plan covers the script environment, the three VM placements, the source format, declarations, deterministic runs, and the Cloudflare remote from the actual vitest suites under packages/codemode/test/.
It excludes the coding-agent codemode tool behavior, which belongs to the consumer package, and live Cloudflare deployments, which the in-process remote double stands in for.
Suite counts at sync time: sandbox.test.ts 54 tests, deterministic.test.ts 24, declarations.test.ts 17, portable.test.ts 7, source.test.ts 5.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Source options line parses | // @options: {"max_output_tokens": 2000, "timeout_ms": 30000} plus code |
Options { maxOutputTokens: 2000, timeoutMs: 30000 }, code line count unchanged |
| TC-2 | Source rejects bad input | Empty input, invalid JSON, unknown field, options-only input, misplaced options line | CodemodeSourceError for each |
| TC-3 | Schema renders primitives, unions, arrays, tuples | JSON schemas with literals, bounds, $defs refs |
One-line TypeScript with sorted properties and constraint tags |
| TC-4 | Renderer budgets long types to unknown | Oversized schema | Constraint tags dropped first, then the type becomes unknown |
| TC-5 | Recursive references stop | Self-referential schema | Renders as unknown without hanging |
| TC-6 | Tool sample and declarations render | Tools with normalized identifiers and namespaced globals | Valid declare const block with doc comments |
| TC-7 | Comment terminators escaped | Description containing */ |
Escaped so the declaration block stays valid |
| TC-8 | Store and load names reserved | Tool or global named store or load |
Constructor rejects the registration |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-9 | Script execution across all backends | Worker, inline, and in-process remote sandboxes | Return value after JSON round trip, top-level await, ordered text/image/console output |
| TC-10 | Tool calling across all backends | Registered tools including my-tool |
Async calls, concurrent calls, identifier normalization, ALL_TOOLS listing, unknown-tool rejection with close-match hint |
| TC-11 | Tool errors become catchable script errors | Tool that throws | Script Error with the same message; uncaught failure keeps partial output |
| TC-12 | Unawaited calls abort on return | Script returning with a pending call | Call reported cancelled and its signal aborts |
| TC-13 | Store snapshot and writes | Snapshot passed via options.store |
load reads copies, store reports { set, delete }, oversized writes throw RangeError with an explanation |
| TC-14 | exit() keeps output and writes |
Script calling exit() after output and a store write |
Ok result with value undefined |
| TC-15 | Stack traces map to script lines | Syntax error and thrown error | codemode.js:<line> frames in V8 Name: message style without prelude frames |
| TC-16 | Deterministic replay on worker and remote | Same startedAt, seed, and ordered results |
Identical calls and output; fingerprint before any call; monotonic clock enforced |
| TC-17 | Out-of-order delivery applies in seq order | Delayed first result on the remote transport | VM waits for the missing number and applies results strictly 1, 2, ... |
| TC-18 | Abort ends a run uncatchably | Aborted start() run signal |
Run fails with an error the script cannot catch and finished is set |
| TC-19 | execute() stays non-deterministic |
Default execution | Real clock and real randomness observed |
| TC-20 | Inline budget ends compute as timeout | Small interruptBudget with spinning scripts |
Kind timeout for while (true) {} and while (true) await null |
| TC-21 | Remote runs tools in the caller | In-process recording remote | Script runs remotely, tools execute locally, output is batched not per-line |
| TC-22 | Remote caps client limits | Client asking above server maxInterruptBudget |
Server cap wins and runaway compute fails as timeout |
| TC-23 | Caller abort stops the remote | Aborted remote execution | Remote told to stop; failing or vanishing remote reports kind sandbox |
| TC-24 | Embedded sources parse as JavaScript | raw-worker.ts fixture |
Fixture content parses with the project parser |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-25 | Agent-style tool round trip | Expose agent tools to a sandbox, run a script calling two of them, collect output and return value | Ok result whose output plus JSON return value carry the composed answer |
| TC-26 | Cloudflare example wiring | Follow examples/cloudflare agent plus sandbox Workers with per-session object naming |
Scripts execute in the sandbox Worker and tool calls resolve in the agent Worker |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-27 | Stalled await with nothing pending | VM reports stalled |
| TC-28 | Non-serializable return value | Script returns a non-JSON value |
| TC-29 | Non-Error throw | Script throws a string |
| TC-30 | Invalid text()/image() arguments |
Bad shapes and remote URLs |
| TC-31 | Unserializable call answer in a run | Host delivers a value JSON cannot carry |
| TC-32 | Duplicate result number or unknown call id | Host mis-delivers |
| TC-33 | Non-finite clock value | Host delivers NaN as now |
| TC-34 | Register and unregister between executions | Tool added then removed |
Test Infrastructure
- Vitest suites under
packages/codemode/test/with a backend matrix (worker, inline, in-process remote) insandbox.test.tsanddeterministic.test.ts. - The in-process remote double structured-clones every message, matching Workers RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). semantics.
test/fixtures/raw-worker.tsfixture for the embedded worker source parse test.- No live Cloudflare account or deployment is needed for any suite.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FRFunctional Requirement.-1MustThe system shall execute model-written JavaScript in a fresh QuickJS VM per execution where calling injected tools is the only host capability. | TC-9, TC-10, TC-24 |
| FRFunctional Requirement.-2MustThe system shall provide one script environment on every sandbox: `tools.<name>(args)` plus `tools["<name>"]`, `ALL_TOOLS`, `text(value)`, `image(urlOrItem)`, `exit()`, `console.*`, `store(key, value)`/`load(key)`, host `globals`, top-level `await`, and `return`. | TC-9, TC-10, TC-11, TC-14, TC-15, TC-30 |
| FRFunctional Requirement.-3MustThe system shall offer three sandboxes with one API, one script environment, and one result format: `CodemodeSandbox` on a worker thread per execution, `RemoteCodemodeSandbox` in another isolate, and `InlineCodemodeSandbox` on the calling thread. | TC-9, TC-20, TC-21 |
| FRFunctional Requirement.-4MustThe system shall accept an optional first-line `// @options:` directive carrying `max_output_tokens` and `timeout_ms`, and reject empty input, invalid JSON, unknown fields, a directive without code, and a directive on any line but the first. | TC-1, TC-2 |
| FRFunctional Requirement.-5MustThe system shall return a `CodemodeResult` that never rejects for script failures, with `ok`, `value` or `error` (`script`, `timeout`, `aborted`, `sandbox`), `output` kept for failed executions, per-call `calls`, and `storeWrites` on success. | TC-11, TC-12, TC-14, TC-15, TC-23, TC-27, TC-28, TC-29 |
| FRFunctional Requirement.-6MustThe system shall implement `store`/`load` as a caller-owned snapshot: the caller passes `options.store`, the script reads copies synchronously, `store(key, undefined)` deletes, and a successful result reports `{ set, delete }`. | TC-13, TC-34 |
| FRFunctional Requirement.-7MustThe system shall render TypeScript declarations for tools and globals from their descriptions and JSON schemas so a model description can embed them. | TC-3, TC-4, TC-5, TC-6, TC-7 |
| FRFunctional Requirement.-8MustThe system shall support deterministic runs via `start()` with fixed `startedAt`, `seed`, caller-answered calls, ordered result delivery, a VM fingerprint, and a monotonic clock. | TC-16, TC-17, TC-18, TC-19, TC-31, TC-32, TC-33 |
| FRFunctional Requirement.-9ShouldThe system shall deploy on Cloudflare Workers via a stateless sandbox Durable Object in a separate Worker plus an inline constructor, with server-side caps on interrupt budget and memory. | TC-21, TC-22, TC-23, TC-26 |
| FRFunctional Requirement.-10ShouldThe system shall let the coding agent wrap `execute()` as an agent tool whose nested calls run through the agent tool pipeline while only script output reaches the model. | TC-25 |
| NFRNon-Functional Requirement.-1MustThe system shall isolate scripts so nested tool calls and their results never enter the LLMLarge Language Model. context, and scripts reach no timers, `fetch`, `process`, `require`, modules, or `WebAssembly`. | TC-10, TC-11 |
| NFRNon-Functional Requirement.-2MustThe system shall enforce a per-execution deadline (default 300000 ms, `Infinity` disables it) and fail scripts that wait on a promise nothing can settle instead of hanging. | TC-20, TC-27 |
| NFRNon-Functional Requirement.-3MustThe system shall bound script output to `MAX_OUTPUT_CHARS` (16 Mi) and `MAX_OUTPUT_ITEMS` (100000), failing with a `RangeError` past either limit. | TC-13 |
| NFRNon-Functional Requirement.-4MustThe system shall cap VM heap use via `memoryLimitBytes` (Cloudflare default 32 MiB) and surface overuse inside the script as `InternalError: out of memory`. | TC-22 |
| NFRNon-Functional Requirement.-5MustThe system shall keep zero pi dependencies (only `quickjs-wasi`) and a `/portable` entry with no Node imports for Workers, Durable Objects, and browsers. | TC-9, TC-21 |
| NFRNon-Functional Requirement.-6ShouldThe system shall keep worker-thread startup including VM creation around 20 ms and keep pure computation interruptible via a poll-counted interrupt budget. | TC-20 |
requirements
None. The behavior above is reverse-engineered from the shipped implementation, so no open question blocks anything.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Remote Execution Env
Overview
Agents need their tools to run on a remote machine, usually reached over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines)., while the Durable worker, its storage, and its credentials stay local.
This feature provides a Rust daemon that runs on the remote machine plus a Durable ExecutionEnv client (RemoteExecutionEnv) that talks to it through a lazily started Connection.
LocalExecutionEnv reuses the same daemon on the local machine so local and remote file listings share one implementation.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Agent runtime (Durable) | Runs tools against any ExecutionEnv without knowing whether it is local or remote |
| Machine owner | Accepts host keys out of band and deploys a verified daemon to their remote machines |
| Daemon operator | Debugs remote failures from daemon diagnostics and client error codes |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-1MustThe system shall run a daemon on the remote machine that performs file operations and commands there over a framed protocol on stdin and stdout (`docs/protocol.md`). | Must | The system shall run a daemon on the remote machine that performs file operations and commands there over a framed protocol on stdin and stdout (docs/protocol.md). |
| FRFunctional Requirement.-2MustThe system shall detect the remote system (Linux, macOS, Android Termux, Windows on x86-64 and arm64), deploy the matching daemon binary when missing or changed, and verify it by SHA-256 before every start. | Must | The system shall detect the remote system (Linux, macOS, Android Termux, Windows on x86-64 and arm64), deploy the matching daemon binary when missing or changed, and verify it by SHA-256 before every start. |
| FRFunctional Requirement.-3MustThe system shall connect over the system `ssh` with strict host-key checking against the application's own known-hosts file under a fixed alias, with no forwarding, no shared connections, and no locale forwarding. | Must | The system shall connect over the system ssh with strict host-key checking against the application's own known-hosts file under a fixed alias, with no forwarding, no shared connections, and no locale forwarding. |
| FRFunctional Requirement.-4MustThe system shall require explicit host-key trust: `scanHostKey` shows fingerprints for out-of-band comparison, `acceptHostKey` records them, and a changed key is never accepted automatically. | Must | The system shall require explicit host-key trust: scanHostKey shows fingerprints for out-of-band comparison, acceptHostKey records them, and a changed key is never accepted automatically. |
| FRFunctional Requirement.-5MustThe system shall start the connection lazily on the first operation and retry the next operation after a failure; a lost connection fails in-flight requests and a new daemon starts on the next request. | Must | The system shall start the connection lazily on the first operation and retry the next operation after a failure; a lost connection fails in-flight requests and a new daemon starts on the next request. |
| FRFunctional Requirement.-6MustThe system shall make `RemoteExecutionEnv` results match `NodeExecutionEnv` running on the remote machine, with only error messages allowed to differ (`docs/semantics.md`). | Must | The system shall make RemoteExecutionEnv results match NodeExecutionEnv running on the remote machine, with only error messages allowed to differ (docs/semantics.md). |
| FRFunctional Requirement.-7MustThe system shall list the file tree below a directory in the daemon (`listFiles`, bounded by `maxEntries`, `maxBytes`, `timeoutMs` with a `truncated` flag), skipping `.git`, excluded names, and git-ignored entries without following symbolic links. | Must | The system shall list the file tree below a directory in the daemon (listFiles, bounded by maxEntries, maxBytes, timeoutMs with a truncated flag), skipping .git, excluded names, and git-ignored entries without following symbolic links. |
| FRFunctional Requirement.-8ShouldThe system shall run interactive programs in a daemon pseudo-terminal (`openTerminal`), reporting raw output, input, resize, and exit code. | Should | The system shall run interactive programs in a daemon pseudo-terminal (openTerminal), reporting raw output, input, resize, and exit code. |
| FRFunctional Requirement.-9ShouldThe system shall report older daemons that lack `listFiles` as `not_supported` via `hello.features` so callers fall back to their own walk. | Should | The system shall report older daemons that lack listFiles as not_supported via hello.features so callers fall back to their own walk. |
| FRFunctional Requirement.-10MayThe system shall provide `LocalExecutionEnv` (`NodeExecutionEnv` plus daemon-backed `listFiles` on the same machine) for local sessions. | May | The system shall provide LocalExecutionEnv (NodeExecutionEnv plus daemon-backed listFiles on the same machine) for local sessions. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-1MustThe system shall never forward agents, X11, or local commands, never run `ssh` with prompts (`BatchMode`), and never start a daemon whose hash was not verified. | Must | Security | The system shall never forward agents, X11, or local commands, never run ssh with prompts (BatchMode), and never start a daemon whose hash was not verified. |
| NFRNon-Functional Requirement.-2MustThe system shall support Linux, macOS, Android (Termux), and Windows on x86-64 and arm64, including Windows string commands through Git Bash. | Must | Compatibility | The system shall support Linux, macOS, Android (Termux), and Windows on x86-64 and arm64, including Windows string commands through Git Bash. |
| NFRNon-Functional Requirement.-3ShouldThe system shall kill every remote process group it started and exit the daemon after 30 seconds without receiving bytes or when stdin ends. | Should | Reliability | The system shall kill every remote process group it started and exit the daemon after 30 seconds without receiving bytes or when stdin ends. |
| NFRNon-Functional Requirement.-4ShouldThe system shall bound frames at 16 MiB, pace command output through windows, and answer control frames ahead of bulk data. | Should | Performance | The system shall bound frames at 16 MiB, pace command output through windows, and answer control frames ahead of bulk data. |
Constraints
- The daemon is a Rust program shipped per supported remote system in
bin/. - There is no HTTPHypertext Transfer Protocol. surface; the only wire contract is the framed stdio protocol in
docs/protocol.md. - Windows terminals are not supported yet.
Acceptance Criteria
Every FRFunctional Requirement. and NFRNon-Functional Requirement. shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
-
FRFunctional Requirement.-1MustThe system shall run a daemon on the remote machine that performs file operations and commands there over a framed protocol on stdin and stdout (`docs/protocol.md`).
gherkin @FRFunctional Requirement.-1MustThe system shall run a daemon on the remote machine that performs file operations and commands there over a framed protocol on stdin and stdout (`docs/protocol.md`). Scenario: daemon serves file operations over stdio Given a built daemon binary started with serve and a token When the client sends framed hello and lstat requests Then the daemon answers with its info and file metadata -
FRFunctional Requirement.-2MustThe system shall detect the remote system (Linux, macOS, Android Termux, Windows on x86-64 and arm64), deploy the matching daemon binary when missing or changed, and verify it by SHA-256 before every start.
gherkin @FRFunctional Requirement.-2MustThe system shall detect the remote system (Linux, macOS, Android Termux, Windows on x86-64 and arm64), deploy the matching daemon binary when missing or changed, and verify it by SHA-256 before every start. Scenario: missing daemon is deployed and verified Given an SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). target whose remote tool directory lacks the current daemon When connectSsh runs detection and deployment Then the daemon at the SHA-256 named path matches the shipped binary before it starts -
FRFunctional Requirement.-3MustThe system shall connect over the system `ssh` with strict host-key checking against the application's own known-hosts file under a fixed alias, with no forwarding, no shared connections, and no locale forwarding.
gherkin @FRFunctional Requirement.-3MustThe system shall connect over the system `ssh` with strict host-key checking against the application's own known-hosts file under a fixed alias, with no forwarding, no shared connections, and no locale forwarding. Scenario: ssh runs hardened Given any SshTarget When sshArguments builds the command line Then BatchMode is on, all forwardings are off, and host keys resolve only against the application known-hosts file -
FRFunctional Requirement.-4MustThe system shall require explicit host-key trust: `scanHostKey` shows fingerprints for out-of-band comparison, `acceptHostKey` records them, and a changed key is never accepted automatically.
gherkin @FRFunctional Requirement.-4MustThe system shall require explicit host-key trust: `scanHostKey` shows fingerprints for out-of-band comparison, `acceptHostKey` records them, and a changed key is never accepted automatically. Scenario: unknown host key blocks connection until accepted Given a target whose key is not in the known-hosts file When the client connects Then it fails with HostKeyUnknownError and succeeds only after scanHostKey fingerprints are acceptedgherkin @FRFunctional Requirement.-4MustThe system shall require explicit host-key trust: `scanHostKey` shows fingerprints for out-of-band comparison, `acceptHostKey` records them, and a changed key is never accepted automatically. Scenario: changed host key is refused Given a target whose presented key differs from the trusted key of the same type When acceptHostKey is called with the new lines Then it rejects with HostKeyChangedError until forgetHostKey removes the old keys -
FRFunctional Requirement.-5MustThe system shall start the connection lazily on the first operation and retry the next operation after a failure; a lost connection fails in-flight requests and a new daemon starts on the next request.
gherkin @FRFunctional Requirement.-5MustThe system shall start the connection lazily on the first operation and retry the next operation after a failure; a lost connection fails in-flight requests and a new daemon starts on the next request. Scenario: lazy connection retries after failure Given an sshConnection with no network on first use When the first operation fails and the network returns Then the next operation detects, deploys, and connects without recreating the env -
FRFunctional Requirement.-6MustThe system shall make `RemoteExecutionEnv` results match `NodeExecutionEnv` running on the remote machine, with only error messages allowed to differ (`docs/semantics.md`).
gherkin @FRFunctional Requirement.-6MustThe system shall make `RemoteExecutionEnv` results match `NodeExecutionEnv` running on the remote machine, with only error messages allowed to differ (`docs/semantics.md`). Scenario: remote results match NodeExecutionEnv Given the same operation sequence against RemoteExecutionEnv and NodeExecutionEnv When the differential suite compares them Then results match except error message text -
FRFunctional Requirement.-7MustThe system shall list the file tree below a directory in the daemon (`listFiles`, bounded by `maxEntries`, `maxBytes`, `timeoutMs` with a `truncated` flag), skipping `.git`, excluded names, and git-ignored entries without following symbolic links.
gherkin @FRFunctional Requirement.-7MustThe system shall list the file tree below a directory in the daemon (`listFiles`, bounded by `maxEntries`, `maxBytes`, `timeoutMs` with a `truncated` flag), skipping `.git`, excluded names, and git-ignored entries without following symbolic links. Scenario: bounded listing with truncation flag Given a directory tree larger than maxEntries When listFiles runs with a small maxEntries limit Then it returns the first entries with truncated true -
FRFunctional Requirement.-8ShouldThe system shall run interactive programs in a daemon pseudo-terminal (`openTerminal`), reporting raw output, input, resize, and exit code.
gherkin @FRFunctional Requirement.-8ShouldThe system shall run interactive programs in a daemon pseudo-terminal (`openTerminal`), reporting raw output, input, resize, and exit code. Scenario: interactive terminal echoes and exits Given a connection to a POSIX daemon When openTerminal runs the login shell and sends input Then raw output streams back and the exit code is reported on completion -
FRFunctional Requirement.-9ShouldThe system shall report older daemons that lack `listFiles` as `not_supported` via `hello.features` so callers fall back to their own walk.
gherkin @FRFunctional Requirement.-9ShouldThe system shall report older daemons that lack `listFiles` as `not_supported` via `hello.features` so callers fall back to their own walk. Scenario: old daemon falls back Given a daemon whose hello features lack listFiles When listFiles is called Then it fails with not_supported so the caller walks the tree itself -
FRFunctional Requirement.-10MayThe system shall provide `LocalExecutionEnv` (`NodeExecutionEnv` plus daemon-backed `listFiles` on the same machine) for local sessions.
gherkin @FRFunctional Requirement.-10MayThe system shall provide `LocalExecutionEnv` (`NodeExecutionEnv` plus daemon-backed `listFiles` on the same machine) for local sessions. Scenario: local env lists through local daemon Given a LocalExecutionEnv with a connection to localDaemon When listFiles runs on a local directory Then entries match the daemon implementation used by remote envs -
NFRNon-Functional Requirement.-1MustThe system shall never forward agents, X11, or local commands, never run `ssh` with prompts (`BatchMode`), and never start a daemon whose hash was not verified.
gherkin @NFRNon-Functional Requirement.-1MustThe system shall never forward agents, X11, or local commands, never run `ssh` with prompts (`BatchMode`), and never start a daemon whose hash was not verified. Scenario: no forwarding or prompts in ssh invocation Given the ssh argument builder When any connection command is produced Then ForwardAgent, ForwardX11, and PermitLocalCommand are disabled and BatchMode is enabled -
NFRNon-Functional Requirement.-2MustThe system shall support Linux, macOS, Android (Termux), and Windows on x86-64 and arm64, including Windows string commands through Git Bash.
gherkin @NFRNon-Functional Requirement.-2MustThe system shall support Linux, macOS, Android (Termux), and Windows on x86-64 and arm64, including Windows string commands through Git Bash. Scenario: platform matrix detected Given reachable Linux, macOS, Android, and Windows targets in both architectures When detectPlatform probes each Then each reports its platform, arch, and home correctly -
NFRNon-Functional Requirement.-3ShouldThe system shall kill every remote process group it started and exit the daemon after 30 seconds without receiving bytes or when stdin ends.
gherkin @NFRNon-Functional Requirement.-3ShouldThe system shall kill every remote process group it started and exit the daemon after 30 seconds without receiving bytes or when stdin ends. Scenario: dropped connection stops remote commands Given running remote commands with their output When the client stops sending bytes for 30 seconds Then the daemon kills every process group it started and exits -
NFRNon-Functional Requirement.-4ShouldThe system shall bound frames at 16 MiB, pace command output through windows, and answer control frames ahead of bulk data.
gherkin @NFRNon-Functional Requirement.-4ShouldThe system shall bound frames at 16 MiB, pace command output through windows, and answer control frames ahead of bulk data. Scenario: large output is paced not lost Given a command producing output beyond the window When it runs with a window configured Then coalesced output arrives with skipped accounting and control replies are not starved
Conflicts
None identified yet.
Open Questions
- Which remote systems beyond Linux, macOS, Android Termux, and Windows must be supported before this feature is declared complete.
- Whether Windows pseudo-terminal support has a required delivery date or stays out of scope indefinitely.
Specification: Remote Execution Env
Overview
A small Rust daemon (daemon/, crate pi-env) runs on the remote machine and speaks a framed request/response protocol over its stdin and stdout.
The TypeScript client (packages/env/src/) opens a Connection to one daemon process, detects the remote platform and deploys the matching binary over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). before starting it, and exposes the daemon through RemoteExecutionEnv, which implements Durable's ExecutionEnv with Node's path, error, and result rules applied client-side.
Architecture
flowchart LR
subgraph local["Local machine"]
Durable["Durable worker"]
Env["RemoteExecutionEnv"]
Conn["Connection"]
SSHSecure Shell (transport pi-env uses to start its daemon on remote machines).["ssh transport"]
Durable --> Env
Env --> Conn
Conn --> SSHSecure Shell (transport pi-env uses to start its daemon on remote machines).
end
subgraph remote["Remote machine"]
Daemon["pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout."]
FS["files and processes"]
end
SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). --> Daemon
Daemon --> FS
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
RemoteInfo (hello reply)
| Field | Type | Constraints | Description |
|---|---|---|---|
| protocol | number | Must be 1 | Wire protocol version |
| version | string | Not null | npm package version the daemon shipped with |
| os | string | Rust spelling | linux, android, macos, or windows |
| arch | string | Rust spelling | x86_64 or aarch64, mapped by nodePlatform |
| home | string | Not null | Remote home directory |
| tmpdir | string | Not null | Follows remote Node os.tmpdir rules |
| separator | string | / or \ |
Remote path separator |
| cwd | string | Not null | Daemon working directory for drive-relative resolution |
| driveCwds | map | Windows only | Per-drive working directories from =C: variables |
| pid | number | Not null | Daemon process id |
| features | string[] | Optional | Protocol-1 additions this daemon supports (e.g. listFiles) |
Frame (both directions, big-endian)
| Field | Type | Constraints | Description |
|---|---|---|---|
| length | u32 | 9 to 16 MiB | Bytes after this field |
| type | u8 | 1 to 6 | request, result, error, event, cancel, ping |
| id | u32 | 0 for unowned frames | Request id the frame belongs to |
| jsonLength | u32 | Within length | UTF-8 JSON object size |
| json | object | Must parse | op plus operation fields; errors carry { code, message, syscall?, path? } |
| payload | bytes | Remainder | File contents, command output, or listing records |
SshTarget
| Field | Type | Constraints | Description |
|---|---|---|---|
| host | string | No leading dash or whitespace | Host name or ~/.ssh/config alias |
| user | string | Optional | Remote login user |
| port | number | Optional, 1 to 65535 | SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). port |
| identityFile | string | Optional | Key file, forced with IdentitiesOnly |
| knownHostsFile | string | Not null | Application-owned trust store |
| hostKeyAlias | string | Not null | Fixed alias keys are stored under |
| ssh | string | Optional | ssh program override |
| configFile | string | Optional | -F config instead of ~/.ssh/config |
RemotePlatform
| Field | Type | Constraints | Description |
|---|---|---|---|
| platform | enum | linux, android, darwin, windows |
Detected remote system |
| arch | enum | x64, arm64 |
Normalized architecture |
| home | string | Not null | Remote home in remote spelling |
| shell | enum | Windows only | cmd or powershell default shell |
| warnings | string[] | Not null | Operator notices (e.g. Termux without termux-exec) |
API Contracts
There is no HTTPHypertext Transfer Protocol. surface, so there is no api.yaml.
The normative wire contract is packages/env/docs/protocol.md; result parity rules are packages/env/docs/semantics.md.
The TypeScript surface is:
| Export | Kind | Purpose |
|---|---|---|
RemoteExecutionEnv |
class | Durable ExecutionEnv on another machine through a Connection |
LocalExecutionEnv |
class | NodeExecutionEnv with daemon-backed listFiles on the same machine |
Connection |
class | Lazily started, self-restarting session with one daemon process |
connectSsh |
function | Detect and deploy now, return a connection that starts the daemon over ssh |
sshConnection |
function | Lazy connection that detects, deploys, and connects on first request |
scanHostKey |
function | Capture presented host keys plus fingerprints against a temporary file |
acceptHostKey |
function | Trust scanned key lines, refusing changed keys of the same type |
forgetHostKey |
function | Remove all trusted keys for the alias |
detectPlatform |
function | Probe the remote system via login shell or PowerShell |
deployDaemon |
function | Upload the matching binary to its SHA-256 named path and verify it |
openTerminal |
function | Run a program in a daemon pseudo-terminal |
nodePlatform |
function | Map Rust os/arch spellings to Node platform names |
localDaemon |
function | Path of the shipped daemon for this machine |
Error codes shared across operations:
| Code | Description |
|---|---|
| ENOENT and Node-style codes | File failures; the client maps them via toFileError as NodeExecutionEnv does |
| shell_unavailable | Configured shell path does not exist |
| spawn_error | Process or connection start failure, carrying lost: true when the connection is gone |
| timeout | Command exceeded its timeout |
| aborted | Request cancelled; abort settles exec as aborted, cleanup kills without aborting |
| unknown | Anything else, including lost connections (lost: true), forcing reconnect on next request |
| not_supported | Daemon predates listFiles; callers fall back to their own walk |
Sequences
Detect, deploy, connect, execute
sequenceDiagram
autonumber
participant E as RemoteExecutionEnv
participant C as Connection
participant S as ssh + remote shell
participant D as pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout.
E->>C: request (first op triggers start)
C->>S: detect platform (POSIX probe, PowerShell fallback)
S-->>C: RemotePlatform
C->>S: check SHA-256 named binary, upload if missing
S-->>C: verified daemon path
C->>S: start daemon over ssh
D-->>C: PI-ENV token sync line
C->>D: hello { protocol: 1 }
D-->>C: RemoteInfo
E->>D: exec / file ops (framed requests)
D-->>E: results, errors, events
Lazy retry after failure
sequenceDiagram
autonumber
participant E as RemoteExecutionEnv
participant C as Connection
E->>C: op (start fails: no network, untrusted key)
C-->>E: spawn_error with ssh diagnostics
E->>C: next op (new start attempt)
C-->>E: fresh session, request succeeds
Cancellation and liveness
sequenceDiagram
autonumber
participant C as Connection
participant D as pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout.
C->>D: cancel { id }
D-->>C: exec and pty kill the process group, finish aborted
C->>D: ping (every 5 s)
D-->>C: ping (every 5 s; daemon exits after 30 s of silence)
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Daemon language | Rust (daemon/, crate pi-env) |
Single static binary per platform with no remote runtime dependency |
| Transport | Framed stdio protocol over the daemon child process | Works over any ssh invocation and locally over a pipe with identical code |
| Shell banner tolerance | PI-ENV <token> sync line |
Login shell startup files may print to stdout before the daemon runs |
| Split of work | Daemon does syscalls, client applies Node rules | Guarantees parity with NodeExecutionEnv on the remote machine |
| Daemon naming | Remote path includes full SHA-256 | Versions never collide and verification precedes every start |
| Host-key trust | Application-owned known-hosts file plus fixed alias | Trust is independent of aliases, ports, and jump hosts |
| Watching | Port of NodeFileWatcher inside the daemon |
Native events only trigger rescans next to the files; reconnect reports overflow |
| Output handling | Windowed, paced, spillable exec output | Slow links delay bulk data, not control replies |
Risks and Unknowns
- A changed host key blocks the owner until they confirm it out of band and forget the old key, which can strand automation.
- SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). hardening (no multiplexing, no locale forwarding) adds one connection per daemon start and may slow high-churn workloads.
- POSIX remotes without
sha256sum,shasum, oropensslcannot verify the daemon and are refused outright. - Handles belong to the daemon session that opened them, so every reconnect invalidates open readers and watchers.
Out of Scope
- HTTPHypertext Transfer Protocol. or any other management surface on the daemon.
- Windows pseudo-terminals (
ptyreturnsENOTSUPthere). - Credential or secret management on the remote machine; credentials stay local.
Test Plan: Remote Execution Env
Scope
The framed stdio protocol, the SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). detection and deployment flow, RemoteExecutionEnv parity with NodeExecutionEnv, listFiles, terminals, and watching are in scope.
Real-SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). coverage gated on PI_ENV_SSH_HOST documents the manual path and is not run in CIContinuous Integration (the `ci` GitHub workflow). by default.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | ssh argument hardening | Any SshTarget | BatchMode on, forwardings off, strict keys against the application file |
| TC-2 | host-key line parsing | Scanned known-hosts lines | Plain alias lines accepted, markers and patterns rejected |
| TC-3 | frame codec round trip | Request, result, error, event, cancel, ping frames | Parsed id, JSON, and payload match what was written |
| TC-4 | corrupt frame handling | Overlong or unparseable frame | Connection torn down with a lost error |
| TC-5 | error code mapping | Daemon error codes | Client FileError codes match NodeExecutionEnv mapping |
| TC-6 | path resolution | ~, file://, relative, drive-relative paths |
Absolute remote paths under remote path rules |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-7 | conformance suite over piped daemon | Debug daemon binary or PI_ENV_DAEMON |
Durable env conformance suite passes against RemoteExecutionEnv |
| TC-8 | differential operation sequences | Same-machine daemon | Random sequences match NodeExecutionEnv except error messages |
| TC-9 | Durable tools comparison | Same-machine daemon | Tool results match NodeExecutionEnv |
| TC-10 | old daemon fallback | Daemon without listFiles feature |
not_supported error and caller-side walk |
| TC-11 | terminal session | POSIX daemon | terminal.test.ts input, resize, and exit code behavior |
| TC-12 | reconnect semantics | Killed daemon mid-request | In-flight requests fail lost, next request starts a new daemon, stale handles fail |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-13 | SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). deploy and execute | PI_ENV_SSH_HOST set, trusted host key |
Detect, deploy, connect, and run the suite over a real SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). server |
| TC-14 | lazy connection recovery | Unreachable target, then reachable | First op fails with its diagnostics, next op connects |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-15 | Changed host key | HostKeyChangedError, never auto-accepted |
| TC-16 | Daemon upload corruption | Hash mismatch removes the temp file and fails the deploy |
| TC-17 | Remote without hash tools | Deploy refused with a no-verification error |
| TC-18 | Shell banner on stdout | Bytes before the PI-ENV sync line are discarded |
| TC-19 | Watch reconnect | Watcher reopens on the new daemon and reports overflow |
Test Infrastructure
test/daemon.tsspawns the daemon over a pipe;PI_ENV_DAEMONoverrides the binary under test.test/old-daemon.tspins the pre-listFilesdaemon for fallback coverage.test/ssh-external.test.tsruns the suite over a real SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). server whenPI_ENV_SSH_HOSTis set.- Test files present:
conformance.test.ts,differential.test.ts,remote.test.ts,ssh.test.ts,terminal.test.ts,ssh-external.test.ts.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FRFunctional Requirement.-1MustThe system shall run a daemon on the remote machine that performs file operations and commands there over a framed protocol on stdin and stdout (`docs/protocol.md`). | TC-3, TC-4, TC-7 |
| FRFunctional Requirement.-2MustThe system shall detect the remote system (Linux, macOS, Android Termux, Windows on x86-64 and arm64), deploy the matching daemon binary when missing or changed, and verify it by SHA-256 before every start. | TC-13 |
| FRFunctional Requirement.-3MustThe system shall connect over the system `ssh` with strict host-key checking against the application's own known-hosts file under a fixed alias, with no forwarding, no shared connections, and no locale forwarding. | TC-1 |
| FRFunctional Requirement.-4MustThe system shall require explicit host-key trust: `scanHostKey` shows fingerprints for out-of-band comparison, `acceptHostKey` records them, and a changed key is never accepted automatically. | TC-2, TC-15 |
| FRFunctional Requirement.-5MustThe system shall start the connection lazily on the first operation and retry the next operation after a failure; a lost connection fails in-flight requests and a new daemon starts on the next request. | TC-12, TC-14 |
| FRFunctional Requirement.-6MustThe system shall make `RemoteExecutionEnv` results match `NodeExecutionEnv` running on the remote machine, with only error messages allowed to differ (`docs/semantics.md`). | TC-7, TC-8, TC-9 |
| FRFunctional Requirement.-7MustThe system shall list the file tree below a directory in the daemon (`listFiles`, bounded by `maxEntries`, `maxBytes`, `timeoutMs` with a `truncated` flag), skipping `.git`, excluded names, and git-ignored entries without following symbolic links. | TC-10 |
| FRFunctional Requirement.-8ShouldThe system shall run interactive programs in a daemon pseudo-terminal (`openTerminal`), reporting raw output, input, resize, and exit code. | TC-11 |
| FRFunctional Requirement.-9ShouldThe system shall report older daemons that lack `listFiles` as `not_supported` via `hello.features` so callers fall back to their own walk. | TC-10 |
| FRFunctional Requirement.-10MayThe system shall provide `LocalExecutionEnv` (`NodeExecutionEnv` plus daemon-backed `listFiles` on the same machine) for local sessions. | TC-7 |
| NFRNon-Functional Requirement.-1MustThe system shall never forward agents, X11, or local commands, never run `ssh` with prompts (`BatchMode`), and never start a daemon whose hash was not verified. | TC-1 |
| NFRNon-Functional Requirement.-2MustThe system shall support Linux, macOS, Android (Termux), and Windows on x86-64 and arm64, including Windows string commands through Git Bash. | TC-13 |
| NFRNon-Functional Requirement.-3ShouldThe system shall kill every remote process group it started and exit the daemon after 30 seconds without receiving bytes or when stdin ends. | TC-12 |
| NFRNon-Functional Requirement.-4ShouldThe system shall bound frames at 16 MiB, pace command output through windows, and answer control frames ahead of bulk data. | TC-8 |
requirements
- Which remote systems beyond Linux, macOS, Android Termux, and Windows must be supported before this feature is declared complete.
- Whether Windows pseudo-terminal support has a required delivery date or stays out of scope indefinitely.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Client
Overview
PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. needs a standalone ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol client plus a built-in replaceable extension so the agent can call tools and read resources from user-configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers without depending on the official MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). SDKSoftware Development Kit (the embeddable programmatic API)..
The client core owns initialization, request correlation, timeouts, cancellation, progress, and server-request handling, while pluggable transports own framing and I/O.
The built-in extension connects servers from mcp.json and extension-registered servers, adapts their tools into pi's tool pipeline, and exposes them to the model through configurable exposure modes.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Agent users | Call MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). tools and read MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). resources from their configured servers reliably |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. authors | Register additional MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and replace the built-in extension behavior |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server operators | Serve tools and resources to pi over stdio or Streamable HTTPHypertext Transfer Protocol. with OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). sign-in |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-1MustThe system shall connect to an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server through a transport, negotiate a supported protocol version, and send `notifications/initialized` | Must | The system shall connect to an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server through a transport, negotiate a supported protocol version, and send notifications/initialized |
| FRFunctional Requirement.-2MustThe system shall list all tools of a server by following `tools/list` pagination cursors | Must | The system shall list all tools of a server by following tools/list pagination cursors |
| FRFunctional Requirement.-3MustThe system shall call a server tool and return its `CallToolResult` including structured content and the `isError` flag | Must | The system shall call a server tool and return its CallToolResult including structured content and the isError flag |
| FRFunctional Requirement.-4MustThe system shall list resources, list resource templates, and read resources from a server | Must | The system shall list resources, list resource templates, and read resources from a server |
| FRFunctional Requirement.-5MustThe system shall answer server `ping` and `roots/list` requests with the configured roots | Must | The system shall answer server ping and roots/list requests with the configured roots |
| FRFunctional Requirement.-6MustThe system shall support per-request timeouts, abort-signal cancellation with `notifications/cancelled`, and progress callbacks with timeout renewal | Must | The system shall support per-request timeouts, abort-signal cancellation with notifications/cancelled, and progress callbacks with timeout renewal |
| FRFunctional Requirement.-7MustThe system shall expose a generic notification subscription API covering logging and tool-list-change notifications | Must | The system shall expose a generic notification subscription API covering logging and tool-list-change notifications |
| FRFunctional Requirement.-8MustThe system shall provide a stdio transport that spawns the server and shuts it down per the spec | Must | The system shall provide a stdio transport that spawns the server and shuts it down per the spec |
| FRFunctional Requirement.-9MustThe system shall provide a Streamable HTTPHypertext Transfer Protocol. transport with session handling, the server-to-client GET stream with reconnection, and `Last-Event-ID` resumption | Must | The system shall provide a Streamable HTTPHypertext Transfer Protocol. transport with session handling, the server-to-client GET stream with reconnection, and Last-Event-ID resumption |
| FRFunctional Requirement.-10MustThe system shall provide an in-memory transport pair for client and adapter tests | Must | The system shall provide an in-memory transport pair for client and adapter tests |
| FRFunctional Requirement.-11MustThe system shall convert a `CallToolResult` to model-facing text and image content via `toLlmContent` | Must | The system shall convert a CallToolResult to model-facing text and image content via toLlmContent |
| FRFunctional Requirement.-12MustThe system shall implement the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). client subset covering protected-resource and authorization-server discovery, PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). authorization code flow, dynamic client registration, shared token refresh, and step-up authorization | Must | The system shall implement the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). client subset covering protected-resource and authorization-server discovery, PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). authorization code flow, dynamic client registration, shared token refresh, and step-up authorization |
| FRFunctional Requirement.-13MustThe system shall connect servers from `mcp.json` and extension-registered servers, with `mcp.json` entries taking precedence over same-name registered servers | Must | The system shall connect servers from mcp.json and extension-registered servers, with mcp.json entries taking precedence over same-name registered servers |
| FRFunctional Requirement.-14MustThe system shall register each server tool as `mcp__<server>__<tool>` sanitized to provider limits with a hash suffix on collision or overflow | Must | The system shall register each server tool as mcp__<server>__<tool> sanitized to provider limits with a hash suffix on collision or overflow |
| FRFunctional Requirement.-15MustThe system shall honor per-server `exposure` and per-tool `toolExposure` across the `codemode`, `deferred`, `direct`, and `hidden` modes | Must | The system shall honor per-server exposure and per-tool toolExposure across the codemode, deferred, direct, and hidden modes |
| FRFunctional Requirement.-16MustThe system shall list enabled servers with indirect tools in the `mcp_servers` system prompt section | Must | The system shall list enabled servers with indirect tools in the mcp_servers system prompt section |
| FRFunctional Requirement.-17MustThe system shall provide the `/mcp` manager for sign-in, reconnect, enable or disable, and exposure changes | Must | The system shall provide the /mcp manager for sign-in, reconnect, enable or disable, and exposure changes |
| FRFunctional Requirement.-18MustThe system shall expose MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). resources through the Codex-compatible `list_mcp_resources`, `list_mcp_resource_templates`, and `read_mcp_resource` tools | Must | The system shall expose MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). resources through the Codex-compatible list_mcp_resources, list_mcp_resource_templates, and read_mcp_resource tools |
| FRFunctional Requirement.-19ShouldThe system shall wait for still-connecting `direct` servers only briefly before the first prompt so a hanging server never blocks prompting indefinitely | Should | The system shall wait for still-connecting direct servers only briefly before the first prompt so a hanging server never blocks prompting indefinitely |
| FRFunctional Requirement.-20ShouldThe system shall run every MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). tool call through pi's tool pipeline so hooks and permission extensions apply uniformly | Should | The system shall run every MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). tool call through pi's tool pipeline so hooks and permission extensions apply uniformly |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-1MustThe system shall have no dependency on the official MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). SDKSoftware Development Kit (the embeddable programmatic API). or on other pi packages, keeping `cross-spawn` as its only runtime dependency | Must | Maintainability | The system shall have no dependency on the official MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). SDKSoftware Development Kit (the embeddable programmatic API). or on other pi packages, keeping cross-spawn as its only runtime dependency |
| NFRNon-Functional Requirement.-2MustThe system shall run on Node.js 22.19 or newer | Must | Portability | The system shall run on Node.js 22.19 or newer |
| NFRNon-Functional Requirement.-3MustThe system shall default every request to a 30 second timeout that progress notifications renew | Must | Reliability | The system shall default every request to a 30 second timeout that progress notifications renew |
| NFRNon-Functional Requirement.-4MustThe system shall cap model-facing MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). text output and spill the full text to a temp file the model can read | Must | Performance | The system shall cap model-facing MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). text output and spill the full text to a temp file the model can read |
| NFRNon-Functional Requirement.-5ShouldThe system shall cap inbound JSON-RPCJSON-RPC 2.0, the MCP request and notification format. messages at 16 MiB by default | Should | Reliability | The system shall cap inbound JSON-RPCJSON-RPC 2.0, the MCP request and notification format. messages at 16 MiB by default |
| NFRNon-Functional Requirement.-6ShouldThe system shall report startup config errors, failed connections, and sign-in needs exactly once per session start | Should | Usability | The system shall report startup config errors, failed connections, and sign-in needs exactly once per session start |
Constraints
- The client shall not depend on the official MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). SDKSoftware Development Kit (the embeddable programmatic API)..
- Batch JSON-RPCJSON-RPC 2.0, the MCP request and notification format. messages, legacy HTTPHypertext Transfer Protocol.+SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP)., MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers, sampling, and tasks are out of scope for the client core.
- The OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). implementation is adapted from the MIT-licensed MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). TypeScript SDKSoftware Development Kit (the embeddable programmatic API). v1.29.0 and its license is carried under
LICENSES/.
Acceptance Criteria
Every FRFunctional Requirement. and NFRNon-Functional Requirement. shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
Acceptance criteria verify how a requirement is proven done, they do not restate it.
Write concrete, scenario-based criteria (happy path, edge cases and error states where applicable).
Write each criterion as a fenced gherkin block with a tag matching its requirement ID, so the criteria are parseable and later executable via BDD tooling (pytest-bdd, cucumber).
Multiple scenarios per requirement are allowed; tag each with the requirement ID.
-
FRFunctional Requirement.-1MustThe system shall connect to an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server through a transport, negotiate a supported protocol version, and send `notifications/initialized`
gherkin @FRFunctional Requirement.-1MustThe system shall connect to an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server through a transport, negotiate a supported protocol version, and send `notifications/initialized` Scenario: Client initializes against an in-memory server Given an in-memory transport pair with a server that accepts protocol version 2025-11-25 When the client connects and the server selects a supported version Then the client records the server info and capabilities and sends notifications/initializedgherkin @FRFunctional Requirement.-1MustThe system shall connect to an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server through a transport, negotiate a supported protocol version, and send `notifications/initialized` Scenario: Server selects an unsupported version Given a server whose initialize result names an unknown protocol version When the client connects Then the connection fails with an unsupported-version error and the client ends closed -
FRFunctional Requirement.-2MustThe system shall list all tools of a server by following `tools/list` pagination cursors
gherkin @FRFunctional Requirement.-2MustThe system shall list all tools of a server by following `tools/list` pagination cursors Scenario: Tools are collected across pages Given a server that returns two pages of tools/list with a nextCursor When the client lists tools Then every tool from every page is returned in order -
FRFunctional Requirement.-3MustThe system shall call a server tool and return its `CallToolResult` including structured content and the `isError` flag
gherkin @FRFunctional Requirement.-3MustThe system shall call a server tool and return its `CallToolResult` including structured content and the `isError` flag Scenario: Tool failure arrives in the result Given a server whose tools/call result carries isError true with content blocks When the client calls the tool Then the returned result preserves the content and reports isError true instead of raising a protocol error -
FRFunctional Requirement.-4MustThe system shall list resources, list resource templates, and read resources from a server
gherkin @FRFunctional Requirement.-4MustThe system shall list resources, list resource templates, and read resources from a server Scenario: Resources round-trip through the client Given a server offering one resource and one template When the client lists resources, lists templates, and reads the resource URI Then the listings contain the offered entries and the read returns their contents -
FRFunctional Requirement.-5MustThe system shall answer server `ping` and `roots/list` requests with the configured roots
gherkin @FRFunctional Requirement.-5MustThe system shall answer server `ping` and `roots/list` requests with the configured roots Scenario: Server requests roots Given a client configured with a workspace root When the server sends roots/list Then the client answers with the configured root entries -
FRFunctional Requirement.-6MustThe system shall support per-request timeouts, abort-signal cancellation with `notifications/cancelled`, and progress callbacks with timeout renewal
gherkin @FRFunctional Requirement.-6MustThe system shall support per-request timeouts, abort-signal cancellation with `notifications/cancelled`, and progress callbacks with timeout renewal Scenario: Slow request times out and cancels remotely Given a server that never answers tools/call When the client calls the tool with a short timeout Then the call rejects with a timeout error and the server receives notifications/cancelledgherkin @FRFunctional Requirement.-6MustThe system shall support per-request timeouts, abort-signal cancellation with `notifications/cancelled`, and progress callbacks with timeout renewal Scenario: Progress renews the timeout Given a server that emits progress notifications for a long call When the client calls the tool with a progress callback Then the callback receives the progress and the request outlives a single timeout window -
FRFunctional Requirement.-7MustThe system shall expose a generic notification subscription API covering logging and tool-list-change notifications
gherkin @FRFunctional Requirement.-7MustThe system shall expose a generic notification subscription API covering logging and tool-list-change notifications Scenario: Tool list change reaches subscribers Given a subscribed notifications/tools/list_changed listener When the server emits the notification Then the listener fires with the notification params -
FRFunctional Requirement.-8MustThe system shall provide a stdio transport that spawns the server and shuts it down per the spec
gherkin @FRFunctional Requirement.-8MustThe system shall provide a stdio transport that spawns the server and shuts it down per the spec Scenario: Stdio server lifecycle Given a stdio server command When the client connects and later closes Then the process group is terminated after stdin close, SIGTERM, and SIGKILL escalation -
FRFunctional Requirement.-9MustThe system shall provide a Streamable HTTPHypertext Transfer Protocol. transport with session handling, the server-to-client GET stream with reconnection, and `Last-Event-ID` resumption
gherkin @FRFunctional Requirement.-9MustThe system shall provide a Streamable HTTPHypertext Transfer Protocol. transport with session handling, the server-to-client GET stream with reconnection, and `Last-Event-ID` resumption Scenario: Dropped stream resumes Given a Streamable HTTPHypertext Transfer Protocol. server with a session and event IDs When the response stream drops mid-call Then the client reconnects the GET stream with Last-Event-ID and completes the pending call -
FRFunctional Requirement.-10MustThe system shall provide an in-memory transport pair for client and adapter tests
gherkin @FRFunctional Requirement.-10MustThe system shall provide an in-memory transport pair for client and adapter tests Scenario: In-memory pair delivers both directions Given a connected in-memory transport pair When the client side sends a JSON-RPCJSON-RPC 2.0, the MCP request and notification format. message Then the server side receives an equal copy without shared references -
FRFunctional Requirement.-11MustThe system shall convert a `CallToolResult` to model-facing text and image content via `toLlmContent`
gherkin @FRFunctional Requirement.-11MustThe system shall convert a `CallToolResult` to model-facing text and image content via `toLlmContent` Scenario: Tool result becomes model content Given a CallToolResult with text, an embedded image resource, and an audio block When toLlmContent converts it Then text and images pass through and the audio block becomes a short text placeholder -
FRFunctional Requirement.-12MustThe system shall implement the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). client subset covering protected-resource and authorization-server discovery, PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). authorization code flow, dynamic client registration, shared token refresh, and step-up authorization
gherkin @FRFunctional Requirement.-12MustThe system shall implement the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). client subset covering protected-resource and authorization-server discovery, PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). authorization code flow, dynamic client registration, shared token refresh, and step-up authorization Scenario: OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). sign-in against a protected server Given a Streamable HTTPHypertext Transfer Protocol. server that answers 401 with protected-resource metadata When the client runs discovery, dynamic registration, and the PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). code flow Then subsequent calls carry a valid bearer token and concurrent 401s share one refresh -
FRFunctional Requirement.-13MustThe system shall connect servers from `mcp.json` and extension-registered servers, with `mcp.json` entries taking precedence over same-name registered servers
gherkin @FRFunctional Requirement.-13MustThe system shall connect servers from `mcp.json` and extension-registered servers, with `mcp.json` entries taking precedence over same-name registered servers Scenario: Config entry wins over registration Given an extension-registered server and an mcp.json entry with the same name When the session starts Then the mcp.json entry connects and the registered one is reported as overridden -
FRFunctional Requirement.-14MustThe system shall register each server tool as `mcp__<server>__<tool>` sanitized to provider limits with a hash suffix on collision or overflow
gherkin @FRFunctional Requirement.-14MustThe system shall register each server tool as `mcp__<server>__<tool>` sanitized to provider limits with a hash suffix on collision or overflow Scenario: Colliding tool names stay unique Given two tools whose sanitized mcp__server__tool names are identical When the server connects Then both register under distinct names with a hash suffix and calls still reach the right tool -
FRFunctional Requirement.-15MustThe system shall honor per-server `exposure` and per-tool `toolExposure` across the `codemode`, `deferred`, `direct`, and `hidden` modes
gherkin @FRFunctional Requirement.-15MustThe system shall honor per-server `exposure` and per-tool `toolExposure` across the `codemode`, `deferred`, `direct`, and `hidden` modes Scenario: Exposure modes route tools correctly Given one codemode server, one deferred server, one direct server, and one hidden server When the session starts Then direct tools are declared immediately, deferred tools load through tool_search, codemode tools resolve through scripts, and hidden tools are unreachable -
FRFunctional Requirement.-16MustThe system shall list enabled servers with indirect tools in the `mcp_servers` system prompt section
gherkin @FRFunctional Requirement.-16MustThe system shall list enabled servers with indirect tools in the `mcp_servers` system prompt section Scenario: Prompt section lists indirect servers Given enabled codemode and deferred servers with descriptions When the agent prompt is assembled Then the mcp_servers section names each server with its reach mode and one-line summary within the character budget -
FRFunctional Requirement.-17MustThe system shall provide the `/mcp` manager for sign-in, reconnect, enable or disable, and exposure changes
gherkin @FRFunctional Requirement.-17MustThe system shall provide the `/mcp` manager for sign-in, reconnect, enable or disable, and exposure changes Scenario: Manager disables and re-enables a server Given a connected server When the user disables it in /mcp and then enables it again Then its tools become hidden while disabled and reconnect on enable -
FRFunctional Requirement.-18MustThe system shall expose MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). resources through the Codex-compatible `list_mcp_resources`, `list_mcp_resource_templates`, and `read_mcp_resource` tools
gherkin @FRFunctional Requirement.-18MustThe system shall expose MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). resources through the Codex-compatible `list_mcp_resources`, `list_mcp_resource_templates`, and `read_mcp_resource` tools Scenario: ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. reads a resource through tools Given a connected server with resources When the model calls list_mcp_resources and then read_mcp_resource with the returned server and URI Then the resource contents return as model content with the JSON payload intact -
FRFunctional Requirement.-19ShouldThe system shall wait for still-connecting `direct` servers only briefly before the first prompt so a hanging server never blocks prompting indefinitely
gherkin @FRFunctional Requirement.-19ShouldThe system shall wait for still-connecting `direct` servers only briefly before the first prompt so a hanging server never blocks prompting indefinitely Scenario: First prompt does not hang on a slow direct server Given a direct server that never finishes connecting When the first prompt starts Then prompting proceeds after the startup wait and the tools appear once the server connects -
FRFunctional Requirement.-20ShouldThe system shall run every MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). tool call through pi's tool pipeline so hooks and permission extensions apply uniformly
gherkin @FRFunctional Requirement.-20ShouldThe system shall run every MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). tool call through pi's tool pipeline so hooks and permission extensions apply uniformly Scenario: Permission hook sees MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). calls Given a permission extension that observes tool_call events When an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). tool is invoked Then the hook observes the call exactly as it would for a built-in tool -
NFRNon-Functional Requirement.-1MustThe system shall have no dependency on the official MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). SDKSoftware Development Kit (the embeddable programmatic API). or on other pi packages, keeping `cross-spawn` as its only runtime dependency
gherkin @NFRNon-Functional Requirement.-1MustThe system shall have no dependency on the official MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). SDKSoftware Development Kit (the embeddable programmatic API). or on other pi packages, keeping `cross-spawn` as its only runtime dependency Scenario: Dependency surface stays minimal Given the published package manifest of @earendil-works/pi-mcp When its runtime dependencies are listed Then the only entry is cross-spawn with no MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). SDKSoftware Development Kit (the embeddable programmatic API). or pi workspace dependency -
NFRNon-Functional Requirement.-2MustThe system shall run on Node.js 22.19 or newer
gherkin @NFRNon-Functional Requirement.-2MustThe system shall run on Node.js 22.19 or newer Scenario: Engine floor is enforced Given a Node.js 22.19 runtime When the package builds and its tests run Then every step passes without engine warnings -
NFRNon-Functional Requirement.-3MustThe system shall default every request to a 30 second timeout that progress notifications renew
gherkin @NFRNon-Functional Requirement.-3MustThe system shall default every request to a 30 second timeout that progress notifications renew Scenario: Default timeout applies Given a client created without an explicit timeout When a request runs past 30 seconds with no progress Then the request rejects with a timeout error naming the elapsed budget -
NFRNon-Functional Requirement.-4MustThe system shall cap model-facing MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). text output and spill the full text to a temp file the model can read
gherkin @NFRNon-Functional Requirement.-4MustThe system shall cap model-facing MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). text output and spill the full text to a temp file the model can read Scenario: Oversized output spills to disk Given a tool result whose text exceeds 20 KiB When it is converted for the model Then the model sees a truncated middle-cut rendering plus the temp file path holding the full text -
NFRNon-Functional Requirement.-5ShouldThe system shall cap inbound JSON-RPCJSON-RPC 2.0, the MCP request and notification format. messages at 16 MiB by default
gherkin @NFRNon-Functional Requirement.-5ShouldThe system shall cap inbound JSON-RPCJSON-RPC 2.0, the MCP request and notification format. messages at 16 MiB by default Scenario: Oversized message is rejected Given a transport receiving a JSON-RPCJSON-RPC 2.0, the MCP request and notification format. message larger than 16 MiB When the frame completes Then the message is rejected without being delivered to the client -
NFRNon-Functional Requirement.-6ShouldThe system shall report startup config errors, failed connections, and sign-in needs exactly once per session start
gherkin @NFRNon-Functional Requirement.-6ShouldThe system shall report startup config errors, failed connections, and sign-in needs exactly once per session start Scenario: Startup problems are reported once Given a session start with one broken config entry and one failing server When startup completes Then the user sees a single warning covering both problems and no repeats
Conflicts
None identified yet.
Open Questions
- Will any supported server require the legacy HTTPHypertext Transfer Protocol.+SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). transport that the client core currently excludes.
- Will any consumer need the client to act as an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server (sampling) rather than only calling tools and reading resources.
Specification: MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Client
Overview
The implementation keeps a transport-neutral McpClient core in packages/mcp/src/ that speaks JSON-RPCJSON-RPC 2.0, the MCP request and notification format. plus MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). lifecycle semantics, with stdio, Streamable HTTPHypertext Transfer Protocol., and in-memory transports behind the McpTransport interface and the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). client subset under src/oauth/.
The packages/coding-agent built-in MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. consumes that client lazily at session start, adapts each server tool to a pi ToolDefinition, and routes tools to the model through the four exposure modes.
Architecture
flowchart TB
subgraph pkg["packages/mcp (standalone)"]
Client[McpClient core]
Stdio[StdioTransport]
Http[StreamableHttpTransport]
Mem[InMemoryTransport]
OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot).[oauth/ provider + flow + callback]
Content[toLlmContent]
Client --- Stdio
Client --- Http
Client --- Mem
Http --- OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot).
end
subgraph ext["coding-agent built-in mcp extension"]
Index[index.ts lifecycle]
Tools[tools.ts adapter]
Res[resources.ts resource tools]
Cfg[config.ts mcp.json]
Runtime[runtime.ts connection]
end
Client --> Runtime
Runtime --> Tools
Runtime --> Res
Cfg --> Index
Index --> Tools
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
McpClientOptions
| Field | Type | Constraints | Description |
|---|---|---|---|
| name | string | required | Client info name sent in initialize |
| version | string | required | Client info version sent in initialize |
| capabilities | ClientCapabilities | optional | Advertised capabilities, with roots added automatically when roots are set |
| protocolVersion | SupportedProtocolVersion | optional, defaults to 2025-11-25 |
Preferred version offered during initialization |
| requestTimeoutMs | number | optional, defaults to 30000 | Per-request timeout renewed by progress notifications |
| roots | Root[] or provider fn | optional | Roots served to roots/list server requests |
Tool
| Field | Type | Constraints | Description |
|---|---|---|---|
| name | string | required | Server-side tool name before pi namespacing |
| description | string | optional | Human description shown in the adapted tool definition |
| inputSchema | object | required | JSON schema normalized to an object schema with properties |
| outputSchema | object | optional | Structured-content schema relocated under the result schema pointer |
| annotations | ToolAnnotations | optional | Boolean hints such as readOnly and destructive mapped to pi annotations |
CallToolResult
| Field | Type | Constraints | Description |
|---|---|---|---|
| content | ContentBlock[] | defaults to [] when omitted |
Text, image, audio, resource, and resource-link blocks |
| structuredContent | JSON value | optional | Machine payload passed through to scripts and the result schema |
| isError | boolean | optional | Tool-level failure flag preserved instead of raised as a protocol error |
Resource
| Field | Type | Constraints | Description |
|---|---|---|---|
| uri | string | required | Address read by resources/read |
| name | string | defaults to uri when omitted | Display name, tolerating servers that omit it |
| mimeType | string | optional | Filters MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). App resources and detects text blobs |
| size | number | optional | Rendered next to resource links for the model |
InitializeResult
| Field | Type | Constraints | Description |
|---|---|---|---|
| protocolVersion | string | must be one of the four supported versions | Version the server selected for the session |
| capabilities | ServerCapabilities | required | What the server offers, including tools and resources |
| serverInfo | Implementation | required, name plus version | Identity recorded on the client after connect |
| instructions | string | optional | Server instructions surfaced in the mcp_servers section and namespace |
McpServerEntry
| Field | Type | Constraints | Description |
|---|---|---|---|
| name | string | required, namespace-unique modulo - versus _ |
Server name used in tool names and the prompt section |
| config | McpServerConfig | validated, stdio or HTTPHypertext Transfer Protocol. shape | Command or URL plus enabled, exposure, toolExposure, timeout, and description |
| source | string | required | Config file path or registering extension path |
| scope | global, project, or extension | optional | Where the entry came from, deciding where edits are saved |
| override | string | optional | Project mcp.json carrying an enabled, exposure, or toolExposure override |
API Contracts
No api.yaml accompanies this specification because the feature defines no HTTPHypertext Transfer Protocol. surface of its own.
The normative surfaces are the TypeScript client API and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). transports it speaks.
| Surface | Member | Purpose |
|---|---|---|
| TS client | McpClient.connect(transport) |
Runs transport start, initialize negotiation, and notifications/initialized |
| TS client | McpClient.listTools(options?) |
Returns every tool across all tools/list pages |
| TS client | McpClient.callTool(name, args?, options?) |
Calls one tool with timeout, cancellation, and progress support |
| TS client | McpClient.listResources / listResourceTemplates / readResource |
Reads resource listings and contents, one page or all pages |
| TS client | McpClient.ping / request / notify |
Sends protocol ping plus generic requests and notifications |
| TS client | McpClient.setRequestHandler / onNotification / onError / onClose |
Serves ping and roots/list and observes connection events |
| TS client | toLlmContent(result) |
Converts a CallToolResult to pi-ai text and image content |
| TS transport | McpTransport.start / send / close |
Framing and I/O contract every transport implements |
| TS transport | StdioTransport({ command, args }) |
Spawns a server process with spec-ordered shutdown of its process group |
| TS transport | StreamableHttpTransport({ url, headers, authProvider }) |
HTTPHypertext Transfer Protocol. transport with sessions, GET-stream reconnection, and Last-Event-ID resume |
| TS testing | createInMemoryTransportPair() |
Linked client and server transports for unit and adapter tests |
| TS oauth | McpOAuthProvider / authorizeMcp / OAuthCallbackServer |
Discovery, PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). flow, registration, refresh, and loopback callback |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | createMcpExtension(options?) |
Replaceable built-in extension wiring config, runtime, tools, and /mcp |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | mcp.json mcpServers shape |
Shared config format with global file, trusted-project file, and per-tool overrides |
Error codes shared across endpoints:
| Status | Code | Description |
|---|---|---|
| n/a | McpError with JSON-RPCJSON-RPC 2.0, the MCP request and notification format. code | Protocol errors reject the pending request with code, message, and data |
| n/a | McpTimeoutError | Request exceeded its timeout without progress renewal |
| n/a | McpAbortError | Caller aborted the request through its abort signal |
| n/a | McpConnectionClosedError | Request or send raced a closed transport or client |
| n/a | McpOAuthAuthorizationRequiredError | HTTPHypertext Transfer Protocol. 401 needs a browser sign-in before retry |
Sequences
Connect, list tools, call tool, close
sequenceDiagram
autonumber
participant App as ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. runtime
participant C as McpClient
participant T as Transport
participant S as MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server
App->>C: connect(transport)
C->>T: start()
C->>S: initialize (via T)
S-->>C: InitializeResult + protocolVersion
C->>S: notifications/initialized
App->>C: listTools()
C->>S: tools/list (+ cursor pages)
S-->>C: Tool[] pages
App->>C: callTool(name, args)
C->>S: tools/call
S-->>C: CallToolResult
App->>C: close()
C->>T: close()
OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). sign-in and retry
sequenceDiagram
autonumber
participant C as McpClient
participant T as StreamableHttpTransport
participant O as McpOAuthProvider
participant B as Browser + callback
C->>T: send tools/call
T-->>C: 401 McpOAuthAuthorizationRequiredError
O->>B: open authorization URL (PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). + registration as needed)
B-->>O: authorization code via loopback callback
O->>O: authorizeMcp (token exchange + store)
C->>T: retry with bearer token
Tool-call readiness in the extension
sequenceDiagram
autonumber
participant Hook as tool_call hook
participant E as MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`.
participant S as McpServerConnection
Hook->>E: tool reaches server namespace
E->>S: await server.ready (bounded for first prompt)
S-->>E: connected tools + instructions
E->>E: registerTools with exposure + namespace
Hook-->>Hook: run the call through the tool pipeline
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Official SDKSoftware Development Kit (the embeddable programmatic API). | No dependency on the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). SDKSoftware Development Kit (the embeddable programmatic API). anywhere | Keeps the client small, version-controlled, and free of SDKSoftware Development Kit (the embeddable programmatic API). release coupling |
| Transport shape | Client core owns protocol semantics while transports own framing and I/O | Lets stdio, Streamable HTTPHypertext Transfer Protocol., and in-memory transports evolve independently |
| Protocol versions | Offer 2025-11-25 and accept the three prior versions back to 2024-11-05 |
Tracks the current spec while staying compatible with older servers |
| Tool naming | Sanitize to mcp__server__tool with a hash suffix on collision or 64-char overflow |
Satisfies provider name limits and keeps names stable and unique |
| Default exposure | codemode unless configured otherwise |
Keeps MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). tools out of model declarations until scripts or search load them |
| Resource tools | Reuse the Codex list_mcp_resources trio with JSON payloads |
ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. trained on those tools work unchanged against pi |
| Prompt section | Bounded mcp_servers section instead of declaring indirect tools |
Informs the model about reachable servers within a fixed character budget |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). scope | Adapt the SDKSoftware Development Kit (the embeddable programmatic API). flow without opening browsers or choosing storage | Leaves UX and credential persistence to the host while reusing proven logic |
| Test seam | Ship the in-memory transport as a public testing entry point | Gives client and adapter tests a deterministic transport without processes or network |
Risks and Unknowns
- Servers that only speak legacy HTTPHypertext Transfer Protocol.+SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). cannot connect until a transport is added for them.
- Servers with non-conformant pagination or missing required fields may need further lenient validation beyond the current null-cursor and unnamed-resource handling.
- OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). edge cases across heterogeneous providers may surface flows the adapted implementation does not yet cover.
- Large tool counts can strain the prompt budget, since direct exposure declares every tool to the model.
Out of Scope
- Batch JSON-RPCJSON-RPC 2.0, the MCP request and notification format. messages and the legacy HTTPHypertext Transfer Protocol.+SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). transport.
- Acting as an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server, including sampling support.
- MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). tasks and elicitation workflows.
- A browser-based sign-in UI beyond opening the authorization URL and serving the loopback callback.
Test Plan: MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Client
Scope
Unit and transport tests in packages/mcp/test/ cover the client core, content conversion, stdio, Streamable HTTPHypertext Transfer Protocol., and OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). against the in-memory pair and fixtures.
ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. adapter coverage lives with the coding-agent MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. tests for tools, resources, and config.
Conformance against the official suite runs through packages/coding-agent/test/mcp-conformance/ and the mcp-conformance CIContinuous Integration (the `ci` GitHub workflow). job.
Out of scope are legacy HTTPHypertext Transfer Protocol.+SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). servers, sampling, and tasks, which the client core does not implement.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Initialize negotiates the protocol version | initialize result selecting 2025-11-25 over the in-memory pair |
Client records server info and sends notifications/initialized |
| TC-2 | Unsupported version fails connect | initialize result with an unknown version |
Connect rejects and the client ends closed |
| TC-3 | Paginated tool listing collects every page | Two tools/list pages joined by nextCursor |
All tools returned in order |
| TC-4 | Duplicate pagination cursor is rejected | Repeated nextCursor across pages |
Listing throws a duplicate-cursor error |
| TC-5 | Tool result validation tolerates missing content | tools/call result with only structuredContent |
Result defaults content to an empty array |
| TC-6 | Content conversion maps blocks to model content | Text, image, embedded resource, audio, and resource-link blocks | Text and images pass through while audio and links become placeholders |
| TC-7 | Request timeout rejects and cancels remotely | Unanswered tools/call with a short timeout |
Timeout error plus notifications/cancelled to the server |
| TC-8 | Progress renews the timeout and fires the callback | notifications/progress during a long call |
Callback fires and the request survives one timeout window |
| TC-9 | Roots provider answers server requests | roots/list from the server side |
Configured roots returned |
| TC-10 | In-memory pair isolates messages | One JSON-RPCJSON-RPC 2.0, the MCP request and notification format. message sent client to server | Equal structured-cloned copy delivered exactly once |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-11 | Stdio server lifecycle | Fixture server command from packages/mcp/test/fixtures |
Connect, list, call, and spec-ordered process-group shutdown all succeed |
| TC-12 | Streamable HTTPHypertext Transfer Protocol. session with resume | HTTPHypertext Transfer Protocol. fixture server with event IDs | Dropped response stream reconnects with Last-Event-ID and the call completes |
| TC-13 | OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). flow against a protected server | Authorization and token endpoints plus loopback callback | Bearer-authenticated calls succeed after discovery, registration, and code exchange |
| TC-14 | Concurrent 401s share one refresh | Expired token with two racing calls | Exactly one token refresh serves both retries |
| TC-15 | MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). tool naming stays unique | Two tools sanitizing to the same mcp__server__tool name |
Distinct registered names with a hash suffix routing to the right tools |
| TC-16 | Exposure routing reaches tools correctly | Servers configured as codemode, deferred, direct, and hidden | Each tool resolves only through its configured reach path |
| TC-17 | Resource tools round-trip listings and reads | Connected server with resources | list_mcp_resources plus read_mcp_resource return contents and JSON payloads |
| TC-18 | Startup does not hang on a slow direct server | Direct server that never finishes connecting | First prompt proceeds after the startup wait and tools register on connect |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-19 | Official conformance suite stays at baseline | Run npm run test:mcp-conformance across negotiated protocol versions |
No baseline-passing check fails and no unlisted failure appears |
| TC-20 | OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). sign-in through the real connection path | Run the conformance client with the simulated browser against auth scenarios | Protected scenarios complete including step-up re-sign-in within the retry limit |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-21 | resources/list page ends with a null cursor |
Pagination stops after that page without an extra request |
| TC-22 | Resource without a name | Listing uses the URI as the name |
| TC-23 | Oversized model text beyond 20 KiB | Middle-cut rendering plus a temp file holding the full text |
| TC-24 | Inbound message beyond 16 MiB | Message rejected before delivery to the client |
| TC-25 | Unknown response ID arrives | Client emits an error without disturbing pending requests |
Test Infrastructure
createInMemoryTransportPair()from@earendil-works/pi-mcp/testingfor deterministic client and adapter tests.- Fixture servers under
packages/mcp/test/fixturesplushelpers.tsfor stdio and HTTPHypertext Transfer Protocol. harnesses. - Pinned official conformance suite
@modelcontextprotocol/conformance@0.2.0-alpha.11withbaseline.jsonlocking known results. - The
mcp-conformancejob in.github/workflows/ci.ymlrunningnpm run test:mcp-conformanceon every main push and pull request.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FRFunctional Requirement.-1MustThe system shall connect to an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server through a transport, negotiate a supported protocol version, and send `notifications/initialized` | TC-1, TC-2 |
| FRFunctional Requirement.-2MustThe system shall list all tools of a server by following `tools/list` pagination cursors | TC-3, TC-4 |
| FRFunctional Requirement.-3MustThe system shall call a server tool and return its `CallToolResult` including structured content and the `isError` flag | TC-5 |
| FRFunctional Requirement.-4MustThe system shall list resources, list resource templates, and read resources from a server | TC-17 |
| FRFunctional Requirement.-5MustThe system shall answer server `ping` and `roots/list` requests with the configured roots | TC-9 |
| FRFunctional Requirement.-6MustThe system shall support per-request timeouts, abort-signal cancellation with `notifications/cancelled`, and progress callbacks with timeout renewal | TC-7, TC-8 |
| FRFunctional Requirement.-7MustThe system shall expose a generic notification subscription API covering logging and tool-list-change notifications | TC-25 |
| FRFunctional Requirement.-8MustThe system shall provide a stdio transport that spawns the server and shuts it down per the spec | TC-11 |
| FRFunctional Requirement.-9MustThe system shall provide a Streamable HTTPHypertext Transfer Protocol. transport with session handling, the server-to-client GET stream with reconnection, and `Last-Event-ID` resumption | TC-12 |
| FRFunctional Requirement.-10MustThe system shall provide an in-memory transport pair for client and adapter tests | TC-10 |
| FRFunctional Requirement.-11MustThe system shall convert a `CallToolResult` to model-facing text and image content via `toLlmContent` | TC-6 |
| FRFunctional Requirement.-12MustThe system shall implement the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). client subset covering protected-resource and authorization-server discovery, PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). authorization code flow, dynamic client registration, shared token refresh, and step-up authorization | TC-13, TC-14, TC-20 |
| FRFunctional Requirement.-13MustThe system shall connect servers from `mcp.json` and extension-registered servers, with `mcp.json` entries taking precedence over same-name registered servers | TC-15 |
| FRFunctional Requirement.-14MustThe system shall register each server tool as `mcp__<server>__<tool>` sanitized to provider limits with a hash suffix on collision or overflow | TC-15 |
| FRFunctional Requirement.-15MustThe system shall honor per-server `exposure` and per-tool `toolExposure` across the `codemode`, `deferred`, `direct`, and `hidden` modes | TC-16 |
| FRFunctional Requirement.-16MustThe system shall list enabled servers with indirect tools in the `mcp_servers` system prompt section | TC-18 |
| FRFunctional Requirement.-17MustThe system shall provide the `/mcp` manager for sign-in, reconnect, enable or disable, and exposure changes | TC-18 |
| FRFunctional Requirement.-18MustThe system shall expose MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). resources through the Codex-compatible `list_mcp_resources`, `list_mcp_resource_templates`, and `read_mcp_resource` tools | TC-17 |
| FRFunctional Requirement.-19ShouldThe system shall wait for still-connecting `direct` servers only briefly before the first prompt so a hanging server never blocks prompting indefinitely | TC-18 |
| FRFunctional Requirement.-20ShouldThe system shall run every MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). tool call through pi's tool pipeline so hooks and permission extensions apply uniformly | TC-16 |
| NFRNon-Functional Requirement.-1MustThe system shall have no dependency on the official MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). SDKSoftware Development Kit (the embeddable programmatic API). or on other pi packages, keeping `cross-spawn` as its only runtime dependency | TC-19 |
| NFRNon-Functional Requirement.-2MustThe system shall run on Node.js 22.19 or newer | TC-19 |
| NFRNon-Functional Requirement.-3MustThe system shall default every request to a 30 second timeout that progress notifications renew | TC-7 |
| NFRNon-Functional Requirement.-4MustThe system shall cap model-facing MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). text output and spill the full text to a temp file the model can read | TC-23 |
| NFRNon-Functional Requirement.-5ShouldThe system shall cap inbound JSON-RPCJSON-RPC 2.0, the MCP request and notification format. messages at 16 MiB by default | TC-24 |
| NFRNon-Functional Requirement.-6ShouldThe system shall report startup config errors, failed connections, and sign-in needs exactly once per session start | TC-18 |
requirements
- Will any supported server require the legacy HTTP+SSE transport that the client core currently excludes.
- Will any consumer need the client to act as an MCP server (sampling) rather than only calling tools and reading resources.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Remote SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Protocol
Overview
@earendil-works/pi-protocol defines a runtime-neutral wire protocol for remote pi sessions.
It provides schemas, types, CBOR encoding/decoding, and byte-stream framing so that a client and a server can exchange messages over any ordered byte transport.
The protocol is versioned (currently 2) and message-correlated (request/response envelopes plus server event envelopes), with authoritative server/session snapshots and transient progress events.
Stakeholders
| Stakeholder | Interest |
|---|---|
Remote session client (pi-client) |
A validated, framed message API plus incremental decoders that tolerate arbitrary fragmentation or coalescing |
SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. server (pi-server) |
Matching encode/decode on the server side with an authoritative snapshot model |
| Transport authors | A wire format that is transport-agnostic (streams, sockets, custom byte transports) |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-01MustThe system shall define runtime-neutral schemas and types for all protocol messages (client and server). | Must | The system shall define runtime-neutral schemas and types for all protocol messages (client and server). |
| FRFunctional Requirement.-02MustThe system shall encode messages as one definite-length CBOR item framed by a four-byte unsigned big-endian payload length. | Must | The system shall encode messages as one definite-length CBOR item framed by a four-byte unsigned big-endian payload length. |
| FRFunctional Requirement.-03MustThe system shall provide `encodeClientMessage()` and `encodeServerMessage()` that validate a message and return a complete framed `Uint8Array`. | Must | The system shall provide encodeClientMessage() and encodeServerMessage() that validate a message and return a complete framed Uint8Array. |
| FRFunctional Requirement.-04MustThe system shall provide incremental decoders that accept arbitrary fragmentation or coalescing of framed bytes. | Must | The system shall provide incremental decoders that accept arbitrary fragmentation or coalescing of framed bytes. |
| FRFunctional Requirement.-05MustThe system shall require the first client message to be `hello`, carrying `PROTOCOL_VERSION` and a bearer token. | Must | The system shall require the first client message to be hello, carrying PROTOCOL_VERSION and a bearer token. |
| FRFunctional Requirement.-06MustThe system shall correlate subsequent messages by request/response envelopes and server event envelopes. | Must | The system shall correlate subsequent messages by request/response envelopes and server event envelopes. |
| FRFunctional Requirement.-07MustThe system shall expose a version constant (`PROTOCOL_VERSION`) used by both client and server. | Must | The system shall expose a version constant (PROTOCOL_VERSION) used by both client and server. |
| FRFunctional Requirement.-08ShouldThe system shall treat server and session snapshots as authoritative, and progress events as transient UI hints. | Should | The system shall treat server and session snapshots as authoritative, and progress events as transient UI hints. |
| FRFunctional Requirement.-09ShouldThe system shall ship a self-contained CBOR encoder/decoder (no external CBOR dependency). | Should | The system shall ship a self-contained CBOR encoder/decoder (no external CBOR dependency). |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-01MustThe protocol shall be versioned so incompatible wire changes bump `PROTOCOL_VERSION`. | Must | Compatibility | The protocol shall be versioned so incompatible wire changes bump PROTOCOL_VERSION. |
| NFRNon-Functional Requirement.-02MustThe `hello` handshake shall carry a bearer token before any session operations are allowed. | Must | Security | The hello handshake shall carry a bearer token before any session operations are allowed. |
| NFRNon-Functional Requirement.-03ShouldFraming shall use a fixed-length length prefix for cheap incremental parsing. | Should | Performance | Framing shall use a fixed-length length prefix for cheap incremental parsing. |
| NFRNon-Functional Requirement.-04ShouldThe package shall be runtime-neutral with no Node-specific imports. | Should | Portability | The package shall be runtime-neutral with no Node-specific imports. |
Constraints
- Depends on
typeboxfor schema definitions. - Protocol version
2is the current wire layout; version1is not preserved. - Experimental; the message surface may change without notice.
Acceptance Criteria
- FRFunctional Requirement.-02MustThe system shall encode messages as one definite-length CBOR item framed by a four-byte unsigned big-endian payload length.
- Given a protocol message
- When encoded to bytes
- Then the result is a four-byte big-endian length prefix followed by one definite-length CBOR item.
- FRFunctional Requirement.-04MustThe system shall provide incremental decoders that accept arbitrary fragmentation or coalescing of framed bytes.
- Given a framed byte stream delivered in arbitrary chunk boundaries
- When fed to the incremental decoder
- Then the original messages are recovered exactly.
- FRFunctional Requirement.-05MustThe system shall require the first client message to be `hello`, carrying `PROTOCOL_VERSION` and a bearer token.
- Given a client that has not sent
hello - When it sends a session operation
- Then the server rejects the message until a valid
hellowith a matching token is received.
- Given a client that has not sent
- NFRNon-Functional Requirement.-04ShouldThe package shall be runtime-neutral with no Node-specific imports.
- Given the package source
- When scanned for Node imports
- Then none are present.
Conflicts
None identified yet.
Open Questions
- Should the protocol expose a negotiation mechanism for future wire-version migration beyond bumping
PROTOCOL_VERSION?
Specification: Remote SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Protocol
Overview
pi-protocol is the wire boundary for remote pi sessions.
Messages are schema-validated objects encoded as a single definite-length CBOR item and framed with a four-byte big-endian length prefix.
The package ships a self-contained CBOR encoder/decoder, incremental decoders tolerant of arbitrary fragmentation, and a validated message API (encodeClientMessage/encodeServerMessage).
Architecture
Client messages Server messages
+----------------+ +----------------+
| hello (v2) | | session events |
| request/ |<------->| server events |
| response env. | framed | response env. |
+--------+-------+ CBOR +--------+-------+
| |
v v
length-prefixed framed bytes incremental decoders
The protocol is runtime-neutral: no Node-specific imports.
framing.ts owns the length-prefix layout; cbor/ owns encode/decode; schemas.ts owns the message definitions; codec.ts ties validation + framing into the message API.
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
ClientHello
| Field | Type | Constraints | Description |
|---|---|---|---|
| type | string | "hello" |
Message discriminator |
| version | number | PROTOCOL_VERSION |
Protocol version |
| token | string | not null | Bearer token for authentication |
Framed message
| Field | Type | Constraints | Description |
|---|---|---|---|
| length | uint32 | big-endian | Byte length of the CBOR payload |
| payload | CBOR | definite-length | One schema-validated message |
API Contracts
encodeClientMessage(message)
Request
| Field | Type | Required | Description |
|---|---|---|---|
| message | ClientMessage | yes | Message to validate and frame |
Response (200 OK)
| Field | Type | Description |
|---|---|---|
| Uint8Array | framed bytes | Complete framed message ready to send |
createServerMessageDecoder()
Request
None; incremental state is held in the returned decoder.
Response (200 OK)
| Field | Type | Description |
|---|---|---|
| decoder | object | Accepts arbitrary chunks and emits decoded messages |
Sequences
Hello handshake
Client → encodeClientMessage(hello) → transport
Server → decoder → validate hello (version + token) → accept connection
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Payload format | CBOR | Compact, schema-validated, binary-safe |
| Framing | 4-byte BE length prefix | Cheap incremental parsing, exact boundaries |
| CBOR implementation | Self-contained encoder/decoder | No runtime dependency, full control |
| Message validation | typebox schemas | Shared schema + validate pipeline |
| Versioning | PROTOCOL_VERSION constant |
Single source of truth for wire compatibility |
Risks and Unknowns
- Experimental protocol surface may change; consumers must pin the package.
- Snapshot-authoritative semantics depend on server cooperation; progress events must never be reduced into authoritative state.
Out of Scope
- The client implementation itself (
pi-client). - The server implementation (
pi-server). - Transport plumbing (sockets, WebSocket adapters) beyond the framing/decoder layer.
Test Plan: Remote SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Protocol
Scope
Tests cover CBOR encoding/decoding correctness, length-prefixed framing, incremental decoding across fragmentation boundaries, and the validated message API (encodeClientMessage/encodeServerMessage) plus the hello handshake.
Transport-level behavior is out of scope (covered by pi-client/pi-server).
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | CBOR encode/decode round-trips representative values | Mixed JS values | Lossless round-trip |
| TC-2 | Encoded messages carry a four-byte BE length prefix then one definite-length CBOR item | A hello message |
Length prefix matches CBOR payload length |
| TC-3 | Incremental decoder recovers messages across arbitrary fragmentation | Framed bytes split at many offsets | Original messages recovered exactly |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-4 | encodeClientMessage validates and frames a valid client message |
Valid message object | Complete framed Uint8Array returned |
| TC-5 | Decoder tolerates coalescing of multiple framed messages in one chunk | Multiple encoded messages concatenated | All messages emitted in order |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-6 | Fragment boundary inside the length prefix | Decoder waits for the full prefix before parsing |
| TC-7 | Fragment boundary inside the CBOR payload | Decoder buffers until the full payload arrives |
| TC-8 | Invalid message shape | encodeClientMessage rejects rather than emitting malformed bytes |
Test Infrastructure
- Pure function tests; no network, sockets, or timers.
- Ran with Vitest (
packages/protocol/test/).
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FRFunctional Requirement.-01MustThe system shall define runtime-neutral schemas and types for all protocol messages (client and server). | TC-1, TC-2 |
| FRFunctional Requirement.-02MustThe system shall encode messages as one definite-length CBOR item framed by a four-byte unsigned big-endian payload length. | TC-2, TC-5 |
| FRFunctional Requirement.-03MustThe system shall provide `encodeClientMessage()` and `encodeServerMessage()` that validate a message and return a complete framed `Uint8Array`. | TC-4 |
| FRFunctional Requirement.-04MustThe system shall provide incremental decoders that accept arbitrary fragmentation or coalescing of framed bytes. | TC-3, TC-5, TC-6, TC-7 |
| FRFunctional Requirement.-05MustThe system shall require the first client message to be `hello`, carrying `PROTOCOL_VERSION` and a bearer token. | TC-8 |
| FRFunctional Requirement.-09ShouldThe system shall ship a self-contained CBOR encoder/decoder (no external CBOR dependency). | TC-1 |
requirements
- Should the protocol expose a negotiation mechanism for future wire-version migration beyond bumping
PROTOCOL_VERSION?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Remote SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Client
Overview
@earendil-works/pi-client is a transport-neutral client for remote pi sessions.
PiClient exchanges length-prefixed CBOR messages through a small ByteTransport interface, so it works over Unix sockets, WebSockets, or any ordered byte transport without Node-specific imports.
It provides session acquisition with exclusive/shared leases, session creation/attachment, snapshot subscriptions, and request correlation by ID.
Stakeholders
| Stakeholder | Interest |
|---|---|
Coding agent (pi-coding-agent) |
Attach to remote pi sessions (create, resume, subscribe) from the CLICommand-Line Interface (the `pi` binary). |
| Server operators | A client that authenticates with a bearer token and honors exclusive/shared session ownership |
| Transport authors | A minimal ByteTransport contract that is easy to implement |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-01MustThe system shall provide a `PiClient` that connects to a server via a `ByteTransportFactory` and authenticates with a bearer token. | Must | The system shall provide a PiClient that connects to a server via a ByteTransportFactory and authenticates with a bearer token. |
| FRFunctional Requirement.-02MustThe system shall support creating a session (`createSession({ cwd })`) and returning a new session lease. | Must | The system shall support creating a session (createSession({ cwd })) and returning a new session lease. |
| FRFunctional Requirement.-03MustThe system shall support attaching to an existing session (`attachSession()`) as a shared acquisition. | Must | The system shall support attaching to an existing session (attachSession()) as a shared acquisition. |
| FRFunctional Requirement.-04MustThe system shall support acquiring sessions with explicit lease modes: `{ mode: "exclusive" }` or `{ mode: "shared" }`. | Must | The system shall support acquiring sessions with explicit lease modes: { mode: "exclusive" } or { mode: "shared" }. |
| FRFunctional Requirement.-05MustThe system shall enforce ownership: exclusive acquisition fails while any lease exists; shared acquisition fails while an exclusive lease exists. | Must | The system shall enforce ownership: exclusive acquisition fails while any lease exists; shared acquisition fails while an exclusive lease exists. |
| FRFunctional Requirement.-06MustThe system shall correlate requests by ID and deliver responses to the right caller. | Must | The system shall correlate requests by ID and deliver responses to the right caller. |
| FRFunctional Requirement.-07MustThe system shall publish session snapshots to subscribers and list sessions (`listSessions()`). | Must | The system shall publish session snapshots to subscribers and list sessions (listSessions()). |
| FRFunctional Requirement.-08ShouldThe system shall support `reconnect()` after disconnection (no automatic reconnect). | Should | The system shall support reconnect() after disconnection (no automatic reconnect). |
| FRFunctional Requirement.-09ShouldThe system shall expose cached session summaries from the latest snapshot. | Should | The system shall expose cached session summaries from the latest snapshot. |
| FRFunctional Requirement.-10ShouldThe system shall drive a session with `session.prompt(...)` and stream events to subscribers. | Should | The system shall drive a session with session.prompt(...) and stream events to subscribers. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-01MustThe package shall have no Node-specific imports; all byte movement goes through `ByteTransport`. | Must | Portability | The package shall have no Node-specific imports; all byte movement goes through ByteTransport. |
| NFRNon-Functional Requirement.-02MustA transport factory must create a fresh transport for every connection attempt. | Must | Correctness | A transport factory must create a fresh transport for every connection attempt. |
| NFRNon-Functional Requirement.-03MustThe client shall send the bearer token only through the `hello` handshake. | Must | Security | The client shall send the bearer token only through the hello handshake. |
| NFRNon-Functional Requirement.-04ShouldOn transport close/error the client shall surface the failure to callers and support explicit reconnect. | Should | Reliability | On transport close/error the client shall surface the failure to callers and support explicit reconnect. |
Constraints
- No automatic reconnect; callers must call
reconnect(). - One connection can attach several sessions.
- Experimental; API may change without notice.
Acceptance Criteria
- FRFunctional Requirement.-01MustThe system shall provide a `PiClient` that connects to a server via a `ByteTransportFactory` and authenticates with a bearer token.
- Given a
PiClientwith a token and transport factory - When
connect()is called - Then the client authenticates via
helloand becomes ready.
- Given a
- FRFunctional Requirement.-04MustThe system shall support acquiring sessions with explicit lease modes: `{ mode: "exclusive" }` or `{ mode: "shared" }`.
- Given a session with no active leases
- When an exclusive acquisition is requested
- Then an exclusive lease is returned and shared acquisitions now fail.
- FRFunctional Requirement.-05MustThe system shall enforce ownership: exclusive acquisition fails while any lease exists; shared acquisition fails while an exclusive lease exists.
- Given an exclusive lease already held
- When a second exclusive acquisition is requested
- Then
PiSessionOwnershipErroris thrown.
- FRFunctional Requirement.-06MustThe system shall correlate requests by ID and deliver responses to the right caller.
- Given multiple in-flight requests
- When responses arrive out of order
- Then each caller receives the response matching its request ID.
- NFRNon-Functional Requirement.-01MustThe package shall have no Node-specific imports; all byte movement goes through `ByteTransport`.
- Given the package source
- When scanned for Node imports
- Then none are present.
Conflicts
None identified yet.
Open Questions
- Should automatic reconnect with backoff be added, or does explicit
reconnect()suffice?
Specification: Remote SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Client
Overview
pi-client is the transport-neutral remote-session client.
PiClient connects through a ByteTransportFactory, authenticates via the protocol hello handshake, and exchanges request/response envelopes with the server.
SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. access is mediated by SessionLease objects with exclusive/shared ownership semantics.
Architecture
+----------------------+
| PiClient |
| - connect() |
| - createSession() |
| - attachSession() |
| - acquireSession() |
| - listSessions() |
| - reconnect() |
+---------+------------+
| ByteTransportFactory (one fresh transport per attempt)
v
+----------------------+
| ByteTransport |
| send(chunk), close() |
| onData/onClose/onErr |
+----------------------+
connection.ts owns transport lifecycle, state.ts the connection/session state machine, session-handle.ts the lease model, promise.ts request correlation, and client.ts the public PiClient API.
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
SessionLease
| Field | Type | Constraints | Description |
|---|---|---|---|
| mode | "exclusive" \| "shared" |
not null | Ownership mode |
| session | session handle | not null | Underlying remote session |
| release | function | — | Releases the lease |
Leases cannot be constructed directly; they come from createSession() (exclusive) or acquireSession()/attachSession().
API Contracts
client.createSession({ cwd })
Request
| Field | Type | Required | Description |
|---|---|---|---|
| cwd | string | yes | Working directory for the session |
Response (200 OK)
| Field | Type | Description |
|---|---|---|
| lease | SessionLease | New exclusive lease for the created session |
Error Responses
| Status | Code | Description |
|---|---|---|
| 409 | SESSION_OWNERSHIP | Ownership conflict during acquisition |
client.acquireSession({ mode })
Request
| Field | Type | Required | Description |
|---|---|---|---|
| mode | "exclusive" | "shared" | yes | Desired lease mode |
Response (200 OK)
| Field | Type | Description |
|---|---|---|
| lease | SessionLease | Lease in the requested mode |
Error Responses
| Status | Code | Description |
|---|---|---|
| 409 | SESSION_OWNERSHIP | Exclusive requested while a lease exists, or shared while exclusive held |
Sequences
SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. create flow
PiClient → encodeClientMessage(create_session) → server
server → session created → response snapshot
PiClient → SessionLease (exclusive) → caller
Ownership enforcement
caller acquires exclusive (ok)
caller attempts shared → PiSessionOwnershipError
caller releases exclusive
caller acquires shared (ok)
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Transport abstraction | ByteTransportFactory |
Fresh transport per attempt; keeps client Node-agnostic |
| Ownership | SessionLease exclusive/shared |
Guards mutation vs. observation; single coordinator |
| Request correlation | per-request ID + promises | Correct handling of out-of-order responses |
| Snapshot model | authoritative snapshots, transient progress | No optimistic mutation of authoritative state |
Risks and Unknowns
- No automatic reconnect; long-lived connections must manage
reconnect()explicitly. - Experimental API may change without notice.
Out of Scope
- The wire protocol (
pi-protocol). - The server (
pi-server). - Concrete transports beyond the
ByteTransportcontract.
Test Plan: Remote SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Client
Scope
Tests cover connection lifecycle, session acquisition and ownership enforcement, request/response correlation, state transitions, and disposal semantics.
Transport-level integration uses a Unix-socket transport (unix.ts); core client logic is transport-neutral.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Connection establishes via ByteTransportFactory and authenticates |
Valid factory + token | Client reaches connected/ready state |
| TC-2 | Ownership enforcement: exclusive then shared acquisition | SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. with exclusive lease held | Shared acquisition throws PiSessionOwnershipError |
| TC-3 | Ownership enforcement: exclusive while a lease exists | SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. with any lease held | Exclusive acquisition throws PiSessionOwnershipError |
| TC-4 | Request correlation delivers each response to its caller | Concurrent in-flight requests | Each caller receives its own response |
| TC-5 | State machine transitions on connect/close/error | Sequence of transport events | Correct state transitions |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-6 | Unix-socket transport end-to-end session create | Running server on a Unix socket | createSession({ cwd }) returns an exclusive lease |
| TC-7 | SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. subscribe/event delivery over the socket | Active session | Subscribers receive snapshots/events |
| TC-8 | Disposal releases leases and cleans up | Leases held | Disposal closes connection and releases resources |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-9 | Transport factory returns a stale/closed transport | Fresh transport is created per attempt |
| TC-10 | Disconnection without explicit reconnect | Client surfaces failure; no auto-reconnect |
| TC-11 | Duplicate release of a lease | Release is idempotent, no double-free |
Test Infrastructure
packages/client/test/support.tsprovides shared transport/test harness helpers.test/unix.test.tsexercises the concrete Unix-socket transport.- Ran with Vitest.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FRFunctional Requirement.-01MustThe system shall provide a `PiClient` that connects to a server via a `ByteTransportFactory` and authenticates with a bearer token. | TC-1, TC-6 |
| FRFunctional Requirement.-02MustThe system shall support creating a session (`createSession({ cwd })`) and returning a new session lease. | TC-6 |
| FRFunctional Requirement.-04MustThe system shall support acquiring sessions with explicit lease modes: `{ mode: "exclusive" }` or `{ mode: "shared" }`. | TC-2, TC-3 |
| FRFunctional Requirement.-05MustThe system shall enforce ownership: exclusive acquisition fails while any lease exists; shared acquisition fails while an exclusive lease exists. | TC-2, TC-3 |
| FRFunctional Requirement.-06MustThe system shall correlate requests by ID and deliver responses to the right caller. | TC-4 |
| FRFunctional Requirement.-07MustThe system shall publish session snapshots to subscribers and list sessions (`listSessions()`). | TC-7 |
| NFRNon-Functional Requirement.-02MustA transport factory must create a fresh transport for every connection attempt. | TC-9 |
| NFRNon-Functional Requirement.-04ShouldOn transport close/error the client shall surface the failure to callers and support explicit reconnect. | TC-10 |
requirements
- Should automatic reconnect with backoff be added, or does explicit
reconnect()suffice?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Server
Overview
@earendil-works/pi-server provides the experimental PiServer session server for remote pi sessions.
It is token-authenticated, listens on listeners (including a createUnixServer preset), manages live sessions via LiveSessionManager, publishes server and session snapshots, and ships a testing harness for building servers/clients in tests.
The legacy child-process supervisor (server CLICommand-Line Interface (the `pi` binary).) coexists in the same package under legacy/.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Remote session users | Host a pi session server that accepts authenticated clients over Unix sockets |
Coding agent (pi-coding-agent) |
A server-side counterpart to PiClient for remote sessions |
| Test authors | A testing harness for driving server/client pairs in tests |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-01MustThe system shall provide a `PiServer` class that serves authenticated remote sessions over listeners. | Must | The system shall provide a PiServer class that serves authenticated remote sessions over listeners. |
| FRFunctional Requirement.-02MustThe system shall require a bearer token before accepting session operations (validated in the `hello` handshake). | Must | The system shall require a bearer token before accepting session operations (validated in the hello handshake). |
| FRFunctional Requirement.-03MustThe system shall support a Unix socket transport preset (`createUnixServer`) with a configurable socket path. | Must | The system shall support a Unix socket transport preset (createUnixServer) with a configurable socket path. |
| FRFunctional Requirement.-04MustThe system shall manage live sessions through a `LiveSessionManager`. | Must | The system shall manage live sessions through a LiveSessionManager. |
| FRFunctional Requirement.-05MustThe system shall publish authoritative server snapshots and session snapshots to connected clients. | Must | The system shall publish authoritative server snapshots and session snapshots to connected clients. |
| FRFunctional Requirement.-06MustThe system shall route client requests (create/open/list sessions, prompt, subscribe) through the protocol. | Must | The system shall route client requests (create/open/list sessions, prompt, subscribe) through the protocol. |
| FRFunctional Requirement.-07ShouldThe system shall expose a `PiSessionBackend` interface decoupling the server from concrete session storage. | Should | The system shall expose a PiSessionBackend interface decoupling the server from concrete session storage. |
| FRFunctional Requirement.-08ShouldThe system shall ship a `testing` entrypoint with in-memory server/client helpers for tests. | Should | The system shall ship a testing entrypoint with in-memory server/client helpers for tests. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-01MustAccess shall require the configured bearer token; no anonymous sessions. | Must | Security | Access shall require the configured bearer token; no anonymous sessions. |
| NFRNon-Functional Requirement.-02MustThe server shall remain functional across client connect/disconnect cycles. | Must | Reliability | The server shall remain functional across client connect/disconnect cycles. |
| NFRNon-Functional Requirement.-03ShouldThe `legacy` supervisor CLICommand-Line Interface (the `pi` binary). and exports shall remain available while the new server is additive. | Should | Compatibility | The legacy supervisor CLICommand-Line Interface (the `pi` binary). and exports shall remain available while the new server is additive. |
| NFRNon-Functional Requirement.-04ShouldServer behavior shall be covered by a conformance suite plus per-component tests. | Should | Maintainability | Server behavior shall be covered by a conformance suite plus per-component tests. |
Constraints
- Experimental; APIs may change or be removed without notice.
- Unix socket transport only for the built-in preset.
- Same package hosts both the new
PiServerand the legacy supervisor (serverCLICommand-Line Interface (the `pi` binary).).
Acceptance Criteria
- FRFunctional Requirement.-01MustThe system shall provide a `PiServer` class that serves authenticated remote sessions over listeners.
- Given a
PiServerwith a backend and a Unix listener - When started
- Then it accepts connections on the configured socket path.
- Given a
- FRFunctional Requirement.-02MustThe system shall require a bearer token before accepting session operations (validated in the `hello` handshake).
- Given a connection without a valid token
- When it sends a session operation
- Then the server rejects it.
- FRFunctional Requirement.-05MustThe system shall publish authoritative server snapshots and session snapshots to connected clients.
- Given connected clients and a live session
- When session state changes
- Then authoritative snapshots are published to subscribers.
- NFRNon-Functional Requirement.-01MustAccess shall require the configured bearer token; no anonymous sessions.
- Given no configured token client
- When connecting
- Then the handshake fails.
Conflicts
None identified yet.
Open Questions
- Will the legacy supervisor eventually be removed in favor of
PiServeralone?
Specification: SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Server
Overview
pi-server hosts the experimental PiServer session server.
A PiServer is constructed with a PiSessionBackend (session storage) and one or more listeners; createUnixServer wires a Unix socket transport.
Connections authenticate via the protocol hello token, then exchange request/response and event envelopes.
LiveSessionManager tracks active sessions and publishes snapshots.
Architecture
+----------------------------+
| PiServer |
| - backend (PiSessionBackend)|
| - listeners |
+------------+---------------+
| accepts connections (e.g. Unix socket via createUnixServer)
v
+------------+---------------+
| connection.ts |
| hello/auth, protocol.ts |
+------------+---------------+
|
v
+------------+---------------+
| LiveSessionManager |
| sessions.ts, snapshots.ts |
+----------------------------+
server.ts is the entry point; listener.ts defines listeners; transports/unix/ the Unix transport; sessions.ts/snapshots.ts live-session and snapshot management; testing/ in-memory server/client helpers.
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
PiSessionBackend
| Method | Signature | Description |
|---|---|---|
| listSessions | () => Promise<SessionSummary[]> |
List known sessions |
| listModels | () => Promise<ModelInfo[]> |
List available models |
| createSession | (options) => Promise<SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`.> |
Create and open a session |
| openSession | (sessionId) => Promise<SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`.> |
Open an existing session |
API Contracts
createUnixServer(backend, options)
Request
| Field | Type | Required | Description |
|---|---|---|---|
| backend | PiSessionBackend | yes | SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. storage adapter |
| options.token | string | yes | Bearer token |
| options.path | string | yes | Unix socket path |
Response (200 OK)
| Field | Type | Description |
|---|---|---|
| server | PiServer | Started server instance |
Sequences
Client connect
Client → createUnixServer → server.start()
Client connects (Unix socket)
Client → hello {version, token} → server validates → session established
Client → createSession/openSession → LiveSessionManager → snapshots → client
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Auth | bearer token in hello |
Reuses protocol handshake, no extra round trips |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. management | LiveSessionManager |
Single owner of live session lifecycle |
| Snapshot publication | server + session snapshots | Clients render from authoritative state |
| Backend abstraction | PiSessionBackend |
Decouples transport from session storage |
| Package layout | new PiServer + legacy/ supervisor |
Additive migration; legacy CLICommand-Line Interface (the `pi` binary). kept |
Risks and Unknowns
- Experimental; the API may change or be removed without notice.
- Only a Unix socket preset ships; other transports are future work.
- Relationship to the legacy supervisor is transitional.
Out of Scope
- The wire protocol (
pi-protocol). - The client (
pi-client). - SQLite session persistence (separate feature in
pi-storage-sqlite-node).
Test Plan: SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. Server
Scope
Tests cover server startup and listeners, protocol handling, live-session management, snapshot publication, Unix-socket connectivity, and a conformance suite exercising the server as a client would.
Legacy supervisor behavior is not covered here (separate feature, p1-orchestrator).
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | LiveSessionManager creates and tracks sessions | Create/open requests | Sessions tracked; snapshots updated |
| TC-2 | Snapshot publication reflects authoritative state | State change on a live session | Subscribers receive new snapshot |
| TC-3 | Protocol routing handles client requests | Request envelopes | Correct responses routed |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-4 | Server starts and accepts Unix-socket connections | createUnixServer on a temp path |
Connections accepted |
| TC-5 | End-to-end session create over Unix socket | Running server + client | SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. created and snapshots flow |
| TC-6 | Conformance suite drives server as a client | testing harness |
Behavior matches the protocol contract |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-7 | Connection with missing/invalid token | Rejected before session operations |
| TC-8 | Client disconnect mid-session | Live session cleaned up; server remains up |
| TC-9 | Concurrent client connections | Sessions isolated per client lease |
Test Infrastructure
test/fixturesprovides shared setup.testing/entrypoint provides in-memory server/client harness.- Ran with Vitest (
packages/server/test/).
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FRFunctional Requirement.-01MustThe system shall provide a `PiServer` class that serves authenticated remote sessions over listeners. | TC-4, TC-5 |
| FRFunctional Requirement.-02MustThe system shall require a bearer token before accepting session operations (validated in the `hello` handshake). | TC-7 |
| FRFunctional Requirement.-03MustThe system shall support a Unix socket transport preset (`createUnixServer`) with a configurable socket path. | TC-4 |
| FRFunctional Requirement.-04MustThe system shall manage live sessions through a `LiveSessionManager`. | TC-1 |
| FRFunctional Requirement.-05MustThe system shall publish authoritative server snapshots and session snapshots to connected clients. | TC-2 |
| FRFunctional Requirement.-06MustThe system shall route client requests (create/open/list sessions, prompt, subscribe) through the protocol. | TC-3, TC-5 |
| FRFunctional Requirement.-08ShouldThe system shall ship a `testing` entrypoint with in-memory server/client helpers for tests. | TC-6 |
| NFRNon-Functional Requirement.-02MustThe server shall remain functional across client connect/disconnect cycles. | TC-8, TC-9 |
requirements
- Will the legacy supervisor eventually be removed in favor of
PiServeralone?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: SQLite SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.
Overview
@earendil-works/pi-storage-sqlite-node provides a node:sqlite storage backend for pi-agent-core sessions.
It ships the SqliteDatabase adapter, a SqliteSessionRepository, schema migrations (including branch-tips tracking), materialized session projections, and an optional full-text search backend.
Sessions can be created, opened, and queried with text search against a single canonical SQLite database.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Agent users | Fast, queryable session persistence with search |
pi-agent-core integrators |
A drop-in SQLite backend behind the existing session repository interface |
| Search consumers | Optional FTS search over session content |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-01MustThe system shall provide a `SqliteDatabase` adapter over `node:sqlite`. | Must | The system shall provide a SqliteDatabase adapter over node:sqlite. |
| FRFunctional Requirement.-02MustThe system shall provide a `SqliteSessionRepository` implementing the agent session repository interface. | Must | The system shall provide a SqliteSessionRepository implementing the agent session repository interface. |
| FRFunctional Requirement.-03MustThe system shall create and open sessions with a cwd, and persist session data durably. | Must | The system shall create and open sessions with a cwd, and persist session data durably. |
| FRFunctional Requirement.-04MustThe system shall run schema migrations on open (including `001_initial` and `002_branch_tips`). | Must | The system shall run schema migrations on open (including 001_initial and 002_branch_tips). |
| FRFunctional Requirement.-05ShouldThe system shall maintain materialized views for session summaries, entries, and sequences. | Should | The system shall maintain materialized views for session summaries, entries, and sequences. |
| FRFunctional Requirement.-06ShouldThe system shall provide an optional FTS search backend (`createSqliteSessionSearch`) for text queries. | Should | The system shall provide an optional FTS search backend (createSqliteSessionSearch) for text queries. |
| FRFunctional Requirement.-07ShouldThe system shall share one lazy database connection across repository and search. | Should | The system shall share one lazy database connection across repository and search. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-01MustMigrations shall be idempotent and version-tracked. | Must | Correctness | Migrations shall be idempotent and version-tracked. |
| NFRNon-Functional Requirement.-02MustThe repository shall lazily own one shared connection; errors surface cleanly. | Must | Reliability | The repository shall lazily own one shared connection; errors surface cleanly. |
| NFRNon-Functional Requirement.-03ShouldSearch shall be a query-only projection over the canonical database. | Should | Performance | Search shall be a query-only projection over the canonical database. |
| NFRNon-Functional Requirement.-04ShouldNode `>=22.19.0` with built-in `node:sqlite`; no native build step. | Should | Portability | Node >=22.19.0 with built-in node:sqlite; no native build step. |
Constraints
- Requires Node's built-in
node:sqlite(Node >= 22.19.0). - Tested through
packages/agent/test/harness/; the package itself carries no test files.
Acceptance Criteria
- FRFunctional Requirement.-02MustThe system shall provide a `SqliteSessionRepository` implementing the agent session repository interface.
- Given an open
SqliteSessionRepository - When
repository.create({ cwd })is called - Then a new session is created and persisted.
- Given an open
- FRFunctional Requirement.-04MustThe system shall run schema migrations on open (including `001_initial` and `002_branch_tips`).
- Given a fresh database file
- When the repository is opened
- Then migrations
001_initialand002_branch_tipsare applied.
- FRFunctional Requirement.-06ShouldThe system shall provide an optional FTS search backend (`createSqliteSessionSearch`) for text queries.
- Given a session with content
- When
search.search({ text: "needle" })runs - Then matching session entries are returned.
- NFRNon-Functional Requirement.-01MustMigrations shall be idempotent and version-tracked.
- Given an already-migrated database
- When the repository is opened again
- Then no migration is re-applied and no error is thrown.
Conflicts
None identified yet.
Open Questions
- Should the SQLite backend become the default session store, or remain an opt-in alternative to JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol).?
Specification: SQLite SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.
Overview
pi-storage-sqlite-node implements a node:sqlite backend for agent sessions.
A SqliteSessionRepository implements the agent session-repository contract, backed by a single lazy shared connection.
Schema migrations set up the canonical tables plus materialized projections (session summaries, entries, sequences, branch tips), and an independent search backend provides FTS queries over the same database.
Architecture
+-------------------------------+
| SqliteSessionRepository |
| (implements session repo) |
+--------------+----------------+
| node:sqlite (lazy single connection)
v
+--------------+----------------+
| SQLite database |
| migrations 001_initial, |
| 002_branch_tips |
| storage/: sessions, entries, |
| sequences, materialized, |
| branch-cache |
+-------------------------------+
^
+--------------+----------------+
| createSqliteSessionSearch |
| (FTS search, query-only) |
+-------------------------------+
sqlite/repo.ts is the repository; sqlite/migrations.ts + sqlite/migrations/*.sql the schema; sqlite/storage/ the table/storage modules; sqlite/search-backend.ts the FTS search; sqlite/types.ts the shared types.
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. table (excerpt, from 001_initial.sql)
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | text/uuid | PK | SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. identifier |
| cwd | text | not null | Working directory |
| created_at | int | not null | Creation timestamp |
| ... | Full session schema from migration |
Branch tips (from 002_branch_tips.sql)
Tracks the tip of each session branch to support fast branch navigation and summaries.
API Contracts
new SqliteSessionRepository(options)
Request
| Field | Type | Required | Description |
|---|---|---|---|
| options | object | yes | Path/database + session schema options |
Response (200 OK)
| Field | Type | Description |
|---|---|---|
| repository | SqliteSessionRepository | Async-disposable repository |
createSqliteSessionSearch(options)
Request
| Field | Type | Required | Description |
|---|---|---|---|
| options | object | yes | Database + search options |
Response (200 OK)
| Field | Type | Description |
|---|---|---|
| search | object | .search({ text }) returning matching entries |
Sequences
Open + migrate
new SqliteSessionRepository → open database → run pending migrations
→ materialize views → ready
Search
createSqliteSessionSearch → query-only projection over same database
→ search({ text }) → hits
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Driver | node:sqlite |
No native dependency, Node >= 22.19.0 |
| Connection | single lazy shared connection | Simplicity; repository owns lifecycle |
| Migrations | versioned .sql files |
Deterministic schema evolution |
| Projections | materialized views + branch tips | Fast reads without touching raw logs |
| Search | separate query-only backend | No write coupling between repo and search |
Risks and Unknowns
node:sqliteis a recent Node API; version floor must be honored.- FTS behavior and query semantics are experimental.
Out of Scope
- The remote-session protocol/client/server (separate features).
- The JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). session manager in the coding agent.
Test Plan: SQLite SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.
Scope
Tests cover migrations, the SQLite session repository, branch-cache behavior, search queries, and backend equivalence against the agent session contract.
Tests live in packages/agent/test/harness/ because the package itself carries no test files.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Migrations apply idempotently and in order | Fresh database, then reopen | 001_initial + 002_branch_tips applied once |
| TC-2 | Repository create/open persists sessions | create({ cwd }) |
SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. persisted and reopenable |
| TC-3 | Branch-cache materialization tracks branch tips | BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). operations | Tips maintained correctly |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-4 | SQLite backend matches the session-backend contract | HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. driving the repo | Same observable behavior as the contract |
| TC-5 | Branch queries over SQLite return correct branch data | Sessions with branches | Correct branch results |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-6 | Reopen an already-migrated database | No re-migration, no error |
| TC-7 | Search over sessions with no FTS content | Empty result set, no crash |
Test Infrastructure
- Ran with Vitest from
packages/agent/test/harness/: sqlite-migrations.test.ts,sqlite-branch-cache.test.ts,sqlite-node.test.ts,branch-query.test.ts,session-backends.test.ts.- Requires Node
>=22.19.0fornode:sqlite.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FRFunctional Requirement.-01MustThe system shall provide a `SqliteDatabase` adapter over `node:sqlite`. | TC-4 |
| FRFunctional Requirement.-02MustThe system shall provide a `SqliteSessionRepository` implementing the agent session repository interface. | TC-2, TC-4 |
| FRFunctional Requirement.-03MustThe system shall create and open sessions with a cwd, and persist session data durably. | TC-2 |
| FRFunctional Requirement.-04MustThe system shall run schema migrations on open (including `001_initial` and `002_branch_tips`). | TC-1, TC-6 |
| FRFunctional Requirement.-05ShouldThe system shall maintain materialized views for session summaries, entries, and sequences. | TC-3 |
| FRFunctional Requirement.-06ShouldThe system shall provide an optional FTS search backend (`createSqliteSessionSearch`) for text queries. | TC-7 |
| NFRNon-Functional Requirement.-01MustMigrations shall be idempotent and version-tracked. | TC-1, TC-6 |
requirements
- Should the SQLite backend become the default session store, or remain an opt-in alternative to JSONL?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`).
Overview
@earendil-works/pi-evals provides behavioral, model-backed evals for PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. workflows.
EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). adapt a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. to vitest-evals, run it in isolated temporary project and agent directories, and attach native PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. session artifacts.
They measure end-to-end behavior to compare prompts, tools, skills, models, or other harness configurations.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Maintainers | Behavioral regression signals for PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. workflows across model/harness configurations |
| Contributors | A harness for validating extensions, prompts, skills, and tools |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities./tool researchers | Apples-to-apples comparisons of prompt/model/tool configs |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-01MustThe system shall adapt a real `AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.` to the `vitest-evals` harness interface. | Must | The system shall adapt a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. to the vitest-evals harness interface. |
| FRFunctional Requirement.-02MustThe system shall run each eval in an isolated temporary project directory and agent directory. | Must | The system shall run each eval in an isolated temporary project directory and agent directory. |
| FRFunctional Requirement.-03MustThe system shall attach native PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. session artifacts to eval results. | Must | The system shall attach native PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. session artifacts to eval results. |
| FRFunctional Requirement.-04MustThe system shall be runnable from the repo root via `npm run eval` with a provider/model default. | Must | The system shall be runnable from the repo root via npm run eval with a provider/model default. |
| FRFunctional Requirement.-05ShouldThe system shall support filtering evals by file or by test name (Vitest forwarding). | Should | The system shall support filtering evals by file or by test name (Vitest forwarding). |
| FRFunctional Requirement.-06ShouldThe system shall ship a set of core evals (e.g. smoke, documentation-audit, `*.docs.eval.ts`). | Should | The system shall ship a set of core evals (e.g. smoke, documentation-audit, *.docs.eval.ts). |
| FRFunctional Requirement.-07ShouldThe system shall allow harnesses to configure their own model, overriding the default. | Should | The system shall allow harnesses to configure their own model, overriding the default. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-01MustEvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). shall be isolated (temp dirs) so runs do not touch the real workspace. | Must | Reliability | EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). shall be isolated (temp dirs) so runs do not touch the real workspace. |
| NFRNon-Functional Requirement.-02MustEvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). shall not require real provider keys beyond the user's normal PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. auth. | Must | Security | EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). shall not require real provider keys beyond the user's normal PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. auth. |
| NFRNon-Functional Requirement.-03ShouldResults shall include session artifacts so failures are diagnosable. | Should | Maintainability | Results shall include session artifacts so failures are diagnosable. |
Constraints
- Requires a configured provider/model (CLICommand-Line Interface (the `pi` binary). values or
PI_PROVIDER/PI_MODEL). - Requires the normal PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries.
ModelRuntimeauth (subscription credentials or API-key env vars). - EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). are model-backed; they cost tokens and are not part of the default
test.shsuite.
Acceptance Criteria
- FRFunctional Requirement.-01MustThe system shall adapt a real `AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.` to the `vitest-evals` harness interface.
- Given a working PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. installation with a provider configured
- When
npm run evalruns - Then an
AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.runs inside thevitest-evalsharness in an isolated temp dir.
- FRFunctional Requirement.-02MustThe system shall run each eval in an isolated temporary project directory and agent directory.
- Given an eval run
- When it executes
- Then the project and agent directories are temporary and isolated.
- FRFunctional Requirement.-04MustThe system shall be runnable from the repo root via `npm run eval` with a provider/model default.
- Given a repo with a provider/model configured
- When
npm run eval -- --provider openai --model gpt-5.6-solruns - Then evals execute with that default.
- FRFunctional Requirement.-05ShouldThe system shall support filtering evals by file or by test name (Vitest forwarding).
- Given many evals
- When
npm run eval:host -w packages/evals -- evals/documentation-audit.eval.tsor-t "<name>"is used - Then only the matching evals run.
Conflicts
None identified yet.
Open Questions
- Should evals be integrated into CIContinuous Integration (the `ci` GitHub workflow). with a pinned model, or stay local/on-demand only?
Specification: EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`).
Overview
pi-evals turns real PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. agent runs into behavioral evals.
A harness.ts adapter exposes a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. to the vitest-evals harness, running it inside isolated temporary project and agent directories.
CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. evals (smoke, documentation-audit, *.docs.eval.ts) plus the docs-comparison runner (cli.ts, docker.ts, plan.ts, report.ts) and container images (docker/) support measuring and comparing workflow behavior.
Architecture
npm run eval (root forwards to packages/evals: eval:host + eval:docs via src/cli.ts)
|
v
+---------------------+
| vitest-evals |
| (harness runner; |
| host + docs |
| projects) |
+----------+----------+
| adapts a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.
v
+---------------------+
| src/harness.ts |
| (isolated temp |
| project + agent) |
+----------+----------+
|
v
+---------------------+
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. |
| (real pi agent) |
+---------------------+
evals/smoke.eval.ts and evals/documentation-audit.eval.ts are host evals; evals/*.docs.eval.ts are documentation-lift evals run as paired (case, variant, run) arms in containers. src/cli.ts orchestrates the comparison, src/docker.ts builds images and runs arms, src/plan.ts expands cases into tasks, src/report.ts pairs arms and computes lift, and src/harness.ts is the vitest-evals adapter. Unit tests live in test/ (harness, plan, report, comparison, configured-runtime, acme-server).
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
Eval artifact
| Field | Type | Constraints | Description |
|---|---|---|---|
| session | native pi session | attached | The AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. transcript/artifacts from the run |
| result | vitest-evals result | — | HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. verdict and observations |
API Contracts
npm run eval [-- --provider <p> --model <m>]
Request
| Field | Type | Required | Description |
|---|---|---|---|
| provider | string | yes* | Default provider (* unless every harness sets its own model) |
| model | string | yes* | Default model |
Response (200 OK)
| Field | Type | Description |
|---|---|---|
| exit code | number | Vitest exit code for the eval run |
Sequences
Run an eval
npm run eval → packages/evals (eval:host via vitest.evals.config.ts host project; eval:docs via src/cli.ts) → vitest-evals → src/harness.ts
→ create temp project + agent dirs → adapt AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.
→ run workflow → attach session artifacts → record result
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | vitest-evals |
Reuses Vitest runner, filtering, and reporting |
| Isolation | temp project + agent dirs per eval | No side effects on the real workspace |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. defaults | CLICommand-Line Interface (the `pi` binary). args or PI_PROVIDER/PI_MODEL |
CLICommand-Line Interface (the `pi` binary). wins; harnesses may override per eval |
| Auth | normal ModelRuntime |
Subscription + env API keys, no new secret handling |
Risks and Unknowns
- ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.-backed evals are non-deterministic and cost tokens; thresholds need care.
- Auth availability (subscription vs. API keyApplication Programming Interface key (ambient provider authentication).) affects whether evals can run locally.
Out of Scope
- The remote-session stack (protocol/client/server).
- SQLite session storage.
- The interactive coding agent itself (covered by other features).
Test Plan: EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`).
Scope
Tests cover the src/harness.ts adapter (model selection, environment isolation, documentation variants), the comparison runner (src/plan.ts task planning, src/report.ts observation pairing and lift summary), and the harness contract.
ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.-backed eval runs themselves (smoke, documentation-audit, *.docs.eval.ts) are on-demand and excluded from the default unit suite.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | src/harness.ts adapts an AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. to the harness interface |
HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. options | A valid harness instance |
| TC-2 | Task planning expands cases into (case, variant, model, run) arms |
Discovered cases | Correct planned cohort |
| TC-3 | Observation reading attaches session artifacts and aggregates lift | Completed run | Artifacts recorded, paired summary |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-4 | vitest-evals summary aggregates results across evals |
Multiple eval results | Aggregated summary with pass/fail |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-5 | No provider/model configured | Eval run fails with a clear error |
| TC-6 | HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. without a model selection and no default | Run reports a configuration error |
Test Infrastructure
- Ran with Vitest (
packages/evals/test/): harness.test.ts,plan.test.ts,report.test.ts,comparison.test.ts,configured-runtime.test.ts,acme-server.test.ts.- Host evals live in
evals/(smoke.eval.ts,documentation-audit.eval.ts) and documentation-lift evals inevals/*.docs.eval.ts; run vianpm run eval(host) /npm run eval:docs(comparison) with a provider/model.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FRFunctional Requirement.-01MustThe system shall adapt a real `AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume.` to the `vitest-evals` harness interface. | TC-1 |
| FRFunctional Requirement.-07ShouldThe system shall allow harnesses to configure their own model, overriding the default. | TC-2 |
| NFRNon-Functional Requirement.-03ShouldResults shall include session artifacts so failures are diagnosable. | TC-3, TC-4 |
| FRFunctional Requirement.-04MustThe system shall be runnable from the repo root via `npm run eval` with a provider/model default. | TC-5 |
requirements
- Should evals be integrated into CI with a pinned model, or stay local/on-demand only?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences.
Overview
@earendil-works/pi-durable provides the durable conversation, task, and document runtime for PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries..
It implements the Pico model in which a SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. atomically commits immutable entries, full task records, and ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.-tracked documents.
The package currently ships the durable record contracts, the StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. persistence boundary, and the detached in-memory MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. reference implementation.
The root conversation always uses the reserved ROOT_CONVERSATION_ID (1), and fresh IDs are minted from 2 upward.
The normative design lives in packages/durable/docs/spec.md.
Stakeholders
| Stakeholder | Interest |
|---|---|
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. implementers | A stable record and storage contract for building the Pico SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. mutation line. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend authors | A conformance baseline (MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence.) for serialization-backed stores. |
| Contributors | Typed record contracts that fail fast at compile time on invalid state transitions. |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-1MustThe system shall model conversations as immutable records with an ID, an optional fork parent edge, and an optional task owner edge. | Must | The system shall model conversations as immutable records with an ID, an optional fork parent edge, and an optional task owner edge. |
| FRFunctional Requirement.-2MustThe system shall model entries as immutable transcript events with kind, optional model messages, optional JSON data, optional head marker, optional context edits, and optional producing task ID. | Must | The system shall model entries as immutable transcript events with kind, optional model messages, optional JSON data, optional head marker, optional context edits, and optional producing task ID. |
| FRFunctional Requirement.-3MustThe system shall model host inputs through the queued, placed, done, and unanswered lifecycle states with conversation-scoped request ID deduplication. | Must | The system shall model host inputs through the queued, placed, done, and unanswered lifecycle states with conversation-scoped request ID deduplication. |
| FRFunctional Requirement.-4MustThe system shall model tasks as pending, running, and terminal states with completed, failed, aborted, orphaned, and faulted outcomes. | Must | The system shall model tasks as pending, running, and terminal states with completed, failed, aborted, orphaned, and faulted outcomes. |
| FRFunctional Requirement.-5MustThe system shall model document incarnations with session, conversation, and task scopes plus history and fork policies. | Must | The system shall model document incarnations with session, conversation, and task scopes plus history and fork policies. |
| FRFunctional Requirement.-6MustThe system shall expose a `StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.` boundary with atomic commit, global ID minting, conversation lookup and scan, entry lookup with commit sequence, head-marker search, fork-aware entry scan, task lookup and filtered scan, input lookup by ID and request key, and close. | Must | The system shall expose a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. boundary with atomic commit, global ID minting, conversation lookup and scan, entry lookup with commit sequence, head-marker search, fork-aware entry scan, task lookup and filtered scan, input lookup by ID and request key, and close. |
| FRFunctional Requirement.-7MustThe system shall provide `MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence.` as a detached in-memory `StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.` with atomic commits, sorted indexes, opaque cursors, fork-aware history scans, a single global ID namespace, and post-close rejection. | Must | The system shall provide MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. as a detached in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. with atomic commits, sorted indexes, opaque cursors, fork-aware history scans, a single global ID namespace, and post-close rejection. |
| FRFunctional Requirement.-8MustThe system shall reserve `ROOT_CONVERSATION_ID` (`1`) for the root conversation and start minted IDs at `2`. | Must | The system shall reserve ROOT_CONVERSATION_ID (1) for the root conversation and start minted IDs at 2. |
| FRFunctional Requirement.-9MustThe system shall enforce omit and replace context-edit discriminators so omissions carry no messages and replacements always carry messages. | Must | The system shall enforce omit and replace context-edit discriminators so omissions carry no messages and replacements always carry messages. |
| FRFunctional Requirement.-10ShouldThe system shall expose pagination (`Page`, `Cursor`), scan filters (`EntryQuery`, `TaskQuery`), and the atomic `StorageWrite` table-mutation union. | Should | The system shall expose pagination (Page, Cursor), scan filters (EntryQuery, TaskQuery), and the atomic StorageWrite table-mutation union. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-1MustCommits shall be atomic so a failed batch persists none of its writes. | Must | Reliability | Commits shall be atomic so a failed batch persists none of its writes. |
| NFRNon-Functional Requirement.-2MustStored and returned values shall be detached clones that never pollute object prototypes. | Must | Security | Stored and returned values shall be detached clones that never pollute object prototypes. |
| NFRNon-Functional Requirement.-3MustThe package shall use erasable TypeScript with top-level imports only and no `any`. | Must | Maintainability | The package shall use erasable TypeScript with top-level imports only and no any. |
| NFRNon-Functional Requirement.-4ShouldIn-memory reads and scans shall use sorted-index seeks rather than full-table sorts. | Should | Performance | In-memory reads and scans shall use sorted-index seeks rather than full-table sorts. |
Constraints
MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence.is a conformance reference, not a persistent backend.- StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. trusts the owning SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. for semantic validity of records, references, ancestry, and transitions.
- The package has no HTTPHypertext Transfer Protocol. surface and therefore ships no
api.yaml.
Acceptance Criteria
Every FRFunctional Requirement. and NFRNon-Functional Requirement. shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
-
FRFunctional Requirement.-1MustThe system shall model conversations as immutable records with an ID, an optional fork parent edge, and an optional task owner edge.
gherkin @FRFunctional Requirement.-1MustThe system shall model conversations as immutable records with an ID, an optional fork parent edge, and an optional task owner edge. Scenario: create and read a forked conversation Given a storage with a root conversation When a child conversation with a parent edge is committed Then reading the child returns the exact parent edge -
FRFunctional Requirement.-2MustThe system shall model entries as immutable transcript events with kind, optional model messages, optional JSON data, optional head marker, optional context edits, and optional producing task ID.
gherkin @FRFunctional Requirement.-2MustThe system shall model entries as immutable transcript events with kind, optional model messages, optional JSON data, optional head marker, optional context edits, and optional producing task ID. Scenario: commit and read an immutable entry Given a storage with a root conversation When an entry with kind, model messages, and data is committed Then reading the entry returns the same kind, messages, and data with its commit sequence -
FRFunctional Requirement.-3MustThe system shall model host inputs through the queued, placed, done, and unanswered lifecycle states with conversation-scoped request ID deduplication.
gherkin @FRFunctional Requirement.-3MustThe system shall model host inputs through the queued, placed, done, and unanswered lifecycle states with conversation-scoped request ID deduplication. Scenario: advance an input through its lifecycle Given a queued input with a request ID When the input is replaced by placed and then done records Then lookups by ID and by request key return the latest record -
FRFunctional Requirement.-4MustThe system shall model tasks as pending, running, and terminal states with completed, failed, aborted, orphaned, and faulted outcomes.
gherkin @FRFunctional Requirement.-4MustThe system shall model tasks as pending, running, and terminal states with completed, failed, aborted, orphaned, and faulted outcomes. Scenario: run a task to a terminal outcome Given a pending task with a checkpoint When the task is replaced by running and then terminal records Then the stored task carries the terminal outcome and no live checkpoint -
FRFunctional Requirement.-5MustThe system shall model document incarnations with session, conversation, and task scopes plus history and fork policies.
gherkin @FRFunctional Requirement.-5MustThe system shall model document incarnations with session, conversation, and task scopes plus history and fork policies. Scenario: declare scoped document incarnations Given the document record contracts When a conversation document declares rewindable history with as-of fork Then the type system accepts it and rejects session documents with conversation policies -
FRFunctional Requirement.-6MustThe system shall expose a `StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.` boundary with atomic commit, global ID minting, conversation lookup and scan, entry lookup with commit sequence, head-marker search, fork-aware entry scan, task lookup and filtered scan, input lookup by ID and request key, and close.
gherkin @FRFunctional Requirement.-6MustThe system shall expose a `StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.` boundary with atomic commit, global ID minting, conversation lookup and scan, entry lookup with commit sequence, head-marker search, fork-aware entry scan, task lookup and filtered scan, input lookup by ID and request key, and close. Scenario: exercise the full storage boundary Given an empty storage When conversations, entries, tasks, and inputs are committed and scanned Then every lookup, filtered scan, and cursor page returns the committed records -
FRFunctional Requirement.-7MustThe system shall provide `MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence.` as a detached in-memory `StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.` with atomic commits, sorted indexes, opaque cursors, fork-aware history scans, a single global ID namespace, and post-close rejection.
gherkin @FRFunctional Requirement.-7MustThe system shall provide `MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence.` as a detached in-memory `StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.` with atomic commits, sorted indexes, opaque cursors, fork-aware history scans, a single global ID namespace, and post-close rejection. Scenario: scan deep fork history newest-first Given a grandchild conversation forked through two ancestor caps When entries are scanned newest-first with cursors Then results cross each ancestor cap in order and excluded entries never appear -
FRFunctional Requirement.-8MustThe system shall reserve `ROOT_CONVERSATION_ID` (`1`) for the root conversation and start minted IDs at `2`.
gherkin @FRFunctional Requirement.-8MustThe system shall reserve `ROOT_CONVERSATION_ID` (`1`) for the root conversation and start minted IDs at `2`. Scenario: reserve the root conversation ID Given a fresh storage When the first ID is minted and the root conversation is committed Then the minted ID is 2 and recommitting ID 1 is rejected -
FRFunctional Requirement.-9MustThe system shall enforce omit and replace context-edit discriminators so omissions carry no messages and replacements always carry messages.
gherkin @FRFunctional Requirement.-9MustThe system shall enforce omit and replace context-edit discriminators so omissions carry no messages and replacements always carry messages. Scenario: enforce context-edit discriminators Given the context-edit contracts When a replacement without messages or an omission with messages is assigned Then the type system rejects the assignment -
FRFunctional Requirement.-10ShouldThe system shall expose pagination (`Page`, `Cursor`), scan filters (`EntryQuery`, `TaskQuery`), and the atomic `StorageWrite` table-mutation union.
gherkin @FRFunctional Requirement.-10ShouldThe system shall expose pagination (`Page`, `Cursor`), scan filters (`EntryQuery`, `TaskQuery`), and the atomic `StorageWrite` table-mutation union. Scenario: paginate scans with opaque cursors Given three conversations in storage When the first page of size two is read and continued with its cursor Then the second page returns only the remaining conversation -
NFRNon-Functional Requirement.-1MustCommits shall be atomic so a failed batch persists none of its writes.
gherkin @NFRNon-Functional Requirement.-1MustCommits shall be atomic so a failed batch persists none of its writes. Scenario: roll back a failed mixed-table batch Given committed entry, task, and input records When a batch containing a duplicate conversation ID is committed Then the commit rejects and none of the batch writes are visible -
NFRNon-Functional Requirement.-2MustStored and returned values shall be detached clones that never pollute object prototypes.
gherkin @NFRNon-Functional Requirement.-2MustStored and returned values shall be detached clones that never pollute object prototypes. Scenario: resist prototype pollution through stored JSON Given an entry carrying `__proto__` and `constructor` keys When the entry is committed and read back twice Then the reads keep `Object.prototype` and the stored values stay unchanged -
NFRNon-Functional Requirement.-3MustThe package shall use erasable TypeScript with top-level imports only and no `any`.
gherkin @NFRNon-Functional Requirement.-3MustThe package shall use erasable TypeScript with top-level imports only and no `any`. Scenario: hold the erasable TypeScript boundary Given the package sources and tests When the root check runs Then no strip-only violations are reported for the package -
NFRNon-Functional Requirement.-4ShouldIn-memory reads and scans shall use sorted-index seeks rather than full-table sorts.
gherkin @NFRNon-Functional Requirement.-4ShouldIn-memory reads and scans shall use sorted-index seeks rather than full-table sorts. Scenario: seek sorted indexes on scan Given entries committed out of ID order When entries are scanned newest-first Then results arrive in ID order without caller-side sorting
Conflicts
None identified yet.
Open Questions
- Which serialization-backed store becomes the first persistent
StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.beyondMemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence.? - Should document deltas ship inside this package or stay in the ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. package with usage docs only?
- Does the SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`.-level commit path need a published conformance suite shared by every backend?
Specification: Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences.
Overview
The package implements the Pico durable-record layer as TypeScript contracts with MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. and SqliteStorage backends behind the StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. boundary, plus the SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. mutation line and the ExecutionEnv interface.
Record types encode every lifecycle discriminator as a union so invalid states fail at compile time.
MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. keeps sorted per-table indexes and clones across the ownership boundary so it behaves like a serialization-backed store.
Architecture
types.ts owns all record contracts and the StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. interface.
storage/memory.ts implements StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. with Map tables and sorted ID arrays.
storage/sqlite/ implements the persistent SqliteStorage over a portable SqliteDatabase facade (node and cloudflare adapters).
session/ owns the SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. mutation line (createSession); index.ts re-exports the public surface.
The SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. serializes commits and supplies semantic validity.
flowchart LR
SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. --> StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.
StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. --> MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence.
types --> MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence.
types --> SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`.
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. record
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | Id | PK, not null, globally unique | Transcript scope identity. |
| parent.conversationId | Id | FK when present | Fork source conversation. |
| parent.at | Id | Inclusive cap when present | Newest inherited parent entry. |
| owner.conversationId | Id | FK when present | Creator conversation for abort and idle waits. |
| owner.taskId | Id | FK when present | Creator task for abort and idle waits. |
Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context.
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | Id | PK, immutable, never reused | Global transcript event identity. |
| conversationId | Id | FK, not null | Owning conversation. |
| kind | string | Not null | Application-defined entry discriminator. |
| model | readonly Message[] | Optional | Messages contributed to model context. |
| data | JsonValue | Optional | Payload for views, plugins, or bookkeeping. |
| head | Id | Optional | First entry of the active context selected by this entry. |
| edits | readonly ContextEdit[] | Optional | Context-only overrides of earlier visible entries. |
| byTaskId | Id | Optional | Task that appended this entry. |
Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps.
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | Id | PK, globally unique | Task identity. |
| conversationId | Id | FK, not null | Attaching conversation. |
| kind | string | Not null | Registered task definition name. |
| version | number | Not null | Definition version for input and checkpoint migration. |
| input | I | Retained while live or terminal | Original task input. |
| after | readonly Id[] | Possibly empty | Tasks that must be terminal before ordinary execution. |
| background | boolean | Not null | Exclusion from idle waits and conversation aborts. |
| abortRequested | boolean | Not null | Durable abort mark checked before run-mode progress commits. |
| state | TaskState | Pending, running, or terminal | Complete durable execution state. |
| memos | Record |
Live tasks only | Small first-writer-wins values. |
| outcome | TaskOutcome | Terminal tasks only | Completed, failed, aborted, orphaned, or faulted receipt. |
DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. record
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | Id | PK, never reused across incarnations | Unique incarnation identity. |
| kind | string | Not null | Registered document kind. |
| key | string | Optional | Family member key, absent for singletons. |
| createdAt | Seq | Stamped by storage | Creating commit sequence. |
| retiredAt | Seq | Absent while current | Retiring commit sequence. |
| scope | session, conversation, or task | Not null | Ownership scope with conversation ID or task ID where applicable. |
| history | latest or rewindable | ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. scope only | Retention policy for as-of reads. |
| fork | current, initial, or asOf | ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. scope only | Initialization policy, constrained by history choice. |
Input record
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | Id | PK, globally unique | Admitted input identity. |
| conversationId | Id | FK, not null | Owning conversation. |
| requestId | string | Optional, conversation-scoped | Host deduplication key. |
| status | queued, placed, done, or unanswered | Not null | Lifecycle state. |
| entry | Id | Placed and done, optional for unanswered | Transcript entry created at placement. |
| answer | Id | Done only | Assistant answer entry. |
| reason | string | Unanswered only | Machine-readable terminal explanation. |
| detail | JsonValue | Optional | Structured diagnostics for unanswered inputs and stored errors. |
API Contracts
The package exposes a TypeScript interface, not an HTTPHypertext Transfer Protocol. surface, so there is no api.yaml.
The StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. boundary is: commit, mintId, conversation, scanConversations, entry, findLatestHeadMarker, scanEntries, task, scanTasks, input, inputByRequest, and close.
Cursor pagination returns { items, next } where next is an opaque { after } continuation.
findLatestHeadMarker walks the conversation ancestry so forks resolve markers through each parent cap.
Sequences
Atomic mixed-table commit
sequenceDiagram
autonumber
participant S as SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`.
participant M as MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence.
participant T as Tables
S->>M: commit(writes)
M->>M: clone writes
M->>M: check immutable IDs
M->>T: apply conversation, entry, task, input writes
M->>M: advance nextId and nextSeq
M-->>S: seq
Fork-aware entry scan
sequenceDiagram
autonumber
participant S as SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`.
participant M as MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence.
participant T as Tables
S->>M: scanEntries(query, cursor, limit)
M->>T: newest-first walk of own entries
M->>T: descend to parent capped at parent.at
M-->>S: page with opaque cursor
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| ID space | One global number namespace starting at 2 with 1 reserved |
A single namespace lets one commit span tables without cross-table collisions. |
| Detachment | Deep clone on write and on read | Cloning matches serialization-backed ownership so conformance transfers to real backends. |
| Immutability enforcement | Reject duplicate conversation and entry IDs, reject cross-table ID reuse | The store guarantees IDs are never reused after a committed write. |
| Fork history | Ancestry walk capped at each parent.at |
Caps give deterministic newest-first visibility without copying parent entries. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. scope split | SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`., conversation-scoped, and task-scoped variants in one union | The union keeps history and fork policies exactly where they apply. |
Risks and Unknowns
- A future persistent backend may interpret cursor shape or commit ordering differently than
MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence.. - Prototype-safe cloning adds per-record cost that needs measuring once real workloads exist.
- DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. deltas persist in-package (
document_revisions,DocumentContentbase/delta); SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. commits exercise the full commit path.
Out of Scope
- HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. scheduling policies beyond the SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. mutation line (
src/session/,src/harness/). - Persistent storage backends beyond the in-package
SqliteStorage(src/storage/sqlite/, node and cloudflare adapters). - ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. document delta mechanics, covered by the ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. package.
- HTTPHypertext Transfer Protocol. endpoints and OpenAPI contracts.
Test Plan: Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences.
Scope
This plan covers the Pico record contracts and StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. behavior in packages/durable.
It is derived from the shared storage conformance suite (src/testing/storage-conformance.ts, registered for the memory, SQLite, and JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). backends), test/memory-storage.test.ts (retained-state case), and test/types.test.ts (three compile-time discriminator cases).
Out of scope are the SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. mutation line, the HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. agent loop, and ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. delta mechanics.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Root conversation reserves ID 1 and rejects duplicates | Mint ID, commit root, recommit root | First mint is 2, duplicate commit throws already belongs to conversation. |
| TC-2 | Mixed-table batch commits atomically and rolls back on failure | Entry, task, and input writes followed by a batch with a duplicate conversation ID | First batch visible with its sequence, failed batch throws, none of its writes visible, next commit gets initialSeq + 1. |
| TC-3 | Retained writes and returned records are detached | Mutated caller objects and mutated read results | Stored entry data, task checkpoint, and input detail keep original values. |
| TC-4 | Prototype-like JSON keys clone without changing prototypes | Entry data with __proto__, constructor, and toString keys |
Reads keep Object.prototype, keep own __proto__ data, and global prototype stays clean. |
| TC-5 | Out-of-order entry IDs index in sorted order | Entries 30, 10, and marker 20 committed together | Newest-first scan returns 30, 20, 10 and latest head marker is 20. |
| TC-6 | Entry cursor continues below its last item after a newer commit | Two-page newest-first scan with an append between pages | Second page returns only the oldest entry with no further cursor. |
| TC-7 | Conversations paginate ascending by opaque cursor | Root plus two conversations committed out of order | First page returns root and second with { after } cursor, second page returns third. |
| TC-8 | Deep fork history scans newest-first through every ancestor cap | Three-level fork with caps, exclusions, and head markers | Pages return grandchild, child-cap, and root entries in order with correct markers and commit sequences. |
| TC-9 | Task records replace fully and page through filtered scans | Three tasks with memo, background, and abort flags advanced to terminal | Latest record returned, pending pages split 1 plus 1, terminal and background filters match. |
| TC-10 | Request IDs index per conversation and input records replace fully | Same key in two conversations plus placed transition | Per-conversation lookup resolves, replacement visible by ID and by key. |
| TC-11 | Global ID namespace rejects cross-table reuse and exhausted minting | Explicit ID 100, cross-table task write, MAX_SAFE_INTEGER entry |
Cross-table write throws already belongs to entry, minting past the safe integer throws. |
| TC-12 | Closed storage rejects every operation | Commit and reads after close |
Commit, lookup, and mint all throw closed. |
| TC-13 | Type discriminators accept valid shapes and reject invalid ones | Omit, replace, pending, terminal, document, outcome, and input shapes | Valid shapes compile, twenty-nine invalid shapes each raise @ts-expect-error. |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-14 | Entry commit sequence ties reads to their commit | Root conversation exists | Each entry read carries the sequence of its creating commit. |
| TC-15 | Head-marker search resolves through fork ancestry | Three-level fork with markers at each level | Current and historical markers resolve, pre-history cutoff returns undefined. |
| TC-16 | Unknown conversations fail fast on history reads | No conversation with the queried ID | Entry scan and head-marker search throw Unknown conversation. |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-17 | Package check passes for sources and tests | Run the root check | No erasable-TypeScript or import-hygiene violations for the package. |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-18 | Same input written twice in one batch | Commit rejects the batch and persists nothing. |
| TC-19 | Task write reuses an entry ID | Commit throws already belongs to entry. |
| TC-20 | Cursor continuation after interleaved newer commit | Older page resumes strictly below the first page cursor. |
Test Infrastructure
- Vitest suite in
packages/durable/test/usingBACKGROUND_CONTEXTas the storage context. - The shared conformance suite runs every behavior case against each backend through its provider-constructed instance (
registerStorageConformance). - Type-level assertions use
expectTypeOfplus@ts-expect-errorfor the twenty-nine invalid shapes. - Targeted runs avoid the full suite (from
packages/durable):npx vitest --run test/memory-storage.test.ts.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FRFunctional Requirement.-1MustThe system shall model conversations as immutable records with an ID, an optional fork parent edge, and an optional task owner edge. | TC-8, TC-15, TC-16 |
| FRFunctional Requirement.-2MustThe system shall model entries as immutable transcript events with kind, optional model messages, optional JSON data, optional head marker, optional context edits, and optional producing task ID. | TC-5, TC-6, TC-8, TC-14 |
| FRFunctional Requirement.-3MustThe system shall model host inputs through the queued, placed, done, and unanswered lifecycle states with conversation-scoped request ID deduplication. | TC-10, TC-18 |
| FRFunctional Requirement.-4MustThe system shall model tasks as pending, running, and terminal states with completed, failed, aborted, orphaned, and faulted outcomes. | TC-9 |
| FRFunctional Requirement.-5MustThe system shall model document incarnations with session, conversation, and task scopes plus history and fork policies. | TC-13 |
| FRFunctional Requirement.-6MustThe system shall expose a `StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.` boundary with atomic commit, global ID minting, conversation lookup and scan, entry lookup with commit sequence, head-marker search, fork-aware entry scan, task lookup and filtered scan, input lookup by ID and request key, and close. | TC-2, TC-7, TC-9, TC-10, TC-14, TC-15, TC-16 |
| FRFunctional Requirement.-7MustThe system shall provide `MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence.` as a detached in-memory `StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it.` with atomic commits, sorted indexes, opaque cursors, fork-aware history scans, a single global ID namespace, and post-close rejection. | TC-1, TC-2, TC-3, TC-4, TC-5, TC-6, TC-7, TC-8, TC-11, TC-12, TC-20 |
| FRFunctional Requirement.-8MustThe system shall reserve `ROOT_CONVERSATION_ID` (`1`) for the root conversation and start minted IDs at `2`. | TC-1, TC-11 |
| FRFunctional Requirement.-9MustThe system shall enforce omit and replace context-edit discriminators so omissions carry no messages and replacements always carry messages. | TC-13 |
| FRFunctional Requirement.-10ShouldThe system shall expose pagination (`Page`, `Cursor`), scan filters (`EntryQuery`, `TaskQuery`), and the atomic `StorageWrite` table-mutation union. | TC-6, TC-7, TC-9 |
| NFRNon-Functional Requirement.-1MustCommits shall be atomic so a failed batch persists none of its writes. | TC-2 |
| NFRNon-Functional Requirement.-2MustStored and returned values shall be detached clones that never pollute object prototypes. | TC-3, TC-4 |
| NFRNon-Functional Requirement.-3MustThe package shall use erasable TypeScript with top-level imports only and no `any`. | TC-13, TC-17 |
| NFRNon-Functional Requirement.-4ShouldIn-memory reads and scans shall use sorted-index seeks rather than full-table sorts. | TC-5, TC-8 |
requirements
- Which serialization-backed store becomes the first persistent
StoragebeyondMemoryStorage? - Should document deltas ship inside this package or stay in the Chord package with usage docs only?
- Does the Session-level commit path need a published conformance suite shared by every backend?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. Composition Runtime
Overview
ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. is a standalone application-composition runtime that assembles applications from plugins whose facets declare, provide, and consume typed services with replicated state across local and remote boundaries.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Application host authors | Compose worker, TUITerminal User Interface (the interactive mode, and the `pi-tui` library)., and WebUI environments from one plugin model |
| Plugin authors | Declare services once and run each facet where it belongs |
| Agent developers | Build extensions without owning transport, framing, or lifecycle |
Functional Requirements
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-1MustThe system shall let plugins declare facets as synchronous setup units that state the services they provide and require. | Must | The system shall let plugins declare facets as synchronous setup units that state the services they provide and require. |
| FRFunctional Requirement.-2MustThe system shall validate the complete facet dependency graph and reject missing dependencies, duplicate providers, cycles, and asynchronous setup. | Must | The system shall validate the complete facet dependency graph and reject missing dependencies, duplicate providers, cycles, and asynchronous setup. |
| FRFunctional Requirement.-3MustThe system shall support singleton services with one provider behind a stable consumer-facing handle. | Must | The system shall support singleton services with one provider behind a stable consumer-facing handle. |
| FRFunctional Requirement.-4MustThe system shall support keyed services with dynamically spawned and retired per-key instances. | Must | The system shall support keyed services with dynamically spawned and retired per-key instances. |
| FRFunctional Requirement.-5MustThe system shall bind services after graph validation, activate providers before consumers, and dispose resources in reverse dependency order. | Must | The system shall bind services after graph validation, activate providers before consumers, and dispose resources in reverse dependency order. |
| FRFunctional Requirement.-6MustThe system shall provide replicated state where producers mutate a tracked state proxy and publish while consumers receive immutable values. | Must | The system shall provide replicated state where producers mutate a tracked state proxy and publish while consumers receive immutable values. |
| FRFunctional Requirement.-7MustThe system shall expose remotely consumable services through an application-supplied transport carrying strict-JSON calls and subscriptions. | Must | The system shall expose remotely consumable services through an application-supplied transport carrying strict-JSON calls and subscriptions. |
| FRFunctional Requirement.-8MustThe system shall track and coalesce JSON delta operations with durable base batches and validation of untrusted operations at apply time. | Must | The system shall track and coalesce JSON delta operations with durable base batches and validation of untrusted operations at apply time. |
| FRFunctional Requirement.-9ShouldThe system shall reload facets by replacing singletons without an unavailable interval and giving keyed replacements fresh generations. | Should | The system shall reload facets by replacing singletons without an unavailable interval and giving keyed replacements fresh generations. |
| FRFunctional Requirement.-10ShouldThe system shall load facet modules through a configured loader that shares one copy of each facet directory per load and re-imports fresh copies on reload. | Should | The system shall load facet modules through a configured loader that shares one copy of each facet directory per load and re-imports fresh copies on reload. |
| FRFunctional Requirement.-11ShouldThe system shall provide a Go-like context carrying cancellation and invocation-scoped values through operations. | Should | The system shall provide a Go-like context carrying cancellation and invocation-scoped values through operations. |
Non-Functional Requirements
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-1MustThe system shall ship as a standalone package with no dependency on any other PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. workspace package. | Must | Portability | The system shall ship as a standalone package with no dependency on any other PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. workspace package. |
| NFRNon-Functional Requirement.-2MustThe system shall validate every value crossing the remote boundary as strict JSON. | Must | Security | The system shall validate every value crossing the remote boundary as strict JSON. |
| NFRNon-Functional Requirement.-3ShouldThe system shall mark replicas unready on disconnect or replacement and rehydrate them before delivering new updates. | Should | Reliability | The system shall mark replicas unready on disconnect or replacement and rehydrate them before delivering new updates. |
| NFRNon-Functional Requirement.-4ShouldThe system shall flush at most one decoded operation batch per publication with independent path-codec state per client stream. | Should | Performance | The system shall flush at most one decoded operation batch per publication with independent path-codec state per client stream. |
Constraints
- ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. prescribes no transport, framing, routing, or application wire envelope.
- Process-local services accept unrestricted contracts and are never published remotely.
- ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. never installs dependencies and never runs package lifecycle scripts.
Acceptance Criteria
-
FRFunctional Requirement.-1MustThe system shall let plugins declare facets as synchronous setup units that state the services they provide and require.
gherkin @FRFunctional Requirement.-1MustThe system shall let plugins declare facets as synchronous setup units that state the services they provide and require. Scenario: facet declares its service shape synchronously Given a plugin facet with a synchronous setup function When the host collects provided and required services Then the facet shape is registered without running any async work -
FRFunctional Requirement.-2MustThe system shall validate the complete facet dependency graph and reject missing dependencies, duplicate providers, cycles, and asynchronous setup.
gherkin @FRFunctional Requirement.-2MustThe system shall validate the complete facet dependency graph and reject missing dependencies, duplicate providers, cycles, and asynchronous setup. Scenario: invalid dependency graphs are rejected before binding Given facets with a missing dependency, a duplicate provider, or a dependency cycle When the host validates the complete dependency graph Then activation fails with a descriptive error and no service is bound -
FRFunctional Requirement.-3MustThe system shall support singleton services with one provider behind a stable consumer-facing handle.
gherkin @FRFunctional Requirement.-3MustThe system shall support singleton services with one provider behind a stable consumer-facing handle. Scenario: singleton facade survives provider replacement Given a consumer holding a singleton service handle When the providing facet is replaced by a reload Then the same handle routes to the new provider without an unavailable interval -
FRFunctional Requirement.-4MustThe system shall support keyed services with dynamically spawned and retired per-key instances.
gherkin @FRFunctional Requirement.-4MustThe system shall support keyed services with dynamically spawned and retired per-key instances. Scenario: keyed instances spawn and retire independently Given a keyed service owned by one facet When the owner spawns two keys and retires one Then observers see both instances appear and only the retired key close -
FRFunctional Requirement.-5MustThe system shall bind services after graph validation, activate providers before consumers, and dispose resources in reverse dependency order.
gherkin @FRFunctional Requirement.-5MustThe system shall bind services after graph validation, activate providers before consumers, and dispose resources in reverse dependency order. Scenario: activation and disposal follow dependency order Given a provider facet and a consumer facet depending on it When the host activates the graph and later disposes it Then the provider activates first and disposes last -
FRFunctional Requirement.-6MustThe system shall provide replicated state where producers mutate a tracked state proxy and publish while consumers receive immutable values.
gherkin @FRFunctional Requirement.-6MustThe system shall provide replicated state where producers mutate a tracked state proxy and publish while consumers receive immutable values. Scenario: published mutations reach subscribers as immutable values Given a producer mutating its tracked state proxy When the producer publishes with a context Then each subscriber receives a complete immutable value reflecting the mutation -
FRFunctional Requirement.-7MustThe system shall expose remotely consumable services through an application-supplied transport carrying strict-JSON calls and subscriptions.
gherkin @FRFunctional Requirement.-7MustThe system shall expose remotely consumable services through an application-supplied transport carrying strict-JSON calls and subscriptions. Scenario: remote calls cross an application-supplied transport Given a remotely exposable service and a transport adapter When a consumer invokes a method and subscribes to its state Then arguments, results, snapshots, and updates all cross as strict JSON -
FRFunctional Requirement.-8MustThe system shall track and coalesce JSON delta operations with durable base batches and validation of untrusted operations at apply time.
gherkin @FRFunctional Requirement.-8MustThe system shall track and coalesce JSON delta operations with durable base batches and validation of untrusted operations at apply time. Scenario: deltas coalesce and untrusted ops are validated Given tracked plain JSON with buffered mutations When the tracker flushes and a replica applies the batch Then the replica converges and malformed operations are rejected -
FRFunctional Requirement.-9ShouldThe system shall reload facets by replacing singletons without an unavailable interval and giving keyed replacements fresh generations.
gherkin @FRFunctional Requirement.-9ShouldThe system shall reload facets by replacing singletons without an unavailable interval and giving keyed replacements fresh generations. Scenario: reload keeps singleton consumers connected Given active singleton consumers on a running host When a candidate generation activates and cuts over successfully Then singleton handles stay connected while keyed replacements get fresh generations -
FRFunctional Requirement.-10ShouldThe system shall load facet modules through a configured loader that shares one copy of each facet directory per load and re-imports fresh copies on reload.
gherkin @FRFunctional Requirement.-10ShouldThe system shall load facet modules through a configured loader that shares one copy of each facet directory per load and re-imports fresh copies on reload. Scenario: loader shares one copy per load and reloads fresh copies Given facet modules loaded through the Node loader When facets import from each other's directories and the host reloads Then one load shares one copy of shared modules, reload imports fresh copies, and modules without a facet default export are rejected -
FRFunctional Requirement.-11ShouldThe system shall provide a Go-like context carrying cancellation and invocation-scoped values through operations.
gherkin @FRFunctional Requirement.-11ShouldThe system shall provide a Go-like context carrying cancellation and invocation-scoped values through operations. Scenario: cancellation and values flow through context Given an operation invoked with a cancellable context carrying a typed value When the caller cancels or the callee reads the value Then waiting stops promptly and the callee observes the carried value -
NFRNon-Functional Requirement.-1MustThe system shall ship as a standalone package with no dependency on any other PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. workspace package.
gherkin @NFRNon-Functional Requirement.-1MustThe system shall ship as a standalone package with no dependency on any other PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. workspace package. Scenario: package boundary stays PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries.-free Given the ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. package source tree When the boundary test scans its imports and file references Then no import reaches any other PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. workspace package or file outside ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. -
NFRNon-Functional Requirement.-2MustThe system shall validate every value crossing the remote boundary as strict JSON.
gherkin @NFRNon-Functional Requirement.-2MustThe system shall validate every value crossing the remote boundary as strict JSON. Scenario: non-JSON values are rejected at the boundary Given a candidate value containing undefined, functions, or other non-JSON data When the adapter validates it with the strict-JSON check Then the value is rejected without normalization -
NFRNon-Functional Requirement.-3ShouldThe system shall mark replicas unready on disconnect or replacement and rehydrate them before delivering new updates.
gherkin @NFRNon-Functional Requirement.-3ShouldThe system shall mark replicas unready on disconnect or replacement and rehydrate them before delivering new updates. Scenario: disconnected replicas rehydrate before updating Given a subscribed replica whose provider disconnects When the provider returns and publishes new state Then the replica reports unready until rehydration completes -
NFRNon-Functional Requirement.-4ShouldThe system shall flush at most one decoded operation batch per publication with independent path-codec state per client stream.
gherkin @NFRNon-Functional Requirement.-4ShouldThe system shall flush at most one decoded operation batch per publication with independent path-codec state per client stream. Scenario: one publication produces one batch per stream Given a producer with two remote client streams on one state When the producer publishes once Then each stream encodes exactly one operation batch with its own path-codec state
Conflicts
None identified yet.
Open Questions
- Should symmetric RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). peers ship as the first optional transport over the remote-service boundary?
- Should the reserved
$chord.*service namespace become a permanent part of the ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. contract? - Do delta batches need a canonical or minimal form beyond the current convergence guarantee?
Specification: ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. Composition Runtime
Overview
The runtime models each plugin as synchronous facet setup functions over a typed service graph, resolves that graph in a facet kernel, and replicates tracked JSON state to local and remote subscribers through a transport-independent wire grammar.
Architecture
flowchart LR
subgraph Plugin
F1[FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. A]
F2[FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. B]
end
K[FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. Kernel]
P[ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.]
S[Replicated State]
T[Remote Transport Adapter]
F1 --> K
F2 --> K
K --> P
P --> S
P --> T
T --> C[Remote Consumer]
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes.
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | string | PK, not null | Stable identity of one facet within its plugin |
| setup | function | synchronous, not null | Declares provided and required services against the facet environment |
ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`.
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | string | PK, not null, $chord.* reserved |
Stable identity of one shared TypeScript service contract |
| local | boolean | not null, defaults false | Marks process-local contracts that are never published remotely |
| mode | singleton or keyed | not null | Selects one provider versus dynamic per-key instances |
Replicated State
| Field | Type | Constraints | Description |
|---|---|---|---|
| state | tracked proxy | producer-only writes | Mutable view that records operations for the next publication |
| value | immutable snapshot or undefined | consumer-visible | Latest hydrated value, never mutated by later updates |
| sequence | number | monotonically increasing | Orders hydrate and update deliveries per subscription |
ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Subscription Snapshot
| Field | Type | Constraints | Description |
|---|---|---|---|
| serviceId | string | not null | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. the snapshot describes |
| mode | singleton or keyed | not null | ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. mode the snapshot was taken under |
| instances | array | possibly empty | Per-instance member lists with state sequences and operation batches |
API Contracts
There is no HTTPHypertext Transfer Protocol. surface in this feature, so no api.yaml exists. The normative contract is the TypeScript surface exported from the package root plus the context, delta, and node entry points.
Sequences
Plugin bind, activate, publish, replicate
sequenceDiagram
autonumber
participant F as FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes.
participant K as FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. Kernel
participant P as ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.
participant C as Consumer
F->>K: setup(env): provide and require services
K->>K: validate dependency graph
K->>P: bind stable service handles
K->>F: onActivate in dependency order
F->>P: mutate tracked state and publish(context)
P->>P: flush one operation batch
P->>C: hydrate or update with immutable value
C-->>P: subscribe for further updates
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Package coupling | Standalone with zero PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. workspace dependencies | Lets unrelated applications adopt ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. without the PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. monorepo |
| Remote boundary | Transport-independent wire grammar with application-supplied adapters | Keeps ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. neutral on framing, routing, and envelopes while enforcing strict JSON |
| State replication | Proxy-tracked mutations with per-stream path codecs | Preserves string and array operations compactly while isolating client streams |
| Module loading | Node loader importing facet modules with a reload query hook | Shares one copy of each facet directory per load and re-imports fresh copies on reload, without isolation or eviction |
| Context model | Explicit Go-like context parameter on operations | Carries cancellation and scoped values without ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. depending on either domain |
Risks and Unknowns
- Symmetric RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). peers are planned but not yet specified as the reference transport implementation.
- DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. batches guarantee convergence without a canonical or minimal form, which may surprise bandwidth-sensitive adapters.
- The
$chord.*service-ID reservation is enforced in code but its long-term namespace policy is undecided.
Out of Scope
- Any concrete transport, framing, routing, or envelope implementation.
- A canonical or minimal delta-batch encoding.
- PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries.-specific hosts, TUIs, or agent workers built on top of ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links..
Test Plan: ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. Composition Runtime
Scope
The suite exercises facets, services, replicated state, delta tracking, the remote-service wire boundary, facet loading and reload, context, and strict-JSON validation. The suite covers thirty test files under packages/chord/test with roughly four hundred individual cases. Out of scope is any real transport, PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. host integration, and performance benchmarking beyond the delta traversal bench.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. tracker records intent, root ops, and whole-value replacement | Mutations through the tracked proxy | Correct operation batches with a complete base batch on first flush |
| TC-2 | Immutable apply preserves prior revisions while converging replicas | Operation batches against a base value | New revision equals the producer value and old revisions are unchanged |
| TC-3 | Unsafe array indices, malformed ops, and boundary escapes are rejected | Hostile or out-of-range operations | Descriptive apply-time errors with no state corruption |
| TC-4 | Path codec interns paths and property tests round-trip random ops | Random tracked mutations | Decoded batches match the producer value on every seed |
| TC-5 | DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. payloads are deeply detached from producer mutations | Shared and subsequently edited producer objects | Published snapshots stay independent of later producer edits |
| TC-6 | Tracker proxies survive garbage-collection pressure | Mutations interleaved with GC jobs | No lost operations and no retained-worker failures |
| TC-7 | Singleton provide, consume, replacement, and disposal behave stably | FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. graphs with singleton providers | Stable facades, buffered-update replay, and facade cleanup on disposal |
| TC-8 | Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. hydrates, buffers racing updates, and survives rebinds | Publish, rebind, and hydration races | Cold replicas hydrate and buffered updates arrive exactly once |
| TC-16 | Context layers values and propagates cancellation | Nested contexts with typed keys | Child isolation, parent inheritance, and prompt cancellation |
| TC-17 | Strict-JSON validation accepts JSON and rejects the rest | JSON and non-JSON candidate values | True for strict JSON and false otherwise with no normalization |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-9 | FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. host validates graphs and orders activation and disposal | Facets with chained dependencies | Providers activate before consumers and dispose in reverse order |
| TC-10 | Keyed services route through the host and stay local when marked local | Keyed providers with local and remote contracts | Remote keyed calls route through the provider while local ones never leave the process |
| TC-11 | Loaders combine in order and dispose generations in reverse | Multiple facet loaders with resources | Load-order facets and reverse-order disposal with cleanup on partial failure |
| TC-12 | Wire grammar encodes control calls and isolates per-state codecs | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. catalogue, subscribe, and unsubscribe calls | Valid calls encode and malformed snapshots or updates are rejected |
| TC-13 | Remote endpoints publish provider subscriptions and clean them up | A provider endpoint with active subscriptions | Updates publish while subscribed and resources release on close |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-14 | Package boundary keeps ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. free of PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. dependencies | Run the boundary test over the ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. tree | No import reaches another PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. workspace package or outside file |
| TC-15 | FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. modules load, share one copy per load, and reload fresh copies | Load facet fixtures through the Node loader in a child process | Shared directory imports resolve to one copy, reload re-imports, and invalid default exports are rejected |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-9E | Missing dependencies, cycles, duplicate providers, async setup | Host rejects the graph before binding any service |
| TC-11E | Replacement activation or post-cutover cleanup fails | Old generation stays active or the host terminates deterministically |
| TC-15E | Missing loader or invalid facet module | Load without a configured loader, or a module without a facet default export |
Test Infrastructure
- Vitest runs the suite from packages/chord with a loopback service transport helper.
- A dedicated retention worker exercises tracker proxies under garbage-collection pressure.
- FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. loader fixtures run in a child process through the Node loader with its reload query hook.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FRFunctional Requirement.-1MustThe system shall let plugins declare facets as synchronous setup units that state the services they provide and require. | TC-9, TC-11 |
| FRFunctional Requirement.-2MustThe system shall validate the complete facet dependency graph and reject missing dependencies, duplicate providers, cycles, and asynchronous setup. | TC-9, TC-9E |
| FRFunctional Requirement.-3MustThe system shall support singleton services with one provider behind a stable consumer-facing handle. | TC-7 |
| FRFunctional Requirement.-4MustThe system shall support keyed services with dynamically spawned and retired per-key instances. | TC-10 |
| FRFunctional Requirement.-5MustThe system shall bind services after graph validation, activate providers before consumers, and dispose resources in reverse dependency order. | TC-9 |
| FRFunctional Requirement.-6MustThe system shall provide replicated state where producers mutate a tracked state proxy and publish while consumers receive immutable values. | TC-7, TC-8 |
| FRFunctional Requirement.-7MustThe system shall expose remotely consumable services through an application-supplied transport carrying strict-JSON calls and subscriptions. | TC-12, TC-13 |
| FRFunctional Requirement.-8MustThe system shall track and coalesce JSON delta operations with durable base batches and validation of untrusted operations at apply time. | TC-1, TC-2, TC-3, TC-4, TC-5, TC-6 |
| FRFunctional Requirement.-9ShouldThe system shall reload facets by replacing singletons without an unavailable interval and giving keyed replacements fresh generations. | TC-11, TC-11E |
| FRFunctional Requirement.-10ShouldThe system shall load facet modules through a configured loader that shares one copy of each facet directory per load and re-imports fresh copies on reload. | TC-15, TC-15E |
| FRFunctional Requirement.-11ShouldThe system shall provide a Go-like context carrying cancellation and invocation-scoped values through operations. | TC-16 |
| NFRNon-Functional Requirement.-1MustThe system shall ship as a standalone package with no dependency on any other PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. workspace package. | TC-14 |
| NFRNon-Functional Requirement.-2MustThe system shall validate every value crossing the remote boundary as strict JSON. | TC-12, TC-17 |
| NFRNon-Functional Requirement.-3ShouldThe system shall mark replicas unready on disconnect or replacement and rehydrate them before delivering new updates. | TC-8 |
| NFRNon-Functional Requirement.-4ShouldThe system shall flush at most one decoded operation batch per publication with independent path-codec state per client stream. | TC-4, TC-8 |
requirements
- Should symmetric RPC peers ship as the first optional transport over the remote-service boundary?
- Should the reserved
$chord.*service namespace become a permanent part of the Chord contract? - Do delta batches need a canonical or minimal form beyond the current convergence guarantee?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Telemetry Contracts
Overview
The pi-telemetry package defines vendor-neutral telemetry contracts for explicit callback-managed spans. TelemetryContext exposes startSpan for creating child spans around callbacks. TelemetrySpan exposes addEvent and setAttributes and setStatus for recording diagnostics. Typed schema utilities define serializable span and event and attribute vocabularies with inferred TypeScript types. Noop and in-memory backends provide passive defaults and process-local reference recording without exporters.
Stakeholders
| Stakeholder | Interest |
|---|---|
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. package maintainer | Needs explicit telemetry propagation without global state. |
| Backend adapter author | Needs a stable contract with observable conformance semantics. |
| Application operator | Needs diagnostic spans without business behavior changes. |
Functional Requirements
| ID | Priority | Requirement |
|---|---|---|
| FRFunctional Requirement.-1MustThe system shall provide TelemetryContext with startSpan that admits the callback synchronously exactly once. | Must | The system shall provide TelemetryContext with startSpan that admits the callback synchronously exactly once. |
| FRFunctional Requirement.-2MustThe system shall provide TelemetrySpan with setAttributes that merges attribute bags with last-defined-wins semantics. | Must | The system shall provide TelemetrySpan with setAttributes that merges attribute bags with last-defined-wins semantics. |
| FRFunctional Requirement.-3MustThe system shall provide TelemetrySpan with addEvent that records ordered named events with attributes. | Must | The system shall provide TelemetrySpan with addEvent that records ordered named events with attributes. |
| FRFunctional Requirement.-4MustThe system shall provide TelemetrySpan with setStatus that records explicit ok or error outcomes with last-write-wins semantics. | Must | The system shall provide TelemetrySpan with setStatus that records explicit ok or error outcomes with last-write-wins semantics. |
| FRFunctional Requirement.-5MustThe system shall treat normal completion as ok and throws or rejections as errors unless an explicit status was set. | Must | The system shall treat normal completion as ok and throws or rejections as errors unless an explicit status was set. |
| FRFunctional Requirement.-6MustThe system shall provide a shared noop context that invokes callbacks without inspecting or retaining payloads. | Must | The system shall provide a shared noop context that invokes callbacks without inspecting or retaining payloads. |
| FRFunctional Requirement.-7MustThe system shall provide an in-memory context that records detached span snapshots in span-start order. | Must | The system shall provide an in-memory context that records detached span snapshots in span-start order. |
| FRFunctional Requirement.-8MustThe system shall provide serializable schema helpers that infer exact start and end and event attribute types. | Must | The system shall provide serializable schema helpers that infer exact start and end and event attribute types. |
| FRFunctional Requirement.-9MustThe system shall provide a typed span starter that binds a parent context to one or more schema vocabularies. | Must | The system shall provide a typed span starter that binds a parent context to one or more schema vocabularies. |
Non-Functional Requirements
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFRNon-Functional Requirement.-1MustThe system shall keep recording methods synchronous and passive and non-throwing. | Must | Reliability | The system shall keep recording methods synchronous and passive and non-throwing. |
| NFRNon-Functional Requirement.-2MustThe system shall remain runtime-neutral without ambient context APIs. | Must | Portability | The system shall remain runtime-neutral without ambient context APIs. |
| NFRNon-Functional Requirement.-3ShouldThe system shall keep noop overhead negligible by sharing one frozen inert span. | Should | Performance | The system shall keep noop overhead negligible by sharing one frozen inert span. |
| NFRNon-Functional Requirement.-4MustThe system shall restrict attribute values to primitive scalars and arrays and avoid sensitive payloads by default. | Must | Security | The system shall restrict attribute values to primitive scalars and arrays and avoid sensitive payloads by default. |
Constraints
- The package shall not include exporters or global current-span state.
- Backend-specific identifiers and buffering and flushing belong to adapters.
- Schema objects shall remain JSON-serializable data without runtime validation.
Acceptance Criteria
Every FRFunctional Requirement. and NFRNon-Functional Requirement. has at least one executable criterion below.
-
FRFunctional Requirement.-1MustThe system shall provide TelemetryContext with startSpan that admits the callback synchronously exactly once.
gherkin @FRFunctional Requirement.-1MustThe system shall provide TelemetryContext with startSpan that admits the callback synchronously exactly once. Scenario: synchronous single admission preserves result Given a fresh TelemetryContext When startSpan is called with a callback returning a value Then the callback runs synchronously exactly once and the returned promise resolves with the same value -
FRFunctional Requirement.-2MustThe system shall provide TelemetrySpan with setAttributes that merges attribute bags with last-defined-wins semantics.
gherkin @FRFunctional Requirement.-2MustThe system shall provide TelemetrySpan with setAttributes that merges attribute bags with last-defined-wins semantics. Scenario: attribute merging keeps last defined values Given a span with start attributes When setAttributes is called repeatedly with overlapping keys Then later defined values replace earlier values and undefined entries are ignored -
FRFunctional Requirement.-3MustThe system shall provide TelemetrySpan with addEvent that records ordered named events with attributes.
gherkin @FRFunctional Requirement.-3MustThe system shall provide TelemetrySpan with addEvent that records ordered named events with attributes. Scenario: events are recorded in call order Given an open span When addEvent is called twice with distinct names Then the snapshot contains both events in call order with their attributes -
FRFunctional Requirement.-4MustThe system shall provide TelemetrySpan with setStatus that records explicit ok or error outcomes with last-write-wins semantics.
gherkin @FRFunctional Requirement.-4MustThe system shall provide TelemetrySpan with setStatus that records explicit ok or error outcomes with last-write-wins semantics. Scenario: explicit status uses last-write-wins semantics Given an open span When setStatus is called with error and then with ok Then the final snapshot status is ok -
FRFunctional Requirement.-5MustThe system shall treat normal completion as ok and throws or rejections as errors unless an explicit status was set.
gherkin @FRFunctional Requirement.-5MustThe system shall treat normal completion as ok and throws or rejections as errors unless an explicit status was set. Scenario: throw without explicit status becomes error Given a fresh TelemetryContext When the callback throws synchronously without setting a status Then the returned promise rejects with the identical value and the span status is error -
FRFunctional Requirement.-6MustThe system shall provide a shared noop context that invokes callbacks without inspecting or retaining payloads.
gherkin @FRFunctional Requirement.-6MustThe system shall provide a shared noop context that invokes callbacks without inspecting or retaining payloads. Scenario: noop context stays inert Given the shared noop context When startSpan runs nested callbacks that record attributes and events Then values pass through unchanged and nested spans reuse the same frozen span -
FRFunctional Requirement.-7MustThe system shall provide an in-memory context that records detached span snapshots in span-start order.
gherkin @FRFunctional Requirement.-7MustThe system shall provide an in-memory context that records detached span snapshots in span-start order. Scenario: in-memory context returns detached snapshots Given an in-memory context with one completed span When getSpans is called and the caller mutates the result Then a subsequent getSpans call still returns the original recorded values -
FRFunctional Requirement.-8MustThe system shall provide serializable schema helpers that infer exact start and end and event attribute types.
gherkin @FRFunctional Requirement.-8MustThe system shall provide serializable schema helpers that infer exact start and end and event attribute types. Scenario: schema helper infers exact attribute types Given a serializable schema with closed string sets When TypeScript infers start attributes for a declared span Then missing required attributes and unknown keys and out-of-set values are rejected at compile time -
FRFunctional Requirement.-9MustThe system shall provide a typed span starter that binds a parent context to one or more schema vocabularies.
gherkin @FRFunctional Requirement.-9MustThe system shall provide a typed span starter that binds a parent context to one or more schema vocabularies. Scenario: typed starter binds children to their parent span Given a typed starter over operation and request schemas When an operation span starts a nested request span Then the recorded child carries the parent identifier and the callback result passes through -
NFRNon-Functional Requirement.-1MustThe system shall keep recording methods synchronous and passive and non-throwing.
gherkin @NFRNon-Functional Requirement.-1MustThe system shall keep recording methods synchronous and passive and non-throwing. Scenario: unreadable payloads never break business work Given recording payloads that throw on property reads When setAttributes and addEvent and setStatus are called with those payloads Then no call throws and the business callback still executes exactly once -
NFRNon-Functional Requirement.-2MustThe system shall remain runtime-neutral without ambient context APIs.
gherkin @NFRNon-Functional Requirement.-2MustThe system shall remain runtime-neutral without ambient context APIs. Scenario: explicit propagation works without ambient state Given parent spans passed only as context arguments When nested and concurrent children run Then parentage is recorded correctly without ambient context APIs -
NFRNon-Functional Requirement.-3ShouldThe system shall keep noop overhead negligible by sharing one frozen inert span.
gherkin @NFRNon-Functional Requirement.-3ShouldThe system shall keep noop overhead negligible by sharing one frozen inert span. Scenario: noop path performs no recording work Given the shared noop context When many spans run with attributes and events Then callbacks execute directly against one shared frozen span -
NFRNon-Functional Requirement.-4MustThe system shall restrict attribute values to primitive scalars and arrays and avoid sensitive payloads by default.
gherkin @NFRNon-Functional Requirement.-4MustThe system shall restrict attribute values to primitive scalars and arrays and avoid sensitive payloads by default. Scenario: attribute surface stays primitive-only Given the AttributeValue type definition When a schema declares attribute types Then only scalar and array primitives are expressible without payload fields
Conflicts
No conflicts were identified.
Open Questions
No open questions remain because the contracts are implemented and documented.
Specification: Telemetry Contracts
Overview
The package implements explicit callback-managed telemetry with generic adapter semantics. Schemas act as compile-time vocabularies while adapters translate generic calls to backend concepts at runtime. Reference backends cover disabled telemetry and process-local capture without exporters.
Architecture
Adapter implementations bridge one generic surface to many backends while pi code always passes parents explicitly. The typed starter binds a parent context to schema vocabularies without retaining schemas at runtime.
flowchart LR
App --> Ctx[TelemetryContext]
Ctx --> Span[TelemetrySpan]
Span --> Noop[Noop backend]
Span --> Mem[In-memory backend]
Span --> Adapters[External adapters]
Schemas[Typed schemas] --> Starter[Typed starter]
Starter --> Ctx
Data ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider.
SpanOptions
| Field | Type | Constraints | Description |
|---|---|---|---|
| name | string | required | Open span name |
| attributes | SpanAttributes | optional | Open start attribute bag |
SpanAttributes and AttributeValue
AttributeValue supports string and number and boolean scalars plus readonly arrays of each scalar. SpanAttributes maps names to values where undefined entries are ignored. Merging copies values so later reads cannot mutate recorded state through aliases.
SpanStatus
| Variant | Fields | Description |
|---|---|---|
| ok | none | Normal completion marker |
| error | optional name and message | Failure marker with optional error details |
Automatic settlement uses ok for normal returns and error for throws or rejections. Explicit setStatus calls override automatic settlement with last-write-wins semantics.
RecordedTelemetrySpan
| Field | Type | Description |
|---|---|---|
| id | number | Deterministic span identifier |
| parentId | number or null | Parent identifier with null for roots |
| name | string | Recorded span name |
| attributes | SpanAttributes | Merged attribute bag |
| events | array of RecordedTelemetryEvent | Ordered event list |
| status | SpanStatus | Final outcome |
| settled | boolean | Settlement marker |
| endSequence | number or undefined | Deterministic end ordering assigned at settlement |
Snapshots are detached copies returned in span-start order without timestamps.
RecordedTelemetryEvent
| Field | Type | Description |
|---|---|---|
| name | string | Event name |
| attributes | SpanAttributes | Event attribute bag |
TelemetrySchemaDefinition
| Field | Type | Description |
|---|---|---|
| version | number | Schema version marker |
| spans | record of TelemetrySpanDefinition | Declared span vocabulary |
Schemas are ordinary JSON-serializable data with no runtime validation behavior.
TelemetrySpanDefinition
| Field | Type | Description |
|---|---|---|
| description | string | Span purpose |
| parents | TelemetryParentDefinition | Descriptive parent rule |
| startAttributes | record of definitions | Attributes normally known at span creation |
| endAttributes | record of definitions | Optional completion enrichment recorded later |
| events | optional record of TelemetryEventDefinition | Declared event vocabulary |
| status | default plus errorWhen | Documented outcome rule |
Start and end attributes share one backend attribute bag despite their separate declaration timing.
TelemetryAttributeDefinition
Supported types are string and number and boolean plus string arrays and number arrays and boolean arrays. Scalar definitions accept closed value sets while array definitions accept closed element value sets. Metadata covers description and examples and sensitivity and cardinality markers. Start and event attribute definitions add a required flag while end attributes stay optional.
TelemetryEventDefinition
| Field | Type | Description |
|---|---|---|
| description | string | Event purpose |
| attributes | record of definitions | Declared event attribute vocabulary |
TelemetryParentDefinition
| Kind | Meaning |
|---|---|
| any | Root span or any caller span |
| root_or_external | Root span or caller-owned span outside the schema |
| spans | Only the listed schema spans |
Parent metadata is descriptive and is not enforced at runtime.
API Contracts
No HTTPHypertext Transfer Protocol. API exists because the package exposes TypeScript interfaces only. Normative types live beside the reference backends in the telemetry source tree.
| Export | Purpose |
|---|---|
| TelemetryContext | Starts callback-managed child spans |
| TelemetrySpan | Records attributes and events and status while acting as a child context |
| NOOP_TELEMETRY_CONTEXT | Shared passive context for disabled telemetry |
| InMemoryTelemetryContext | Reference adapter with process-local recording |
| defineTelemetrySchema | Typed identity helper for serializable schema data |
| createTypedSpanStarter | Binds a parent context to one or more schema vocabularies |
Sequences
Callback span lifecycle
sequenceDiagram
autonumber
participant App as App
participant Ctx as Context
participant Span as Span
App->>Ctx: startSpan(options, callback)
Ctx->>Span: create child span
App->>Span: addEvent and setAttributes
App->>Span: setStatus optional
Ctx->>Span: settle on callback resolve or reject
Ctx-->>App: promise of callback result
The startSpan call creates a child span and invokes the callback synchronously exactly once. The call keeps the span open until a returned promise settles. Recording calls merge into the span while the callback is active. Settlement applies automatic status only when no explicit status was recorded. Calls made after settlement are inert and never throw.
Typed nested spans
The typed starter resolves a span name to its owning schema at compile time. Its callback receives a schema-scoped span plus a child starter bound to the callback span. Nested starter calls therefore record correct parentage without ambient state.
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Propagation model | Explicit parent contexts | Explicit propagation avoids ambient state and stays portable across runtimes. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). shape | Vendor-neutral callback API | A neutral API lets adapters target tracing or logging backends without changing call sites. |
| Schema role | Schema-first compile-time vocabularies | Compile-time checks keep emitted names consistent without runtime validation costs. |
| Settlement ownership | startSpan owns settlement | Single ownership keeps spans open across async work and makes post-settlement calls inert. |
| Failure handling | Passive non-throwing recording | Passive recording keeps diagnostics from changing business outcomes. |
Risks and Unknowns
- Unbounded in-memory storage can grow without limit in long-lived recording scopes.
- Sensitive attributes rely on schema authors and data policies rather than runtime redaction.
- Backend translation quality depends on adapter authors applying the conformance suite correctly.
Out of Scope
- Exporters and sampling and flushing remain adapter responsibilities.
- No OpenAPI contract exists because the surface is a TypeScript module rather than an HTTPHypertext Transfer Protocol. service.
- Durable persistence of contexts or spans is excluded from this package.
Test Plan: Telemetry Contracts
Scope
This plan covers unit behavior in telemetry.test.ts and adapter conformance in conformance.test.ts. Package-level behavior is verified with vitest from the telemetry package directory. External backend exporters remain out of scope for this plan.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Schema definition preserves identity and infers exact attributes | Serializable definition with closed string sets | Same object reference with JSON round-trip and exact kind union |
| TC-2 | Combined vocabularies bind child starters and preserve parentage | Operation and request schemas with nested typed starter calls | Child span records parent identifier and result value passes through |
| TC-3 | Noop context admits callbacks synchronously with one frozen span | Named span with nested child callback | Synchronous admission with identical child span and frozen parent span |
| TC-4 | Noop and typed starters preserve rejection identity | Callbacks that throw synchronously or reject asynchronously | Promises rejected with the identical thrown or rejected value |
| TC-5 | Recording ignores unreadable payloads without throwing | Proxy payloads that throw on property reads | Business callback still runs exactly once without exceptions |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-6 | Conformance callback lifecycle preserves results and errors | Fresh in-memory context per case | Single synchronous admission with ok status and identical rejection values |
| TC-7 | Conformance status keeps last explicit write | Spans with explicit ok or error before return or throw | Final status matches the last explicit write without automatic overwrite |
| TC-8 | Conformance recording merges attributes and orders events | Start attributes plus repeated setAttributes and two events | Merged bag with last-defined wins and ordered event list |
| TC-9 | Conformance atomicity ignores failed recording calls | Attributes containing unreadable values | Prior attributes retained with no partial merge and no throw |
| TC-10 | Conformance settlement makes late calls inert | Captured span used after its callback returned | Late mutations ignored while late child span still executes normally |
| TC-11 | Conformance parentage tracks nested and concurrent children | Overlapping first and second child spans under one parent | Correct parent identifiers with ordered end sequences |
| TC-12 | Conformance passivity suppresses backend payload failures | Unreadable span options and recording payloads | Business callbacks execute once with empty or retained snapshots |
| TC-13 | Snapshot isolation detaches recorded state | Open span observed mid-callback plus later external mutation | Open snapshot unsettled without end sequence and later reads unaffected by mutation |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-14 | Package-level span flow exercises start through settlement | Start span then add event then set attributes then set status then resolve | Settled snapshot contains merged attributes and ordered events and final status |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-15 | Synchronous throw inside callback | Span settles as error and promise rejects with identical value |
| TC-16 | Asynchronous rejection inside callback | Span settles as error and rejection value is preserved |
| TC-17 | Explicit ok status before a throw | Explicit status survives without automatic overwrite |
| TC-18 | Child started from settled parent | Call degrades to noop semantics while still executing the callback |
| TC-19 | Undefined attribute values in merges | Undefined entries are ignored without removing prior values |
Test Infrastructure
- Vitest runs the telemetry package suite from the package directory.
- In-memory contexts isolate each test without shared global state.
- Proxy-based unreadable payloads verify passive non-throwing behavior.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FRFunctional Requirement.-1MustThe system shall provide TelemetryContext with startSpan that admits the callback synchronously exactly once. | TC-3, TC-4, TC-6 |
| FRFunctional Requirement.-2MustThe system shall provide TelemetrySpan with setAttributes that merges attribute bags with last-defined-wins semantics. | TC-8, TC-9, TC-19 |
| FRFunctional Requirement.-3MustThe system shall provide TelemetrySpan with addEvent that records ordered named events with attributes. | TC-8, TC-13 |
| FRFunctional Requirement.-4MustThe system shall provide TelemetrySpan with setStatus that records explicit ok or error outcomes with last-write-wins semantics. | TC-7, TC-14, TC-17 |
| FRFunctional Requirement.-5MustThe system shall treat normal completion as ok and throws or rejections as errors unless an explicit status was set. | TC-4, TC-6, TC-15, TC-16 |
| FRFunctional Requirement.-6MustThe system shall provide a shared noop context that invokes callbacks without inspecting or retaining payloads. | TC-3, TC-4, TC-5 |
| FRFunctional Requirement.-7MustThe system shall provide an in-memory context that records detached span snapshots in span-start order. | TC-11, TC-12, TC-13, TC-18 |
| FRFunctional Requirement.-8MustThe system shall provide serializable schema helpers that infer exact start and end and event attribute types. | TC-1, TC-2 |
| FRFunctional Requirement.-9MustThe system shall provide a typed span starter that binds a parent context to one or more schema vocabularies. | TC-2, TC-11 |
| NFRNon-Functional Requirement.-1MustThe system shall keep recording methods synchronous and passive and non-throwing. | TC-5, TC-9, TC-12 |
| NFRNon-Functional Requirement.-2MustThe system shall remain runtime-neutral without ambient context APIs. | TC-2, TC-6 |
| NFRNon-Functional Requirement.-3ShouldThe system shall keep noop overhead negligible by sharing one frozen inert span. | TC-3 |
| NFRNon-Functional Requirement.-4MustThe system shall restrict attribute values to primitive scalars and arrays and avoid sensitive payloads by default. | TC-5, TC-8 |
requirements
No open questions remain because the contracts are implemented and documented.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. | The coding agent's session object (packages/coding-agent/src/core/agent-session.ts): it owns the pi-agent-core Agent, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). modes consume. |
| AgentSessionRuntimeThe wrapper around `AgentSession` (`src/core/agent-session-runtime.ts`) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. | The wrapper around AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (src/core/agent-session-runtime.ts) that holds the session services, the model fallback message, and the factory that rebuilds a runtime after a session switch. |
| Branch summaryA `branch_summary` session entry (`src/core/compaction/branch-summarization.ts`) holding a summary of an abandoned branch, attached when `/tree` navigation leaves that branch. | A branch_summary session entry (src/core/compaction/branch-summarization.ts) holding a summary of an abandoned branch, attached when /tree navigation leaves that branch. |
| BranchingTree-structured session forking (`/fork`, `/clone`, `/tree`) where each JSONL entry carries `id` and `parentId` (`src/core/session-manager.ts`). | Tree-structured session forking (/fork, /clone, /tree) where each JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entry carries id and parentId (src/core/session-manager.ts). |
| ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links. | The typed host runtime in packages/chord: facets declare the contract tokens they consume (uses) and serve typed contracts (remote or local), and state travels between hosts as replicated state over links. |
| CodemodeThe model-facing `codemode` tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. | The model-facing codemode tool (a coding-agent built-in extension, inactive by default) that runs model-written JavaScript in a QuickJS sandbox whose only capability is calling injected tools. |
| CompactionLossy summarization of older session messages to reclaim context; the original JSONL entries stay on disk and the `compaction` entry records the summary and the first kept entry. | Lossy summarization of older session messages to reclaim context; the original JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). entries stay on disk and the compaction entry records the summary and the first kept entry. |
| Context editA `context_edit` session entry (`src/core/session-manager.ts`) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. | A context_edit session entry (src/core/session-manager.ts) that appends a replacement for, or an omission of, an earlier entry's model-visible content without rewriting history. |
| ContractA chord type definition (`remote(name, def)` or `local(name, def)` in `packages/chord/src/contract.ts`) with TypeBox input and output schemas, a fingerprint, and a placement rule (`hostNamed` or `hostFamily`). | A chord type definition (remote(name, def) or local(name, def) in packages/chord/src/contract.ts) with TypeBox input and output schemas, a fingerprint, and a placement rule (hostNamed or hostFamily). |
| ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. | A durable transcript scope in packages/durable (ConversationA durable transcript scope in `packages/durable` (`Conversation` in `src/harness/types.ts`): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. in src/harness/types.ts): it owns entries, admits submissions, forks, compacts, and resolves the agent that serves it. |
| CoreThe deliberately minimal set of built-in capabilities (four tools: `read`, `bash`, `edit`, `write`); features outside core must be extensions. | The deliberately minimal set of built-in capabilities (four tools: read, bash, edit, write); features outside core must be extensions. |
| DeltaThe chord operation vocabulary (`Op` in `packages/chord/src/delta/index.ts`): tuples such as `["r", value]`, `["s", path, value]`, and `["p", path, start, end, items]` that describe a change to a JSON value so the change can be stored, sent, and replayed. | The chord operation vocabulary (Op in packages/chord/src/delta/index.ts): tuples such as ["r", value], ["s", path, value], and ["p", path, start, end, items] that describe a change to a JSON value so the change can be stored, sent, and replayed. |
| DocumentA versioned JSON value in `packages/durable` addressed by a `DocumentAddress` (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are `pi.agent`, `pi.inbox`, `pi.live`, `pi.provider`, `pi.usage`, and `pi.tool.nested-call`. | A versioned JSON value in packages/durable addressed by a DocumentAddress (kind, scope, and an optional family key) and stored as a base plus deltas. The built-in kinds are pi.agent, pi.inbox, pi.live, pi.provider, pi.usage, and pi.tool.nested-call. |
| Durable runtimeThe `packages/durable` runtime that separates transcript scope (`conversation`), executable work (`task`), and persisted JSON (`document`) behind a `Storage` contract with monotonic commit sequences. | The packages/durable runtime that separates transcript scope (conversation), executable work (task), and persisted JSON (document) behind a StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. contract with monotonic commit sequences. |
| Entry recordAn immutable transcript event in `packages/durable` (`EntryRecord` in `src/types.ts`) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the `head` marker that starts the active context. | An immutable transcript event in packages/durable (EntryRecord in src/types.ts) holding optional model-facing messages, an app-facing JSON payload, context overrides of earlier entries, and the head marker that starts the active context. |
| EvalsBehavioral, model-backed checks for pi workflows run with `vitest-evals` and a real `AgentSession` (`packages/evals`). | Behavioral, model-backed checks for pi workflows run with vitest-evals and a real AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. (packages/evals). |
| Execution environmentThe `ExecutionEnv` contract in `packages/durable/src/env/index.ts` that a harness uses for file, shell, and watcher operations, independent of where the work runs. | The ExecutionEnv contract in packages/durable/src/env/index.ts that a harness uses for file, shell, and watcher operations, independent of where the work runs. |
| ExtensionA TypeScript module with a default export `function (pi: ExtensionAPI)` that augments the agent with tools, commands, events, UI, or providers. | A TypeScript module with a default export function (pi: ExtensionAPI) that augments the agent with tools, commands, events, UI, or providers. |
| Extension contextThe `ExtensionContext` object (`src/core/extensions/types.ts`) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. | The ExtensionContext object (src/core/extensions/types.ts) passed to every extension handler: it carries the UI surface, the run mode, the working directory, the model, the scoped models, and the abort signal. |
| Extension runner`ExtensionRunner` (`src/core/extensions/runner.ts`): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. | ExtensionRunner (src/core/extensions/runner.ts): it binds the shared runtime to the session, emits extension events to the loaded handlers, and reports extension errors. |
| FacetA chord plugin unit (`defineFacet` in `packages/chord/src/host.ts`) whose `setup(api)` registers served types on one host kind and whose `uses` list names the contract tokens it consumes. | A chord plugin unit (defineFacet in packages/chord/src/host.ts) whose setup(api) registers served types on one host kind and whose uses list names the contract tokens it consumes. |
| Faux providerThe scripted in-memory provider in `packages/ai/src/providers/faux.ts` (`fauxProvider()`), used for deterministic tests with no real API calls. | The scripted in-memory provider in packages/ai/src/providers/faux.ts (fauxProvider()), used for deterministic tests with no real API calls. |
| Follow-upA queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. | A queued message delivered after the agent would otherwise stop, checked only when no tool calls and no steering messages remain. |
| HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. | The durable runtime entry point in packages/durable (HarnessThe durable runtime entry point in `packages/durable` (`Harness.open(storage, options, context)`), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend..open(storage, options, context)), which owns the scheduler, the task registry, the settings, and the conversations derived from a storage backend. |
| Hot reloadChord's `runReload` (`packages/chord/src/reload.ts`): a host swaps facet code while running, letting in-flight work finish on the code version it started with. | ChordThe typed host runtime in `packages/chord`: facets declare the contract tokens they consume (`uses`) and serve typed contracts (`remote` or `local`), and state travels between hosts as replicated state over links.'s runReload (packages/chord/src/reload.ts): a host swaps facet code while running, letting in-flight work finish on the code version it started with. |
| JsonlStorageThe durable storage backend that appends commits to a `main.jsonl` file plus sidecar files (`packages/durable/src/storage/jsonl/storage.ts`). | The durable storage backend that appends commits to a main.jsonl file plus sidecar files (packages/durable/src/storage/jsonl/storage.ts). |
| LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. | An ordered, bidirectional frame channel between two chord hosts (LinkAn ordered, bidirectional frame channel between two chord hosts (`Link` in `packages/chord/src/link.ts`); `memoryLinkPair`, `ipcLink`, and `webSocketLink` are the shipped transports. in packages/chord/src/link.ts); memoryLinkPair, ipcLink, and webSocketLink are the shipped transports. |
| MCP exposureThe per-server setting `McpExposure` (`codemode`, `deferred`, `direct`, `hidden`) in `src/core/mcp-servers.ts` that decides how an MCP server's tools reach the model. | The per-server setting McpExposure (codemode, deferred, direct, hidden) in src/core/mcp-servers.ts that decides how an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server's tools reach the model. |
| MCP extensionThe coding-agent built-in extension that connects configured MCP servers and registers their tools as `mcp__<server>__<tool>`. | The coding-agent built-in extension that connects configured MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers and registers their tools as mcp__<server>__<tool>. |
| MemoryStorageThe in-memory `Storage` implementation in `packages/durable/src/storage/memory.ts`, the reference implementation of the storage contract with no persistence. | The in-memory StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. implementation in packages/durable/src/storage/memory.ts, the reference implementation of the storage contract with no persistence. |
| ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. | One catalog entry in pi-ai (ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.<TApi> in packages/ai/src/types.ts): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. |
| Model registry`ModelRegistry` (`src/core/model-registry.ts`): the synchronous facade over `ModelRuntime` that extensions use to list and look up models. | ModelRegistry (src/core/model-registry.ts): the synchronous facade over ModelRuntime that extensions use to list and look up models. |
| Model runtime`ModelRuntime` (`src/core/model-runtime.ts`): the canonical model and auth runtime that owns the pi-ai `Models` collection, the credential store, and catalog refresh. | ModelRuntime (src/core/model-runtime.ts): the canonical model and auth runtime that owns the pi-ai ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. collection, the credential store, and catalog refresh. |
| ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. | The pi-ai provider registry (ModelsThe pi-ai provider registry (`Models` in `packages/ai/src/models.ts`) that routes model lookups, auth checks, and streams by owning provider. in packages/ai/src/models.ts) that routes model lookups, auth checks, and streams by owning provider. |
| PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. | The project: a minimal, extensible agent harness that you can make your own, shipped as the pi CLICommand-Line Interface (the `pi` binary). and the @earendil-works/pi-* libraries. |
| pi packageA distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via `pi install`. | A distributable bundle (npm or git) of extensions, skills, prompts, themes, or custom providers, installed via pi install. |
| pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. | The small Rust program (pi-env serve --token <hex>) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. |
| Project trustA per-folder decision (`~/.pi/agent/trust.json`) gating whether project settings, resources, and extensions execute. | A per-folder decision (~/.pi/agent/trust.json) gating whether project settings, resources, and extensions execute. |
| Prompt templateA Markdown file invoked as `/<name>` whose body receives shell-style argument substitution (`$1`, `$@`, `$ARGUMENTS`). | A Markdown file invoked as /<name> whose body receives shell-style argument substitution ($1, $@, $ARGUMENTS). |
| ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. | The pi-ai runtime unit (ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.<TApi> in packages/ai/src/models.ts) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models. |
| Remote execution environmentA durable `ExecutionEnv` whose tools run on another machine through the pi-env daemon while storage and credentials stay local. | A durable ExecutionEnv whose tools run on another machine through the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. while storage and credentials stay local. |
| Replicated stateAn immutable JSON value with ordered change notifications (`replicatedState` in `packages/chord/src/state.ts`): subscribers get a `hydrate` delivery first and an `update` delivery for each published change. | An immutable JSON value with ordered change notifications (replicatedState in packages/chord/src/state.ts): subscribers get a hydrate delivery first and an update delivery for each published change. |
| Resource loader`ResourceLoader` (`src/core/resource-loader.ts`): the component that discovers extensions, skills, prompt templates, themes, and `AGENTS.md` context files, and reloads them on demand. | ResourceLoader (src/core/resource-loader.ts): the component that discovers extensions, skills, prompt templates, themes, and AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. context files, and reloads them on demand. |
| Scope (model) | A scoped model set selected with --models pat1,pat2 for Ctrl+P cycling; each entry is a ScopedModel (a model plus an optional thinking level). |
| ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. | A served type in chord (ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. in packages/chord/src/object.ts): a contract plus the factory that builds its objects, with a lifetime of referenced or host. |
| SessionA persistent, branchable conversation log stored as JSONL (`SessionHeader`, messages, compaction summaries, branch summaries) under `~/.pi/agent/sessions/<encoded-cwd>/`. | A persistent, branchable conversation log stored as JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). (SessionHeader, messages, compaction summaries, branch summaries) under ~/.pi/agent/sessions/<encoded-cwd>/. |
| Session entryOne line of a session file (`SessionEntry` in `src/core/session-manager.ts`): a typed record such as `message`, `thinking_level_change`, `model_change`, `usage`, `compaction`, `branch_summary`, `custom`, `custom_message`, `context_edit`, `label`, or `session_info`. | One line of a session file (SessionEntry in src/core/session-manager.ts): a typed record such as message, thinking_level_change, model_change, usage, compaction, branch_summary, custom, custom_message, context_edit, label, or session_info. |
| Session manager`SessionManager` (`src/core/session-manager.ts`): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. | SessionManager (src/core/session-manager.ts): the reader and writer for session files, with factories to create, open, continue, fork, and list sessions and to build the tree and the model context. |
| SkillAn on-demand capability package following the Agent Skills standard (`SKILL.md` plus optional frontmatter), invoked as `/skill:name`. | An on-demand capability package following the Agent Skills standard (SKILL.md plus optional frontmatter), invoked as /skill:name. |
| SQLite storageThe durable `Storage` backend that persists conversations, tasks, and documents in SQLite (`packages/durable/src/storage/sqlite`), with a Node adapter (`node:sqlite`) and a Cloudflare Durable Object adapter. | The durable StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. backend that persists conversations, tasks, and documents in SQLite (packages/durable/src/storage/sqlite), with a Node adapter (node:sqlite) and a Cloudflare Durable Object adapter. |
| SteeringA queued message delivered to a streaming agent after the current tool batch completes. | A queued message delivered to a streaming agent after the current tool batch completes. |
| StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. | The atomic persistence boundary in packages/durable (StorageThe atomic persistence boundary in `packages/durable` (`Storage` in `src/types.ts`): `commit(writes)` returns a commit sequence, and every later read observes it. in src/types.ts): commit(writes) returns a commit sequence, and every later read observes it. |
| SubmissionA durably admitted user input or passive write (`SubmissionRecord` in `packages/durable`), which either runs at once or queues in `pi.inbox` while the conversation is busy. | A durably admitted user input or passive write (SubmissionRecord in packages/durable), which either runs at once or queues in pi.inbox while the conversation is busy. |
| Task recordThe durable state of one executable unit of work (`TaskRecord` in `packages/durable`): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. | The durable state of one executable unit of work (TaskRecord in packages/durable): input, checkpoint, owner, background flag, abort mark, restarts, and timestamps. |
| Telemetry schemaA versioned contract (`defineTelemetrySchema` in `packages/telemetry`) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships `AI_TELEMETRY_SCHEMA` and `DURABLE_TELEMETRY_SCHEMA`. | A versioned contract (defineTelemetrySchema in packages/telemetry) that declares allowed span names, parents, start and end attributes, events, and metrics. The repo ships AI_TELEMETRY_SCHEMA and DURABLE_TELEMETRY_SCHEMA. |
| Tool exposureHow a tool reaches the model and the runtime. `direct` and `model-only` tools are activated when they are registered; `codemode`, `deferred`, and `hidden` tools are not. | How a tool reaches the model and the runtime. direct and model-only tools are activated when they are registered; codemode, deferred, and hidden tools are not. |
| Virtual modelA model registered by an extension with a context-aware `route()` function (`VirtualModelDefinition` in `src/core/virtual-models.ts`) that picks the real provider and model for each request. | A model registered by an extension with a context-aware route() function (VirtualModelDefinition in src/core/virtual-models.ts) that picks the real provider and model for each request. |
Technical Terms
| Term | Definition |
|---|---|
Agent |
pi-agent-core's stateful class owning the transcript and lifecycle (prompt, continue, abort). |
AgentEvent |
The pi-agent-core lifecycle event union (agent_start, turn_start, message_start, tool_execution_start, and their matching end events). |
agentLoop |
The low-level prompt-stream-tool-continue loop in pi-agent-core. |
AgentMessage |
pi-agent-core's app-extensible message union (via declaration merging); convertToLlm bridges to pi-ai Message. |
AgentTool |
pi-agent-core's tool contract (packages/agent/src/types.ts): a pi-ai Tool plus label, execute, and optional prepareArguments, outputSchema, and executionMode. |
ALL_TOOLS |
The codemode script global listing every callable tool as { name, description }, including tools omitted from the model-facing description. |
Alternate screen |
pi-tui's TuiAltScreen renderer: a fixed-height viewport that owns its own scrolling and layout root. |
API implementation |
A wire-protocol backend shared by providers (e.g. anthropic-messages, openai-responses, openai-completions, google-generative-ai, bedrock-converse-stream). |
AssistantMessageEvent |
The pi-ai streaming event union (start, text_start/text_delta/text_end, thinking_*, toolcall_*, done, error). |
AssistantMessageEventStream |
pi-ai's async-iterable event queue (push queue + result promise) carrying start/*_delta/done/error events. |
AutocompleteProvider |
The pi-tui completion interface (getSuggestions, applyCompletion) that the editor consults for completions. |
BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. |
The Okapi BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. ranking function used to search deferred tools in tool_search and in codemode's searchTools(). |
CodemodeSandbox |
The Node/Bun codemode sandbox running each script in a worker thread with a fresh QuickJS VM. |
Connection |
A pi-env handle to a running daemon process (over SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). or a local command) that multiplexes framed requests; owned by the caller and closed at shutdown. |
Constrained sampling |
ProviderThe pi-ai runtime unit (`Provider<TApi>` in `packages/ai/src/models.ts`) that owns a model catalog, an auth configuration, and the stream, image, and classifier implementations for its models.-side schema enforcement of a tool's parameters, declared as constrainedSampling on a pi-ai Tool and converted per API to a strict JSON schema or a grammar. |
Context |
The caller-facing request shape in pi-ai (Context in packages/ai/src/types.ts): a system prompt, a message list, and optional tool declarations. |
createInMemoryTransportPair |
The @earendil-works/pi-mcp/testing helper returning a linked client/server transport pair for protocol tests without I/O. |
credential store |
The pi-ai CredentialStore interface (read, list, modify, delete) and its file-backed implementation in packages/coding-agent/src/core/auth-storage.ts over ~/.pi/agent/auth.json. |
Differential rendering |
pi-tui's technique of diffing a new line array against the previous frame and writing minimal escape sequences. |
Dynamic client registration |
The MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow where the client registers itself with the authorization server (registerClient in packages/mcp/src/oauth/flow.ts). |
Erasable TypeScript |
The subset of TypeScript enforced via erasableSyntaxOnly so types strip without code generation (no enums, namespaces, or parameter properties). |
Focusable |
The pi-tui marker interface for components that own a text cursor and emit the zero-width CURSOR_MARKER sequence. |
InlineCodemodeSandbox |
The codemode sandbox running scripts on the calling thread for runtimes without worker threads, when blocking the caller is acceptable. |
iTerm2 inline images |
The iTerm2 image protocol pi-tui encodes (encodeITerm2); in alternate-screen mode it falls back to text placeholders. |
Jiti |
The runtime TypeScript transpiler (jiti 2.7.0) that loads TypeScript extensions on the fly in the coding agent. |
JSON mode |
The coding agent's --mode json run mode, which streams AgentSessionThe coding agent's session object (`packages/coding-agent/src/core/agent-session.ts`): it owns the pi-agent-core `Agent`, the session file, the tool loadout, compaction, and the event stream the interactive, print, JSON, and RPC modes consume. events as JSON lines. |
JSON-RPCJSON-RPC 2.0, the MCP request and notification format. |
The JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0 message format MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). uses on the wire, parsed in packages/mcp/src/protocol/jsonrpc.ts. |
Keybinding |
A named action bound to a key id (packages/tui/src/keybindings.ts); defaults live in TUI_KEYBINDINGS and APP_KEYBINDINGS. |
KeyId |
The normalized key identifier string pi-tui parses from terminal input (ctrl+c, shift+tab, alt+left). |
Kitty graphics protocol |
The terminal image protocol pi-tui encodes for Kitty-compatible terminals (encodeKitty in packages/tui/src/terminal-image.ts). |
Kitty keyboard protocol |
Terminal input protocol pi-tui negotiates for richer key reporting. |
LaTeX rendering |
pi-tui's renderLatex (packages/tui/src/latex.ts), which converts LaTeX math into ANSI text. |
lazy SDKSoftware Development Kit (the embeddable programmatic API). loading |
The .lazy.ts wrappers in packages/ai/src/api/ that defer a provider SDKSoftware Development Kit (the embeddable programmatic API). import until the first request (lazyApi in src/api/lazy.ts). |
LocalExecutionEnv |
A NodeExecutionEnv that adds listFiles through a pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. on the same machine (packages/env/src/list-files.ts). |
Lockstep versioning |
All published packages share one version and release together. |
Main screen |
pi-tui's TuiMainScreen renderer: a linear document that grows and leaves terminal scrollback intact. |
McpClient |
The transport-neutral client in @earendil-works/pi-mcp owning request correlation, initialization, timeouts, cancellation, and tool helpers. |
McpTransport |
The pi-mcp transport contract (send, close, message/error/close listeners), implemented by StdioTransport and StreamableHttpTransport. |
ModelsStore |
The pi-ai seam that persists a provider's dynamic catalog (models, lastModified, checkedAt, etag), with InMemoryModelsStore as the default. |
node:sqlite |
The Node built-in SQLite driver behind openNodeSqliteDatabase and openNodeSqliteStorage. |
@options |
The optional first line of a codemode script (// @options: {...}) carrying max_output_tokens and timeout_ms, interpreted by the caller rather than the sandbox. |
pi-env protocol |
The versioned framed protocol between pi-env client and daemon (big-endian length-prefixed JSON plus raw payload frames for requests, results, errors, events, cancel, and ping). |
PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). |
Proof Key for Code Exchange, the OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai providers and the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). client (packages/ai/src/auth/oauth/pkce.ts). |
print mode |
The coding agent's non-interactive -p run mode, which prints the final answer to stdout. |
QuickJS |
The JavaScript engine compiled to WebAssembly that hosts codemode scripts (quickjs-wasi 3.6.2). |
RemoteCodemodeSandbox |
The portable codemode sandbox running the VM in a separately deployed Cloudflare Durable Object so computing scripts do not block the session isolate. |
RemoteExecutionEnv |
The durable ExecutionEnv talking to the pi-env daemonThe small Rust program (`pi-env serve --token <hex>`) that runs on a remote machine and performs file operations and commands there over a framed protocol on stdin/stdout. through a Connection, matching NodeExecutionEnv semantics on the remote machine. |
renderDeclarations |
The pi-codemode helper turning tool and global schemas into TypeScript declarations for a model-facing tool description. |
roots |
The filesystem roots an McpClient advertises so servers can request roots/list. |
RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). mode |
The coding agent's --mode rpc run mode, which speaks newline-delimited JSON commands and events over stdin/stdout. |
scanHostKey / acceptHostKey |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). trust flow: show a host key fingerprint for out-of-band verification, then persist it to the application's own known-hosts file. |
Span/Event taxonomy |
The versioned telemetry schema (defineTelemetrySchema) declaring allowed span names, parents, start/end attributes, and events for typed telemetry. |
SQLite migration |
An ordered, versioned set of SQLStructured Query Language (the durable SQLite schema and chord's migration runner). statements applied by chord's applySqliteMigrations; the durable schema sits at CURRENT_SQLITE_SCHEMA_VERSION = 2. |
SQLITE_MIGRATIONS |
The ordered durable SQLite schema migrations in packages/durable/src/storage/sqlite/migrations.ts. |
SqliteStorage |
The portable SQLite implementation of the durable storage contract, opened via openNodeSqliteStorage on Node or openDurableObjectSqliteStorage on Cloudflare. |
SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). |
Server-Sent Events, the server-to-client stream of the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol. transport (consumeSseStream in packages/mcp/src/transports/streamable-http.ts). |
sshConnection / connectSsh |
The pi-env SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). entry points: a lazy connection that detects, deploys, and dials on first use, and an eager variant that does so immediately. |
StdioTransport |
The pi-mcp transport spawning an MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). server as a child process and speaking JSON-RPCJSON-RPC 2.0, the MCP request and notification format. over its stdin/stdout. |
StreamableHttpTransport |
The pi-mcp transport for remote MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). servers over Streamable HTTPHypertext Transfer Protocol. with session resumption via Last-Event-ID. |
streamFn / StreamFn |
The injectable function the agent calls to reach the LLMLarge Language Model.; streamSimple is the default. |
STRICT tables |
SQLite STRICT tables, used for every durable table so column types are enforced. |
Synchronized output |
Terminal escape sequence (\x1b[?2026h..l) used by pi-tui for atomic, flicker-free rendering. |
TelemetryCarrier |
The opaque Record<string, string> that carries a telemetry parent across process boundaries. |
TelemetryContext / TelemetrySpan |
The span-creation scope (TelemetryContext.startSpan) and its active unit (TelemetrySpan, itself a context) carrying attributes, events, and status. |
ThinkingLevel |
The reasoning budget of a request: off, minimal, low, medium, high, xhigh, or max. |
tool_search |
The built-in extension tool that finds deferred tools with BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. and loads the matches for the next model call. |
ToolCall |
A model-emitted tool invocation (ToolCall in packages/ai/src/types.ts) with an id, a name, and arguments. |
ToolExposure |
The coding-agent tool exposure type: direct, model-only, codemode, deferred, or hidden. |
ToolResultMessage |
The transcript message carrying a tool's output (role: "toolResult") back to the model. |
TranscriptContext |
The branded message-only context produced by normalizeContext() in pi-ai, the only form the agent loop hands to a provider. |
Trusted publishing |
npm publish via GitHub Actions OIDCOpenID Connect (used for npm trusted publishing identity). (environment npm-publish); no local credentials required. |
TypeBox |
The schema library used for tool parameter definitions (serializable JSON, self-validating). |
WASMWebAssembly (the QuickJS sandbox and the Photon image library). |
WebAssembly, the compilation target of the QuickJS sandbox (quickjs-wasi) and the Photon image library. |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACAcceptance Criterion / Acceptance Criteria. | Acceptance Criterion / Acceptance Criteria. |
| ADRArchitecture Decision Record. | Architecture Decision Record. |
| AGENTS.mdProject-specific rules file for humans and agents, read automatically from the repo root. | Project-specific rules file for humans and agents, read automatically from the repo root. |
| API keyApplication Programming Interface key (ambient provider authentication). | Application Programming Interface key (ambient provider authentication). |
| BM25Best Matching 25, the Okapi term-weighting ranking function used by `tool_search`. | Best Matching 25, the Okapi term-weighting ranking function used by tool_search. |
| CIContinuous Integration (the `ci` GitHub workflow). | Continuous Integration (the ci GitHub workflow). |
| CJKChinese, Japanese, Korean (terminal width handling for wide characters). | Chinese, Japanese, Korean (terminal width handling for wide characters). |
| CLICommand-Line Interface (the `pi` binary). | Command-Line Interface (the pi binary). |
| CVECommon Vulnerabilities and Exposures. | Common Vulnerabilities and Exposures. |
| DBMLDatabase Markup Language (the schema notation of `.sdlc/context/schema.dbml`). | Database Markup Language (the schema notation of .sdlc/context/schema.dbml). |
| FRFunctional Requirement. | Functional Requirement. |
| HTTPHypertext Transfer Protocol. | Hypertext Transfer Protocol. |
| HTTPSHypertext Transfer Protocol over TLS. | Hypertext Transfer Protocol over TLS. |
| IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). | Input Method Editor (pi-tui positions the hardware cursor for IMEInput Method Editor (pi-tui positions the hardware cursor for IME candidate windows). candidate windows). |
| JSON-RPCJSON-RPC 2.0, the MCP request and notification format. | JSON-RPCJSON-RPC 2.0, the MCP request and notification format. 2.0, the MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). request and notification format. |
| JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). | JSON Lines (one JSON value per line; the session file and the RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). protocol). |
| LLMLarge Language Model. | Large Language ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities.. |
| MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). | ModelOne catalog entry in pi-ai (`Model<TApi>` in `packages/ai/src/types.ts`): a provider-scoped id with its api, context window, cost rates, and thinking capabilities. Context Protocol (standalone client in pi-mcp; built-in coding-agent extension). |
| NFRNon-Functional Requirement. | Non-Functional Requirement. |
| NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. | The NixThe Nix package manager, used to build the `pi` package offline from a pinned model catalog. package manager, used to build the pi package offline from a pinned model catalog. |
| OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). | Open Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). |
| OIDCOpenID Connect (used for npm trusted publishing identity). | OpenID Connect (used for npm trusted publishing identity). |
| PKCEProof Key for Code Exchange (OAuth flow used by pi-ai). | Proof Key for Code Exchange (OAuthOpen Authorization (used for subscription-based provider login: Claude Pro/Max, ChatGPT Plus/Pro, GitHub Copilot). flow used by pi-ai). |
| RFCRequest for Comments (Earendil publishes longer-term Pi proposals as RFCs). | Request for Comments (Earendil publishes longer-term PiThe project: a minimal, extensible agent harness that you can make your own, shipped as the `pi` CLI and the `@earendil-works/pi-*` libraries. proposals as RFCs). |
| RPCRemote Procedure Call (the JSONL stdin/stdout protocol mode). | Remote Procedure Call (the JSONLJSON Lines (one JSON value per line; the session file and the RPC protocol). stdin/stdout protocol mode). |
| SDKSoftware Development Kit (the embeddable programmatic API). | Software Development Kit (the embeddable programmatic API). |
| SLO / SLIService Level Objective / Service Level Indicator. | ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Objective / ServiceA served type in chord (`Service` in `packages/chord/src/object.ts`): a contract plus the factory that builds its objects, with a lifetime of `referenced` or `host`. Level Indicator. |
| SQLStructured Query Language (the durable SQLite schema and chord's migration runner). | Structured Query Language (the durable SQLite schema and chord's migration runner). |
| SSEServer-Sent Events (the server-to-client stream of MCP Streamable HTTP). | Server-Sent Events (the server-to-client stream of MCPModel Context Protocol (standalone client in `pi-mcp`; built-in coding-agent extension). Streamable HTTPHypertext Transfer Protocol.). |
| SSHSecure Shell (transport pi-env uses to start its daemon on remote machines). | Secure Shell (transport pi-env uses to start its daemon on remote machines). |
| TUITerminal User Interface (the interactive mode, and the `pi-tui` library). | Terminal User Interface (the interactive mode, and the pi-tui library). |
| WASMWebAssembly (the QuickJS sandbox and the Photon image library). | WebAssembly (the QuickJS sandbox and the Photon image library). |
| WSWebSocket (chord's `webSocketLink` transport). | WebSocket (chord's webSocketLink transport). |