Files
ai-agent/runner/README.md
gabrielvidalandClaude Opus 5.5 2c02deb109 refactor(plugins): EVOX2 sidecar helpers → provider-evox2, OpenRouter catalogue → registry discovery
- sidecar/gen_progress.py, local_ready.py, local_room.py moved into the
  provider-evox2 plugin's new provider.sidecar module; the core reaches them
  through usage_loader.live_progress / before_launch and the module's
  extra_routers() (/local-ready, host only). No plugin: no-ops.
- provider.sidecar: a provider sidecar module that is no usage reader
  (typed_manifest, store.sync_typed, DriverLoader code_key tuple).
- backend/models/openrouter.py deleted: the APPE catalogue is the
  openrouter_appe discovery of plugins/providers.py (appe_catalogue,
  warm_discovery, legacy_appe_index).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 18:43:37 +01:00

11 KiB
Raw Permalink Blame History

pi runner — the ai-agent's second harness

Runs viewer-spawned sessions on pi (@earendil-works/ pi-coding-agent) instead of the claude CLI, with open models: Qwen 3.8 (or 3.6) via OpenRouter (hosted) or the EVOX2 box's llm-server (local, free — llama.cpp in router mode, ~/projects/brain/llm/).

How harness switching works

The model chip in the composer is the harness switch. /api/models returns every pickable model tagged with its harness (claude | pi); picking a qwen chip routes the session through this runner, picking a Claude family runs claude exactly as before. The chain:

composer chip → POST /api/spawn {model, harness}
             → sidecar /spawn  → harness == "pi" ? RUNNER_BIN : CLAUDE_BIN
             → runner: pi --mode json --session-id <uuid> …
             → transcript mirrored to ~/.pi-runner/transcripts/<cwd>/<uuid>.jsonl
             → container watches it (PI_TRANSCRIPTS_DIR mount) → SSE → viewer
  • The spawn stamps harness into the conversation metadata sidecar, so a resume with no model picked continues on the same harness (backend fallback); picking a chip from the other harness switches mid-conversation.
  • The runner accepts the same flag shape as claude (-p --session-id/--resume --model), so the sidecar treats both harnesses identically — pidfiles, launch probe, SIGINT interrupt, reused idempotency all work unchanged.
  • The transcript is v1 (docs/transcript-format.md, since step 1c): the runner translates pi's message_end events (assistant / toolResult) into v1 events — a header naming pi, each model step whole (its call, its blocks, its usage, in one append, before its tools run, so a tool card shows while the tool works), the tool results, the compactions — so the viewer's parser, cost-by-tool, SSE streaming and lifecycle checks need no pi-specific code. pi's agent_settled (or the pi process's exit) becomes a turn_end — the equivalent of Claude Code's Stop-hook summary, which the viewer reads as the conversation having finished. A transcript from before v1 (Claude-Code-shaped records) that a resume appends to gets a v1 header line first: the hub reads every line after it as v1. A fork copies its source's lines under the new session id (the header's id, or the old records' sessionId).
  • Built-in tool calls are shaped as Claude's (mapToolCall in cli.mjs): pi's lowercase read/write/edit/bash/grep/find/ls with path/edits[] get Claude Code's argument shapes (file_path, old_string/new_string, bash timeout s→ms) and the neutral tool names (read, write, edit, shell, grep, glob, list_dir), pi's own in native. That's what makes the viewer's cost-by-tool buckets, per-extension sub-breakdowns, auto project/service tags, bash cards and Read image previews light up for pi sessions. Unknown (extension) tools are pi:<name> and render as generic cards.
  • Real cost, not estimates: each step's usage carries pi's own per-message provider cost as cost: {usd, source: "provider"} (omitted when pi reports none). The parser prefers it over its price table — so OpenRouter runs show the billed amount, and a free local EVOX2 run is priced from its duration (electricity + hardware, pricing.local_call).

Model → provider routing

model id provider
any id listed under a provider in ~/.pi/agent/models.json — inkling-2-mini, ggml-org/qwen3.8-27b, qwen3.6-35b-a3b that provider: on the EVOX2, llm-server (evox2, :8090, the Qwens) or llm-inkling (evox2-inkling, :8091, Inkling 2 Mini); the box is WoL-woken automatically (the probe hits the provider's baseUrl). Local runs default to --thinking off — or the model entry's defaultThinking (Inkling: medium) — pass a level to override
everything else with a vendor prefix — openai/gpt-oss-20b, qwen/qwen3.8-27b, … OpenRouter (OPENROUTER_API_KEY, auto-loaded from ~/homelab/.env.claude). The sidecar checks that key (GET /pi/openrouter, OpenRouter's /api/v1/key, cached 10 min) and /api/models marks the OpenRouter chips unavailable — greyed out, the browser too — while it is refused

pi's own registry decides, and the id shape is only the fallback. It has to: The EVOX2 serves the local Qwen 3.8 as ggml-org/qwen3.8-27b — vendor prefix and all — while OpenRouter has a qwen/qwen3.8-27b of its own, so the two differ by provider, not by shape. A model must be listed in that file for pi to run it locally anyway, which is what makes it the authority; anything unlisted falls back to "has a / ⇒ OpenRouter", so any of the several hundred OpenRouter models still runs here with no runner change. Registering a new local model means adding it under its provider's models array there (id, contextWindow, compat.thinkingFormat, zero cost) and adding a chip for it in backend/models.py. Two pickers feed the composer: the curated chips in backend/models.py (PI_MODELS_DEFAULT, override with PI_MODELS_JSON) and the composer's OpenRouter browser, which lists the whole catalogue with per-model prices from backend/plugins/providers.py (appe_catalogue) (sourced from APPE). Those same prices cost the session's transcript, so a run's $ figure is the model's real rate even before pi reports its own cost.

Permissions

extensions/folder-permissions.ts blocks tool calls outside the session's scope (PI_PERM_SCOPE, default = the run's cwd): write/edit only inside the scope, reads inside PI_PERM_READ roots (default $HOME) + system prefixes, bash commands may not reference paths outside the readable roots, and a deny-always list protects .env/credentials/.ssh from writes. This is stricter than the claude harness's bypassPermissions — pi itself has no permission system, so the extension is the enforcement point.

pi session state

pi sessions persist under ~/.pi-runner/sessions/ keyed by the same UUID the viewer uses (--session-dir + --session-id), so resume is stateless: the same id simply reopens the session.

Which model a continuation runs on. pi has no "keep the session's model": the runner always hands it a --provider + --model. So a resume or fork with no model picked runs on the model the session last answered on — the last assistant message in pi's session file that neither errored nor was aborted (the sidecar's pi_runs.session_model, mirrored by the runner for a resume started by hand) — never on a default. Until 2026-11-06 it fell back to SIDECAR_PI_MODEL (then OpenRouter's qwen/qwen3.8-27b), so every untouched follow-up of a local conversation silently moved to OpenRouter. A new run with none picked takes SIDECAR_PI_MODEL, now the local inkling-2-mini (since 2026-11-23; ggml-org/qwen3.8-27b before).

Long runs: compaction

pi summarises the older part of a session once the context passes contextWindow − compaction.reserveTokens (~/.pi/agent/settings.json: reserve 32768, so 75 % of the local models' 131072 window, leaving room for one full 32k reply). Since 2026-11-24 the runner is on pi 1.6.0, which runs that check before every model request inside a run (pi ≥ 0.84.4). The 0.80.6 it ran before checked only once a run was over. A long autonomous run (one prompt, hundreds of tool calls) therefore never compacted: on 2026-11-24 an Inkling run grew to 127k of 131k, pi capped the next reply at 1 token (it keeps 4,096 tokens free, pi-ai clampMaxTokensToContext), the reply stopped at length, and pi compacted after the run and stopped there.

  • The divider. Each compaction pi reports (compaction_end with a result) is written as Claude Code's system/compact_boundary record (trigger: "auto", preTokens = pi's tokensBefore, postTokens = its estimatedTokensAfter, durationMs) followed by an isCompactSummary user record with the summary. The viewer draws its usual "auto-compacted · 98k → 21k" divider, the summary on it. The summary call's own cost is not mirrored: $0 on the EVOX2, a few cents on OpenRouter.
  • The safety net. If a run's last reply still stopped at length and a compaction followed it, the runner starts pi again on the same session with a "you were cut off, carry on" prompt, at most RUNNER_AUTO_CONTINUES times per run (default 2, 0 turns it off). That prompt goes into the transcript as an injected <pi-runner-auto-continue> text, which the viewer doesn't show as a turn. The turn_end is written only once the last pi of the run has settled. A length stop with no compaction after it (a long reply at small context) ends the turn as before.
  • A model's contextWindow in models.json must be the server's real context (ctx-size in brain/llm/models.ini, GUFO_CONTEXT for llm-inkling). If it says more than the server holds, every threshold comes too late. Per-model budgets: compaction.modelOverrides (pi ≥ 0.86).

Tests: node --test runner/test/cli.test.mjs (the runner against a fake pi that replays scripted events) and backend/test_pi_compaction.py (the parse).

Errors become the error card

A failed model call is pi's assistant message with stopReason: "error" and an errorMessage. The runner writes it as Claude Code's API-error turn — isApiErrorMessage: true, model <synthetic>, the message as text (API Error (openrouter · qwen/qwen3.8-27b): 401 API key expired.) and an error field the backend parser maps to the card's kind: invalid_api_key → API key refused, context_exceeded → Context full, network_error (terminated, Connection error.) → Connection lost, plus the claude CLI's rate_limit / server_error. A failure pi retries (auto_retry_start) is held back and dropped; only one that stands is written. An EVOX2 that never wakes and a pi that exits non-zero before any message get a card too, and the prompt is recorded before the wake so it never vanishes. Before 2026-11-06 the runner wrote an empty stop_reason: "error" record instead — 23 of the first 61 sessions ended that way, silently; the parser now shows those as a generic "didn't record why" card. Skills load from ~/.claude/skills via ~/.pi/agent/settings.json; pi reads the repo CLAUDE.md natively.

Files

  • cli.mjs — the runner (arg parsing, EVOX2 wake, pi spawn, transcript writer).
  • extensions/folder-permissions.ts — the permission gate.
  • test/cli.test.mjs — the runner against a fake pi (node --test runner/test/cli.test.mjs).
  • Env knobs: PI_BIN, PI_RUNNER_ROOT, PI_MODELS_FILE, RUNNER_DEFAULT_MODEL, RUNNER_PERM_EXT, RUNNER_ENV_FILE, RUNNER_AUTO_CONTINUES, EVOX2_URL/EVOX2_MAC/EVOX2_BCAST, and on the sidecar side RUNNER_BIN, SIDECAR_PI_MODEL.

Setup (already done on this host)

cd ~/projects/ai-agent/runner && npm ci --ignore-scripts
# ~/.pi/agent/models.json     — evox2 + evox2-inkling providers (llm-server's LLAMA_API_KEY inside)
# ~/.pi/agent/settings.json   — {"skills": ["~/.claude/skills"]}
# OPENROUTER_API_KEY          — in ~/homelab/.env.claude