The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: files changed .git-drv-backup
Steven Enamakelb465cf4a36d2
diff --git a/.git-drv-backup b/.git-drv-backupdeleted file mode 100644index 6363704a8f..0000000000--- a/.git-drv-backup+++ /dev/null@@ -1,700 +0,0 @@-//! Spawn the `claude` CLI for one chat turn, stream its stdout into the-//! event mapper, and return an aggregated `ChatResponse`.-//!-//! The driver does *not* own concurrency limits; the `ClaudeCodeProvider`-//! holds a `Semaphore` and acquires a permit before calling this.--use std::path::PathBuf;-use std::process::Stdio;-use std::sync::Arc;-use std::time::Duration;--use serde_json::json;-use tokio::io::{AsyncReadExt, AsyncWriteExt};-use tokio::process::Command;-use tokio::sync::mpsc;--/// Hard timeout per turn (PLAN §8). If the CLI hangs (network stall,-/// infinite loop, MCP deadlock) we kill the child and surface a timeout.-const DEFAULT_TURN_TIMEOUT_SECS: u64 = 900;--fn turn_timeout() -> Duration {- let secs = std::env::var("OPENHUMAN_CLAUDE_CODE_TURN_TIMEOUT_SECS")- .ok()- .and_then(|raw| raw.trim().parse::<u64>().ok())- .filter(|secs| *secs > 0)- .unwrap_or(DEFAULT_TURN_TIMEOUT_SECS);- Duration::from_secs(secs)-}--fn parse_error_line_shape(line: &str) -> &'static str {- match line.trim_start().chars().next() {- Some('{') => "json object",- Some('[') => "json array",- Some('"') => "json string",- Some(_) => "non-json",- None => "blank",- }-}--fn parse_error_log_line(ev: &ClaudeCodeEvent) -> Option<String> {- let ClaudeCodeEvent::ParseError { line, reason } = ev else {- return None;- };- Some(format!(- "[claude-code][driver] dropping unparsable stream line ({reason}): {} of {} bytes",- parse_error_line_shape(line),- line.len()- ))-}--/// How much of the child's stderr we keep for diagnostics.-const STDERR_DIAGNOSTIC_CAP: usize = 16_384;--/// Append `chunk` to `acc`, keeping at most `max_bytes` and never splitting a-/// character.-///-/// `String::truncate` takes a *byte* index and panics when it is not a character-/// boundary, so bounding this accumulator with `acc.truncate(16_384)` aborted the-/// task the moment a multi-byte character straddled the cap. The panic happened-/// inside `tokio::spawn`, and the join is `unwrap_or_default()`, so it surfaced as-/// an empty stderr string: the operator lost the whole error output for that turn-/// and saw `exit Some(1) stderr=`.-fn push_bounded(acc: &mut String, chunk: &str, max_bytes: usize) {- acc.push_str(chunk);- if acc.len() > max_bytes {- let keep = utf8_safe_prefix_at_byte_boundary(acc, max_bytes).len();- acc.truncate(keep);- }-}--/// Upper bound on the structured stdout error carried into a returned error.-const STDOUT_ERROR_CAP: usize = 2_048;--/// Remove credentials from a CLI-reported message and bound its length.-/// Redacts the configured API key verbatim and any whitespace-delimited token-/// that looks like an `sk-` key.-fn sanitize_cli_message(raw: &str, api_key: Option<&str>) -> String {- let mut text = raw.to_string();- if let Some(key) = api_key.filter(|key| !key.is_empty()) {- text = text.replace(key, "[redacted]");- }- let redacted = text- .split_whitespace()- .map(|token| {- let core =- token.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-' && c != '_');- if core.starts_with("sk-") {- "[redacted]"- } else {- token- }- })- .collect::<Vec<_>>()- .join(" ");- let mut out = String::new();- push_bounded(&mut out, &redacted, STDOUT_ERROR_CAP);- out-}--/// Error text for a nonzero CLI exit: the structured stdout error when the-/// CLI printed one (sanitized and bounded), otherwise the bounded stderr.-fn nonzero_exit_message(- code: Option<i32>,- stdout_error: Option<&str>,- stderr: &str,- api_key: Option<&str>,-) -> String {- match stdout_error.map(|e| sanitize_cli_message(e, api_key)) {- Some(message) if !message.is_empty() => {- format!("[claude-code][driver] exit {code:?}: {message}")- }- _ => format!(- "[claude-code][driver] exit {code:?} stderr={}",- stderr.trim()- ),- }-}--use super::bridge::{ChatMessage, ChatResponse, ProviderDelta};-use super::event_mapper::EventMapper;-use super::input_builder::build_stdin;-use super::session_store::{SessionStore, generate_uuid_v4, is_uuid_v4};-use super::stream_parser::{ClaudeCodeEvent, StreamJsonParser};--fn utf8_safe_prefix_at_byte_boundary(value: &str, max_bytes: usize) -> &str {- if value.len() <= max_bytes {- return value;- }- let mut end = max_bytes;- while end > 0 && !value.is_char_boundary(end) {- end -= 1;- }- &value[..end]-}--/// Authenticated loopback MCP endpoint exposed to the Claude subprocess.-#[derive(Clone, Debug)]-pub struct McpEndpoint {- /// Listening address.- pub addr: std::net::SocketAddr,- /// Bearer token attached to MCP requests.- pub token: String,-}--/// Host hook that lazily starts or locates an MCP endpoint for a turn.-#[async_trait::async_trait]-pub trait McpEndpointProvider: Send + Sync {- /// Return the endpoint to advertise, or an error to continue without MCP.- async fn endpoint(&self) -> Result<McpEndpoint, String>;-}--/// Tools withheld in the DEFAULT (`acceptEdits`) posture: Claude Code can-/// read/edit files in the project, but not run shell, hit the network, or-/// fan out CC subagents. The user opts into the full toolset separately by-/// enabling full access (see [`claude_code_full_access`]), which switches to-/// `bypassPermissions` and drops this list.-const DISALLOWED_CC_BUILTINS: &[&str] = &[- "Bash",- "BashOutput",- "KillShell",- "WebFetch",- "WebSearch",- "Task",-];--/// Whether the user opted into FULL access for Claude Code (`bypassPermissions`-/// + full native toolset incl. Bash/network). Default is **off** → the safer-///-/// `acceptEdits` posture (file edits only). This is a deliberate user choice,-/// not the default — enabling Claude Code alone does not grant shell/network-/// power.-///-/// Resolution order:-/// 1. `OPENHUMAN_CLAUDE_CODE_PERMISSION_MODE` env var, when set to a recognised-/// value, wins (debugging / power users). `bypass`/`bypassPermissions`/`full`-/// force ON; `acceptEdits`/`edits`/`default`/`off`/`false`/`0` force OFF.-/// 2. Otherwise the persisted UI toggle in-/// [`super::settings`] (the Claude Code modal "Full access" switch).-fn claude_code_full_access(workspace_dir: &std::path::Path) -> bool {- if let Ok(raw) = std::env::var("OPENHUMAN_CLAUDE_CODE_PERMISSION_MODE") {- match raw.trim() {- "bypass" | "bypassPermissions" | "full" => return true,- "acceptEdits" | "edits" | "default" | "off" | "false" | "0" => return false,- _ => {}- }- }- super::settings::load(workspace_dir).full_access-}--/// Whether to wrap the `claude` spawn in the macOS Seatbelt jail. On by-/// default on macOS where `sandbox-exec` exists; opt out with-/// `OPENHUMAN_CLAUDE_CODE_SANDBOX=0`.-fn seatbelt_available() -> bool {- #[cfg(target_os = "macos")]- {- let opted_out = std::env::var("OPENHUMAN_CLAUDE_CODE_SANDBOX")- .map(|v| v == "0")- .unwrap_or(false);- !opted_out && std::path::Path::new("/usr/bin/sandbox-exec").exists()- }- #[cfg(not(target_os = "macos"))]- {- false- }-}--/// Render a Seatbelt profile that lets Claude Code do **everything** the user-/// can — read/write anywhere, run subprocesses, use the network — EXCEPT touch-/// OpenHuman's internal workspace (`~/.openhuman*`: memory DB, sessions, auth-/// tokens, config). That is the one hard wall: CC's raw tools must not be able-/// to corrupt OpenHuman's own state. This mirrors OpenHuman's existing-/// `is_workspace_internal_path` invariant (its native tools already can't write-/// there) and now enforces the same boundary for the CC subprocess at the OS-/// level. Everything else is the user's call.-///-/// Denies BOTH reads and writes of the OpenHuman workspace: CC's raw tools-/// can neither corrupt nor exfiltrate OpenHuman's internal state (memory DB,-/// sessions, auth tokens, config). CC still reaches OpenHuman memory — but only-/// through the MCP HTTP server, which runs in the unjailed core (not as CC's-/// child), so this full deny is safe.-#[cfg(target_os = "macos")]-fn seatbelt_profile(workspace_dir: &std::path::Path) -> String {- let esc = |p: String| p.replace('\\', "\\\\").replace('"', "\\\"");- // Deny the ENTIRE `~/.openhuman[-staging]` tree, not just the per-user- // workspace subdir. `workspace_dir` is `…/.openhuman-staging/users/<id>/…`,- // but sensitive files (core.token, credentials) also live at the root — so- // denying only the subdir leaves them readable. Walk up to the `.openhuman*`- // ancestor and deny that whole tree.- let root = openhuman_internal_root(workspace_dir);- let root = esc(std::fs::canonicalize(&root)- .unwrap_or(root)- .to_string_lossy()- .to_string());- format!(- "(version 1)\n(allow default)\n\- (deny file-write*\n (subpath \"{root}\")\n)\n\- (deny file-read*\n (subpath \"{root}\")\n)\n"- )-}--/// Resolve the OpenHuman internal root (`~/.openhuman` / `~/.openhuman-staging`)-/// from a path inside it by walking up to the first `.openhuman*` ancestor.-/// Falls back to the input path when no such ancestor exists.-#[cfg(target_os = "macos")]-fn openhuman_internal_root(workspace_dir: &std::path::Path) -> std::path::PathBuf {- let mut cur = workspace_dir;- loop {- if cur- .file_name()- .and_then(|n| n.to_str())- .map(|n| n.starts_with(".openhuman"))- .unwrap_or(false)- {- return cur.to_path_buf();- }- match cur.parent() {- Some(p) => cur = p,- None => return workspace_dir.to_path_buf(),- }- }-}--/// One CC chat turn.-pub(crate) struct TurnContext<'a> {- /// Resolved path to the `claude` CLI binary to spawn.- pub bin_path: PathBuf,- /// Directory holding this provider's session store and settings- /// (`claude-code-sessions.json`, `claude_code_settings.json`); also the- /// root the macOS Seatbelt jail walls off from the CLI's own tools.- pub workspace_dir: PathBuf,- /// The user's project root. Claude Code runs here- /// (cwd + `--add-dir`) so its file tools act on the user's code, not the- /// internal workspace.- pub project_dir: PathBuf,- /// Caller-provided logical conversation id, used to look up or create a- /// CC session UUID in `session_store`.- pub thread_id: String,- /// Model name passed to `--model`.- pub model: String,- /// Combined system prompt (all `system` messages joined), written to a- /// scratch file and passed via `--append-system-prompt-file`.- pub append_system_prompt: Option<String>,- /// Full conversation for a new session, or just the trailing user turn- /// when resuming (see `input_builder::build_stdin`).- pub messages: &'a [ChatMessage],- /// Thread-key → CC session UUID persistence, shared across turns.- pub session_store: Arc<SessionStore>,- /// Channel to forward streaming deltas on, when the caller wants a- /// streamed response rather than only the final aggregate.- pub stream: Option<&'a mpsc::Sender<ProviderDelta>>,- /// Optional explicit `ANTHROPIC_API_KEY` to set on the child. When- /// `None`, the CLI falls back to its own `~/.claude/.credentials.json`.- pub anthropic_api_key: Option<String>,- /// Optional host MCP endpoint provider.- pub mcp_provider: Option<Arc<dyn McpEndpointProvider>>,-}--/// Write a CC `--mcp-config` JSON pointing at OpenHuman's in-process HTTP MCP-/// server (running in the unjailed core). CC connects over loopback, so the-/// MCP server is NOT a child of the sandboxed `claude` and keeps full access-/// to `~/.openhuman` for memory — while CC's own raw tools are denied that dir-/// by the jail. Returns the on-disk path; caller cleans up.-fn write_mcp_http_config(- dir: &std::path::Path,- addr: std::net::SocketAddr,- token: &str,-) -> std::io::Result<PathBuf> {- let path = dir.join("openhuman-mcp-config.json");- // The loopback MCP server is authenticated — carry the per-process bearer- // token so only this `claude` launch (not other local processes) can reach- // OpenHuman's tools/memory.- let cfg = json!({- "mcpServers": {- "openhuman": {- "type": "http",- "url": format!("http://{addr}/"),- "headers": {- "Authorization": format!("Bearer {token}"),- }- }- }- });- std::fs::write(- &path,- serde_json::to_string_pretty(&cfg).unwrap_or_default(),- )?;- Ok(path)-}--/// Build the child's `PATH` so `claude` — and any tool it shells out to (git,-/// ripgrep, node, …) — resolves even when OpenHuman was launched from-/// Finder/Dock and inherited only the stripped launchd `PATH`-/// (`/usr/bin:/bin:/usr/sbin:/sbin`, no `~/.local/bin`). Prepends the resolved-/// CLI's own directory plus the common user/Homebrew bin dirs to whatever-/// `PATH` we inherited; the inherited system entries are kept after them.-/// Prepend-only — duplicate `PATH` entries are harmless, so this stays safe if-/// a dir is already present (e.g. a terminal launch).-pub(crate) fn child_path_with_user_bins(claude_bin: &std::path::Path) -> std::ffi::OsString {- let mut prefix: Vec<PathBuf> = Vec::new();- if let Some(parent) = claude_bin.parent()- && !parent.as_os_str().is_empty()- {- prefix.push(parent.to_path_buf());- }- if let Some(home) = dirs::home_dir() {- prefix.push(home.join(".local/bin"));- prefix.push(home.join("bin"));- }- #[cfg(target_os = "macos")]- prefix.push(PathBuf::from("/opt/homebrew/bin"));- prefix.push(PathBuf::from("/usr/local/bin"));-- let existing = std::env::var_os("PATH").unwrap_or_default();- std::env::join_paths(- prefix- .into_iter()- .chain(std::env::split_paths(&existing).filter(|path| !path.as_os_str().is_empty())),- )- .unwrap_or(existing)-}--/// Keep the potentially large harness prompt out of argv. Windows flattens-/// argv into a command line capped at 32,767 UTF-16 code units, while Claude's-/// file flag has no such limit. The per-turn scratch directory owns cleanup.-fn append_system_prompt_args(- dir: &std::path::Path,- prompt: Option<&str>,-) -> std::io::Result<Vec<String>> {- let Some(prompt) = prompt.filter(|value| !value.trim().is_empty()) else {- return Ok(Vec::new());- };-- let path = dir.join("append-system-prompt.txt");- tracing::debug!(- "[claude-code][driver] append-system-prompt file write start path={} bytes={}",- path.display(),- prompt.len()- );- if let Err(error) = std::fs::write(&path, prompt) {- tracing::warn!(- "[claude-code][driver] append-system-prompt file write failed path={} error={}",- path.display(),- error- );- return Err(error);- }- tracing::debug!(- "[claude-code][driver] append-system-prompt file write complete path={} bytes={}",- path.display(),- prompt.len()- );- Ok(vec![- "--append-system-prompt-file".to_string(),- path.display().to_string(),- ])-}--/// Run one turn against the `claude` CLI. Awaits process exit. Forwards-/// `ProviderDelta`s through `ctx.stream` as they arrive and returns the-/// aggregated `ChatResponse` when done.-pub(crate) async fn run_turn(ctx: TurnContext<'_>) -> anyhow::Result<ChatResponse> {- let stored = ctx.session_store.get(&ctx.thread_id);- let is_new = !stored.as_deref().map(is_uuid_v4).unwrap_or(false);- let cc_session_id = if is_new {- generate_uuid_v4()- } else {- stored.expect("checked Some above")- };-- // Set up a per-turn scratch dir for --mcp-config and any other transient- // state. Best-effort cleanup at end of turn.- let scratch = tempfile::Builder::new()- .prefix("openhuman-cc-")- .tempdir()- .map_err(|e| anyhow::anyhow!("create scratch dir: {e}"))?;- // Point CC at OpenHuman's in-process HTTP MCP server (unjailed core), so- // the memory bridge survives CC's `.openhuman` jail deny.- let mut mcp_config_path: Option<PathBuf> = None;- if let Some(provider) = ctx.mcp_provider.as_ref() {- match provider.endpoint().await {- Ok(endpoint) => {- match write_mcp_http_config(scratch.path(), endpoint.addr, &endpoint.token) {- Ok(p) => {- tracing::debug!(- "[claude-code][driver] wrote http mcp-config path={} url=http://{}/ (authenticated)",- p.display(),- endpoint.addr- );- mcp_config_path = Some(p);- }- Err(e) => tracing::warn!(- "[claude-code][driver] failed to write mcp-config: {e}; CC will run without OpenHuman MCP tools"- ),- }- }- Err(e) => tracing::warn!(- "[claude-code][driver] in-process MCP HTTP server unavailable: {e}; CC running without OpenHuman MCP tools"- ),- }- }-- // The user explicitly opts into Claude Code, so we do NOT limit its toolset- // on any platform — CC always gets its full tools + `bypassPermissions`.- // The jail (macOS Seatbelt, below) is purely the `.openhuman` wall: it- // doesn't restrict CC, it just protects OpenHuman's internal data where the- // OS supports it. On Linux/Windows there's no OS wall yet, so CC runs- // unconfined there (user's machine, user's call).- let jailed = seatbelt_available();- // `jailed` is only consumed by the macOS Seatbelt spawn-wrap below.- #[cfg(not(target_os = "macos"))]- let _ = jailed;-- // Permission posture is a USER choice. Default `acceptEdits` (file edits- // only); the user opts into `bypassPermissions` (full toolset incl. bash)- // explicitly. On macOS the Seatbelt jail walls off `~/.openhuman` in either- // mode; on Linux/Windows full access is unconfined.- let full_access = claude_code_full_access(&ctx.workspace_dir);- let permission_mode = if full_access {- "bypassPermissions"- } else {- "acceptEdits"- };-- let mut args: Vec<String> = vec![- "-p".into(),- "--input-format".into(),- "stream-json".into(),- "--output-format".into(),- "stream-json".into(),- "--verbose".into(),- "--include-partial-messages".into(),- // Grant file-tool access to the user's project root (cwd is set to the- // same dir below). This is where the coding agent reads/edits code.- "--add-dir".into(),- ctx.project_dir.display().to_string(),- // Default `acceptEdits` (auto-apply edits, gate the rest); the user can- // opt into `bypassPermissions` for the full toolset (see above).- "--permission-mode".into(),- permission_mode.to_string(),- if is_new {- "--session-id".into()- } else {- "--resume".into()- },- cc_session_id.clone(),- "--model".into(),- ctx.model.clone(),- ];- args.extend(- append_system_prompt_args(scratch.path(), ctx.append_system_prompt.as_deref())- .map_err(|e| anyhow::anyhow!("write Claude Code system prompt file: {e}"))?,- );- if let Some(p) = mcp_config_path.as_ref() {- args.push("--mcp-config".into());- args.push(p.display().to_string());- args.push("--strict-mcp-config".into());- }- // Tool surface follows the permission posture: full access → no- // `--disallowedTools` (CC keeps its entire toolset incl. Bash/network);- // default `acceptEdits` → withhold the dangerous builtins (edits only).- if !full_access {- args.push("--disallowedTools".into());- args.push(DISALLOWED_CC_BUILTINS.join(","));- }-- // Validate input *before* spawning so we don't launch a process we- // can't feed (CodeRabbit: validate before spawn).- let stdin_bytes = build_stdin(ctx.messages, is_new);- if stdin_bytes.is_empty() {- anyhow::bail!("[claude-code][driver] no input messages to deliver");- }-- tracing::debug!(- "[claude-code][driver] spawn bin={} model={} is_new={} cc_session_id={}",- ctx.bin_path.display(),- ctx.model,- is_new,- cc_session_id- );-- // Best-effort: ensure the project dir exists so spawn (cwd) doesn't fail.- std::fs::create_dir_all(&ctx.project_dir).ok();-- // Wrap the spawn in the macOS Seatbelt jail when available so CC's file- // writes are OS-confined: `sandbox-exec -p <profile> <claude> <args…>`.- #[cfg(target_os = "macos")]- let (program, final_args): (PathBuf, Vec<String>) = if jailed {- let profile = seatbelt_profile(&ctx.workspace_dir);- let mut wrapped = vec![- "-p".to_string(),- profile,- ctx.bin_path.display().to_string(),- ];- wrapped.extend(args.iter().cloned());- tracing::debug!(- "[claude-code][driver] seatbelt jail active root={}",- ctx.project_dir.display()- );- (PathBuf::from("/usr/bin/sandbox-exec"), wrapped)- } else {- (ctx.bin_path.clone(), args.clone())- };- #[cfg(not(target_os = "macos"))]- let (program, final_args): (PathBuf, Vec<String>) = (ctx.bin_path.clone(), args.clone());-- let mut cmd = Command::new(&program);- cmd.args(&final_args)- .current_dir(&ctx.project_dir)- .stdin(Stdio::piped())- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .kill_on_drop(true);- if let Some(key) = &ctx.anthropic_api_key {- cmd.env("ANTHROPIC_API_KEY", key);- }- // A Finder/Dock launch inherits a stripped launchd PATH; make sure the CLI- // and anything it invokes resolve by prepending the user's bin dirs.- cmd.env("PATH", child_path_with_user_bins(&ctx.bin_path));-- let mut child = cmd- .spawn()- .map_err(|e| anyhow::anyhow!("failed to spawn `claude`: {e}"))?;- if let Some(mut stdin) = child.stdin.take() {- stdin- .write_all(&stdin_bytes)- .await- .map_err(|e| anyhow::anyhow!("write stdin: {e}"))?;- stdin- .shutdown()- .await- .map_err(|e| anyhow::anyhow!("close stdin: {e}"))?;- }-- let mut stdout = child- .stdout- .take()- .ok_or_else(|| anyhow::anyhow!("claude child stdout missing"))?;- let mut stderr = child- .stderr- .take()- .ok_or_else(|| anyhow::anyhow!("claude child stderr missing"))?;-- let mut parser = StreamJsonParser::new();- let mut mapper = EventMapper::new();- let mut buf = [0u8; 8192];-- // Drain stderr in parallel into a buffer for diagnostics.- let stderr_task = tokio::spawn(async move {- let mut acc = String::new();- let mut tmp = [0u8; 4096];- while let Ok(n) = stderr.read(&mut tmp).await {- if n == 0 {- break;- }- push_bounded(- &mut acc,- &String::from_utf8_lossy(&tmp[..n]),- STDERR_DIAGNOSTIC_CAP,- );- }- acc- });-- // Wrap the streaming + wait in a timeout so a stuck CLI doesn't- // block this task forever (PLAN §8).- let timeout = turn_timeout();- let timed = tokio::time::timeout(timeout, async {- loop {- let n = stdout- .read(&mut buf)- .await- .map_err(|e| anyhow::anyhow!("read stdout: {e}"))?;- if n == 0 {- break;- }- for ev in parser.feed_bytes(&buf[..n]) {- if let Some(msg) = parse_error_log_line(&ev) {- tracing::warn!("{msg}");- }- for delta in mapper.handle(ev) {- if let Some(tx) = ctx.stream {- let _ = tx.send(delta).await;- }- }- }- }- for ev in parser.end() {- if let Some(msg) = parse_error_log_line(&ev) {- tracing::warn!("{msg}");- }- for delta in mapper.handle(ev) {- if let Some(tx) = ctx.stream {- let _ = tx.send(delta).await;- }- }- }-- let status = child- .wait()- .await- .map_err(|e| anyhow::anyhow!("wait child: {e}"))?;- Ok::<_, anyhow::Error>(status)- })- .await;-- let status = match timed {- Ok(inner) => inner?,- Err(_elapsed) => {- tracing::error!(- "[claude-code][driver] turn timeout ({timeout:?}) exceeded; killing child"- );- // kill_on_drop handles cleanup, but explicit kill gives us- // a chance to collect stderr.- let _ = child.kill().await;- anyhow::bail!("[claude-code][driver] turn timed out after {:?}", timeout);- }- };-- let stderr_text = stderr_task.await.unwrap_or_default();-- if !status.success() {- // The CLI reports most failures (bad auth, unknown model, invalid- // session) as a structured `result`/`error` event on stdout and often- // leaves stderr empty. Prefer that message; fall back to stderr only- // when stdout carried none.- anyhow::bail!(- "{}",- nonzero_exit_message(- status.code(),- mapper.error.as_deref(),- &stderr_text,- ctx.anthropic_api_key.as_deref(),- )- );- }- if let Some(err) = mapper.error.clone() {- anyhow::bail!("[claude-code][driver] {}", err);- }-- // Do not make a session durable until Claude has accepted the launch and- // completed the turn. A spawn, input, timeout, or CLI validation failure- // must leave the thread eligible for a fresh `--session-id` retry rather- // than poisoning it with a UUID Claude never created.- if is_new {- let accepted_id = mapper.session_id.as_deref().unwrap_or(&cc_session_id);- if let Err(error) = ctx.session_store.set(&ctx.thread_id, accepted_id) {- tracing::warn!(- "[claude-code][driver] failed to persist accepted session uuid for thread {}: {}",- ctx.thread_id,- error- );- }- }-- Ok(mapper.into_response())-}--#[cfg(test)]-#[path = "driver_tests.rs"]-mod tests;