From a70c69dc9f010239bd5aaa33459c6d749cf3ee79 Mon Sep 17 00:00:00 2001 From: haojr Date: Tue, 1 Dec 2026 16:28:44 +0000 Subject: [PATCH] feat: Pi 1.7.0 harness row with settings writer and log parser - pi row (@earendil-works/pi-coding-agent 1.7.0): pi --mode json -p --no-approve --offline --session-id {session_id} for launch and resume, PI_CODING_AGENT_DIR=/agent, provider-table logins (deepseek and openrouter both list pi), --append-system-prompt for bots, --model and --thinking - ConfigFile::Pi writes agent/settings.json (defaultProvider and defaultModel of the first held provider, no key) - LogFormat::Pi: per-run usage from assistant message_end (provider/model named in the log, Pi's cost), 401/402/429 failures from errorMessage, activity, and JSONL transcript retention (agent/sessions) - Pi exits 0 after a failed model call: LogFormat::exit_failure reads its failure on a zero exit too (task and bot runs) - Telegram: Set up Pi through the shared provider onboarding; tool buttons three a row - Fixtures captured from Pi 1.7.0 against a local mock provider Co-Authored-By: Claude Opus 5.5 --- crates/axe-core/src/activity.rs | 37 +- crates/axe-core/src/failure.rs | 50 ++- crates/axe-core/src/harness.rs | 114 ++++++ crates/axe-core/src/log_format.rs | 81 +++++ crates/axe-core/src/provider.rs | 5 +- crates/axe-core/src/retention.rs | 49 +++ crates/axe-core/src/runtime.rs | 51 +++ crates/axe-core/src/runtime_views.rs | 3 +- crates/axe-core/src/usage.rs | 84 ++++- crates/axe-node/src/dispatch.rs | 8 +- crates/axe-node/src/dispatch/bots.rs | 7 +- crates/axe-telegram/src/telegram.rs | 53 ++- crates/axe/tests/config.rs | 8 +- .../axe/tests/fixtures/log-format/golden.json | 324 ++++++++++++++++++ crates/axe/tests/fixtures/pi/pi-401.jsonl | 12 + crates/axe/tests/fixtures/pi/pi-402.jsonl | 12 + crates/axe/tests/fixtures/pi/pi-429.jsonl | 37 ++ .../fixtures/pi/pi-openrouter-resume.jsonl | 13 + .../axe/tests/fixtures/pi/pi-openrouter.jsonl | 15 + crates/axe/tests/fixtures/pi/pi-run.jsonl | 15 + .../axe/tests/fixtures/pi/pi-thinking.jsonl | 15 + .../tests/fixtures/pi/pi-tool-resume.jsonl | 28 ++ crates/axe/tests/log_format.rs | 15 +- crates/axe/tests/telegram.rs | 19 +- crates/axe/tests/usage.rs | 58 ++++ docs/user/concepts/routines-bots-goals.md | 4 + docs/user/concepts/runtimes.md | 24 +- docs/user/guides/runtimes-from-telegram.md | 7 +- docs/user/reference/config.md | 2 +- 29 files changed, 1108 insertions(+), 42 deletions(-) create mode 100644 crates/axe/tests/fixtures/pi/pi-401.jsonl create mode 100644 crates/axe/tests/fixtures/pi/pi-402.jsonl create mode 100644 crates/axe/tests/fixtures/pi/pi-429.jsonl create mode 100644 crates/axe/tests/fixtures/pi/pi-openrouter-resume.jsonl create mode 100644 crates/axe/tests/fixtures/pi/pi-openrouter.jsonl create mode 100644 crates/axe/tests/fixtures/pi/pi-run.jsonl create mode 100644 crates/axe/tests/fixtures/pi/pi-thinking.jsonl create mode 100644 crates/axe/tests/fixtures/pi/pi-tool-resume.jsonl diff --git a/crates/axe-core/src/activity.rs b/crates/axe-core/src/activity.rs index 8c054a9..e5ab50f 100644 --- a/crates/axe-core/src/activity.rs +++ b/crates/axe-core/src/activity.rs @@ -1,7 +1,7 @@ //! Short "what is the agent doing" text from agent JSONL output, read by the //! run's harness's parser (`LogFormat::activity`): claude -//! `--output-format stream-json`, codex `exec --json` or opencode -//! `run --format json`. +//! `--output-format stream-json`, codex `exec --json`, opencode +//! `run --format json` or pi `--mode json`. use std::io::{Read, Seek, SeekFrom}; use std::path::Path; @@ -87,6 +87,39 @@ pub(crate) fn opencode(v: &Value) -> Option { }) } +/// pi --mode json +pub(crate) fn pi(v: &Value) -> Option { + Some(match v.get("type")?.as_str()? { + "tool_execution_start" => { + let name = v["toolName"].as_str()?; + match tool_arg(&v["args"]) { + Some(arg) => format!("{name}: {arg}"), + None => name.to_string(), + } + } + "message_end" if v["message"]["role"] == "assistant" => { + let m = &v["message"]; + if m["stopReason"] == "error" { + return Some(format!( + "error: {}", + m["errorMessage"].as_str().unwrap_or("") + )); + } + m["content"] + .as_array()? + .iter() + .rev() + .find_map(|c| match c["type"].as_str()? { + "text" => Some(format!("says: {}", nonempty(&c["text"])?)), + "thinking" => Some(format!("thinking: {}", nonempty(&c["thinking"])?)), + _ => None, + })? + } + "auto_retry_start" => format!("retrying: {}", v["errorMessage"].as_str().unwrap_or("")), + _ => return None, + }) +} + /// The last tool call or non-empty text block of a claude assistant message. fn claude_message(msg: &Value) -> Option { msg["content"] diff --git a/crates/axe-core/src/failure.rs b/crates/axe-core/src/failure.rs index 0723f94..f39b902 100644 --- a/crates/axe-core/src/failure.rs +++ b/crates/axe-core/src/failure.rs @@ -1,8 +1,9 @@ //! Why an agent run failed, read from its log by its harness's parser //! (`log_format::LogFormat::failure`): Claude Code stream-json //! (`claude -p --output-format stream-json`, [`claude`]), Codex JSONL -//! (`codex exec --json`, [`codex`]) or OpenCode JSON lines -//! (`opencode run --format json`, [`opencode`]). +//! (`codex exec --json`, [`codex`]), OpenCode JSON lines +//! (`opencode run --format json`, [`opencode`]) or Pi JSON lines +//! (`pi --mode json`, [`pi`]). //! //! Four classes are not the task's fault, so the node retries them later //! instead of escalating: an exhausted usage quota, an exhausted prepaid @@ -266,6 +267,51 @@ pub fn opencode(path: &Path) -> Option { }) } +/// Pi `--mode json`: the failed model call that ended the run, the last +/// assistant `message_end` with `stopReason: "error"` (Pi retries rate +/// limits and server errors itself, `auto_retry_start`, and a later call +/// that worked clears it). Its `errorMessage` starts with the HTTP status +/// (`401: {...}` from OpenAI-shaped providers, `401 {...}` from +/// Anthropic-shaped ones), as seen from Pi 1.7.0 against a provider +/// answering 401, 402 and 429 (`tests/fixtures/pi/`). Pi exits 0 either way +/// (`LogFormat::exit_failure`). +pub fn pi(path: &Path) -> Option { + let mut error: Option = None; + scan( + path, + &["\"type\":\"message_end\""], + |_| false, + |_, v| { + let Some(v) = v else { return }; + let m = &v["message"]; + if v["type"] != "message_end" || m["role"] != "assistant" { + return; + } + error = match m["stopReason"].as_str() { + Some("error") => Some(m["errorMessage"].as_str().unwrap_or("").to_string()), + _ => None, + }; + }, + )?; + let message = error?; + let digits: String = message.chars().take_while(char::is_ascii_digit).collect(); + let status = (digits.len() == 3 && message[3..].starts_with([':', ' '])) + .then(|| digits.parse::().ok()) + .flatten(); + let class = match status? { + 402 => OUT_OF_CREDIT, + 401 => AUTH_INVALID, + s if transient_status(s) => PROVIDER_UNAVAILABLE, + _ => return None, + }; + Some(Failure { + class, + status, + message, + retry_at: None, + }) +} + /// Codex reports failures as text only; the phrases are its `CodexErr` /// messages (openai/codex `codex-rs/protocol/src/error.rs`). fn codex_message(message: &str) -> Option { diff --git a/crates/axe-core/src/harness.rs b/crates/axe-core/src/harness.rs index 2ffdf71..ba07013 100644 --- a/crates/axe-core/src/harness.rs +++ b/crates/axe-core/src/harness.rs @@ -170,6 +170,10 @@ pub enum ConfigFile { /// first held provider's) and no self-update; keys stay in the /// environment, where OpenCode's built-in providers read them. OpenCode, + /// `/settings.json`: the default provider and + /// model (the first held provider's); keys stay in the environment, + /// where Pi reads each provider's key. + Pi, } impl ConfigFile { @@ -192,6 +196,19 @@ impl ConfigFile { let text = serde_json::to_string_pretty(&v).expect("json") + "\n"; Some(("config/opencode/opencode.json", text)) } + ConfigFile::Pi => { + // Pi 1.7.0 `docs/settings.md` "Model and thinking"; no secret + // goes in the file. + let mut v = serde_json::json!({ + "$schema": "https://pi.dev/schemas/settings.schema.json", + }); + if let Some(p) = providers.first().and_then(|id| crate::provider::get(id)) { + v["defaultProvider"] = p.id.into(); + v["defaultModel"] = p.default_model.into(); + } + let text = serde_json::to_string_pretty(&v).expect("json") + "\n"; + Some(("agent/settings.json", text)) + } } } } @@ -432,6 +449,71 @@ pub const HARNESSES: &[Harness] = &[ config: ConfigFile::OpenCode, package: Some(("@opencode/cli", "2.4.3")), }, + // Pi (`@earendil-works/pi-coding-agent`), verified on 1.7.0 in a scratch + // home against a local provider mock (store doc + // harvis/research/20261201-open-harness-runtimes.md, sections 3 and 6): + // `--session-id` opens the current directory's session with that id, + // creating it when there is none, so launch and resume are one command; + // `--no-approve` ignores project-local Pi files of the run folder; + // `--offline` skips the startup version check and model catalog refresh + // at pi.dev (axe pins the version). Pi exits 0 when the provider fails a + // call ([`LogFormat::Pi`] reads the failure anyway). + Harness { + name: "pi", + display: "Pi", + bin: "pi", + name_prefix: "pi", + agent: "pi", + launch: &[ + "pi", + "--mode", + "json", + "-p", + "--no-approve", + "--offline", + "--session-id", + "{session_id}", + "{prompt}", + ], + resume: &[ + "pi", + "--mode", + "json", + "-p", + "--no-approve", + "--offline", + "--session-id", + "{session_id}", + "{prompt}", + ], + session: "preset", + // Settings, model catalog and session transcripts are all under + // its agent directory (`docs/environment-variables.md`). + login_env: &[("PI_CODING_AGENT_DIR", "agent")], + default_login: "~/.pi", + providers: Providers::Table, + quota: QuotaSource::None, + meter: Meter::Spend, + // A key login is checked by its provider's free key check: + // `pi auth check` only checks that a key is present. + probe: &[], + logins: &[("api_key", None, "API key")], + login_checks: &[], + stdin_login: &[], + device_login: (&[], false), + shared: &[], + // The bot's system prompt appended from its file, on every run + // (Pi keeps no system prompt in the session). + bot_args: &["--append-system-prompt", "{system_prompt_file}"], + bot_env: &[], + model_args: &["--model", "{model}"], + effort_args: &["--thinking", "{effort}"], + model_effort_args: &[], + log: LogFormat::Pi, + inbox_hook: false, + config: ConfigFile::Pi, + package: Some(("@earendil-works/pi-coding-agent", "1.7.0")), + }, ]; impl Harness { @@ -654,4 +736,36 @@ mod tests { assert_eq!(get("codex").unwrap().config.render(&["deepseek"]), None); assert_eq!(h.package, Some(("@opencode/cli", "2.4.3"))); } + + /// Pi's settings: the first provider and its default model, never a + /// key, in its agent directory (`PI_CODING_AGENT_DIR`). + #[test] + fn pi_settings_name_the_first_provider_and_its_default_model() { + let h = get("pi").unwrap(); + assert_eq!(h.login_env, &[("PI_CODING_AGENT_DIR", "agent")]); + let (path, text) = h.config.render(&["openrouter", "deepseek"]).unwrap(); + assert_eq!(path, "agent/settings.json"); + let v: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!( + v, + serde_json::json!({"$schema": "https://pi.dev/schemas/settings.schema.json", + "defaultProvider": "openrouter", + "defaultModel": "~anthropic/claude-sonnet-latest"}) + ); + let (_, text) = h.config.render(&[]).unwrap(); + assert!(!text.contains("default"), "{text}"); + assert_eq!( + h.package, + Some(("@earendil-works/pi-coding-agent", "1.7.0")) + ); + assert_eq!( + crate::rule::Use { + harness: "pi".into(), + model: Some("deepseek/deepseek-flash".into()), + effort: Some("high".into()), + } + .args(), + ["--model", "deepseek/deepseek-flash", "--thinking", "high"] + ); + } } diff --git a/crates/axe-core/src/log_format.rs b/crates/axe-core/src/log_format.rs index 7020365..05e596c 100644 --- a/crates/axe-core/src/log_format.rs +++ b/crates/axe-core/src/log_format.rs @@ -26,6 +26,12 @@ pub enum LogFormat { /// in the CLI's own database (`/opencode/opencode.db`), not in /// transcript files. OpenCode, + /// `pi --mode json -p` (Pi 1.x): `session`, `agent_start`, `turn_*`, + /// `message_*` (an assistant `message_end` carries one model call's + /// provider, model, usage and cost, or its `errorMessage`), + /// `tool_execution_*`, `auto_retry_*`, and `agent_settled` last. + /// Transcripts `/sessions//