Architecture
flowchart LR
UI[Pi TUI / TypeScript] <-->|JSONL commands and events| Engine[Rust engine]
Engine --> Provider[Compatible model provider]
Engine --> Reviewer[Independent guardrail API]
Reviewer -->|Single-use approval| Shell[Bash process groups]
Engine --> Context[Editable working context]
Engine --> History[Session metadata and journal]
Harbor[Harbor adapter / Python] -->|Headless CLI inside task container| Engine
The model controls strategy, shell commands, command durations and context contents. The caller controls task budgets and the operating-system/container boundary. There is no built-in planning workflow, subagent hierarchy or automatic context summarization.
runtime.rs runs the model/tool loop. provider.rs contains the initial Chat Completions transport, SSE parser and deterministic demo. shell.rs manages process groups and bounded output capture. session.rs validates and atomically saves context; event.rs serializes journal/protocol events. main.rs exposes one-shot and long-lived modes.
The TypeScript frontend uses Pi's presentation components and never calls the model directly. protocol.ts handles subprocess records, request IDs and acknowledgements. app.ts renders messages, tools, input and the meter. This keeps interactive and benchmark execution on the same Rust engine.
launch.ts selects the newest local build or the caller's explicit executable, validates its file/execution permissions, and owns frontend startup/shutdown. It closes the backend even if UI construction or terminal initialization fails. The npm scripts invoke the frontend directly so the caller's directory survives as the default workspace. These are user-facing launch mechanics; they add no model tools, prompts or context changes. Real pseudo-terminal checks cover the npm source entrypoint and compiled frontend alongside the in-memory Pi tests.
content.rs defines typed text/image parts, bounded explicit attachment reads and inline image validation. User content can contain Chat Completions image parts; assistant/tool results remain text. The model views images by editing ordinary user context through bash. Explicit CLI/TUI attachments use the same representation, with bytes embedded for stable resume. Image processing is limited to Base64 and header checks; there is no image decoder, URL fetcher or additional model tool. Context appends validate the complete serialized size before replacing working context, and saved snapshots reuse the same encoded bytes.
history.rs projects journal records into paged, bounded display previews. The TUI renders those in a separate history container and merges older pages for command/output continuity. Historical events never enter the live run handler or model context. The journal records only history-response metadata, avoiding recursive payload copies. The client stops uncertain work on protocol corruption and bounds shutdown rather than silently continuing without a working display.
The Python integration only stages the Linux binary and task statement, delegates execution, collects artifacts, and maps usage into Harbor's accounting. It reuses Harbor's provider/credential/endpoint resolver. Harbor does not become part of the runtime distribution.
The journal is separate from mutable context so normal compaction preserves history. It is a diagnostic record maintained by the runtime, not a tamper-proof audit log. The outer OS/container boundary provides isolation; local mode has the user's permissions.
storage.rs owns private files and bounded reads, protocol.rs bounds stdin records without losing partial input during cancellation, and terminal.rs filters untrusted headless display. These protect runtime mechanics without adding model-visible tools or behavioral instructions. See SECURITY.md.
doctor.rs provides read-only startup diagnostics. Runtime startup and provider requests reuse credential validation from config.rs, so failures discovered locally are rejected before opening a session or counting a provider request. Diagnostic checks do not call a model, run a command or test write access.
catalog.rs discovers default sessions from bounded metadata reads and observed locks, shared by the standalone sessions command and the TUI's /sessions. It uses the existing private-file checks, reads no conversation contents, and changes no discovered session files. Protocol responses journal only query counts. Discovery remains a user interface operation and adds nothing to the model's tools or context.
Changes should preserve a small set of invariants: one bash tool, a descriptive system prompt, model-owned strategy and context, caller-owned resource and OS boundaries, and the same engine for interactive use and evaluation. New orchestration layers, automatic summarizers and extra tools need measured evidence of value. Benchmark comparisons must pin both implementations and hold tasks, models, tools and budgets constant; offline correctness tests alone demonstrate no capability advantage.
The frontend's catalog.ts owns a bounded models.dev metadata subset and fixed provider routes; it is separate from the Rust session catalog. Mutable remote metadata cannot supply credential destinations. Refresh is explicit, HTTPS-only, redirect-denying, credential-free and bounded to 16 MiB/10 seconds; it replaces in-memory data only after validation. The bundled snapshot supports offline setup. Catalog prices remain informational, and models requiring unsupported protocols/reasoning replay are filtered. picker.ts provides shared keyboard/mouse search and detail panels. The fullscreen Pi layout pins the editor and action bar beneath a scrolling transcript. None of this metadata or navigation is sent to model context.
compatibility.rs embeds the reviewed chat-compatibility.json asset shared with the picker. It supplies required Chat Completions defaults before requests and rejects known unsupported direct OpenAI tool routes before session creation. Catalog tool_call metadata alone does not establish protocol compatibility. Explicit incompatible reasoning settings fail rather than being silently downgraded; switching models discards the previous model's effort and resolves the new default. These are transport constraints and do not add tools or alter the system prompt.
home.ts paints the entire terminal viewport, centers the new-session composer, adapts the wordmark to available space and dispatches keyboard/mouse navigation. A first prompt switches to the pinned-composer workspace. Session selection uses the existing metadata-only catalog and the frontend lifecycle to close the old runtime before resuming; model changes clear stale pricing/caps during navigation. UI state and branding never enter model context.
connections.rs defaults to local credential files under the home config directory. Registry entries contain only UUID references; separate private JSON envelopes hold the keys. Existing private-file primitives provide no-follow, ownership/single-link checks and atomic synced writes. Reads also require owner-only permissions. Settings edits retain the registry lock while staging a new key and roll it back if the registry write fails. Keychain/environment references remain optional. Legacy macOS metadata is imported on first edit without reading or moving its referenced secrets.
Approval boundary
guardrails.rs creates a fresh tool-free request for each proposed shell action. The immutable original user request and exact arguments are independent of model-owned context. Only a complete matching API decision can construct ApprovedCommand; Shell::execute consumes that non-cloneable grant. There is no other production shell entry point. Connections and reviewer keys are pinned on engine startup/model change. TUI reviewer changes restart the backend on the same session and retain drafts.
A denial is a blocked tool result, permitting an alternative proposal. Cancellation, API failure or invalid approval blocks the remaining batch and ends the run. guard_review and guard_decision events are separate from tool_started and remain in journal history after context compaction. These files are not tamper-proof against code running as the same user.
usage counts agent requests and guard_usage counts reviewer requests. Both persist pending requests before network I/O. Spending caps and catalog/Harbor totals include both; unknown costs remain unknown. Existing session metadata without guard_usage reads as zero historical review requests. This gate intentionally changes the evaluated harness: historical unguarded FreeHand comparisons are not an apples-to-apples measurement of the guarded agent. Capability comparisons must report this difference or apply the same external policy to both.