Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions crates/axe-core/src/activity.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -87,6 +87,39 @@ pub(crate) fn opencode(v: &Value) -> Option<String> {
})
}

/// pi --mode json
pub(crate) fn pi(v: &Value) -> Option<String> {
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<String> {
msg["content"]
Expand Down
50 changes: 48 additions & 2 deletions crates/axe-core/src/failure.rs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -266,6 +267,51 @@ pub fn opencode(path: &Path) -> Option<Failure> {
})
}

/// 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<Failure> {
let mut error: Option<String> = 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::<i64>().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<Failure> {
Expand Down
114 changes: 114 additions & 0 deletions crates/axe-core/src/harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
/// `<PI_CODING_AGENT_DIR>/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 {
Expand All @@ -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))
}
}
}
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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"]
);
}
}
81 changes: 81 additions & 0 deletions crates/axe-core/src/log_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ pub enum LogFormat {
/// in the CLI's own database (`<data>/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 `<agent>/sessions/<cwd>/<time>_<session>.jsonl`.
Pi,
}

/// Top-level event types only one format writes.
Expand All @@ -47,6 +53,14 @@ const CODEX_EVENTS: &[&str] = &[
"item.completed",
];
const OPENCODE_EVENTS: &[&str] = &["step_start", "step_finish", "tool_use", "retry"];
const PI_EVENTS: &[&str] = &[
"agent_start",
"turn_start",
"message_start",
"message_end",
"tool_execution_start",
"agent_settled",
];

impl LogFormat {
/// The format of harness `harness`'s logs, else of the log at `path`.
Expand Down Expand Up @@ -75,6 +89,7 @@ impl LogFormat {
Some(t) if CODEX_EVENTS.contains(&t) => return LogFormat::Codex,
Some(t) if CLAUDE_EVENTS.contains(&t) => return LogFormat::Claude,
Some(t) if OPENCODE_EVENTS.contains(&t) => return LogFormat::OpenCode,
Some(t) if PI_EVENTS.contains(&t) => return LogFormat::Pi,
Some("error") => error = true,
_ => {}
}
Expand All @@ -94,6 +109,7 @@ impl LogFormat {
LogFormat::Claude => crate::usage::parse_claude(path),
LogFormat::Codex => crate::usage::parse_codex(path, transcript_logins),
LogFormat::OpenCode => crate::usage::parse_opencode(path),
LogFormat::Pi => crate::usage::parse_pi(path),
}
}

Expand All @@ -103,6 +119,18 @@ impl LogFormat {
LogFormat::Claude => crate::failure::claude(path),
LogFormat::Codex => crate::failure::codex(path),
LogFormat::OpenCode => crate::failure::opencode(path),
LogFormat::Pi => crate::failure::pi(path),
}
}

/// The failure of a run that exited with `code`: a non-zero exit's,
/// or a zero exit's when the CLI exits 0 after a failed model call
/// (Pi prints the error and still exits 0).
pub fn exit_failure(self, path: &Path, code: Option<i32>) -> Option<crate::failure::Failure> {
match code {
Some(0) if self != LogFormat::Pi => None,
Some(_) => self.failure(path),
None => None,
}
}

Expand All @@ -112,6 +140,7 @@ impl LogFormat {
LogFormat::Claude => crate::activity::claude(v),
LogFormat::Codex => crate::activity::codex(v),
LogFormat::OpenCode => crate::activity::opencode(v),
LogFormat::Pi => crate::activity::pi(v),
}
}

Expand All @@ -122,6 +151,7 @@ impl LogFormat {
LogFormat::Codex => crate::retention::scan_codex(dir),
// In the CLI's database: nothing for retention to prune as files.
LogFormat::OpenCode => vec![],
LogFormat::Pi => crate::retention::scan_pi(dir),
}
}

Expand All @@ -130,3 +160,54 @@ impl LogFormat {
self == LogFormat::Codex
}
}

#[cfg(test)]
mod tests {
use super::*;

/// Pi exits 0 after a failed model call, so its failure is read on a
/// zero exit too; every other CLI's only on a non-zero one.
#[test]
fn a_zero_exit_fails_only_for_pi() {
let d = tempfile::tempdir().unwrap();
let pi = d.path().join("pi.jsonl");
std::fs::write(
&pi,
concat!(
r#"{"type":"agent_start"}"#,
"\n",
r#"{"type":"message_end","message":{"role":"assistant","stopReason":"error","errorMessage":"402: {\"message\":\"Insufficient Balance\"}"}}"#,
"\n"
),
)
.unwrap();
let f = LogFormat::Pi.exit_failure(&pi, Some(0)).unwrap();
assert_eq!(
(f.class, f.status),
(crate::failure::OUT_OF_CREDIT, Some(402))
);
assert!(LogFormat::Pi.exit_failure(&pi, Some(1)).is_some());
assert!(LogFormat::Pi.exit_failure(&pi, None).is_none(), "a signal");
let oc = d.path().join("oc.jsonl");
std::fs::write(
&oc,
r#"{"type":"error","error":{"type":"provider.quota","status":402,"message":"x"}}"#,
)
.unwrap();
assert!(LogFormat::OpenCode.exit_failure(&oc, Some(0)).is_none());
assert!(LogFormat::OpenCode.exit_failure(&oc, Some(1)).is_some());

// A later call that worked clears the failure (a retry went on).
std::fs::write(
&pi,
concat!(
r#"{"type":"message_end","message":{"role":"assistant","stopReason":"error","errorMessage":"429: busy"}}"#,
"\n",
r#"{"type":"message_end","message":{"role":"assistant","stopReason":"stop","content":[]}}"#,
"\n"
),
)
.unwrap();
assert!(LogFormat::Pi.exit_failure(&pi, Some(0)).is_none());
}
}
Loading
Loading