Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(agent): surface rejected model keys and silent runs; refuse --wire without --base-url (CUA-3069) (#6293)
Francesco Bonaccif595a4fb6f52
diff --git a/libs/cua/crates/cua-agents/runner/acp-runner.mjs b/libs/cua/crates/cua-agents/runner/acp-runner.mjsindex af6ff6f463..911967f5fa 100644--- a/libs/cua/crates/cua-agents/runner/acp-runner.mjs+++ b/libs/cua/crates/cua-agents/runner/acp-runner.mjs@@ -663,8 +663,7 @@ const env = { ...process.env, ...(cfg.env ?? {}), ...secrets };// (cfg.keyCheck: url, headers with ${NAME} references into the run's env,// keyEnv), ask the provider once, in parallel with the agent's start. Only// a definitive "this key is invalid" (HTTP 401, or a 403 that says so, with-// the provider's JSON error body) counts: no key, a base-URL or sign-in-// override, a network error, a timeout, a 429 or a 5xx all resolve to null+// the provider's JSON error body) counts: no key, a sign-in override, a network error, a timeout, a 429 or a 5xx all resolve to null// and the run goes on exactly as before, so the check can never block one.const KEY_CHECK_TIMEOUT_MS = 3000;@@ -696,7 +695,12 @@ async function checkKey(spec) {if (res.status !== 401 && res.status !== 403) return null;const error = JSON.parse(await res.text())?.error;if (!error || typeof error !== "object") return null;- const invalid = error.type === "authentication_error" || error.code === "invalid_api_key";+ // A custom endpoint (a gateway) words its 401 in its own shape: any 401+ // with a JSON error is a rejection there.+ const invalid =+ error.type === "authentication_error" ||+ error.code === "invalid_api_key" ||+ (spec.anyAuthError === true && res.status === 401);if (res.status === 403 && !invalid) return null;const why = providerMessage(error) || "the API key was rejected.";return { status: res.status, message: `Failed to authenticate. ${spec.provider ?? "Provider"} API Error: ${res.status} ${why}` };diff --git a/libs/cua/crates/cua-agents/runner/test/key-check.test.mjs b/libs/cua/crates/cua-agents/runner/test/key-check.test.mjsindex 8e9f4e4c53..a7495d2db4 100644--- a/libs/cua/crates/cua-agents/runner/test/key-check.test.mjs+++ b/libs/cua/crates/cua-agents/runner/test/key-check.test.mjs@@ -207,6 +207,18 @@ test("a 403 that says the key is invalid also ends the turn", async () => {}});+test("a gateway's own 401 shape ends the turn when the check is for a custom endpoint", async () => {+ const body = json(401, { error: { message: "Authentication Error, invalid key", type: "auth_error", code: "401" } });+ const p = await provider(body);+ try {+ const r = await run({ port: p.port, keyCheck: { anyAuthError: true, skipIfEnv: [], provider: "The model endpoint" } });+ assert.equal(r.prompts, 0);+ assert.match(r.events.find((e) => e.type === "error").message, /The model endpoint API Error: 401/);+ } finally {+ p.close();+ }+});+test("an accepted key sends the prompt as before, with no error", async () => {const p = await provider(json(200, { data: [], has_more: false }));try {diff --git a/libs/cua/crates/cua-agents/src/durable.rs b/libs/cua/crates/cua-agents/src/durable.rsindex 0487c99e5a..6a5c005431 100644--- a/libs/cua/crates/cua-agents/src/durable.rs+++ b/libs/cua/crates/cua-agents/src/durable.rs@@ -524,7 +524,7 @@ pub fn durable_driver_spec("exitWhenIdle": true,"idleExitSecs": opts.idle_exit_secs.unwrap_or(1800),"authMethod": h.auth_method,- "keyCheck": harness::key_check(h, &opts.env, endpoint.is_some()),+ "keyCheck": harness::key_check(h, &opts.env, endpoint.as_ref()),"mcpBridge": "~/.cua/bin/mcp-remote","modeKinds": h.mode_kinds,"guardModeKinds": guard_mode_kinds(h),diff --git a/libs/cua/crates/cua-agents/src/harness.rs b/libs/cua/crates/cua-agents/src/harness.rsindex 519551ba8b..39c50c3c87 100644--- a/libs/cua/crates/cua-agents/src/harness.rs+++ b/libs/cua/crates/cua-agents/src/harness.rs@@ -425,10 +425,10 @@ impl Harness {pub fn key_check(h: &Harness,env: &BTreeMap<String, String>,- custom_endpoint: bool,+ endpoint: Option<&Endpoint>,) -> Option<Value> {- if custom_endpoint {- return None;+ if let Some(e) = endpoint {+ return endpoint_key_check(h, env, e);}let (provider, url, candidates, skip_env, skip_file): (&str, &str, &[&str], &[&str], &[&str]) =match h.id {@@ -480,6 +480,30 @@ pub fn key_check(}))}+/// The key check for a custom endpoint (`--base-url`): the same one read-only+/// request, sent to the gateway instead of the provider. Only Claude Code on+/// the Anthropic wire has a models list we can name; a gateway answers 401 in+/// its own error shape, so any 401 with a JSON error counts (`anyAuthError`).+fn endpoint_key_check(h: &Harness, env: &BTreeMap<String, String>, e: &Endpoint) -> Option<Value> {+ if h.id != "claude-code" || e.wire.is_some_and(|w| w != Wire::Anthropic) {+ return None;+ }+ let key = "ANTHROPIC_API_KEY";+ if env.get(key).is_none_or(String::is_empty) {+ return None;+ }+ let base = trim_v1(e.base_url.trim_end_matches('/'));+ Some(json!({+ "provider": "The model endpoint",+ "url": format!("{base}/v1/models?limit=1"),+ "keyEnv": key,+ "headers": {"x-api-key": format!("${{{key}}}"), "anthropic-version": "2023-06-01"},+ "skipIfEnv": [],+ "skipIfFile": [],+ "anyAuthError": true,+ }))+}+/// A custom model endpoint (a proxy, a gateway, a compatible server).#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, serde::Deserialize)]pub struct Endpoint {@@ -1244,7 +1268,7 @@ mod tests {fn a_key_check_names_the_providers_models_list_and_holds_no_secret() {let secret = "sk-ant-test-0123456789abcdef";let claude = harness("claude-code").unwrap();- let c = key_check(claude, &env(&[("ANTHROPIC_API_KEY", secret)]), false).unwrap();+ let c = key_check(claude, &env(&[("ANTHROPIC_API_KEY", secret)]), None).unwrap();assert_eq!(c["provider"], "Anthropic");assert_eq!(c["url"], "https://api.anthropic.com/v1/models?limit=1");assert_eq!(c["keyEnv"], "ANTHROPIC_API_KEY");@@ -1262,7 +1286,7 @@ mod tests {let c = key_check(codex,&env(&[("CODEX_API_KEY", "sk-test-0123456789")]),- false,+ None,).unwrap();assert_eq!(c["provider"], "OpenAI");@@ -1278,18 +1302,30 @@ mod tests {let claude = harness("claude-code").unwrap();let codex = harness("openai-codex").unwrap();// No key, or an empty one: the runner has nothing to ask about.- assert!(key_check(claude, &env(&[]), false).is_none());- assert!(key_check(claude, &env(&[("ANTHROPIC_API_KEY", "")]), false).is_none());- // A custom endpoint takes the key, not the provider.- assert!(key_check(claude, &env(&[("ANTHROPIC_API_KEY", "k")]), true).is_none());+ assert!(key_check(claude, &env(&[]), None).is_none());+ assert!(key_check(claude, &env(&[("ANTHROPIC_API_KEY", "")]), None).is_none());+ // A custom endpoint takes the key, not the provider: the check goes+ // to the gateway, and only for Claude Code on the Anthropic wire.+ let ep = |wire| Endpoint {+ base_url: "http://gw:4000/v1".into(),+ wire,+ model: None,+ };+ let k = env(&[("ANTHROPIC_API_KEY", "k")]);+ let c = key_check(claude, &k, Some(&ep(None))).unwrap();+ assert_eq!(c["url"], "http://gw:4000/v1/models?limit=1");+ assert_eq!(c["anyAuthError"], true);+ assert_eq!(c["skipIfEnv"], json!([]));+ assert!(key_check(claude, &k, Some(&ep(Some(Wire::Gemini)))).is_none());+ assert!(key_check(codex, &k, Some(&ep(None))).is_none());// Claude Code reads other credentials too; only the API key is checked.- assert!(key_check(claude, &env(&[("CLAUDE_CODE_OAUTH_TOKEN", "t")]), false).is_none());+ assert!(key_check(claude, &env(&[("CLAUDE_CODE_OAUTH_TOKEN", "t")]), None).is_none());// Two keys for one harness: cua cannot tell which one it uses.assert!(key_check(codex,&env(&[("OPENAI_API_KEY", "a"), ("CODEX_API_KEY", "b")]),- false+ None).is_none());@@ -1303,7 +1339,7 @@ mod tests {.iter().map(|k| (k.to_string(), "k".to_string())).collect();- assert!(key_check(h, &all, false).is_none(), "{}", h.id);+ assert!(key_check(h, &all, None).is_none(), "{}", h.id);}}diff --git a/libs/cua/crates/cua-agents/src/harness.rs-E b/libs/cua/crates/cua-agents/src/harness.rs-Enew file mode 100644index 0000000000..1a0cf20ea4--- /dev/null+++ b/libs/cua/crates/cua-agents/src/harness.rs-E@@ -0,0 +1,1418 @@+//! The harnesses: which installables each needs, how it speaks the Agent+//! Client Protocol, how it authenticates headlessly, and how it is pointed+//! at a custom endpoint. None of this parses a harness's output: every+//! harness is driven over ACP, natively or through its maintained adapter.++use std::collections::BTreeMap;++use serde::Serialize;+use serde_json::{Value, json};++/// A model endpoint's wire format.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, serde::Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum Wire {+ /// Anthropic Messages.+ Anthropic,+ /// OpenAI Responses.+ OpenaiResponses,+ /// OpenAI Chat Completions (and compatible servers).+ OpenaiChat,+ /// Gemini API.+ Gemini,+}++impl Wire {+ /// Parses `anthropic`, `openai-responses`, `openai-chat` or `gemini`.+ pub fn parse(s: &str) -> Option<Wire> {+ match s {+ "anthropic" => Some(Wire::Anthropic),+ "openai-responses" | "responses" => Some(Wire::OpenaiResponses),+ "openai-chat" | "openai" | "chat" => Some(Wire::OpenaiChat),+ "gemini" | "google" => Some(Wire::Gemini),+ _ => None,+ }+ }+}++/// One harness.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Harness {+ /// Id (`claude-code`, `openai-codex`, ...).+ pub id: &'static str,+ /// Display name.+ pub name: &'static str,+ /// What to install (see `installables.json`), dependencies implied.+ pub installs: &'static [&'static str],+ /// The ACP agent: a binary in `~/.cua/bin` and its arguments.+ pub acp: &'static [&'static str],+ /// The interactive CLI a human uses in a terminal, when there is one.+ pub cli: Option<&'static str>,+ /// Credential env vars the harness reads, in preference order.+ pub keys: &'static [&'static str],+ /// Shell tests (run in the guest) for a sign-in the harness uses+ /// instead of a key: a credentials file under `$HOME`, a Keychain item.+ /// `Some(&[])`: only a key works. `None`: the harness can also be set up+ /// through config files cua does not know, so a missing key is not+ /// conclusive (no harness here is `None` any more: each lists the files+ /// of its own setup, and a run without a key or one of them is refused+ /// before the install).+ pub logins: Option<&'static [&'static str]>,+ /// ACP `authenticate` method used with an env key, when the agent+ /// requires one.+ pub auth_method: Option<&'static str>,+ /// Wire formats it can be pointed at with a base URL.+ pub wires: &'static [Wire],+ /// The agent-side mode to select (by ACP `_meta.kind` or id): the+ /// sandbox is the boundary, so a harness's own sandbox is switched off.+ pub mode_kinds: &'static [&'static str],+ /// The `cua-agent-setup` registry id whose skills directory it reads.+ pub skills_agent: Option<&'static str>,+ /// Whether runs get the sandbox's own MCP (cua-driver) by default.+ pub sandbox_mcp: bool,+ /// Supported by the SDK: installed, driven and proven live.+ pub ready: bool,+ /// What is known not to work, published with its capabilities.+ pub notes: &'static [&'static str],+}++const FULL: &[&str] = &["full_access", "bypassPermissions", "yolo"];++/// Every harness.+pub const HARNESSES: &[Harness] = &[+ Harness {+ id: "claude-code",+ name: "Claude Code",+ installs: &["claude-agent-acp", "claude-code"],+ acp: &["claude-agent-acp"],+ cli: Some("claude"),+ keys: cua_connections::READS_CLAUDE_CODE,+ logins: Some(&[+ "[ -s \"$HOME/.claude/.credentials.json\" ]",+ "security find-generic-password -s 'Claude Code-credentials' >/dev/null 2>&1",+ ]),+ auth_method: None,+ wires: &[Wire::Anthropic],+ mode_kinds: FULL,+ skills_agent: Some("claude-code"),+ sandbox_mcp: true,+ ready: true,+ notes: &[],+ },+ Harness {+ id: "openai-codex",+ name: "OpenAI Codex",+ installs: &["codex-acp"],+ acp: &["codex-acp"],+ cli: Some("codex"),+ // CODEX_AUTH_JSON: the ChatGPT sign-in Connect copied from the+ // person's Mac (their `~/.codex/auth.json`, OpenAI's documented+ // headless route). A run writes it to the guest's+ // `~/.codex/auth.json` when the guest has none ([`crate::runs`]).+ keys: cua_connections::READS_OPENAI_CODEX,+ logins: Some(&["[ -s \"$HOME/.codex/auth.json\" ]"]),+ auth_method: None,+ wires: &[Wire::OpenaiResponses],+ mode_kinds: FULL,+ skills_agent: Some("codex"),+ sandbox_mcp: true,+ ready: true,+ notes: &[],+ },+ Harness {+ id: "gemini-cli",+ name: "Gemini CLI",+ installs: &["gemini-cli"],+ acp: &["gemini", "--acp"],+ cli: Some("gemini"),+ keys: cua_connections::READS_GEMINI_CLI,+ logins: Some(&[]),+ auth_method: Some("gemini-api-key"),+ wires: &[Wire::Gemini],+ mode_kinds: FULL,+ skills_agent: Some("gemini-cli"),+ sandbox_mcp: true,+ ready: true,+ notes: &[+ "Google stopped serving free Gemini CLI accounts on 2026-06-18; use a paid API key",+ ],+ },+ Harness {+ id: "google-antigravity",+ name: "Google Antigravity",+ installs: &["antigravity-acp"],+ acp: &["agy-acp-server", "--uid="],+ cli: None,+ keys: cua_connections::READS_GOOGLE_ANTIGRAVITY,+ logins: Some(&[]),+ auth_method: Some("gemini-api-key"),+ wires: &[Wire::Gemini],+ mode_kinds: FULL,+ skills_agent: Some("antigravity"),+ sandbox_mcp: true,+ ready: true,+ notes: &[+ "runs Google's ACP server (the IDE's agent) headless; there is no interactive terminal CLI",+ "the server is proprietary and about 1 GB; its sha256 is pinned by cua (Google publishes none)",+ ],+ },+ Harness {+ id: "opencode",+ name: "OpenCode",+ installs: &["opencode"],+ acp: &["opencode", "acp"],+ cli: Some("opencode"),+ keys: cua_connections::READS_OPENCODE,+ logins: Some(&[+ "[ -s \"$HOME/.local/share/opencode/auth.json\" ]",+ "[ -s \"$HOME/.config/opencode/opencode.json\" ]",+ ]),+ auth_method: None,+ wires: &[Wire::OpenaiChat],+ mode_kinds: FULL,+ skills_agent: Some("opencode"),+ sandbox_mcp: true,+ ready: true,+ notes: &[],+ },+ Harness {+ id: "goose",+ name: "Goose",+ installs: &["goose"],+ acp: &["goose", "acp"],+ cli: Some("goose"),+ keys: cua_connections::READS_GOOSE,+ logins: Some(&[+ "[ -s \"$HOME/.config/goose/config.yaml\" ]",+ "[ -s \"$HOME/.config/goose/secrets.yaml\" ]",+ ]),+ auth_method: None,+ wires: &[Wire::OpenaiChat],+ mode_kinds: FULL,+ skills_agent: Some("goose"),+ sandbox_mcp: true,+ ready: true,+ notes: &[],+ },+ Harness {+ id: "pi",+ name: "Pi",+ installs: &["pi"],+ acp: &["pi-acp"],+ cli: Some("pi"),+ keys: cua_connections::READS_PI,+ logins: Some(&[+ "[ -s \"$HOME/.pi/agent/auth.json\" ]",+ "[ -s \"$HOME/.pi/agent/models.json\" ]",+ ]),+ auth_method: None,+ wires: &[Wire::OpenaiChat],+ mode_kinds: FULL,+ skills_agent: Some("pi"),+ sandbox_mcp: false,+ ready: true,+ notes: &[+ "Pi has no MCP client (by design); MCP servers passed to a run are ignored",+ "driven through the community pi-acp adapter (MIT), not a first-party ACP server",+ ],+ },+ Harness {+ id: "hermes",+ name: "Hermes",+ installs: &["hermes"],+ acp: &["hermes-acp"],+ cli: Some("hermes"),+ // Provider API keys only, for every provider Hermes supports. The+ // Claude subscription sign-in (CLAUDE_CODE_OAUTH_TOKEN) and the ChatGPT+ // one (CODEX_AUTH_JSON) are Claude Code's and Codex's: they are never+ // given to Hermes (the provider files scope them).+ keys: cua_connections::READS_HERMES,+ // Its own `.env` (a key set inside the Space) or a provider sign-in.+ logins: Some(&[+ "[ -s \"$HOME/.hermes/.env\" ]",+ "[ -s \"$HOME/.hermes/auth.json\" ]",+ ]),+ auth_method: None,+ wires: &[Wire::OpenaiChat],+ mode_kinds: FULL,+ skills_agent: None,+ sandbox_mcp: false,+ ready: true,+ notes: &[+ "hermes-acp does not take ACP session MCP servers; configure MCP in HERMES_HOME's config.yaml",+ "installed from a pinned commit with uv sync --frozen (Hermes ships no wheel); needs git and Python 3.11 to 3.13 or uv's managed Python",+ "cua skills are not copied into ~/.hermes/skills",+ ],+ },+ Harness {+ id: "openclaw",+ name: "OpenClaw",+ installs: &["openclaw"],+ acp: &["openclaw", "acp"],+ cli: Some("openclaw"),+ keys: cua_connections::READS_OPENCLAW,+ logins: Some(&[+ "[ -s \"$HOME/.openclaw/openclaw.json\" ]",+ "[ -s \"$HOME/.openclaw/.env\" ]",+ ]),+ auth_method: None,+ wires: &[Wire::OpenaiChat],+ mode_kinds: FULL,+ skills_agent: Some("openclaw"),+ sandbox_mcp: false,+ ready: true,+ notes: &[+ "openclaw acp (bridge mode) refuses per-session MCP servers; configure MCP on the OpenClaw gateway",+ "openclaw acp bridges to a Gateway; the run starts a loopback Gateway for itself",+ ],+ },+];++impl Harness {+ /// The provider whose Connect row gives this harness a credential+ /// (`anthropic`, `openai`), when it has one. Hermes reads either; the+ /// first is named.+ pub fn connect_provider(&self) -> Option<&'static str> {+ match self.id {+ "claude-code" | "hermes" | "opencode" | "pi" | "openclaw" | "goose" => {+ Some("anthropic")+ }+ "openai-codex" => Some("openai"),+ _ => None,+ }+ }+}++/// Short names people and apps use for a harness, and the id they mean.+const ALIASES: &[(&str, &str)] = &[("codex", "openai-codex"), ("claude", "claude-code")];++/// A harness by id (or by one of its short names: `codex`, `claude`).+pub fn harness(id: &str) -> Option<&'static Harness> {+ let id = ALIASES+ .iter()+ .find(|(a, _)| *a == id)+ .map_or(id, |(_, c)| c);+ HARNESSES.iter().find(|h| h.id == id)+}++/// The env var an endpoint's key is read from, for `h` and `wire`.+pub fn endpoint_key_var(h: &Harness, wire: Option<Wire>) -> &'static str {+ match wire.unwrap_or(h.wires[0]) {+ Wire::Anthropic => "ANTHROPIC_API_KEY",+ Wire::Gemini => "GEMINI_API_KEY",+ Wire::OpenaiChat | Wire::OpenaiResponses => "OPENAI_API_KEY",+ }+}++/// Ids of every harness, sorted.+pub fn ids() -> Vec<&'static str> {+ let mut v: Vec<_> = HARNESSES.iter().map(|h| h.id).collect();+ v.sort_unstable();+ v+}++/// Ids of the ready harnesses, sorted.+pub fn ready() -> Vec<&'static str> {+ let mut v: Vec<_> = HARNESSES.iter().filter(|h| h.ready).map(|h| h.id).collect();+ v.sort_unstable();+ v+}++/// Whether a harness has a credential, as far as cua can tell.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum Auth {+ /// A credential source was found.+ Ok,+ /// None was found, and cua knows every source this harness uses.+ Missing,+ /// None was found, but the harness may be set up through its own config+ /// files (or there was nothing to look at).+ Unknown,+}++/// What the guest probe found: `env:<NAME>`, `login`, or `none`.+pub const PROBE_NONE: &str = "none";++/// Where the Cua Spaces app takes a key named `env` (Settings, Connections):+/// the provider that saves it, else under Other keys.+pub fn settings_hint(env: &str) -> String {+ match cua_connections::provider_of_env(env) {+ Some(p) => format!(+ "Connect {} in Cua Spaces \u{2192} Settings \u{2192} Connections",+ p.name+ ),+ None => format!(+ "Add {env} under Other keys in Cua Spaces \u{2192} Settings \u{2192} Connections"+ ),+ }+}++impl Harness {+ /// A POSIX sh script that prints where this harness's credential would+ /// come from in the guest: `env:<NAME>` for a key in the environment+ /// runs inherit, `login` for a sign-in, otherwise `none`.+ pub fn auth_probe(&self) -> String {+ let mut s = String::new();+ for k in self.keys {+ s.push_str(&format!(+ "[ -n \"${{{k}:-}}\" ] && {{ echo env:{k}; exit 0; }}\n"+ ));+ }+ for t in self.logins.unwrap_or_default() {+ s.push_str(&format!("{t} && {{ echo login; exit 0; }}\n"));+ }+ s.push_str(&format!("echo {PROBE_NONE}\n"));+ s+ }++ /// How to give this harness a credential: the keys it reads, how a key+ /// reaches a run, and signing in inside the Space where that works.+ pub fn auth_hint(&self) -> String {+ let Some(first) = self.keys.first() else {+ return format!("{} needs no key", self.name);+ };+ let others = if self.keys.len() > 1 {+ format!(" (or {})", self.keys[1..].join(", "))+ } else {+ String::new()+ };+ let mut s = format!(+ "{}, or set {first}{others} for the Cua daemon (export it, then `cua daemon stop` and `cua daemon start`) \+ and forward it with env_from_host: [\"{first}\"] (CLI: --env-from-host {first})",+ settings_hint(first)+ );+ match (self.logins, self.cli) {+ (Some(l), Some(cli)) if !l.is_empty() => {+ s.push_str(&format!(+ ", or sign in by running `~/.cua/bin/{cli}` inside the Space"+ ));+ }+ (None, _) => s.push_str(&format!(", or configure {} inside the Space", self.name)),+ _ => {}+ }+ s+ }++ /// The error for a run that has no credential, before anything is+ /// installed.+ pub fn missing_credential(&self) -> String {+ format!(+ "{} ({}) has no credential in this Space and would fail with \"Authentication required\": {}",+ self.name,+ self.id,+ self.auth_hint()+ )+ }+}++/// The request the runner makes once, at the start of a run, to learn+/// whether the provider rejects the run's API key (`keyCheck` in+/// `run.json`; see `runner/acp-runner.mjs`).+///+/// A rejected key is slow to surface otherwise: Claude Code retries a 401+/// ten times with growing pauses (about 3 minutes) and says nothing meanwhile.+/// One read-only GET on the provider's models list answers in about 100 ms.+/// Only a definitive "this key is invalid" ends the run's first turn; the+/// runner treats every other outcome as "carry on".+///+/// The spec holds no secret: header values are `${NAME}` references into the+/// run's env, which the runner resolves. `None` when there is nothing to+/// check: the harness has no known provider, the run's key is not among+/// `env` (the caller's own env: passed keys and saved Cua Spaces keys), more+/// than one candidate key is set (the harness picks, cua cannot tell which),+/// or a custom endpoint takes the key instead of the provider.+pub fn key_check(+ h: &Harness,+ env: &BTreeMap<String, String>,+ endpoint: Option<&Endpoint>,+) -> Option<Value> {+ if let Some(e) = endpoint {+ return endpoint_key_check(h, env, e);+ }+ let (provider, url, candidates, skip_env, skip_file): (&str, &str, &[&str], &[&str], &[&str]) =+ match h.id {+ // The adapter drives Claude Code with the API key; another+ // credential or backend takes precedence or replaces it.+ "claude-code" => (+ "Anthropic",+ "https://api.anthropic.com/v1/models?limit=1",+ &["ANTHROPIC_API_KEY"],+ &[+ "ANTHROPIC_BASE_URL",+ "ANTHROPIC_AUTH_TOKEN",+ "CLAUDE_CODE_OAUTH_TOKEN",+ "CLAUDE_CODE_USE_BEDROCK",+ "CLAUDE_CODE_USE_VERTEX",+ "CLAUDE_CODE_USE_FOUNDRY",+ ],+ &[],+ ),+ // A signed-in Codex may not use the key at all.+ "openai-codex" => (+ "OpenAI",+ "https://api.openai.com/v1/models",+ &["OPENAI_API_KEY", "CODEX_API_KEY"],+ &["OPENAI_BASE_URL", "OPENAI_API_BASE"],+ &["~/.codex/auth.json"],+ ),+ _ => return None,+ };+ let mut set = candidates+ .iter()+ .filter(|k| env.get(**k).is_some_and(|v| !v.is_empty()));+ let key = match (set.next(), set.next()) {+ (Some(k), None) => *k,+ _ => return None,+ };+ let headers = if h.id == "claude-code" {+ json!({"x-api-key": format!("${{{key}}}"), "anthropic-version": "2023-06-01"})+ } else {+ json!({"authorization": format!("Bearer ${{{key}}}")})+ };+ Some(json!({+ "provider": provider,+ "url": url,+ "keyEnv": key,+ "headers": headers,+ "skipIfEnv": skip_env,+ "skipIfFile": skip_file,+ }))+}++/// The key check for a custom endpoint (`--base-url`): the same one read-only+/// request, sent to the gateway instead of the provider. Only Claude Code on+/// the Anthropic wire has a models list we can name; a gateway answers 401 in+/// its own error shape, so any 401 with a JSON error counts (`anyAuthError`).+fn endpoint_key_check(h: &Harness, env: &BTreeMap<String, String>, e: &Endpoint) -> Option<Value> {+ if h.id != "claude-code" || e.wire.is_some_and(|w| w != Wire::Anthropic) {+ return None;+ }+ let key = "ANTHROPIC_API_KEY";+ if env.get(key).is_none_or(String::is_empty) {+ return None;+ }+ let base = trim_v1(e.base_url.trim_end_matches('/'));+ Some(json!({+ "provider": "The model endpoint",+ "url": format!("{base}/v1/models?limit=1"),+ "keyEnv": key,+ "headers": {"x-api-key": format!("${{{key}}}"), "anthropic-version": "2023-06-01"},+ "skipIfEnv": [],+ "skipIfFile": [],+ "anyAuthError": true,+ }))+}++/// A custom model endpoint (a proxy, a gateway, a compatible server).+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, serde::Deserialize)]+pub struct Endpoint {+ /// Base URL, for example `https://proxy.example/v1`.+ pub base_url: String,+ /// Wire format; default: the harness's first.+ #[serde(default)]+ pub wire: Option<Wire>,+ /// Model id; default: the harness's own default.+ #[serde(default)]+ pub model: Option<String>,+}++/// A file the SDK writes into the run directory before launch.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ConfigFile {+ /// Path relative to the run directory, or an absolute guest path (a+ /// persistent agent home).+ pub rel: String,+ pub body: String,+}++/// Everything a harness needs at launch besides the prompt.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Launch {+ /// Env for the agent (never secrets: those go to `secrets.json`).+ pub env: Vec<(String, String)>,+ /// Extra ACP-agent arguments.+ pub args: Vec<String>,+ /// Config files, relative to the run directory.+ pub files: Vec<ConfigFile>,+ /// A wrapper that starts the agent (OpenClaw's Gateway).+ pub wrapper: Option<String>,+ /// Shell lines the launcher runs before it starts the agent (linking a+ /// signed-in harness's credentials into a relocated config dir).+ pub prelude: Vec<String>,+}++fn trim_v1(url: &str) -> &str {+ url.trim_end_matches('/').trim_end_matches("/v1")+}++fn v1(url: &str) -> String {+ format!("{}/v1", trim_v1(url))+}++/// The env, arguments and files that point `h` at `endpoint` (when given)+/// and select a model, for a run whose directory is `run_dir`.+pub fn launch(+ h: &Harness,+ endpoint: Option<&Endpoint>,+ model: Option<&str>,+ run_dir: &str,+ cwd: &str,+) -> crate::Result<Launch> {+ launch_with_home(h, endpoint, model, run_dir, cwd, None)+}++/// Where each harness keeps its memory inside a persistent agent home, so+/// what the agent learns outlives the run and the Space. Paths are relative+/// to the home.+///+/// | Harness | Memory | How it gets there |+/// |---|---|---|+/// | Claude Code | `claude-memory/` | `autoMemoryDirectory` in a per-run `CLAUDE_CONFIG_DIR` |+/// | Codex | `codex/memories/` | `CODEX_HOME=<home>/codex` with `[features] memories = true`; SQLite state off the Volume (`sqlite_home`) |+/// | Hermes | `hermes/memories/` | `HERMES_HOME=<home>/hermes` |+/// | OpenClaw | `workspace/` (`MEMORY.md`, `memory/`) | `OPENCLAW_WORKSPACE_DIR=<home>/workspace` |+///+/// Every harness also works in `<home>/work` unless the caller names a+/// working directory.+pub fn memory_dir(h: &Harness) -> Option<&'static str> {+ match h.id {+ "claude-code" => Some("claude-memory"),+ "openai-codex" => Some("codex/memories"),+ "hermes" => Some("hermes/memories"),+ "openclaw" => Some("workspace"),+ _ => None,+ }+}++/// Where Codex keeps its SQLite state for the persistent agent whose home is+/// `home`: guest-local disk, never the Volume. Homes are+/// `<guest home>/cua-volume/agents/<name>` (see `runs::HOMES_DIR`), so the+/// state is `<guest home>/.cua/agents/codex-state/<name>`; a home elsewhere+/// (an explicit `home_dir`) keeps it in its own `.codex-sqlite` sibling.+pub fn codex_sqlite_dir(home: &str) -> String {+ let home = home.trim_end_matches('/');+ let marker = "/cua-volume/agents/";+ match home.rsplit_once(marker) {+ Some((guest_home, name)) if !name.contains('/') && !name.is_empty() => {+ format!("{guest_home}/.cua/agents/codex-state/{name}")+ }+ _ => format!("{home}.codex-sqlite"),+ }+}++/// [`launch`] for a persistent agent whose home is the guest directory+/// `home` (see [`memory_dir`]).+pub fn launch_with_home(+ h: &Harness,+ endpoint: Option<&Endpoint>,+ model: Option<&str>,+ run_dir: &str,+ cwd: &str,+ home: Option<&str>,+) -> crate::Result<Launch> {+ launch_with_config(h, endpoint, model, run_dir, cwd, home, None)+}++/// [`launch_with_home`] with `hermes_config`: the `config.yaml` Cua generated+/// from the person's connections (`cua_connections::hermes`). Hermes then+/// starts from it, not from the guest's own setup, and uses the provider it+/// names. Ignored for any other harness and when an endpoint is given.+pub fn launch_with_config(+ h: &Harness,+ endpoint: Option<&Endpoint>,+ model: Option<&str>,+ run_dir: &str,+ cwd: &str,+ home: Option<&str>,+ hermes_config: Option<&str>,+) -> crate::Result<Launch> {+ let mut l = Launch::default();+ let model = endpoint+ .and_then(|e| e.model.clone())+ .or_else(|| model.map(str::to_string));+ if let Some(e) = endpoint {+ let wire = e.wire.unwrap_or(h.wires[0]);+ if !h.wires.contains(&wire) {+ return Err(crate::Error::Invalid(format!(+ "{} cannot use a {wire:?} endpoint (it speaks {:?})",+ h.name, h.wires+ )));+ }+ }+ let base = endpoint.map(|e| e.base_url.trim_end_matches('/').to_string());+ let env = |l: &mut Launch, k: &str, v: String| l.env.push((k.into(), v));+ match h.id {+ "claude-code" => {+ if let Some(b) = &base {+ env(&mut l, "ANTHROPIC_BASE_URL", trim_v1(b).to_string());+ }+ if let Some(m) = &model {+ env(&mut l, "ANTHROPIC_MODEL", m.clone());+ }+ if let Some(home) = home {+ // Only memory moves: a per-run config dir points auto memory+ // at the home, and borrows the guest's sign-in and skills.+ let cfg = format!("{run_dir}/claude-config");+ l.files.push(ConfigFile {+ rel: "claude-config/settings.json".into(),+ body: serde_json::to_string_pretty(+ &json!({"autoMemoryDirectory": format!("{home}/claude-memory")}),+ )?,+ });+ let q = crate::quote;+ l.prelude.extend([+ format!("mkdir -p {}", q(&format!("{home}/claude-memory"))),+ format!(+ "[ -e \"$HOME/.claude/.credentials.json\" ] && ln -sf \"$HOME/.claude/.credentials.json\" {}",+ q(&format!("{cfg}/.credentials.json"))+ ),+ format!(+ "[ -e \"$HOME/.claude.json\" ] && [ ! -e {c} ] && cp \"$HOME/.claude.json\" {c}",+ c = q(&format!("{cfg}/.claude.json"))+ ),+ format!(+ "[ -d \"$HOME/.claude/skills\" ] && ln -sfn \"$HOME/.claude/skills\" {}",+ q(&format!("{cfg}/skills"))+ ),+ "true".into(),+ ]);+ env(&mut l, "CLAUDE_CONFIG_DIR", cfg);+ }+ }+ "openai-codex" => {+ // With a home, CODEX_HOME is the home's `codex/` with memories+ // on; without one, a run-local CODEX_HOME holds only the provider+ // override.+ let codex_home = match home {+ Some(h) => Some(format!("{h}/codex")),+ None => base.as_ref().map(|_| format!("{run_dir}/codex-home")),+ };+ let mut toml = String::new();+ if let Some(b) = &base {+ let m = model.clone().unwrap_or_else(|| "gpt-5-codex".into());+ toml.push_str(&format!(+ "model = {m:?}\nmodel_provider = \"cua\"\n\n[model_providers.cua]\n\+ name = \"custom endpoint\"\nbase_url = {:?}\nenv_key = \"OPENAI_API_KEY\"\n\+ wire_api = \"responses\"\n",+ v1(b)+ ));+ } else if let Some(m) = &model {+ l.args.extend(["-c".into(), format!("model={m:?}")]);+ }+ if home.is_some() {+ if !toml.is_empty() {+ toml.push('\n');+ }+ toml.push_str("[features]\nmemories = true\n");+ }+ // Codex keeps its SQLite state (WAL, shared memory) under+ // CODEX_HOME unless told otherwise, and the home is on the Volume,+ // which cannot map shared memory ("failed to initialize sqlite+ // state runtime"). Point it at guest-local disk instead; only+ // config and memories stay on the Volume. `sqlite_home` is a+ // top-level key, so it goes before any table, and it is written on+ // every start with the rest of the generated config.+ if let Some(dir) = home.map(codex_sqlite_dir) {+ toml.insert_str(0, &format!("sqlite_home = {dir:?}\n\n"));+ l.prelude.push(format!("mkdir -p {}", crate::quote(&dir)));+ env(&mut l, "CODEX_SQLITE_HOME", dir);+ }+ if let Some(dir) = codex_home {+ let rel = match home {+ Some(_) => format!("{dir}/config.toml"),+ None => "codex-home/config.toml".into(),+ };+ l.files.push(ConfigFile { rel, body: toml });+ if home.is_some() {+ // A signed-in guest keeps its login; auth.json is never+ // synced to the drive.+ // A link left by an earlier Space (its target gone) is+ // replaced, or it would hide the fresh sign-in.+ l.prelude.push(format!(+ "[ -L {a} ] && [ ! -e {a} ] && rm -f {a}; \+ [ -e \"$HOME/.codex/auth.json\" ] && [ ! -e {a} ] && ln -s \"$HOME/.codex/auth.json\" {a}; true",+ a = crate::quote(&format!("{dir}/auth.json"))+ ));+ }+ env(&mut l, "CODEX_HOME", dir);+ }+ }+ "gemini-cli" | "google-antigravity" => {+ if h.id == "gemini-cli" {+ // The sandbox is the boundary; an untrusted folder would+ // disable the run's MCP servers and full-access mode.+ env(&mut l, "GEMINI_CLI_TRUST_WORKSPACE", "true".into());+ }+ if let Some(b) = &base {+ env(&mut l, "GOOGLE_GEMINI_BASE_URL", trim_v1(b).to_string());+ }+ if h.id == "gemini-cli"+ && let Some(m) = &model+ {+ l.args.extend(["--model".into(), m.clone()]);+ }+ }+ "opencode" => {+ if let Some(b) = &base {+ let m = model.clone().unwrap_or_else(|| "default".into());+ let cfg = json!({+ "$schema": "https://opencode.ai/config.json",+ "provider": {"cua": {+ "npm": "@ai-sdk/openai-compatible",+ "name": "custom endpoint",+ "options": {"baseURL": v1(b), "apiKey": "{env:OPENAI_API_KEY}"},+ "models": {m.clone(): {"name": m, "tool_call": true}}}},+ "model": format!("cua/{m}"),+ "autoupdate": false,+ "share": "disabled",+ });+ l.files.push(ConfigFile {+ rel: "xdg/opencode/opencode.json".into(),+ body: serde_json::to_string_pretty(&cfg)?,+ });+ env(&mut l, "XDG_CONFIG_HOME", format!("{run_dir}/xdg"));+ }+ }+ "goose" => {+ env(&mut l, "GOOSE_MODE", "auto".into());+ env(&mut l, "GOOSE_DISABLE_KEYRING", "1".into());+ if let Some(b) = &base {+ env(&mut l, "GOOSE_PROVIDER", "openai".into());+ env(&mut l, "OPENAI_HOST", trim_v1(b).to_string());+ }+ if let Some(m) = &model {+ env(&mut l, "GOOSE_MODEL", m.clone());+ }+ }+ "pi" => {+ if let Some(b) = &base {+ let m = model.clone().unwrap_or_else(|| "default".into());+ let models = json!({"providers": {"cua": {"baseUrl": v1(b),+ "api": "openai-completions", "apiKey": "${OPENAI_API_KEY}",+ "models": [{"id": m}]}}});+ let settings =+ json!({"defaultProvider": "cua", "defaultModel": m, "quietStartup": true});+ l.files.push(ConfigFile {+ rel: "pi-agent/models.json".into(),+ body: models.to_string(),+ });+ l.files.push(ConfigFile {+ rel: "pi-agent/settings.json".into(),+ body: settings.to_string(),+ });+ env(&mut l, "PI_CODING_AGENT_DIR", format!("{run_dir}/pi-agent"));+ env(&mut l, "PI_OFFLINE", "1".into());+ }+ }+ "hermes" => {+ let generated = hermes_config.filter(|_| endpoint.is_none());+ let hermes_home = match home {+ Some(h) => Some(format!("{h}/hermes")),+ None => base+ .as_ref()+ .map(|_| format!("{run_dir}/hermes-home"))+ .or_else(|| generated.map(|_| format!("{run_dir}/hermes-home"))),+ };+ if let Some(b) = &base {+ let m = model.clone().unwrap_or_else(|| "default".into());+ let dir = hermes_home.clone().expect("set with an endpoint");+ l.files.push(ConfigFile {+ rel: match home {+ Some(_) => format!("{dir}/config.yaml"),+ None => "hermes-home/config.yaml".into(),+ },+ body: format!(+ "model:\n default: {m:?}\n provider: custom\n base_url: {:?}\n \+ api_key: ${{OPENAI_API_KEY}}\n context_length: 131072\n\+ auth:\n adopt_external_logins: false\n",+ v1(b)+ ),+ });+ } else if let Some(yaml) = generated {+ let dir = hermes_home.clone().expect("set with a generated config");+ l.files.push(ConfigFile {+ rel: match home {+ Some(_) => format!("{dir}/config.yaml"),+ None => "hermes-home/config.yaml".into(),+ },+ body: yaml.to_string(),+ });+ // The provider, model and credentials all come from the connections.+ } else if let Some(dir) = &hermes_home {+ // No connections: start from the guest's own Hermes setup.+ let q = crate::quote;+ l.prelude.extend([+ format!("mkdir -p {}", q(dir)),+ format!(+ "[ -e \"$HOME/.hermes/config.yaml\" ] && [ ! -e {c} ] && cp \"$HOME/.hermes/config.yaml\" {c}; true",+ c = q(&format!("{dir}/config.yaml"))+ ),+ format!(+ "[ -e \"$HOME/.hermes/.env\" ] && [ ! -e {c} ] && ln -s \"$HOME/.hermes/.env\" {c}; true",+ c = q(&format!("{dir}/.env"))+ ),+ ]);+ }+ if let Some(dir) = hermes_home {+ env(&mut l, "HERMES_HOME", dir);+ }+ }+ "openclaw" => {+ let workspace = home.map_or_else(|| cwd.to_string(), |h| format!("{h}/workspace"));+ let mut cfg = json!({"gateway": {"mode": "local", "port": 18789,+ "bind": "loopback", "auth": {"mode": "none"}},+ "agents": {"defaults": {"workspace": workspace}}});+ if home.is_some() {+ env(&mut l, "OPENCLAW_WORKSPACE_DIR", workspace.clone());+ }+ if let Some(b) = &base {+ let m = model.clone().unwrap_or_else(|| "default".into());+ cfg["models"] = json!({"providers": {"cua": {"baseUrl": v1(b),+ "apiKey": "${OPENAI_API_KEY}", "api": "openai-completions",+ "models": [{"id": m, "name": m, "reasoning": false, "input": ["text"],+ "contextWindow": 128000, "maxTokens": 4096}]}}});+ cfg["agents"]["defaults"]["model"] = json!({"primary": format!("cua/{m}")});+ }+ l.files.push(ConfigFile {+ rel: "openclaw/openclaw.json".into(),+ body: serde_json::to_string_pretty(&cfg)?,+ });+ env(&mut l, "OPENCLAW_STATE_DIR", format!("{run_dir}/openclaw"));+ env(+ &mut l,+ "OPENCLAW_CONFIG_PATH",+ format!("{run_dir}/openclaw/openclaw.json"),+ );+ l.wrapper = Some(OPENCLAW_WRAPPER.into());+ }+ _ => {}+ }+ Ok(l)+}++/// Starts a loopback Gateway for `openclaw acp` and stops it with the agent.+const OPENCLAW_WRAPPER: &str = r#"#!/bin/sh+"$HOME/.cua/bin/openclaw" gateway --port 18789 --auth none > "$OPENCLAW_STATE_DIR/gateway.log" 2>&1 &+gw=$!+trap 'kill $gw 2>/dev/null' EXIT INT TERM+i=0+while [ $i -lt 240 ]; do+ if command -v nc >/dev/null 2>&1; then nc -z 127.0.0.1 18789 2>/dev/null && break+ else (echo > /dev/tcp/127.0.0.1/18789) 2>/dev/null && break; fi+ i=$((i+1)); sleep 0.5+done+"$HOME/.cua/bin/openclaw" acp --url ws://127.0.0.1:18789+"#;++/// Published capabilities of one harness.+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+pub struct HarnessInfo {+ pub id: &'static str,+ pub name: &'static str,+ /// Supported and, as far as this server can tell, able to authenticate+ /// (`supported` and `auth` is not `missing`).+ pub ready: bool,+ /// Supported by the SDK: installed, driven and proven live.+ pub supported: bool,+ /// Whether a credential is available (see [`Auth`]); filled in by the+ /// server that publishes capabilities, `unknown` until then.+ pub auth: Auth,+ /// How to provide a credential, when `auth` is not `ok`.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub auth_hint: Option<String>,+ pub protocol: &'static str,+ pub sandbox_mcp: bool,+ pub installs: Vec<String>,+ pub keys: &'static [&'static str],+ pub endpoint_wires: &'static [Wire],+ pub interactive_cli: Option<&'static str>,+ pub can_interrupt: bool,+ pub followups: bool,+ pub notes: &'static [&'static str],+}++impl Harness {+ /// Its published capabilities.+ pub fn info(&self) -> HarnessInfo {+ HarnessInfo {+ id: self.id,+ name: self.name,+ ready: self.ready,+ supported: self.ready,+ auth: Auth::Unknown,+ auth_hint: None,+ protocol: "acp",+ sandbox_mcp: self.sandbox_mcp,+ installs: crate::installables::resolve(self.installs).unwrap_or_default(),+ keys: self.keys,+ endpoint_wires: self.wires,+ interactive_cli: self.cli,+ can_interrupt: true,+ followups: true,+ notes: self.notes,+ }+ }++ /// Its published capabilities given `host_key`, the first of its keys+ /// set where the capabilities are served (a key `env_from_host` can+ /// forward). Without one it is `missing` when cua knows every source the+ /// harness uses (a run then needs a sign-in inside its Space, which+ /// `agent_start` checks before installing), else `unknown`.+ pub fn info_with_host_key(&self, host_key: Option<&str>) -> HarnessInfo {+ let mut i = self.info();+ i.auth = match (host_key, self.logins) {+ (Some(_), _) => Auth::Ok,+ (None, Some(_)) => Auth::Missing,+ (None, None) => Auth::Unknown,+ };+ i.ready = self.ready && i.auth != Auth::Missing;+ if i.auth != Auth::Ok {+ i.auth_hint = Some(self.auth_hint());+ }+ i+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn short_names_resolve_to_the_registry_id() {+ assert_eq!(harness("codex").unwrap().id, "openai-codex");+ assert_eq!(harness("claude").unwrap().id, "claude-code");+ assert_eq!(harness("openai-codex").unwrap().id, "openai-codex");+ assert!(harness("cursor").is_none());+ assert!(ids().iter().all(|id| ALIASES.iter().all(|(a, _)| a != id)));+ }++ #[test]+ fn every_harness_installs_known_items_and_links_its_acp_binary() {+ for h in HARNESSES {+ let order = crate::installables::resolve(h.installs).unwrap();+ let bins: Vec<String> = order+ .iter()+ .flat_map(|id| crate::installables::get(id).unwrap().bins.keys().cloned())+ .collect();+ assert!(bins.iter().any(|b| b == h.acp[0]), "{}: {bins:?}", h.id);+ if let Some(cli) = h.cli {+ assert!(bins.iter().any(|b| b == cli), "{}: cli {cli}", h.id);+ }+ if let Some(a) = h.skills_agent {+ assert!(cua_agent_setup::registry::find(a).is_some(), "{a}");+ }+ }+ }++ /// Drift guard: the agent binaries are scripts (`#!/usr/bin/env node`) or+ /// Python entry points, so a Space only starts them when the interpreter+ /// is installed by the launcher itself, not assumed from the image. Every+ /// harness's install list must bring `node` (for npm items) or `uv` (for+ /// git-uv items) before the item, and the generated launcher must install+ /// them, so a public image without Node still starts every harness.+ #[test]+ fn every_harness_installs_the_interpreter_its_launcher_needs() {+ use crate::installables::{Source, get, resolve, script};+ for h in HARNESSES {+ let order = resolve(h.installs).unwrap();+ let pos = |id: &str| order.iter().position(|x| x == id);+ let mut needs_node = false;+ for (i, id) in order.iter().enumerate() {+ let it = get(id).unwrap();+ match &it.how {+ Source::Npm { .. } => {+ needs_node = true;+ assert!(+ pos("node").is_some_and(|n| n < i),+ "{}: {id} before node",+ h.id+ );+ }+ Source::GitUv { .. } => {+ assert!(pos("uv").is_some_and(|n| n < i), "{}: {id} before uv", h.id);+ }+ Source::Archive { .. } => {}+ }+ }+ let sh = script(h.installs).unwrap();+ if needs_node {+ assert!(+ sh.contains("node-v"),+ "{}: the launcher does not install node",+ h.id+ );+ assert!(+ get("node").unwrap().bins.contains_key("node"),+ "node links no `node` into ~/.cua/bin"+ );+ }+ }+ }++ #[test]+ fn endpoints_are_applied_per_wire_and_refused_on_the_wrong_one() {+ let e = Endpoint {+ base_url: "http://127.0.0.1:8787/v1".into(),+ wire: None,+ model: Some("m1".into()),+ };+ let c = launch(harness("claude-code").unwrap(), Some(&e), None, "/r", "/w").unwrap();+ assert!(+ c.env+ .contains(&("ANTHROPIC_BASE_URL".into(), "http://127.0.0.1:8787".into()))+ );+ let x = launch(harness("openai-codex").unwrap(), Some(&e), None, "/r", "/w").unwrap();+ assert!(+ x.files[0]+ .body+ .contains("base_url = \"http://127.0.0.1:8787/v1\"")+ );+ assert!(+ x.env+ .contains(&("CODEX_HOME".into(), "/r/codex-home".into()))+ );+ let bad = Endpoint {+ wire: Some(Wire::Gemini),+ ..e+ };+ assert!(+ launch(+ harness("claude-code").unwrap(),+ Some(&bad),+ None,+ "/r",+ "/w"+ )+ .is_err()+ );+ }+ #[test]+ fn codex_sqlite_state_is_off_the_volume() {+ assert_eq!(+ codex_sqlite_dir("/home/cua/cua-volume/agents/ada/"),+ "/home/cua/.cua/agents/codex-state/ada"+ );+ assert_eq!(+ codex_sqlite_dir("/srv/agents/ada"),+ "/srv/agents/ada.codex-sqlite"+ );+ // Not the home's own `codex/` (CODEX_HOME), which is on the Volume.+ let home = "/home/cua/cua-volume/agents/ada";+ assert!(!codex_sqlite_dir(home).starts_with(home));+ }++ #[test]+ fn a_home_holds_each_harness_memory() {+ let home = "/home/cua/cua-volume/agents/ada";+ let has = |l: &Launch, k: &str, v: &str| l.env.contains(&(k.to_string(), v.to_string()));+ let c = launch_with_home(+ harness("claude-code").unwrap(),+ None,+ None,+ "/r",+ "/w",+ Some(home),+ )+ .unwrap();+ assert!(has(&c, "CLAUDE_CONFIG_DIR", "/r/claude-config"));+ assert_eq!(c.files[0].rel, "claude-config/settings.json");+ assert!(c.files[0].body.contains(+ "\"autoMemoryDirectory\": \"/home/cua/cua-volume/agents/ada/claude-memory\""+ ));+ let x = launch_with_home(+ harness("openai-codex").unwrap(),+ None,+ None,+ "/r",+ "/w",+ Some(home),+ )+ .unwrap();+ assert!(has(+ &x,+ "CODEX_HOME",+ "/home/cua/cua-volume/agents/ada/codex"+ ));+ assert_eq!(+ x.files[0].rel,+ "/home/cua/cua-volume/agents/ada/codex/config.toml"+ );+ // SQLite state is guest-local, never on the Volume; the key is+ // rewritten with the rest of the config on every start and sits+ // before the table.+ let sqlite = "/home/cua/.cua/agents/codex-state/ada";+ assert_eq!(+ x.files[0].body,+ format!("sqlite_home = {sqlite:?}\n\n[features]\nmemories = true\n")+ );+ assert!(has(&x, "CODEX_SQLITE_HOME", sqlite));+ assert!(+ x.prelude+ .contains(&format!("mkdir -p {}", crate::quote(sqlite)))+ );+ assert!(!sqlite.contains("/cua-volume/"));+ // The guest's sign-in is linked in, replacing a link left dangling by+ // an earlier Space, and never copied into the home.+ let link = x.prelude.iter().find(|p| p.contains("auth.json")).unwrap();+ assert!(link.contains("rm -f") && link.contains("ln -s"), "{link}");+ assert!(!link.contains("cp "), "{link}");+ let e = Endpoint {+ base_url: "http://h:1/v1".into(),+ wire: None,+ model: Some("m".into()),+ };+ let x = launch_with_home(+ harness("openai-codex").unwrap(),+ Some(&e),+ None,+ "/r",+ "/w",+ Some(home),+ )+ .unwrap();+ let body = &x.files[0].body;+ assert!(+ body.starts_with("sqlite_home = ") && body.contains("\nmodel = \"m\""),+ "top-level keys come before tables: {body}"+ );+ assert!(+ body.find("model_provider").unwrap() < body.find("[model_providers.cua]").unwrap()+ && body.find("sqlite_home").unwrap() < body.find('[').unwrap(),+ "{body}"+ );+ assert!(body.ends_with("[features]\nmemories = true\n"), "{body}");+ let hm = launch_with_home(+ harness("hermes").unwrap(),+ Some(&e),+ None,+ "/r",+ "/w",+ Some(home),+ )+ .unwrap();+ assert!(has(+ &hm,+ "HERMES_HOME",+ "/home/cua/cua-volume/agents/ada/hermes"+ ));+ assert_eq!(+ hm.files[0].rel,+ "/home/cua/cua-volume/agents/ada/hermes/config.yaml"+ );+ let hm = launch_with_home(+ harness("hermes").unwrap(),+ None,+ None,+ "/r",+ "/w",+ Some(home),+ )+ .unwrap();+ assert!(has(+ &hm,+ "HERMES_HOME",+ "/home/cua/cua-volume/agents/ada/hermes"+ ));+ assert!(hm.files.is_empty());+ let oc = launch_with_home(+ harness("openclaw").unwrap(),+ None,+ None,+ "/r",+ "/w",+ Some(home),+ )+ .unwrap();+ assert!(has(+ &oc,+ "OPENCLAW_WORKSPACE_DIR",+ "/home/cua/cua-volume/agents/ada/workspace"+ ));+ assert!(+ oc.files[0]+ .body+ .contains("/home/cua/cua-volume/agents/ada/workspace")+ );+ // Without a home nothing moves.+ let c = launch(harness("claude-code").unwrap(), None, None, "/r", "/w").unwrap();+ assert!(c.env.is_empty() && c.files.is_empty() && c.prelude.is_empty());+ let x = launch(harness("openai-codex").unwrap(), None, None, "/r", "/w").unwrap();+ assert!(x.env.is_empty() && x.files.is_empty());+ // Every prelude is valid POSIX sh.+ for id in ["claude-code", "openai-codex", "hermes", "openclaw"] {+ let l =+ launch_with_home(harness(id).unwrap(), None, None, "/r", "/w", Some(home)).unwrap();+ let out = std::process::Command::new("/bin/sh")+ .arg("-n")+ .arg("-c")+ .arg(l.prelude.join("\n"))+ .output()+ .unwrap();+ assert!(+ out.status.success(),+ "{id}: {}",+ String::from_utf8_lossy(&out.stderr)+ );+ assert!(memory_dir(harness(id).unwrap()).is_some());+ }+ }+ fn env(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {+ pairs+ .iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect()+ }++ #[test]+ fn a_key_check_names_the_providers_models_list_and_holds_no_secret() {+ let secret = "sk-ant-test-0123456789abcdef";+ let claude = harness("claude-code").unwrap();+ let c = key_check(claude, &env(&[("ANTHROPIC_API_KEY", secret)]), false).unwrap();+ assert_eq!(c["provider"], "Anthropic");+ assert_eq!(c["url"], "https://api.anthropic.com/v1/models?limit=1");+ assert_eq!(c["keyEnv"], "ANTHROPIC_API_KEY");+ assert_eq!(c["headers"]["x-api-key"], "${ANTHROPIC_API_KEY}");+ assert_eq!(c["headers"]["anthropic-version"], "2023-06-01");+ assert!(+ c["skipIfEnv"]+ .as_array()+ .unwrap()+ .contains(&json!("ANTHROPIC_BASE_URL"))+ );+ assert!(!c.to_string().contains(secret));++ let codex = harness("openai-codex").unwrap();+ let c = key_check(+ codex,+ &env(&[("CODEX_API_KEY", "sk-test-0123456789")]),+ false,+ )+ .unwrap();+ assert_eq!(c["provider"], "OpenAI");+ assert_eq!(c["url"], "https://api.openai.com/v1/models");+ assert_eq!(c["keyEnv"], "CODEX_API_KEY");+ assert_eq!(c["headers"]["authorization"], "Bearer ${CODEX_API_KEY}");+ assert_eq!(c["skipIfFile"][0], "~/.codex/auth.json");+ assert!(!c.to_string().contains("0123456789"));+ }++ #[test]+ fn nothing_is_checked_when_the_key_is_not_the_runs_only_credential() {+ let claude = harness("claude-code").unwrap();+ let codex = harness("openai-codex").unwrap();+ // No key, or an empty one: the runner has nothing to ask about.+ assert!(key_check(claude, &env(&[]), false).is_none());+ assert!(key_check(claude, &env(&[("ANTHROPIC_API_KEY", "")]), false).is_none());+ // A custom endpoint takes the key, not the provider.+ assert!(key_check(claude, &env(&[("ANTHROPIC_API_KEY", "k")]), true).is_none());+ // Claude Code reads other credentials too; only the API key is checked.+ assert!(key_check(claude, &env(&[("CLAUDE_CODE_OAUTH_TOKEN", "t")]), false).is_none());+ // Two keys for one harness: cua cannot tell which one it uses.+ assert!(+ key_check(+ codex,+ &env(&[("OPENAI_API_KEY", "a"), ("CODEX_API_KEY", "b")]),+ false+ )+ .is_none()+ );+ // Harnesses without a known provider.+ for h in HARNESSES+ .iter()+ .filter(|h| !matches!(h.id, "claude-code" | "openai-codex"))+ {+ let all: BTreeMap<_, _> = h+ .keys+ .iter()+ .map(|k| (k.to_string(), "k".to_string()))+ .collect();+ assert!(key_check(h, &all, false).is_none(), "{}", h.id);+ }+ }++ /// The registry and the launcher agree on the apps and on how they are pointed at an endpoint.+ #[test]+ fn the_registry_names_the_same_apps_and_wires() {+ let ours: Vec<&str> = HARNESSES.iter().map(|h| h.id).collect();+ assert_eq!(ours, cua_connections::HARNESS_IDS);+ for (id, wire) in cua_connections::ENDPOINT_HARNESSES {+ let h = harness(id).unwrap();+ assert_eq!(Wire::parse(wire), Some(h.wires[0]), "{id}");+ }+ // What an app reads is what the registry delivers to it, nothing more.+ for h in HARNESSES {+ assert_eq!(h.keys, cua_connections::reads(h.id), "{}", h.id);+ }+ }++ #[test]+ fn hermes_starts_from_the_config_cua_generated() {+ let hermes = harness("hermes").unwrap();+ let yaml = "model:\n provider: \"openrouter\"\n";+ let l =+ launch_with_config(hermes, None, None, "/run/1", "/work", None, Some(yaml)).unwrap();+ let f = l+ .files+ .iter()+ .find(|f| f.rel == "hermes-home/config.yaml")+ .unwrap();+ assert_eq!(f.body, yaml);+ assert!(+ l.env+ .contains(&("HERMES_HOME".into(), "/run/1/hermes-home".into()))+ );+ // Nothing is copied from the guest's own Hermes setup, no wrapper or prelude is needed.+ assert!(l.prelude.is_empty() && l.wrapper.is_none());+ // With a persistent home the file lands in the home, over any older copy.+ let l = launch_with_config(+ hermes,+ None,+ None,+ "/run/1",+ "/work",+ Some("/home/a"),+ Some(yaml),+ )+ .unwrap();+ assert!(+ l.files+ .iter()+ .any(|f| f.rel == "/home/a/hermes/config.yaml" && f.body == yaml)+ );+ // An explicit endpoint wins, and never borrows logins either.+ let ep = Endpoint {+ base_url: "http://x/v1".into(),+ wire: None,+ model: Some("m".into()),+ };+ let l = launch_with_config(hermes, Some(&ep), None, "/run/1", "/work", None, Some(yaml))+ .unwrap();+ let f = l+ .files+ .iter()+ .find(|f| f.rel == "hermes-home/config.yaml")+ .unwrap();+ assert!(+ f.body.contains("provider: custom") && f.body.contains("adopt_external_logins: false"),+ "{}",+ f.body+ );+ // No connections: the guest's own setup, as before.+ let l = launch_with_config(hermes, None, None, "/run/1", "/work", Some("/home/a"), None)+ .unwrap();+ assert!(l.files.is_empty() && !l.prelude.is_empty());+ // Other apps ignore it.+ let l = launch_with_config(+ harness("goose").unwrap(),+ None,+ None,+ "/run/1",+ "/work",+ None,+ Some(yaml),+ )+ .unwrap();+ assert!(l.files.is_empty());+ }+}diff --git a/libs/cua/crates/cua-agents/src/runs.rs b/libs/cua/crates/cua-agents/src/runs.rsindex f4c3909133..a55dcc77cf 100644--- a/libs/cua/crates/cua-agents/src/runs.rs+++ b/libs/cua/crates/cua-agents/src/runs.rs@@ -1108,7 +1108,7 @@ impl Agents {"idleExitSecs": opts.idle_exit_secs.unwrap_or(1800),"authMethod": h.auth_method,"authHint": h.auth_hint(),- "keyCheck": harness::key_check(h, &opts.env, endpoint.is_some()),+ "keyCheck": harness::key_check(h, &opts.env, endpoint.as_ref()),"mcpBridge": format!("{}/.cua/bin/mcp-remote", self.home),"modeKinds": h.mode_kinds,"guardModeKinds": crate::durable::guard_mode_kinds(h),diff --git a/libs/cua/crates/cua-cli/src/agent_cmd.rs b/libs/cua/crates/cua-cli/src/agent_cmd.rsindex 12c5aaa4c8..0c9969dca4 100644--- a/libs/cua/crates/cua-cli/src/agent_cmd.rs+++ b/libs/cua/crates/cua-cli/src/agent_cmd.rs@@ -457,16 +457,27 @@ async fn follow(out: &mut dyn Write,) -> Result<u64, CuaError> {// Bounded: at most 24 h of polling at 500 ms.+ let mut last_event = std::time::Instant::now();+ let mut warned = false;for _ in 0..172_800 {let page = run.events(cursor, Some(500)).await?;cursor = page.cursor;let mut done = false;+ if !page.events.is_empty() {+ last_event = std::time::Instant::now();+ warned = false;+ }for e in &page.events {if json || raw {line(out, &e.json);} else if let Some(l) = &e.line {line(out, l);}+ if e.kind == "error"+ && let Some(h) = auth_hint(e.line.as_deref().unwrap_or(&e.json))+ {+ eprintln!("{}", crate::util::hint(h));+ }if matches!(e.kind.as_str(), "turn_ended" | "exited") {done = true;}@@ -479,6 +490,25 @@ async fn follow(if s.status != "running" && !done {break;}+ match silence(last_event.elapsed(), warned) {+ Silence::Fine => {}+ Silence::Warn => {+ warned = true;+ eprintln!(+ "{}",+ crate::util::hint(&format!(+ "No output for {}s and the run still says \"working\". {SILENCE_NEXT_STEP}",+ SILENCE_WARN.as_secs()+ ))+ );+ }+ Silence::Fail => {+ return Err(CuaError::Env(format!(+ "The agent has said nothing for {}s, so it is probably stuck (a model key it could not use is the usual cause). {SILENCE_NEXT_STEP}",+ SILENCE_FAIL.as_secs()+ )));+ }+ }tokio::time::sleep(Duration::from_millis(500)).await;}}@@ -548,8 +578,64 @@ fn split_env_from_host(Ok((env, server))}+/// `--wire` only describes `--base-url`; alone it would be ignored without a+/// word, so refuse it.+fn check_endpoint_flags(a: &RunArgs) -> Result<(), CuaError> {+ if a.wire.is_some() && a.base_url.is_none() {+ return Err(CuaError::InvalidArgument(+ "--wire describes a custom endpoint, so it needs --base-url too (it would be ignored on its own)"+ .into(),+ ));+ }+ Ok(())+}++/// How long a followed run may say nothing before the CLI speaks up, and+/// before it stops waiting. Claude Code retries a rejected key for about+/// three minutes without a word; a run that is working prints within seconds.+const SILENCE_WARN: Duration = Duration::from_secs(60);+const SILENCE_FAIL: Duration = Duration::from_secs(240);++#[derive(Debug, PartialEq, Eq)]+enum Silence {+ Fine,+ Warn,+ Fail,+}++/// What to do about `silent` time without an event; warns only once.+fn silence(silent: Duration, warned: bool) -> Silence {+ if silent >= SILENCE_FAIL {+ Silence::Fail+ } else if silent >= SILENCE_WARN && !warned {+ Silence::Warn+ } else {+ Silence::Fine+ }+}++const SILENCE_NEXT_STEP: &str = "If the provider key was not accepted, check it with `cua agent keys` \+(replace it with `cua agent keys set anthropic`, or pass a valid one with --env-from-host), and check \+--base-url/--wire if you set them. See what the agent did with `cua agent logs <space> <run> --raw`; \+stop it with `cua agent stop <space> <run>`.";++/// A plain-language next step for an authentication failure in `line`.+fn auth_hint(line: &str) -> Option<&'static str> {+ let l = line.to_ascii_lowercase();+ let auth = l.contains("authenticat")+ || l.contains("invalid x-api-key")+ || l.contains("invalid api key")+ || l.contains("incorrect api key")+ || l.contains("api error: 401")+ || l.contains("unauthorized");+ auth.then_some(+ "Your model key was not accepted. Run `cua agent keys set anthropic` (or openai, gemini) to save a valid one, or pass it with --env-from-host. If you use --base-url, the key must be one that endpoint accepts.",+ )+}+/// The `agent_start` arguments for `cua agent run`.fn start_args(a: &RunArgs, space: &str) -> Result<serde_json::Value, CuaError> {+ check_endpoint_flags(a)?;let (env, env_from_host) = split_env_from_host(&a.env_from_host, |n| std::env::var(n).ok())?;let mut files = vec![];for p in &a.files {@@ -649,6 +735,12 @@ async fn start(eprintln!("note: {n}");}}+ if let Some(b) = &a.base_url {+ eprintln!(+ "note: using the model endpoint {b} (wire: {})",+ a.wire.as_deref().unwrap_or("the harness's default")+ );+ }eprintln!("{}",crate::util::hint(&format!(@@ -1427,6 +1519,8 @@ mod tests {"--exit-when-idle","--label","e2e",+ "--base-url",+ "http://127.0.0.1:9","--wire","anthropic",]);@@ -1452,4 +1546,43 @@ mod tests {let missing = run_args(&["local:dev", "claude-code", "x", "--file", "/no/such/file"]);assert!(start_args(&missing, "local:dev").is_err());}++ #[test]+ fn base_url_and_wire_reach_agent_start_and_wire_alone_is_refused() {+ let a = run_args(&[+ "local:dev",+ "claude-code",+ "hi",+ "--base-url",+ "http://gw:4000",+ "--wire",+ "anthropic",+ "--model",+ "m",+ ]);+ let v = start_args(&a, "local:dev").unwrap();+ let parsed: cua_spaces::contract::inputs::AgentStart = serde_json::from_value(v).unwrap();+ assert_eq!(parsed.base_url.as_deref(), Some("http://gw:4000"));+ assert_eq!(parsed.wire.as_deref(), Some("anthropic"));+ let alone = run_args(&["local:dev", "claude-code", "hi", "--wire", "anthropic"]);+ let e = start_args(&alone, "local:dev").unwrap_err().to_string();+ assert!(e.contains("--base-url"), "{e}");+ }++ #[test]+ fn a_silent_run_is_called_out_then_given_up_on() {+ let s = Duration::from_secs;+ assert_eq!(silence(s(5), false), Silence::Fine);+ assert_eq!(silence(SILENCE_WARN, false), Silence::Warn);+ assert_eq!(silence(SILENCE_WARN, true), Silence::Fine);+ assert_eq!(silence(SILENCE_FAIL, true), Silence::Fail);+ }++ #[test]+ fn an_auth_error_gets_a_plain_next_step() {+ let h = auth_hint("Failed to authenticate. Anthropic API Error: 401 invalid x-api-key")+ .unwrap();+ assert!(h.contains("cua agent keys set"));+ assert!(auth_hint("Rate limited, retry in 5s").is_none());+ }}