diff --git a/.github/scripts/assert-pure.sh b/.github/scripts/assert-pure.sh index caa4cb5d..ef543c66 100755 --- a/.github/scripts/assert-pure.sh +++ b/.github/scripts/assert-pure.sh @@ -17,10 +17,11 @@ set -euo pipefail # whose vocabulary dependency includes `anyhow` and `async-trait`. pure_crates=("tinyhivemind-core" "tinyhivemind-lang") tool_crates=("tinyhivemind-tools") -# Host and the process harness clients run harnesses as processes (ADR 0035), +# Host and the process harness clients (OpenHuman's and the ACP one) run +# harnesses as processes (ADR 0035), # and the MCP server serves them hive tools over loopback (ADR 0036), so they may # hold a runtime, a listener and an HTTP client, but none may link a harness. -host_crates=("tinyhivemind-host" "tinyhivemind-mcp" "tinyhivemind-openhuman-process") +host_crates=("tinyhivemind-host" "tinyhivemind-mcp" "tinyhivemind-openhuman-process" "tinyhivemind-acp") forbidden_pure='tokio|futures|async-trait|axum|hyper|reqwest|ureq|curl|anyhow|rusqlite|git2|openhuman|tinyagents|tinytools' # Whole families: `openhuman-embed`, `tinyagents-harness` and so on. diff --git a/AGENTS.md b/AGENTS.md index 92d6a37b..3eabc951 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,7 +53,7 @@ is not advisory — do not add an exception to it to land a change. ## Project Structure -This is a Rust 2024 virtual Cargo workspace with eight packages. Core owns all +This is a Rust 2024 virtual Cargo workspace with ten packages. Core owns all host-neutral behavior; lang is where a hive mind is defined, integrations included; tools renders native tool definitions and records calls; exec runs a package's executable tools and hooks; host is the harness-neutral @@ -79,6 +79,7 @@ crates/ ├── tinyhivemind-mcp/ # hive and package tools served to harness processes over loopback MCP ├── tinyhivemind-openhuman/ # package deployment, seat runners, host integration ├── tinyhivemind-openhuman-process/ # OpenHuman seats as supervised processes +├── tinyhivemind-acp/ # seats on any Agent Client Protocol agent (Claude Code, Codex) ├── tinyhivemind-hives/ # durable cross-hive coordinator └── tinyhivemind-lang/ # pure hive packages: structure, integrations, edits, lineage wiki/ # GitHub wiki submodule @@ -103,6 +104,9 @@ process. `tinyhivemind-exec` runs those executable tools and hooks `tinyhivemind-openhuman-process` implements the host's harness port for the `openhuman` kind over a pinned `openhuman-core` binary (`harnesses.lock`); it links no harness either. +`tinyhivemind-acp` implements the same port once for every agent that speaks +the Agent Client Protocol over stdio; what differs between agents is an +`Agent` descriptor of data, and it links no harness either. `tinyhivemind-host` depends on core, hives and lang, and owns what every harness shares: the hive tools and their dispatch, the send and management policy ports, turn scope and prompt, package loading, the deployment plan, and supervised diff --git a/Cargo.lock b/Cargo.lock index d33cba40..11e20d64 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3528,6 +3528,23 @@ dependencies = [ "uuid", ] +[[package]] +name = "tinyhivemind-acp" +version = "0.2.1" +dependencies = [ + "anyhow", + "serde_json", + "tempfile", + "thiserror", + "tinyhivemind-exec", + "tinyhivemind-hives", + "tinyhivemind-host", + "tinyhivemind-lang", + "tinyhivemind-mcp", + "tinyhivemind-openhuman-process", + "tokio", +] + [[package]] name = "tinyhivemind-core" version = "0.2.1" @@ -3654,6 +3671,7 @@ dependencies = [ "tinyhivemind-hives", "tinyhivemind-host", "tinyhivemind-lang", + "tinyhivemind-mcp", "tokio", "toml 0.8.23", ] diff --git a/Cargo.toml b/Cargo.toml index 43aa7041..e8ccd232 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ resolver = "3" # package, each directory named for the package it holds. There is no root # package: the crate a host links is `crates/tinyhivemind-core`, the same as any # other member. Keeping the root virtual is what makes that uniform. -members = ["crates/tinyhivemind-core", "crates/tinyhivemind-tools", "crates/tinyhivemind-openhuman", "crates/tinyhivemind-hives", "crates/tinyhivemind-lang", "crates/tinyhivemind-exec", "crates/tinyhivemind-host", "crates/tinyhivemind-mcp", "crates/tinyhivemind-openhuman-process"] +members = ["crates/tinyhivemind-core", "crates/tinyhivemind-tools", "crates/tinyhivemind-openhuman", "crates/tinyhivemind-hives", "crates/tinyhivemind-lang", "crates/tinyhivemind-exec", "crates/tinyhivemind-host", "crates/tinyhivemind-mcp", "crates/tinyhivemind-openhuman-process", "crates/tinyhivemind-acp"] # `worktrees/` holds `git worktree` checkouts of this same repository; each # contains a full copy of this manifest. Keep them excluded from Cargo # workspace discovery. @@ -31,6 +31,9 @@ tinyhivemind-exec = { path = "crates/tinyhivemind-exec" } sha2 = "0.10" # Harness-neutral tool belt, policies, package plans and process supervision. tinyhivemind-host = { path = "crates/tinyhivemind-host" } +# Hive tools served to harness processes over loopback MCP. Only tests take +# it: the process runners link no server, and their hive tests start one. +tinyhivemind-mcp = { path = "crates/tinyhivemind-mcp" } # The HTTP/1.1 server under `tinyhivemind-mcp`, which serves hive tools to # harness processes over Streamable HTTP on loopback (ADR 0036). hyper 1 is a # protocol implementation and no framework: no router, no TLS, no HTTP/2, no diff --git a/crates/tinyhivemind-acp/Cargo.toml b/crates/tinyhivemind-acp/Cargo.toml new file mode 100644 index 00000000..4f77c562 --- /dev/null +++ b/crates/tinyhivemind-acp/Cargo.toml @@ -0,0 +1,47 @@ +[package] +name = "tinyhivemind-acp" +description = "Hive seats on any Agent Client Protocol agent, each a supervised child process spoken to over stdio." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +readme = "README.md" +publish = false +# This crate links no harness (ADR 0035): it speaks the Agent Client Protocol +# over a supervised child's stdin and stdout, and what differs between agents +# is a descriptor of data. `.github/scripts/assert-pure.sh` asserts that no +# harness enters its graph. + +[dependencies] +# The harness port, seat runner, verification and process supervision, whose +# JSON lines pipes carry the protocol. +tinyhivemind-host.workspace = true +# The coordinator's turn request and outcome. +tinyhivemind-hives.workspace = true +# The lowered seat and the harness kinds. +tinyhivemind-lang.workspace = true +# Protocol messages, read tolerantly: the usage fields agents send are still +# unstable in the protocol's own schema crate, so this crate does not take it. +serde_json.workspace = true +# The crate's error type. +thiserror.workspace = true +# The reader task, channels and deadlines. +tokio = { workspace = true, features = ["time", "sync", "macros", "rt"] } + +[dev-dependencies] +# The hive tests: a real coordinator and hive tool server. +tinyhivemind-mcp.workspace = true +# The edit test's workspace for the host's edit tool. +tinyhivemind-exec.workspace = true +# The mixed hive test runs an OpenHuman seat beside the ACP ones. +tinyhivemind-openhuman-process = { path = "../tinyhivemind-openhuman-process" } +# Fallible tests over several error types. +anyhow.workspace = true +# Async tests and the scripted model's listener. +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "net", "io-util", "time", "sync", "process"] } +# Seat directories. +tempfile.workspace = true + +[lints] +workspace = true diff --git a/crates/tinyhivemind-acp/README.md b/crates/tinyhivemind-acp/README.md new file mode 100644 index 00000000..8826d1d0 --- /dev/null +++ b/crates/tinyhivemind-acp/README.md @@ -0,0 +1,19 @@ +# tinyhivemind-acp + +Hive seats on any [Agent Client Protocol](https://agentclientprotocol.com) +agent, each a supervised child process spoken to over stdio. One client for +every agent: what differs between them is an `Agent` descriptor of data. +Claude Code and Codex are the two measured; see +[the ACP harness runs](../../docs/experiments/2026-11-26-acp-harnesses.md). +It links no agent ([ADR 0035](../../docs/adr/0035-a-harness-is-a-process.md)). + +An agent's own tools stay off, as [the harness spec](../../docs/specs/harnesses.md) +requires for every kind. A seat that edits files does it through the host's +executable tools, which run in the seat's workspace under the host's access +gate; the live tests show all three harnesses editing that way and a +read-only seat refused. + +| Path | Purpose | +| --- | --- | +| [`src/`](src/README.md) | The crate | +| [`tests/`](tests/README.md) | Live hive tests on the pinned agents | diff --git a/crates/tinyhivemind-acp/src/README.md b/crates/tinyhivemind-acp/src/README.md new file mode 100644 index 00000000..7421b4bc --- /dev/null +++ b/crates/tinyhivemind-acp/src/README.md @@ -0,0 +1,12 @@ +# Source + +| Path | Purpose | +| --- | --- | +| `lib.rs` | Crate overview and public surface | +| [`agent/`](agent/README.md) | `Agent` descriptors, their templates, and the Codex model catalog | +| [`capability/`](capability/README.md) | The one model route a seat may take on an agent | +| [`connection/`](connection/README.md) | JSON-RPC over the supervised process's JSON lines | +| [`protocol/`](protocol/README.md) | The ACP messages a seat needs, built and read as JSON | +| [`seat/`](seat/README.md) | One seat: process, session, turns, cancel and stop | +| [`harness/`](harness/README.md) | `AcpHarness`, the host's harness port, and `Options` | +| [`error/`](error/README.md) | `Error` and how the port sees it | diff --git a/crates/tinyhivemind-acp/src/agent/README.md b/crates/tinyhivemind-acp/src/agent/README.md new file mode 100644 index 00000000..2e1791f3 --- /dev/null +++ b/crates/tinyhivemind-acp/src/agent/README.md @@ -0,0 +1,8 @@ +# Agent + +What differs between ACP agents, as data, with `{name}` templates filled per seat in one pass (a value is never expanded again), TOML-escaped in a `.toml` file. `write_codex_catalog` fails with a typed `CatalogError`. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `Agent`, `Agent::claude_code`, `Agent::codex`, `write_codex_catalog`, template values | +| `test.rs` | Templates, TOML escaping, the two descriptors and each catalog failure | diff --git a/crates/tinyhivemind-acp/src/agent/mod.rs b/crates/tinyhivemind-acp/src/agent/mod.rs new file mode 100644 index 00000000..fd611112 --- /dev/null +++ b/crates/tinyhivemind-acp/src/agent/mod.rs @@ -0,0 +1,413 @@ +//! What differs between ACP agents, as data. +//! +//! An [`Agent`] says how to start one agent process for a seat and how to +//! open its session. Strings in [`Agent::env`], [`Agent::files`] and +//! [`Agent::session_meta`] are templates; each `{name}` below is replaced +//! when a seat starts: +//! +//! | Name | Value | +//! | --- | --- | +//! | `{state}` | the instance's private state directory | +//! | `{home}` | `{state}/home`, the process's `HOME` | +//! | `{endpoint}` | the seat's model endpoint, as the package declares it | +//! | `{model}` | the seat's model name | +//! | `{server}` | the host's MCP server name | +//! | `{program_dir}` | the directory of [`Agent::program`] | +//! | any key of [`Agent::vars`] | its value | +//! +//! In `session_meta`, a string that is exactly `{allowed_tools}` becomes the +//! array of the host's tools under the names [`Agent::tool_name`] gives them. +//! +//! A template is read once, left to right: a value is never itself expanded, +//! so a path holding `{model}` stays that path. In a file whose name ends in +//! `.toml` each value is escaped for a TOML basic string, which the template +//! puts it in. +use serde_json::Value; +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; +use tinyhivemind_lang::HarnessKind; + +/// One ACP agent, as a seat runs it. +#[derive(Clone, Debug, PartialEq)] +pub struct Agent { + /// The kind of seat it runs, as the package names it. + pub kind: HarnessKind, + /// The program, an absolute path: the agent, or the runtime of a script. + pub program: PathBuf, + /// Its arguments. + pub args: Vec, + /// The version `initialize` must report as `agentInfo.version`. + pub version: String, + /// The environment, templated. Nothing else is inherited. + pub env: Vec<(String, String)>, + /// Files written into the state directory before each start: a path + /// relative to it, and templated content (TOML-escaped for a `.toml` + /// path). + pub files: Vec<(PathBuf, String)>, + /// The `_meta` of `session/new` and `session/load`, templated. + pub session_meta: Option, + /// The session mode set after `session/new` and `session/load`. + pub mode: Option, + /// The name the agent's model sees for one of the host's tools, from + /// `{server}` and `{tool}`. + pub tool_name: String, + /// Further template values, such as a file the host generated. + pub vars: BTreeMap, +} + +/// The key every key-free provider is given, so an agent that insists on one +/// finds it and a stray request is plainly not a real one. +pub const NO_KEY: &str = "thm-no-key"; + +/// The environment every agent gets: a private home and a minimal path. +fn base_env() -> Vec<(String, String)> { + vec![ + ("HOME".into(), "{home}".into()), + ("PATH".into(), "{program_dir}:/usr/bin:/bin".into()), + ] +} + +impl Agent { + /// Claude Code through `@agentclientprotocol/claude-agent-acp`, run by + /// `node` from `adapter`, its `dist/index.js`. + /// + /// Its model is the seat's `anthropic` endpoint, the API root without + /// `/v1`. Built-in tools, settings files and deferred tool search are off, + /// and the host's tools are allowed by name, so the model sees those + /// tools and nothing else and is never asked to approve them. + #[must_use] + pub fn claude_code( + node: impl Into, + adapter: impl Into, + version: impl Into, + ) -> Self { + let mut env = base_env(); + env.extend( + [ + ("CLAUDE_CONFIG_DIR", "{state}/claude"), + ("ANTHROPIC_BASE_URL", "{endpoint}"), + ("ANTHROPIC_API_KEY", NO_KEY), + ("ANTHROPIC_MODEL", "{model}"), + ("ANTHROPIC_SMALL_FAST_MODEL", "{model}"), + ("ENABLE_TOOL_SEARCH", "false"), + ("DISABLE_TELEMETRY", "1"), + ("DISABLE_ERROR_REPORTING", "1"), + ("DISABLE_AUTOUPDATER", "1"), + ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1"), + ] + .map(|(name, value)| (name.to_owned(), value.to_owned())), + ); + let meta = serde_json::json!({"claudeCode": {"options": { + "tools": [], + "settingSources": [], + "allowedTools": "{allowed_tools}", + }}}); + Self { + kind: HarnessKind::ClaudeCode, + program: node.into(), + args: vec![adapter.into().to_string_lossy().into_owned()], + version: version.into(), + env, + files: Vec::new(), + session_meta: Some(meta), + mode: None, + tool_name: "mcp__{server}__{tool}".into(), + vars: BTreeMap::new(), + } + } + + /// Codex through `@agentclientprotocol/codex-acp`, run by `node` from + /// `adapter`, its `dist/index.js`, with the model catalog at `catalog` + /// (see [`write_codex_catalog`]). + /// + /// Its model is the seat's `openai` endpoint, spoken to with the + /// Responses API. The session runs in the adapter's `read-only` mode: the + /// default mode has a model review every tool call, which would run + /// unseen and could refuse the host's tools. + #[must_use] + pub fn codex( + node: impl Into, + adapter: impl Into, + version: impl Into, + catalog: impl AsRef, + ) -> Self { + let mut env = base_env(); + env.extend( + [("CODEX_HOME", "{state}/codex"), ("THM_NO_KEY", NO_KEY)] + .map(|(name, value)| (name.to_owned(), value.to_owned())), + ); + let catalog = catalog.as_ref().to_string_lossy().into_owned(); + Self { + kind: HarnessKind::Codex, + program: node.into(), + args: vec![adapter.into().to_string_lossy().into_owned()], + version: version.into(), + env, + files: vec![("codex/config.toml".into(), CODEX_CONFIG.into())], + session_meta: None, + mode: Some("read-only".into()), + tool_name: "mcp__{server}/{tool}".into(), + vars: BTreeMap::from([("catalog".to_owned(), catalog)]), + } + } +} + +/// Codex's `config.toml`: the seat's endpoint as its only provider, and +/// everything that would run, fetch or remember on its own turned off. As +/// the 2026-11-25 spike's, with the provider renamed. +const CODEX_CONFIG: &str = r#"model_catalog_json = "{catalog}" +model = "{model}" +model_provider = "thm" +approval_policy = "never" +sandbox_mode = "read-only" +web_search = "disabled" +check_for_update_on_startup = false +project_doc_max_bytes = 0 +cli_auth_credentials_store = "file" +include_permissions_instructions = false +include_apps_instructions = false +include_environment_context = false +[model_providers.thm] +name = "thm" +base_url = "{endpoint}" +env_key = "THM_NO_KEY" +wire_api = "responses" +supports_websockets = false +request_max_retries = 0 +stream_max_retries = 0 +[analytics] +enabled = false +[feedback] +enabled = false +[otel] +exporter = "none" +trace_exporter = "none" +metrics_exporter = "none" +[history] +persistence = "none" +[skills] +include_instructions = false +[skills.bundled] +enabled = false +[agents] +enabled = false +[features] +view_image = false +multi_agent_v2 = false +shell_tool = false +unified_exec = false +multi_agent = false +goals = false +apps = false +plugins = false +remote_plugin = false +plugin_sharing = false +tool_suggest = false +skill_search = false +skill_mcp_dependency_install = false +image_generation = false +browser_use = false +browser_use_external = false +computer_use = false +in_app_browser = false +sleep_tool = false +code_mode_host = false +hooks = false +shell_snapshot = false +workspace_dependencies = false +daemon_auto_start = false +memories = false +fast_mode = false +api_key_model_discovery = false +[tools] +[tools.experimental_request_user_input] +enabled = false +"#; + +/// Why [`write_codex_catalog`] failed. +#[derive(Debug, thiserror::Error)] +pub enum CatalogError { + /// `codex` could not be started. + #[error("codex could not be run: {0}")] + Launch(#[source] std::io::Error), + /// `codex debug models` failed. + #[error("codex debug models failed ({status}): {stderr}")] + Exit { + /// How it exited. + status: std::process::ExitStatus, + /// The end of what it wrote to stderr. + stderr: String, + }, + /// Its output was not JSON. + #[error("codex's catalog is not JSON: {0}")] + Json(#[source] serde_json::Error), + /// Its catalog has no `models` array. + #[error("codex's catalog has no models")] + NoModels, + /// `out` could not be written. + #[error("the catalog could not be written: {0}")] + Write(#[source] std::io::Error), +} + +/// Write the model catalog Codex needs to `out`, from `codex`'s own bundled +/// one: every model calls tools directly, with no shell, patch tool, tool +/// search or sub-agents, and `model` is added with the first model's +/// metadata if the catalog lacks it. Without this, models hid MCP tools or +/// routed them through code mode (`docs/experiments/2026-11-25-process-harnesses`). +/// +/// # Errors +/// A [`CatalogError`]: `codex` could not be run or failed, its catalog was +/// not JSON or had no models, or `out` could not be written. +pub fn write_codex_catalog(codex: &Path, out: &Path, model: &str) -> Result<(), CatalogError> { + let home = out.parent().unwrap_or(Path::new(".")); + let output = std::process::Command::new(codex) + .args(["debug", "models", "--bundled"]) + .env_clear() + .env("PATH", "/usr/bin:/bin") + .env("HOME", home) + .env("CODEX_HOME", home) + .output() + .map_err(CatalogError::Launch)?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let tail = stderr + .char_indices() + .rev() + .nth(4095) + .map_or(0, |(at, _)| at); + return Err(CatalogError::Exit { + status: output.status, + stderr: stderr[tail..].trim().to_owned(), + }); + } + let mut catalog: Value = serde_json::from_slice(&output.stdout).map_err(CatalogError::Json)?; + let models = catalog["models"] + .as_array_mut() + .ok_or(CatalogError::NoModels)?; + for entry in models.iter_mut() { + let Some(entry) = entry.as_object_mut() else { + continue; + }; + entry.insert("tool_mode".into(), "direct".into()); + entry.insert("shell_type".into(), "disabled".into()); + entry.insert("apply_patch_tool_type".into(), Value::Null); + entry.insert("supports_search_tool".into(), false.into()); + for (key, value) in [ + ("multi_agent_version", Value::Null), + ("use_responses_lite", false.into()), + ("supports_reasoning_effort_updates", false.into()), + ("experimental_supported_tools", Value::Array(Vec::new())), + ] { + if entry.contains_key(key) { + entry.insert(key.into(), value); + } + } + } + if !models.iter().any(|entry| entry["slug"] == model) + && let Some(first) = models.first().cloned() + { + let mut added = first; + added["slug"] = model.into(); + added["display_name"] = model.into(); + models.insert(0, added); + } + let bytes = serde_json::to_vec(&catalog).map_err(CatalogError::Json)?; + std::fs::write(out, bytes).map_err(CatalogError::Write) +} + +/// The values one seat's templates are filled from. +#[derive(Clone, Debug, Default)] +pub(crate) struct Values { + pub(crate) values: BTreeMap, + pub(crate) allowed_tools: Vec, +} + +impl Values { + /// Fill `template`'s `{name}`s. + pub(crate) fn fill(&self, template: &str) -> String { + self.fill_with(template, str::to_owned) + } + + /// Fill `template`'s `{name}`s with values escaped for a TOML basic + /// string. + pub(crate) fn fill_toml(&self, template: &str) -> String { + self.fill_with(template, toml_escape) + } + + /// Fill the file at `path`: TOML-escaped when it is a `.toml` file. + pub(crate) fn fill_file(&self, path: &Path, template: &str) -> String { + if path + .extension() + .is_some_and(|extension| extension == "toml") + { + self.fill_toml(template) + } else { + self.fill(template) + } + } + + /// One pass over `template`: each known `{name}` becomes its value as + /// `escape` writes it, and nothing a value brings in is read again. + fn fill_with(&self, template: &str, escape: impl Fn(&str) -> String) -> String { + let mut filled = String::with_capacity(template.len()); + let mut rest = template; + while let Some(open) = rest.find('{') { + filled.push_str(&rest[..open]); + let after = &rest[open + 1..]; + let known = after.find('}').and_then(|close| { + let value = self.values.get(&after[..close])?; + Some((close, value)) + }); + if let Some((close, value)) = known { + filled.push_str(&escape(value)); + rest = &after[close + 1..]; + } else { + filled.push('{'); + rest = after; + } + } + filled.push_str(rest); + filled + } + + /// Fill every string of `template`, turning an exact `{allowed_tools}` + /// into the allowed tools. + pub(crate) fn fill_json(&self, template: &Value) -> Value { + match template { + Value::String(text) if text == "{allowed_tools}" => { + Value::from(self.allowed_tools.clone()) + } + Value::String(text) => Value::String(self.fill(text)), + Value::Array(items) => items.iter().map(|item| self.fill_json(item)).collect(), + Value::Object(fields) => fields + .iter() + .map(|(key, value)| (key.clone(), self.fill_json(value))) + .collect(), + other => other.clone(), + } + } +} + +/// `value` as the inside of a TOML basic string: quotes, backslashes and +/// control characters escaped. +fn toml_escape(value: &str) -> String { + let mut escaped = String::with_capacity(value.len()); + for character in value.chars() { + match character { + '"' => escaped.push_str("\\\""), + '\\' => escaped.push_str("\\\\"), + '\n' => escaped.push_str("\\n"), + '\t' => escaped.push_str("\\t"), + '\r' => escaped.push_str("\\r"), + control if control.is_control() => { + let _ = write!(escaped, "\\u{:04X}", u32::from(control)); + } + other => escaped.push(other), + } + } + escaped +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-acp/src/agent/test.rs b/crates/tinyhivemind-acp/src/agent/test.rs new file mode 100644 index 00000000..7ff38a1f --- /dev/null +++ b/crates/tinyhivemind-acp/src/agent/test.rs @@ -0,0 +1,145 @@ +//! Descriptors and their templates. +#![allow(clippy::unwrap_used, clippy::panic)] // Tests fail loudly on unexpected results. +use super::*; +use serde_json::json; + +fn values() -> Values { + Values { + values: BTreeMap::from([ + ("state".to_owned(), "/s".to_owned()), + ("endpoint".to_owned(), "http://127.0.0.1:9".to_owned()), + ("model".to_owned(), "mock".to_owned()), + ]), + allowed_tools: vec!["mcp__hive__hivemind_post".into()], + } +} + +#[test] +fn templates_fill_every_known_name_and_leave_the_rest() { + let values = values(); + assert_eq!( + values.fill("{state}/claude at {endpoint} as {model}"), + "/s/claude at http://127.0.0.1:9 as mock" + ); + assert_eq!(values.fill("{unknown}"), "{unknown}"); + let meta = json!({"a": ["{state}", 1, null], "allowed": "{allowed_tools}", "keep": "{allowed_tools} x"}); + assert_eq!( + values.fill_json(&meta), + json!({"a": ["/s", 1, null], "allowed": ["mcp__hive__hivemind_post"], "keep": "{allowed_tools} x"}) + ); +} + +#[test] +fn claude_code_turns_its_own_tools_off_and_allows_the_hosts() { + let agent = Agent::claude_code("/opt/node/bin/node", "/opt/acp/index.js", "0.112.0"); + assert_eq!(agent.kind, HarnessKind::ClaudeCode); + assert_eq!(agent.args, ["/opt/acp/index.js"]); + let env: BTreeMap<_, _> = agent.env.iter().cloned().collect(); + assert_eq!(env["ANTHROPIC_BASE_URL"], "{endpoint}"); + assert_eq!(env["ANTHROPIC_API_KEY"], NO_KEY); + assert_eq!(env["ENABLE_TOOL_SEARCH"], "false"); + assert_eq!(env["HOME"], "{home}"); + let options = &agent.session_meta.as_ref().unwrap()["claudeCode"]["options"]; + assert_eq!(options["tools"], json!([])); + assert_eq!(options["settingSources"], json!([])); + assert_eq!(options["allowedTools"], "{allowed_tools}"); + assert_eq!(agent.mode, None); +} + +#[test] +fn codex_writes_its_config_and_runs_read_only() { + let agent = Agent::codex( + "/opt/node/bin/node", + "/opt/acp/index.js", + "2.12.1", + "/opt/catalog.json", + ); + assert_eq!(agent.kind, HarnessKind::Codex); + assert_eq!(agent.mode.as_deref(), Some("read-only")); + assert_eq!(agent.vars["catalog"], "/opt/catalog.json"); + let (path, config) = &agent.files[0]; + assert_eq!(path, Path::new("codex/config.toml")); + let mut values = values(); + values.values.extend(agent.vars.clone()); + let config = values.fill(config); + assert!(config.contains("base_url = \"http://127.0.0.1:9\"")); + assert!(config.contains("model = \"mock\"")); + assert!(config.contains("model_catalog_json = \"/opt/catalog.json\"")); + assert!(config.contains("shell_tool = false")); + assert!(!config.contains("{model}") && !config.contains("{endpoint}")); +} + +#[test] +fn a_value_is_never_expanded_again() { + let mut values = values(); + values + .values + .insert("catalog".into(), "/tmp/{model}/catalog.json".into()); + assert_eq!( + values.fill("{catalog} for {model}"), + "/tmp/{model}/catalog.json for mock" + ); + assert_eq!(values.fill("{{model}} {model"), "{mock} {model"); +} + +#[test] +fn a_toml_file_gets_its_values_escaped() { + let mut values = values(); + values + .values + .insert("catalog".into(), "/tmp/a\"b\\c\n\u{1}.json".into()); + let template = "model_catalog_json = \"{catalog}\""; + let filled = values.fill_file(Path::new("codex/config.toml"), template); + assert_eq!( + filled, + "model_catalog_json = \"/tmp/a\\\"b\\\\c\\n\\u0001.json\"" + ); + assert_eq!( + values.fill_file(Path::new("notes.txt"), "{catalog}"), + "/tmp/a\"b\\c\n\u{1}.json" + ); +} + +#[cfg(unix)] +#[test] +fn each_catalog_failure_says_which_it_was() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("c.json"); + let script = |name: &str, body: &str| { + let path = dir.path().join(name); + std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path + }; + let missing = dir.path().join("no-codex"); + assert!(matches!( + write_codex_catalog(&missing, &out, "mock"), + Err(CatalogError::Launch(_)) + )); + let failing = script("failing", "echo broken >&2; exit 3"); + match write_codex_catalog(&failing, &out, "mock") { + Err(CatalogError::Exit { stderr, .. }) => assert_eq!(stderr, "broken"), + other => panic!("{other:?}"), + } + let text = script("text", "echo not json"); + assert!(matches!( + write_codex_catalog(&text, &out, "mock"), + Err(CatalogError::Json(_)) + )); + let empty = script("empty", "echo '{}'"); + assert!(matches!( + write_codex_catalog(&empty, &out, "mock"), + Err(CatalogError::NoModels) + )); + let models = script("models", r#"echo '{"models": [{"slug": "other"}]}'"#); + let unwritable = dir.path().join("missing-dir").join("c.json"); + assert!(matches!( + write_codex_catalog(&models, &unwritable, "mock"), + Err(CatalogError::Write(_)) + )); + write_codex_catalog(&models, &out, "mock").unwrap(); + let catalog: Value = serde_json::from_slice(&std::fs::read(&out).unwrap()).unwrap(); + assert_eq!(catalog["models"][0]["slug"], "mock"); + assert_eq!(catalog["models"][1]["tool_mode"], "direct"); +} diff --git a/crates/tinyhivemind-acp/src/capability/README.md b/crates/tinyhivemind-acp/src/capability/README.md new file mode 100644 index 00000000..03f061fb --- /dev/null +++ b/crates/tinyhivemind-acp/src/capability/README.md @@ -0,0 +1,8 @@ +# Capability + +The model route a seat may take: the provider kind the agent speaks, an explicit endpoint, no credential. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `check`, `SeatModel`, `Refusal` | +| `test.rs` | Accepted and refused routes | diff --git a/crates/tinyhivemind-acp/src/capability/mod.rs b/crates/tinyhivemind-acp/src/capability/mod.rs new file mode 100644 index 00000000..1f656780 --- /dev/null +++ b/crates/tinyhivemind-acp/src/capability/mod.rs @@ -0,0 +1,100 @@ +//! The one model route a seat may take on an ACP agent. +//! +//! [`check`] reads a [`LoweredSeat`] for what this runner needs to start it: +//! a model whose provider is declared with an explicit endpoint and no +//! credential, of the provider kind the agent speaks ([`HarnessKind::model_api`]). +//! The rest of the capability table is the package checker's: it already +//! rejected, at the field, whatever no agent here can enforce. +use tinyhivemind_lang::{HarnessKind, LoweredSeat, ModelApi, ProviderKind}; + +/// The model route of a seat. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SeatModel { + /// The provider's id in the package, for messages. + pub provider: String, + /// Its endpoint, as declared. + pub endpoint: String, + /// The provider's model name. + pub model: String, +} + +/// Why a seat cannot run on this agent. Each names the field. +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] +#[non_exhaustive] +pub enum Refusal { + /// The seat resolves to no model. + #[error("seat {0} has no model")] + NoModel(String), + /// The seat's model has no provider: an agent process has none of its + /// own to fall back on. + #[error("model {0} has no provider")] + NoProvider(String), + /// The provider is not of the kind the agent speaks. + #[error("provider {provider} is {found:?}; a {kind} seat needs {needed:?}")] + ProviderKind { + /// The provider. + provider: String, + /// Its kind. + found: ProviderKind, + /// The kind the agent speaks. + needed: ProviderKind, + /// The seat's harness kind. + kind: HarnessKind, + }, + /// The provider declares no endpoint, so the agent would reach its + /// vendor's own, which needs a key. + #[error("provider {0} has no endpoint")] + NoEndpoint(String), + /// The provider declares a credential, which never reaches an agent. + #[error("provider {0} declares a credential")] + Credential(String), +} + +/// The provider kind an agent of `kind` speaks to. +#[must_use] +pub const fn provider_kind(kind: HarnessKind) -> ProviderKind { + match kind.model_api() { + ModelApi::Messages => ProviderKind::Anthropic, + ModelApi::ChatCompletions | ModelApi::Responses => ProviderKind::Openai, + } +} + +/// The route `seat` takes on an agent of `kind`, or why it cannot run there. +/// +/// # Errors +/// The first [`Refusal`]. +pub fn check(seat: &LoweredSeat, kind: HarnessKind) -> Result { + let lowered = seat + .integration + .model + .as_ref() + .ok_or_else(|| Refusal::NoModel(seat.id.clone()))?; + let provider = lowered + .provider + .as_ref() + .ok_or_else(|| Refusal::NoProvider(lowered.model.id.clone()))?; + let needed = provider_kind(kind); + if provider.kind != needed { + return Err(Refusal::ProviderKind { + provider: provider.id.clone(), + found: provider.kind, + needed, + kind, + }); + } + if provider.credential.is_some() { + return Err(Refusal::Credential(provider.id.clone())); + } + let endpoint = provider + .endpoint + .clone() + .ok_or_else(|| Refusal::NoEndpoint(provider.id.clone()))?; + Ok(SeatModel { + provider: provider.id.clone(), + endpoint, + model: lowered.model.name.clone(), + }) +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-acp/src/capability/test.rs b/crates/tinyhivemind-acp/src/capability/test.rs new file mode 100644 index 00000000..cf0cc45d --- /dev/null +++ b/crates/tinyhivemind-acp/src/capability/test.rs @@ -0,0 +1,104 @@ +//! Which model routes an agent accepts. +#![allow(clippy::unwrap_used)] // Tests fail loudly on unexpected results. +use super::*; +use tinyhivemind_lang::{LoweredModel, LoweredSeatIntegration, Model, Provider, SecretRef}; + +fn seat(provider: Option) -> LoweredSeat { + LoweredSeat { + id: "scout".into(), + label: "Scout".into(), + template: "seat".into(), + config: serde_json::Value::Null, + prompt: String::new(), + memory: None, + integration: LoweredSeatIntegration { + model: Some(LoweredModel { + model: Model { + id: "fast".into(), + provider: Some("p".into()), + name: "mock".into(), + ..Model::default() + }, + provider, + }), + ..LoweredSeatIntegration::default() + }, + } +} + +fn provider(kind: ProviderKind, endpoint: Option<&str>) -> Provider { + Provider { + id: "p".into(), + kind, + endpoint: endpoint.map(Into::into), + credential: None, + } +} + +#[test] +fn each_kind_takes_the_provider_it_speaks() { + let anthropic = seat(Some(provider( + ProviderKind::Anthropic, + Some("http://127.0.0.1:1"), + ))); + let model = check(&anthropic, HarnessKind::ClaudeCode).unwrap(); + assert_eq!( + model, + SeatModel { + provider: "p".into(), + endpoint: "http://127.0.0.1:1".into(), + model: "mock".into() + } + ); + let openai = seat(Some(provider( + ProviderKind::Openai, + Some("http://127.0.0.1:1/v1"), + ))); + assert!(check(&openai, HarnessKind::Codex).is_ok()); + assert!(matches!( + check(&openai, HarnessKind::ClaudeCode), + Err(Refusal::ProviderKind { .. }) + )); + assert!(matches!( + check(&anthropic, HarnessKind::Codex), + Err(Refusal::ProviderKind { .. }) + )); +} + +#[test] +fn a_route_without_an_endpoint_or_with_a_credential_is_refused() { + let none = seat(Some(provider(ProviderKind::Openai, None))); + assert_eq!( + check(&none, HarnessKind::Codex), + Err(Refusal::NoEndpoint("p".into())) + ); + let mut keyed = provider(ProviderKind::Openai, Some("http://127.0.0.1:1/v1")); + keyed.credential = Some(SecretRef::Env("KEY".into())); + assert_eq!( + check(&seat(Some(keyed)), HarnessKind::Codex), + Err(Refusal::Credential("p".into())) + ); + assert_eq!( + check(&seat(None), HarnessKind::Codex), + Err(Refusal::NoProvider("fast".into())) + ); + let mut bare = seat(None); + bare.integration.model = None; + assert_eq!( + check(&bare, HarnessKind::Codex), + Err(Refusal::NoModel("scout".into())) + ); +} + +#[test] +fn refusals_name_the_field() { + assert_eq!( + Refusal::NoEndpoint("p".into()).to_string(), + "provider p has no endpoint" + ); + assert_eq!( + provider_kind(HarnessKind::ClaudeCode), + ProviderKind::Anthropic + ); + assert_eq!(provider_kind(HarnessKind::OpenClaw), ProviderKind::Openai); +} diff --git a/crates/tinyhivemind-acp/src/connection/README.md b/crates/tinyhivemind-acp/src/connection/README.md new file mode 100644 index 00000000..28ab8ac9 --- /dev/null +++ b/crates/tinyhivemind-acp/src/connection/README.md @@ -0,0 +1,8 @@ +# Connection + +JSON-RPC 2.0 over the host's supervised JSON lines. Responses settle calls; notifications and requests go to the running turn's route, or a request is refused at once. `answer_detached` answers from a task, for a `Drop`. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `Connection`, `Incoming`, `Error` | +| `test.rs` | Calls, routes, refusals and detached answers against an echoing child, each wait bounded | diff --git a/crates/tinyhivemind-acp/src/connection/mod.rs b/crates/tinyhivemind-acp/src/connection/mod.rs new file mode 100644 index 00000000..f8924c96 --- /dev/null +++ b/crates/tinyhivemind-acp/src/connection/mod.rs @@ -0,0 +1,235 @@ +//! JSON-RPC 2.0 with one agent process, over its supervised JSON lines. +//! +//! A reader task owns the receiving half. A response settles the call that +//! waits for it; a notification or a request from the agent goes to the +//! current route, which a running turn holds, and a request that arrives +//! with no turn to take it is refused at once, so the agent never waits on +//! an answer nobody will give. +use serde_json::{Value, json}; +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use tinyhivemind_host::process::{JsonLines, LineError, LineSender}; +use tokio::sync::{mpsc, oneshot}; +use tokio::task::JoinHandle; + +/// The JSON-RPC code for a method this client does not offer. +const NOT_OFFERED: i64 = -32601; + +/// Why a call failed. +#[derive(Debug, thiserror::Error)] +pub(crate) enum Error { + /// The agent stopped reading or writing. + #[error("the agent closed the connection")] + Closed, + /// The agent answered with an error. + #[error("the agent refused {method}: {message} ({code})")] + Refused { + method: String, + code: i64, + message: String, + }, + /// A line could not be sent. + #[error(transparent)] + Line(#[from] LineError), +} + +/// What the agent sends unasked. +#[derive(Debug)] +pub(crate) enum Incoming { + /// A notification. + Notification { method: String, params: Value }, + /// A request, to be answered with [`Connection::respond`]. + Request { + id: Value, + method: String, + params: Value, + }, +} + +type Waiting = Arc>>>>; +type Route = Arc>>>; + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// One agent's connection. +#[derive(Debug)] +pub(crate) struct Connection { + sender: LineSender, + waiting: Waiting, + route: Route, + /// Set once the reader ended, before it fails what is waiting. + closed: Arc, + next: AtomicU64, + reader: JoinHandle<()>, +} + +impl Connection { + /// Speak over `lines`, reading on a task of the current runtime. + pub(crate) fn new(lines: JsonLines) -> Self { + let JsonLines { + sender, + mut receiver, + } = lines; + let waiting = Waiting::default(); + let route = Route::default(); + let closed = Arc::new(AtomicBool::new(false)); + let reader = tokio::spawn({ + let (sender, waiting, route) = (sender.clone(), waiting.clone(), route.clone()); + let closed = closed.clone(); + async move { + while let Some(line) = receiver.recv().await { + // A malformed line is skipped; the stream goes on. + if let Ok(message) = line { + dispatch(message, &sender, &waiting, &route).await; + } + } + // Set first: a call that finds it unset is still drained here. + closed.store(true, Ordering::SeqCst); + for (_, call) in lock(&waiting).drain() { + let _ = call.send(Err(Error::Closed)); + } + lock(&route).take(); + } + }); + Self { + sender, + waiting, + route, + closed, + next: AtomicU64::new(1), + reader, + } + } + + /// Call `method` and wait for its result. + pub(crate) async fn call(&self, method: &str, params: Value) -> Result { + let id = self.next.fetch_add(1, Ordering::Relaxed); + let (answer, answered) = oneshot::channel(); + lock(&self.waiting).insert(id, answer); + if self.closed.load(Ordering::SeqCst) && lock(&self.waiting).remove(&id).is_some() { + return Err(Error::Closed); + } + let request = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}); + if let Err(error) = self.sender.send(&request).await { + lock(&self.waiting).remove(&id); + return Err(error.into()); + } + match answered.await { + Ok(Ok(result)) => Ok(result), + Ok(Err(Error::Refused { code, message, .. })) => Err(Error::Refused { + method: method.to_owned(), + code, + message, + }), + Ok(Err(error)) => Err(error), + Err(_) => Err(Error::Closed), + } + } + + /// Send the notification `method`. + pub(crate) async fn notify(&self, method: &str, params: Value) -> Result<(), Error> { + let notification = json!({"jsonrpc": "2.0", "method": method, "params": params}); + Ok(self.sender.send(¬ification).await?) + } + + /// Answer the agent's request `id` with `result`. + pub(crate) async fn respond(&self, id: Value, result: Value) -> Result<(), Error> { + let response = json!({"jsonrpc": "2.0", "id": id, "result": result}); + Ok(self.sender.send(&response).await?) + } + + /// Refuse the agent's request `id` with `message`. + pub(crate) async fn refuse(&self, id: Value, message: &str) -> Result<(), Error> { + let error = json!({"code": NOT_OFFERED, "message": message}); + let response = json!({"jsonrpc": "2.0", "id": id, "error": error}); + Ok(self.sender.send(&response).await?) + } + + /// Answer the agent's request `id` from a task of the current runtime, + /// with a result or a refusal, for a caller that cannot wait, such as a + /// `Drop`. Without a runtime nothing is sent; the connection is then + /// ending anyway. + pub(crate) fn answer_detached(&self, id: &Value, answer: Result) { + let Ok(runtime) = tokio::runtime::Handle::try_current() else { + return; + }; + let response = match answer { + Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}), + Err(message) => { + let error = json!({"code": NOT_OFFERED, "message": message}); + json!({"jsonrpc": "2.0", "id": id, "error": error}) + } + }; + let sender = self.sender.clone(); + runtime.spawn(async move { + let _ = sender.send(&response).await; + }); + } + + /// Take what the agent sends unasked, until [`Self::unroute`] or another + /// route replaces this one. + pub(crate) fn route(&self) -> mpsc::UnboundedReceiver { + let (sender, receiver) = mpsc::unbounded_channel(); + *lock(&self.route) = Some(sender); + receiver + } + + /// Stop routing; requests are refused again. Once this returns, nothing + /// more reaches the route's receiver: the reader sends to it only while + /// holding the route. + pub(crate) fn unroute(&self) { + lock(&self.route).take(); + } +} + +impl Drop for Connection { + fn drop(&mut self) { + self.reader.abort(); + } +} + +async fn dispatch(message: Value, sender: &LineSender, waiting: &Waiting, route: &Route) { + let method = message["method"].as_str().map(str::to_owned); + let id = message.get("id").cloned().filter(|id| !id.is_null()); + match (method, id) { + (None, Some(id)) => { + let Some(call) = id.as_u64().and_then(|id| lock(waiting).remove(&id)) else { + return; + }; + let outcome = match message.get("error") { + Some(error) => Err(Error::Refused { + method: String::new(), + code: error["code"].as_i64().unwrap_or_default(), + message: error["message"].as_str().unwrap_or_default().to_owned(), + }), + None => Ok(message.get("result").cloned().unwrap_or(Value::Null)), + }; + let _ = call.send(outcome); + } + (Some(method), id) => { + let params = message.get("params").cloned().unwrap_or(Value::Null); + let incoming = match id.clone() { + Some(id) => Incoming::Request { id, method, params }, + None => Incoming::Notification { method, params }, + }; + let refused = match lock(route).as_ref() { + Some(route) => route.send(incoming).err().map(|unsent| unsent.0), + None => Some(incoming), + }; + if let (Some(Incoming::Request { id, method, .. }), true) = (refused, id.is_some()) { + let error = + json!({"code": NOT_OFFERED, "message": format!("{method} is not offered now")}); + let _ = sender + .send(&json!({"jsonrpc": "2.0", "id": id, "error": error})) + .await; + } + } + (None, None) => {} + } +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-acp/src/connection/test.rs b/crates/tinyhivemind-acp/src/connection/test.rs new file mode 100644 index 00000000..adee4403 --- /dev/null +++ b/crates/tinyhivemind-acp/src/connection/test.rs @@ -0,0 +1,154 @@ +//! The connection over a real child: `cat` echoes every line, so a call +//! comes back as a request from the "agent", and an answer to that comes +//! back as the call's response. +#![allow(clippy::unwrap_used, clippy::panic)] // Tests fail loudly on unexpected results. +use super::*; +use std::time::Duration; +use tinyhivemind_host::process::{Instance, InstanceDir, Launch, StopPolicy}; + +/// `future`, or a failed test after ten seconds. The echoing child dies with +/// its instance, dropped as the test unwinds. +async fn within(future: impl Future) -> T { + tokio::time::timeout(Duration::from_secs(10), future) + .await + .unwrap() +} + +async fn echo() -> (Instance, Connection, tempfile::TempDir) { + let root = tempfile::tempdir().unwrap(); + let dir = InstanceDir::create(root.path().join("cat")).unwrap(); + let mut instance = Instance::start(Launch::new("/bin/cat", dir).json_lines()) + .await + .unwrap(); + let connection = Connection::new(instance.take_lines().unwrap()); + (instance, connection, root) +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_request_nobody_routes_is_refused_at_once() { + let (instance, connection, _root) = echo().await; + let refused = within(connection.call("ping", json!({}))).await; + match refused { + Err(Error::Refused { + method, + code, + message, + }) => { + assert_eq!((method.as_str(), code), ("ping", NOT_OFFERED)); + assert!(message.contains("ping")); + } + other => panic!("{other:?}"), + } + instance + .stop(async {}, StopPolicy::default()) + .await + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_routed_request_is_answered_by_its_taker() { + let (instance, connection, _root) = echo().await; + let mut incoming = connection.route(); + let call = connection.call("ask", json!({"q": 1})); + tokio::pin!(call); + let request = within(async { + tokio::select! { + message = incoming.recv() => message.unwrap(), + _ = &mut call => panic!("answered before it was taken"), + } + }) + .await; + let Incoming::Request { id, method, params } = request else { + panic!("not a request") + }; + assert_eq!((method.as_str(), ¶ms), ("ask", &json!({"q": 1}))); + connection.respond(id, json!({"ok": true})).await.unwrap(); + assert_eq!(within(call).await.unwrap(), json!({"ok": true})); + connection.notify("note", json!({"a": 1})).await.unwrap(); + let note = within(incoming.recv()).await.unwrap(); + assert!(matches!(note, Incoming::Notification { ref method, .. } if method == "note")); + connection.unroute(); + assert!(within(connection.call("again", json!(null))).await.is_err()); + instance + .stop(async {}, StopPolicy::default()) + .await + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_refusal_from_the_client_reaches_the_caller() { + let (instance, connection, _root) = echo().await; + let mut incoming = connection.route(); + let call = connection.call("ask", json!({})); + tokio::pin!(call); + let request = within(async { + tokio::select! { + message = incoming.recv() => message.unwrap(), + _ = &mut call => panic!("answered before it was taken"), + } + }) + .await; + let Incoming::Request { id, .. } = request else { + panic!("not a request") + }; + connection.refuse(id, "no").await.unwrap(); + assert!( + matches!(within(call).await, Err(Error::Refused { ref message, .. }) if message == "no") + ); + instance + .stop(async {}, StopPolicy::default()) + .await + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_call_fails_once_the_agent_is_gone() { + let (instance, connection, _root) = echo().await; + instance + .stop(async {}, StopPolicy::default()) + .await + .unwrap(); + assert!(within(connection.call("late", json!({}))).await.is_err()); + assert!(Error::Closed.to_string().contains("closed")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_detached_answer_reaches_the_caller() { + let (instance, connection, _root) = echo().await; + let mut incoming = connection.route(); + let answered = connection.call("ask", json!({})); + tokio::pin!(answered); + let refused = connection.call("other", json!({})); + tokio::pin!(refused); + let mut ids = Vec::new(); + while ids.len() < 2 { + let message = within(async { + tokio::select! { + message = incoming.recv() => message.unwrap(), + _ = &mut answered => panic!("answered before it was taken"), + _ = &mut refused => panic!("refused before it was taken"), + } + }) + .await; + let Incoming::Request { id, method, .. } = message else { + panic!("not a request") + }; + ids.push((id, method)); + } + for (id, method) in ids { + let answer = if method == "ask" { + Ok(json!({"ok": true})) + } else { + Err("no".to_owned()) + }; + connection.answer_detached(&id, answer); + } + assert_eq!(within(answered).await.unwrap(), json!({"ok": true})); + assert!( + matches!(within(refused).await, Err(Error::Refused { ref message, .. }) if message == "no") + ); + instance + .stop(async {}, StopPolicy::default()) + .await + .unwrap(); +} diff --git a/crates/tinyhivemind-acp/src/error/README.md b/crates/tinyhivemind-acp/src/error/README.md new file mode 100644 index 00000000..da8c76a7 --- /dev/null +++ b/crates/tinyhivemind-acp/src/error/README.md @@ -0,0 +1,8 @@ +# Error + +This crate's failures, and the port's error each becomes. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `Error` and `From for harness::Error` | +| `test.rs` | The mapping | diff --git a/crates/tinyhivemind-acp/src/error/mod.rs b/crates/tinyhivemind-acp/src/error/mod.rs new file mode 100644 index 00000000..823a2f8f --- /dev/null +++ b/crates/tinyhivemind-acp/src/error/mod.rs @@ -0,0 +1,71 @@ +//! What can go wrong in this crate, and how the port sees it. +use crate::capability::Refusal; +use crate::connection; +use tinyhivemind_host::harness::{self, Mismatch}; +use tinyhivemind_host::process; + +/// Result of this crate's fallible steps. +pub(crate) type Result = std::result::Result; + +/// Failures before they reach the port. +#[derive(Debug, thiserror::Error)] +pub(crate) enum Error { + /// The seat asks for what this agent cannot do. + #[error(transparent)] + Refused(#[from] Refusal), + /// The agent's protocol failed. + #[error(transparent)] + Protocol(#[from] connection::Error), + /// The process could not be supervised. + #[error(transparent)] + Process(#[from] process::Error), + /// The agent is not the one asked for. + #[error(transparent)] + Mismatch(#[from] Mismatch), + /// The agent cannot run a seat: it does not offer what a seat needs. + #[error("the agent cannot run a seat: {0}")] + Unsupported(String), + /// The agent broke the protocol. + #[error("the agent broke the protocol: {0}")] + Broken(String), + /// The seat's session could not be resumed; no new one is started. + #[error("session {session} could not be resumed: {reason}")] + Resume { session: String, reason: String }, + /// The turn's request could not be rendered as its prompt. + #[error("the turn could not be rendered: {0}")] + Render(String), + /// The seat was stopped. + #[error("the seat is stopped")] + Closed, + /// A file of the instance could not be written. + #[error("{what}: {source}")] + Io { + what: &'static str, + source: std::io::Error, + }, +} + +impl Error { + /// An I/O failure at `what`. + pub(crate) fn io(what: &'static str) -> impl FnOnce(std::io::Error) -> Self { + move |source| Self::Io { what, source } + } +} + +impl From for harness::Error { + fn from(error: Error) -> Self { + match error { + Error::Refused(refusal) => Self::Refused(Box::new(refusal)), + Error::Process(error) => Self::Process(error), + Error::Mismatch(mismatch) => Self::Mismatch(mismatch), + Error::Resume { session, reason } => Self::Resume { + session_id: session, + reason, + }, + other => Self::Harness(other.to_string()), + } + } +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-acp/src/error/test.rs b/crates/tinyhivemind-acp/src/error/test.rs new file mode 100644 index 00000000..282ed978 --- /dev/null +++ b/crates/tinyhivemind-acp/src/error/test.rs @@ -0,0 +1,30 @@ +//! How this crate's errors reach the port. +#![allow(clippy::unwrap_used)] // Tests fail loudly on unexpected results. +use super::*; +use tinyhivemind_host::harness::Error as Port; + +#[test] +fn errors_keep_their_meaning_at_the_port() { + let refused: Port = Error::Refused(Refusal::NoModel("s".into())).into(); + assert!(matches!(refused, Port::Refused(_))); + let resume: Port = Error::Resume { + session: "x".into(), + reason: "gone".into(), + } + .into(); + assert!(matches!(resume, Port::Resume { ref session_id, .. } if session_id == "x")); + let closed: Port = Error::Closed.into(); + assert_eq!(closed.to_string(), "harness failed: the seat is stopped"); + let unsupported: Port = Error::Unsupported("no HTTP MCP".into()).into(); + assert_eq!( + unsupported.to_string(), + "harness failed: the agent cannot run a seat: no HTTP MCP" + ); + let broken: Port = Error::Broken("no stopReason".into()).into(); + assert_eq!( + broken.to_string(), + "harness failed: the agent broke the protocol: no stopReason" + ); + let io = Error::io("a file")(std::io::Error::other("full")); + assert_eq!(io.to_string(), "a file: full"); +} diff --git a/crates/tinyhivemind-acp/src/harness/README.md b/crates/tinyhivemind-acp/src/harness/README.md new file mode 100644 index 00000000..5809e474 --- /dev/null +++ b/crates/tinyhivemind-acp/src/harness/README.md @@ -0,0 +1,7 @@ +# Harness + +`AcpHarness`: the host's `Harness` port for any `Agent`, one process per seat. A seat id is held from the start of its start to the end of its stop: a dropped start stops what it began before it frees the id, and a failed stop keeps it, so two processes never run for one id. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `AcpHarness`, `Options` | diff --git a/crates/tinyhivemind-acp/src/harness/mod.rs b/crates/tinyhivemind-acp/src/harness/mod.rs new file mode 100644 index 00000000..dab53500 --- /dev/null +++ b/crates/tinyhivemind-acp/src/harness/mod.rs @@ -0,0 +1,185 @@ +//! [`AcpHarness`]: the host's harness port for any [`Agent`]. +//! +//! Each seat is one process of the agent, started by [`crate::seat`] and run +//! by a seat runner held to the port's rules by [`SeatRunner`]. +use crate::agent::Agent; +use crate::capability; +use crate::seat::{Runner, Seat}; +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; +use tinyhivemind_hives::AgentRunner; +use tinyhivemind_host::harness::{ + Error, Harness, HarnessKind, SeatPlan, SeatRunner, StartFuture, StopFuture, ToolEndpoint, +}; +use tinyhivemind_host::process::StopPolicy; + +/// How long the steps of running a seat may take. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Options { + /// From spawn to an answered `initialize`. + pub ready: Duration, + /// Each step of a stop. + pub stop: StopPolicy, + /// For the seat's approver to decide what the agent asks; then the call + /// is refused. + pub approval: Duration, + /// For a cancelled prompt to be answered; then the process is stopped. + pub cancel: Duration, +} + +impl Default for Options { + /// 60 s to initialize, the supervisor's own stop, 2 minutes for an + /// approval and 10 s for a cancel. + fn default() -> Self { + Self { + ready: Duration::from_secs(60), + stop: StopPolicy::default(), + approval: Duration::from_secs(120), + cancel: Duration::from_secs(10), + } + } +} + +/// The seats of one harness, by id. +type Registry = Arc>>>; + +/// Runs seats on one ACP agent, one supervised process per seat. +/// +/// A seat id is held from the start of its start to the end of its stop, so +/// no two processes ever run for one id: a second start meanwhile is refused. +/// +/// Its futures must be driven within a Tokio runtime with time and I/O +/// enabled. +#[derive(Debug)] +pub struct AcpHarness { + agent: Agent, + options: Options, + seats: Registry, +} + +impl AcpHarness { + /// Seats on `agent`, with the default [`Options`]. + #[must_use] + pub fn new(agent: Agent) -> Self { + Self { + agent, + options: Options::default(), + seats: Arc::default(), + } + } + + /// The same, with `options`. + #[must_use] + pub fn with_options(mut self, options: Options) -> Self { + self.options = options; + self + } +} + +fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Free `id` if `seat` still holds it. +fn release(seats: &Registry, id: &str, seat: &Arc) { + let mut seats = lock(seats); + if seats.get(id).is_some_and(|held| Arc::ptr_eq(held, seat)) { + seats.remove(id); + } +} + +/// A seat's hold on its id while its start runs. Dropped before +/// [`Self::keep`], because the start failed or its future was dropped, it +/// stops the seat and only then frees the id. A process mid-launch is killed +/// with its dropped instance; one already running is stopped here. +struct Reservation { + seats: Registry, + id: String, + seat: Arc, + kept: bool, +} + +impl Reservation { + /// The start succeeded: the seat keeps its id. + fn keep(mut self) { + self.kept = true; + } +} + +impl Drop for Reservation { + fn drop(&mut self) { + if self.kept { + return; + } + let (seats, id, seat) = (self.seats.clone(), self.id.clone(), self.seat.clone()); + match tokio::runtime::Handle::try_current() { + Ok(runtime) => { + runtime.spawn(async move { + // A seat that will not stop keeps its id: nothing may + // start beside it. + if seat.stop().await.is_ok() { + release(&seats, &id, &seat); + } + }); + } + Err(_) => release(&seats, &id, &seat), + } + } +} + +impl Harness for AcpHarness { + fn kind(&self) -> HarnessKind { + self.agent.kind + } + + /// Refuses, with [`Error::Refused`] holding a [`capability::Refusal`], a + /// seat whose model route the agent cannot take, before anything starts. + fn start(&self, plan: SeatPlan, tools: ToolEndpoint) -> StartFuture { + let agent = self.agent.clone(); + let options = self.options; + let seats = self.seats.clone(); + Box::pin(async move { + let model = capability::check(&plan.seat, agent.kind) + .map_err(|refusal| Error::Refused(Box::new(refusal)))?; + let id = plan.seat.id.clone(); + let timeout = plan.turn_timeout(); + let seat = Arc::new(Seat::new(agent, options, plan, tools, &model)); + let reservation = { + // Reserved before anything starts, so that a second start is + // refused and a stop meanwhile finds the seat to stop. + let mut held = lock(&seats); + if held.contains_key(&id) { + return Err(Error::Harness(format!("seat {id} is already running"))); + } + held.insert(id.clone(), seat.clone()); + Reservation { + seats: seats.clone(), + id: id.clone(), + seat: seat.clone(), + kept: false, + } + }; + seat.start().await?; + reservation.keep(); + let runner = SeatRunner::new(Arc::new(Runner(seat))).with_timeout(timeout); + Ok(Arc::new(runner) as Arc) + }) + } + + /// The id stays held until the process is proved stopped, and after a + /// failed stop, so the stop can be retried and nothing starts beside it. + fn stop(&self, seat_id: &str) -> StopFuture { + let seats = self.seats.clone(); + let id = seat_id.to_owned(); + let seat = lock(&seats).get(seat_id).cloned(); + Box::pin(async move { + let Some(seat) = seat else { + return Ok(()); + }; + seat.stop().await?; + release(&seats, &id, &seat); + Ok(()) + }) + } +} diff --git a/crates/tinyhivemind-acp/src/lib.rs b/crates/tinyhivemind-acp/src/lib.rs new file mode 100644 index 00000000..b2c7c20d --- /dev/null +++ b/crates/tinyhivemind-acp/src/lib.rs @@ -0,0 +1,51 @@ +//! Hive seats on any Agent Client Protocol agent, each a supervised process. +//! +//! [`AcpHarness`] implements the host's +//! [`Harness`](tinyhivemind_host::harness::Harness) port once, for every +//! agent that speaks the [Agent Client Protocol](https://agentclientprotocol.com) +//! over stdio. What differs between agents is an [`Agent`]: the command, its +//! environment and files, the `session/new` metadata that turns its built-in +//! tools off, and the session mode. [`Agent::claude_code`] and +//! [`Agent::codex`] are the two measured in +//! `docs/experiments/2026-11-26-acp-harnesses.md`. +//! +//! A seat is one agent process in its own private directory. Its first turn +//! opens an ACP session with the host's tool server as its one MCP server; +//! every turn is a `session/prompt` on that session, and a restarted process +//! resumes it with `session/load`. A permission request for one of the host's +//! tools is allowed here, since the tool server already judges hive tools; +//! any other goes to the seat's approver. +//! +//! ```no_run +//! use tinyhivemind_acp::{AcpHarness, Agent}; +//! use tinyhivemind_host::harness::{Harness, SeatPlan, ToolEndpoint}; +//! +//! # async fn start(seat: tinyhivemind_lang::LoweredSeat) -> Result<(), Box> { +//! let agent = Agent::claude_code( +//! "/usr/bin/node", +//! "/opt/acp/claude/node_modules/@agentclientprotocol/claude-agent-acp/dist/index.js", +//! "0.112.0", +//! ); +//! let harness = AcpHarness::new(agent); +//! let tools = ToolEndpoint::new("hive", "http://127.0.0.1:7000/mcp", "seat-bearer", ["hivemind_post".to_owned()]); +//! let runner = harness.start(SeatPlan::new(seat, "/var/lib/hive/scout"), tools).await?; +//! // Register `runner` with the coordinator; stop the seat with: +//! harness.stop("scout").await?; +//! # drop(runner); Ok(()) } +//! ``` +//! +//! What this crate does not hold: it links no agent and installs none (the +//! host passes the paths of pinned installs); it serves no tools (the host's +//! MCP server does); and it cannot observe the tool list an agent shows its +//! model, which ACP does not expose, so that is held by each descriptor's +//! settings and proven by the live tests rather than checked at start. +pub mod agent; +pub mod capability; +mod connection; +mod error; +mod harness; +mod protocol; +mod seat; + +pub use agent::{Agent, CatalogError}; +pub use harness::{AcpHarness, Options}; diff --git a/crates/tinyhivemind-acp/src/protocol/README.md b/crates/tinyhivemind-acp/src/protocol/README.md new file mode 100644 index 00000000..8900ce1f --- /dev/null +++ b/crates/tinyhivemind-acp/src/protocol/README.md @@ -0,0 +1,8 @@ +# Protocol + +The ACP version 1 messages a seat needs. Reading is tolerant; usage is read where the measured agents put it. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `initialize` and accepting its result, MCP server, prompt, usage, stop reasons, updates, permission answers | +| `test.rs` | Each message built and read | diff --git a/crates/tinyhivemind-acp/src/protocol/mod.rs b/crates/tinyhivemind-acp/src/protocol/mod.rs new file mode 100644 index 00000000..40bed281 --- /dev/null +++ b/crates/tinyhivemind-acp/src/protocol/mod.rs @@ -0,0 +1,170 @@ +//! The few Agent Client Protocol messages a seat needs, built and read as +//! JSON. +//! +//! Protocol version 1. The client offers no file system and no terminal, so +//! the agent can only use the tools it is given. Reading is tolerant: a +//! field this crate does not know is ignored, and the usage an agent reports +//! (still unstable in the protocol's schema) is read where the measured +//! agents put it. +use serde_json::{Value, json}; +use tinyhivemind_host::harness::{ToolEndpoint, TurnUsage}; + +/// The protocol version this client speaks. +pub(crate) const VERSION: u64 = 1; + +/// `initialize`'s parameters: version 1, no file system, no terminal. +pub(crate) fn initialize() -> Value { + json!({ + "protocolVersion": VERSION, + "clientCapabilities": { + "fs": {"readTextFile": false, "writeTextFile": false}, + "terminal": false, + }, + "clientInfo": {"name": "tinyhivemind-acp", "version": env!("CARGO_PKG_VERSION")}, + }) +} + +/// The version an `initialize` result reports for the agent, if any. +pub(crate) fn agent_version(result: &Value) -> Option<&str> { + result["agentInfo"]["version"].as_str() +} + +/// What an agent's `initialize` result promises that a seat relies on. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct Accepted { + /// Whether it can `session/load` a session it ran before. + pub(crate) load_session: bool, +} + +/// Accept an `initialize` result, or say why a seat cannot use the agent: +/// it must speak protocol version 1 and connect to an HTTP MCP server, +/// which is how the host's tools reach it. +pub(crate) fn accept(result: &Value) -> Result { + let version = &result["protocolVersion"]; + if version.as_u64() != Some(VERSION) { + return Err(format!( + "the agent speaks protocol version {version}, not {VERSION}" + )); + } + let capabilities = &result["agentCapabilities"]; + if capabilities["mcpCapabilities"]["http"] != true { + return Err("the agent cannot connect to an HTTP MCP server".to_owned()); + } + Ok(Accepted { + load_session: capabilities["loadSession"] == true, + }) +} + +/// The host's tool server as an ACP HTTP MCP server, its bearer in a header. +pub(crate) fn mcp_server(tools: &ToolEndpoint) -> Value { + json!({ + "type": "http", + "name": tools.server, + "url": tools.url, + "headers": [{"name": "Authorization", "value": format!("Bearer {}", tools.bearer())}], + }) +} + +/// A prompt of one text block. +pub(crate) fn prompt(session: &str, text: &str) -> Value { + json!({"sessionId": session, "prompt": [{"type": "text", "text": text}]}) +} + +/// The usage of a `session/prompt` result: `inputTokens` there excludes the +/// cached reads and writes, which [`TurnUsage::input_tokens`] includes. +pub(crate) fn usage(result: &Value) -> Option { + let usage = result.get("usage").filter(|usage| usage.is_object())?; + let count = |name: &str| usage[name].as_u64().unwrap_or(0); + Some(TurnUsage { + input_tokens: count("inputTokens") + count("cachedReadTokens") + count("cachedWriteTokens"), + cached_input_tokens: count("cachedReadTokens"), + output_tokens: count("outputTokens"), + reasoning_tokens: count("thoughtTokens"), + }) +} + +/// Why a turn that stopped for `reason` failed, or `None` if it ended +/// normally. +pub(crate) fn failure(reason: &str) -> Option { + (reason != "end_turn").then(|| format!("the agent stopped: {reason}")) +} + +/// One `session/update` this crate acts on. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum Update { + /// Some of the agent's reply. + Text(String), + /// A tool call started, with the MCP server it goes to when the agent + /// says. + ToolCall { + id: String, + title: String, + server: Option, + }, + /// A tool call ended. + ToolEnded { id: String, failed: bool }, + /// Anything else. + Other, +} + +/// Read a `session/update` notification's `update`. +pub(crate) fn update(update: &Value) -> Update { + let text = |name: &str| update[name].as_str().unwrap_or_default().to_owned(); + match update["sessionUpdate"].as_str() { + Some("agent_message_chunk") => match update["content"]["text"].as_str() { + Some(chunk) => Update::Text(chunk.to_owned()), + None => Update::Other, + }, + Some("tool_call") => Update::ToolCall { + id: text("toolCallId"), + title: text("title"), + server: update["rawInput"]["server"].as_str().map(str::to_owned), + }, + Some("tool_call_update") => match update["status"].as_str() { + Some(status @ ("completed" | "failed")) => Update::ToolEnded { + id: text("toolCallId"), + failed: status == "failed", + }, + _ => Update::Other, + }, + _ => Update::Other, + } +} + +/// The option of a `session/request_permission` that allows the call once, +/// or failing that at all. +pub(crate) fn allow(options: &Value) -> Option { + pick(options, &["allow_once", "allow_always"]) +} + +/// The answer that refuses the call: its reject option, or cancelled. +pub(crate) fn refuse(options: &Value) -> Value { + match pick(options, &["reject_once", "reject_always"]) { + Some(option) => selected(&option), + None => cancelled(), + } +} + +/// The answer to a permission request whose turn was cancelled. +pub(crate) fn cancelled() -> Value { + json!({"outcome": {"outcome": "cancelled"}}) +} + +/// The answer that selects `option`. +pub(crate) fn selected(option: &str) -> Value { + json!({"outcome": {"outcome": "selected", "optionId": option}}) +} + +fn pick(options: &Value, kinds: &[&str]) -> Option { + let options = options.as_array()?; + kinds.iter().find_map(|kind| { + options + .iter() + .find(|option| option["kind"] == *kind) + .and_then(|option| option["optionId"].as_str()) + .map(str::to_owned) + }) +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-acp/src/protocol/test.rs b/crates/tinyhivemind-acp/src/protocol/test.rs new file mode 100644 index 00000000..b16fbf19 --- /dev/null +++ b/crates/tinyhivemind-acp/src/protocol/test.rs @@ -0,0 +1,161 @@ +//! Building and reading the protocol's messages. +#![allow(clippy::unwrap_used)] // Tests fail loudly on unexpected results. +use super::*; +use serde_json::json; + +#[test] +fn initialize_offers_no_file_system_and_no_terminal() { + let params = initialize(); + assert_eq!(params["protocolVersion"], 1); + assert_eq!(params["clientCapabilities"]["fs"]["readTextFile"], false); + assert_eq!(params["clientCapabilities"]["fs"]["writeTextFile"], false); + assert_eq!(params["clientCapabilities"]["terminal"], false); + let result = json!({"agentInfo": {"name": "a", "version": "1.2.3"}}); + assert_eq!(agent_version(&result), Some("1.2.3")); + assert_eq!(agent_version(&json!({})), None); +} + +#[test] +fn the_host_server_carries_its_bearer_in_a_header() { + let tools = ToolEndpoint::new( + "hive", + "http://127.0.0.1:1/mcp", + "secret", + ["hivemind_post".to_owned()], + ); + let server = mcp_server(&tools); + assert_eq!(server["type"], "http"); + assert_eq!(server["name"], "hive"); + assert_eq!(server["url"], "http://127.0.0.1:1/mcp"); + assert_eq!( + server["headers"][0], + json!({"name": "Authorization", "value": "Bearer secret"}) + ); + assert_eq!( + prompt("s", "hi"), + json!({"sessionId": "s", "prompt": [{"type": "text", "text": "hi"}]}) + ); +} + +#[test] +fn usage_counts_cached_input_as_input() { + let result = json!({"usage": {"inputTokens": 90, "cachedReadTokens": 10, "cachedWriteTokens": 5, + "outputTokens": 7, "thoughtTokens": 2, "totalTokens": 114}}); + assert_eq!( + usage(&result), + Some(TurnUsage { + input_tokens: 105, + cached_input_tokens: 10, + output_tokens: 7, + reasoning_tokens: 2 + }) + ); + assert_eq!(usage(&json!({"stopReason": "end_turn"})), None); + assert_eq!(usage(&json!({"usage": null})), None); +} + +#[test] +fn only_end_turn_is_a_normal_end() { + assert_eq!(failure("end_turn"), None); + for reason in ["cancelled", "max_tokens", "max_turn_requests", "refusal"] { + assert_eq!( + failure(reason), + Some(format!("the agent stopped: {reason}")) + ); + } +} + +#[test] +fn updates_are_read_by_kind() { + let text = + json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "hi"}}); + assert_eq!(update(&text), Update::Text("hi".into())); + let image = json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "image"}}); + assert_eq!(update(&image), Update::Other); + let call = json!({"sessionUpdate": "tool_call", "toolCallId": "c1", "title": "mcp.hive.hivemind_post", + "rawInput": {"server": "hive", "tool": "hivemind_post"}}); + assert_eq!( + update(&call), + Update::ToolCall { + id: "c1".into(), + title: "mcp.hive.hivemind_post".into(), + server: Some("hive".into()) + } + ); + let done = + json!({"sessionUpdate": "tool_call_update", "toolCallId": "c1", "status": "completed"}); + assert_eq!( + update(&done), + Update::ToolEnded { + id: "c1".into(), + failed: false + } + ); + let failed = + json!({"sessionUpdate": "tool_call_update", "toolCallId": "c1", "status": "failed"}); + assert_eq!( + update(&failed), + Update::ToolEnded { + id: "c1".into(), + failed: true + } + ); + let running = + json!({"sessionUpdate": "tool_call_update", "toolCallId": "c1", "status": "in_progress"}); + assert_eq!(update(&running), Update::Other); + assert_eq!( + update(&json!({"sessionUpdate": "usage_update"})), + Update::Other + ); +} + +#[test] +fn permission_answers_pick_the_options_by_kind() { + let options = json!([ + {"optionId": "a1", "kind": "allow_always"}, + {"optionId": "a0", "kind": "allow_once"}, + {"optionId": "r0", "kind": "reject_once"}, + ]); + assert_eq!(allow(&options).as_deref(), Some("a0")); + assert_eq!(refuse(&options), selected("r0")); + let only_always = json!([{"optionId": "a1", "kind": "allow_always"}]); + assert_eq!(allow(&only_always).as_deref(), Some("a1")); + assert_eq!( + refuse(&only_always), + json!({"outcome": {"outcome": "cancelled"}}) + ); + assert_eq!(allow(&json!(null)), None); + assert_eq!( + selected("x"), + json!({"outcome": {"outcome": "selected", "optionId": "x"}}) + ); +} + +#[test] +fn an_agent_is_accepted_only_on_version_1_with_http_mcp() { + let init = |version: Value, http: Value, load: Value| { + json!({"protocolVersion": version, "agentCapabilities": { + "mcpCapabilities": {"http": http}, "loadSession": load}}) + }; + assert_eq!( + accept(&init(json!(1), json!(true), json!(true))), + Ok(Accepted { load_session: true }) + ); + assert_eq!( + accept(&init(json!(1), json!(true), Value::Null)), + Ok(Accepted { + load_session: false + }) + ); + let old = accept(&init(json!(2), json!(true), json!(true))).unwrap_err(); + assert!(old.contains("version 2"), "{old}"); + let missing = accept(&json!({"agentCapabilities": {}})).unwrap_err(); + assert!(missing.contains("version null"), "{missing}"); + let no_http = accept(&init(json!(1), json!(false), json!(true))).unwrap_err(); + assert!(no_http.contains("HTTP MCP"), "{no_http}"); +} + +#[test] +fn a_cancelled_permission_answers_cancelled() { + assert_eq!(cancelled(), json!({"outcome": {"outcome": "cancelled"}})); +} diff --git a/crates/tinyhivemind-acp/src/seat/README.md b/crates/tinyhivemind-acp/src/seat/README.md new file mode 100644 index 00000000..612d315b --- /dev/null +++ b/crates/tinyhivemind-acp/src/seat/README.md @@ -0,0 +1,8 @@ +# Seat + +One seat: its agent process in a private directory, its one session (new, or loaded after a restart), the turn it runs, cancel and stop. An agent is used only if its `initialize` says protocol version 1 and HTTP MCP; a session is loaded only if it says `loadSession`. A cancel answers the turn's pending permission requests `cancelled`, and a turn's route is closed, and what it held answered, even if its future is dropped. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `Seat`, `Live`, launch and verification, sessions, cancel, stop, `Runner` | +| `turn.rs` | One `session/prompt`: progress, permission answers, reply and usage; a result without a `stopReason` is a broken protocol | diff --git a/crates/tinyhivemind-acp/src/seat/mod.rs b/crates/tinyhivemind-acp/src/seat/mod.rs new file mode 100644 index 00000000..b165b93a --- /dev/null +++ b/crates/tinyhivemind-acp/src/seat/mod.rs @@ -0,0 +1,411 @@ +//! One seat: its agent process, its session, and the turn it may be running. +//! +//! An instance lives in the seat's directory, made private by +//! [`InstanceDir`]. Its state directory holds `home/` (the process's +//! `HOME`), `cwd/` (its working directory and the session's `cwd`) and the +//! descriptor's files. The state survives a restart, so a session the agent +//! stored there can be loaded again. +mod turn; + +use crate::agent::{Agent, Values}; +use crate::capability::SeatModel; +use crate::connection::Connection; +use crate::error::{Error, Result}; +use crate::harness::Options; +use crate::protocol; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, HashSet}; +use std::fs; +use std::os::unix::fs::DirBuilderExt as _; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use tinyhivemind_hives::{AgentRunner, TurnFuture, TurnOutcome, TurnRequest}; +use tinyhivemind_host::harness::{ + self, CancelFuture, CancellableRunner, Event, Expected, Observed, SeatPlan, Started, + ToolEndpoint, +}; +use tinyhivemind_host::process::{Instance, InstanceDir, Launch}; +use tokio::sync::{Mutex as AsyncMutex, watch}; + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// A started, verified agent process. +#[derive(Debug)] +pub(crate) struct Live { + pub(crate) instance: Instance, + pub(crate) connection: Connection, + pub(crate) started: Started, + /// Whether the agent can `session/load` a session. + load_session: bool, + /// Sessions opened or loaded by this process. + sessions: Mutex>, + /// Of those, the ones in the descriptor's mode. + moded: Mutex>, +} + +/// The turn running now: its session, and the signal that it is cancelled. +#[derive(Debug)] +struct Active { + session: String, + cancelled: watch::Sender, +} + +impl Active { + /// Tell the turn it is cancelled; its session. + fn cancel(&self) -> String { + self.cancelled.send_replace(true); + self.session.clone() + } +} + +/// A seat and its process, if one is running. +#[derive(Debug)] +pub(crate) struct Seat { + agent: Agent, + options: Options, + plan: SeatPlan, + tools: ToolEndpoint, + values: Values, + live: AsyncMutex>>, + /// The turn running now, for a cancel. + active: Mutex>, + /// The seat's one session, once it has one. + session: Mutex>, + closed: watch::Sender, +} + +/// The state directory [`InstanceDir`] keeps under a seat's directory. +fn state_of(directory: &Path) -> PathBuf { + directory.join("state") +} + +/// The template values of one seat. +fn values(agent: &Agent, plan: &SeatPlan, tools: &ToolEndpoint, model: &SeatModel) -> Values { + let state = state_of(&plan.directory); + let path = |path: &Path| path.to_string_lossy().into_owned(); + let program_dir = agent.program.parent().map(path).unwrap_or_default(); + let mut values = BTreeMap::from([ + ("state".to_owned(), path(&state)), + ("home".to_owned(), path(&state.join("home"))), + ("endpoint".to_owned(), model.endpoint.clone()), + ("model".to_owned(), model.model.clone()), + ("server".to_owned(), tools.server.clone()), + ("program_dir".to_owned(), program_dir), + ]); + values.extend(agent.vars.clone()); + let allowed_tools = tools + .tools + .iter() + .map(|tool| { + agent + .tool_name + .replace("{server}", &tools.server) + .replace("{tool}", tool) + }) + .collect(); + Values { + values, + allowed_tools, + } +} + +impl Seat { + pub(crate) fn new( + agent: Agent, + options: Options, + plan: SeatPlan, + tools: ToolEndpoint, + model: &SeatModel, + ) -> Self { + let values = values(&agent, &plan, &tools, model); + Self { + agent, + options, + plan, + tools, + values, + live: AsyncMutex::new(None), + active: Mutex::new(None), + session: Mutex::new(None), + closed: watch::channel(false).0, + } + } + + fn cwd(&self) -> PathBuf { + state_of(&self.plan.directory).join("cwd") + } + + /// Start a process if none is running, reporting it. + pub(crate) async fn start(&self) -> Result> { + let mut live = self.live.lock().await; + if *self.closed.borrow() { + return Err(Error::Closed); + } + if let Some(running) = live.as_ref().filter(|live| live.instance.exit().is_none()) { + return Ok(running.clone()); + } + // Kept until it is proved stopped, so a failed stop can be retried. + if let Some(dead) = live.clone() { + dead.instance.stop(async {}, self.options.stop).await?; + *live = None; + } + let started = Arc::new(self.launch().await?); + if *self.closed.borrow() { + started.instance.stop(async {}, self.options.stop).await?; + return Err(Error::Closed); + } + let event = Event::Started(started.started.clone()); + self.plan.observer.event(&self.plan.seat.id, event); + *live = Some(started.clone()); + Ok(started) + } + + /// Write the descriptor's files, start the agent and verify it; or leave + /// nothing running. + async fn launch(&self) -> Result { + let dir = InstanceDir::create(&self.plan.directory)?; + let state = dir.state().to_path_buf(); + let mut builder = fs::DirBuilder::new(); + builder.recursive(true).mode(0o700); + for sub in ["home", "cwd"] { + builder + .create(state.join(sub)) + .map_err(Error::io("the instance directories"))?; + } + for (path, template) in &self.agent.files { + let content = self.values.fill_file(path, template); + let path = state.join(path); + if let Some(parent) = path.parent() { + builder + .create(parent) + .map_err(Error::io("an agent file's directory"))?; + } + fs::write(&path, content).map_err(Error::io("an agent file"))?; + } + let mut launch = Launch::new(&self.agent.program, dir.clone()) + .current_dir(self.cwd()) + .json_lines(); + for argument in &self.agent.args { + launch = launch.arg(self.values.fill(argument)); + } + for (name, value) in &self.agent.env { + launch = launch.env(name, self.values.fill(value)); + } + let mut instance = Instance::start(launch).await?; + let Some(lines) = instance.take_lines() else { + let stopped = instance.stop(async {}, self.options.stop).await; + return Err(stopped.map_or_else(Error::from, |_| Error::Closed)); + }; + let connection = Connection::new(lines); + let initialize = connection.call("initialize", protocol::initialize()); + let init = match instance.ready(initialize, self.options.ready).await { + Ok(init) => init, + Err(error) => { + let _ = instance.stop(async {}, self.options.stop).await; + return Err(error.into()); + } + }; + let accepted = match protocol::accept(&init) { + Ok(accepted) => accepted, + Err(reason) => { + let _ = instance.stop(async {}, self.options.stop).await; + return Err(Error::Unsupported(reason)); + } + }; + let pid = instance.pid(); + let version = protocol::agent_version(&init).unwrap_or_default(); + let names = self.values.allowed_tools.clone(); + let expected = Expected::new(pid, &self.agent.version).tools(names.clone()); + // ACP shows no tool list; these are the names the descriptor allows. + let observed = Observed::new(pid, version).tools(names); + match expected.verify(&observed) { + Ok(started) => Ok(Live { + instance, + connection, + started, + load_session: accepted.load_session, + sessions: Mutex::default(), + moded: Mutex::default(), + }), + Err(mismatch) => { + let _ = instance.stop(async {}, self.options.stop).await; + Err(mismatch.into()) + } + } + } + + /// The `session/new` and `session/load` parameters. + fn session_params(&self) -> Value { + let mut params = json!({ + "cwd": self.cwd(), + "mcpServers": [protocol::mcp_server(&self.tools)], + }); + if let Some(meta) = &self.agent.session_meta { + params["_meta"] = self.values.fill_json(meta); + } + params + } + + /// The session for a turn that asks for `requested`: the one this process + /// has, one it loads, or a new one for the seat's first turn; in the + /// descriptor's mode. + /// + /// A session is the seat's once it is opened, before its mode is set, so + /// a failed `session/set_mode` is retried on that session next turn + /// rather than leaving it behind for a new one. + async fn session(&self, live: &Live, requested: Option) -> Result { + let requested = requested.or_else(|| lock(&self.session).clone()); + let open = requested + .as_ref() + .filter(|session| lock(&live.sessions).contains(*session)) + .cloned(); + let session = match (open, requested) { + (Some(session), _) => session, + (None, Some(session)) => self.load(live, session).await?, + (None, None) => { + let params = self.session_params(); + let created = live.connection.call("session/new", params).await?; + created["sessionId"] + .as_str() + .filter(|id| !id.is_empty()) + .map(str::to_owned) + .ok_or_else(|| Error::Broken("session/new returned no sessionId".into()))? + } + }; + lock(&live.sessions).insert(session.clone()); + *lock(&self.session) = Some(session.clone()); + if let Some(mode) = &self.agent.mode + && !lock(&live.moded).contains(&session) + { + let params = json!({"sessionId": session, "modeId": mode}); + live.connection.call("session/set_mode", params).await?; + lock(&live.moded).insert(session.clone()); + } + Ok(session) + } + + /// Load `session` into this process, which must be able to. + async fn load(&self, live: &Live, session: String) -> Result { + if !live.load_session { + return Err(Error::Resume { + session, + reason: "the agent cannot load a session".into(), + }); + } + let mut params = self.session_params(); + params["sessionId"] = session.clone().into(); + let loaded = live.connection.call("session/load", params).await; + loaded.map_err(|error| Error::Resume { + session: session.clone(), + reason: error.to_string(), + })?; + Ok(session) + } + + async fn run(&self, request: TurnRequest) -> Result { + if *self.closed.borrow() { + return Err(Error::Closed); + } + let live = self.start().await?; + let session = self.session(&live, request.session_id.clone()).await?; + let text = tinyhivemind_host::turn::render(&request) + .map_err(|error| Error::Render(error.to_string()))?; + let (cancelled, cancel) = watch::channel(false); + *lock(&self.active) = Some(Active { + session: session.clone(), + cancelled, + }); + let turn = turn::Turn { + live: &live, + seat: &self.plan.seat.id, + server: &self.tools.server, + id: &request.turn_id, + session: &session, + plan: &self.plan, + approval: self.options.approval, + cancelled: cancel, + }; + let ended = turn.run(&text).await; + lock(&self.active).take(); + let ended = ended?; + if let Some(usage) = ended.usage { + let event = Event::Usage { + turn_id: request.turn_id.clone(), + usage, + }; + self.plan.observer.event(&self.plan.seat.id, event); + } + Ok(TurnOutcome { + session_id: session, + reply: Some(ended.reply).filter(|reply| !reply.is_empty()), + disposition: ended.disposition, + }) + } + + /// Cancel the running turn and see its prompt answered, or stop the + /// process. + async fn cancel(&self) -> Result<()> { + let Some(session) = lock(&self.active).as_ref().map(Active::cancel) else { + return Ok(()); + }; + let mut live = self.live.lock().await; + let Some(running) = live.clone() else { + return Ok(()); + }; + if running.instance.exit().is_none() { + let params = json!({"sessionId": session}); + let _ = running.connection.notify("session/cancel", params).await; + let deadline = tokio::time::Instant::now() + self.options.cancel; + while lock(&self.active).is_some() && tokio::time::Instant::now() < deadline { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + if lock(&self.active).is_none() { + return Ok(()); + } + } + // It did not show the turn stopped: nothing of it may run on. + running.instance.stop(async {}, self.options.stop).await?; + *live = None; + lock(&self.active).take(); + Ok(()) + } + + /// Cancel, then stop the process and prove it gone. The process is kept + /// until then, so a failed stop can be retried. + pub(crate) async fn stop(&self) -> Result<()> { + self.closed.send_replace(true); + let mut held = self.live.lock().await; + let Some(live) = held.clone() else { + return Ok(()); + }; + let active = lock(&self.active).as_ref().map(Active::cancel); + let cancel = async { + if let Some(session) = active { + let params = json!({"sessionId": session}); + let _ = live.connection.notify("session/cancel", params).await; + } + }; + live.instance.stop(cancel, self.options.stop).await?; + *held = None; + Ok(()) + } +} + +/// The seat as the seat runner sees it. +pub(crate) struct Runner(pub(crate) Arc); + +impl AgentRunner for Runner { + fn run(&self, request: TurnRequest) -> TurnFuture { + let seat = self.0.clone(); + Box::pin(async move { Ok(seat.run(request).await.map_err(harness::Error::from)?) }) + } +} + +impl CancellableRunner for Runner { + fn cancel(&self, _: &str) -> CancelFuture { + let seat = self.0.clone(); + Box::pin(async move { Ok(seat.cancel().await?) }) + } +} diff --git a/crates/tinyhivemind-acp/src/seat/turn.rs b/crates/tinyhivemind-acp/src/seat/turn.rs new file mode 100644 index 00000000..ffee0610 --- /dev/null +++ b/crates/tinyhivemind-acp/src/seat/turn.rs @@ -0,0 +1,221 @@ +//! One turn: a `session/prompt`, and what the agent sends until it answers. +//! +//! While the prompt runs the turn holds the connection's route. It reports +//! the agent's text and tool calls as [`Progress`], and answers each +//! `session/request_permission`: a call to the host's own MCP server is +//! allowed here, since the tool server judges hive tools itself; any other +//! goes to the seat's approver, and is refused if the approver does not +//! answer in time. Once the turn is cancelled, a permission request pending +//! or new is answered `cancelled`, as ACP requires. Requests for a file +//! system or a terminal, which this client never offered, are refused. +//! +//! The route is closed before the turn's last messages are read, and closed +//! again if the turn's future is dropped, answering whatever it still held, +//! so the agent never waits on a request nobody will answer. +use super::Live; +use crate::connection::{Connection, Incoming}; +use crate::error::{Error, Result}; +use crate::protocol::{self, Update}; +use serde_json::Value; +use std::collections::HashMap; +use std::time::Duration; +use tinyhivemind_hives::TurnDisposition; +use tinyhivemind_host::harness::{ + Event, Progress, SeatPlan, ToolApproval, ToolDecision, TurnUsage, +}; +use tokio::sync::{mpsc, watch}; + +/// A turn to run. +pub(super) struct Turn<'a> { + pub(super) live: &'a Live, + pub(super) seat: &'a str, + pub(super) server: &'a str, + pub(super) id: &'a str, + pub(super) session: &'a str, + pub(super) plan: &'a SeatPlan, + pub(super) approval: Duration, + /// Set once the turn is cancelled. + pub(super) cancelled: watch::Receiver, +} + +/// A turn's hold on the connection's route. Dropped, it closes the route and +/// answers every request still queued: a permission request `cancelled`, +/// anything else refused. +struct Held<'a> { + connection: &'a Connection, + incoming: mpsc::UnboundedReceiver, +} + +impl Drop for Held<'_> { + fn drop(&mut self) { + self.connection.unroute(); + while let Ok(message) = self.incoming.try_recv() { + if let Incoming::Request { id, method, .. } = message { + let answer = if method == "session/request_permission" { + Ok(protocol::cancelled()) + } else { + Err(format!("{method} came after its turn")) + }; + self.connection.answer_detached(&id, answer); + } + } + } +} + +/// How a turn ended. +#[derive(Debug)] +pub(super) struct Ended { + pub(super) reply: String, + pub(super) usage: Option, + pub(super) disposition: TurnDisposition, +} + +/// What a tool call was, as its `tool_call` update said. +struct Call { + title: String, + server: Option, + raw: Value, +} + +impl Turn<'_> { + /// Prompt with `text` and follow the turn until the prompt is answered. + pub(super) async fn run(self, text: &str) -> Result { + let connection = &self.live.connection; + let mut held = Held { + connection, + incoming: connection.route(), + }; + let prompt = connection.call("session/prompt", protocol::prompt(self.session, text)); + tokio::pin!(prompt); + let mut reply = String::new(); + let mut calls = HashMap::new(); + let answered = loop { + tokio::select! { + answered = &mut prompt => break answered, + Some(message) = held.incoming.recv() => { + self.handle(message, &mut reply, &mut calls).await; + } + } + }; + // Closed first, so nothing more arrives; what the agent sent before + // it answered still belongs to the turn. + connection.unroute(); + while let Ok(message) = held.incoming.try_recv() { + self.handle(message, &mut reply, &mut calls).await; + } + drop(held); + let result = answered?; + let reason = result["stopReason"] + .as_str() + .ok_or_else(|| Error::Broken("session/prompt answered without a stopReason".into()))?; + let disposition = + protocol::failure(reason).map_or(TurnDisposition::Completed, TurnDisposition::Failed); + Ok(Ended { + reply, + usage: protocol::usage(&result), + disposition, + }) + } + + fn report(&self, progress: Progress) { + let event = Event::Progress { + turn_id: self.id.to_owned(), + progress, + }; + self.plan.observer.event(self.seat, event); + } + + async fn handle( + &self, + message: Incoming, + reply: &mut String, + calls: &mut HashMap, + ) { + match message { + Incoming::Notification { method, params } => { + if method != "session/update" || params["sessionId"] != self.session { + return; + } + match protocol::update(¶ms["update"]) { + Update::Text(chunk) => { + reply.push_str(&chunk); + self.report(Progress::Text { delta: chunk }); + } + Update::ToolCall { id, title, server } => { + self.report(Progress::ToolCall { + call_id: id.clone(), + tool: title.clone(), + }); + let raw = params["update"]["rawInput"].clone(); + calls.insert(id, Call { title, server, raw }); + } + Update::ToolEnded { id, failed } => { + self.report(Progress::ToolResult { + call_id: id, + failed, + }); + } + Update::Other => {} + } + } + Incoming::Request { id, method, params } => { + let answer = if method == "session/request_permission" { + self.permission(¶ms, calls).await + } else { + let error = format!("{method} is not offered"); + let _ = self.live.connection.refuse(id, &error).await; + return; + }; + let _ = self.live.connection.respond(id, answer).await; + } + } + } + + /// The answer to a permission request: allowed for the host's own + /// server, otherwise the approver's. + async fn permission(&self, params: &Value, calls: &HashMap) -> Value { + let mut cancelled = self.cancelled.clone(); + if *cancelled.borrow() { + return protocol::cancelled(); + } + let options = ¶ms["options"]; + let tool_call = ¶ms["toolCall"]; + let call_id = tool_call["toolCallId"].as_str().unwrap_or_default(); + let known = calls.get(call_id); + let server = tool_call["rawInput"]["server"] + .as_str() + .or_else(|| known.and_then(|call| call.server.as_deref())); + if server == Some(self.server) { + return protocol::allow(options).map_or_else( + || protocol::refuse(options), + |option| protocol::selected(&option), + ); + } + let title = tool_call["title"] + .as_str() + .or_else(|| known.map(|call| call.title.as_str())) + .unwrap_or_default(); + let arguments = Some(&tool_call["rawInput"]) + .filter(|raw| !raw.is_null()) + .or_else(|| known.map(|call| &call.raw)) + .cloned() + .unwrap_or(Value::Null); + let request = ToolApproval { + seat: self.seat.to_owned(), + turn_id: self.id.to_owned(), + call_id: call_id.to_owned(), + tool: title.to_owned(), + arguments, + }; + let decide = tokio::time::timeout(self.approval, self.plan.approver.decide(request)); + let decided = tokio::select! { + decided = decide => decided, + // Cancelled, or the seat has let the turn go. + _ = cancelled.wait_for(|cancelled| *cancelled) => return protocol::cancelled(), + }; + match (decided, protocol::allow(options)) { + (Ok(ToolDecision::Allow), Some(option)) => protocol::selected(&option), + _ => protocol::refuse(options), + } + } +} diff --git a/crates/tinyhivemind-acp/tests/README.md b/crates/tinyhivemind-acp/tests/README.md new file mode 100644 index 00000000..4f7b0728 --- /dev/null +++ b/crates/tinyhivemind-acp/tests/README.md @@ -0,0 +1,6 @@ +# Tests + +| Path | Purpose | +| --- | --- | +| `hive.rs` | `live_*`: a Claude Code seat, a Codex seat, and a mixed hive of OpenHuman, Claude Code and Codex, each in a real hive with a real tool server; then the same three editing files only through the host's `write_file` tool, each in its own workspace: a retried write runs once, writes that climb out of the workspace or are absolute are refused, a supervised seat's writes go to the host's approver, and a read-only seat and a denied seat write nothing. Opted into by `THM_NODE`, `THM_ACP_CLAUDE`, `THM_ACP_CODEX`, `THM_CODEX` and `THM_OPENHUMAN_CORE`. | +| [`hive/`](hive/README.md) | The scripted model the hive tests play | diff --git a/crates/tinyhivemind-acp/tests/hive.rs b/crates/tinyhivemind-acp/tests/hive.rs new file mode 100644 index 00000000..7232e546 --- /dev/null +++ b/crates/tinyhivemind-acp/tests/hive.rs @@ -0,0 +1,536 @@ +//! `live_*`: ACP seats, alone and beside an `OpenHuman` seat, in a real hive. +//! +//! Each seat runs a pinned agent through its runner, is registered with a +//! real coordinator and reaches its hive tools through a real +//! `tinyhivemind-mcp` server, with its own bearer. Only the model is +//! scripted: `hive/model.rs` speaks the three model APIs, reads each +//! rendered turn and calls `hivemind_post`, the same call again (once, then +//! the host's `write_file`, for a seat that edits), then +//! `hivemind_complete`. +//! +//! Opt in with `THM_NODE` (a Node 22+ binary) and, per agent, +//! `THM_ACP_CLAUDE` (the `claude-agent-acp` script), `THM_ACP_CODEX` (the +//! `codex-acp` script) with `THM_CODEX` (its Codex binary, for the model +//! catalog), and `THM_OPENHUMAN_CORE` for the mixed hive. A test whose +//! agents are missing says so on stderr and passes. +#![cfg(target_os = "linux")] + +#[path = "hive/model.rs"] +mod model; + +use anyhow::{Context as _, Result, ensure}; +use model::{EDIT_TOOL, EDITS, HiveModel, Seen, edited}; +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; +use tinyhivemind_acp::agent::write_codex_catalog; +use tinyhivemind_acp::{AcpHarness, Agent}; +use tinyhivemind_exec::ExecContext; +use tinyhivemind_hives::{ + AgentRegistration, Coordinator, CoordinatorOptions, Destination, EpisodePhase, HiveInfo, + MemoryStorage, Message, SendMessage, +}; +use tinyhivemind_host::harness::{ + ApprovalFuture, Approver, Harness, SeatPlan, ToolApproval, ToolDecision, +}; +use tinyhivemind_lang::{ + Access, ExecTool, LoweredModel, LoweredSeat, LoweredSeatIntegration, Model, Provider, + ProviderKind, +}; +use tinyhivemind_mcp::{HiveToolServer, SeatTools, ServerOptions, Services}; + +/// The pinned versions, as each agent reports itself. +const CLAUDE_ACP: &str = "0.112.0"; +const CODEX_ACP: &str = "2.12.1"; +const OPENHUMAN: &str = "0.64.15"; +/// Long enough for every seat to start and finish its turns. +const SETTLE: Duration = Duration::from_secs(300); + +fn var(name: &str) -> Option { + std::env::var_os(name).map(PathBuf::from) +} + +/// One seat of the hive: its harness, its lowered seat and, when it may +/// edit, the access the host's edit tool runs under. +struct Member { + id: &'static str, + harness: Arc, + seat: LoweredSeat, + edit: Option, +} + +impl Member { + /// This seat, with the host's edit tool under `access`. + fn editing(mut self, access: Access) -> Self { + self.edit = Some(access); + self + } +} + +/// Writes `content` to `path` in the seat's workspace, refusing a path that +/// is absolute or climbs out of it, and logs each write it makes to +/// `writes.log` in the package root, one ` ` line per run. The +/// host runs it, so every harness edits the same way and the host's access +/// gate judges each call. +const WRITE_FILE: &str = r#"case "$1" in /*|..|../*|*/..|*/../*) echo "outside the workspace: $1" >&2; exit 2;; esac +printf '%s' "$2" > "$1" && printf '%s %s\n' "$THM_SEAT" "$1" >> "$THM_PACKAGE_ROOT/writes.log" && echo "wrote $1""#; + +/// What the host's approver tells a seat it denies. +const DENIED: &str = "this host denies seat refused"; + +/// The host's approver for supervised seats: it records every request and +/// allows all but seat `refused`'s. +#[derive(Default)] +struct Approvals { + asked: Mutex>, +} + +impl Approvals { + fn asked(&self) -> Vec { + self.asked + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } +} + +impl Approver for Approvals { + fn decide(&self, request: ToolApproval) -> ApprovalFuture { + let denied = request.seat == "refused"; + self.asked + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(request); + Box::pin(async move { + if denied { + ToolDecision::Deny { + reason: DENIED.into(), + } + } else { + ToolDecision::Allow + } + }) + } +} + +/// The host's edit tool. +fn write_file() -> Result { + let declaration = serde_json::json!({ + "id": EDIT_TOOL, + "description": "Write content to a file in your workspace.", + "command": ["sh", "-c", WRITE_FILE, EDIT_TOOL], + "args": { + "type": "object", + "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, + "required": ["path", "content"], + }, + "argv": ["{path}", "{content}"], + "stdin": "none", + "side_effects": "write", + "cwd": "workspace", + }); + Ok(serde_json::from_value(declaration)?) +} + +/// Seat `id`'s workspace, where its edit tool writes. +fn workspace(root: &Path, id: &str) -> PathBuf { + root.join("workspaces").join(id) +} + +/// Seat `id` on a `kind` provider at `endpoint`, with no credential. +fn seat(id: &str, kind: ProviderKind, endpoint: &str) -> LoweredSeat { + let provider = Provider { + id: "local".into(), + kind, + endpoint: Some(endpoint.into()), + credential: None, + }; + let model = Model { + id: "fast".into(), + provider: Some("local".into()), + name: "mock".into(), + ..Model::default() + }; + LoweredSeat { + id: id.into(), + label: id.into(), + template: "seat".into(), + config: serde_json::Value::Null, + prompt: format!("You are {id}. Report, then complete."), + memory: None, + integration: LoweredSeatIntegration { + model: Some(LoweredModel { + model, + provider: Some(provider), + }), + ..LoweredSeatIntegration::default() + }, + } +} + +fn claude(id: &'static str, port: u16) -> Option { + let agent = Agent::claude_code(var("THM_NODE")?, var("THM_ACP_CLAUDE")?, CLAUDE_ACP); + let endpoint = format!("http://127.0.0.1:{port}"); + Some(Member { + id, + harness: Arc::new(AcpHarness::new(agent)), + seat: seat(id, ProviderKind::Anthropic, &endpoint), + edit: None, + }) +} + +fn codex(id: &'static str, port: u16, root: &Path) -> Result> { + let (Some(node), Some(adapter), Some(binary)) = + (var("THM_NODE"), var("THM_ACP_CODEX"), var("THM_CODEX")) + else { + return Ok(None); + }; + let catalog = root.join(format!("{id}-catalog.json")); + write_codex_catalog(&binary, &catalog, "mock")?; + let agent = Agent::codex(node, adapter, CODEX_ACP, &catalog); + let endpoint = format!("http://127.0.0.1:{port}/v1"); + Ok(Some(Member { + id, + harness: Arc::new(AcpHarness::new(agent)), + seat: seat(id, ProviderKind::Openai, &endpoint), + edit: None, + })) +} + +fn openhuman(port: u16) -> Option { + use tinyhivemind_openhuman_process::{OpenHumanHarness, Options, Program}; + let options = Options { + ready: Duration::from_secs(60), + ..Options::default() + }; + let harness = OpenHumanHarness::new(Program::new(var("THM_OPENHUMAN_CORE")?, OPENHUMAN)) + .with_options(options); + let endpoint = format!("http://127.0.0.1:{port}/v1"); + Some(Member { + id: "openhuman", + harness: Arc::new(harness), + seat: seat("openhuman", ProviderKind::Openai, &endpoint), + edit: None, + }) +} + +/// What seat `id` must have done: posted once under its own name, seen its +/// turn and the hive tools on every model call, and, unless it edits (whose +/// retry is its write's), been answered the first result for its post's +/// retry. +fn seat_took_its_turn(id: &str, edits: bool, transcript: &[Message], seen: &[Seen]) -> Result<()> { + let posts = transcript + .iter() + .filter(|message| message.sender == id && message.body == format!("{id} reporting")) + .count(); + ensure!(posts == 1, "{id} posted {posts} times: {transcript:#?}"); + let turns: Vec<_> = seen.iter().filter(|request| request.agent == id).collect(); + ensure!(!turns.is_empty(), "the model never saw a turn of {id}"); + for request in &turns { + ensure!( + !request.turn.is_empty(), + "a turn of {id} reached the model without its id" + ); + let offered = |name: &str| request.offered.iter().any(|tool| tool.contains(name)); + ensure!( + offered("hivemind_post") && offered("hivemind_complete"), + "{id} was not offered the hive tools: {:?}", + request.offered + ); + } + if edits { + return Ok(()); + } + let retried = turns + .iter() + .find(|request| request.results.len() == 2) + .with_context(|| format!("{id} never saw its retried post answered: {seen:#?}"))?; + ensure!( + retried.results[0] == retried.results[1], + "{id}'s retry was not answered with the first result: {:?}", + retried.results + ); + Ok(()) +} + +/// Run one episode with every member as a starter, and check each seat and +/// the episode; then stop every seat. +async fn hive(members: Vec, model: &HiveModel, root: &Path) -> Result<()> { + hive_with(members, model, root, None).await +} + +/// [`hive`], with `approver` asked about supervised seats' edits. +async fn hive_with( + members: Vec, + model: &HiveModel, + root: &Path, + approver: Option>, +) -> Result<()> { + let coordinator = Coordinator::new( + "runtime".into(), + Arc::new(MemoryStorage::new()), + CoordinatorOptions::default(), + ) + .await?; + let mut services = Services::new(coordinator.clone()); + if let Some(approver) = approver { + services = services.with_approver(approver); + } + let server = HiveToolServer::start(services, ServerOptions::default()).await?; + let ids: Vec = members.iter().map(|member| member.id.to_owned()).collect(); + for member in &members { + let mut tools = SeatTools::new(member.id); + if let Some(access) = member.edit { + let workspace = workspace(root, member.id); + std::fs::create_dir_all(&workspace)?; + let context = ExecContext { + package_root: root.to_path_buf(), + workspace: Some(workspace), + hive: "work".into(), + seat: member.id.into(), + ..ExecContext::default() + }; + tools = tools + .with_programs(vec![write_file()?]) + .with_context(context) + .with_access(access); + } + let tools = server.serve_seat(tools)?; + let plan = SeatPlan::new(member.seat.clone(), root.join(member.id)); + let runner = member + .harness + .start(plan, tools) + .await + .with_context(|| format!("starting {}", member.id))?; + coordinator + .register_agent(AgentRegistration { + agent_id: member.id.into(), + runtime_id: coordinator.runtime_id().into(), + runner, + }) + .await?; + } + coordinator + .create_hive(HiveInfo { + hive_id: "work".into(), + name: "Work".into(), + description: None, + members: ids.clone(), + }) + .await?; + coordinator + .send_as_host(SendMessage { + message_id: "task".into(), + sender: String::new(), + destination: Destination::Hive("work".into()), + body: "Report, then complete.".into(), + thread: None, + only_for: Vec::new(), + starters: ids.clone(), + }) + .await?; + tokio::time::timeout(SETTLE, coordinator.run_until_idle()) + .await + .context("the hive did not settle in time")??; + let transcript = coordinator.read_transcript(None)?; + let seen = model.seen(); + for member in &members { + seat_took_its_turn(member.id, member.edit.is_some(), &transcript, &seen)?; + } + let episodes = coordinator.episodes()?; + ensure!( + episodes.len() == 1 && episodes[0].phase == EpisodePhase::Settled, + "the episode did not settle: {episodes:#?}" + ); + for member in &members { + member.harness.stop(member.id).await?; + } + server.shutdown().await?; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn live_a_claude_code_seat_posts_once_and_settles() -> Result<()> { + let model = HiveModel::start().await?; + let Some(member) = claude("claude", model.port) else { + eprintln!("skipped: set THM_NODE and THM_ACP_CLAUDE"); + return Ok(()); + }; + let root = tempfile::tempdir()?; + hive(vec![member], &model, root.path()).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn live_a_codex_seat_posts_once_and_settles() -> Result<()> { + let model = HiveModel::start().await?; + let root = tempfile::tempdir()?; + let Some(member) = codex("codex", model.port, root.path())? else { + eprintln!("skipped: set THM_NODE, THM_ACP_CODEX and THM_CODEX"); + return Ok(()); + }; + hive(vec![member], &model, root.path()).await +} + +/// One episode, three harnesses: `OpenHuman` over its own API, Claude Code +/// and Codex over ACP, each seat posting once as itself. +#[tokio::test(flavor = "multi_thread")] +async fn live_a_mixed_hive_of_openhuman_claude_code_and_codex_settles() -> Result<()> { + let model = HiveModel::start().await?; + let root = tempfile::tempdir()?; + let (Some(openhuman), Some(claude), Some(codex)) = ( + openhuman(model.port), + claude("claude", model.port), + codex("codex", model.port, root.path())?, + ) else { + eprintln!( + "skipped: set THM_OPENHUMAN_CORE, THM_NODE, THM_ACP_CLAUDE, THM_ACP_CODEX and THM_CODEX" + ); + return Ok(()); + }; + hive(vec![openhuman, claude, codex], &model, root.path()).await?; + let apis: std::collections::BTreeSet = model + .seen() + .iter() + .map(|seen| format!("{:?}", seen.api)) + .collect(); + ensure!( + apis.len() == 3, + "the hive spoke {apis:?}, not all three model APIs" + ); + Ok(()) +} + +/// The results of seat `id`'s edits, in [`EDITS`] order: those its last +/// model call carried. +fn edit_results(model: &HiveModel, id: &str) -> Result> { + let last = model + .seen() + .into_iter() + .filter(|seen| seen.agent == id) + .max_by_key(|seen| seen.results.len()) + .with_context(|| format!("the model never saw a turn of {id}"))?; + let edits = last.results.get(1..=EDITS.len()).map(<[String]>::to_vec); + edits.with_context(|| format!("{id} did not make every edit: {:?}", last.results)) +} + +/// Every harness edits only through the host's tool, and the host judges +/// each edit. An autonomous `OpenHuman` seat and supervised Claude Code and +/// Codex seats, which the host's approver allows, each write their own file; +/// a read-only Claude Code seat and a supervised Codex seat the approver +/// denies write nothing. Every editing seat also retries its write, which +/// the host answers with the first result without running it again, and +/// tries a path that climbs out of its workspace and an absolute one, which +/// the tool refuses. +#[tokio::test(flavor = "multi_thread")] +async fn live_seats_on_every_harness_edit_only_through_the_host() -> Result<()> { + let root = tempfile::tempdir()?; + let root = root.path(); + let outside = root.join("outside"); + std::fs::create_dir_all(&outside)?; + let model = HiveModel::start_with(&outside.to_string_lossy()).await?; + let (Some(openhuman), Some(claude), Some(codex), Some(reader), Some(refused)) = ( + openhuman(model.port), + claude("claude", model.port), + codex("codex", model.port, root)?, + claude("reader", model.port), + codex("refused", model.port, root)?, + ) else { + eprintln!( + "skipped: set THM_OPENHUMAN_CORE, THM_NODE, THM_ACP_CLAUDE, THM_ACP_CODEX and THM_CODEX" + ); + return Ok(()); + }; + let members = vec![ + openhuman.editing(Access::Autonomous), + claude.editing(Access::Supervised), + codex.editing(Access::Supervised), + reader.editing(Access::ReadOnly), + refused.editing(Access::Supervised), + ]; + let approvals = Arc::new(Approvals::default()); + hive_with(members, &model, root, Some(approvals.clone())).await?; + let log = std::fs::read_to_string(root.join("writes.log")).unwrap_or_default(); + let runs = |id: &str| { + log.lines() + .filter(|line| line.split(' ').next() == Some(id)) + .count() + }; + + for id in ["openhuman", "claude", "codex"] { + let file = workspace(root, id).join(format!("{id}.md")); + let written = std::fs::read_to_string(&file) + .with_context(|| format!("{id} did not write {}", file.display()))?; + ensure!(written == edited(id), "{id} wrote {written:?}"); + let entries = std::fs::read_dir(workspace(root, id))?.count(); + ensure!(entries == 1, "{id}'s workspace holds {entries} entries"); + // The host ran the program once, for the edit, and nothing else. + ensure!( + runs(id) == 1, + "the host wrote {} times for {id}: {log:?}", + runs(id) + ); + let results = edit_results(&model, id)?; + ensure!( + results[0].contains(&format!("wrote {id}.md")), + "{id}'s edit did not come back from the host's tool: {:?}", + results[0] + ); + ensure!( + results[1] == results[0], + "{id}'s retry was not answered with the first result: {results:?}" + ); + for (edit, result) in EDITS.iter().zip(&results).skip(2) { + ensure!( + result.contains("outside the workspace"), + "{id}'s {edit} write was not refused: {result:?}" + ); + } + } + + for (id, reason) in [("reader", "read_only"), ("refused", DENIED)] { + let entries = std::fs::read_dir(workspace(root, id))?.count(); + ensure!(entries == 0, "{id} wrote {entries} entries"); + ensure!(runs(id) == 0, "the host ran {id}'s write: {log:?}"); + let results = edit_results(&model, id)?; + ensure!( + results.iter().all(|result| result.contains(reason)), + "{id} was not told every write was refused ({reason}): {results:?}" + ); + } + + // Nothing landed outside a workspace: no escape file beside them, and + // nothing in the directory the absolute writes aimed at. + let beside: BTreeSet = std::fs::read_dir(root.join("workspaces"))? + .map(|entry| Ok(entry?.file_name().to_string_lossy().into_owned())) + .collect::>()?; + let seats: BTreeSet = ["openhuman", "claude", "codex", "reader", "refused"] + .map(str::to_owned) + .into(); + ensure!(beside == seats, "the workspaces directory holds {beside:?}"); + let outside_entries = std::fs::read_dir(&outside)?.count(); + ensure!( + outside_entries == 0, + "{outside_entries} files landed outside" + ); + + // The approver judged exactly the supervised seats, and the edit's + // retry was answered from the host's record without asking it again. + let asked = approvals.asked(); + let judged: BTreeSet<&str> = asked.iter().map(|request| request.seat.as_str()).collect(); + ensure!( + judged == BTreeSet::from(["claude", "codex", "refused"]), + "the approver judged {judged:?}" + ); + for id in ["claude", "codex"] { + let edits = asked + .iter() + .filter(|request| request.seat == id && request.call_id == "edit") + .count(); + ensure!( + edits == 1, + "the approver was asked {edits} times about {id}'s edit" + ); + } + Ok(()) +} diff --git a/crates/tinyhivemind-acp/tests/hive/README.md b/crates/tinyhivemind-acp/tests/hive/README.md new file mode 100644 index 00000000..20b7e445 --- /dev/null +++ b/crates/tinyhivemind-acp/tests/hive/README.md @@ -0,0 +1,5 @@ +# Hive + +| File | Purpose | +| --- | --- | +| `model.rs` | A model in Chat Completions, Responses and Anthropic Messages that reads each rendered turn and calls `hivemind_post` and the same call again, then `hivemind_complete`; a seat offered `write_file` posts once and writes, retries, and tries two paths outside its workspace before it completes | diff --git a/crates/tinyhivemind-acp/tests/hive/model.rs b/crates/tinyhivemind-acp/tests/hive/model.rs new file mode 100644 index 00000000..8ab30257 --- /dev/null +++ b/crates/tinyhivemind-acp/tests/hive/model.rs @@ -0,0 +1,498 @@ +//! A model on loopback that acts as a hive seat would, in the three APIs the +//! harnesses speak: Chat Completions (`OpenHuman`), Responses (Codex) and +//! Anthropic Messages (Claude Code). +//! +//! A request carries a seat's turn when one of its user texts is the +//! rendered `TurnRequest`. The model reads the turn and episode from it and, +//! counting the tool results after it, calls `hivemind_post` with call +//! `post` and the same call again, then `hivemind_complete` with call +//! `done`, then answers. A seat offered the host's `write_file` posts once +//! and makes the edits [`EDITS`] lists before it completes, so that its turn +//! stays within `OpenHuman`'s cap of eight model calls. Any other request, or +//! one that offers no tools (a harness's own side call), gets a plain answer +//! and changes nothing. +#[expect( + dead_code, + reason = "shared with the OpenHuman runner's fakes; this model reads bodies only" +)] +#[path = "../../../tinyhivemind-openhuman-process/tests/support/http.rs"] +mod http; + +use http::{Reply, Request, serve}; +use serde_json::{Value, json}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use tokio::net::TcpListener; +use tokio::sync::mpsc; + +/// The phrase that opens a rendered turn. +const TURN: &str = "Incoming attributed Hivemind context"; + +/// The host's edit tool, as the hive test declares it. +pub(crate) const EDIT_TOOL: &str = "write_file"; + +/// What an editing seat writes, in order, after its one post: its own file +/// with call `edit`, the same call again, a path climbing out of its +/// workspace, and an absolute path into the model's `outside` directory. +/// Their results are a turn's results from index 1. +pub(crate) const EDITS: [&str; 4] = ["edit", "retry", "escape", "absolute"]; + +/// What seat `agent` writes to its file. +pub(crate) fn edited(agent: &str) -> String { + format!("{agent} was here\n") +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// The API a request spoke. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Api { + Chat, + Responses, + Messages, +} + +/// What one request of a turn showed. +#[derive(Clone, Debug)] +pub(crate) struct Seen { + pub(crate) api: Api, + pub(crate) agent: String, + pub(crate) turn: String, + pub(crate) offered: Vec, + pub(crate) results: Vec, +} + +/// The model, serving until dropped. +pub(crate) struct HiveModel { + pub(crate) port: u16, + seen: Arc>>, + task: tokio::task::JoinHandle<()>, +} + +impl HiveModel { + pub(crate) async fn start() -> std::io::Result { + Self::start_with("/nonexistent").await + } + + /// The model, whose editing seats aim their absolute write at `outside`. + pub(crate) async fn start_with(outside: &str) -> std::io::Result { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let port = listener.local_addr()?.port(); + let seen = Arc::new(Mutex::new(Vec::new())); + let serving = seen.clone(); + let aim = outside.to_owned(); + let task = tokio::spawn(serve(listener, move |request| { + let seen = serving.clone(); + let outside = aim.clone(); + async move { answer(&seen, &outside, &request) } + })); + Ok(Self { port, seen, task }) + } + + /// Every request that carried a turn. + pub(crate) fn seen(&self) -> Vec { + lock(&self.seen).clone() + } +} + +impl Drop for HiveModel { + fn drop(&mut self) { + self.task.abort(); + } +} + +/// The text of a `content`: a string, or the text of its parts. +fn text(content: &Value) -> String { + match content { + Value::String(text) => text.clone(), + Value::Array(parts) => parts + .iter() + .map(|part| text(&part["text"]) + &text(&part["content"])) + .collect(), + _ => String::new(), + } +} + +/// A tool result without the timing Codex puts before it +/// (`Wall time: … seconds\nOutput:…`), which differs between two runs of +/// the same call. +fn tool_output(text: &str) -> String { + match (text.starts_with("Wall time:"), text.split_once("Output:")) { + (true, Some((_, output))) => output.to_owned(), + _ => text.to_owned(), + } +} + +/// The rendered turn in `text`: the JSON after the phrase. +fn turn_of(text: &str) -> Option { + let at = text.find(TURN)?; + let start = at + text[at..].find('{')?; + let mut stream = serde_json::Deserializer::from_str(&text[start..]).into_iter::(); + stream.next()?.ok() +} + +/// One request, read alike in each API: the turn, the tools offered (with a +/// namespace, for Responses) and the tool results after the turn. +struct Read { + turn: Option, + offered: Vec<(Option, String)>, + results: Vec, +} + +fn read(api: Api, body: &Value) -> Read { + let items: Vec = match api { + Api::Responses => match &body["input"] { + Value::Array(items) => items.clone(), + other => vec![json!({"role": "user", "content": other})], + }, + Api::Chat | Api::Messages => body["messages"].as_array().cloned().unwrap_or_default(), + }; + let mut turn = None; + let mut at = 0; + for (index, item) in items.iter().enumerate() { + if item["role"] == "user" + && let Some(found) = turn_of(&text(&item["content"])) + { + turn = Some(found); + at = index; + } + } + let after = items.get(at + 1..).unwrap_or_default(); + let results = match api { + Api::Chat => after + .iter() + .filter(|item| item["role"] == "tool") + .map(|item| text(&item["content"])) + .collect(), + Api::Responses => after + .iter() + .filter(|item| item["type"] == "function_call_output") + .map(|item| tool_output(&text(&item["output"]))) + .collect(), + Api::Messages => after + .iter() + .flat_map(|item| item["content"].as_array().cloned().unwrap_or_default()) + .filter(|block| block["type"] == "tool_result") + .map(|block| text(&block["content"])) + .collect(), + }; + let offered = body["tools"] + .as_array() + .into_iter() + .flatten() + .flat_map(|tool| match (tool["type"].as_str(), api) { + (Some("namespace"), _) => tool["tools"] + .as_array() + .into_iter() + .flatten() + .filter_map(|inner| inner["name"].as_str()) + .map(|name| (tool["name"].as_str().map(str::to_owned), name.to_owned())) + .collect::>(), + (_, Api::Chat) => tool["function"]["name"] + .as_str() + .map(|name| (None, name.to_owned())) + .into_iter() + .collect(), + _ => tool["name"] + .as_str() + .map(|name| (None, name.to_owned())) + .into_iter() + .collect(), + }) + .collect(); + Read { + turn: turn.filter(|turn| turn["turn_id"].is_string()), + offered, + results, + } +} + +fn answer(seen: &Arc>>, outside: &str, request: &Request) -> Reply { + let path = request.path.as_str(); + if request.method == "GET" && path.ends_with("/models") { + return Reply::Json( + 200, + json!({"object": "list", "data": [{"id": "mock", "object": "model"}]}), + ); + } + if path.contains("/count_tokens") { + return Reply::Json(200, json!({"input_tokens": 100})); + } + let api = if path.ends_with("/chat/completions") { + Api::Chat + } else if path.ends_with("/responses") { + Api::Responses + } else if path.contains("/v1/messages") { + Api::Messages + } else { + return Reply::Json(404, json!({})); + }; + let body = request.json(); + let stream = body["stream"] == true; + let read = read(api, &body); + // A harness's side call (a session title, say) offers no tools: it gets a + // plain answer and is not part of the turn. + let Some(turn) = read.turn.filter(|_| !read.offered.is_empty()) else { + return say(api, "ok", stream); + }; + let agent = turn["agent_id"].as_str().unwrap_or_default().to_owned(); + let turn_id = turn["turn_id"].as_str().unwrap_or_default().to_owned(); + let episode = turn["episode"]["episode_id"].as_str().map(str::to_owned); + lock(seen).push(Seen { + api, + agent: agent.clone(), + turn: turn_id.clone(), + offered: read.offered.iter().map(|(_, name)| name.clone()).collect(), + results: read.results.clone(), + }); + let find = |name: &str| { + read.offered + .iter() + .find(|(_, tool)| tool.contains(name)) + .cloned() + }; + // A seat offered the edit tool posts once, then makes the edits `EDITS` + // lists before it completes. + let edit = find(EDIT_TOOL); + let posts = if edit.is_some() { 1 } else { 2 }; + let complete_at = posts + edit.as_ref().map_or(0, |_| EDITS.len()); + let step = match (episode, read.results.len()) { + (Some(episode), at) if at < posts => find("hivemind_post").map(|tool| { + let body = format!("{agent} reporting"); + ( + tool, + json!({"episode_id": episode, "body": body, "turn": turn_id, "call": "post"}), + ) + }), + (Some(_), at) if at >= posts && at < complete_at => edit.map(|tool| { + let (path, call) = match EDITS[at - posts] { + "escape" => (format!("../{agent}-escape.md"), "escape"), + "absolute" => (format!("{outside}/{agent}.md"), "absolute"), + // The retry repeats the edit's call exactly. + _ => (format!("{agent}.md"), "edit"), + }; + let content = edited(&agent); + ( + tool, + json!({"path": path, "content": content, "turn": turn_id, "call": call}), + ) + }), + (Some(episode), at) if at == complete_at => find("hivemind_complete").map(|tool| { + let body = format!("{agent} done"); + ( + tool, + json!({"episode_id": episode, "body": body, "turn": turn_id, "call": "done"}), + ) + }), + _ => None, + }; + match step { + Some(((namespace, name), arguments)) => { + let id = format!("call_{}_{}", agent, read.results.len()); + call(api, &id, namespace.as_deref(), &name, &arguments, stream) + } + None => say(api, &format!("{agent} finished"), stream), + } +} + +fn sse(events: Vec<(Option<&str>, Value)>, done: bool) -> Reply { + let (sender, receiver) = mpsc::channel(32); + let mut frames: Vec = events + .into_iter() + .map(|(event, data)| match event { + Some(event) => format!("event: {event}\ndata: {data}\n\n"), + None => format!("data: {data}\n\n"), + }) + .collect(); + if done { + frames.push("data: [DONE]\n\n".to_owned()); + } + tokio::spawn(async move { + for frame in frames { + let _ = sender.send(frame).await; + } + }); + Reply::Stream(receiver) +} + +/// A tool call, in `api`. +fn call( + api: Api, + id: &str, + namespace: Option<&str>, + name: &str, + arguments: &Value, + stream: bool, +) -> Reply { + let arguments = arguments.to_string(); + match api { + Api::Chat => { + let calls = json!([{"index": 0, "id": id, "type": "function", "function": {"name": name, "arguments": arguments}}]); + let usage = json!({"prompt_tokens": 100, "completion_tokens": 7, "total_tokens": 107}); + if !stream { + return Reply::Json( + 200, + json!({"id": "c", "object": "chat.completion", "created": 1, "model": "mock", + "choices": [{"index": 0, "finish_reason": "tool_calls", "message": {"role": "assistant", "content": null, "tool_calls": calls}}], "usage": usage}), + ); + } + let chunk = |choices: Value, usage: Option| { + let mut chunk = json!({"id": "c", "object": "chat.completion.chunk", "created": 1, "model": "mock", "choices": choices}); + if let Some(usage) = usage { + chunk["usage"] = usage; + } + (None, chunk) + }; + sse( + vec![ + chunk( + json!([{"index": 0, "delta": {"role": "assistant", "tool_calls": calls}, "finish_reason": null}]), + None, + ), + chunk( + json!([{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]), + None, + ), + chunk(json!([]), Some(usage)), + ], + true, + ) + } + Api::Responses => { + let mut item = json!({"type": "function_call", "id": format!("fc_{id}"), "call_id": id, "name": name, "arguments": arguments, "status": "completed"}); + if let Some(namespace) = namespace { + item["namespace"] = namespace.into(); + } + responses(&item, stream) + } + Api::Messages => { + let input: Value = serde_json::from_str(&arguments).unwrap_or(Value::Null); + let block = json!({"type": "tool_use", "id": id, "name": name, "input": input}); + messages(&block, "tool_use", stream) + } + } +} + +/// A plain answer, in `api`. +fn say(api: Api, text: &str, stream: bool) -> Reply { + match api { + Api::Chat => { + let usage = json!({"prompt_tokens": 100, "completion_tokens": 7, "total_tokens": 107}); + if !stream { + return Reply::Json( + 200, + json!({"id": "c", "object": "chat.completion", "created": 1, "model": "mock", + "choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": text}}], "usage": usage}), + ); + } + let base = json!({"id": "c", "object": "chat.completion.chunk", "created": 1, "model": "mock"}); + let with = |extra: Value| { + let mut chunk = base.clone(); + if let (Some(chunk), Some(extra)) = (chunk.as_object_mut(), extra.as_object()) { + chunk.extend(extra.clone()); + } + (None, chunk) + }; + sse( + vec![ + with( + json!({"choices": [{"index": 0, "delta": {"role": "assistant", "content": text}, "finish_reason": null}]}), + ), + with(json!({"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]})), + with(json!({"choices": [], "usage": usage})), + ], + true, + ) + } + Api::Responses => { + let item = json!({"type": "message", "id": "msg_1", "role": "assistant", "status": "completed", + "content": [{"type": "output_text", "text": text, "annotations": []}]}); + responses(&item, stream) + } + Api::Messages => messages(&json!({"type": "text", "text": text}), "end_turn", stream), + } +} + +fn responses(item: &Value, stream: bool) -> Reply { + let usage = json!({"input_tokens": 100, "input_tokens_details": {"cached_tokens": 10}, "output_tokens": 7, + "output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 107}); + let response = json!({"id": "resp_1", "object": "response", "status": "completed", "model": "mock", "output": [item], "usage": usage}); + if !stream { + return Reply::Json(200, response); + } + let mut created = response.clone(); + created["status"] = "in_progress".into(); + created["output"] = json!([]); + let mut added = item.clone(); + added["status"] = "in_progress".into(); + let mut events = vec![ + ( + Some("response.created"), + json!({"type": "response.created", "response": created}), + ), + ( + Some("response.output_item.added"), + json!({"type": "response.output_item.added", "output_index": 0, "item": added}), + ), + ]; + if item["type"] == "message" { + let delta = item["content"][0]["text"].clone(); + events.push((Some("response.output_text.delta"), json!({"type": "response.output_text.delta", "item_id": item["id"], "output_index": 0, "content_index": 0, "delta": delta}))); + } + events.push(( + Some("response.output_item.done"), + json!({"type": "response.output_item.done", "output_index": 0, "item": item}), + )); + events.push(( + Some("response.completed"), + json!({"type": "response.completed", "response": response}), + )); + sse(events, false) +} + +fn messages(block: &Value, stop: &str, stream: bool) -> Reply { + let usage = json!({"input_tokens": 100, "output_tokens": 7, "cache_read_input_tokens": 10, "cache_creation_input_tokens": 0}); + let message = json!({"id": "msg_1", "type": "message", "role": "assistant", "model": "mock", "content": [block], + "stop_reason": stop, "stop_sequence": null, "usage": usage}); + if !stream { + return Reply::Json(200, message); + } + let mut start = message.clone(); + start["content"] = json!([]); + start["stop_reason"] = Value::Null; + let (opened, delta) = if block["type"] == "tool_use" { + let mut opened = block.clone(); + opened["input"] = json!({}); + ( + opened, + json!({"type": "input_json_delta", "partial_json": block["input"].to_string()}), + ) + } else { + ( + json!({"type": "text", "text": ""}), + json!({"type": "text_delta", "text": block["text"]}), + ) + }; + let event = |kind: &'static str, mut data: Value| { + data["type"] = kind.into(); + (Some(kind), data) + }; + sse( + vec![ + event("message_start", json!({"message": start})), + event( + "content_block_start", + json!({"index": 0, "content_block": opened}), + ), + event("content_block_delta", json!({"index": 0, "delta": delta})), + event("content_block_stop", json!({"index": 0})), + event( + "message_delta", + json!({"delta": {"stop_reason": stop, "stop_sequence": null}, "usage": {"output_tokens": 7}}), + ), + event("message_stop", json!({})), + ], + false, + ) +} diff --git a/crates/tinyhivemind-lang/src/harness/capability.rs b/crates/tinyhivemind-lang/src/harness/capability.rs index 128c1316..d0760e22 100644 --- a/crates/tinyhivemind-lang/src/harness/capability.rs +++ b/crates/tinyhivemind-lang/src/harness/capability.rs @@ -22,8 +22,10 @@ pub enum Capability { OpenaiDefaultEndpoint, /// Provider `openrouter`. Openrouter, - /// Provider `anthropic`. + /// Provider `anthropic` without an `endpoint`. Anthropic, + /// Provider `anthropic` with an explicit `endpoint` and no `credential`. + AnthropicEndpoint, /// Provider `inherit`, or no provider at all: a child process has none /// to inherit. InheritedProvider, @@ -128,13 +130,16 @@ pub enum Unlock { Spec, } -/// The model API a kind speaks to an `openai` provider's endpoint. +/// The model API a kind speaks to its provider's endpoint: an `openai` +/// provider's for every kind but `claude-code`, an `anthropic` one's for it. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum ModelApi { /// `POST /chat/completions`. ChatCompletions, /// `POST /responses`. Responses, + /// `POST /v1/messages`, Anthropic's. + Messages, } impl Support { @@ -147,12 +152,13 @@ impl Support { impl Capability { /// Every capability, in the order of the spec's table. - pub const ALL: [Self; 41] = [ + pub const ALL: [Self; 42] = [ Self::Essentials, Self::OpenaiEndpoint, Self::OpenaiDefaultEndpoint, Self::Openrouter, Self::Anthropic, + Self::AnthropicEndpoint, Self::InheritedProvider, Self::ProviderCredential, Self::ServedToolPolicy, @@ -191,17 +197,21 @@ impl Capability { Self::Undecided, ]; - /// The row: support for `openhuman`, `openclaw` and `codex`, in that - /// order ([`HarnessKind::ALL`]). - const fn row(self) -> [Support; 3] { + /// The row: support for `openhuman`, `openclaw`, `codex` and + /// `claude-code`, in that order ([`HarnessKind::ALL`]). + const fn row(self) -> [Support; 4] { use Support::{Harness as H, Host}; const T: Support = Support::Rejected(Unlock::Conformance); const R: Support = Support::Rejected(Unlock::Release); const D: Support = Support::Rejected(Unlock::Spec); match self { - Self::Essentials | Self::OpenaiEndpoint | Self::NoSandbox => [H, H, H], + Self::Essentials | Self::NoSandbox => [H, H, H, H], + // Claude Code speaks only Anthropic's Messages API. + Self::OpenaiEndpoint => [H, H, H, D], + // And the other kinds speak no Anthropic API. + Self::AnthropicEndpoint => [D, D, D, H], Self::ServedToolPolicy | Self::Autonomy | Self::McpServers | Self::Workflows => { - [Host, Host, Host] + [Host, Host, Host, Host] } // The spike ran one provider shape per kind; every other one // waits for a conformance test, `credential` for one whose @@ -209,7 +219,7 @@ impl Capability { Self::OpenaiDefaultEndpoint | Self::Openrouter | Self::Anthropic - | Self::ProviderCredential => [T, T, T], + | Self::ProviderCredential => [T, T, T, T], // No fallback: a process harness never uses its own default. Self::InheritedProvider // Executable tools run from the host's MCP server, where nothing @@ -242,11 +252,11 @@ impl Capability { | Self::MaxAgents | Self::SqliteSessions | Self::InProcessMemory - | Self::Undecided => [D, D, D], - Self::BuiltinToolRules => [R, D, D], + | Self::Undecided => [D, D, D, D], + Self::BuiltinToolRules => [R, D, D, D], // OpenHuman honours a limit up to its fixed cap. - Self::IterationLimit => [H, D, D], - Self::Subagents | Self::DefinitionBase | Self::Jev | Self::SessionTuning => [T, D, D], + Self::IterationLimit => [H, D, D, D], + Self::Subagents | Self::DefinitionBase | Self::Jev | Self::SessionTuning => [T, D, D, D], } } } @@ -260,10 +270,11 @@ impl HarnessKind { Self::OpenHuman => row[0], Self::OpenClaw => row[1], Self::Codex => row[2], + Self::ClaudeCode => row[3], } } - /// The API this kind speaks to an `openai` provider. The language cannot + /// The API this kind speaks to its provider. The language cannot /// tell which one an endpoint serves, so `check` cannot see a mismatch; /// the turn fails instead. #[must_use] @@ -271,6 +282,7 @@ impl HarnessKind { match self { Self::OpenHuman | Self::OpenClaw => ModelApi::ChatCompletions, Self::Codex => ModelApi::Responses, + Self::ClaudeCode => ModelApi::Messages, } } @@ -282,7 +294,7 @@ impl HarnessKind { pub const fn iteration_cap(self) -> Option { match self { Self::OpenHuman => Some(8), - Self::OpenClaw | Self::Codex => None, + Self::OpenClaw | Self::Codex | Self::ClaudeCode => None, } } } @@ -294,7 +306,8 @@ impl fmt::Display for Capability { Self::OpenaiEndpoint => "provider openai with an endpoint and no credential", Self::OpenaiDefaultEndpoint => "provider openai without an endpoint", Self::Openrouter => "provider openrouter", - Self::Anthropic => "provider anthropic", + Self::Anthropic => "provider anthropic without an endpoint", + Self::AnthropicEndpoint => "provider anthropic with an endpoint and no credential", Self::InheritedProvider => "an inherited provider, or none", Self::ProviderCredential => "a provider credential", Self::ServedToolPolicy => "hooks and permissions on hive and executable tools", diff --git a/crates/tinyhivemind-lang/src/harness/mod.rs b/crates/tinyhivemind-lang/src/harness/mod.rs index 8c278303..627388b4 100644 --- a/crates/tinyhivemind-lang/src/harness/mod.rs +++ b/crates/tinyhivemind-lang/src/harness/mod.rs @@ -21,11 +21,19 @@ pub enum HarnessKind { OpenClaw, /// `codex`. Codex, + /// `claude-code`. + #[serde(rename = "claude-code")] + ClaudeCode, } impl HarnessKind { /// Every kind, in the order the capability table lists them. - pub const ALL: [Self; 3] = [Self::OpenHuman, Self::OpenClaw, Self::Codex]; + pub const ALL: [Self; 4] = [ + Self::OpenHuman, + Self::OpenClaw, + Self::Codex, + Self::ClaudeCode, + ]; /// How instances of this kind are shared when a harness entry does not /// say: one per deployment for `openclaw`, whose instance costs @@ -34,7 +42,7 @@ impl HarnessKind { pub const fn default_isolation(self) -> Isolation { match self { Self::OpenClaw => Isolation::Deployment, - Self::OpenHuman | Self::Codex => Isolation::Seat, + Self::OpenHuman | Self::Codex | Self::ClaudeCode => Isolation::Seat, } } } @@ -45,6 +53,7 @@ impl fmt::Display for HarnessKind { Self::OpenHuman => "openhuman", Self::OpenClaw => "openclaw", Self::Codex => "codex", + Self::ClaudeCode => "claude-code", }) } } diff --git a/crates/tinyhivemind-lang/src/harness/test.rs b/crates/tinyhivemind-lang/src/harness/test.rs index 59bfbd87..b2159204 100644 --- a/crates/tinyhivemind-lang/src/harness/test.rs +++ b/crates/tinyhivemind-lang/src/harness/test.rs @@ -11,12 +11,20 @@ fn each_kind_has_the_name_a_package_uses() -> Result<(), serde_json::Error> { (HarnessKind::OpenHuman, "openhuman"), (HarnessKind::OpenClaw, "openclaw"), (HarnessKind::Codex, "codex"), + (HarnessKind::ClaudeCode, "claude-code"), ] { assert_eq!(serde_json::to_value(kind)?, json!(name)); assert_eq!(serde_json::from_value::(json!(name))?, kind); assert_eq!(kind.to_string(), name); } - for unknown in ["open_human", "OpenClaw", "claude", ""] { + for unknown in [ + "open_human", + "OpenClaw", + "claude", + "claude_code", + "claudecode", + "", + ] { assert!(serde_json::from_value::(json!(unknown)).is_err()); } Ok(()) @@ -166,47 +174,48 @@ fn the_capability_table_is_the_spec_table() { const R: Support = Rejected(Unlock::Release); const D: Support = Rejected(Unlock::Spec); let table = [ - (C::Essentials, [H, H, H]), - (C::OpenaiEndpoint, [H, H, H]), - (C::OpenaiDefaultEndpoint, [T, T, T]), - (C::Openrouter, [T, T, T]), - (C::Anthropic, [T, T, T]), - (C::InheritedProvider, [D, D, D]), - (C::ProviderCredential, [T, T, T]), - (C::ServedToolPolicy, [Host, Host, Host]), - (C::NoSandbox, [H, H, H]), - (C::Sandbox, [D, D, D]), - (C::Autonomy, [Host, Host, Host]), - (C::BuiltinToolGroups, [D, D, D]), - (C::BuiltinToolRules, [R, D, D]), - (C::BuiltinToolHooks, [D, D, D]), - (C::McpServers, [Host, Host, Host]), - (C::HostSessionStore, [D, D, D]), - (C::HostMemoryEngine, [D, D, D]), - (C::Subagents, [T, D, D]), - (C::DefinitionBase, [T, D, D]), - (C::Jev, [T, D, D]), - (C::SessionTuning, [T, D, D]), - (C::Workflows, [Host, Host, Host]), - (C::Skills, [D, D, D]), - (C::UserSkills, [D, D, D]), - (C::Budget, [D, D, D]), - (C::IterationLimit, [H, D, D]), - (C::Temperature, [D, D, D]), - (C::MaxTokens, [D, D, D]), - (C::BarePrompt, [D, D, D]), - (C::ToolLists, [D, D, D]), - (C::SendPolicy, [D, D, D]), - (C::StopHooks, [D, D, D]), - (C::FactoryConfig, [D, D, D]), - (C::AgentId, [D, D, D]), - (C::Workspace, [D, D, D]), - (C::DeploymentId, [D, D, D]), - (C::Concurrency, [D, D, D]), - (C::MaxAgents, [D, D, D]), - (C::SqliteSessions, [D, D, D]), - (C::InProcessMemory, [D, D, D]), - (C::Undecided, [D, D, D]), + (C::Essentials, [H, H, H, H]), + (C::OpenaiEndpoint, [H, H, H, D]), + (C::OpenaiDefaultEndpoint, [T, T, T, T]), + (C::Openrouter, [T, T, T, T]), + (C::Anthropic, [T, T, T, T]), + (C::AnthropicEndpoint, [D, D, D, H]), + (C::InheritedProvider, [D, D, D, D]), + (C::ProviderCredential, [T, T, T, T]), + (C::ServedToolPolicy, [Host, Host, Host, Host]), + (C::NoSandbox, [H, H, H, H]), + (C::Sandbox, [D, D, D, D]), + (C::Autonomy, [Host, Host, Host, Host]), + (C::BuiltinToolGroups, [D, D, D, D]), + (C::BuiltinToolRules, [R, D, D, D]), + (C::BuiltinToolHooks, [D, D, D, D]), + (C::McpServers, [Host, Host, Host, Host]), + (C::HostSessionStore, [D, D, D, D]), + (C::HostMemoryEngine, [D, D, D, D]), + (C::Subagents, [T, D, D, D]), + (C::DefinitionBase, [T, D, D, D]), + (C::Jev, [T, D, D, D]), + (C::SessionTuning, [T, D, D, D]), + (C::Workflows, [Host, Host, Host, Host]), + (C::Skills, [D, D, D, D]), + (C::UserSkills, [D, D, D, D]), + (C::Budget, [D, D, D, D]), + (C::IterationLimit, [H, D, D, D]), + (C::Temperature, [D, D, D, D]), + (C::MaxTokens, [D, D, D, D]), + (C::BarePrompt, [D, D, D, D]), + (C::ToolLists, [D, D, D, D]), + (C::SendPolicy, [D, D, D, D]), + (C::StopHooks, [D, D, D, D]), + (C::FactoryConfig, [D, D, D, D]), + (C::AgentId, [D, D, D, D]), + (C::Workspace, [D, D, D, D]), + (C::DeploymentId, [D, D, D, D]), + (C::Concurrency, [D, D, D, D]), + (C::MaxAgents, [D, D, D, D]), + (C::SqliteSessions, [D, D, D, D]), + (C::InProcessMemory, [D, D, D, D]), + (C::Undecided, [D, D, D, D]), ]; assert_eq!( table.iter().map(|(c, _)| *c).collect::>(), @@ -249,14 +258,17 @@ fn each_kind_names_its_model_api_and_iteration_cap() { ); assert_eq!(HarnessKind::OpenClaw.model_api(), ModelApi::ChatCompletions); assert_eq!(HarnessKind::Codex.model_api(), ModelApi::Responses); + assert_eq!(HarnessKind::ClaudeCode.model_api(), ModelApi::Messages); assert_eq!(HarnessKind::OpenHuman.iteration_cap(), Some(8)); assert_eq!(HarnessKind::OpenClaw.iteration_cap(), None); assert_eq!(HarnessKind::Codex.iteration_cap(), None); + assert_eq!(HarnessKind::ClaudeCode.iteration_cap(), None); assert_eq!( HarnessKind::OpenClaw.default_isolation(), Isolation::Deployment ); assert_eq!(HarnessKind::Codex.default_isolation(), Isolation::Seat); + assert_eq!(HarnessKind::ClaudeCode.default_isolation(), Isolation::Seat); } /// Every field `T` declares, read from the decoder rather than from a diff --git a/crates/tinyhivemind-lang/src/validation/capability/mod.rs b/crates/tinyhivemind-lang/src/validation/capability/mod.rs index e3a164b7..e91ba094 100644 --- a/crates/tinyhivemind-lang/src/validation/capability/mod.rs +++ b/crates/tinyhivemind-lang/src/validation/capability/mod.rs @@ -194,15 +194,20 @@ impl Judge<'_, '_> { ProviderKind::Openrouter => { self.reject(Capability::Openrouter, field("kind"), at("kind")); } - ProviderKind::Anthropic => { + ProviderKind::Anthropic if provider.endpoint.is_none() => { self.reject(Capability::Anthropic, field("kind"), at("kind")); } + ProviderKind::Anthropic => { + self.reject(Capability::AnthropicEndpoint, field("kind"), at("kind")); + } ProviderKind::Openai if provider.endpoint.is_none() => self.reject( Capability::OpenaiDefaultEndpoint, field("endpoint"), at("endpoint"), ), - ProviderKind::Openai => {} + ProviderKind::Openai => { + self.reject(Capability::OpenaiEndpoint, field("kind"), at("kind")); + } } if provider.credential.is_some() { self.reject( diff --git a/crates/tinyhivemind-lang/src/validation/test/harness.rs b/crates/tinyhivemind-lang/src/validation/test/harness.rs index e0da943d..e42a3fc6 100644 --- a/crates/tinyhivemind-lang/src/validation/test/harness.rs +++ b/crates/tinyhivemind-lang/src/validation/test/harness.rs @@ -162,6 +162,41 @@ fn every_rejected_provider_row_is_reported_at_the_provider() { } } +/// `mixed-harnesses` with every seat on one `claude-code` harness. +fn all_on_claude_code(m: &mut Value) { + m["harnesses"] = json!([{"id": "claude", "kind": "claude-code"}]); + m["runtime"]["harness"] = json!("claude"); + for list in ["seats", "profiles"] { + for entry in m[list].as_array_mut().unwrap() { + entry.as_object_mut().unwrap().remove("harness"); + } + } +} + +#[test] +fn claude_code_speaks_only_to_an_anthropic_endpoint() { + let found = mixed(all_on_claude_code); + assert_eq!(integration_pointers(&found), ["/providers/0/kind"]); + assert!( + found.iter().any(|d| d + .message + .contains("provider openai with an endpoint and no credential")), + "{found:?}" + ); + let found = mixed(|m| { + all_on_claude_code(m); + m["providers"][0]["kind"] = json!("anthropic"); + }); + assert_eq!(found, vec![]); + // Without an endpoint it would reach Anthropic itself, which needs a key. + let found = mixed(|m| { + all_on_claude_code(m); + m["providers"][0]["kind"] = json!("anthropic"); + m["providers"][0]["endpoint"] = json!(null); + }); + assert_eq!(integration_pointers(&found), ["/providers/0/kind"]); +} + #[test] fn a_seat_that_resolves_to_no_provider_is_rejected() { let found = mixed(|m| { diff --git a/crates/tinyhivemind-openhuman-process/Cargo.toml b/crates/tinyhivemind-openhuman-process/Cargo.toml index 04173e7e..ce71f114 100644 --- a/crates/tinyhivemind-openhuman-process/Cargo.toml +++ b/crates/tinyhivemind-openhuman-process/Cargo.toml @@ -57,6 +57,8 @@ rustix = { version = "1.1", default-features = false, features = ["std", "proces [dev-dependencies] tinyhivemind-host = { workspace = true, features = ["conformance"] } +# The hive test: a real coordinator and hive tool server for live seats. +tinyhivemind-mcp.workspace = true # Fallible tests over several error types. anyhow.workspace = true # Async tests, and the in-process fake's listener. diff --git a/crates/tinyhivemind-openhuman-process/tests/README.md b/crates/tinyhivemind-openhuman-process/tests/README.md index 4841cee4..bcb5bded 100644 --- a/crates/tinyhivemind-openhuman-process/tests/README.md +++ b/crates/tinyhivemind-openhuman-process/tests/README.md @@ -4,6 +4,8 @@ | --- | --- | | `conformance.rs` | The host's conformance suite over this runner and the fake child; refusals through the port. Needs `--features conformance`. | | `live.rs` | `live_*`: the suite and the spike gate on the pinned binary, opted into with `THM_OPENHUMAN_CORE` (and Node, from `THM_NODE` or `PATH`). | +| `hive.rs` | `live_hive_*`: two seats on the pinned binary in one hive, with a real coordinator and a real `tinyhivemind-mcp` server; each posts once though it retries, completes, and the episode settles. Opted into with `THM_OPENHUMAN_CORE`. | | [`fake/`](fake/README.md) | The fake `openhuman-core` surface and child | +| [`hive/`](hive/README.md) | The tool-calling model the hive test plays | | [`live/`](live/README.md) | The live subject and scripted model | | [`support/`](support/README.md) | Shared HTTP server and seat helpers | diff --git a/crates/tinyhivemind-openhuman-process/tests/hive.rs b/crates/tinyhivemind-openhuman-process/tests/hive.rs new file mode 100644 index 00000000..aaca5762 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/hive.rs @@ -0,0 +1,210 @@ +//! `live_hive_*`: seats of this runner, on the pinned `openhuman-core`, in a +//! real hive. +//! +//! Each seat runs the pinned `openhuman-core` through this crate's runner, is +//! registered with a real [`Coordinator`], and reaches its hive tools through +//! a real [`HiveToolServer`], with its own bearer. Nothing here is a stub but +//! the model: `hive/model.rs` reads each rendered turn and calls +//! `hivemind_post`, retries that same call, then calls `hivemind_complete`. +//! +//! Opt in with `THM_OPENHUMAN_CORE=`, fetched and +//! checked by `.github/scripts/fetch-harness.sh`. Without it each test says +//! why on stderr and passes. +#![cfg(target_os = "linux")] + +#[path = "hive/model.rs"] +mod model; + +use anyhow::{Context as _, Result, ensure}; +use model::{HiveModel, Seen}; +use serde_json::Value; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; +use tinyhivemind_hives::{ + AgentRegistration, Coordinator, CoordinatorOptions, Destination, EpisodePhase, HiveInfo, + MemoryStorage, Message, SendMessage, +}; +use tinyhivemind_host::harness::{Harness as _, SeatPlan}; +use tinyhivemind_host::process::StopPolicy; +use tinyhivemind_lang::{ + LoweredModel, LoweredSeat, LoweredSeatIntegration, Model, Provider, ProviderKind, +}; +use tinyhivemind_mcp::{HiveToolServer, SeatTools, ServerOptions, Services}; +use tinyhivemind_openhuman_process::{OpenHumanHarness, Options, Program}; + +/// The pinned version, as `harnesses.lock` records it. +const PINNED: &str = "0.64.15"; +/// The hive's seats, both starters of its one episode. +const SEATS: [&str; 2] = ["lead", "builder"]; +/// Long enough for both seats to start, warm up and finish their turns. +const SETTLE: Duration = Duration::from_secs(240); + +fn options() -> Options { + Options { + // The first start after an idle spell took about 30 s on a loaded + // shared machine (load average near 100); later starts take 2 s. + ready: Duration::from_secs(60), + warm_up: Duration::from_secs(20), + stop: StopPolicy::default(), + approval: Duration::from_secs(5), + } +} + +/// Seat `id` on an `openai` endpoint at `endpoint`, with no credential. +fn seat(id: &str, endpoint: &str) -> LoweredSeat { + let provider = Provider { + id: "local".into(), + kind: ProviderKind::Openai, + endpoint: Some(endpoint.into()), + credential: None, + }; + let model = Model { + id: "fast".into(), + provider: Some("local".into()), + name: "mock".into(), + ..Model::default() + }; + LoweredSeat { + id: id.into(), + label: id.into(), + template: "seat".into(), + config: Value::Null, + prompt: format!("You are {id}. Report, then complete."), + memory: None, + integration: LoweredSeatIntegration { + model: Some(LoweredModel { + model, + provider: Some(provider), + }), + ..LoweredSeatIntegration::default() + }, + } +} + +/// Whatever runs in `instance`. +fn processes_in(instance: &Path) -> Vec { + fs::read_dir("/proc") + .into_iter() + .flatten() + .flatten() + .filter_map(|entry| entry.file_name().to_str()?.parse().ok()) + .filter(|pid: &u32| { + fs::read_link(format!("/proc/{pid}/cwd")).is_ok_and(|cwd| cwd.starts_with(instance)) + }) + .collect() +} + +/// What seat `id` must have done: posted once under its own name though the +/// post was sent twice, seen its turn id and the hive tools on every model +/// call, and been answered the first result for its retry. +fn seat_took_its_turn(id: &str, transcript: &[Message], seen: &[Seen]) -> Result<()> { + let posts = transcript + .iter() + .filter(|message| message.sender == id && message.body == format!("{id} reporting")) + .count(); + ensure!(posts == 1, "{id} posted {posts} times: {transcript:#?}"); + let turns: Vec<_> = seen.iter().filter(|request| request.agent == id).collect(); + ensure!(!turns.is_empty(), "the model never saw a turn of {id}"); + for request in &turns { + ensure!( + !request.turn.is_empty(), + "a turn of {id} reached the model without its turn id" + ); + let offered = |name: &str| request.offered.iter().any(|tool| tool.contains(name)); + ensure!( + offered("hivemind_post") && offered("hivemind_complete"), + "{id} was not offered the hive tools: {:?}", + request.offered + ); + } + let retried = turns + .iter() + .find(|request| request.results.len() == 2) + .with_context(|| format!("{id} never saw its retried post answered: {seen:#?}"))?; + ensure!( + retried.results[0] == retried.results[1], + "{id}'s retry was not answered with the first result: {:?}", + retried.results + ); + Ok(()) +} + +/// Two `OpenHuman` processes take one episode together: each posts once +/// although its post is sent twice, each completes, and the episode settles +/// with every message attributed to the seat whose bearer sent it. +#[tokio::test(flavor = "multi_thread")] +async fn live_hive_two_openhuman_seats_post_once_each_and_settle() -> Result<()> { + let Some(binary) = std::env::var_os("THM_OPENHUMAN_CORE").map(PathBuf::from) else { + eprintln!("skipped: THM_OPENHUMAN_CORE is not set to the pinned openhuman-core"); + return Ok(()); + }; + let root = tempfile::tempdir()?; + let model = HiveModel::start().await?; + let endpoint = format!("http://127.0.0.1:{}/v1", model.port); + let coordinator = Coordinator::new( + "runtime".into(), + Arc::new(MemoryStorage::new()), + CoordinatorOptions::default(), + ) + .await?; + let server = + HiveToolServer::start(Services::new(coordinator.clone()), ServerOptions::default()).await?; + let harness = OpenHumanHarness::new(Program::new(binary, PINNED)).with_options(options()); + for id in SEATS { + let tools = server.serve_seat(SeatTools::new(id))?; + let plan = SeatPlan::new(seat(id, &endpoint), root.path().join(id)); + let runner = harness.start(plan, tools).await?; + coordinator + .register_agent(AgentRegistration { + agent_id: id.into(), + runtime_id: coordinator.runtime_id().into(), + runner, + }) + .await?; + } + coordinator + .create_hive(HiveInfo { + hive_id: "work".into(), + name: "Work".into(), + description: None, + members: SEATS.map(Into::into).to_vec(), + }) + .await?; + coordinator + .send_as_host(SendMessage { + message_id: "task".into(), + sender: String::new(), + destination: Destination::Hive("work".into()), + body: "Report, then complete.".into(), + thread: None, + only_for: Vec::new(), + starters: SEATS.map(Into::into).to_vec(), + }) + .await?; + tokio::time::timeout(SETTLE, coordinator.run_until_idle()) + .await + .context("the hive did not settle in time")??; + + let transcript = coordinator.read_transcript(None)?; + let seen = model.seen(); + for id in SEATS { + seat_took_its_turn(id, &transcript, &seen)?; + } + let episodes = coordinator.episodes()?; + ensure!( + episodes.len() == 1 && episodes[0].phase == EpisodePhase::Settled, + "the episode did not settle: {episodes:#?}" + ); + + for id in SEATS { + harness.stop(id).await?; + } + server.shutdown().await?; + for id in SEATS { + let left = processes_in(&root.path().join(id)); + ensure!(left.is_empty(), "{id} left processes behind: {left:?}"); + } + Ok(()) +} diff --git a/crates/tinyhivemind-openhuman-process/tests/hive/README.md b/crates/tinyhivemind-openhuman-process/tests/hive/README.md new file mode 100644 index 00000000..38bd8dd0 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/hive/README.md @@ -0,0 +1,5 @@ +# Hive + +| File | Purpose | +| --- | --- | +| `model.rs` | A Chat Completions model that reads each rendered turn and calls `hivemind_post`, the same call again, then `hivemind_complete`, recording what it was offered and what each call returned. | diff --git a/crates/tinyhivemind-openhuman-process/tests/hive/model.rs b/crates/tinyhivemind-openhuman-process/tests/hive/model.rs new file mode 100644 index 00000000..9d3e533c --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/hive/model.rs @@ -0,0 +1,228 @@ +//! A Chat Completions model on loopback that acts as a hive seat would. +//! +//! Each request carries one seat's turn: the rendered `TurnRequest` is the +//! latest user message. The model reads the turn and episode from it and, +//! counting the tool results that follow, plays three tool calls and a +//! reply: `hivemind_post` with call `post`, the same call again as a retry, +//! then `hivemind_complete` with call `done`. It records what it was offered +//! and what each tool answered, so a test can compare the retry with the +//! first call. +#[expect( + dead_code, + reason = "shared with the fake surface; this model reads bodies only" +)] +#[path = "../support/http.rs"] +mod http; + +use http::{Reply, Request, serve}; +use serde_json::{Value, json}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use tokio::net::TcpListener; +use tokio::sync::mpsc; + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// What one model request showed. +#[derive(Clone, Debug)] +pub(crate) struct Seen { + /// The seat whose turn it is, from the rendered request. + pub(crate) agent: String, + /// The turn, from the rendered request. + pub(crate) turn: String, + /// The names of the tools offered. + pub(crate) offered: Vec, + /// The tool results since the turn's message, in order. + pub(crate) results: Vec, +} + +/// The model, serving until dropped. +pub(crate) struct HiveModel { + pub(crate) port: u16, + seen: Arc>>, + task: tokio::task::JoinHandle<()>, +} + +impl HiveModel { + pub(crate) async fn start() -> std::io::Result { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let port = listener.local_addr()?.port(); + let seen = Arc::new(Mutex::new(Vec::new())); + let serving = seen.clone(); + let task = tokio::spawn(serve(listener, move |request| { + let seen = serving.clone(); + async move { answer(&seen, &request) } + })); + Ok(Self { port, seen, task }) + } + + /// Every request so far. + pub(crate) fn seen(&self) -> Vec { + lock(&self.seen).clone() + } +} + +impl Drop for HiveModel { + fn drop(&mut self) { + self.task.abort(); + } +} + +/// The rendered turn in `content`: the JSON after the first `{`. +fn turn_of(content: &str) -> Option { + let start = content.find('{')?; + serde_json::from_str(&content[start..]).ok() +} + +/// Text of a message's `content`, a string or a list of text parts. +fn text(message: &Value) -> String { + match &message["content"] { + Value::String(text) => text.clone(), + Value::Array(parts) => parts + .iter() + .filter_map(|part| part["text"].as_str()) + .collect::>() + .join(""), + _ => String::new(), + } +} + +/// The offered tool whose name contains `suffix`, as the client named it. +fn tool(offered: &[String], suffix: &str) -> Option { + offered.iter().find(|name| name.contains(suffix)).cloned() +} + +fn answer(seen: &Arc>>, request: &Request) -> Reply { + if request.method == "GET" && request.path.ends_with("/models") { + return Reply::Json( + 200, + json!({"object": "list", "data": [{"id": "mock", "object": "model"}]}), + ); + } + if !request.path.ends_with("/chat/completions") { + return Reply::Json(404, json!({})); + } + let body = request.json(); + let messages = body["messages"].as_array().cloned().unwrap_or_default(); + let offered: Vec = body["tools"] + .as_array() + .into_iter() + .flatten() + .filter_map(|tool| tool["function"]["name"].as_str().map(str::to_owned)) + .collect(); + let last_user = messages + .iter() + .rposition(|message| message["role"] == "user"); + let rendered = last_user + .and_then(|index| turn_of(&text(&messages[index]))) + .unwrap_or(Value::Null); + let results: Vec = last_user + .map(|index| &messages[index + 1..]) + .unwrap_or_default() + .iter() + .filter(|message| message["role"] == "tool") + .map(text) + .collect(); + let agent = rendered["agent_id"].as_str().unwrap_or_default().to_owned(); + let turn = rendered["turn_id"].as_str().unwrap_or_default().to_owned(); + let episode = rendered["episode"]["episode_id"] + .as_str() + .map(str::to_owned); + lock(seen).push(Seen { + agent: agent.clone(), + turn: turn.clone(), + offered: offered.clone(), + results: results.clone(), + }); + let step = match (episode, results.len()) { + (Some(episode), 0 | 1) => tool(&offered, "hivemind_post").map(|name| { + let body = format!("{agent} reporting"); + ( + name, + json!({"episode_id": episode, "body": body, "turn": turn, "call": "post"}), + ) + }), + (Some(episode), 2) => tool(&offered, "hivemind_complete").map(|name| { + let body = format!("{agent} done"); + ( + name, + json!({"episode_id": episode, "body": body, "turn": turn, "call": "done"}), + ) + }), + _ => None, + }; + let stream = body["stream"] == true; + match step { + Some((name, arguments)) => call(&name, &arguments, results.len(), stream), + None => reply(&format!("{agent} finished"), stream), + } +} + +const BASE: &str = r#"{"id":"c","created":1,"model":"mock"}"#; + +fn usage() -> Value { + json!({"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11}) +} + +fn frames(chunks: Vec) -> Reply { + let (sender, receiver) = mpsc::channel(16); + let base: Value = serde_json::from_str(BASE).unwrap_or(Value::Null); + let mut out: Vec = chunks + .into_iter() + .map(|mut extra| { + let mut chunk = base.clone(); + chunk["object"] = json!("chat.completion.chunk"); + if let (Some(chunk), Some(extra)) = (chunk.as_object_mut(), extra.as_object_mut()) { + chunk.append(extra); + } + format!("data: {chunk}\n\n") + }) + .collect(); + out.push("data: [DONE]\n\n".to_owned()); + tokio::spawn(async move { + for frame in out { + let _ = sender.send(frame).await; + } + }); + Reply::Stream(receiver) +} + +/// A tool call, numbered by how many came before it in the turn. +fn call(name: &str, arguments: &Value, index: usize, stream: bool) -> Reply { + let id = format!("call-{index}"); + let arguments = arguments.to_string(); + if !stream { + let mut reply: Value = serde_json::from_str(BASE).unwrap_or(Value::Null); + reply["object"] = json!("chat.completion"); + reply["choices"] = json!([{"index": 0, "finish_reason": "tool_calls", + "message": {"role": "assistant", "content": null, "tool_calls": [ + {"id": id, "type": "function", "function": {"name": name, "arguments": arguments}}]}}]); + reply["usage"] = usage(); + return Reply::Json(200, reply); + } + frames(vec![ + json!({"choices": [{"index": 0, "delta": {"role": "assistant", "tool_calls": [ + {"index": 0, "id": id, "type": "function", + "function": {"name": name, "arguments": arguments}}]}, "finish_reason": null}]}), + json!({"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]}), + json!({"choices": [], "usage": usage()}), + ]) +} + +/// A plain answer that ends the turn. +fn reply(text: &str, stream: bool) -> Reply { + if !stream { + let mut reply: Value = serde_json::from_str(BASE).unwrap_or(Value::Null); + reply["object"] = json!("chat.completion"); + reply["choices"] = json!([{"index": 0, "finish_reason": "stop", + "message": {"role": "assistant", "content": text}}]); + reply["usage"] = usage(); + return Reply::Json(200, reply); + } + frames(vec![ + json!({"choices": [{"index": 0, "delta": {"role": "assistant", "content": text}, "finish_reason": null}]}), + json!({"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}), + json!({"choices": [], "usage": usage()}), + ]) +} diff --git a/docs/adr/0037-claude-code-is-a-fourth-harness-kind.md b/docs/adr/0037-claude-code-is-a-fourth-harness-kind.md new file mode 100644 index 00000000..2e81d093 --- /dev/null +++ b/docs/adr/0037-claude-code-is-a-fourth-harness-kind.md @@ -0,0 +1,43 @@ +# 37. Claude Code is a fourth harness kind + +- **Status:** Proposed +- **Date:** 2026-11-26 +- **Specification:** [harnesses](../specs/harnesses.md) +- **Amends:** [ADR 0035](0035-a-harness-is-a-process.md), whose kinds were + `openhuman`, `openclaw` and `codex` + +## Context + +The process harness work aims at one hive whose seats run on different +harnesses. Claude Code is a harness a team is likely to want there: it runs +headless as a command-line program, streams newline-delimited JSON over +stdio, takes MCP servers with request headers, keeps sessions it can resume, +and can be held to an exact tool allowlist. It was not in the November spike, +so nothing about it is measured yet. + +It differs from the other three in one way the language must see: it speaks +only Anthropic's Messages API. A package that gives a `claude-code` seat an +`openai` endpoint would be accepted and then fail every turn. + +## Decision + +- `claude-code` is a harness kind, beside `openhuman`, `openclaw` and `codex`, + with one instance per seat. +- Its model API is Anthropic's Messages API (`ModelApi::Messages`). A new + capability row, provider `anthropic` with an explicit `endpoint` and no + `credential`, is the one provider shape it accepts; `openai` with an + endpoint is rejected for it by the spec. The other kinds reject the new row. +- Every other row is the same as `codex`'s: built-in tools off, the rest + rejected until a conformance test on the pinned release proves it. +- The client is `tinyhivemind-claude-code`, a crate that links no harness, as + ADR 0035 requires of every client. + +## Consequences + +- `HarnessKind::ALL` and every capability row grow a column; a package naming + `claude-code` is checked like any other. +- The key rule is unchanged: a seat gets an endpoint, never a credential, so a + real Anthropic model is reached through a host-side proxy that holds the key. +- The pin, the start-up verification and the conformance suite carry the + evidence the spike carried for the other three. Until they pass on the + pinned release, this decision stays proposed. diff --git a/docs/adr/0038-acp-agents-share-one-client.md b/docs/adr/0038-acp-agents-share-one-client.md new file mode 100644 index 00000000..182c747c --- /dev/null +++ b/docs/adr/0038-acp-agents-share-one-client.md @@ -0,0 +1,48 @@ +# 38. ACP agents share one client + +- **Status:** Proposed +- **Date:** 2026-11-26 +- **Specification:** [harnesses](../specs/harnesses.md) +- **Evidence:** [the ACP harness runs](../experiments/2026-11-26-acp-harnesses.md) +- **Amends:** [ADR 0035](0035-a-harness-is-a-process.md), whose plan gave each + kind a client crate of its own + +## Context + +ADR 0035 planned one client crate per harness kind, each speaking its +harness's native protocol: Codex's app-server, OpenClaw's Gateway WebSocket. +Each would be thousands of lines, and every further harness another crate. + +Claude Code, Codex and OpenClaw all speak the Agent Client Protocol over stdio, +Claude Code and Codex through adapters published by the protocol's maintainers +and OpenClaw through a bridge it ships. Driven by one minimal ACP client +against the spike's scripted model, each called the hive tool as the right +seat, cancelled, and resumed after a restart, and a restarted agent made no +model call on its own, once one +setting per agent was made: Claude Code's built-in tools and tool search off, +and Codex out of its model-reviewed mode. + +## Decision + +- `tinyhivemind-acp` implements the harness port once, for any agent that + speaks ACP version 1 over stdio. It links no agent. +- What differs between agents is an `Agent` descriptor of data: the command, + environment and files, the `session/new` metadata, and the session mode. + Claude Code and Codex have descriptors; OpenClaw's follows, with its shared + Gateway supervised beside the bridge. +- A permission request for a tool of the host's own MCP server is allowed by + the client, since the tool server already judges hive tools. Any other goes + to the seat's approver. +- OpenHuman keeps its own client (`tinyhivemind-openhuman-process`) until it + speaks ACP. + +## Consequences + +- A new ACP agent is a descriptor and a conformance run, not a crate. +- ACP shows no tool list, so the start-up check cannot observe what the model + sees; each descriptor's settings hold it, and the live tests prove it. +- The adapters are extra processes: a Codex seat costs about twice its native + app-server's memory. +- Per-turn usage depends on the agent reporting it: Claude Code and Codex do, + OpenClaw's bridge does not. +- This stays proposed until the conformance suite passes on each pinned agent. diff --git a/docs/adr/README.md b/docs/adr/README.md index 9911506c..4eb30059 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -62,6 +62,8 @@ link any earlier ADR it amends. | [0034](0034-the-hive-language-defines-the-deployment.md) | The hive language defines the deployment | Accepted — supersedes the parallel schema of the OpenHuman hive configuration spec | | [0035](0035-a-harness-is-a-process.md) | A harness is a process | Accepted — amends 0034; supersedes 0020 and the linking crate of 0028 once the link is removed | | [0036](0036-hive-tools-are-served-over-loopback-mcp.md) | Hive tools are served over loopback MCP | Accepted — amends 0027 | +| [0037](0037-claude-code-is-a-fourth-harness-kind.md) | Claude Code is a fourth harness kind | Proposed — amends 0035 | +| [0038](0038-acp-agents-share-one-client.md) | ACP agents share one client | Proposed — amends 0035 | ## Reading order diff --git a/docs/experiments/2026-11-26-acp-harnesses.md b/docs/experiments/2026-11-26-acp-harnesses.md new file mode 100644 index 00000000..1cde945e --- /dev/null +++ b/docs/experiments/2026-11-26-acp-harnesses.md @@ -0,0 +1,107 @@ +# Can Claude Code, Codex and OpenClaw run as hive seats over ACP? + +- **Date:** 2026-11-26 +- **Status:** Recorded +- **Spec:** [harnesses](../specs/harnesses.md) +- **Follows:** [the process harness spike](2026-11-25-process-harnesses.md) +- **Code:** [the companion directory](2026-11-26-acp-harnesses/README.md) + +## Question and gate + +Written before the runs: can one generic Agent Client Protocol (ACP) client, +over stdio, drive each harness as a seat? For each, it must list and call the +hive tool as the right seat over HTTP MCP with a bearer header, report per-turn +token usage, cancel a turn, keep a session across a restart, and leave nothing +running after a kill. If it can, one ACP client replaces three bespoke clients. + +## Method + +All runs used the scripted model and MCP stub of the 2026-11-25 spike, with +Anthropic's Messages API added for Claude Code. `acp.mjs` is a minimal ACP +client: newline-delimited JSON-RPC, protocol version 1, no file system or +terminal offered to the agent. Each permission request was answered with the +first "allow" option. No real model and no credential were involved: the +fixture ignores keys. + +Versions, on Linux x86_64 (all-in, load average around 80) with Node 24.16.0: + +| Harness | ACP entry point | Harness inside | +| --- | --- | --- | +| Claude Code | `@agentclientprotocol/claude-agent-acp` 0.112.0 | Claude Agent SDK 0.3.331, Claude Code 2.1.331 | +| Codex | `@agentclientprotocol/codex-acp` 2.12.1 | `@openai/codex` 0.172.0 (`app-server`) | +| OpenClaw | `openclaw acp` (built-in bridge) | `openclaw` 2026.10.33 Gateway | + +## Result: the gate passes for all three, except usage on OpenClaw and cleanup on Claude Code + +| | Claude Code | Codex | OpenClaw | +| --- | --- | --- | --- | +| Hive tool called as seat `a` | yes | yes | yes | +| Tools the model saw | the hive tool only | the hive tool and three MCP resource readers | the hive tool only | +| Per-turn usage in the `session/prompt` result | yes | yes | **no**: only `usage_update` with context size | +| Approval of the hive tool | none asked (allowlisted) | `session/request_permission` to the client | none asked (Gateway allowlist) | +| Cancel: answered / model call closed | 3 ms / 5 ms | 154 ms / 5 ms | 4 ms / 21 ms | +| Same session after restart (`session/load`) | yes | yes | yes | +| Processes left after `kill -9` of the agent | 1 (the CLI child) | 0 | 0 (bridge only killed) | +| Model calls a new agent made on its own within 15 s (the interrupted session not loaded) | 0 | 0 | 0 | +| Processes per seat | 2 | 2 | 2, plus the shared Gateway's 2 | +| Idle PSS (10 s) | 292 MB | 257 to 267 MB | 1,981 MB with the Gateway | +| PSS after 13 turns | 341 MB | 258 to 282 MB | 2,163 MB with the Gateway | +| Start to `initialize` | 0.26 to 0.30 s | 0.29 to 2.6 s | 5.0 s, after 16.5 s for the Gateway | +| `session/new` | 0.3 to 2.5 s | 0.04 to 0.11 s | 0.38 s | +| Median turn, plain / one tool call | 22 / 43 ms | 20 / 36 ms | 406 / 317 ms | + +Single runs on a loaded shared machine: the timings are indicative, and the +start-up times varied by an order of magnitude between runs. + +Claude Code fails the "leave nothing running after a kill" part of the gate +on its own: after `kill -9` of its adapter, its CLI child ran on. A seat +kills the whole process tree, so a supervised Claude Code seat leaves +nothing, but the adapter alone does not. + +The replay row shows only that a new agent makes no model call when it +starts. The interrupted session was not loaded into it, so whether loading +such a session replays its turn was not measured. + +## What each harness needed + +1. **Claude Code hid the hive tool by default.** With the adapter's defaults the + model was offered the built-in tools and `ToolSearch`, and the MCP tool was + deferred behind it, so the scripted model never saw it. Passing Claude Agent + SDK options on `session/new`, `_meta.claudeCode.options` = `tools: []`, + `settingSources: []` and `allowedTools: ["mcp__hive__hivemind_post"]`, with + `ENABLE_TOOL_SEARCH=false`, left exactly the hive tool and no prompt. +2. **Codex reviewed tool calls with a model.** The adapter's default mode, + "Auto review", runs a guardian sub-turn with model `codex-auto-review` + before each tool call. Against the fixture it did not approve, so the call + never reached the MCP server and each tool turn took about 700 ms. Switching + the session to the `read-only` mode (`session/set_mode`) sends the approval + to the client instead, where the host's approver answers it. Codex also + needs the spike's direct-tool model catalog, with an entry for the + configured model, or it prints a metadata warning into the reply. +3. **OpenClaw takes MCP servers from the Gateway, not the session.** The bridge + rejects per-session MCP servers, so the seat's server and bearer go into the + Gateway config per agent, as in the spike. The bridge reports no per-turn + token usage. + +## What this changes + +- One ACP client can drive all three. What differs per harness is data: the + command, environment, `session/new` metadata, mode, and where MCP is + configured. That is a descriptor, not a crate. +- ACP adds an adapter process per seat for Claude Code and Codex. Against the + spike's native Codex `app-server` (127 MB RSS idle) the adapter roughly + doubles a Codex seat's memory. +- OpenClaw remains the outlier: about 2 GB for the Gateway and bridge, a 20 s + cold start, and no usage. It stays shared per deployment, and its usage needs + another source (the Gateway's own frames, as in the spike) or the row stays + rejected. +- A Claude Code CLI child outlived `kill -9` of its adapter. The host's + supervisor already stops the whole tree; this confirms it must. + +## Not tested + +Real models and credentials; whether `session/load` of an interrupted +session replays its turn; the Gateway's own crash and its turn replay (only +the bridge was killed here); concurrent seats; long sessions and compaction; +ACP protocol v2; whether each adapter honours `session/cancel` during a tool +call rather than a model call; macOS and ARM. diff --git a/docs/experiments/2026-11-26-acp-harnesses/README.md b/docs/experiments/2026-11-26-acp-harnesses/README.md new file mode 100644 index 00000000..36bedce6 --- /dev/null +++ b/docs/experiments/2026-11-26-acp-harnesses/README.md @@ -0,0 +1,34 @@ +# Repeating the ACP harness runs + +Companion to [the record](../2026-11-26-acp-harnesses.md). + +| File | Does | +| --- | --- | +| `fixture.mjs` | the 2026-11-25 fixture plus Anthropic's Messages API: a scripted model and an MCP stub that maps `seat-a-token` to seat `a` | +| `acp.mjs` | a minimal ACP client over stdio, and process-tree memory | +| `measure.mjs` | one harness's gate and measurements, with its per-harness setup | + +The Codex and OpenClaw setups reuse the spike's `codex/catalog.mjs`, +`codex/config.toml.in` and `openclaw/mkcfg.mjs`. + +## Run + +Install each harness in its own directory under ``: + +```sh +npm install @agentclientprotocol/claude-agent-acp@0.112.0 # in /claude +npm install @agentclientprotocol/codex-acp@2.12.1 # in /codex +npm install openclaw@2026.10.33 # in /openclaw +``` + +Then, per harness, start a fixture and measure against it: + +```sh +node fixture.mjs 19701 /abs/runs/claude-fx.log & +node measure.mjs claude /abs/pkgs /abs/runs/claude 19701 /abs/runs/claude-fx.log +node measure.mjs codex /abs/pkgs /abs/runs/codex 19702 /abs/runs/codex-fx.log +node measure.mjs openclaw /abs/pkgs /abs/runs/openclaw 19703 /abs/runs/openclaw-fx.log 19803 +``` + +Each line printed is one JSON measurement. Egress is not blocked by these +scripts. diff --git a/docs/experiments/2026-11-26-acp-harnesses/acp.mjs b/docs/experiments/2026-11-26-acp-harnesses/acp.mjs new file mode 100644 index 00000000..4b1db742 --- /dev/null +++ b/docs/experiments/2026-11-26-acp-harnesses/acp.mjs @@ -0,0 +1,80 @@ +// A minimal Agent Client Protocol client over stdio (newline-delimited +// JSON-RPC), and the process-tree measurements the runs share. +import { spawn, execSync } from "node:child_process"; +import fs from "node:fs"; + +export const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +/** Start `cmd` as an ACP agent in its own process group. */ +export function agent(cmd, args, { env, cwd, log }) { + const child = spawn(cmd, args, { env, cwd, detached: true, stdio: ["pipe", "pipe", "pipe"] }); + const err = fs.openSync(log, "a"); + child.stderr.on("data", (d) => fs.writeSync(err, d)); + let buf = "", id = 0; + const pending = new Map(); + const updates = []; + const requests = []; + let closed = null; + const write = (o) => child.stdin.write(JSON.stringify(o) + "\n"); + // Decoded as a stream, so a character split across chunks stays whole. + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (d) => { + buf += d; + for (let i; (i = buf.indexOf("\n")) >= 0;) { + const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1); + if (!line) continue; + let m; try { m = JSON.parse(line); } catch { fs.writeSync(err, "non-json: " + line + "\n"); continue; } + if (m.id !== undefined && (m.result !== undefined || m.error !== undefined) && pending.has(m.id)) { + const p = pending.get(m.id); pending.delete(m.id); + m.error ? p.reject(Object.assign(new Error(m.error.message), { rpc: m.error })) : p.resolve(m.result); + } else if (m.method === "session/update") { + updates.push({ t: Date.now(), ...m.params.update }); + } else if (m.method && m.id !== undefined) { + // A request from the agent: allow tool permissions once, refuse the rest. + requests.push({ t: Date.now(), method: m.method, params: m.params }); + if (m.method === "session/request_permission") { + const allow = m.params.options?.find((o) => o.kind?.startsWith("allow")); + write({ jsonrpc: "2.0", id: m.id, result: { outcome: allow ? { outcome: "selected", optionId: allow.optionId } : { outcome: "cancelled" } } }); + } else { + write({ jsonrpc: "2.0", id: m.id, error: { code: -32601, message: "not offered" } }); + } + } + } + }); + // Once the agent's output ends, every waiting call fails, and so does any later one. + child.stdout.on("close", () => { + closed = new Error("the agent closed the connection"); + for (const p of pending.values()) p.reject(closed); + pending.clear(); + }); + const call = (method, params) => new Promise((resolve, reject) => { + if (closed) return reject(closed); + const n = ++id; pending.set(n, { resolve, reject }); write({ jsonrpc: "2.0", id: n, method, params }); + }); + const notify = (method, params) => write({ jsonrpc: "2.0", method, params }); + const exited = new Promise((r) => child.on("exit", (code, signal) => r({ code, signal }))); + return { child, call, notify, updates, requests, exited }; +} + +/** The pids of `root` and every descendant. */ +export function tree(root) { + const all = execSync("ps -eo pid,ppid", { encoding: "utf8" }).trim().split("\n").slice(1).map((l) => l.trim().split(/\s+/).map(Number)); + const s = [root]; + for (let i = 0; i < s.length; i++) for (const [a, b] of all) if (b === s[i]) s.push(a); + return s; +} + +/** RSS and PSS of a process tree, in MB, and its size. */ +export function memory(root) { + const pids = tree(root); + let rss = 0, pss = 0; + for (const p of pids) { + try { + const r = fs.readFileSync(`/proc/${p}/smaps_rollup`, "utf8"); + rss += +r.match(/Rss:\s+(\d+)/)[1]; pss += +r.match(/Pss:\s+(\d+)/)[1]; + } catch {} + } + return { processes: pids.length, rssMB: Math.round(rss / 1024), pssMB: Math.round(pss / 1024), commands: pids.map((p) => { try { return fs.readFileSync(`/proc/${p}/cmdline`, "utf8").split("\0").slice(0, 3).join(" ").slice(0, 90); } catch { return "?"; } }) }; +} + +export const median = (a) => [...a].sort((x, y) => x - y)[a.length >> 1]; diff --git a/docs/experiments/2026-11-26-acp-harnesses/fixture.mjs b/docs/experiments/2026-11-26-acp-harnesses/fixture.mjs new file mode 100644 index 00000000..11e7701b --- /dev/null +++ b/docs/experiments/2026-11-26-acp-harnesses/fixture.mjs @@ -0,0 +1,104 @@ +// Scripted model (Chat Completions, Responses and Anthropic Messages, streaming or not) and MCP stub. +// The 2026-11-25 spike's fixture with the Messages API added for Claude Code. +// usage: node fixture.mjs bearer for MCP: seat-a-token -> seat a, seat-b-token -> seat b +// Prompt keywords in the LATEST user message: CALLTOOL -> call *hivemind_post once; SLOW -> stream nothing for 120s. +import http from "node:http"; import fs from "node:fs"; +const [port, log] = [Number(process.argv[2]), process.argv[3]]; +const L = (o) => fs.appendFileSync(log, JSON.stringify({ t: Date.now(), ...o }) + "\n"); +const seats = { "Bearer seat-a-token": "a", "Bearer seat-b-token": "b" }; +const read = (q) => new Promise((r) => { let b = ""; q.on("data", (c) => (b += c)); q.on("end", () => r(b)); }); +const txt = (c) => typeof c === "string" ? c : (c ?? []).map((p) => p.text ?? "").join(""); +let n = 0; +// Anthropic Messages (`POST /v1/messages`): Claude Code's only model API. +const blocks = (c) => typeof c === "string" ? [{ type: "text", text: c }] : (c ?? []); +async function messages(q, s, b, raw, json) { + if (q.url.includes("/count_tokens")) return json({ input_tokens: 100 }); + const items = b.messages ?? []; + const said = (m) => m.role === "user" && /CALLTOOL|SLOW|PLAIN/.test(blocks(m.content).map((c) => c.text ?? "").join("")); + const lastUser = items.findLastIndex(said); + const ut = lastUser >= 0 ? blocks(items[lastUser].content).map((c) => c.text ?? "").join("") : ""; + const key = [...ut.matchAll(/CALLTOOL|SLOW|PLAIN/g)].at(-1)?.[0]; + const results = items.slice(lastUser + 1).flatMap((m) => blocks(m.content)).filter((c) => c.type === "tool_result"); + const after = results.length > 0; + const names = (b.tools ?? []).map((t) => t.name ?? t.type); + const tool = names.find((x) => x?.includes("hivemind_post")); + L({ kind: "model", api: "messages", model: b.model, stream: !!b.stream, key, after, userTurns: items.filter(said).length, bytes: raw.length, tools: names, toolResults: results.map((r) => JSON.stringify(r.content).slice(0, 200)) }); + q.socket.on("close", () => { if (key === "SLOW" && !s.writableEnded) L({ kind: "model-disconnect" }); }); + if (key === "SLOW") await new Promise((r) => setTimeout(r, 120000)); + const call = key === "CALLTOOL" && !after && tool; + const text = key === "CALLTOOL" && !after && !tool ? "NO_HIVE_TOOL" : `MOCK_REPLY turns=${items.filter(said).length}`; + const id = `toolu_${++n}`; + const content = call ? [{ type: "tool_use", id, name: tool, input: { body: "hello hive" } }] : [{ type: "text", text }]; + const usage = { input_tokens: 100, output_tokens: 7, cache_read_input_tokens: 10, cache_creation_input_tokens: 0 }; + const msg = { id: "msg_" + n, type: "message", role: "assistant", model: b.model, content, stop_reason: call ? "tool_use" : "end_turn", stop_sequence: null, usage }; + if (!b.stream) return json(msg); + s.writeHead(200, { "content-type": "text/event-stream" }); + const ev = (type, o) => s.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...o })}\n\n`); + ev("message_start", { message: { ...msg, content: [], stop_reason: null, usage: { ...usage, output_tokens: 1 } } }); + if (call) { + ev("content_block_start", { index: 0, content_block: { type: "tool_use", id, name: tool, input: {} } }); + ev("content_block_delta", { index: 0, delta: { type: "input_json_delta", partial_json: JSON.stringify({ body: "hello hive" }) } }); + } else { + ev("content_block_start", { index: 0, content_block: { type: "text", text: "" } }); + ev("content_block_delta", { index: 0, delta: { type: "text_delta", text } }); + } + ev("content_block_stop", { index: 0 }); + ev("message_delta", { delta: { stop_reason: msg.stop_reason, stop_sequence: null }, usage: { output_tokens: 7 } }); + ev("message_stop", {}); + s.end(); +} +http.createServer(async (q, s) => { + const raw = await read(q); let b = {}; try { b = JSON.parse(raw || "{}"); } catch {} + const json = (o, c = 200, h = {}) => { s.writeHead(c, { "content-type": "application/json", ...h }); s.end(JSON.stringify(o)); }; + if (q.url.startsWith("/mcp")) { + const seat = seats[q.headers.authorization]; + L({ kind: "mcp", http: q.method, rpc: b.method, seat: seat ?? null, params: b.params }); + if (!seat) return json({ error: "unauthorized" }, 401); + if (q.method !== "POST") return json({}, 405); + if (b.id === undefined) { s.writeHead(202); return s.end(); } + const ok = (result) => json({ jsonrpc: "2.0", id: b.id, result }); + if (b.method === "initialize") return ok({ protocolVersion: b.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "hive-stub", version: "0" } }); + if (b.method === "tools/list") return ok({ tools: [{ name: "hivemind_post", description: "Post to the episode.", inputSchema: { type: "object", properties: { body: { type: "string" } }, required: ["body"] } }] }); + if (b.method === "tools/call") return ok({ content: [{ type: "text", text: `posted as seat ${seat}` }], isError: false }); + return json({ jsonrpc: "2.0", id: b.id, error: { code: -32601, message: "no method" } }); + } + if (q.url.includes("/v1/messages")) return messages(q, s, b, raw, json); + if (q.method === "GET" && q.url.includes("/models")) return json({ object: "list", data: [{ id: "mock", object: "model" }] }); + const resp = q.url.includes("/responses"); const chat = q.url.includes("/chat/completions"); + if (!resp && !chat) { L({ kind: "other", m: q.method, url: q.url }); return json({}, 404); } + const items = resp ? (Array.isArray(b.input) ? b.input : [{ role: "user", content: b.input }]) : b.messages ?? []; + const lastUser = items.findLastIndex((m) => m.role === "user" && /CALLTOOL|SLOW|PLAIN/.test(txt(m.content))); + const ut = lastUser >= 0 ? txt(items[lastUser].content) : ""; + const key = [...ut.matchAll(/CALLTOOL|SLOW|PLAIN/g)].at(-1)?.[0]; + const after = items.slice(lastUser + 1).some((m) => m.role === "tool" || m.type === "function_call_output"); + // Responses may nest MCP tools in {type:"namespace",name,tools:[...]} + const flat = (b.tools ?? []).flatMap((t) => t.type === "namespace" ? (t.tools ?? []).map((u) => ({ ns: t.name, name: u.name })) : [{ name: t.name ?? t.function?.name ?? t.type }]); + const tool = flat.find((t) => t.name?.includes("hivemind_post")); + const marks = items.filter((m) => m.role === "user" && /CALLTOOL|SLOW|PLAIN/.test(txt(m.content))).length; + L({ kind: "model", api: resp ? "responses" : "chat", model: b.model, stream: !!b.stream, key, after, userTurns: marks, bytes: raw.length, tools: flat.map((t) => (t.ns ? t.ns + "/" : "") + t.name), toolResults: items.filter((m) => m.role === "tool" || m.type === "function_call_output").map((m) => txt(m.content ?? m.output).slice(0, 200)) }); + q.socket.on("close", () => { if (key === "SLOW" && !s.writableEnded) L({ kind: "model-disconnect" }); }); + if (key === "SLOW") await new Promise((r) => setTimeout(r, 120000)); + const call = key === "CALLTOOL" && !after && tool; const id = `call_${++n}`; const args = '{"body":"hello hive"}'; + const text = key === "CALLTOOL" && !after && !tool ? "NO_HIVE_TOOL" : `MOCK_REPLY turns=${marks}`; + const sse = (o, ev) => s.write((ev ? `event: ${ev}\n` : "") + `data: ${typeof o === "string" ? o : JSON.stringify(o)}\n\n`); + if (resp) { + const item = call ? { type: "function_call", id: "fc_" + n, call_id: id, name: tool.name, ...(tool.ns ? { namespace: tool.ns } : {}), arguments: args, status: "completed" } + : { type: "message", id: "msg_" + ++n, role: "assistant", status: "completed", content: [{ type: "output_text", text, annotations: [] }] }; + const r = { id: "resp_" + n, object: "response", status: "completed", model: b.model, output: [item], usage: { input_tokens: 100, input_tokens_details: { cached_tokens: 10 }, output_tokens: 7, output_tokens_details: { reasoning_tokens: 0 }, total_tokens: 107 } }; + if (!b.stream) return json(r); + s.writeHead(200, { "content-type": "text/event-stream" }); + sse({ type: "response.created", response: { ...r, status: "in_progress", output: [] } }, "response.created"); + sse({ type: "response.output_item.added", output_index: 0, item: { ...item, status: "in_progress" } }, "response.output_item.added"); + if (!call) sse({ type: "response.output_text.delta", item_id: item.id, output_index: 0, content_index: 0, delta: text }, "response.output_text.delta"); + sse({ type: "response.output_item.done", output_index: 0, item }, "response.output_item.done"); + sse({ type: "response.completed", response: r }, "response.completed"); return s.end(); + } + const usage = { prompt_tokens: 100, completion_tokens: 7, total_tokens: 107, prompt_tokens_details: { cached_tokens: 10 } }; + const tc = [{ index: 0, id, type: "function", function: { name: tool?.name, arguments: args } }]; + const base = { id: "c" + n, created: 1, model: b.model }; + if (!b.stream) return json({ ...base, object: "chat.completion", choices: [{ index: 0, finish_reason: call ? "tool_calls" : "stop", message: call ? { role: "assistant", content: null, tool_calls: tc } : { role: "assistant", content: text } }], usage }); + s.writeHead(200, { "content-type": "text/event-stream" }); + const ch = (delta, f = null) => sse({ ...base, object: "chat.completion.chunk", choices: [{ index: 0, delta, finish_reason: f }] }); + ch(call ? { role: "assistant", tool_calls: tc } : { role: "assistant", content: text }); ch({}, call ? "tool_calls" : "stop"); + sse({ ...base, object: "chat.completion.chunk", choices: [], usage }); sse("[DONE]"); s.end(); +}).listen(port, "127.0.0.1", () => console.log("ready")); diff --git a/docs/experiments/2026-11-26-acp-harnesses/measure.mjs b/docs/experiments/2026-11-26-acp-harnesses/measure.mjs new file mode 100644 index 00000000..36d10b2e --- /dev/null +++ b/docs/experiments/2026-11-26-acp-harnesses/measure.mjs @@ -0,0 +1,137 @@ +// node measure.mjs [gateway port] +// One agent over ACP against the running fixture: start-up, the hive tool as +// seat a, usage, turn latency, memory, cancel, resume after restart, kill -9. +import fs from "node:fs"; import path from "node:path"; import { execFileSync } from "node:child_process"; +import { agent, memory, tree, median, sleep } from "./acp.mjs"; + +const [kind, pkgs, work, fport, flog, gport] = process.argv.slice(2); +const here = path.dirname(new URL(import.meta.url).pathname); +const spike = `${here}/../2026-11-25-process-harnesses`; +const node = process.execPath; +const out = (k, v) => console.log(JSON.stringify({ kind, k, v })); +const fx = (n = 0) => fs.readFileSync(flog, "utf8").trim().split("\n").filter(Boolean).map(JSON.parse).slice(n); +for (const d of ["home", "tmp", "cwd"]) fs.mkdirSync(`${work}/${d}`, { recursive: true }); +const base = { PATH: `${path.dirname(node)}:/usr/bin:/bin`, HOME: `${work}/home`, TMPDIR: `${work}/tmp` }; +const hive = [{ type: "http", name: "hive", url: `http://127.0.0.1:${fport}/mcp`, headers: [{ name: "Authorization", value: "Bearer seat-a-token" }] }]; + +let gateway = null; +const setups = { + claude: () => ({ + cmd: node, args: [`${pkgs}/claude/node_modules/@agentclientprotocol/claude-agent-acp/dist/index.js`], + env: { ...base, CLAUDE_CONFIG_DIR: `${work}/claude`, ANTHROPIC_BASE_URL: `http://127.0.0.1:${fport}`, ANTHROPIC_API_KEY: "dummy", ANTHROPIC_MODEL: "mock", ANTHROPIC_SMALL_FAST_MODEL: "mock", DISABLE_TELEMETRY: "1", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1", DISABLE_ERROR_REPORTING: "1", ENABLE_TOOL_SEARCH: "false" }, + mcp: hive, + // No built-in tools, no settings files, and the hive tool allowed without a prompt. + meta: { claudeCode: { options: { tools: [], settingSources: [], allowedTools: ["mcp__hive__hivemind_post"] } } }, + }), + codex: () => { + const home = `${work}/codex`; fs.mkdirSync(home, { recursive: true }); + const bin = execFileSync("find", [`${pkgs}/codex/node_modules/@openai`, "-type", "f", "-name", "codex", "-path", "*vendor*"], { encoding: "utf8" }).trim().split("\n")[0]; + execFileSync(node, [`${spike}/codex/catalog.mjs`, bin, `${home}/catalog.json`]); + // The fixture's model is `mock`: give it the first model's metadata. + const catalog = JSON.parse(fs.readFileSync(`${home}/catalog.json`, "utf8")); + catalog.models.unshift({ ...catalog.models[0], slug: "mock", display_name: "mock" }); + fs.writeFileSync(`${home}/catalog.json`, JSON.stringify(catalog)); + const cfg = fs.readFileSync(`${spike}/codex/config.toml.in`, "utf8").replaceAll("@FIXTURE_PORT@", fport).replaceAll("@CATALOG@", `${home}/catalog.json`); + fs.writeFileSync(`${home}/config.toml`, cfg); + return { + cmd: node, args: [`${pkgs}/codex/node_modules/@agentclientprotocol/codex-acp/dist/index.js`], + env: { ...base, CODEX_HOME: home, MOCK_KEY: "dummy" }, mcp: hive, + // The adapter's default mode has an AI reviewer approve each tool call; + // read-only sends approvals to the client instead. + mode: "read-only", + }; + }, + openclaw: () => { + const pkg = `${pkgs}/openclaw/node_modules/openclaw`; + execFileSync(node, [`${spike}/openclaw/mkcfg.mjs`, `${work}/oc`, gport, fport, "a"]); + fs.mkdirSync(`${work}/oc/state`, { recursive: true }); + const env = { ...base, OPENCLAW_STATE_DIR: `${work}/oc/state`, OPENCLAW_CONFIG_PATH: `${work}/oc/openclaw.json`, OPENCLAW_SKIP_CHANNELS: "1", OPENCLAW_DISABLE_BONJOUR: "1", OPENCLAW_NO_RESPAWN: "1", OPENCLAW_EXEC_SHELL_SNAPSHOT: "0" }; + return { + gateway: { cmd: node, args: [`${pkg}/openclaw.mjs`, "gateway"], env }, + cmd: node, args: [`${pkg}/openclaw.mjs`, "acp", "--url", `ws://127.0.0.1:${gport}`, "--token", "gw-secret-token", "--session", "agent:a:acp", "--no-prefix-cwd"], + env, mcp: [], + }; + }, +}; +const setup = setups[kind](); + +const roots = () => [a.child.pid, ...(gateway ? [gateway.child.pid] : [])]; +const mem = () => roots().map(memory).reduce((x, y) => ({ processes: x.processes + y.processes, rssMB: x.rssMB + y.rssMB, pssMB: x.pssMB + y.pssMB, commands: [...x.commands, ...y.commands] })); +const waitGateway = async () => { + const t0 = Date.now(); + for (;;) { try { const r = await fetch(`http://127.0.0.1:${gport}/`); if (r) break; } catch {} if (Date.now() - t0 > 60000) throw new Error("gateway never listened"); await sleep(200); } + return Date.now() - t0; +}; + +let a; +const start = async () => { + if (setup.gateway && !gateway) { + gateway = agent(setup.gateway.cmd, setup.gateway.args, { env: setup.gateway.env, cwd: `${work}/cwd`, log: `${work}/gateway.log` }); + out("gateway listening ms", await waitGateway()); + } + const t0 = Date.now(); + a = agent(setup.cmd, setup.args, { env: setup.env, cwd: `${work}/cwd`, log: `${work}/agent.log` }); + const init = await a.call("initialize", { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, clientInfo: { name: "thm-acp-spike", version: "0" } }); + return { ms: Date.now() - t0, init }; +}; +const prompt = async (sessionId, text) => { + const t0 = Date.now(), n = a.updates.length; + const r = await a.call("session/prompt", { sessionId, prompt: [{ type: "text", text }] }); + const ups = a.updates.slice(n); + const reply = ups.filter((u) => u.sessionUpdate === "agent_message_chunk").map((u) => u.content?.text ?? "").join(""); + return { ms: Date.now() - t0, stopReason: r.stopReason, usage: r.usage ?? r._meta?.usage ?? null, meta: r._meta ? Object.keys(r._meta) : [], reply: reply.slice(0, 80), updates: [...new Set(ups.map((u) => u.sessionUpdate))], usageUpdates: ups.filter((u) => /usage/i.test(u.sessionUpdate)).map((u) => u.used ?? u.usage ?? u) }; +}; + +try { + const s = await start(); + out("cold start to initialize ms", s.ms); + out("agent capabilities", s.init.agentCapabilities); + let t0 = Date.now(); + const sess = await a.call("session/new", { cwd: `${work}/cwd`, mcpServers: setup.mcp, ...(setup.meta ? { _meta: setup.meta } : {}) }); + out("session/new ms", Date.now() - t0); + out("session/new keys", Object.keys(sess)); + const id = sess.sessionId; + if (setup.mode) { await a.call("session/set_mode", { sessionId: id, modeId: setup.mode }); out("mode", setup.mode); } + out("warm PLAIN", await prompt(id, "PLAIN")); + let n = fx().length; + const tool = await prompt(id, "CALLTOOL"); + out("CALLTOOL", tool); + out("hive tool calls by seat", fx(n).filter((x) => x.rpc === "tools/call").map((x) => x.seat)); + out("tools the model was offered", fx(n).find((x) => x.kind === "model")?.tools); + out("permission requests so far", a.requests.map((r) => r.method)); + await sleep(10000); out("idle memory (10 s)", mem()); + for (const k of ["PLAIN", "CALLTOOL"]) { const d = []; for (let i = 0; i < 5; i++) d.push((await prompt(id, k)).ms); out(`${k} ms`, { runs: d, median: median(d) }); } + out("memory after 13 turns", mem()); + n = fx().length; + const slow = a.call("session/prompt", { sessionId: id, prompt: [{ type: "text", text: "SLOW" }] }); + while (!fx(n).some((x) => x.kind === "model" && x.key === "SLOW")) await sleep(50); + await sleep(300); t0 = Date.now(); a.notify("session/cancel", { sessionId: id }); + const cancelled = await Promise.race([slow.then((r) => r.stopReason, (e) => "error: " + e.message), sleep(15000).then(() => "no answer in 15 s")]); + await sleep(1000); + out("cancel", { stopReason: cancelled, answeredAfterMs: Date.now() - t0 - 1000, modelCallClosedAfterMs: fx(n).filter((x) => x.kind === "model-disconnect").map((x) => x.t - t0) }); + // Restart the agent (not the gateway) and resume the session. + const pids = tree(a.child.pid); a.child.stdin.end(); process.kill(-a.child.pid, "SIGTERM"); + await Promise.race([a.exited, sleep(5000)]); for (const p of pids) try { process.kill(p, "SIGKILL"); } catch {} + const s2 = await start(); + if (s.init.agentCapabilities?.loadSession) { + try { await a.call("session/load", { sessionId: id, cwd: `${work}/cwd`, mcpServers: setup.mcp, ...(setup.meta ? { _meta: setup.meta } : {}) }); out("resumed after restart", await prompt(id, "PLAIN")); } + catch (e) { out("resume failed", e.rpc ?? e.message); } + } else out("resume", "agent does not offer loadSession"); + // kill -9 mid-turn: what is left, and does a new agent replay the turn? + const id2 = (await a.call("session/new", { cwd: `${work}/cwd`, mcpServers: setup.mcp, ...(setup.meta ? { _meta: setup.meta } : {}) })).sessionId; + if (setup.mode) await a.call("session/set_mode", { sessionId: id2, modeId: setup.mode }); + n = fx().length; a.call("session/prompt", { sessionId: id2, prompt: [{ type: "text", text: "SLOW" }] }).catch(() => {}); + while (!fx(n).some((x) => x.kind === "model" && x.key === "SLOW")) await sleep(50); + const before = tree(a.child.pid); process.kill(a.child.pid, "SIGKILL"); await sleep(2000); + out("left after kill -9 of the agent", before.filter((p) => fs.existsSync(`/proc/${p}`)).length); + for (const p of before) try { process.kill(p, "SIGKILL"); } catch {} + n = fx().length; await start(); await sleep(15000); + // The interrupted session is not loaded: this shows only what a new agent + // does when it starts, not whether loading that session replays its turn. + out("model calls a new agent made on its own within 15 s (session not loaded)", fx(n).filter((x) => x.kind === "model").length); +} catch (e) { + out("error", e.rpc ?? e.message); +} finally { + for (const h of [a, gateway]) if (h) { for (const p of tree(h.child.pid)) try { process.kill(p, "SIGKILL"); } catch {} } + process.exit(0); +} diff --git a/docs/experiments/README.md b/docs/experiments/README.md index 8deba87e..70c0bad6 100644 --- a/docs/experiments/README.md +++ b/docs/experiments/README.md @@ -26,6 +26,7 @@ does. | date | question | answer | | --- | --- | --- | | [2026-11-25](2026-11-25-process-harnesses.md) | Can OpenHuman, OpenClaw and Codex run as child processes in a hive? | Yes against a scripted model: each called a hive tool as the right seat, resumed and cancelled. OpenClaw replays a crashed turn and costs over 1 GB, and a linked baseline was measured but is not like for like | +| [2026-11-26](2026-11-26-acp-harnesses.md) | Can Claude Code, Codex and OpenClaw run as hive seats over ACP? | Yes against a scripted model, each after one setting: Claude Code's built-in tools off, Codex's auto review off. OpenClaw reports no usage over ACP and costs about 2 GB; the adapters roughly double a Codex seat's memory | | [2026-10-11](2026-10-11-euler-hive-live.md) | Can a hive defined entirely in the hive language attempt live Euler problems with web search, sandboxed Python and CortexDB memory? | Yes for the design problem: correct on both full runs, about $0.40 each. The harder equilibrium problem reproduced every sample but never reached the right sum: two runs committed wrong answers. The runs exposed host defects, now fixed and tested. With the fixes in place, verify objected to the wrong value and the run ended `no_decision`. | | [2026-10-11](2026-10-11-math-hive-scale.md) | Offline, does a math hive decide better at one, five, or fifty seats? | Swarm of 50 was right on 50/50 seeds, one seat on 64%, and the five-seat panel on 58%: 28% of panel runs exhausted their budget. The swarm also has exact residue seats the panel lacks, so size alone is not isolated | | [2026-10-10](2026-10-10-live-hive-language.md) | Can a live model propose a guarded hive edit and evaluate the lowered candidate? | Three repeated smoke runs accepted a 3/3 correction and rejected a 0/3 negative control; lineage and immutable-setting guards held. | diff --git a/docs/specs/harnesses.md b/docs/specs/harnesses.md index 92e8b97c..631a4ac9 100644 --- a/docs/specs/harnesses.md +++ b/docs/specs/harnesses.md @@ -42,7 +42,7 @@ embeddable agent runtime, and Codex is a command-line program. ## Vocabulary -- **Harness kind:** `openhuman`, `openclaw` or `codex`. +- **Harness kind:** `openhuman`, `openclaw`, `codex` or `claude-code`. - **Instance:** one supervised process tree and its private state directory. - **Turn:** one coordinator reservation, identified by `TurnRequest.turn_id`. @@ -51,6 +51,7 @@ embeddable agent runtime, and Codex is a command-line program. | `openhuman` | `openhuman-core run --headless-api`: JSON-RPC, SSE | one | | `openclaw` | `openclaw gateway`: WebSocket protocol 4 | one deployment, or one seat if `isolation` is `seat` | | `codex` | `codex app-server`: JSON-RPC over stdio | one | +| `claude-code` | `claude --print --input-format stream-json --output-format stream-json`: newline-delimited JSON over stdio | one | OpenHuman needs one instance per seat because `web_chat` takes its agent from process configuration. Codex does not need it for tool identity; it is the @@ -132,34 +133,35 @@ layer that sets `limits.iterations`. No built-in tool can be turned on, so no hook can match one; `check` does not inspect hook matchers for built-in tool names. -| Field | openhuman | openclaw | codex | -| --- | --- | --- | --- | -| prompt, model name, hive and executable tools, limits.timeout_ms | yes | yes | yes | -| provider `openai` with an explicit `endpoint`, no `credential` | Chat Completions | Chat Completions | Responses API | -| provider `openai` without an `endpoint` | rejected | rejected | rejected | -| provider `openrouter`, `anthropic` | rejected | rejected | rejected | -| provider `inherit`, or no provider at all | rejected | rejected | rejected | -| provider `credential` | rejected | rejected | rejected | -| hooks and permissions on hive and executable tools | yes, host side | yes, host side | yes, host side | -| `sandbox` `none` or absent, on `runtime` and `permissions` | yes | yes | yes | -| `sandbox` `read_only` or `sandboxed` | rejected | rejected | rejected | -| `autonomy` and `permissions.access` | yes, host side | yes, host side | yes, host side | -| built-in tool groups | off | off | off | -| `tool_rules` on built-in tools | rejected until a release has them | rejected | rejected | -| hooks on built-in tools | rejected | rejected | rejected | -| package MCP servers | through the host server | through the host server | through the host server | -| `session_store = "host"`, `memory_engine = "host"` | rejected | rejected | rejected | -| subagents, `definition_base`, `jev`, `session` tuning | rejected at first | rejected | rejected | -| workflows | coordinator schedule | coordinator schedule | coordinator schedule | -| `limits.iterations` | up to the cap below | rejected | rejected | -| skills, `include_user_skills` | rejected | rejected | rejected | -| `limits.budget_usd`, a model's `temperature` and `max_tokens` | rejected | rejected | rejected | -| `bare_prompt`, a seat's `config` and `agent_id` | rejected | rejected | rejected | -| tool allow and deny lists (`tools`, `allow_tools`, `deny_tools`) | rejected | rejected | rejected | -| `send_destinations`, `send_operations` | rejected | rejected | rejected | -| `stop` hooks | rejected | rejected | rejected | -| `runtime` `workspace`, `deployment_id`, `max_agents`, a non-default `concurrency` | rejected | rejected | rejected | -| `session_store = "sqlite"`, `memory_engine = "memory"` | rejected | rejected | rejected | +| Field | openhuman | openclaw | codex | claude-code | +| --- | --- | --- | --- | --- | +| prompt, model name, hive and executable tools, limits.timeout_ms | yes | yes | yes | yes | +| provider `openai` with an explicit `endpoint`, no `credential` | Chat Completions | Chat Completions | Responses API | rejected: Messages API only | +| provider `anthropic` with an explicit `endpoint`, no `credential` | rejected | rejected | rejected | Messages API | +| provider `openai` without an `endpoint` | rejected | rejected | rejected | rejected | +| provider `openrouter`, or `anthropic` without an `endpoint` | rejected | rejected | rejected | rejected | +| provider `inherit`, or no provider at all | rejected | rejected | rejected | rejected | +| provider `credential` | rejected | rejected | rejected | rejected | +| hooks and permissions on hive and executable tools | yes, host side | yes, host side | yes, host side | yes, host side | +| `sandbox` `none` or absent, on `runtime` and `permissions` | yes | yes | yes | yes | +| `sandbox` `read_only` or `sandboxed` | rejected | rejected | rejected | rejected | +| `autonomy` and `permissions.access` | yes, host side | yes, host side | yes, host side | yes, host side | +| built-in tool groups | off | off | off | off | +| `tool_rules` on built-in tools | rejected until a release has them | rejected | rejected | rejected | +| hooks on built-in tools | rejected | rejected | rejected | rejected | +| package MCP servers | through the host server | through the host server | through the host server | through the host server | +| `session_store = "host"`, `memory_engine = "host"` | rejected | rejected | rejected | rejected | +| subagents, `definition_base`, `jev`, `session` tuning | rejected at first | rejected | rejected | rejected | +| workflows | coordinator schedule | coordinator schedule | coordinator schedule | coordinator schedule | +| `limits.iterations` | up to the cap below | rejected | rejected | rejected | +| skills, `include_user_skills` | rejected | rejected | rejected | rejected | +| `limits.budget_usd`, a model's `temperature` and `max_tokens` | rejected | rejected | rejected | rejected | +| `bare_prompt`, a seat's `config` and `agent_id` | rejected | rejected | rejected | rejected | +| tool allow and deny lists (`tools`, `allow_tools`, `deny_tools`) | rejected | rejected | rejected | rejected | +| `send_destinations`, `send_operations` | rejected | rejected | rejected | rejected | +| `stop` hooks | rejected | rejected | rejected | rejected | +| `runtime` `workspace`, `deployment_id`, `max_agents`, a non-default `concurrency` | rejected | rejected | rejected | rejected | +| `session_store = "sqlite"`, `memory_engine = "memory"` | rejected | rejected | rejected | rejected | Built-in tools start **off** for every kind. Turning one on is a later change that must first show its permissions are enforced. "Off" is the rule for every