Introducing a new way to review your PRs.

Read the announcement

earendil-works / pi

AI agent toolkit: unified LLM API, agent loop, TUI, coding agent CLI

View on GitHub

13 documents · Updated Nov 19, 2026

docs / coding-agent

Coding Agent Package

Overview

Path-routing coverage: route any change under packages/coding-agent/** to this document. This doc owns the Pi coding-agent CLI/runtime package: CLI and RPC entrypoints, run modes, session/runtime management, built-in tools, extension/resource loading, configuration schemas, package-management commands, scripts, examples, and tests that exercise this package.

packages/…/package.json publishes the pi binary from dist/…/cli.js, exports the SDK from dist/index.js, and exposes ./rpc-entry for embedders. src/cli.ts is the normal executable entrypoint: it runs setupCli() and then calls main(process.argv.slice(2)) from src/main.ts. src/rpc-entry.ts is the specialized RPC executable: it sets process identity/environment markers, suppresses process warnings, configures HTTP dispatching, and invokes main(["--mode", "rpc", ...args]).

src/main.ts is the orchestration layer. It parses arguments with src/…/args.ts, handles auth/package/config/MCP subcommands before constructing a session, determines app mode (interactive, print, json, or rpc) from --mode, --print, stdin, and stdout, then builds an AgentSessionRuntime. Startup state is split deliberately: a bootstrap SettingsManager from src/…/settings-manager.ts is used for early proxy/session-dir/startup UI decisions, then createAgentSessionServices() in src/…/agent-session-services.ts recreates cwd-bound services once the effective session cwd is known. This matters because --session, --resume, /resume, and /fork can move execution to a session whose saved cwd differs from the process cwd.

Runtime construction flows through src/…/agent-session-runtime.ts, src/…/agent-session-services.ts, and src/…/sdk.ts. createAgentSessionServices() resolves the cwd and agent dir, creates ModelRuntime, SettingsManager, and DefaultResourceLoader, loads resources, registers providers/virtual models queued by extensions, refreshes model availability without network, and returns diagnostics instead of printing. createAgentSessionFromServices() then delegates to createAgentSession() in src/…/sdk.ts, which restores or chooses a model/thinking level, resolves the startup tool set, wraps provider streaming through ModelRuntime, installs cache warming, creates the underlying Agent from @earendil-works/pi-agent-core, and wraps it in AgentSession from src/…/agent-session.ts.

AgentSession in src/…/agent-session.ts is the shared business object for all modes. It owns agent event subscription, session persistence, model/thinking changes, system prompt refresh, tool registration/exposure, extension binding, compaction/retry, queued steering/follow-up messages, nested tool calls, bash execution, branch/tree navigation, and session reload. Modes only provide I/O: src/…/interactive-mode.ts draws the TUI and binds terminal UI primitives, src/…/print-mode.ts runs one-shot text or JSON event output and exits, and src/…/rpc-mode.ts reads JSONL commands from stdin and emits JSONL responses/events on stdout. src/…/rpc-client.ts is the typed process-spawning client for that JSONL protocol, while src/…/rpc-types.ts defines command/response/session-state contracts.

Sessions are append-only JSONL files managed by src/…/session-manager.ts. A file starts with a session header containing version, id, timestamp, cwd, and optional parent session; subsequent entries record messages, model/thinking changes, usage, compaction summaries, branch summaries, custom extension state, custom context messages, context edits, labels, and session names. SessionManager delays creating a persisted file until a user or assistant message exists, builds the active branch by walking parentId links from the current leaf, and computes LLM-visible context through buildSessionProjection()/buildSessionContext(), which apply compaction and latest context edits. AgentSessionRuntime wraps the current AgentSession plus services and recreates them for /new, /resume, /fork, and import, emitting session_shutdown before invalidating the old extension runtime.

Model/auth state is centralized in src/…/model-runtime.ts. It composes built-in providers from @earendil-works/pi-ai, custom provider configs from models.json, native/provider registrations from extensions, Radius-backed providers, remote/personally tailored catalogs, and virtual models. Credentials flow through RuntimeCredentials and auth storage; ModelRuntime serializes credential mutations per provider and can settle pending writes during runtime disposal. src/main.ts wires CLI --model, --provider, --models, --thinking, and --api-key into ModelRuntime and session options before creating AgentSession.

Settings and resources are file-backed but trust-aware. src/config.ts defines package asset paths, release/binary detection, ~/.pi/agent paths, environment overrides such as PI_CODING_AGENT_DIR, PI_CODING_AGENT_SESSION_DIR, PI_PACKAGE_DIR, PI_OFFLINE, and self-update helpers. src/…/settings-manager.ts loads and deep-merges global ~/…/settings.json and project .pi/settings.json, with project settings skipped when the project is untrusted. src/…/trust-manager.ts detects trust-requiring project resources under .pi/ and .agents/skills, persists trust decisions in trust.json, and src/…/project-trust.ts prompts or delegates to extension project_trust handlers before enabling project-local settings/resources.

src/…/resource-loader.ts discovers and reloads extensions, skills, prompt templates, themes, context files (AGENTS*.md and CLAUDE*.md), SYSTEM.md, and APPEND_SYSTEM.md. It uses src/…/package-manager.ts to resolve npm/git/local package resources, apply resource precedence, install missing packages, and pass source metadata into loaded resources. The CLI package-management surface is in src/package-manager-cli.ts: pi install/remove/update/list/config manipulates package sources, self-updates Pi, refreshes models, and opens the resource configuration TUI. Interactive reloads capture package command output so git/npm logs do not corrupt the TUI.

The extension system is implemented under src/core/extensions/**. src/…/loader.ts loads TypeScript/JavaScript extension modules via jiti or embedded virtual modules, aliases host-provided packages so extensions share the host @earendil-works/pi-* runtime, creates an ExtensionAPI, and queues provider/virtual-model/MCP registrations until the runtime is bound. src/…/types.ts defines extension UI, event, tool, command, flag, provider, markdown-renderer, session, and project-trust contracts. Built-in extensions are registered in src/…/index.ts: llama.cpp, codemode, tool-search, and MCP. The MCP extension in src/…/index.ts loads mcp.json, connects servers in the background, registers tools as mcp__<server>__<tool>, and exposes direct/codemode/deferred/hidden reachability. The codemode extension in src/…/index.ts registers the inactive codemode tool, which becomes active through settings/CLI or MCP auto-enablement.

Built-in tools live under src/core/tools/**. src/…/index.ts aggregates read, bash, PowerShell, edit, write, grep, find, and ls definitions and exposes createCodingToolDefinitions() for the default read/bash/edit/write set. src/…/bash.ts executes shell commands through pluggable BashOperations, streams updates, enforces optional timeouts by killing process trees, truncates model-facing output while saving full output when needed, and injects PI_SESSION_ID, PI_SESSION_FILE, PI_PROVIDER, PI_MODEL, and PI_REASONING_LEVEL when a session context is available. src/…/edit.ts performs exact, unique, non-overlapping replacements, computes diffs before writing, preserves BOM/line endings, and serializes mutations per file with withFileMutationQueue(). Tool definitions are first-class ToolDefinitions so extensions can render them, intercept calls/results, alter loadouts, hide declarations, or run nested tools through ctx.executeTool().

System prompt and context behavior are assembled in src/…/system-prompt.ts. The prompt is sectioned (preamble, tools, rules, docs, addendum, project context, skills, cwd, and extension-added sections) so later changes can be recorded as section patches instead of replacing the entire system message. Skills from src/…/skills.ts and prompt templates from src/…/prompt-templates.ts are loaded from global/project/package/CLI paths by DefaultResourceLoader; templates expand positional placeholders, while skills are validated from Markdown/frontmatter and can become slash commands when enabled. Compaction logic in src/…/compaction.ts estimates context usage, chooses cut points that do not orphan tool results, summarizes older context, stores file-operation details, and appends compaction entries. src/…/branch-summarization.ts summarizes abandoned branches during tree navigation so returning later preserves context.

Interactive UI is concentrated in src/…/interactive-mode.ts and its components/theme subdirectories. It binds TUI components from @earendil-works/pi-tui, renders transcript entries and tool executions, handles slash commands, selectors, session tree/resume/fork, model/thinking selectors, login dialogs, project-trust prompts, /share, bug reports, changelog notices, cache notices, terminal status reporting, clipboard/image paste, external editor integration, and extension UI surfaces. Themes are validated in src/…/theme-schema.ts and generated into schemas/theme.schema.json by scripts/generate-schemas.ts.

Generated schemas and references live inside this package. src/…/settings-schema.ts, src/…/model-config.ts, src/…/keybindings-schema.ts, and src/…/theme-schema.ts feed scripts/generate-schemas.ts, which writes schemas/settings.schema.json, schemas/models.schema.json, schemas/keybindings.schema.json, and schemas/theme.schema.json. scripts/generate-references.ts renders documentation tables for model configuration from the same TypeBox schemas. Tests under packages/coding-agent/test/** cover the package at multiple layers: CLI/config/settings/session managers, RPC and JSONL behavior, tools and renderers, extensions and built-ins, system prompts, themes, model/runtime behavior, project trust, and session export/share flows.

Coupling

Risks

  • src/…/rpc-mode.ts, src/…/rpc-client.ts, and src/…/print-mode.ts are fragile around stdout/protocol cleanliness and session replacement. Recent history includes fixes for emitting session_start exactly once or at the right time in RPC/JSON print mode (beffcde92, 6aab551a7) and for moving remaining direct terminal writes away from stdout (ac78a6068). If a new diagnostic, extension message, or startup notice writes to stdout in RPC/JSON mode, embedders will fail to parse the JSONL stream.
  • src/…/agent-session-runtime.ts, src/…/agent-session-services.ts, and src/main.ts have high churn around diagnostics and replacement lifecycles (c47ad0432, c8c456c85, e03dca7a3). If /resume, /fork, /new, import, or reload recreates services without rebinding mode listeners before extension session_start handlers run, startup/replacement diagnostics or appended entries can be lost or reported twice.
  • src/…/package-manager.ts, src/…/resource-loader.ts, and src/main.ts are sensitive to terminal ownership. A recent fix (b513b64d8) captured git/npm output while the interactive TUI runs. If package resolution or update code reverts to inherited stdio during interactive reloads, npm/git output can corrupt the TUI; if it captures when running explicit pi install/pi update, users can lose needed progress and credential-failure context.
  • src/…/bash.ts and src/…/shell.ts have repeated edge-case fixes for process termination and output retention (a83b75a07, 935f0ac0c). If timeout/abort handling stops killing process trees or misreports signal exits, long-running commands can leak child processes or appear successful; if truncation changes mishandle overlong tail lines, the model may lose the useful failure output.
  • src/…/session-manager.ts and src/core/compaction/** preserve append-only tree semantics and old-session compatibility. Because malformed JSONL lines are skipped and old entries are migrated in place, changes to entry projection, context edits, compaction boundaries, or branch summaries can silently alter what the model sees on resume rather than throwing an obvious error.
  • src/…/loader.ts has runtime-specific module resolution for source, bundled Node, Bun binaries, and Node SEA. Recent history includes a standalone-binary extension dependency resolution fix (4cfea9786). If aliases or embedded virtual modules stop pointing extensions at the host package copies, extensions can load duplicate pi-ai/pi-tui/typebox instances, making registered tools, schemas, or UI components incompatible with the host runtime.