Skip to content
2 changes: 1 addition & 1 deletion crates/agent-registry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub use detect::{
};
pub use registry::{
Agent, AgentSpec, REGISTRY, Tier, agent_by_name, autonomous_args, canonicalize, headless_args,
spec,
json_output_args, resume_arg, spec,
};
pub use router::{
RouteDecision, RouterConfig, RouterRule, RuleMatch, TaskContext, parse_router_config, route,
Expand Down
51 changes: 51 additions & 0 deletions crates/agent-registry/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,35 @@ pub fn autonomous_args(agent: Agent) -> Option<&'static [&'static str]> {
}
}

/// CLI flags that switch an agent's headless print mode to structured JSON
/// output (`{"type":"result","result":"...","session_id":"...",...}`),
/// letting `agent_launch::run_headless` capture a provider session id and
/// (where the provider reports it) a cost instead of treating stdout as an
/// opaque text reply. `None` for every agent whose JSON schema hasn't been
/// verified — `run_headless` must fall back to plain-text parsing for those,
/// never guess a schema.
#[allow(dead_code)]
#[must_use]
pub fn json_output_args(agent: Agent) -> Option<&'static [&'static str]> {
match agent {
Agent::ClaudeCode | Agent::Cursor => Some(&["--output-format", "json"]),
_ => None,
}
}

/// The flag that resumes a prior session by id (e.g. `claude --resume
/// <session_id>`, `cursor-agent --resume <chatId>`), appended after
/// print-mode flags and before the prompt. `None` for agents with no known
/// resume flag.
#[allow(dead_code)]
#[must_use]
pub fn resume_arg(agent: Agent) -> Option<&'static str> {
match agent {
Agent::ClaudeCode | Agent::Cursor => Some("--resume"),
_ => None,
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -439,6 +468,28 @@ mod tests {
assert_eq!(autonomous_args(Agent::Cursor), Some(&["--force"][..]));
}

#[test]
fn json_output_args_maps_claude_and_cursor_only() {
assert_eq!(
json_output_args(Agent::ClaudeCode),
Some(&["--output-format", "json"][..])
);
assert_eq!(
json_output_args(Agent::Cursor),
Some(&["--output-format", "json"][..])
);
assert_eq!(json_output_args(Agent::Opencode), None);
assert_eq!(json_output_args(Agent::Codex), None);
}

#[test]
fn resume_arg_maps_claude_and_cursor_only() {
assert_eq!(resume_arg(Agent::ClaudeCode), Some("--resume"));
assert_eq!(resume_arg(Agent::Cursor), Some("--resume"));
assert_eq!(resume_arg(Agent::Opencode), None);
assert_eq!(resume_arg(Agent::Codex), None);
}

#[test]
fn canonicalize_maps_known_aliases_and_passes_through_unknown() {
assert_eq!(canonicalize("claude"), "claude-code");
Expand Down
470 changes: 470 additions & 0 deletions docs/superpowers/plans/2026-08-17-sdd-loop-session-resume.md

Large diffs are not rendered by default.

150 changes: 143 additions & 7 deletions src/agent_launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Finds the agent binary on PATH, maps --model/--mode to agent-native
// flags, and executes with pass-through args and inherited stdio.
use agent_registry::detect::find_binary;
use agent_registry::{Agent, AgentSpec, Tier, headless_args};
use agent_registry::{Agent, AgentSpec, Tier, headless_args, json_output_args};
use std::io::Read;
use std::path::Path;
use std::process::{Command, Stdio};
Expand Down Expand Up @@ -388,11 +388,18 @@ fn launch_command(binary: &Path, args: &[String]) -> (String, Vec<String>, bool)
}

/// Outcome of a headless (non-interactive, output-captured) agent invocation.
#[allow(dead_code)]
#[derive(Debug, Clone, Default, PartialEq)]
pub struct HeadlessReply {
pub text: String,
pub session_id: Option<String>,
pub cost_usd: Option<f64>,
}

#[allow(dead_code)]
#[derive(Debug)]
pub enum HeadlessOutcome {
/// The agent ran and exited 0; carries captured stdout (the reply).
Ok(String),
Ok(HeadlessReply),
UnknownAgent(String),
/// The agent has no non-interactive print mode.
NotHeadless(String),
Expand All @@ -402,6 +409,30 @@ pub enum HeadlessOutcome {
Failed(String),
}

fn parse_json_reply(stdout: &str) -> HeadlessReply {
match serde_json::from_str::<serde_json::Value>(stdout.trim()) {
Ok(value) => HeadlessReply {
text: value
.get("result")
.and_then(serde_json::Value::as_str)
.unwrap_or(stdout)
.to_string(),
session_id: value
.get("session_id")
.and_then(serde_json::Value::as_str)
.map(str::to_string),
cost_usd: value
.get("total_cost_usd")
.and_then(serde_json::Value::as_f64),
},
Err(_) => HeadlessReply {
text: stdout.to_string(),
session_id: None,
cost_usd: None,
},
}
}

/// Run an agent non-interactively with `prompt` and capture its reply, killing
/// it if it outlives `hard_cap` or goes `idle_timeout` without new output
/// (see `run_captured`'s doc comment for the distinction). Reuses the shared
Expand All @@ -415,6 +446,7 @@ pub fn run_headless(
hard_cap: Duration,
idle_timeout: Duration,
extra_args: &[String],
request_json: bool,
) -> HeadlessOutcome {
let Some(spec) = registry.iter().find(|s| s.id.as_str() == agent) else {
return HeadlessOutcome::UnknownAgent(format!("unknown agent: {agent}"));
Expand All @@ -433,7 +465,12 @@ pub fn run_headless(
spec.binary_names.join(" / ")
));
};
let Some(argv) = headless_argv(spec.id, &binary, extra_args) else {
let mut full_args: Vec<String> = Vec::with_capacity(extra_args.len() + 2);
if request_json && let Some(flags) = json_output_args(spec.id) {
full_args.extend(flags.iter().map(|s| (*s).to_string()));
}
full_args.extend(extra_args.iter().cloned());
let Some(argv) = headless_argv(spec.id, &binary, &full_args) else {
return HeadlessOutcome::NotHeadless(format!(
"{} has no headless print mode",
spec.display_name
Expand Down Expand Up @@ -492,7 +529,17 @@ pub fn run_headless(
// that's correct for all of them — only an explicit per-spawn env var is.
cmd.env("AGENTFLARE_AGENT", spec.id.as_str());
match run_captured(cmd, hard_cap, idle_timeout, Some(prompt)) {
Ok(c) if c.success => HeadlessOutcome::Ok(c.stdout),
Ok(c) if c.success => {
if request_json && json_output_args(spec.id).is_some() {
HeadlessOutcome::Ok(parse_json_reply(&c.stdout))
} else {
HeadlessOutcome::Ok(HeadlessReply {
text: c.stdout,
session_id: None,
cost_usd: None,
})
}
}
Ok(c) if c.timed_out => {
let reason = if c.idle_killed {
format!("went idle for {idle_timeout:?} (no new output)")
Expand Down Expand Up @@ -955,6 +1002,7 @@ mod tests {
Duration::from_secs(1),
Duration::from_secs(1),
&[],
false,
) {
HeadlessOutcome::UnknownAgent(m) => assert!(m.contains("nope")),
other => panic!("expected UnknownAgent, got {other:?}"),
Expand All @@ -971,6 +1019,7 @@ mod tests {
Duration::from_secs(1),
Duration::from_secs(1),
&[],
false,
) {
HeadlessOutcome::NotHeadless(m) => assert!(m.contains("aider")),
other => panic!("expected NotHeadless, got {other:?}"),
Expand All @@ -988,6 +1037,7 @@ mod tests {
Duration::from_secs(120),
Duration::from_secs(60),
&["--force".to_string()],
false,
);
eprintln!("elapsed={:?}", t0.elapsed());
match out {
Expand All @@ -1006,6 +1056,7 @@ mod tests {
Duration::from_secs(1),
Duration::from_secs(1),
&[],
false,
) {
HeadlessOutcome::NotFound(m) => assert!(m.contains("not found")),
other => panic!("expected NotFound, got {other:?}"),
Expand Down Expand Up @@ -1046,10 +1097,11 @@ mod tests {
Duration::from_secs(10),
Duration::from_secs(10),
&["-c".to_string(), "wc -c".to_string()],
false,
) {
HeadlessOutcome::Ok(out) => {
HeadlessOutcome::Ok(reply) => {
assert_eq!(
out.trim(),
reply.text.trim(),
huge_prompt.len().to_string(),
"the full oversized prompt should have arrived via stdin"
);
Expand Down Expand Up @@ -1189,4 +1241,88 @@ mod tests {
"expected captured stderr in the failure message, got: {msg}"
);
}

#[test]
fn parse_json_reply_extracts_result_session_and_cost() {
let reply = parse_json_reply(
r#"{"type":"result","result":"pong","session_id":"abc-123","total_cost_usd":0.05}"#,
);
assert_eq!(reply.text, "pong");
assert_eq!(reply.session_id.as_deref(), Some("abc-123"));
assert_eq!(reply.cost_usd, Some(0.05));
}

#[test]
fn parse_json_reply_handles_missing_cost_usd() {
let reply = parse_json_reply(r#"{"type":"result","result":"pong","session_id":"abc-123"}"#);
assert_eq!(reply.text, "pong");
assert_eq!(reply.session_id.as_deref(), Some("abc-123"));
assert_eq!(reply.cost_usd, None);
}

#[test]
fn parse_json_reply_falls_back_to_raw_text_on_malformed_json() {
let reply = parse_json_reply("not json at all");
assert_eq!(reply.text, "not json at all");
assert_eq!(reply.session_id, None);
assert_eq!(reply.cost_usd, None);
}

#[cfg(unix)]
#[test]
fn run_headless_with_request_json_parses_a_json_reply_from_the_child() {
use std::os::unix::fs::PermissionsExt;
// This file's usual `sh -c <script>` stub-agent idiom doesn't work
// with `request_json: true`: it prepends `--output-format json`
// ahead of `extra_args`, and a real `sh`/bash rejects that as an
// unrecognized long option before ever reaching `-c` -- so instead
// this fake binary ignores its argv entirely and always emits a
// fixed JSON reply. It lives under this crate's own `target/` dir,
// not the system temp dir -- `run_headless`'s bwrap sandbox remounts
// `/tmp` as a private, empty tmpfs invisible to the child (see
// `flare_sandbox::bwrap`'s `--tmpfs /tmp`), while `target/` sits
// under the sandboxed cwd bind and stays visible and writable.
let dir = tempfile::Builder::new()
.prefix("agentflare-fake-claude-")
.tempdir_in(std::env::current_dir().unwrap().join("target"))
.unwrap();
let fake_bin = dir.path().join("fake-claude");
std::fs::write(
&fake_bin,
"#!/bin/sh\necho '{\"type\":\"result\",\"result\":\"pong\",\"session_id\":\"sess-xyz\"}'\n",
)
.unwrap();
std::fs::set_permissions(&fake_bin, std::fs::Permissions::from_mode(0o755)).unwrap();
let binary_names: &'static [&'static str] = Box::leak(
vec![&*Box::leak(
fake_bin.to_string_lossy().into_owned().into_boxed_str(),
)]
.into_boxed_slice(),
);

let reg = vec![AgentSpec {
id: Agent::ClaudeCode,
display_name: "claude-code",
tier: Tier::Cli,
binary_names,
version_args: &[],
package_manager: None,
package_name: None,
}];
match run_headless(
&reg,
"claude-code",
"hi",
Duration::from_secs(10),
Duration::from_secs(10),
&[],
true,
) {
HeadlessOutcome::Ok(reply) => {
assert_eq!(reply.text, "pong");
assert_eq!(reply.session_id.as_deref(), Some("sess-xyz"));
}
other => panic!("expected Ok, got {other:?}"),
}
}
}
3 changes: 2 additions & 1 deletion src/agents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,10 @@ pub fn cli_run_headless(agent: &str, prompt: &str, timeout: std::time::Duration)
timeout,
timeout,
&[],
false,
) {
agent_launch::HeadlessOutcome::Ok(reply) => {
print!("{reply}");
print!("{}", reply.text);
0
}
agent_launch::HeadlessOutcome::UnknownAgent(msg)
Expand Down
Loading
Loading