--verify (read-only, the default) rewrites every lab transcript and its hub archive copy in a temp dir and parses both with this tree's backend: with no fix the copy must parse exactly like the original (summary, full, chunked); each fix alone lists the parse paths it changes. --dry-run, --apply (skips a session with a live run, a file modified in the last 10 min or one that changes meanwhile; originals to ~/.cache/ai-agent/transcript-backups/ v1-rewrite-<date>/ with a manifest; mtime + 1 s), --restore (a file a run appended to since keeps its v1 tail behind a header), --prune (30 days). The workers' synced copies are left in the old format and counted: the FeedMirror syncs them by size, a rewrite here would be undone or corrupted. The v1 reader no longer times a call from a session event (a fact that changed, not what unblocked the call), so a session event keeps its time (the resource miner dates a worktree's branch with it); a converter's header takes the first moment it writes. A mirror that loaded a file in the old format re-checks its head before appending (it may have been rewritten). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
845 lines
39 KiB
JavaScript
Executable File
845 lines
39 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
||
/**
|
||
* pi-runner — run one headless pi (pi.dev) session and mirror it as a v1
|
||
* transcript (docs/transcript-format.md).
|
||
*
|
||
* The ai-agent sidecar launches this exactly like it launches `claude`:
|
||
*
|
||
* pi-runner -p <prompt> --session-id <uuid> [--model <id>]
|
||
* pi-runner -p <prompt> --resume <uuid> [--model <id>]
|
||
*
|
||
* It spawns `pi --mode json` (session persisted under SESSIONS_DIR keyed by the
|
||
* SAME uuid, so resume is just the same --session-id again) and translates pi's
|
||
* AgentSessionEvent stream into v1 events, appended live to
|
||
*
|
||
* ~/.pi-runner/transcripts/<cwd with / → ->/<uuid>.jsonl
|
||
*
|
||
* which the ai-agent container watches read-only (PI_TRANSCRIPTS_DIR mount).
|
||
* Each model step is written whole as soon as pi ends it (`message_end`):
|
||
* its `call`, its blocks, its `usage` — before its tools run, so a tool card
|
||
* shows while the tool works. A transcript written 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.
|
||
*
|
||
* Model → provider routing: whichever provider lists the id in
|
||
* ~/.pi/agent/models.json serves it — the EVOX2 LM Studio ("ggml-org/
|
||
* qwen3.8-27b") or llama.cpp box is woken over WoL first. An unlisted id falls
|
||
* back to its shape: a vendor prefix ("qwen/qwen3.8-27b") means OpenRouter.
|
||
* A --resume with no --model keeps the model the session last answered on.
|
||
*
|
||
* A failed model call (pi's `stopReason: "error"` + `errorMessage`), an EVOX2
|
||
* that never woke, or a pi that died before answering is written as an
|
||
* API-error call (`failed`, on the `<synthetic>` placeholder model, its
|
||
* `error`, the turn's end) — the viewer's red error card — never as a silent
|
||
* empty reply.
|
||
*/
|
||
import { spawn, execSync } from "node:child_process";
|
||
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync,
|
||
writeFileSync } from "node:fs";
|
||
import { createSocket } from "node:dgram";
|
||
import os from "node:os";
|
||
import path from "node:path";
|
||
import readline from "node:readline";
|
||
import { fileURLToPath } from "node:url";
|
||
|
||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||
const HOME = os.homedir();
|
||
const PI_BIN = process.env.PI_BIN || path.join(HERE, "node_modules", ".bin", "pi");
|
||
const RUNNER_ROOT = process.env.PI_RUNNER_ROOT || path.join(HOME, ".pi-runner");
|
||
const TRANSCRIPTS_DIR = path.join(RUNNER_ROOT, "transcripts");
|
||
const SESSIONS_DIR = path.join(RUNNER_ROOT, "sessions");
|
||
const ENV_FILE = process.env.RUNNER_ENV_FILE || path.join(HOME, "homelab", ".env.claude");
|
||
// The EVOX2's Inkling 2 Mini (llm-inkling, since 2026-11-23; Qwen 3.8 27B
|
||
// before) — free, and no key to expire. The sidecar names a model on every
|
||
// launch; this is for a run started by hand.
|
||
const DEFAULT_MODEL = process.env.RUNNER_DEFAULT_MODEL || "inkling-2-mini";
|
||
const PERM_EXT = process.env.RUNNER_PERM_EXT || path.join(HERE, "extensions", "folder-permissions.ts");
|
||
// What a run on a local (EVOX2) model is told on top of pi's prompt — small
|
||
// tool calls, big files in sections: it streams at ~17 tok/s and nothing shows
|
||
// until a call completes. Shared with the opencode harness (sidecar/opencode_cli.py).
|
||
const LOCAL_MODEL_GUIDE = process.env.SIDECAR_LOCAL_MODEL_GUIDE
|
||
|| path.join(HERE, "..", "sidecar", "local-model.md");
|
||
// The safety net behind pi's own compaction: how many times one run resumes
|
||
// itself after a reply a full context cut off (see `runPi`).
|
||
const AUTO_CONTINUES = Math.max(0, Number(process.env.RUNNER_AUTO_CONTINUES ?? 2) || 0);
|
||
const AUTO_CONTINUE_PROMPT = "Your last reply was cut off: the context window filled up, "
|
||
+ "and the conversation has been compacted since (the summary above). Carry on with the "
|
||
+ "task from where you stopped — if you were writing a file, check what is on disk first.";
|
||
// pi's own provider registry. Whichever provider lists a model id here is the
|
||
// one that serves it — see `resolveProvider`.
|
||
const PI_MODELS_FILE = process.env.PI_MODELS_FILE
|
||
|| path.join(HOME, ".pi", "agent", "models.json");
|
||
// EVOX2 wake config — used only for the local providers. The probe hits the
|
||
// provider's own `baseUrl` (models.json); EVOX2_URL is the fallback when it has none.
|
||
const EVOX2_URL = process.env.EVOX2_URL || "http://100.93.171.39:1234";
|
||
const EVOX2_MAC = process.env.EVOX2_MAC || "84:47:09:77:48:b4";
|
||
const EVOX2_BCAST = process.env.EVOX2_BCAST || "192.168.1.255";
|
||
const WAKE_TIMEOUT_S = Number(process.env.WAKE_TIMEOUT || 150);
|
||
|
||
// pi's thinking scale. The sidecar speaks each harness's own vocabulary, so it
|
||
// sends us `off` — but it drives both CLIs with one flag shape, so accept the
|
||
// claude spelling too rather than choke on it. Anything else is dropped: an
|
||
// unrecognised level would make `pi` exit 2 before the session even starts.
|
||
const PI_THINKING = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
||
const THINKING_ALIASES = { disabled: "off" };
|
||
|
||
function thinkingLevel(raw) {
|
||
const level = THINKING_ALIASES[raw] ?? raw;
|
||
return PI_THINKING.includes(level) ? level : null;
|
||
}
|
||
|
||
// ── args (claude-compatible flag shape, see sidecar.py) ─────────────────────
|
||
function parseArgs(argv) {
|
||
const a = { prompt: "", sessionId: null, resume: false, model: null, thinking: null,
|
||
forkFrom: null, cutLine: 0, cutUserOrd: 0, cutText: null,
|
||
lean: false, systemPrompt: null, tools: null, allow: null, read: null };
|
||
for (let i = 0; i < argv.length; i++) {
|
||
const v = argv[i];
|
||
if (v === "-p" || v === "--prompt") a.prompt = argv[++i] ?? "";
|
||
else if (v === "--session-id") a.sessionId = argv[++i];
|
||
else if (v === "--resume") { a.sessionId = argv[++i]; a.resume = true; }
|
||
else if (v === "--model") a.model = argv[++i];
|
||
else if (v === "--thinking") a.thinking = thinkingLevel(argv[++i]);
|
||
// fork: branch --fork-from's session at its --cut-user-ord'th user message
|
||
// (mirror sliced at raw line --cut-line), run under --session-id.
|
||
else if (v === "--fork-from") a.forkFrom = argv[++i];
|
||
else if (v === "--cut-line") a.cutLine = Number(argv[++i]) || 0;
|
||
else if (v === "--cut-user-ord") a.cutUserOrd = Number(argv[++i]) || 0;
|
||
else if (v === "--cut-text") a.cutText = argv[++i];
|
||
// a lean run (sidecar launch.py "lean runs"): the sidecar's short prompt,
|
||
// no skills / AGENTS.md / extensions, these tools, these programs.
|
||
else if (v === "--lean") a.lean = true;
|
||
else if (v === "--system-prompt") a.systemPrompt = argv[++i];
|
||
else if (v === "--tools") a.tools = argv[++i];
|
||
else if (v === "--allow") a.allow = argv[++i];
|
||
// a guest's job (sidecar "scoped pi run"): the only roots it may read
|
||
// (colon-separated) instead of the whole home directory.
|
||
else if (v === "--read") a.read = argv[++i];
|
||
// a guest's own run (sidecar "scoped pi run", not lean): none of the
|
||
// owner's skills / extensions / prompt templates, the scope's system
|
||
// prompt appended, reads narrowed by --read, writes inside the cwd.
|
||
else if (v === "--scoped") a.scoped = true;
|
||
else if (v === "--append-system-prompt") (a.append ??= []).push(argv[++i]);
|
||
// claude flags the sidecar may still pass — accepted and ignored:
|
||
else if (v === "--output-format" || v === "--permission-mode") i++;
|
||
else if (v === "--remote-control") continue;
|
||
else if (!v.startsWith("-") && !a.prompt) a.prompt = v;
|
||
}
|
||
return a;
|
||
}
|
||
|
||
function loadEnvFile(file) {
|
||
try {
|
||
for (const line of readFileSync(file, "utf8").split("\n")) {
|
||
const m = line.match(/^([A-Z0-9_]+)=(.*)$/);
|
||
if (m && !process.env[m[1]]) process.env[m[1]] = m[2];
|
||
}
|
||
} catch { /* no env file — rely on the process env */ }
|
||
}
|
||
|
||
// ── provider resolution ─────────────────────────────────────────────────────
|
||
/** Which provider serves `model` — a name from `~/.pi/agent/models.json`.
|
||
*
|
||
* The id's shape can't answer this on its own: LM Studio 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. pi needs a model listed under a
|
||
* provider to run it there at all, so that registry *is* the answer for every
|
||
* locally-served model. Anything it doesn't list falls back to the id shape,
|
||
* which keeps the whole OpenRouter catalogue runnable without registering
|
||
* several hundred ids by hand.
|
||
*/
|
||
function resolveProvider(model) {
|
||
try {
|
||
const cfg = JSON.parse(readFileSync(PI_MODELS_FILE, "utf8"));
|
||
for (const [name, p] of Object.entries(cfg.providers || {}))
|
||
if ((p.models || []).some((m) => m.id === model)) return name;
|
||
} catch { /* unreadable registry — fall back to the id shape */ }
|
||
return model.includes("/") ? "openrouter" : "evox2";
|
||
}
|
||
|
||
/** A local model's thinking level when the run names none: its models.json
|
||
* entry's `defaultThinking` (a key of ours pi ignores — Inkling 2 Mini:
|
||
* "medium", the level it was graded at), else "off". */
|
||
function localDefaultThinking(provider, model) {
|
||
try {
|
||
const cfg = JSON.parse(readFileSync(PI_MODELS_FILE, "utf8"));
|
||
const m = (cfg.providers?.[provider]?.models || []).find((x) => x.id === model);
|
||
const level = m?.defaultThinking ? thinkingLevel(m.defaultThinking) : null;
|
||
if (level) return level;
|
||
} catch { /* unreadable registry — off */ }
|
||
return "off";
|
||
}
|
||
|
||
/** The server root of a models.json provider (`baseUrl` minus `/v1`), or null. */
|
||
function providerRoot(provider) {
|
||
try {
|
||
const cfg = JSON.parse(readFileSync(PI_MODELS_FILE, "utf8"));
|
||
const url = cfg.providers?.[provider]?.baseUrl;
|
||
return url ? url.replace(/\/v1\/?$/, "") : null;
|
||
} catch { return null; }
|
||
}
|
||
|
||
// ── EVOX2 wake (local provider only) ────────────────────────────────────────
|
||
async function serverUp(root) {
|
||
try {
|
||
const r = await fetch(`${root}/v1/models`, {
|
||
signal: AbortSignal.timeout(4000),
|
||
headers: { Authorization: "Bearer x" }, // any reply (even 401) = awake
|
||
});
|
||
return r.status < 500;
|
||
} catch { return false; }
|
||
}
|
||
|
||
function sendWol() {
|
||
const mac = EVOX2_MAC.split(":").map((h) => parseInt(h, 16));
|
||
const packet = Buffer.alloc(102, 0xff);
|
||
for (let i = 6; i < 102; i += 6) Buffer.from(mac).copy(packet, i);
|
||
const sock = createSocket("udp4");
|
||
sock.bind(() => {
|
||
sock.setBroadcast(true);
|
||
sock.send(packet, 9, EVOX2_BCAST, () => sock.close());
|
||
});
|
||
}
|
||
|
||
async function ensureEvox2Awake(root) {
|
||
if (await serverUp(root)) return;
|
||
process.stderr.write("[pi-runner] EVOX2 asleep — sending WoL…\n");
|
||
const deadline = Date.now() + WAKE_TIMEOUT_S * 1000;
|
||
while (Date.now() < deadline) {
|
||
sendWol();
|
||
await new Promise((r) => setTimeout(r, 5000));
|
||
if (await serverUp(root)) return;
|
||
}
|
||
throw new Error(`EVOX2 model server unreachable after ${WAKE_TIMEOUT_S}s (${root})`);
|
||
}
|
||
|
||
// ── the v1 transcript writer ────────────────────────────────────────────────
|
||
const nowIso = () => new Date().toISOString();
|
||
|
||
/** pi built-in tool call → Claude-Code tool name + input shape.
|
||
*
|
||
* The viewer's tool cards, diffs and project tags read Claude Code's argument
|
||
* shapes (`file_path`, `old_string`…), so the runner translates pi's
|
||
* lowercase built-ins (`read`/`bash`/`edit`/… with `path`/`edits[]`) at write
|
||
* time; the Claude name then gives the neutral `tool` (`neutralTool`), pi's
|
||
* own name rides in `native`. Unknown (extension) tools pass through
|
||
* untouched — they render as generic tool cards, which is right. */
|
||
function mapToolCall(name, args) {
|
||
const a = args ?? {};
|
||
switch (name) {
|
||
case "read": {
|
||
const { path: file_path, ...rest } = a;
|
||
return { name: "Read", input: { file_path, ...rest } };
|
||
}
|
||
case "write": {
|
||
const { path: file_path, ...rest } = a;
|
||
return { name: "Write", input: { file_path, ...rest } };
|
||
}
|
||
case "edit": {
|
||
// pi edit is multi-edit natively: {path, edits:[{oldText,newText}]}.
|
||
const edits = (a.edits ?? []).map((e) => ({
|
||
old_string: e?.oldText ?? "",
|
||
new_string: e?.newText ?? "",
|
||
}));
|
||
if (edits.length === 1)
|
||
return { name: "Edit", input: { file_path: a.path, ...edits[0] } };
|
||
return { name: "MultiEdit", input: { file_path: a.path, edits } };
|
||
}
|
||
case "bash": {
|
||
const { timeout, ...rest } = a;
|
||
// pi timeout is seconds; Claude's Bash carries milliseconds.
|
||
return { name: "Bash", input: {
|
||
...rest, ...(typeof timeout === "number" ? { timeout: timeout * 1000 } : {}),
|
||
} };
|
||
}
|
||
case "grep":
|
||
return { name: "Grep", input: { ...a, ...(a.caseInsensitive ? { "-i": true } : {}) } };
|
||
case "find":
|
||
return { name: "Glob", input: a };
|
||
case "ls":
|
||
return { name: "LS", input: a };
|
||
default:
|
||
return { name, input: a };
|
||
}
|
||
}
|
||
|
||
// The hub's neutral tool names (backend/conversations/parse/readers/toolnames.py,
|
||
// the Claude Code column): what a call `mapToolCall` shaped as Claude's is.
|
||
const NEUTRAL = { Read: "read", Write: "write", Edit: "edit", MultiEdit: "edit", Bash: "shell",
|
||
Grep: "grep", Glob: "glob", LS: "list_dir" };
|
||
|
||
function neutralTool(claudeName, native) {
|
||
if (NEUTRAL[claudeName]) return NEUTRAL[claudeName];
|
||
if (String(claudeName).startsWith("mcp_")) return claudeName; // an MCP tool keeps its name
|
||
return `pi:${native}`;
|
||
}
|
||
|
||
function gitBranch(cwd) {
|
||
try {
|
||
return execSync("git rev-parse --abbrev-ref HEAD", {
|
||
cwd, stdio: ["ignore", "pipe", "ignore"],
|
||
}).toString().trim() || null;
|
||
} catch { return null; }
|
||
}
|
||
|
||
/** pi's `errorMessage` → the error's class in the claude CLI's vocabulary
|
||
* (`rate_limit`…) plus the runner's own (`invalid_api_key`, `context_exceeded`,
|
||
* `network_error`) — `errorKind` below maps both to the v1 error kinds. A
|
||
* provider's JSON body ("401: {\"message\":\"API key expired.\"…}") is
|
||
* reduced to its message. */
|
||
function errorField(raw) {
|
||
if (/\b(401|403)\b|api.?key|user not found|unauthori[sz]ed|invalid.?token|forbidden/i.test(raw))
|
||
return "invalid_api_key";
|
||
if (/context (size|length|window)|maximum context|too many tokens|prompt is too long/i.test(raw))
|
||
return "context_exceeded";
|
||
if (/\b429\b|rate.?limit|quota/i.test(raw)) return "rate_limit";
|
||
if (/^\s*5\d\d\b|overloaded|server error|internal error/i.test(raw)) return "server_error";
|
||
if (/terminated|connection|ECONN|ETIMEDOUT|EHOSTUNREACH|fetch failed|socket|network|timed? ?out/i
|
||
.test(raw)) return "network_error";
|
||
return "unknown";
|
||
}
|
||
|
||
// The hub's API-error kinds (backend/conversations/parse/errors.py): the
|
||
// class first, else the wording.
|
||
const ERROR_FIELD = { authentication_failed: "auth", rate_limit: "rate_limit",
|
||
server_error: "overloaded", overloaded: "overloaded",
|
||
invalid_api_key: "api_key", context_exceeded: "context",
|
||
network_error: "network" };
|
||
const ERROR_TEXT = [
|
||
["api_key", /api key (expired|revoked)|key expired|user not found/i],
|
||
["auth", /not logged in|please run \/login|failed to authenticate|oauth.*(expired|revoked|refresh)|invalid api key/i],
|
||
["rate_limit", /session limit|usage limit|rate.?limit|weekly limit/i],
|
||
["cli_outdated", /does not support this model|newer is required|claude update/i],
|
||
["context", /context (size|length|window)\b.{0,40}(exceed|too)|maximum context length|prompt is too long/i],
|
||
["network", /connection (lost|error|refused)|ECONNRESET|ETIMEDOUT|fetch failed/i],
|
||
["overloaded", /overloaded|API Error: 5\d\d/i],
|
||
];
|
||
|
||
function errorKind(field, text) {
|
||
if (ERROR_FIELD[field]) return ERROR_FIELD[field];
|
||
for (const [kind, rx] of ERROR_TEXT) if (rx.test(text || "")) return kind;
|
||
return "unknown";
|
||
}
|
||
|
||
function describeError(msg) {
|
||
let raw = String(msg.errorMessage ?? "").trim() || "the model call failed (no error message)";
|
||
const m = raw.match(/^(\d{3}):?\s*(\{[\s\S]*\})\s*$/);
|
||
if (m) {
|
||
try {
|
||
const body = JSON.parse(m[2]);
|
||
const detail = body?.message ?? body?.error?.message ?? body?.error;
|
||
if (typeof detail === "string" && detail) raw = `${m[1]} ${detail}`;
|
||
} catch { /* not JSON after all — keep it whole */ }
|
||
}
|
||
if (raw === "terminated") raw = "terminated — the model server closed the stream";
|
||
const where = [msg.provider, msg.model].filter(Boolean).join(" · ");
|
||
return { error: errorField(raw), text: `API Error${where ? ` (${where})` : ""}: ${raw.slice(0, 600)}` };
|
||
}
|
||
|
||
// What a message the user (or the hub on their behalf) sent is, the way the
|
||
// hub's reader of the old format read it (sidecar/transcript_v1.py
|
||
// `prompt_events`): the inbox note and the author tag unwrapped, the
|
||
// interrupt marker a `turn_end`, anything else in `<…>` context.
|
||
const INBOX_RE = /^(?:Another Claude session sent a message[^:\n]*:\s*\n)?\[(?:Follow-up from your user|Message from the ai-agent hub)[^\]]*\]\s*\n+([\s\S]*?)(?:\n\n+This came from another Claude session\b[\s\S]*)?$/;
|
||
const AUTHOR_RE = /^<ai-agent-from user="([^"]*)" name="([^"]*)" role="([^"]*)"\s*\/>\s*\n?/;
|
||
const NO_RESPONSE_RE = /^\s*No response requested\.?\s*$/;
|
||
|
||
function promptEvents(text) {
|
||
let c = typeof text === "string" ? text : "";
|
||
let origin = "user";
|
||
const inbox = c.match(INBOX_RE);
|
||
if (inbox && inbox[1].trim() !== c) { origin = "inbox"; c = inbox[1].trim(); }
|
||
let author = null;
|
||
const a = c.match(AUTHOR_RE);
|
||
if (a) { author = { id: a[1], name: a[2], role: a[3] }; c = c.slice(a[0].length); }
|
||
if (/^\s*\[Request interrupted by user/.test(c)) return [{ t: "turn_end", reason: "interrupted" }];
|
||
if (c.trim() && !c.startsWith("<"))
|
||
return [{ t: "prompt", text: c, origin, ...(author ? { author } : {}) }];
|
||
if (c.trimStart().startsWith("<command-")) {
|
||
const name = c.match(/<command-name>\/?([^<\s]+)\s*<\/command-name>/);
|
||
const args = c.match(/<command-args>([\s\S]*?)<\/command-args>/);
|
||
return [{ t: "inject", kind: "command", text: c,
|
||
...(name ? { name: name[1], args: args ? args[1].trim() : "" } : {}) }];
|
||
}
|
||
return [{ t: "inject", kind: c.trimStart().startsWith("<system-reminder>") ? "reminder" : "note",
|
||
text: c }];
|
||
}
|
||
|
||
// Fields that say nothing (null, a false flag, a zero token count) are left
|
||
// out of a line: the hub reads them as absent (sidecar/transcript_v1.py).
|
||
const FALSE_FLAGS = { call: ["virtual", "failed", "empty"], text: ["paused"] };
|
||
const ZERO_TOKENS = ["cacheRead", "cacheWrite5m", "cacheWrite1h", "cacheWrite", "reasoning"];
|
||
|
||
function line(ev) {
|
||
const flags = FALSE_FLAGS[ev.t] ?? [];
|
||
const out = {};
|
||
for (const [k, v] of Object.entries(ev)) {
|
||
if (v === undefined || v === null) continue;
|
||
if (flags.includes(k) && v === false) continue;
|
||
if (ev.t === "usage" && ZERO_TOKENS.includes(k) && v === 0) continue;
|
||
out[k] = v;
|
||
}
|
||
return JSON.stringify(out);
|
||
}
|
||
|
||
class TranscriptWriter {
|
||
constructor(sessionId, cwd) {
|
||
this.sessionId = sessionId;
|
||
this.cwd = cwd;
|
||
this.branch = gitBranch(cwd);
|
||
const encoded = cwd.replaceAll("/", "-");
|
||
const dir = path.join(TRANSCRIPTS_DIR, encoded);
|
||
mkdirSync(dir, { recursive: true });
|
||
this.file = path.join(dir, `${sessionId}.jsonl`);
|
||
this.opened = false;
|
||
}
|
||
|
||
/** What the file already holds: nothing (a header first), the old format
|
||
* (a v1 header before the first v1 line), or v1 — and the cwd / branch it
|
||
* last said. */
|
||
open() {
|
||
if (this.opened) return;
|
||
this.opened = true;
|
||
this.needHeader = true;
|
||
this.facts = {};
|
||
let text = "";
|
||
try { text = readFileSync(this.file, "utf8"); } catch { return; }
|
||
let first = true;
|
||
for (const l of text.split("\n")) {
|
||
let o; try { o = JSON.parse(l); } catch { continue; }
|
||
if (!o || typeof o !== "object") continue;
|
||
const v1 = "t" in o && "v" in o;
|
||
if (first) { this.needHeader = !v1; first = false; } else if (v1) this.needHeader = false;
|
||
if (o.t === "session") {
|
||
if ("cwd" in o) this.facts.cwd = o.cwd;
|
||
if ("branch" in o) this.facts.branch = o.branch;
|
||
} else if (!("t" in o)) {
|
||
if ("cwd" in o) this.facts.cwd = o.cwd;
|
||
if ("gitBranch" in o) this.facts.branch = o.gitBranch;
|
||
}
|
||
}
|
||
}
|
||
|
||
/** Append one group of events, all at this moment. */
|
||
emit(events) {
|
||
this.open();
|
||
const at = nowIso();
|
||
const lines = [];
|
||
if (this.needHeader) {
|
||
lines.push(line({ t: "session", at, v: 1, id: this.sessionId, harness: "pi",
|
||
cwd: this.cwd, branch: this.branch }));
|
||
this.needHeader = false;
|
||
this.facts = { cwd: this.cwd, branch: this.branch };
|
||
} else {
|
||
const moved = {};
|
||
if (this.cwd && this.facts.cwd !== this.cwd) moved.cwd = this.cwd;
|
||
if (this.branch && this.facts.branch !== this.branch) moved.branch = this.branch;
|
||
if (Object.keys(moved).length) {
|
||
lines.push(line({ t: "session", at, ...moved }));
|
||
Object.assign(this.facts, moved);
|
||
}
|
||
}
|
||
for (const ev of events) lines.push(line({ t: ev.t, at, ...ev }));
|
||
appendFileSync(this.file, lines.join("\n") + "\n");
|
||
}
|
||
|
||
user(content) {
|
||
this.emit(promptEvents(content));
|
||
}
|
||
|
||
/** A failed model call: a `failed` call on the `<synthetic>` placeholder
|
||
* (it reached no model, so it never becomes one the conversation ran
|
||
* on), its error — `field` typing it — a zero usage, and the turn's end:
|
||
* what the hub makes of Claude Code's own API-error turn. */
|
||
apiError(field, text) {
|
||
this.answered = true;
|
||
this.emit([{ t: "call", model: "<synthetic>", failed: true },
|
||
{ t: "error", kind: errorKind(field, text), text },
|
||
{ t: "usage", input: 0, output: 0 },
|
||
{ t: "turn_end", reason: "error" }]);
|
||
}
|
||
|
||
/** The turn is over — what Claude Code's own `stop_hook_summary` /
|
||
* `turn_duration` records say; the viewer reads a trailing one as the
|
||
* conversation having finished (no DONE needed). Once per turn. */
|
||
turnEnd() {
|
||
if (this.ended) return;
|
||
this.ended = true;
|
||
this.emit([{ t: "turn_end", reason: "done" }]);
|
||
}
|
||
|
||
/** A pi compaction: the boundary (the viewer's "auto-compacted · 98k →
|
||
* 21k" divider) then the summary the run goes on from, the divider's
|
||
* text. `result` is pi's `compaction_end` result. */
|
||
compaction(reason, result, durationMs) {
|
||
const n = (v) => (Number.isFinite(v) ? v : null);
|
||
this.emit([{ t: "compact", trigger: reason === "manual" ? "manual" : "auto",
|
||
preTokens: n(result.tokensBefore), postTokens: n(result.estimatedTokensAfter),
|
||
durationMs: n(durationMs) }]);
|
||
if (result.summary)
|
||
this.emit([{ t: "inject", kind: "compact_summary", text: compactSummaryText(result.summary) }]);
|
||
}
|
||
|
||
/** The prompt an auto-continue sends: kept in the transcript for the
|
||
* record, as context the viewer doesn't show as a turn — the compaction
|
||
* divider just above already says what happened. */
|
||
autoContinue(text) {
|
||
this.emit([{ t: "inject", kind: "note",
|
||
text: `<pi-runner-auto-continue>\n${text}\n</pi-runner-auto-continue>` }]);
|
||
}
|
||
|
||
/** A pi assistant message → one whole step: the call, its blocks, its
|
||
* usage. Splits any inline `<think>…</think>` (the LM Studio path) into
|
||
* thinking blocks. */
|
||
assistant(msg) {
|
||
const blocks = [];
|
||
let raw = 0; // the message's blocks, empty ones included
|
||
for (const b of msg.content ?? []) {
|
||
if (!b || typeof b !== "object") continue;
|
||
if (b.type === "text") {
|
||
const rest = b.text ?? "";
|
||
const think = /<think>([\s\S]*?)<\/think>/g;
|
||
let m; let cursor = 0;
|
||
const part = (tx) => { raw++; blocks.push(NO_RESPONSE_RE.test(tx)
|
||
? { t: "text", text: tx, paused: true } : { t: "text", text: tx }); };
|
||
while ((m = think.exec(rest))) {
|
||
if (rest.slice(cursor, m.index).trim()) part(rest.slice(cursor, m.index));
|
||
if (m[1].trim()) { raw++; blocks.push({ t: "thinking", text: m[1] }); }
|
||
cursor = m.index + m[0].length;
|
||
}
|
||
if (rest.slice(cursor).trim()) part(rest.slice(cursor));
|
||
} else if (b.type === "thinking") {
|
||
raw++;
|
||
if ((b.thinking ?? "").trim()) blocks.push({ t: "thinking", text: b.thinking });
|
||
} else if (b.type === "toolCall") {
|
||
raw++;
|
||
const mapped = mapToolCall(b.name, b.arguments);
|
||
blocks.push({ t: "tool_call", id: String(b.id), tool: neutralTool(mapped.name, b.name),
|
||
native: b.name, input: mapped.input });
|
||
}
|
||
}
|
||
const u = msg.usage ?? {};
|
||
const failed = msg.stopReason === "error";
|
||
// A failed call's empty shell (no content, no tokens) says nothing the
|
||
// error call below doesn't; whatever it did stream before failing stays.
|
||
if (raw || u.input || u.output || !failed) this.emit([
|
||
{ t: "call", model: msg.model, empty: !raw },
|
||
...blocks,
|
||
{ t: "usage", input: u.input ?? 0, output: u.output ?? 0, cacheRead: u.cacheRead ?? 0,
|
||
cacheWrite: u.cacheWrite ?? 0,
|
||
// pi computes the real provider cost per message (0 for the free
|
||
// local EVOX2 provider) — the hub takes it over its own price table.
|
||
// Left out when pi reports none, so the hub's estimate kicks in.
|
||
...(typeof u.cost?.total === "number" ? { cost: { usd: u.cost.total, source: "provider" } } : {}) },
|
||
]);
|
||
this.answered = true;
|
||
// Held until pi settles: a retryable failure (a dropped stream, a 5xx)
|
||
// is retried with backoff (`auto_retry_start` drops it), and only the
|
||
// attempt that stays failed becomes the error card.
|
||
if (failed) this.pendingError = describeError(msg);
|
||
}
|
||
|
||
/** Write the held error call, if the failure stood. */
|
||
flushError() {
|
||
const e = this.pendingError;
|
||
this.pendingError = null;
|
||
if (e) this.apiError(e.error, e.text);
|
||
}
|
||
|
||
toolResult(msg) {
|
||
// Text survives; image blocks (vision `read`) become a placeholder — the
|
||
// viewer previews images from the Read card's file_path, not the result.
|
||
const text = (msg.content ?? [])
|
||
.map((b) => (b && b.type === "text" ? b.text : b?.type === "image" ? "[image]" : ""))
|
||
.filter(Boolean).join("\n");
|
||
this.emit([{ t: "tool_result", toolCall: String(msg.toolCallId), ok: !msg.isError, text }]);
|
||
}
|
||
}
|
||
|
||
/** A compaction's summary as the divider shows it (the hub's
|
||
* `_compact_summary_text`): reminders and a "Summary:" lead dropped. */
|
||
function compactSummaryText(text) {
|
||
return String(text ?? "").replace(/^This session is being continued from a previous conversation[\s\S]*?\n\n/, "")
|
||
.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g, "").trim().replace(/^Summary:\s*/, "");
|
||
}
|
||
|
||
// ── fork: branch a session at a user message ────────────────────────────────
|
||
const collapse = (s) => (s || "").split(/\s+/).filter(Boolean).join(" ");
|
||
|
||
function findSessionFile(sid) {
|
||
// pi names session files <timestamp>_<sessionId>.jsonl and resolves
|
||
// --session-id by scanning the session dir, so we match the same way.
|
||
try {
|
||
for (const f of readdirSync(SESSIONS_DIR))
|
||
if (f.endsWith(`_${sid}.jsonl`)) return path.join(SESSIONS_DIR, f);
|
||
} catch { /* no sessions dir yet */ }
|
||
return null;
|
||
}
|
||
|
||
/** The model a session last answered on (an assistant message that neither
|
||
* errored nor was aborted), else its last `model_change` — what a --resume
|
||
* with no --model keeps. Mirrors the sidecar's pi_runs.session_model. */
|
||
function sessionModel(sid) {
|
||
const file = findSessionFile(sid);
|
||
if (!file) return null;
|
||
let answered = null, changed = null;
|
||
for (const line of readFileSync(file, "utf8").split("\n")) {
|
||
let o; try { o = JSON.parse(line); } catch { continue; }
|
||
if (o?.type === "model_change" && o.modelId) changed = o.modelId;
|
||
const m = o?.type === "message" ? o.message : null;
|
||
if (m?.role === "assistant" && m.model && !["error", "aborted"].includes(m.stopReason))
|
||
answered = m.model;
|
||
}
|
||
return answered || changed;
|
||
}
|
||
|
||
function findMirrorFile(sid) {
|
||
try {
|
||
for (const dir of readdirSync(TRANSCRIPTS_DIR)) {
|
||
const p = path.join(TRANSCRIPTS_DIR, dir, `${sid}.jsonl`);
|
||
if (existsSync(p)) return p;
|
||
}
|
||
} catch { /* no transcripts dir yet */ }
|
||
return null;
|
||
}
|
||
|
||
function entryTexts(msg) {
|
||
const c = msg?.content;
|
||
if (typeof c === "string") return [c];
|
||
if (Array.isArray(c))
|
||
return c.filter((b) => b?.type === "text").map((b) => b.text ?? "");
|
||
return [];
|
||
}
|
||
|
||
/** Branch a pi session at a user message. pi sessions are trees of
|
||
* id/parentId entries, but a headless runner session is a linear chain — so
|
||
* the branch is simply the entries strictly before user message
|
||
* #cutUserOrd, written under a fresh session id (header rewritten, entry ids
|
||
* kept). Resuming that id then continues from the fork point. Also writes
|
||
* the truncated CC-schema mirror (source mirror's first cutLine lines under
|
||
* the new id) so the viewer shows the inherited history. */
|
||
function forkSession(args) {
|
||
const src = findSessionFile(args.forkFrom);
|
||
if (!src) throw new Error(`source pi session not found: ${args.forkFrom}`);
|
||
const kept = [];
|
||
let userSeen = 0, found = false;
|
||
for (const line of readFileSync(src, "utf8").split("\n")) {
|
||
if (!line.trim()) continue;
|
||
let o; try { o = JSON.parse(line); } catch { continue; }
|
||
if (o.type === "session") {
|
||
kept.push({ ...o, id: args.sessionId, timestamp: nowIso() });
|
||
continue;
|
||
}
|
||
if (o.type === "message" && o.message?.role === "user") {
|
||
if (userSeen === args.cutUserOrd) {
|
||
if (args.cutText) {
|
||
const want = collapse(args.cutText);
|
||
if (!entryTexts(o.message)
|
||
.some((t) => collapse(t).slice(0, want.length) === want))
|
||
throw new Error("fork point mismatch: the pi session diverged "
|
||
+ "from the transcript the viewer showed");
|
||
}
|
||
found = true;
|
||
break;
|
||
}
|
||
userSeen++;
|
||
}
|
||
kept.push(o);
|
||
}
|
||
if (!found)
|
||
throw new Error(`fork point not found: user message #${args.cutUserOrd} `
|
||
+ `(session has ${userSeen})`);
|
||
const stamp = nowIso().replaceAll(":", "-").replace(".", "-");
|
||
writeFileSync(path.join(SESSIONS_DIR, `${stamp}_${args.sessionId}.jsonl`),
|
||
kept.map((o) => JSON.stringify(o)).join("\n") + "\n");
|
||
|
||
// The viewer-facing mirror: same prefix, new session id. Written
|
||
// to the path the live TranscriptWriter will append to. A purged mirror
|
||
// only loses the *displayed* history — pi's context is intact — so warn.
|
||
const mirror = findMirrorFile(args.forkFrom);
|
||
if (mirror && args.cutLine > 0) {
|
||
const out = readFileSync(mirror, "utf8").split("\n")
|
||
.slice(0, args.cutLine).map((l) => {
|
||
try {
|
||
const o = JSON.parse(l);
|
||
if (o.sessionId) o.sessionId = args.sessionId; // the old format
|
||
if (o.t === "session" && o.id) o.id = args.sessionId; // v1
|
||
return JSON.stringify(o);
|
||
} catch { return l; }
|
||
});
|
||
const w = new TranscriptWriter(args.sessionId, process.cwd());
|
||
writeFileSync(w.file, out.join("\n") + "\n");
|
||
} else {
|
||
process.stderr.write("[pi-runner] fork: source mirror transcript missing "
|
||
+ "— forked conversation starts without visible history\n");
|
||
}
|
||
}
|
||
|
||
// ── main ────────────────────────────────────────────────────────────────────
|
||
async function main() {
|
||
const args = parseArgs(process.argv.slice(2));
|
||
if (!args.prompt.trim()) { console.error("pi-runner: empty prompt"); process.exit(2); }
|
||
if (!args.sessionId) { console.error("pi-runner: --session-id/--resume required"); process.exit(2); }
|
||
|
||
loadEnvFile(ENV_FILE);
|
||
const model = args.model || (args.resume && sessionModel(args.sessionId)) || DEFAULT_MODEL;
|
||
const provider = resolveProvider(model);
|
||
if (provider === "openrouter" && !process.env.OPENROUTER_API_KEY)
|
||
{ console.error("pi-runner: OPENROUTER_API_KEY not set (env or " + ENV_FILE + ")"); process.exit(2); }
|
||
// Every EVOX2-hosted provider (`evox2` = the box's llm-server) lives on the
|
||
// same box, so any of them means: wake it first.
|
||
const local = provider.startsWith("evox2");
|
||
|
||
const cwd = process.cwd();
|
||
mkdirSync(SESSIONS_DIR, { recursive: true });
|
||
if (args.forkFrom) forkSession(args); // before the writer appends the prompt
|
||
// The prompt goes into the transcript before the (up to 150 s) wake, so a
|
||
// box that never wakes leaves the message and why — not nothing at all.
|
||
const writer = new TranscriptWriter(args.sessionId, cwd);
|
||
writer.user(args.prompt);
|
||
if (local) {
|
||
try {
|
||
await ensureEvox2Awake(providerRoot(provider) || EVOX2_URL);
|
||
} catch (e) {
|
||
writer.apiError("network_error", `API Error (${provider} · ${model}): ${e.message ?? e}`);
|
||
writer.turnEnd();
|
||
throw e;
|
||
}
|
||
}
|
||
|
||
const piArgs = [
|
||
"--mode", "json", "-p",
|
||
"--session-dir", SESSIONS_DIR,
|
||
"--session-id", args.sessionId,
|
||
"--provider", provider,
|
||
"--model", model,
|
||
];
|
||
// Unset ⇒ pi's own default level — except on the EVOX2, where reasoning runs
|
||
// at local speed (Qwen 3.8 spent 25–30 min on single 10–13k-token thinking
|
||
// bursts): a local run thinks only when it asks to, or at its model's own
|
||
// `defaultThinking` (Inkling: medium — it thinks half as much as Qwen).
|
||
const thinking = args.thinking ?? (local ? localDefaultThinking(provider, model) : null);
|
||
if (thinking) piArgs.push("--thinking", thinking);
|
||
if (args.lean) {
|
||
// Only what the job says: no skills catalogue, no AGENTS.md/CLAUDE.md
|
||
// (~10k tokens in ~/homelab), no discovered extensions — the permissions
|
||
// one below is loaded explicitly and still applies.
|
||
piArgs.push("--no-skills", "--no-context-files", "--no-extensions", "--no-prompt-templates");
|
||
if (args.systemPrompt) piArgs.push("--system-prompt", args.systemPrompt);
|
||
if (args.tools) piArgs.push("--tools", args.tools);
|
||
} else {
|
||
if (args.scoped) piArgs.push("--no-skills", "--no-extensions", "--no-prompt-templates");
|
||
if (args.tools) piArgs.push("--tools", args.tools);
|
||
if (local && existsSync(LOCAL_MODEL_GUIDE)) piArgs.push("--append-system-prompt", LOCAL_MODEL_GUIDE);
|
||
}
|
||
for (const text of args.append ?? []) piArgs.push("--append-system-prompt", text);
|
||
if (existsSync(PERM_EXT)) piArgs.push("-e", PERM_EXT);
|
||
|
||
let interrupted = false;
|
||
const onSignal = () => { interrupted = true; }; // pi shares our process group
|
||
process.on("SIGINT", onSignal);
|
||
process.on("SIGTERM", onSignal);
|
||
const env = { ...process.env, PI_PERM_SCOPE: process.env.PI_PERM_SCOPE || cwd,
|
||
...(args.allow ? { PI_ALLOW_CMDS: args.allow } : {}),
|
||
...(args.read ? { PI_PERM_READ: args.read } : {}) };
|
||
|
||
// pi resumes a session from its --session-id, so an auto-continue is the
|
||
// same command with the continue prompt in place of the user's.
|
||
let prompt = args.prompt;
|
||
for (let continues = 0; ; continues++) {
|
||
const mayContinue = () => continues < AUTO_CONTINUES && !interrupted;
|
||
const { code, signal, cutOff } = await runPi([...piArgs, prompt], { cwd, env, writer, mayContinue });
|
||
if (interrupted || signal === "SIGINT" || signal === "SIGTERM") {
|
||
writer.user("[Request interrupted by user]");
|
||
process.exit(code ?? (signal ? 130 : 0));
|
||
}
|
||
if (cutOff && !code && mayContinue()) {
|
||
writer.autoContinue(AUTO_CONTINUE_PROMPT);
|
||
prompt = AUTO_CONTINUE_PROMPT;
|
||
continue;
|
||
}
|
||
writer.flushError();
|
||
// pi died before a single message: say so rather than end on the prompt.
|
||
if (code && !writer.answered)
|
||
writer.apiError("unknown", `API Error (${provider} · ${model}): pi exited with code ${code} `
|
||
+ "before answering — its stderr is in the run log");
|
||
writer.turnEnd(); // a pi without `agent_settled`, or one that died
|
||
process.exit(code ?? (signal ? 130 : 0));
|
||
}
|
||
}
|
||
|
||
/** One `pi --mode json` process, its events mirrored into `writer`. Resolves
|
||
* once it has exited and its stdout is drained, with `cutOff`: its last reply
|
||
* stopped on the output limit (`length`) and a compaction succeeded after it
|
||
* — what a full context looks like: pi caps each reply at the room left in
|
||
* the window less a 4,096-token margin (pi-ai `clampMaxTokensToContext`), so
|
||
* near the end it asks for 1 token and the reply stops at `length`. That is
|
||
* no overflow error, so pi's own compact-and-retry never fires; it compacts
|
||
* once the run is over and stops there (2026-11-24, 127k of 131k). The
|
||
* session is small again then, and a "continue" picks the task up. */
|
||
function runPi(piArgs, { cwd, env, writer, mayContinue }) {
|
||
return new Promise((resolve) => {
|
||
const child = spawn(PI_BIN, piArgs, { cwd, stdio: ["ignore", "pipe", "inherit"], env });
|
||
let last = null, compactedAfterLast = false, compactStart = null;
|
||
const cutOff = () => last?.stopReason === "length" && compactedAfterLast;
|
||
|
||
const rl = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
|
||
rl.on("line", (line) => {
|
||
let e; try { e = JSON.parse(line); } catch { return; }
|
||
// pi's own end of the run: no retry, compaction or queued prompt to
|
||
// come — the turn is over, unless the runner continues it.
|
||
if (e.type === "agent_settled") {
|
||
writer.flushError();
|
||
if (!(cutOff() && mayContinue())) writer.turnEnd();
|
||
return;
|
||
}
|
||
// The failed attempt is being retried: it was not the answer.
|
||
if (e.type === "auto_retry_start") { writer.pendingError = null; return; }
|
||
// pi ≥ 0.84.4 compacts mid-run, before the request that would cross
|
||
// the threshold (`compaction.reserveTokens`, ~/.pi/agent/settings.json).
|
||
if (e.type === "compaction_start") { compactStart = Date.now(); return; }
|
||
if (e.type === "compaction_end") {
|
||
if (e.result && !e.aborted) {
|
||
compactedAfterLast = true;
|
||
try {
|
||
writer.compaction(e.reason, e.result, compactStart ? Date.now() - compactStart : null);
|
||
} catch (err) {
|
||
process.stderr.write(`[pi-runner] transcript write failed: ${err}\n`);
|
||
}
|
||
}
|
||
compactStart = null;
|
||
return;
|
||
}
|
||
if (e.type !== "message_end" || !e.message) return;
|
||
const role = e.message.role;
|
||
if (role === "assistant") { last = e.message; compactedAfterLast = false; }
|
||
try {
|
||
writer.flushError(); // a failure pi moved on from without a retry
|
||
if (role === "assistant") writer.assistant(e.message);
|
||
else if (role === "toolResult") writer.toolResult(e.message);
|
||
// role === "user" is the prompt we already recorded ourselves.
|
||
} catch (err) {
|
||
process.stderr.write(`[pi-runner] transcript write failed: ${err}\n`);
|
||
}
|
||
});
|
||
|
||
// 'exit' can beat the last stdout lines (a run that fails in 0.3 s): finish
|
||
// once readline has drained them, or 2 s on if a grandchild holds the pipe.
|
||
let drained = false;
|
||
rl.on("close", () => { drained = true; });
|
||
child.on("exit", (code, signal) => {
|
||
let done = false;
|
||
const finish = () => {
|
||
if (done) return;
|
||
done = true;
|
||
resolve({ code, signal, cutOff: cutOff() });
|
||
};
|
||
if (drained) return finish();
|
||
rl.once("close", finish);
|
||
setTimeout(finish, 2000);
|
||
});
|
||
});
|
||
}
|
||
|
||
main().catch((e) => { console.error(`pi-runner: ${e.message ?? e}`); process.exit(1); });
|