diff --git a/.github/scripts/assert-pure.sh b/.github/scripts/assert-pure.sh index 3d5b9ac9..caa4cb5d 100755 --- a/.github/scripts/assert-pure.sh +++ b/.github/scripts/assert-pure.sh @@ -17,10 +17,10 @@ set -euo pipefail # whose vocabulary dependency includes `anyhow` and `async-trait`. pure_crates=("tinyhivemind-core" "tinyhivemind-lang") tool_crates=("tinyhivemind-tools") -# Host runs harnesses as processes (ADR 0035), and the MCP server serves them -# hive tools over loopback (ADR 0036), so both may hold a runtime and a -# listener, but neither may link a harness. -host_crates=("tinyhivemind-host" "tinyhivemind-mcp") +# Host and the process harness clients 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") 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. @@ -40,7 +40,9 @@ check_crate() { echo "assert-pure: cargo tree failed for '$crate'" >&2 exit 1 } - found="$(grep -Ei "^(${forbidden})(-embed)? v" <<<"$tree" || true)" + # The crate's own line is not a dependency: `tinyhivemind-openhuman-process` + # is named like the forbidden linked adapter's family. + found="$(grep -Ei "^(${forbidden})(-embed)? v" <<<"$tree" | grep -v "^${crate} v" || true)" if [ -n "$found" ]; then echo "$crate pulled in a dependency its manifest forbids:" >&2 echo "$found" >&2 @@ -64,7 +66,8 @@ if [ "$status" -ne 0 ]; then echo "A pure crate is linked into the hot path of every agent turn and must" >&2 echo "compile in a host's default build. It must stay free of async" >&2 echo "runtimes, transports, HTTP clients and web frameworks. The host crate" >&2 - echo "runs harnesses as processes and must link none (ADR 0035)." >&2 + echo "and the process harness clients run harnesses as processes and must" >&2 + echo "link none (ADR 0035)." >&2 exit 1 fi diff --git a/.github/scripts/fetch-harness.sh b/.github/scripts/fetch-harness.sh new file mode 100755 index 00000000..9ba36f5a --- /dev/null +++ b/.github/scripts/fetch-harness.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +# fetch-harness.sh [target] +# +# Fetch the harness binary `harnesses.lock` pins for and +# (default: this machine's), verify it, and print the binary's absolute path. +# The asset's sha256 must match the lock, and so must the binary's where the +# lock records it. Nothing is installed or run; the library takes the path. +# +# THM_OPENHUMAN_CORE=$(.github/scripts/fetch-harness.sh openhuman target/harness) +set -euo pipefail + +kind="${1:?usage: fetch-harness.sh [target]}" +dest="${2:?usage: fetch-harness.sh [target]}" +target="${3:-$(uname -m)-unknown-linux-gnu}" +root="$(cd "$(dirname "$0")/../.." && pwd)" +lock="$root/harnesses.lock" + +# The entry of the lock for this kind and target, as `key=value` lines. +entry="$(awk -v kind="[[$kind]]" -v target="$target" ' + $0 == kind { inside = 1; delete fields; next } + /^\[\[/ { inside = 0 } + inside && /^[a-z_0-9]+ = "/ { + key = $1; value = $0; sub(/^[^"]*"/, "", value); sub(/"[^"]*$/, "", value) + fields[key] = value + if (key == "binary" && fields["target"] == target) { + for (k in fields) print k "=" fields[k] + } + } + inside && /^binary_sha256 = / && fields["target"] == target { print "binary_sha256=" fields["binary_sha256"] } +' "$lock" | sort -u)" +# One entry per kind and target: two would leave the pin ambiguous. +count="$(awk -v kind="[[$kind]]" -v target="target = \"$target\"" ' + $0 == kind { inside = 1; next } + /^\[\[/ { inside = 0 } + inside && $0 == target { n++ } + END { print n + 0 } +' "$lock")" +if [ "$count" -gt 1 ]; then + echo "fetch-harness: harnesses.lock has $count $kind entries for $target" >&2 + exit 1 +fi +field() { sed -n "s/^$1=//p" <<<"$entry"; } +url="$(field url)"; sha="$(field sha256)"; version="$(field version)" +binary="$(field binary)"; binary_sha="$(field binary_sha256)" +if [ -z "$url" ] || [ -z "$sha" ] || [ -z "$binary" ]; then + echo "fetch-harness: no $kind entry for $target in harnesses.lock" >&2 + exit 1 +fi + +mkdir -p "$dest" +dest="$(cd "$dest" && pwd)" +asset="$dest/$(basename "$url")" +if ! echo "$sha $asset" | sha256sum -c --status >/dev/null 2>&1; then + curl -fsSL --proto '=https' --proto-redir '=https' -o "$asset.partial" "$url" + mv "$asset.partial" "$asset" +fi +if ! echo "$sha $asset" | sha256sum -c --status; then + echo "fetch-harness: $asset does not have the sha256 harnesses.lock pins" >&2 + rm -f "$asset" + exit 1 +fi + +unpacked="$dest/$kind-$version-$target" +rm -rf "$unpacked" && mkdir -p "$unpacked" +tar -xzf "$asset" -C "$unpacked" +path="$(find "$unpacked" -type f -name "$binary" | head -n 1)" +if [ -z "$path" ]; then + echo "fetch-harness: $asset holds no $binary" >&2 + exit 1 +fi +if [ -n "$binary_sha" ] && ! echo "$binary_sha $path" | sha256sum -c --status; then + echo "fetch-harness: $path does not have the sha256 harnesses.lock pins" >&2 + exit 1 +fi +echo "$path" diff --git a/AGENTS.md b/AGENTS.md index ca42fa76..92d6a37b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,6 +78,7 @@ crates/ ├── tinyhivemind-host/ # hive tool belt, policies, package plans, harness processes ├── 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-hives/ # durable cross-hive coordinator └── tinyhivemind-lang/ # pure hive packages: structure, integrations, edits, lineage wiki/ # GitHub wiki submodule @@ -99,6 +100,9 @@ permissions, profiles, hooks, session, Jev, features and workflows — as data, and lowering resolves it per seat; it names no harness type and starts no process. `tinyhivemind-exec` runs those executable tools and hooks (`docs/specs/executable-tools.md`) and is not one of the pure crates. +`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-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 5d1653f2..eb91c961 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3641,6 +3641,23 @@ dependencies = [ "wiremock", ] +[[package]] +name = "tinyhivemind-openhuman-process" +version = "0.2.1" +dependencies = [ + "anyhow", + "reqwest", + "rustix 1.1.5", + "serde_json", + "tempfile", + "thiserror", + "tinyhivemind-hives", + "tinyhivemind-host", + "tinyhivemind-lang", + "tokio", + "toml 0.8.23", +] + [[package]] name = "tinyhivemind-tools" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index 6752b7e6..43aa7041 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"] +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"] # `worktrees/` holds `git worktree` checkouts of this same repository; each # contains a full copy of this manifest. Keep them excluded from Cargo # workspace discovery. @@ -48,6 +48,14 @@ http-body-util = "0.1" subtle = { version = "2", default-features = false, features = ["std"] } # Random per-seat bearers, from the operating system. getrandom = "0.3" +# The HTTP client process harness clients speak to a harness's loopback API +# with: JSON-RPC posts and a Server-Sent Events stream. Default features off, +# so no TLS stack, no HTTP/2 and no proxy lookup from the environment: every +# URL is `http://127.0.0.1`, and a proxy must never see a seat's token. It is +# already in this lockfile through the linked OpenHuman tree and `wiremock`, +# and it is `MIT OR Apache-2.0`. Its streaming `Response::chunk` is all SSE +# needs, so the `stream` feature is not taken either. +reqwest = { version = "0.12", default-features = false } # Durable cross-hive coordinator used at the harness boundary. tinyhivemind-hives = { path = "crates/tinyhivemind-hives" } # Concurrent owned runner futures in the coordinator, outside core. diff --git a/crates/tinyhivemind-host/src/harness/error.rs b/crates/tinyhivemind-host/src/harness/error.rs index 04531839..e4bb45cc 100644 --- a/crates/tinyhivemind-host/src/harness/error.rs +++ b/crates/tinyhivemind-host/src/harness/error.rs @@ -15,6 +15,10 @@ pub enum Error { /// The started instance is not what was asked for. #[error(transparent)] Mismatch(#[from] Mismatch), + /// The seat asks for something this harness cannot honour, so it is not + /// started. The client's own error says what, and may be downcast to it. + #[error("the seat cannot run on this harness: {0}")] + Refused(#[source] Box), /// The harness refused a call, broke its protocol or went away. #[error("harness failed: {0}")] Harness(String), diff --git a/crates/tinyhivemind-host/src/harness/test/payloads.rs b/crates/tinyhivemind-host/src/harness/test/payloads.rs index a4d0c02f..3ba19ed1 100644 --- a/crates/tinyhivemind-host/src/harness/test/payloads.rs +++ b/crates/tinyhivemind-host/src/harness/test/payloads.rs @@ -171,3 +171,17 @@ fn a_port_error_reaches_the_coordinator_as_its_own_message() { }; assert!(resume.to_string().contains("s1")); } + +#[test] +fn a_refused_seat_keeps_the_clients_own_error() { + let reason = std::io::Error::other("no provider"); + let error = Error::Refused(Box::new(reason)); + assert_eq!( + error.to_string(), + "the seat cannot run on this harness: no provider" + ); + let Error::Refused(source) = error else { + unreachable!("built as refused") + }; + assert!(source.downcast_ref::().is_some()); +} diff --git a/crates/tinyhivemind-openhuman-process/Cargo.toml b/crates/tinyhivemind-openhuman-process/Cargo.toml new file mode 100644 index 00000000..04173e7e --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/Cargo.toml @@ -0,0 +1,72 @@ +[package] +name = "tinyhivemind-openhuman-process" +description = "Hive seats on OpenHuman as supervised `openhuman-core` child processes, through its JSON-RPC and event stream." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +readme = "README.md" +publish = false +# This crate names no OpenHuman type and links no harness (ADR 0035): it talks +# to a pinned `openhuman-core` binary over loopback HTTP. It is a crate of its +# own, not a module of `tinyhivemind-openhuman`, so that removing the linked +# adapter and `vendor/openhuman` deletes that crate without touching this one. +# `.github/scripts/assert-pure.sh` asserts that no harness enters its graph. + +[features] +# The host's conformance suite, and the scripted fake `openhuman-core` it runs +# against, which has to be a real process and so is a binary. +conformance = ["tinyhivemind-host/conformance", "dep:toml", "dep:rustix"] + +[[bin]] +name = "tinyhivemind-fake-openhuman" +path = "tests/fake/child.rs" +required-features = ["conformance"] +test = false +doc = false + +[[test]] +name = "conformance" +required-features = ["conformance"] + +[[test]] +name = "live" +required-features = ["conformance"] + +[dependencies] +# The harness port, seat runner, verification and process supervision. +tinyhivemind-host.workspace = true +# `AgentRunner`, `TurnRequest` and `TurnOutcome`. +tinyhivemind-hives.workspace = true +# The lowered seat and its provider, which decide what may be written. +tinyhivemind-lang.workspace = true +# Loopback JSON-RPC and the `/events` stream. +reqwest.workspace = true +# Request and event payloads, and the effective config. +serde_json.workspace = true +# Typed errors. +thiserror.workspace = true +# Deadlines, the seat's locks and the close signal of a running turn. +tokio = { workspace = true, features = ["time", "sync", "macros", "rt", "net", "io-util"] } +# The fake child reads the config the runner wrote, as `openhuman-core` does. +toml = { version = "0.8", optional = true } +# The fake child's grandchild leaves its session with `setsid`; the workspace +# forbids `unsafe`, so `std`'s `pre_exec` is out. Already in the lockfile. +rustix = { version = "1.1", default-features = false, features = ["std", "process"], optional = true } + +[dev-dependencies] +tinyhivemind-host = { workspace = true, features = ["conformance"] } +# Fallible tests over several error types. +anyhow.workspace = true +# Async tests, and the in-process fake's listener. +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "net", "io-util", "time", "sync", "process"] } +# Seat and control directories. +tempfile.workspace = true +# The in-process fake reads the written config. +toml = "0.8" +# Killing a seat's child in the conformance suite. +rustix = { version = "1.1", default-features = false, features = ["std", "process"] } + +[lints] +workspace = true diff --git a/crates/tinyhivemind-openhuman-process/README.md b/crates/tinyhivemind-openhuman-process/README.md new file mode 100644 index 00000000..2a66aa55 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/README.md @@ -0,0 +1,21 @@ +# tinyhivemind-openhuman-process + +Hive seats on OpenHuman without linking it: each seat is one supervised +`openhuman-core run --headless-api`, pinned by version and checksum, driven +over its loopback JSON-RPC and event stream. A seat starts only once the +running instance is shown to be the child that was started, at the pinned +version, with the config that was written, offering its model exactly the +hive's tools. + +It implements the `openhuman` kind of the harness port in +[`tinyhivemind-host`](../tinyhivemind-host/README.md), names no OpenHuman type, +and is a crate of its own so that the linked +[`tinyhivemind-openhuman`](../tinyhivemind-openhuman/README.md) adapter and +`vendor/openhuman` can be deleted without touching it. +[The spec](../../docs/specs/harnesses.md) says what a seat may ask for; the +repository [README](../../README.md) says how this fits the rest. + +| Path | Purpose | +| --- | --- | +| [`src/`](src/README.md) | The crate's modules | +| [`tests/`](tests/README.md) | Conformance over a fake child, and `live_*` on the pin | diff --git a/crates/tinyhivemind-openhuman-process/src/README.md b/crates/tinyhivemind-openhuman-process/src/README.md new file mode 100644 index 00000000..b515e2cc --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/README.md @@ -0,0 +1,13 @@ +# Source + +| Path | Purpose | +| --- | --- | +| `lib.rs` | Crate overview and public surface: `OpenHumanHarness`, `Program`, `Options`, `capability`. | +| [`error/`](error/README.md) | The crate's internal `Error`, and how it reaches the port as `harness::Error`. | +| `fixture.rs` | Unit tests only: the in-process fake surface with a written config, and a client. | +| [`capability/`](capability/README.md) | What a lowered seat may ask of this harness: `check`, `Refusal`, `SeatModel`. | +| [`config/`](config/README.md) | The generated `config.toml`, and comparing an effective config with it. | +| [`rpc/`](rpc/README.md) | The loopback client: JSON-RPC, `/health`, `/events`. | +| [`turn/`](turn/README.md) | One turn over `channel_web_chat` and its events; cancellation. | +| [`instance/`](instance/README.md) | Launching an instance, tool discovery, start-up verification. | +| [`harness/`](harness/README.md) | `OpenHumanHarness` and the seat it runs. | diff --git a/crates/tinyhivemind-openhuman-process/src/capability/README.md b/crates/tinyhivemind-openhuman-process/src/capability/README.md new file mode 100644 index 00000000..6116752e --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/capability/README.md @@ -0,0 +1,22 @@ +# Capability + +`check` holds a `LoweredSeat` to the `openhuman` column of the capability +table in [the spec](../../../../docs/specs/harnesses.md#capabilities) and +returns the `SeatModel` the config is written from, or the first `Refusal`. + +- Providers: only `openai` with an explicit endpoint and no credential. No + model, no provider (inherit), `inherit`, `openrouter`, `anthropic`, a missing + endpoint and a credential are each a `Refusal`. +- `temperature` and `max_tokens` are refused: nothing proves the binary honours them. +- `limits.iterations` above `ITERATION_CAP` (8) is refused; below it, a turn + past the limit fails. `limits.budget_usd` is refused. +- A sandbox other than `none`, a built-in tool group not `off`, `memory`, + `agent_id`, `definition_base`, `subagents`, `skills`, `context` and + `bare_prompt` are refused. +- Hive and executable tools, hooks, permissions other than `sandbox`, + `autonomy`, `access` and package MCP servers are host side and not judged here. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `check`, `Refusal`, `SeatModel`, `ITERATION_CAP` | +| `test.rs` | Every row and refusal | diff --git a/crates/tinyhivemind-openhuman-process/src/capability/mod.rs b/crates/tinyhivemind-openhuman-process/src/capability/mod.rs new file mode 100644 index 00000000..b976ba09 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/capability/mod.rs @@ -0,0 +1,203 @@ +//! What a lowered seat may ask of an `OpenHuman` process, and what it gets. +//! +//! [`check`] reads a [`LoweredSeat`] against the `openhuman` column of the +//! capability table in `docs/specs/harnesses.md` and returns the [`SeatModel`] +//! the generated config is written from, or the first [`Refusal`]. Everything +//! the spec marks "host side" (hive and executable tools, hooks, permission +//! layers other than `sandbox`, `autonomy`, `access`, package MCP servers) is +//! the MCP server's business and is not judged here. +use tinyhivemind_lang::{GroupMode, LoweredSeat, ProviderKind, Sandbox}; + +/// Model iterations after which the released binary ends a custom agent's +/// turn, reporting it as a normal end. +pub const ITERATION_CAP: usize = 8; + +/// The one provider route a seat runs on. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SeatModel { + /// The provider's id in the package, for messages. + pub provider: String, + /// The Chat Completions base URL, as declared. + pub endpoint: String, + /// The provider's model name. + pub model: String, + /// Most model iterations a turn may start, at most [`ITERATION_CAP`]. + pub iterations: usize, +} + +/// Why a seat cannot run on this harness. Each names the field. +#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] +#[non_exhaustive] +pub enum Refusal { + /// The seat resolves to no model at all. + #[error("the seat names no model")] + NoModel, + /// The model has no provider, so it would inherit one; a child process + /// has none and never falls back to its own. + #[error("model {model} names no provider, and a process harness has none to inherit")] + NoProvider { + /// The model's id. + model: String, + }, + /// The provider's kind is not one this harness has been shown to run. + #[error("provider {provider} is of kind {kind}, which this harness does not run")] + ProviderKind { + /// The provider's id. + provider: String, + /// Its kind, as a package names it. + kind: &'static str, + }, + /// An `openai` provider without an explicit endpoint. + #[error("provider {provider} has no endpoint")] + NoEndpoint { + /// The provider's id. + provider: String, + }, + /// A provider credential, which no conformance test has proven yet. + #[error("provider {provider} has a credential, which this harness does not take yet")] + Credential { + /// The provider's id. + provider: String, + }, + /// A model setting the generated config cannot carry. + #[error("model {model} sets {setting}, which this harness does not take")] + ModelSetting { + /// The model's id. + model: String, + /// `temperature` or `max_tokens`. + setting: &'static str, + }, + /// More iterations than the binary runs. + #[error("the seat asks for {asked} iterations, more than the {cap} this harness runs")] + Iterations { + /// What the seat asked for. + asked: usize, + /// [`ITERATION_CAP`]. + cap: usize, + }, + /// A spend limit, which nothing here can enforce. + #[error("the seat sets limits.budget_usd, which this harness cannot enforce")] + Budget, + /// A sandbox, which would not reach the executable tools the host serves. + #[error("permission set {permission} asks for a sandbox, which this harness cannot provide")] + Sandbox { + /// The permission set's id. + permission: String, + }, + /// Built-in tools, which start off for every process harness. + #[error("the seat turns on built-in tool group {group}")] + ToolGroup { + /// The group. + group: String, + }, + /// A field this harness does not take at all yet. + #[error("the seat sets {0}, which this harness does not take")] + Unsupported(&'static str), +} + +/// What `seat` runs on, if this harness can honour all of it. +/// +/// # Errors +/// The first [`Refusal`], provider rows first. +pub fn check(seat: &LoweredSeat) -> Result { + let integration = &seat.integration; + let lowered = integration.model.as_ref().ok_or(Refusal::NoModel)?; + let model = &lowered.model; + let provider = lowered + .provider + .as_ref() + .ok_or_else(|| Refusal::NoProvider { + model: model.id.clone(), + })?; + let kind = match provider.kind { + ProviderKind::Openai => None, + ProviderKind::Inherit => Some("inherit"), + ProviderKind::Openrouter => Some("openrouter"), + ProviderKind::Anthropic => Some("anthropic"), + }; + if let Some(kind) = kind { + return Err(Refusal::ProviderKind { + provider: provider.id.clone(), + kind, + }); + } + let endpoint = provider + .endpoint + .clone() + .filter(|endpoint| !endpoint.trim().is_empty()) + .ok_or_else(|| Refusal::NoEndpoint { + provider: provider.id.clone(), + })?; + if provider.credential.is_some() { + return Err(Refusal::Credential { + provider: provider.id.clone(), + }); + } + for (set, setting) in [ + (model.temperature.is_some(), "temperature"), + (model.max_tokens.is_some(), "max_tokens"), + ] { + if set { + return Err(Refusal::ModelSetting { + model: model.id.clone(), + setting, + }); + } + } + let iterations = integration.limits.iterations.unwrap_or(ITERATION_CAP); + if iterations > ITERATION_CAP { + return Err(Refusal::Iterations { + asked: iterations, + cap: ITERATION_CAP, + }); + } + if integration.limits.budget_usd.is_some() { + return Err(Refusal::Budget); + } + unsupported(seat)?; + Ok(SeatModel { + provider: provider.id.clone(), + endpoint, + model: model.name.clone(), + iterations, + }) +} + +/// Everything else the table rejects for this kind. +fn unsupported(seat: &LoweredSeat) -> Result<(), Refusal> { + let integration = &seat.integration; + if let Some(set) = integration + .permissions + .iter() + .find(|set| set.sandbox != Sandbox::None) + { + return Err(Refusal::Sandbox { + permission: set.id.clone(), + }); + } + if let Some((group, _)) = integration + .groups + .iter() + .find(|(_, mode)| **mode != GroupMode::Off) + { + return Err(Refusal::ToolGroup { + group: group.clone(), + }); + } + let fields = [ + (seat.memory.is_some(), "memory"), + (integration.agent_id.is_some(), "agent_id"), + (integration.definition_base.is_some(), "definition_base"), + (!integration.subagents.is_empty(), "subagents"), + (!integration.skills.is_empty(), "skills"), + (!integration.context.is_empty(), "context"), + (integration.bare_prompt, "bare_prompt"), + ]; + match fields.into_iter().find(|(set, _)| *set) { + Some((_, field)) => Err(Refusal::Unsupported(field)), + None => Ok(()), + } +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-openhuman-process/src/capability/test.rs b/crates/tinyhivemind-openhuman-process/src/capability/test.rs new file mode 100644 index 00000000..e010bd8b --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/capability/test.rs @@ -0,0 +1,238 @@ +//! The `openhuman` column of the capability table, row by row. +use super::{ITERATION_CAP, Refusal, SeatModel, check}; +use tinyhivemind_lang::{ + GroupMode, LoweredModel, LoweredSeat, LoweredSeatIntegration, Model, PermissionSet, Provider, + ProviderKind, Sandbox, SecretRef, +}; + +/// A seat on `openai` at an explicit endpoint, with nothing else set. +pub(crate) fn seat() -> LoweredSeat { + let provider = Provider { + id: "local".into(), + kind: ProviderKind::Openai, + endpoint: Some("http://127.0.0.1:9/v1".into()), + credential: None, + }; + let model = Model { + id: "fast".into(), + provider: Some("local".into()), + name: "mock".into(), + ..Model::default() + }; + LoweredSeat { + id: "scout".into(), + label: "Scout".into(), + template: "seat".into(), + config: serde_json::Value::Null, + prompt: "You scout.".into(), + memory: None, + integration: LoweredSeatIntegration { + model: Some(LoweredModel { + model, + provider: Some(provider), + }), + ..LoweredSeatIntegration::default() + }, + } +} + +fn refused(change: impl FnOnce(&mut LoweredSeat)) -> Refusal { + let mut seat = seat(); + change(&mut seat); + match check(&seat) { + Err(refusal) => refusal, + Ok(model) => unreachable!("accepted {model:?}"), + } +} + +fn provider(seat: &mut LoweredSeat) -> &mut Provider { + let model = seat + .integration + .model + .as_mut() + .map(|model| &mut model.provider); + let provider = model.and_then(Option::as_mut); + provider.unwrap_or_else(|| unreachable!("the seat has a provider")) +} + +fn model(seat: &mut LoweredSeat) -> &mut Model { + let model = seat + .integration + .model + .as_mut() + .map(|model| &mut model.model); + model.unwrap_or_else(|| unreachable!("the seat has a model")) +} + +#[test] +fn openai_at_an_explicit_endpoint_without_a_credential_is_accepted() { + let accepted = check(&seat()); + let expected = SeatModel { + provider: "local".into(), + endpoint: "http://127.0.0.1:9/v1".into(), + model: "mock".into(), + iterations: ITERATION_CAP, + }; + assert_eq!(accepted, Ok(expected)); +} + +#[test] +fn every_other_provider_row_is_rejected() { + assert_eq!( + refused(|seat| seat.integration.model = None), + Refusal::NoModel + ); + let inherits = refused(|seat| { + if let Some(model) = &mut seat.integration.model { + model.provider = None; + } + }); + assert_eq!( + inherits, + Refusal::NoProvider { + model: "fast".into() + } + ); + for (kind, name) in [ + (ProviderKind::Inherit, "inherit"), + (ProviderKind::Openrouter, "openrouter"), + (ProviderKind::Anthropic, "anthropic"), + ] { + let refusal = refused(|seat| provider(seat).kind = kind); + let expected = Refusal::ProviderKind { + provider: "local".into(), + kind: name, + }; + assert_eq!(refusal, expected); + } + for endpoint in [None, Some(" ".to_owned())] { + let refusal = refused(|seat| provider(seat).endpoint = endpoint); + let expected = Refusal::NoEndpoint { + provider: "local".into(), + }; + assert_eq!(refusal, expected); + } + let credential = refused(|seat| provider(seat).credential = Some(SecretRef::Env("K".into()))); + let expected = Refusal::Credential { + provider: "local".into(), + }; + assert_eq!(credential, expected); +} + +#[test] +fn model_settings_the_config_cannot_carry_are_rejected() { + let temperature = refused(|seat| model(seat).temperature = Some(0.2)); + assert!(matches!( + temperature, + Refusal::ModelSetting { + setting: "temperature", + .. + } + )); + let tokens = refused(|seat| model(seat).max_tokens = Some(10)); + assert!(matches!( + tokens, + Refusal::ModelSetting { + setting: "max_tokens", + .. + } + )); +} + +#[test] +fn more_iterations_than_the_cap_are_rejected_and_fewer_are_kept() { + let refusal = refused(|seat| seat.integration.limits.iterations = Some(9)); + assert_eq!(refusal, Refusal::Iterations { asked: 9, cap: 8 }); + let mut fewer = seat(); + fewer.integration.limits.iterations = Some(3); + assert_eq!(check(&fewer).map(|model| model.iterations), Ok(3)); + let budget = refused(|seat| seat.integration.limits.budget_usd = Some(1.0)); + assert_eq!(budget, Refusal::Budget); +} + +#[test] +fn a_sandbox_and_built_in_tools_are_rejected() { + for sandbox in [Sandbox::ReadOnly, Sandbox::Sandboxed] { + let refusal = refused(|seat| { + let set = PermissionSet { + id: "tight".into(), + sandbox, + ..PermissionSet::default() + }; + seat.integration.permissions.push(set); + }); + let expected = Refusal::Sandbox { + permission: "tight".into(), + }; + assert_eq!(refusal, expected); + } + let mut none = seat(); + none.integration.permissions.push(PermissionSet::default()); + none.integration + .groups + .insert("shell".into(), GroupMode::Off); + assert!(check(&none).is_ok()); + for mode in [GroupMode::Advertised, GroupMode::Withheld] { + let refusal = refused(|seat| { + seat.integration.groups.insert("shell".into(), mode); + }); + let expected = Refusal::ToolGroup { + group: "shell".into(), + }; + assert_eq!(refusal, expected); + } +} + +#[test] +fn fields_this_harness_does_not_take_are_named() { + type Change = fn(&mut LoweredSeat); + let cases: [(&str, Change); 6] = [ + ("agent_id", |seat| { + seat.integration.agent_id = Some("a".into()); + }), + ("definition_base", |seat| { + seat.integration.definition_base = Some("b".into()); + }), + ("subagents", |seat| { + seat.integration.subagents.push("helper".into()); + }), + ("context", |seat| { + let document = ("notes.md".to_owned(), "text".to_owned()); + seat.integration.context.push(document); + }), + ("bare_prompt", |seat| seat.integration.bare_prompt = true), + ("skills", |seat| { + let skill = serde_json::json!({"id": "s"}); + let skill = serde_json::from_value(skill) + .unwrap_or_else(|error| unreachable!("a skill of an id and a path: {error}")); + seat.integration.skills.push(skill); + }), + ]; + for (field, change) in cases { + assert_eq!(refused(change), Refusal::Unsupported(field), "{field}"); + } + let memory = serde_json::from_value(serde_json::json!({ + "agent_id": "scout", "namespace": "agent:scout", "kind": "agent", "root": "", + "identity": {"id": "m", "namespace": "agent:scout", "kind": "agent", "lifecycle": "run"}, + "settings": {"seat": "scout", "identity": "m", "budget_chars": 100} + })) + .unwrap_or_else(|error| unreachable!("a memory binding: {error}")); + assert_eq!( + refused(|seat| seat.memory = Some(memory)), + Refusal::Unsupported("memory") + ); +} + +#[test] +fn refusals_read_as_lowercase_sentences_naming_the_field() { + let refusal = Refusal::Iterations { asked: 9, cap: 8 }; + assert_eq!( + refusal.to_string(), + "the seat asks for 9 iterations, more than the 8 this harness runs" + ); + let unsupported = Refusal::Unsupported("memory").to_string(); + assert_eq!( + unsupported, + "the seat sets memory, which this harness does not take" + ); +} diff --git a/crates/tinyhivemind-openhuman-process/src/config/README.md b/crates/tinyhivemind-openhuman-process/src/config/README.md new file mode 100644 index 00000000..a631082d --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/config/README.md @@ -0,0 +1,17 @@ +# Config + +The `config.toml` of a seat's instance, built as one JSON tree from the spike's +`config.toml.in` and written as TOML. `Written::settings` names every leaf +written plus `api_key`, `api_url` and `inference_url`, which must stay unset; +`Written::observe` reads the same paths from a `config_get` snapshot, cutting +lists of tables down to the keys written. The binary falls back to defaults on +TOML it cannot read, so that comparison is the only proof the config took. + +Not written: the top-level `embeddings_provider`, which 0.64.15 rewrites to +its hosted default on load whatever it says; memory is off, so nothing embeds. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `Input`, `Written`, `AGENT_ID`, the fixed settings and why | +| `toml.rs` | JSON as TOML, for the shapes the config has | +| `test.rs` | What the config says, that it parses back, and the comparison | diff --git a/crates/tinyhivemind-openhuman-process/src/config/mod.rs b/crates/tinyhivemind-openhuman-process/src/config/mod.rs new file mode 100644 index 00000000..62dae1b8 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/config/mod.rs @@ -0,0 +1,231 @@ +//! The `config.toml` a seat's instance runs with, and how its effective +//! config is compared with it. +//! +//! The config is built as one JSON tree from the experiment's +//! `docs/experiments/2026-11-25-process-harnesses/openhuman/config.toml.in`, +//! with the seat's provider, prompt and tools put in, and written as TOML. +//! The same tree is what [`Written::settings`] compares: every leaf that was +//! written, by its dotted path, plus the routes that must stay unset. The +//! binary silently falls back to its defaults on a config it cannot read, so +//! nothing else shows that it runs with this one. +//! +//! What is fixed, and why: +//! +//! - one cloud provider, `auth_style = "none"`, named by `primary_cloud` and by +//! every workload route, so the hosted provider is never consulted; +//! - one MCP server, the host's, with `expose = "direct"` and the seat's +//! bearer, so its tools are offered by name; +//! - one custom agent with an exact `tool_allowlist` and no denylist, because +//! `"*"` with a denylist let `mcp_call_tool` post as another seat; +//! - `auto_approve` exactly the hive tools, whose policy is the host's; +//! - memory, recall, conversation memory, search, hooks, suggestions and +//! token compression off, and tool-output compaction too: while it is on, +//! 0.64.15 adds `juice_retrieve` to every allowlist. +//! +//! The top-level `embeddings_provider` is not written: 0.64.15 rewrites any +//! value to its hosted default on load, and nothing embeds with memory off. +mod toml; + +use crate::capability::SeatModel; +use serde_json::{Map, Value, json}; + +/// The custom agent every seat's instance runs as. +pub(crate) const AGENT_ID: &str = "thm_seat"; +/// The provider's id and slug in the generated config. +const PROVIDER: &str = "thm"; +/// Effective settings that must stay unset: any of them is another route. +const UNSET: [&str; 3] = ["api_key", "api_url", "inference_url"]; + +/// What a seat's config is made of. +#[derive(Clone, Copy)] +pub(crate) struct Input<'a> { + /// The provider route. + pub(crate) model: &'a SeatModel, + /// The seat's id, which names its agent. + pub(crate) seat: &'a str, + /// The seat's system prompt. + pub(crate) prompt: &'a str, + /// The host's MCP server name. + pub(crate) server: &'a str, + /// Its URL. + pub(crate) url: &'a str, + /// The seat's bearer for it. + pub(crate) bearer: &'a str, + /// The model-visible names of the hive tools, which the allowlist and + /// `auto_approve` hold exactly. + pub(crate) tools: &'a [String], + /// How long the binary itself lets a turn run, in seconds. + pub(crate) turn_secs: u64, +} + +/// A config as written. +#[derive(Clone, PartialEq)] +pub(crate) struct Written { + tree: Value, +} + +impl std::fmt::Debug for Input<'_> { + /// The bearer and the prompt are not shown. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Input") + .field("seat", &self.seat) + .field("server", &self.server) + .field("url", &self.url) + .field("tools", &self.tools) + .field("bearer", &"redacted") + .finish_non_exhaustive() + } +} + +impl std::fmt::Debug for Written { + /// Setting names only: the values hold the bearer. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let names: Vec = self.settings().into_iter().map(|(name, _)| name).collect(); + f.debug_struct("Written").field("settings", &names).finish() + } +} + +impl Written { + /// The config for `input`. + pub(crate) fn new(input: &Input<'_>) -> Self { + let model = input.model; + let route = format!("{PROVIDER}:{}", model.model); + let tree = json!({ + "schema_version": 13, + "chat_provider": route, + "reasoning_provider": route, + "agentic_provider": route, + "coding_provider": route, + "primary_cloud": PROVIDER, + "default_model": model.model, + "memory": { + "engine": "", + "embedding_provider": "none", + "recall": {"enabled": false}, + "conversations": {"enabled": false}, + }, + "search": {"enabled": false}, + "observability": {"analytics_enabled": false, "share_usage_data": false}, + "mcp_client": { + "enabled": true, + "servers": [{ + "name": input.server, + "endpoint": input.url, + "expose": "direct", + "enabled": true, + "auth": {"kind": "bearer_token", "token": input.bearer}, + }], + }, + "agent": { + "chat_agent_id": AGENT_ID, + "tool_dispatcher": "native", + "agent_timeout_secs": input.turn_secs, + }, + "autonomy": {"auto_approve": input.tools, "auto_approve_all": false}, + "tokenjuice": { + "router_enabled": false, + "ccr_enabled": false, + "repl_handle_enabled": false, + }, + "context": {"compaction_enabled": false}, + "hooks": {"enabled": false}, + "web_chat": {"suggestions_enabled": false}, + "agent_registry": {"entries": [{ + "id": AGENT_ID, + "name": input.seat, + "description": "hive seat", + "source": "custom", + "enabled": true, + "system_prompt": input.prompt, + "tool_allowlist": input.tools, + }]}, + "cloud_providers": [{ + "id": PROVIDER, + "slug": PROVIDER, + "label": "tinyhivemind", + "endpoint": model.endpoint, + "auth_style": "none", + }], + }); + Self { tree } + } + + /// The file's text. + pub(crate) fn toml(&self) -> String { + toml::write(&self.tree) + } + + /// Every setting this config fixes, by dotted path, as written. + pub(crate) fn settings(&self) -> Vec<(String, Value)> { + let mut settings = Vec::new(); + leaves("", &self.tree, &mut settings); + settings.extend(UNSET.map(|name| (name.to_owned(), Value::Null))); + settings + } + + /// The same settings as `effective`, a `config_get` snapshot's `config`, + /// has them. A list of tables is cut down to the keys that were written + /// in each of its entries; an entry beyond them is kept whole, so that it + /// differs. + pub(crate) fn observe(&self, effective: &Value) -> Vec<(String, Value)> { + let settings = self.settings(); + let observed = settings.into_iter().map(|(path, written)| { + let found = lookup(effective, &path).cloned().unwrap_or(Value::Null); + let found = project(&written, found); + (path, found) + }); + observed.collect() + } +} + +/// Collect the leaves of `value` under `prefix`. A list is one leaf. +fn leaves(prefix: &str, value: &Value, into: &mut Vec<(String, Value)>) { + match value { + Value::Object(map) => { + for (key, value) in map { + let path = if prefix.is_empty() { + key.clone() + } else { + format!("{prefix}.{key}") + }; + leaves(&path, value, into); + } + } + leaf => into.push((prefix.to_owned(), leaf.clone())), + } +} + +fn lookup<'a>(value: &'a Value, path: &str) -> Option<&'a Value> { + path.split('.').try_fold(value, |value, key| value.get(key)) +} + +/// `found` cut down to the shape of `written`. +fn project(written: &Value, found: Value) -> Value { + match (written, found) { + (Value::Array(written), Value::Array(found)) => { + let entries = + found + .into_iter() + .enumerate() + .map(|(index, entry)| match written.get(index) { + Some(shape) => project(shape, entry), + None => entry, + }); + Value::Array(entries.collect()) + } + (Value::Object(written), Value::Object(mut found)) => { + let kept: Map = written + .iter() + .filter_map(|(key, shape)| { + let value = found.remove(key)?; + Some((key.clone(), project(shape, value))) + }) + .collect(); + Value::Object(kept) + } + (_, found) => found, + } +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-openhuman-process/src/config/test.rs b/crates/tinyhivemind-openhuman-process/src/config/test.rs new file mode 100644 index 00000000..300e9f93 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/config/test.rs @@ -0,0 +1,232 @@ +//! The generated config: what it says, that it parses back, and how an +//! effective config is held against it. +use super::{AGENT_ID, Input, Written}; +use crate::capability::SeatModel; +use serde_json::{Value, json}; + +fn model() -> SeatModel { + SeatModel { + provider: "local".into(), + endpoint: "http://127.0.0.1:9/v1".into(), + model: "mock".into(), + iterations: 8, + } +} + +fn written(prompt: &str, tools: &[String]) -> Written { + Written::new(&Input { + model: &model(), + seat: "scout", + prompt, + server: "hivemind", + url: "http://127.0.0.1:7/mcp", + bearer: "secret-bearer", + tools, + turn_secs: 600, + }) +} + +fn tools() -> Vec { + vec![ + "mcp_hivemind_post_1a2b3c".into(), + "mcp_hivemind_ask_4d5e6f".into(), + ] +} + +/// The file as `openhuman-core` reads it. +fn parsed(written: &Written) -> Value { + let text = written.toml(); + let table: ::toml::Table = text + .parse() + .unwrap_or_else(|error| unreachable!("the config does not parse: {error}\n{text}")); + serde_json::to_value(table).unwrap_or_else(|error| unreachable!("{error}")) +} + +#[test] +fn the_config_parses_back_to_what_was_built() { + let written = written("You scout.", &tools()); + assert_eq!(parsed(&written), written.tree); +} + +#[test] +fn the_allowlist_and_auto_approve_are_exactly_the_hive_tools() { + let config = parsed(&written("You scout.", &tools())); + let agent = &config["agent_registry"]["entries"][0]; + assert_eq!(agent["id"], AGENT_ID); + assert_eq!(agent["tool_allowlist"], json!(tools())); + assert!(agent.get("tool_denylist").is_none()); + assert_eq!(config["autonomy"]["auto_approve"], json!(tools())); + assert_eq!(config["autonomy"]["auto_approve_all"], false); + assert_eq!(config["agent"]["chat_agent_id"], AGENT_ID); + let text = written("You scout.", &tools()).toml(); + assert!(!text.contains("\"*\""), "{text}"); +} + +#[test] +fn the_provider_is_the_seats_alone_and_needs_no_key() { + let config = parsed(&written("You scout.", &tools())); + let providers = config["cloud_providers"].as_array().cloned(); + let providers = providers.unwrap_or_default(); + assert_eq!(providers.len(), 1); + assert_eq!(providers[0]["endpoint"], "http://127.0.0.1:9/v1"); + assert_eq!(providers[0]["auth_style"], "none"); + assert_eq!(config["primary_cloud"], providers[0]["id"]); + for route in [ + "chat_provider", + "reasoning_provider", + "agentic_provider", + "coding_provider", + ] { + assert_eq!(config[route], "thm:mock", "{route}"); + } +} + +#[test] +fn the_host_server_is_direct_with_the_seats_bearer() { + let config = parsed(&written("You scout.", &tools())); + let servers = &config["mcp_client"]["servers"]; + assert_eq!(servers.as_array().map(Vec::len), Some(1)); + assert_eq!(servers[0]["name"], "hivemind"); + assert_eq!(servers[0]["endpoint"], "http://127.0.0.1:7/mcp"); + assert_eq!(servers[0]["expose"], "direct"); + assert_eq!( + servers[0]["auth"], + json!({"kind": "bearer_token", "token": "secret-bearer"}) + ); +} + +#[test] +fn memory_search_hooks_suggestions_and_compression_are_off() { + let config = parsed(&written("You scout.", &tools())); + assert_eq!(config["memory"]["engine"], ""); + assert_eq!(config["memory"]["recall"]["enabled"], false); + assert_eq!(config["memory"]["conversations"]["enabled"], false); + assert_eq!(config["search"]["enabled"], false); + assert_eq!(config["hooks"]["enabled"], false); + assert_eq!(config["web_chat"]["suggestions_enabled"], false); + for flag in ["router_enabled", "ccr_enabled", "repl_handle_enabled"] { + assert_eq!(config["tokenjuice"][flag], false, "{flag}"); + } + assert_eq!(config["observability"]["analytics_enabled"], false); +} + +#[test] +fn a_prompt_cannot_break_out_of_its_string() { + let prompt = "line one\n[hooks]\nenabled = true\n\"\"\" ' \\ \u{1}"; + let config = parsed(&written(prompt, &tools())); + assert_eq!( + config["agent_registry"]["entries"][0]["system_prompt"], + prompt + ); + assert_eq!(config["hooks"], json!({"enabled": false})); +} + +#[test] +fn settings_name_every_leaf_written_and_the_routes_left_unset() { + let settings = written("You scout.", &tools()).settings(); + let names: Vec<&str> = settings.iter().map(|(name, _)| name.as_str()).collect(); + for name in [ + "primary_cloud", + "memory.recall.enabled", + "mcp_client.servers", + "agent_registry.entries", + "autonomy.auto_approve", + "api_key", + "inference_url", + ] { + assert!(names.contains(&name), "{name} in {names:?}"); + } + let unset = settings.iter().find(|(name, _)| name == "api_url"); + assert_eq!(unset.map(|(_, value)| value), Some(&Value::Null)); +} + +/// What `config_get` returns for the written file: the same, plus defaults. +fn effective(written: &Written) -> Value { + let mut config = written.tree.clone(); + config["agent"]["max_history_messages"] = json!(50); + config["mcp_client"]["servers"][0]["timeout_secs"] = json!(30); + config["mcp_client"]["servers"][0]["allowed_tools"] = json!([]); + config["embeddings_provider"] = json!("openhuman"); + for name in ["api_key", "api_url", "inference_url"] { + config[name] = Value::Null; + } + config +} + +#[test] +fn an_effective_config_with_defaults_added_is_the_one_written() { + let written = written("You scout.", &tools()); + let observed = written.observe(&effective(&written)); + assert_eq!(observed, written.settings()); +} + +#[test] +fn an_effective_config_that_differs_anywhere_written_is_another_one() { + let written = written("You scout.", &tools()); + let changes: [fn(&mut Value); 5] = [ + |config| config["hooks"]["enabled"] = json!(true), + |config| config["api_url"] = json!("https://hosted.example"), + |config| { + let extra = json!({"name": "other", "endpoint": "http://127.0.0.1:8/mcp"}); + if let Some(servers) = config["mcp_client"]["servers"].as_array_mut() { + servers.push(extra); + } + }, + |config| { + let tools = &mut config["agent_registry"]["entries"][0]["tool_allowlist"]; + if let Some(tools) = tools.as_array_mut() { + tools.push(json!("shell")); + } + }, + // What a config that did not parse falls back to. + |config| *config = json!({"schema_version": 13}), + ]; + for change in changes { + let mut config = effective(&written); + change(&mut config); + assert_ne!(written.observe(&config), written.settings(), "{config}"); + } +} + +#[test] +fn the_writer_leaves_out_null_and_writes_other_shapes_inline() { + let tree = json!({ + "gone": null, + "empty": [], + "mixed": [1, {"a": "b"}], + "table": {"inner": {"deep": true}}, + }); + let text = super::toml::write(&tree); + assert!(!text.contains("gone"), "{text}"); + let table: ::toml::Table = text + .parse() + .unwrap_or_else(|error| unreachable!("{error}\n{text}")); + let parsed = serde_json::to_value(table).unwrap_or_else(|error| unreachable!("{error}")); + let expected = json!({ + "empty": [], + "mixed": [1, {"a": "b"}], + "table": {"inner": {"deep": true}}, + }); + assert_eq!(parsed, expected); + assert_eq!(super::toml::write(&json!("not a table")), ""); +} + +#[test] +fn debug_shows_neither_the_bearer_nor_the_prompt() { + let tools = tools(); + let model = model(); + let input = Input { + model: &model, + seat: "scout", + prompt: "You scout.", + server: "hivemind", + url: "http://127.0.0.1:7/mcp", + bearer: "secret-bearer", + tools: &tools, + turn_secs: 600, + }; + let written = Written::new(&input); + for shown in [format!("{input:?}"), format!("{written:?}")] { + assert!(!shown.contains("secret-bearer"), "{shown}"); + } +} diff --git a/crates/tinyhivemind-openhuman-process/src/config/toml.rs b/crates/tinyhivemind-openhuman-process/src/config/toml.rs new file mode 100644 index 00000000..3a00a895 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/config/toml.rs @@ -0,0 +1,71 @@ +//! JSON written as TOML, for the shapes a config has. +//! +//! Scalars and lists of scalars are `key = value` lines; tables are `[a.b]` +//! sections and lists of tables `[[a.b]]` sections, after the scalars of +//! their parent. A JSON string is a valid TOML basic string, since the escapes +//! `serde_json` writes (`\"`, `\\`, `\n`, `\uXXXX` and the like) are all TOML +//! escapes, so no value can break out of its line. Keys are the config's own +//! and are bare. `null` is left out, as TOML has none. +use serde_json::{Map, Value}; +use std::fmt::Write as _; + +/// `tree`, an object, as a TOML document. +pub(super) fn write(tree: &Value) -> String { + let mut out = String::new(); + if let Value::Object(map) = tree { + table(&mut out, "", map); + } + out +} + +fn is_table(value: &Value) -> bool { + value.is_object() +} + +fn is_table_list(value: &Value) -> bool { + matches!(value, Value::Array(items) if !items.is_empty() && items.iter().all(Value::is_object)) +} + +fn table(out: &mut String, path: &str, map: &Map) { + for (key, value) in map { + if !is_table(value) && !is_table_list(value) && !value.is_null() { + let _ = writeln!(out, "{key} = {}", inline(value)); + } + } + for (key, value) in map { + let path = if path.is_empty() { + key.clone() + } else { + format!("{path}.{key}") + }; + match value { + Value::Object(inner) => { + let _ = writeln!(out, "[{path}]"); + table(out, &path, inner); + } + Value::Array(items) if is_table_list(value) => { + for item in items.iter().filter_map(Value::as_object) { + let _ = writeln!(out, "[[{path}]]"); + table(out, &path, item); + } + } + _ => {} + } + } +} + +fn inline(value: &Value) -> String { + match value { + Value::Array(items) => { + let items: Vec = items.iter().map(inline).collect(); + format!("[{}]", items.join(", ")) + } + Value::Object(map) => { + let entries = map + .iter() + .map(|(key, value)| format!("{key} = {}", inline(value))); + format!("{{ {} }}", entries.collect::>().join(", ")) + } + scalar => scalar.to_string(), + } +} diff --git a/crates/tinyhivemind-openhuman-process/src/error/README.md b/crates/tinyhivemind-openhuman-process/src/error/README.md new file mode 100644 index 00000000..bdf14a8e --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/error/README.md @@ -0,0 +1,12 @@ +# Errors + +The crate's internal `Error`. At the port a refusal becomes +`harness::Error::Refused` holding the `capability::Refusal`, supervision, +mismatch and resume failures keep the port's own variants, and the rest +become `harness::Error::Harness` with their message. No message holds a token, +a bearer or a config value. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `Error`, `Result` and the conversion | +| `test.rs` | Every variant through the port | diff --git a/crates/tinyhivemind-openhuman-process/src/error/mod.rs b/crates/tinyhivemind-openhuman-process/src/error/mod.rs new file mode 100644 index 00000000..fdd1f001 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/error/mod.rs @@ -0,0 +1,89 @@ +//! What can go wrong in this crate, and how the port sees it. +use crate::capability::Refusal; +use crate::{rpc, turn}; +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 harness cannot do. + #[error(transparent)] + Refused(#[from] Refusal), + /// The instance's API failed. + #[error(transparent)] + Api(#[from] rpc::Error), + /// A turn failed to run. + #[error(transparent)] + Turn(#[from] turn::Error), + /// The process could not be supervised. + #[error(transparent)] + Process(#[from] process::Error), + /// The instance is not the one asked for. + #[error(transparent)] + Mismatch(#[from] Mismatch), + /// The instance never listed some of the host's tools. + #[error("the instance did not list {missing:?} of server {server}")] + ToolsNotListed { + /// The server. + server: String, + /// Its tools, by the names it serves them under. + missing: Vec, + }, + /// The seat's session is gone from the instance; no new one is started. + #[error("the instance has no thread {0}")] + Resume(String), + /// The seat's first turn failed, so there is no session to report. + #[error("the turn failed before its thread had a transcript: {0}")] + FailedWithoutSession(String), + /// The turn's request could not be rendered as its message. + #[error("the turn could not be rendered: {0}")] + Render(String), + /// The keyring key file is not a private 256-bit hex key. + #[error("the keyring key file is unusable: {0}")] + KeyFile(&'static str), + /// A start failed, and so did stopping what it had started. + #[error("{error}; and its instance could not be stopped: {stop}")] + Abandoned { + /// Why the start failed. + error: Box, + /// Why the stop did. + stop: process::Error, + }, + /// A file of the instance could not be written or read. + #[error("{what}: {source}")] + Io { + /// What it was. + what: &'static str, + /// The failure. + 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_id) => Self::Resume { + reason: format!("the instance has no thread {session_id}"), + session_id, + }, + other => Self::Harness(other.to_string()), + } + } +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-openhuman-process/src/error/test.rs b/crates/tinyhivemind-openhuman-process/src/error/test.rs new file mode 100644 index 00000000..08c536f8 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/error/test.rs @@ -0,0 +1,71 @@ +//! How each failure reaches the port. +use super::Error; +use crate::capability::Refusal; +use tinyhivemind_host::harness::{self, Mismatch}; + +#[test] +fn a_refusal_stays_typed_through_the_port() { + let error: harness::Error = Error::from(Refusal::Budget).into(); + let harness::Error::Refused(refusal) = error else { + unreachable!("refused") + }; + assert_eq!(refusal.downcast_ref::(), Some(&Refusal::Budget)); +} + +#[test] +fn supervision_mismatch_and_resume_keep_the_ports_own_variants() { + let process: harness::Error = Error::from(tinyhivemind_host::process::Error::Unproven).into(); + assert!(matches!(process, harness::Error::Process(_))); + let mismatch = Mismatch::Pid { + expected: 1, + found: 2, + }; + let mismatch: harness::Error = Error::from(mismatch).into(); + assert!(matches!( + mismatch, + harness::Error::Mismatch(Mismatch::Pid { .. }) + )); + let resume: harness::Error = Error::Resume("thm-scout".into()).into(); + let harness::Error::Resume { session_id, reason } = resume else { + unreachable!("a resume failure") + }; + assert_eq!(session_id, "thm-scout"); + assert_eq!(reason, "the instance has no thread thm-scout"); +} + +#[test] +fn everything_else_is_a_harness_failure_with_its_message() { + let cases = [ + ( + Error::ToolsNotListed { + server: "hivemind".into(), + missing: vec!["hivemind_ask".into()], + }, + "the instance did not list [\"hivemind_ask\"] of server hivemind", + ), + ( + Error::io("the config")(std::io::Error::other("disk full")), + "the config: disk full", + ), + ( + Error::FailedWithoutSession("chat_error".into()), + "the turn failed before its thread had a transcript: chat_error", + ), + ( + Error::Render("bad request".into()), + "the turn could not be rendered: bad request", + ), + ( + Error::from(crate::turn::Error::StreamEnded), + "the event stream ended before the turn did", + ), + ( + Error::from(crate::rpc::Error::Decode("eof".into())), + "the instance answered with something unreadable: eof", + ), + ]; + for (error, message) in cases { + let error: harness::Error = error.into(); + assert_eq!(error.to_string(), format!("harness failed: {message}")); + } +} diff --git a/crates/tinyhivemind-openhuman-process/src/fixture.rs b/crates/tinyhivemind-openhuman-process/src/fixture.rs new file mode 100644 index 00000000..ad4f77e5 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/fixture.rs @@ -0,0 +1,134 @@ +//! Unit-test fixture: the in-process fake surface, a seat config written for +//! it, and a client. +use crate::capability::SeatModel; +use crate::config::{Input, Written}; +use crate::fake::{Fake, Setup, control, hashed}; +use crate::rpc::Client; +use serde_json::{Value, json}; +use std::fs; +use std::path::PathBuf; + +pub(crate) const TOKEN: &str = "fake-core-token"; +pub(crate) const PID: u32 = 4242; +pub(crate) const SERVER: &str = "hivemind"; + +/// A fake instance with a written config. +pub(crate) struct Fixture { + pub(crate) _root: tempfile::TempDir, + pub(crate) control: PathBuf, + pub(crate) written: Written, + pub(crate) client: Client, + pub(crate) fake: Fake, +} + +pub(crate) fn served() -> Vec { + vec!["hivemind_post".into(), "hivemind_ask".into()] +} + +pub(crate) fn hashed_tools() -> Vec { + served().iter().map(|tool| hashed(SERVER, tool)).collect() +} + +pub(crate) fn model() -> SeatModel { + SeatModel { + provider: "local".into(), + endpoint: "http://127.0.0.1:9/v1".into(), + model: "mock".into(), + iterations: 8, + } +} + +impl Fixture { + /// A fake whose control directory already holds `files`. + pub(crate) async fn with(files: &[(&str, &str)]) -> Self { + let root = tempfile::tempdir().unwrap_or_else(|error| unreachable!("{error}")); + let control = control(root.path()).unwrap_or_else(|error| unreachable!("{error}")); + let workspace = root.path().join("ws"); + let tools = hashed_tools(); + let model = model(); + let written = Written::new(&Input { + model: &model, + seat: "scout", + prompt: "You scout.", + server: SERVER, + url: "http://127.0.0.1:1/mcp", + bearer: "bearer", + tools: &tools, + turn_secs: 600, + }); + let wrote = fs::create_dir_all(&workspace) + .and_then(|()| fs::write(workspace.join("config.toml"), written.toml())) + .and_then(|()| fs::write(control.join("served"), json!(served()).to_string())); + for (name, text) in files { + let _ = fs::write(control.join(name), text); + } + assert!(wrote.is_ok(), "{wrote:?}"); + let setup = Setup { + token: TOKEN.into(), + workspace, + control: control.clone(), + pid: PID, + }; + let fake = Fake::start(setup).await; + let fake = fake.unwrap_or_else(|error| unreachable!("the fake starts: {error}")); + let client = Client::new(fake.port, TOKEN); + let client = client.unwrap_or_else(|error| unreachable!("a client: {error}")); + Self { + _root: root, + control, + written, + client, + fake, + } + } + + /// The config every fixture writes, without a fake. + pub(crate) fn written_for_test() -> Written { + let tools = hashed_tools(); + Written::new(&Input { + model: &model(), + seat: "scout", + prompt: "You scout.", + server: SERVER, + url: "http://127.0.0.1:1/mcp", + bearer: "bearer", + tools: &tools, + turn_secs: 600, + }) + } + + pub(crate) async fn new() -> Self { + Self::with(&[]).await + } + + /// Have the model play `steps` from its next call on. + pub(crate) fn script(&self, steps: &[Value]) { + for (index, step) in steps.iter().enumerate() { + let path = self.control.join("steps").join(format!("{index:04}")); + let _ = fs::write(path, step.to_string()); + } + } + + /// Each line of a control file the fake writes. + pub(crate) fn log(&self, name: &str) -> Vec { + let text = fs::read_to_string(self.control.join(name)).unwrap_or_default(); + text.lines() + .filter_map(|line| serde_json::from_str(line).ok()) + .collect() + } + + /// The states of the model calls, in order. + pub(crate) fn calls(&self) -> Vec { + let mut states: Vec = Vec::new(); + for entry in self.log("calls.jsonl") { + let index = usize::try_from(entry["call"].as_u64().unwrap_or(0)).unwrap_or(0); + let state = entry["state"].as_str().unwrap_or_default().to_owned(); + if index < states.len() { + states[index] = state; + } else { + states.push(state); + } + } + states + } +} diff --git a/crates/tinyhivemind-openhuman-process/src/harness/README.md b/crates/tinyhivemind-openhuman-process/src/harness/README.md new file mode 100644 index 00000000..c30d749a --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/harness/README.md @@ -0,0 +1,15 @@ +# Harness + +`OpenHumanHarness` refuses a seat `capability::check` refuses, reserves the +seat's id so that a second start is refused and a stop meanwhile stops what +starts, then starts one instance per seat and returns a `SeatRunner` around the seat. The seat starts +another instance when its child has died, resumes only a thread whose +transcript the instance has (`threads_transcript_get`), cancels by its +`Active` turn, and kills the instance when a cancel cannot be shown to work. +`stop` closes a running turn's events, cancels it and stops the instance +through the supervisor. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `OpenHumanHarness`, `Program`, `Options` | +| `seat.rs` | `Seat` and its `Runner` | diff --git a/crates/tinyhivemind-openhuman-process/src/harness/mod.rs b/crates/tinyhivemind-openhuman-process/src/harness/mod.rs new file mode 100644 index 00000000..8fcfdbba --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/harness/mod.rs @@ -0,0 +1,151 @@ +//! [`OpenHumanHarness`]: the `openhuman` kind of the host's harness port. +//! +//! Each seat is one instance of the pinned binary, started by +//! [`crate::instance`] and run by a seat runner held to the port's rules by +//! [`SeatRunner`]. See the crate documentation for what a seat may ask for. +mod seat; + +use crate::capability; +use seat::{Runner, Seat}; +use std::collections::BTreeMap; +use std::path::PathBuf; +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; + +/// The pinned `openhuman-core` binary. The library never downloads it: +/// `.github/scripts/fetch-harness.sh` fetches and checks the one in +/// `harnesses.lock`, and the host passes its path. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Program { + /// The binary, an absolute path. + pub path: PathBuf, + /// The version it must report, as `harnesses.lock` records it. + pub version: String, +} + +impl Program { + /// The binary at `path`, which must report `version`. + #[must_use] + pub fn new(path: impl Into, version: impl Into) -> Self { + Self { + path: path.into(), + version: version.into(), + } + } +} + +/// How long the steps of starting and stopping an instance may take. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Options { + /// From spawn to a healthy `/health`. + pub ready: Duration, + /// For the instance to list the host's tools, which it does only once + /// it has connected to the MCP server. + pub warm_up: Duration, + /// Each step of a stop. + pub stop: StopPolicy, + /// For the seat's approver to decide what the harness asks; then the + /// call is denied. + pub approval: Duration, +} + +impl Default for Options { + /// 30 s to be healthy, 20 s to warm up, the supervisor's own stop, and + /// 2 minutes for an approval. + fn default() -> Self { + Self { + ready: Duration::from_secs(30), + warm_up: Duration::from_secs(20), + stop: StopPolicy::default(), + approval: Duration::from_secs(120), + } + } +} + +/// Runs seats on `OpenHuman`, one supervised `openhuman-core` per seat. +/// +/// Its futures must be driven within a Tokio runtime with time and I/O +/// enabled. +#[derive(Debug)] +pub struct OpenHumanHarness { + program: Program, + options: Options, + seats: Arc>>>, +} + +impl OpenHumanHarness { + /// Seats on `program`, with the default [`Options`]. + #[must_use] + pub fn new(program: Program) -> Self { + Self { + program, + 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) +} + +impl Harness for OpenHumanHarness { + fn kind(&self) -> HarnessKind { + HarnessKind::OpenHuman + } + + /// Refuses, with [`Error::Refused`] holding a [`capability::Refusal`], a + /// seat this harness cannot honour, before anything is started. + fn start(&self, plan: SeatPlan, tools: ToolEndpoint) -> StartFuture { + let program = self.program.clone(); + let options = self.options; + let seats = self.seats.clone(); + Box::pin(async move { + let model = capability::check(&plan.seat) + .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(program, options, plan, tools, model)); + { + // Reserved before anything starts, so that a second start is + // refused and a stop meanwhile finds the seat to stop. + let mut seats = lock(&seats); + if seats.contains_key(&id) { + return Err(Error::Harness(format!("seat {id} is already running"))); + } + seats.insert(id.clone(), seat.clone()); + } + if let Err(error) = seat.start().await { + let mut seats = lock(&seats); + if seats.get(&id).is_some_and(|held| Arc::ptr_eq(held, &seat)) { + seats.remove(&id); + } + return Err(error.into()); + } + let runner = SeatRunner::new(Arc::new(Runner(seat))).with_timeout(timeout); + Ok(Arc::new(runner) as Arc) + }) + } + + fn stop(&self, seat_id: &str) -> StopFuture { + let seat = lock(&self.seats).remove(seat_id); + Box::pin(async move { + match seat { + Some(seat) => Ok(seat.stop().await?), + None => Ok(()), + } + }) + } +} diff --git a/crates/tinyhivemind-openhuman-process/src/harness/seat.rs b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs new file mode 100644 index 00000000..747b54d5 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/harness/seat.rs @@ -0,0 +1,219 @@ +//! One seat: its instance, its thread, and the turn it may be running. +use super::{Options, Program}; +use crate::capability::SeatModel; +use crate::error::{Error, Result}; +use crate::instance::{Launcher, Live}; +use crate::turn::{self, Active, Turn}; +use serde_json::json; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use tinyhivemind_hives::{AgentRunner, TurnDisposition, TurnFuture, TurnOutcome, TurnRequest}; +use tinyhivemind_host::harness::{ + self, CancelFuture, CancellableRunner, Event, SeatPlan, ToolEndpoint, +}; +use tokio::sync::{Mutex as AsyncMutex, watch}; + +/// A seat and its instance, if one is running. +#[derive(Debug)] +pub(super) struct Seat { + program: Program, + options: Options, + plan: SeatPlan, + tools: ToolEndpoint, + model: SeatModel, + live: AsyncMutex>>, + active: Mutex>, + closed: watch::Sender, + turns: AtomicU64, +} + +fn current(active: &Mutex>) -> Option { + active + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() +} + +fn clear(active: &Mutex>) { + *active.lock().unwrap_or_else(PoisonError::into_inner) = None; +} + +impl Seat { + pub(super) fn new( + program: Program, + options: Options, + plan: SeatPlan, + tools: ToolEndpoint, + model: SeatModel, + ) -> Self { + Self { + program, + options, + plan, + tools, + model, + live: AsyncMutex::new(None), + active: Mutex::new(None), + closed: watch::channel(false).0, + turns: AtomicU64::new(0), + } + } + + /// The thread a seat's first turn starts, and keeps for its life. + fn thread(&self) -> String { + format!("thm-{}", self.plan.seat.id) + } + + /// Start an instance if none is running, reporting it. + pub(super) async fn start(&self) -> Result> { + let mut live = self.live.lock().await; + if *self.closed.borrow() { + return Err(turn::Error::Closed.into()); + } + if let Some(running) = live.as_ref().filter(|live| live.instance.exit().is_none()) { + return Ok(running.clone()); + } + if let Some(dead) = live.take() { + dead.instance.stop(async {}, self.options.stop).await?; + } + let launcher = Launcher { + program: &self.program, + options: &self.options, + plan: &self.plan, + tools: &self.tools, + model: &self.model, + }; + let started = Arc::new(launcher.launch().await?); + if *self.closed.borrow() { + // Stopped while it started: what started is stopped too. + started.instance.stop(async {}, self.options.stop).await?; + return Err(turn::Error::Closed.into()); + } + let event = Event::Started(started.started.clone()); + self.plan.observer.event(&self.plan.seat.id, event); + *live = Some(started.clone()); + Ok(started) + } + + async fn run(&self, request: TurnRequest) -> Result { + if *self.closed.borrow() { + return Err(turn::Error::Closed.into()); + } + let live = self.start().await?; + let thread = request.session_id.clone().unwrap_or_else(|| self.thread()); + if let Some(session) = &request.session_id + && !has_transcript(&live, session).await? + { + return Err(Error::Resume(session.clone())); + } + turn::deny_stale(&live.client).await?; + let message = tinyhivemind_host::turn::render(&request) + .map_err(|error| Error::Render(error.to_string()))?; + let number = self.turns.fetch_add(1, Ordering::Relaxed); + let turn = Turn { + client: &live.client, + seat: &self.plan.seat.id, + thread: &thread, + id: &request.turn_id, + client_id: format!("thm-turn-{number}"), + iterations: self.model.iterations, + observer: self.plan.observer.as_ref(), + approver: self.plan.approver.as_ref(), + approval_limit: self.options.approval, + closed: self.closed.subscribe(), + }; + let ended = turn::run(turn, &message, &self.active).await?; + 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); + } + // A thread exists once a turn on it has ended. A failure before that + // reports no session, or the next turn would be refused its resume + // of a thread that never was. + if let Some(reason) = &ended.failure + && !has_transcript(&live, &thread).await? + { + return Err(Error::FailedWithoutSession(reason.clone())); + } + let disposition = ended + .failure + .map_or(TurnDisposition::Completed, TurnDisposition::Failed); + Ok(TurnOutcome { + session_id: thread, + reply: ended.reply, + disposition, + }) + } + + /// Cancel the submitted turn and show it stopped, or kill the instance. + async fn cancel(&self) -> Result<()> { + let Some(active) = current(&self.active) else { + return Ok(()); + }; + let mut live = self.live.lock().await; + let Some(running) = live.clone() else { + // Stopped since, so the turn is over. + clear(&self.active); + return Ok(()); + }; + let alive = running.instance.exit().is_none(); + if alive && turn::cancel(&running.client, &active).await.is_ok() { + clear(&self.active); + return Ok(()); + } + // Dead, or it could not show the turn stopped: then nothing of it may + // run on. + running.instance.stop(async {}, self.options.stop).await?; + *live = None; + clear(&self.active); + Ok(()) + } + + /// Cancel, close the turn's events, then stop the instance and prove it. + pub(super) async fn stop(&self) -> Result<()> { + self.closed.send_replace(true); + let Some(live) = self.live.lock().await.take() else { + return Ok(()); + }; + let active = current(&self.active); + let cancel = async { + if let Some(active) = &active { + // Best effort: the stop that follows ends the turn anyway. + let _ = turn::cancel(&live.client, active).await; + } + }; + live.instance.stop(cancel, self.options.stop).await?; + clear(&self.active); + Ok(()) + } +} + +/// Whether the instance keeps a transcript of `thread`. +async fn has_transcript(live: &Live, thread: &str) -> Result { + let params = json!({"thread_id": thread}); + let found = live + .client + .call("openhuman.threads_transcript_get", params) + .await?; + Ok(found["data"]["hasTranscript"] == true) +} + +/// The seat as the seat runner sees it. +pub(super) struct Runner(pub(super) 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-openhuman-process/src/instance/README.md b/crates/tinyhivemind-openhuman-process/src/instance/README.md new file mode 100644 index 00000000..b3dd056f --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/instance/README.md @@ -0,0 +1,19 @@ +# Instances + +`Launcher::launch` makes the seat's private directories (`ws/`, `home/`, +`action/`, the keyring key), starts a discovery instance whose allowlist +matches nothing, waits out the MCP warm-up and reads each hive tool's hashed +name, stops it, writes the exact allowlist and starts again. `verify` then +compares `/health.pid` with the child, `core.version` with the pin, `config_get` +with what was written, and the model-visible tools with the hive tools. No +RPC reports those, so `visible` computes them as 0.64.15's `resolved_scope` +does; see the spec's OpenHuman rules for every source it counts. Any +difference stops the instance and fails the start, and a stop that then fails +too is reported with it (`Error::Abandoned`). The keyring key file must be a +0600 file of 64 hex digits; another is refused, not replaced. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `Launcher`, `Live`, `Layout`, the environment | +| `verify.rs` | `discover`, `verify` | +| `test.rs` | Against the fake surface, and the exact environment | diff --git a/crates/tinyhivemind-openhuman-process/src/instance/mod.rs b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs new file mode 100644 index 00000000..f60b321a --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/instance/mod.rs @@ -0,0 +1,279 @@ +//! Starting one instance: its directories, environment and config, tool +//! discovery, and the verification it must pass. +//! +//! An instance lives in the seat's directory, made private by +//! [`InstanceDir`]. Its state directory holds: +//! +//! | Path | For | +//! | --- | --- | +//! | `ws/` | `OPENHUMAN_WORKSPACE`: `config.toml`, sessions, the keyring | +//! | `home/` | `HOME` | +//! | `action/` | `OPENHUMAN_ACTION_DIR`, and the working directory | +//! | `keyring.key` | the keyring's random master key, mode 0600, kept across starts | +//! +//! A start is two starts. The model-visible name of an MCP tool carries a +//! hash that only the instance knows, so the first start runs with an +//! allowlist that matches nothing, waits out the MCP warm-up and reads the +//! names from `agent_registry_available_tools`; then it is stopped, the exact +//! allowlist is written, and the second start is verified. The core token is +//! new for every start; the port is a free one, and an instance that moved +//! to another fails the pid check. `OPENHUMAN_SANDBOX` is never set. +mod verify; + +pub(crate) use verify::{discover, verify}; + +use crate::capability::SeatModel; +use crate::config::{Input, Written}; +use crate::error::{Error, Result}; +use crate::harness::{Options, Program}; +use crate::rpc::Client; +use std::fmt::Write as _; +use std::fs; +use std::io::{Read as _, Write as _}; +use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _, PermissionsExt as _}; +use std::path::{Path, PathBuf}; +use std::time::Duration; +use tinyhivemind_host::harness::{SeatPlan, Started, ToolEndpoint}; +use tinyhivemind_host::process::{Instance, InstanceDir, Launch}; + +/// The allowlist of the discovery start, which no tool is called. +const NOTHING: &str = "thm_no_tool"; +/// The least a turn may run inside the binary, which has its own deadline. +const TURN_FLOOR: u64 = 600; + +/// A started, verified instance. +#[derive(Debug)] +pub(crate) struct Live { + pub(crate) instance: Instance, + pub(crate) client: Client, + pub(crate) started: Started, +} + +/// The directories of one instance's state. +#[derive(Clone, Debug)] +pub(crate) struct Layout { + state: PathBuf, +} + +impl Layout { + pub(crate) fn new(state: &Path) -> Self { + Self { + state: state.to_path_buf(), + } + } + pub(crate) fn workspace(&self) -> PathBuf { + self.state.join("ws") + } + fn home(&self) -> PathBuf { + self.state.join("home") + } + fn action(&self) -> PathBuf { + self.state.join("action") + } + fn create(&self) -> Result<()> { + let mut builder = fs::DirBuilder::new(); + builder.recursive(true).mode(0o700); + for dir in [self.workspace(), self.home(), self.action()] { + builder + .create(dir) + .map_err(Error::io("the instance directories"))?; + } + Ok(()) + } + + /// The keyring's master key, made on first use. + fn master_key(&self) -> Result { + let path = self.state.join("keyring.key"); + if let Ok(meta) = fs::symlink_metadata(&path) { + if !meta.is_file() || meta.permissions().mode() & 0o777 != 0o600 { + return Err(Error::KeyFile("it is not a file of mode 0600")); + } + let key = fs::read_to_string(&path).map_err(Error::io("the keyring key"))?; + if key.len() != 64 || !key.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(Error::KeyFile("it does not hold 64 hex digits")); + } + return Ok(key); + } + let key = random()?; + let mut file = fs::File::options() + .write(true) + .create_new(true) + .mode(0o600) + .open(&path) + .map_err(Error::io("the keyring key"))?; + file.write_all(key.as_bytes()) + .map_err(Error::io("the keyring key"))?; + Ok(key) + } + + fn write_config(&self, written: &Written) -> Result<()> { + let path = self.workspace().join("config.toml"); + let mut file = fs::File::options() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .open(path) + .map_err(Error::io("the config"))?; + // The mode above applies only to a new file. + let private = fs::Permissions::from_mode(0o600); + file.set_permissions(private) + .map_err(Error::io("the config"))?; + file.write_all(written.toml().as_bytes()) + .map_err(Error::io("the config")) + } +} + +/// `error`, and the stop that followed it if that failed too. +pub(crate) fn abandon( + error: Error, + stopped: std::result::Result, +) -> Error { + match stopped { + Ok(_) => error, + Err(stop) => Error::Abandoned { + error: Box::new(error), + stop, + }, + } +} + +/// 256 random bits, as hex. +fn random() -> Result { + let mut bytes = [0_u8; 32]; + let mut source = fs::File::open("/dev/urandom").map_err(Error::io("/dev/urandom"))?; + source + .read_exact(&mut bytes) + .map_err(Error::io("/dev/urandom"))?; + Ok(bytes.iter().fold(String::new(), |mut hex, byte| { + let _ = write!(hex, "{byte:02x}"); + hex + })) +} + +/// The child's whole environment, besides what the supervisor adds. +pub(crate) fn environment(layout: &Layout, token: &str, key: &str) -> Vec<(&'static str, String)> { + let path = |path: PathBuf| path.to_string_lossy().into_owned(); + vec![ + ("PATH", "/usr/bin:/bin".into()), + ("HOME", path(layout.home())), + ("LANG", "C.UTF-8".into()), + ("OPENHUMAN_WORKSPACE", path(layout.workspace())), + ("OPENHUMAN_ACTION_DIR", path(layout.action())), + ("OPENHUMAN_TOOL_DISPATCHER", "native".into()), + ("OPENHUMAN_COMPOSIO_MODE", "disabled".into()), + // The binary asks for a backend key; this one opens nothing. + ("OPENHUMAN_BACKEND_API_KEY", "dummy".into()), + ("OPENHUMAN_KEYRING_BACKEND", "encrypted_file".into()), + ("OPENHUMAN_KEYRING_MASTER_KEY", key.into()), + ("OPENHUMAN_CORE_TOKEN", token.into()), + ("RUST_LOG", "warn".into()), + ] +} + +/// A port nobody is listening on now. +fn free_port() -> Result { + let listener = std::net::TcpListener::bind("127.0.0.1:0").map_err(Error::io("a free port"))?; + let address = listener.local_addr().map_err(Error::io("a free port"))?; + Ok(address.port()) +} + +/// How long the binary itself lets a turn run: past the seat's own limit, +/// which the seat runner enforces. +fn turn_secs(limit: Option) -> u64 { + let limit = limit.map_or(0, |limit| limit.as_secs().saturating_add(60)); + limit.max(TURN_FLOOR) +} + +/// Starts a seat's instances. +pub(crate) struct Launcher<'a> { + pub(crate) program: &'a Program, + pub(crate) options: &'a Options, + pub(crate) plan: &'a SeatPlan, + pub(crate) tools: &'a ToolEndpoint, + pub(crate) model: &'a SeatModel, +} + +impl Launcher<'_> { + /// Start, discover, restart and verify; or leave nothing running. + pub(crate) async fn launch(&self) -> Result { + let dir = InstanceDir::create(&self.plan.directory)?; + let layout = Layout::new(dir.state()); + layout.create()?; + let key = layout.master_key()?; + let nothing = [NOTHING.to_owned()]; + let ((probe, client), _) = self.start(&dir, &layout, &key, ¬hing).await?; + let server = &self.tools.server; + let names = discover(&client, server, &self.tools.tools, self.options.warm_up).await; + let stopped = probe.stop(async {}, self.options.stop).await; + let names = match names { + Ok(names) => { + stopped?; + names + } + Err(error) => return Err(abandon(error, stopped)), + }; + let ((instance, client), written) = self.start(&dir, &layout, &key, &names).await?; + let version = &self.program.version; + let pid = instance.pid(); + let warm_up = self.options.warm_up; + match verify(&client, pid, version, &written, &names, warm_up).await { + Ok(started) => Ok(Live { + instance, + client, + started, + }), + Err(error) => Err(abandon( + error, + instance.stop(async {}, self.options.stop).await, + )), + } + } + + /// One healthy instance with `tools` allowed. + async fn start( + &self, + dir: &InstanceDir, + layout: &Layout, + key: &str, + tools: &[String], + ) -> Result<((Instance, Client), Written)> { + let written = Written::new(&Input { + model: self.model, + seat: &self.plan.seat.id, + prompt: &self.plan.seat.prompt, + server: &self.tools.server, + url: &self.tools.url, + bearer: self.tools.bearer(), + tools, + turn_secs: turn_secs(self.plan.turn_timeout()), + }); + layout.write_config(&written)?; + let token = random()?; + let port = free_port()?; + let mut launch = Launch::new(&self.program.path, dir.clone()).current_dir(layout.action()); + for argument in ["run", "--headless-api", "--host", "127.0.0.1", "--port"] { + launch = launch.arg(argument); + } + launch = launch.arg(port.to_string()); + for (name, value) in environment(layout, &token, key) { + launch = launch.env(name, value); + } + let instance = Instance::start(launch).await?; + let client = Client::new(port, &token)?; + let probe = async { + while client.health().await.is_err() { + tokio::time::sleep(Duration::from_millis(50)).await; + } + Ok::<(), String>(()) + }; + if let Err(error) = instance.ready(probe, self.options.ready).await { + let stopped = instance.stop(async {}, self.options.stop).await; + return Err(abandon(error.into(), stopped)); + } + Ok(((instance, client), written)) + } +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-openhuman-process/src/instance/test.rs b/crates/tinyhivemind-openhuman-process/src/instance/test.rs new file mode 100644 index 00000000..bcd2f5b2 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/instance/test.rs @@ -0,0 +1,352 @@ +//! Start-up verification and tool discovery, against the fake surface. +use super::verify::{discover, verify}; +use super::{Layout, environment, turn_secs}; +use crate::error::Error; +use crate::fixture::{Fixture, PID, SERVER, hashed_tools, served}; +use std::collections::BTreeSet; +use std::time::Duration; +use tinyhivemind_host::harness::Mismatch; + +const WARM: Duration = Duration::from_secs(5); + +async fn verified( + fixture: &Fixture, + pid: u32, +) -> Result { + let tools = hashed_tools(); + verify( + &fixture.client, + pid, + "0.64.15", + &fixture.written, + &tools, + WARM, + ) + .await +} + +#[tokio::test] +async fn the_instance_that_was_written_is_verified_after_its_warm_up() { + let fixture = Fixture::with(&[("warm", "3")]).await; + let started = verified(&fixture, PID).await; + let started = started.unwrap_or_else(|error| unreachable!("verified: {error}")); + assert_eq!(started.pid, PID); + assert_eq!( + started.tools, + hashed_tools().into_iter().collect::>() + ); + assert!(started.settings.contains("agent_registry.entries")); + assert!(started.settings.contains("api_url")); +} + +#[tokio::test] +async fn another_process_answering_is_refused() { + let fixture = Fixture::new().await; + let refused = verified(&fixture, PID + 1).await; + assert!( + matches!(refused, Err(Error::Mismatch(Mismatch::Pid { .. }))), + "{refused:?}" + ); +} + +#[tokio::test] +async fn another_version_is_refused() { + let fixture = Fixture::with(&[("version", "0.64.14")]).await; + let refused = verified(&fixture, PID).await; + assert!( + matches!(refused, Err(Error::Mismatch(Mismatch::Version { .. }))), + "{refused:?}" + ); +} + +#[tokio::test] +async fn a_config_that_fell_back_to_defaults_is_refused() { + let fixture = Fixture::with(&[("misconfigured", "")]).await; + let refused = verified(&fixture, PID).await; + assert!( + matches!(refused, Err(Error::Mismatch(Mismatch::Settings { .. }))), + "{refused:?}" + ); +} + +#[tokio::test] +async fn a_tool_the_model_would_see_besides_the_hive_tools_is_refused() { + let fixture = Fixture::with(&[("tools", "extra")]).await; + let refused = verified(&fixture, PID).await; + assert!(matches!(refused, Err(Error::Mismatch(_))), "{refused:?}"); +} + +#[tokio::test] +async fn a_hive_tool_the_model_would_not_see_is_refused() { + let fixture = Fixture::with(&[("tools", "missing"), ("warm", "0")]).await; + let tools = hashed_tools(); + let refused = verify( + &fixture.client, + PID, + "0.64.15", + &fixture.written, + &tools, + Duration::ZERO, + ) + .await; + let Err(Error::Mismatch(Mismatch::Tools { + missing, + unexpected, + })) = refused + else { + unreachable!("refused for its tools: {refused:?}") + }; + assert_eq!(missing, [tools[1].clone()]); + assert_eq!(unexpected, Vec::::new()); +} + +#[tokio::test] +async fn discovery_waits_out_the_warm_up_and_reads_the_hashed_names() { + let fixture = Fixture::with(&[("warm", "4")]).await; + let wanted: BTreeSet = served().into_iter().collect(); + let found = discover(&fixture.client, SERVER, &wanted, WARM).await; + let mut expected = hashed_tools(); + expected.sort(); + assert_eq!(found.ok(), Some(expected)); +} + +#[tokio::test] +async fn a_tool_never_listed_fails_discovery_by_name() { + let fixture = Fixture::with(&[("tools", "missing")]).await; + let wanted: BTreeSet = served().into_iter().collect(); + let found = discover(&fixture.client, SERVER, &wanted, Duration::from_millis(300)).await; + let Err(Error::ToolsNotListed { missing, .. }) = found else { + unreachable!("not listed: {found:?}") + }; + assert_eq!(missing, ["hivemind_ask"]); +} + +#[tokio::test] +async fn a_tool_whose_name_another_tools_name_starts_with_is_told_apart() { + let fixture = Fixture::with(&[("served", r#"["post", "post_x"]"#), ("warm", "0")]).await; + let wanted: BTreeSet = ["post".to_owned()].into_iter().collect(); + let found = discover(&fixture.client, SERVER, &wanted, WARM).await; + assert_eq!(found.ok(), Some(vec![crate::fake::hashed(SERVER, "post")])); +} + +#[test] +fn the_environment_is_exactly_the_recipe_and_never_turns_the_sandbox_off() { + let layout = Layout::new(std::path::Path::new("/seat/state")); + let environment = environment(&layout, "token", "key"); + let names: Vec<&str> = environment.iter().map(|(name, _)| *name).collect(); + assert_eq!( + names, + [ + "PATH", + "HOME", + "LANG", + "OPENHUMAN_WORKSPACE", + "OPENHUMAN_ACTION_DIR", + "OPENHUMAN_TOOL_DISPATCHER", + "OPENHUMAN_COMPOSIO_MODE", + "OPENHUMAN_BACKEND_API_KEY", + "OPENHUMAN_KEYRING_BACKEND", + "OPENHUMAN_KEYRING_MASTER_KEY", + "OPENHUMAN_CORE_TOKEN", + "RUST_LOG", + ] + ); + let value = |name: &str| { + environment + .iter() + .find(|(key, _)| *key == name) + .map(|(_, value)| value.as_str()) + }; + assert_eq!(value("OPENHUMAN_WORKSPACE"), Some("/seat/state/ws")); + assert_eq!(value("OPENHUMAN_KEYRING_BACKEND"), Some("encrypted_file")); + assert_eq!(value("OPENHUMAN_BACKEND_API_KEY"), Some("dummy")); + assert!(value("OPENHUMAN_SANDBOX").is_none()); +} + +#[test] +fn the_binary_lets_a_turn_run_past_the_seats_own_limit() { + assert_eq!(turn_secs(None), 600); + assert_eq!(turn_secs(Some(Duration::from_secs(5))), 600); + assert_eq!(turn_secs(Some(Duration::from_secs(3600))), 3660); +} + +#[test] +fn compaction_puts_the_recovery_tool_before_the_model_whatever_the_allowlist() { + let available = ["juice_retrieve".to_owned(), "mcp_s_post_1".to_owned()]; + let agent = + serde_json::json!({"id": crate::config::AGENT_ID, "tool_allowlist": ["mcp_s_post_1"]}); + let chat = serde_json::json!({"chat_agent_id": crate::config::AGENT_ID}); + let on = serde_json::json!({"agent": chat, "agent_registry": {"entries": [agent.clone()]}}); + assert_eq!( + super::verify::visible(&on, &available), + ["mcp_s_post_1", "juice_retrieve"] + ); + let off = serde_json::json!({"agent": chat, "agent_registry": {"entries": [agent]}, "context": {"compaction_enabled": false}}); + assert_eq!(super::verify::visible(&off, &available), ["mcp_s_post_1"]); + // Another chat agent is a built-in one, whose tools are not these. + let other = serde_json::json!({"agent_registry": {"entries": []}}); + assert_eq!( + super::verify::visible(&other, &available), + [""] + ); +} + +#[test] +fn the_written_config_turns_compaction_off() { + let settings = Fixture::written_for_test().settings(); + let compaction = settings + .iter() + .find(|(name, _)| name == "context.compaction_enabled"); + assert_eq!( + compaction.map(|(_, value)| value.clone()), + Some(serde_json::json!(false)) + ); +} + +/// What `resolved_scope` in 0.64.15's `definition_registry.rs` adds to an +/// allowlist, each of which the start check must see. +#[test] +fn every_source_the_binary_adds_tools_from_is_counted() { + use serde_json::json; + let available: Vec = [ + "mcp_s_post_1", + "tool_search", + "juice_retrieve", + "juice_find", + "juice_extract", + "juice_summarize", + "shell", + ] + .map(String::from) + .to_vec(); + let entry = |extra: serde_json::Value| { + let mut entry = json!({"id": crate::config::AGENT_ID, "tool_allowlist": ["mcp_s_post_1"]}); + if let (Some(entry), Some(extra)) = (entry.as_object_mut(), extra.as_object()) { + entry.extend(extra.clone()); + } + entry + }; + let config = |entry: serde_json::Value, rest: serde_json::Value| { + let mut config = json!({ + "agent_registry": {"entries": [entry]}, + "context": {"compaction_enabled": false}, + "agent": {"chat_agent_id": crate::config::AGENT_ID}, + }); + if let (Some(config), Some(rest)) = (config.as_object_mut(), rest.as_object()) { + for (key, value) in rest { + config.insert(key.clone(), value.clone()); + } + } + config + }; + let seen = |config: &serde_json::Value| super::verify::visible(config, &available); + assert_eq!(seen(&config(entry(json!({})), json!({}))), ["mcp_s_post_1"]); + // Deferred tools, when the allowlist names the tool search. + let search = entry(json!({"tool_allowlist": ["mcp_s_post_1", "tool_search"]})); + assert!( + seen(&config(search, json!({}))) + .iter() + .any(|tool| tool.contains("deferred")) + ); + // The REPL tools, while results are stored behind a handle. + let repl = json!({ + "context": {"compaction_enabled": true}, + "tokenjuice": {"router_enabled": true, "ccr_enabled": true, "repl_handle_enabled": true}, + }); + let repl = seen(&config(entry(json!({})), repl)); + for tool in [ + "juice_retrieve", + "juice_find", + "juice_extract", + "juice_summarize", + ] { + assert!(repl.contains(&tool.to_owned()), "{tool} in {repl:?}"); + } + // The summary stage, which only the orchestrator gets. + let orchestrator = json!({"id": "orchestrator", "tool_allowlist": ["mcp_s_post_1"]}); + let summary = json!({ + "agent": {"chat_agent_id": "orchestrator"}, + "context": {"compaction_enabled": false, "summarizer_payload_threshold_tokens": 100}, + }); + let summary = seen(&config(orchestrator, summary)); + assert!( + summary.contains(&"juice_retrieve".to_owned()), + "{summary:?}" + ); + // `extra_tools`, and a session's delegation tools for an agent with subagents. + let extra = seen(&config(entry(json!({"extra_tools": ["shell"]})), json!({}))); + assert!(extra.contains(&"shell".to_owned()), "{extra:?}"); + let delegating = seen(&config(entry(json!({"subagents": ["helper"]})), json!({}))); + assert!( + delegating.iter().any(|tool| tool.contains("delegation")), + "{delegating:?}" + ); +} + +#[test] +fn the_keyring_key_is_made_once_and_a_bad_one_is_refused() { + use std::os::unix::fs::PermissionsExt as _; + let dir = tempfile::tempdir().unwrap_or_else(|error| unreachable!("{error}")); + let layout = Layout::new(dir.path()); + let made = layout.master_key(); + let made = made.unwrap_or_else(|error| unreachable!("a new key: {error}")); + assert_eq!(made.len(), 64); + assert!(made.bytes().all(|byte| byte.is_ascii_hexdigit())); + assert_eq!(layout.master_key().ok(), Some(made)); + let path = dir.path().join("keyring.key"); + let chmod = |bits| std::fs::set_permissions(&path, std::fs::Permissions::from_mode(bits)); + assert!(chmod(0o644).is_ok()); + assert!(matches!(layout.master_key(), Err(Error::KeyFile(_)))); + for bad in ["", "abc", &"z".repeat(64)] { + assert!(std::fs::write(&path, bad).is_ok() && chmod(0o600).is_ok()); + assert!( + matches!(layout.master_key(), Err(Error::KeyFile(_))), + "{bad:?}" + ); + } +} + +#[test] +fn a_config_already_there_is_made_private_when_written() { + use std::os::unix::fs::PermissionsExt as _; + let dir = tempfile::tempdir().unwrap_or_else(|error| unreachable!("{error}")); + let layout = Layout::new(dir.path()); + assert!(std::fs::create_dir_all(layout.workspace()).is_ok()); + let path = layout.workspace().join("config.toml"); + assert!(std::fs::write(&path, "old").is_ok()); + assert!(std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).is_ok()); + assert!(layout.write_config(&Fixture::written_for_test()).is_ok()); + let mode = std::fs::metadata(&path).map(|meta| meta.permissions().mode() & 0o777); + assert_eq!(mode.ok(), Some(0o600)); +} + +#[test] +fn a_stop_that_fails_after_a_failed_start_keeps_both_errors() { + let start = Error::Resume("t".into()); + let kept = super::abandon(start, Ok::<(), tinyhivemind_host::process::Error>(())); + assert!(matches!(kept, Error::Resume(_))); + let stopped: Result<(), _> = Err(tinyhivemind_host::process::Error::Unproven); + let both = super::abandon(Error::Resume("t".into()), stopped); + let shown = both.to_string(); + assert!( + shown.contains("no thread t") && shown.contains("could not be proven gone"), + "{shown}" + ); +} + +#[tokio::test] +async fn tools_whose_names_differ_only_in_hex_like_suffixes_are_told_apart() { + let served = r#"["post", "post_a", "post_ab", "post_abc123"]"#; + let fixture = Fixture::with(&[("served", served), ("warm", "0")]).await; + let wanted: BTreeSet = ["post", "post_a", "post_ab", "post_abc123"] + .map(String::from) + .into_iter() + .collect(); + let found = discover(&fixture.client, SERVER, &wanted, WARM).await; + let mut expected: Vec = wanted + .iter() + .map(|tool| crate::fake::hashed(SERVER, tool)) + .collect(); + expected.sort(); + assert_eq!(found.ok(), Some(expected)); +} diff --git a/crates/tinyhivemind-openhuman-process/src/instance/verify.rs b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs new file mode 100644 index 00000000..aa713c47 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/instance/verify.rs @@ -0,0 +1,200 @@ +//! Whether a started instance is the one that was asked for, and the names +//! its model sees the hive tools under. +use crate::config::Written; +use crate::error::{Error, Result}; +use crate::rpc::Client; +use serde_json::{Value, json}; +use std::collections::BTreeSet; +use std::time::Duration; +use tinyhivemind_host::harness::{Expected, Observed, Started}; +use tokio::time::Instant; + +/// How often a warming instance is asked again. +const POLL: Duration = Duration::from_millis(100); + +/// Every tool name the instance offers. +async fn available(client: &Client) -> Result> { + let listed = client + .call("openhuman.agent_registry_available_tools", json!({})) + .await?; + let tools = listed["tools"].as_array().cloned().unwrap_or_default(); + let names = tools + .iter() + .filter_map(|tool| tool["name"].as_str().map(str::to_owned)); + Ok(names.collect()) +} + +/// The name `tool` of `server` has among `names`: `mcp___` and +/// a hex hash, which no other tool's name also matches. +fn name_of<'a>(names: &'a [String], server: &str, tool: &str) -> Option<&'a String> { + let prefix = format!("mcp_{server}_{tool}_"); + let mut found = names.iter().filter(|name| { + name.strip_prefix(&prefix) + .is_some_and(|hash| !hash.is_empty() && hash.bytes().all(|b| b.is_ascii_hexdigit())) + }); + let first = found.next(); + first.filter(|_| found.next().is_none()) +} + +/// The model-visible names of `tools`, served by `server`, once the instance +/// has connected to it, within `warm_up`. +/// +/// # Errors +/// [`Error::ToolsNotListed`] for tools still unnamed when `warm_up` is over. +pub(crate) async fn discover( + client: &Client, + server: &str, + tools: &BTreeSet, + warm_up: Duration, +) -> Result> { + let deadline = Instant::now() + warm_up; + loop { + let names = available(client).await?; + let found: Vec<_> = tools + .iter() + .map(|tool| name_of(&names, server, tool)) + .collect(); + if found.iter().all(Option::is_some) { + let mut found: Vec = found.into_iter().flatten().cloned().collect(); + found.sort(); + return Ok(found); + } + if Instant::now() >= deadline { + let missing = tools.iter().zip(&found).filter(|(_, name)| name.is_none()); + return Err(Error::ToolsNotListed { + server: server.to_owned(), + missing: missing.map(|(tool, _)| tool.clone()).collect(), + }); + } + tokio::time::sleep(POLL).await; + } +} + +/// The recovery tool 0.64.15 adds to a non-empty allowlist while tool +/// output can be compacted or summarized. +const RECOVERY: &str = "juice_retrieve"; +/// The tools it adds while results are stored behind a handle. +const REPL: [&str; 3] = ["juice_find", "juice_extract", "juice_summarize"]; +/// The tool whose presence in an allowlist adds every deferred tool. +const TOOL_SEARCH: &str = "tool_search"; +/// Stand-ins for tools only a running session knows the names of. None is +/// ever expected, so any of them fails the check. +const DEFERRED: &str = ""; +const DELEGATION: &str = ""; + +fn enabled(value: &Value) -> bool { + // A switch the snapshot leaves out is the binary's default, on. + value != false +} + +/// The tools the model sees, computed as 0.64.15's `resolved_scope` does +/// (`agent/tinyagents/host/definition_registry.rs`): the chat agent's +/// allowlist, of the tools the instance has; every deferred tool if it names +/// `tool_search`; the session's delegation tools for an agent with +/// subagents; the recovery tool while compaction or the orchestrator's +/// summary stage is on, and the REPL tools while results are stored behind a +/// handle, both only for a non-empty allowlist; and `extra_tools`. No RPC +/// reports the set, so the live tests check it at the model. +pub(super) fn visible(config: &Value, available: &[String]) -> Vec { + let agent = config["agent"]["chat_agent_id"] + .as_str() + .unwrap_or("orchestrator"); + let entries = config["agent_registry"]["entries"].as_array().cloned(); + let Some(entry) = entries + .unwrap_or_default() + .into_iter() + .find(|entry| entry["id"] == agent) + else { + return vec![format!("")]; + }; + let has = |name: &str| available.iter().any(|tool| tool == name); + let list = |key: &str| { + let names = entry[key].as_array().cloned().unwrap_or_default(); + names + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect::>() + }; + let allowed = list("tool_allowlist"); + let mut seen: Vec = allowed.iter().filter(|name| has(name)).cloned().collect(); + if allowed.iter().any(|name| name == TOOL_SEARCH) { + seen.push(DEFERRED.to_owned()); + } + if !list("subagents").is_empty() { + seen.push(DELEGATION.to_owned()); + } + let compaction = enabled(&config["context"]["compaction_enabled"]); + let threshold = &config["context"]["summarizer_payload_threshold_tokens"]; + let summarizes = agent == "orchestrator" && threshold.as_u64() != Some(0); + let juice = &config["tokenjuice"]; + let repl = compaction + && enabled(&juice["router_enabled"]) + && enabled(&juice["ccr_enabled"]) + && enabled(&juice["repl_handle_enabled"]); + if !allowed.is_empty() { + let mut companions = Vec::new(); + if compaction || summarizes { + companions.push(RECOVERY); + } + if repl { + companions.extend(REPL); + } + seen.extend( + companions + .into_iter() + .filter(|name| has(name)) + .map(str::to_owned), + ); + } + seen.extend(list("extra_tools")); + let mut unique = Vec::new(); + for tool in seen { + if !unique.contains(&tool) { + unique.push(tool); + } + } + unique +} + +/// Hold the instance at `client` against the child `pid`, the pinned +/// `version`, the `written` config and exactly `tools`, waiting up to +/// `warm_up` for its MCP tools to be listed. +/// +/// # Errors +/// [`Error::Mismatch`] for any difference, or the API's own failure. +pub(crate) async fn verify( + client: &Client, + pid: u32, + version: &str, + written: &Written, + tools: &[String], + warm_up: Duration, +) -> Result { + let health = client.health().await?; + let answering = health["pid"] + .as_u64() + .and_then(|pid| u32::try_from(pid).ok()); + let running = client.call("core.version", json!({})).await?; + let running = running["version"].as_str().unwrap_or_default().to_owned(); + let snapshot = client.call("openhuman.config_get", json!({})).await?; + let config = &snapshot["result"]["config"]; + let deadline = Instant::now() + warm_up; + let seen = loop { + let seen = visible(config, &available(client).await?); + let all = tools.iter().all(|tool| seen.contains(tool)); + if all || Instant::now() >= deadline { + break seen; + } + tokio::time::sleep(POLL).await; + }; + let mut expected = Expected::new(pid, version).tools(tools.iter().cloned()); + for (name, value) in written.settings() { + expected = expected.setting(name, value); + } + let mut observed = Observed::new(answering.unwrap_or_default(), running).tools(seen); + for (name, value) in written.observe(config) { + observed = observed.setting(name, value); + } + Ok(expected.verify(&observed)?) +} diff --git a/crates/tinyhivemind-openhuman-process/src/lib.rs b/crates/tinyhivemind-openhuman-process/src/lib.rs new file mode 100644 index 00000000..d68df61b --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/lib.rs @@ -0,0 +1,60 @@ +//! Hive seats on `OpenHuman`, each a supervised `openhuman-core` process. +//! +//! [`OpenHumanHarness`] implements the host's +//! [`Harness`](tinyhivemind_host::harness::Harness) port for the `openhuman` +//! kind. Each seat gets one `openhuman-core run --headless-api` in its own +//! private directory, with a generated `config.toml`, and is driven over its +//! loopback JSON-RPC and `/events` stream: a turn is `channel_web_chat` on +//! the seat's one thread, followed by its events until `chat_done` or +//! `chat_error`, and cancelled with `channel_web_cancel`. +//! +//! Before a seat starts, [`capability::check`] holds it to the `openhuman` +//! column of the capability table in `docs/specs/harnesses.md`: only an +//! `openai` provider with an explicit endpoint and no credential, no more +//! than [`capability::ITERATION_CAP`] iterations, no sandbox, no built-in +//! tools. A start is verified: the process answering is the child, its +//! version is the pin, its effective config is the one written, and its +//! model sees exactly the host's tools. +//! +//! ```no_run +//! use std::sync::Arc; +//! use tinyhivemind_host::harness::{Harness, SeatPlan, ToolEndpoint}; +//! use tinyhivemind_openhuman_process::{OpenHumanHarness, Program}; +//! +//! # async fn start(seat: tinyhivemind_lang::LoweredSeat) -> Result<(), Box> { +//! let harness = OpenHumanHarness::new(Program::new("/opt/oh/openhuman-core", "0.64.15")); +//! let tools = ToolEndpoint::new( +//! "hivemind", +//! "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 names no `OpenHuman` type and links no +//! harness, so it outlives the linked adapter; it serves no tools (the host's +//! MCP server does, and judges their policy); and it never downloads a +//! binary: `.github/scripts/fetch-harness.sh` fetches the one pinned in +//! `harnesses.lock`, and the host passes its path. +pub mod capability; +mod config; +mod error; +mod harness; +mod instance; +mod rpc; +mod turn; + +pub use harness::{OpenHumanHarness, Options, Program}; + +#[cfg(test)] +#[path = "../tests/fake/surface.rs"] +mod fake; +#[cfg(test)] +mod fixture; +#[cfg(test)] +#[path = "../tests/support/http.rs"] +mod http; diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/README.md b/crates/tinyhivemind-openhuman-process/src/rpc/README.md new file mode 100644 index 00000000..c486eacc --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/rpc/README.md @@ -0,0 +1,12 @@ +# Loopback client + +`Client` talks to one instance at `http://127.0.0.1:` with its core +token as bearer: `call` for JSON-RPC at `/rpc` (30 s each), `health` for +`/health`, and `events` for the `/events` stream of one `client_id`, parsed by +`sse::Parser`. No proxy, no TLS, and no URL, token or body in an error. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `Client`, `Events`, `Error` | +| `sse.rs` | Server-Sent Events framing | +| `test.rs` | Against the fake surface, and the parser on every split | diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs b/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs new file mode 100644 index 00000000..4b81a992 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/rpc/mod.rs @@ -0,0 +1,180 @@ +//! The instance's loopback API: JSON-RPC at `/rpc`, `/health`, and the +//! `/events` stream of one `client_id`. +//! +//! Every request carries the instance's core token as a bearer. The client +//! uses no proxy and no TLS: the URL is always `http://127.0.0.1:`. +//! Neither the token nor a request body is ever put in an error. +mod sse; + +use serde_json::{Value, json}; +use std::collections::VecDeque; +use std::time::Duration; + +/// How long one RPC may take. Turns are not RPCs: `channel_web_chat` +/// answers once the turn is accepted. +const CALL: Duration = Duration::from_secs(30); + +/// Result of an API call. +pub(crate) type Result = std::result::Result; + +/// API failures. +#[derive(Debug, thiserror::Error)] +pub(crate) enum Error { + /// Nothing answered, or the connection broke. + #[error("the instance could not be reached: {0}")] + Transport(String), + /// An answer other than 200. + #[error("{what} answered with status {status}")] + Status { + /// The endpoint. + what: &'static str, + /// Its status. + status: u16, + }, + /// A JSON-RPC error. + #[error("{method} failed: {message}")] + Rpc { + /// The method. + method: String, + /// The instance's message. + message: String, + }, + /// An answer that is not what the API says. + #[error("the instance answered with something unreadable: {0}")] + Decode(String), +} + +impl From for Error { + fn from(error: reqwest::Error) -> Self { + // Without the URL: it is loopback, and says nothing a reader needs. + Self::Transport(error.without_url().to_string()) + } +} + +/// A client of one instance. +#[derive(Clone)] +pub(crate) struct Client { + http: reqwest::Client, + base: String, + token: String, +} + +impl Client { + /// The instance at `127.0.0.1:port`, which takes `token`. + pub(crate) fn new(port: u16, token: &str) -> Result { + let http = reqwest::Client::builder().no_proxy().build()?; + Ok(Self { + http, + base: format!("http://127.0.0.1:{port}"), + token: token.to_owned(), + }) + } + + /// `GET /health`, which only a healthy instance answers with 200. + pub(crate) async fn health(&self) -> Result { + let url = format!("{}/health", self.base); + let response = self.http.get(url).timeout(CALL).send().await?; + let status = response.status().as_u16(); + if status != 200 { + return Err(Error::Status { + what: "/health", + status, + }); + } + decode(&response.bytes().await?) + } + + /// Call `method` with `params`; its `result`. + pub(crate) async fn call(&self, method: &str, params: Value) -> Result { + let body = json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}); + let response = self + .http + .post(format!("{}/rpc", self.base)) + .bearer_auth(&self.token) + .header("content-type", "application/json") + .body(body.to_string()) + .timeout(CALL) + .send() + .await?; + let status = response.status().as_u16(); + if status != 200 { + return Err(Error::Status { + what: "/rpc", + status, + }); + } + let mut answer = decode(&response.bytes().await?)?; + if let Some(error) = answer.get("error").filter(|error| !error.is_null()) { + let message = error["message"].as_str().unwrap_or("no message"); + return Err(Error::Rpc { + method: method.to_owned(), + message: message.to_owned(), + }); + } + Ok(answer["result"].take()) + } + + /// Subscribe to the events of `client`. They are published to whoever + /// is subscribed when they happen, so this must come first. + pub(crate) async fn events(&self, client: &str) -> Result { + let response = self + .http + .get(format!("{}/events", self.base)) + .query(&[("client_id", client)]) + .bearer_auth(&self.token) + .send() + .await?; + let status = response.status().as_u16(); + if status != 200 { + return Err(Error::Status { + what: "/events", + status, + }); + } + Ok(Events { + response, + parser: sse::Parser::default(), + ready: VecDeque::new(), + }) + } +} + +impl std::fmt::Debug for Client { + /// The token is the instance's whole authority, so it is not shown. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Client") + .field("base", &self.base) + .field("token", &"redacted") + .finish_non_exhaustive() + } +} + +fn decode(bytes: &[u8]) -> Result { + serde_json::from_slice(bytes).map_err(|error| Error::Decode(error.to_string())) +} + +/// One client's event stream. Dropping it closes the connection. +#[derive(Debug)] +pub(crate) struct Events { + response: reqwest::Response, + parser: sse::Parser, + ready: VecDeque>, +} + +impl Events { + /// The next event's payload, or `None` once the stream has ended. + pub(crate) async fn next(&mut self) -> Result> { + loop { + if let Some(ready) = self.ready.pop_front() { + return ready.map(Some); + } + match self.response.chunk().await? { + Some(chunk) => self.ready.extend(self.parser.push(&chunk)), + None => return Ok(None), + } + } + } +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/sse.rs b/crates/tinyhivemind-openhuman-process/src/rpc/sse.rs new file mode 100644 index 00000000..9ac143ce --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/rpc/sse.rs @@ -0,0 +1,42 @@ +//! Server-Sent Events, as `/events` frames them: `event:` and `data:` lines, +//! a blank line ending each message, and `:` comments for keep-alive. +use super::Error; +use serde_json::Value; + +/// Bytes in, JSON payloads out, whatever the chunking. +#[derive(Debug, Default)] +pub(crate) struct Parser { + line: Vec, + data: Vec, +} + +impl Parser { + /// Feed `bytes`; the payloads of every message they complete. + pub(crate) fn push(&mut self, bytes: &[u8]) -> Vec> { + let mut frames = Vec::new(); + for &byte in bytes { + if byte != b'\n' { + self.line.push(byte); + continue; + } + let mut line = std::mem::take(&mut self.line); + if line.last() == Some(&b'\r') { + line.pop(); + } + if line.is_empty() { + if !self.data.is_empty() { + let data = std::mem::take(&mut self.data).join("\n"); + let parsed = serde_json::from_str(&data); + frames.push(parsed.map_err(|error| Error::Decode(error.to_string()))); + } + continue; + } + let line = String::from_utf8_lossy(&line); + if let Some(data) = line.strip_prefix("data:") { + self.data + .push(data.strip_prefix(' ').unwrap_or(data).to_owned()); + } + } + frames + } +} diff --git a/crates/tinyhivemind-openhuman-process/src/rpc/test.rs b/crates/tinyhivemind-openhuman-process/src/rpc/test.rs new file mode 100644 index 00000000..9b30036e --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/rpc/test.rs @@ -0,0 +1,146 @@ +//! The loopback client against the fake surface, and the SSE parser alone. +use super::sse::Parser; +use super::{Client, Error}; +use crate::fixture::{Fixture, PID}; +use serde_json::json; + +#[tokio::test] +async fn health_reports_the_process_that_answers() { + let fixture = Fixture::new().await; + let health = fixture.client.health().await; + assert_eq!( + health.ok().map(|health| health["pid"].clone()), + Some(json!(PID)) + ); +} + +#[tokio::test] +async fn a_call_returns_its_result() { + let fixture = Fixture::new().await; + let version = fixture.client.call("core.version", json!({})).await; + assert_eq!(version.ok(), Some(json!({"version": "0.64.15"}))); +} + +#[tokio::test] +async fn a_wrong_token_is_refused_by_status() { + let fixture = Fixture::new().await; + let client = Client::new(fixture.fake.port, "wrong"); + let client = client.unwrap_or_else(|error| unreachable!("{error}")); + let refused = client.call("core.version", json!({})).await; + assert!( + matches!(refused, Err(Error::Status { status: 401, .. })), + "{refused:?}" + ); + let events = client.events("c").await.err(); + assert!(matches!(events, Some(Error::Status { status: 401, .. }))); +} + +#[tokio::test] +async fn an_rpc_error_carries_its_method_and_message() { + let fixture = Fixture::new().await; + let refused = fixture.client.call("openhuman.nope", json!({})).await; + let Err(Error::Rpc { method, message }) = refused else { + unreachable!("refused as an rpc error: {refused:?}") + }; + assert_eq!(method, "openhuman.nope"); + assert_eq!(message, "unknown method: openhuman.nope"); +} + +#[tokio::test] +async fn nobody_listening_is_a_transport_error() { + let port = { + let listener = std::net::TcpListener::bind("127.0.0.1:0"); + let listener = listener.unwrap_or_else(|error| unreachable!("{error}")); + listener.local_addr().map_or(1, |address| address.port()) + }; + let client = Client::new(port, "t").unwrap_or_else(|error| unreachable!("{error}")); + let refused = client.health().await; + assert!(matches!(refused, Err(Error::Transport(_))), "{refused:?}"); +} + +#[tokio::test] +async fn events_are_those_of_the_subscribed_client_in_order() { + let fixture = Fixture::new().await; + fixture.script(&[json!({"reply": "hi", "tokens": 5})]); + let mut mine = fixture + .client + .events("mine") + .await + .unwrap_or_else(|error| unreachable!("{error}")); + let params = json!({"client_id": "mine", "thread_id": "t", "message": "go"}); + let ack = fixture + .client + .call("openhuman.channel_web_chat", params) + .await; + assert_eq!( + ack.ok().map(|ack| ack["result"]["accepted"].clone()), + Some(json!(true)) + ); + let mut names = Vec::new(); + while let Ok(Some(event)) = mine.next().await { + let name = event["event"].as_str().unwrap_or_default().to_owned(); + assert_eq!(event["client_id"], "mine"); + names.push(name.clone()); + if name == "chat_done" { + break; + } + } + assert_eq!( + names, + ["iteration_start", "text_delta", "turn_cost", "chat_done"] + ); +} + +#[tokio::test] +async fn a_stream_the_server_drops_ends() { + let fixture = Fixture::new().await; + let mut events = fixture + .client + .events("c") + .await + .unwrap_or_else(|error| unreachable!("{error}")); + drop(fixture); + let ended = events.next().await; + assert!( + matches!(ended, Ok(None) | Err(Error::Transport(_))), + "{ended:?}" + ); +} + +#[test] +fn sse_frames_split_anywhere_are_put_back_together() { + let text = + ": keep-alive\n\nevent: a\ndata: {\"n\":\ndata: 1}\n\nevent: b\r\ndata: {\"n\":2}\r\n\r\n"; + for split in 0..text.len() { + let mut parser = Parser::default(); + let mut found = parser.push(&text.as_bytes()[..split]); + found.extend(parser.push(&text.as_bytes()[split..])); + let found: Vec<_> = found + .into_iter() + .map(|frame| frame.map_err(|error| error.to_string())) + .collect(); + assert_eq!( + found, + [Ok(json!({"n": 1})), Ok(json!({"n": 2}))], + "split at {split}" + ); + } +} + +#[test] +fn an_sse_frame_that_is_not_json_is_an_error() { + let mut parser = Parser::default(); + let found = parser.push(b"data: nope\n\n"); + assert!( + matches!(found.as_slice(), [Err(Error::Decode(_))]), + "{found:?}" + ); +} + +#[test] +fn debug_does_not_show_the_core_token() { + let client = + Client::new(1, "secret-core-token").unwrap_or_else(|error| unreachable!("{error}")); + let shown = format!("{client:?}"); + assert!(!shown.contains("secret-core-token"), "{shown}"); +} diff --git a/crates/tinyhivemind-openhuman-process/src/turn/README.md b/crates/tinyhivemind-openhuman-process/src/turn/README.md new file mode 100644 index 00000000..89146aad --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/turn/README.md @@ -0,0 +1,19 @@ +# Turns + +`run` subscribes to `/events` for the turn's own `client_id`, then submits +`channel_web_chat` on the seat's thread, records the returned `request_id` in +the seat's `Active`, and follows that request's events: progress, approvals +through the seat's approver and `approval_decide`, `chat_done` with the turn's +own usage, `chat_error` and `chat_cancelled` as failures. Reaching the +eight-iteration cap is a failed turn, as is passing a lower seat limit. +Approvals are denied when the approver takes longer than its limit, and an +`approval_request` without an id fails the turn. `deny_stale` denies what a +turn that is over left pending. A `chat_error` message is kept to one line of +200 characters. +`cancel` is `channel_web_cancel` scoped to the request, then a wait for its end. +A turn is never submitted twice. + +| File | Purpose | +| --- | --- | +| `mod.rs` | `run`, `cancel`, `Turn`, `Active`, `Ended`, `Error` | +| `test.rs` | Against the fake surface | diff --git a/crates/tinyhivemind-openhuman-process/src/turn/mod.rs b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs new file mode 100644 index 00000000..fd9f1ea1 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/turn/mod.rs @@ -0,0 +1,318 @@ +//! One turn: `channel_web_chat` on the seat's thread, followed on `/events`. +//! +//! The order matters, and so does what is ignored: +//! +//! 1. Subscribe to `/events` for the turn's own `client_id` first, since +//! events go only to whoever is subscribed when they happen, and the +//! first ones can be out before `channel_web_chat` answers. +//! 2. Submit, and keep the `request_id` it returns in the seat's [`Active`], +//! which is what a cancellation names. The turn is never submitted again. +//! 3. Read events of that `request_id` only. `approval_request` is the +//! exception: its `request_id` is the approval's, and the seat's approver +//! decides it through `approval_decide`. +//! 4. `chat_done` ends the turn with its reply and usage, unless the turn +//! reached [`ITERATION_CAP`] `iteration_start` events, which the binary +//! reports as a normal end. `chat_error` and `chat_cancelled` fail it. +//! A seat limit below the cap fails the turn at the first iteration past +//! it, and the seat runner then cancels it. +//! +//! [`cancel`] is `channel_web_cancel` scoped to the request, then a wait for +//! that request's end on a fresh subscription. +use crate::capability::ITERATION_CAP; +use crate::rpc::{self, Client, Events}; +use serde_json::{Value, json}; +use std::sync::{Mutex, PoisonError}; +use tinyhivemind_host::harness::{ + Approver, Event, Observer, Progress, ToolApproval, ToolDecision, TurnUsage, +}; +use tokio::sync::watch; + +/// Result of a turn. +pub(crate) type Result = std::result::Result; + +/// Why a turn has no outcome. +#[derive(Debug, thiserror::Error)] +pub(crate) enum Error { + /// The API failed. + #[error(transparent)] + Api(#[from] rpc::Error), + /// `channel_web_chat` answered without accepting the message. + #[error("the instance did not accept the turn: {0}")] + NotAccepted(String), + /// The event stream ended before the turn did: the instance went away. + #[error("the event stream ended before the turn did")] + StreamEnded, + /// The seat is being stopped. + #[error("the turn was closed by a stop")] + Closed, + /// An event the API does not allow. + #[error("the instance broke its protocol: {0}")] + Protocol(&'static str), +} + +/// The submitted turn of a seat, which a cancellation names. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct Active { + /// The seat's thread. + pub(crate) thread: String, + /// The turn's own `client_id`. + pub(crate) client_id: String, + /// What `channel_web_chat` returned, once it has. + pub(crate) request_id: Option, +} + +/// How a turn ended. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub(crate) struct Ended { + /// The model's reply. + pub(crate) reply: Option, + /// What the turn used, if it said. + pub(crate) usage: Option, + /// Why it failed, if it did. + pub(crate) failure: Option, +} + +/// What one turn runs with. +pub(crate) struct Turn<'a> { + pub(crate) client: &'a Client, + pub(crate) seat: &'a str, + pub(crate) thread: &'a str, + /// The coordinator's turn id. + pub(crate) id: &'a str, + pub(crate) client_id: String, + /// The seat's iteration limit, at most [`ITERATION_CAP`]. + pub(crate) iterations: usize, + pub(crate) observer: &'a dyn Observer, + pub(crate) approver: &'a dyn Approver, + /// How long the approver may take; then the call is denied. + pub(crate) approval_limit: std::time::Duration, + /// Becomes true when the seat is stopped. + pub(crate) closed: watch::Receiver, +} + +fn set(active: &Mutex>, value: Option) { + *active.lock().unwrap_or_else(PoisonError::into_inner) = value; +} + +/// Run `turn` with `message`. `active` holds the submitted turn until it has +/// ended, so that a turn dropped meanwhile can be cancelled. +pub(crate) async fn run( + mut turn: Turn<'_>, + message: &str, + active: &Mutex>, +) -> Result { + let mut events = turn.client.events(&turn.client_id).await?; + let mut submitted = Active { + thread: turn.thread.to_owned(), + client_id: turn.client_id.clone(), + request_id: None, + }; + set(active, Some(submitted.clone())); + let params = json!({"client_id": turn.client_id, "thread_id": turn.thread, "message": message}); + let ack = turn + .client + .call("openhuman.channel_web_chat", params) + .await?; + let ack = &ack["result"]; + let request_id = ack["request_id"] + .as_str() + .filter(|_| ack["accepted"] == true); + let request_id = request_id.ok_or_else(|| Error::NotAccepted(ack.to_string()))?; + submitted.request_id = Some(request_id.to_owned()); + set(active, Some(submitted)); + let mut closed = turn.closed.clone(); + let ended = tokio::select! { + ended = follow(&turn, request_id, &mut events) => ended, + _ = closed.wait_for(|closed| *closed) => Err(Error::Closed), + }; + turn.closed = closed; + let (ended, over) = ended?; + if over { + set(active, None); + } + Ok(ended) +} + +/// Read events until the request ends, or fails while it runs on: whether +/// the instance's turn is over. +async fn follow(turn: &Turn<'_>, request_id: &str, events: &mut Events) -> Result<(Ended, bool)> { + let mut iterations = 0_usize; + let progress = |progress| Event::Progress { + turn_id: turn.id.to_owned(), + progress, + }; + while let Some(event) = events.next().await? { + let name = event["event"].as_str().unwrap_or_default(); + if name == "approval_request" { + approve(turn, &event).await?; + continue; + } + if event["request_id"] != request_id { + continue; + } + let text = |key: &str| event[key].as_str().unwrap_or_default().to_owned(); + match name { + "iteration_start" => { + iterations += 1; + let iteration = u32::try_from(iterations).unwrap_or(u32::MAX); + let step = progress(Progress::ModelCall { iteration }); + turn.observer.event(turn.seat, step); + if turn.iterations < ITERATION_CAP && iterations > turn.iterations { + let failure = format!( + "the turn started iteration {iterations}, past the seat's limit of {}", + turn.iterations + ); + let ended = Ended { + failure: Some(failure), + ..Ended::default() + }; + return Ok((ended, false)); + } + } + "text_delta" if event["delta_kind"] == "text" => { + let delta = Progress::Text { + delta: text("delta"), + }; + turn.observer.event(turn.seat, progress(delta)); + } + "tool_call" => { + let call = Progress::ToolCall { + call_id: text("tool_call_id"), + tool: text("tool_name"), + }; + turn.observer.event(turn.seat, progress(call)); + } + "tool_result" => { + let result = Progress::ToolResult { + call_id: text("tool_call_id"), + failed: event["success"] != true, + }; + turn.observer.event(turn.seat, progress(result)); + } + "chat_done" => { + let failure = (iterations >= ITERATION_CAP).then(|| { + format!( + "the turn reached the binary's cap of {ITERATION_CAP} iterations, which it reports as a normal end" + ) + }); + let ended = Ended { + reply: event["full_response"].as_str().map(str::to_owned), + usage: usage(&event["usage"]), + failure, + }; + return Ok((ended, true)); + } + "chat_error" | "chat_cancelled" => { + let failure = bounded(name, &text("error_type"), &text("message")); + let ended = Ended { + failure: Some(failure), + ..Ended::default() + }; + return Ok((ended, true)); + } + _ => {} + } + } + Err(Error::StreamEnded) +} + +fn usage(usage: &Value) -> Option { + let count = |key: &str| usage[key].as_u64(); + Some(TurnUsage { + input_tokens: count("input_tokens")?, + cached_input_tokens: count("cached_input_tokens").unwrap_or(0), + output_tokens: count("output_tokens").unwrap_or(0), + reasoning_tokens: 0, + }) +} + +/// Ask the seat's approver, and tell the instance. +async fn approve(turn: &Turn<'_>, event: &Value) -> Result<()> { + let id = event["request_id"].as_str().filter(|id| !id.is_empty()); + let id = id.ok_or(Error::Protocol("an approval_request without a request_id"))?; + let id = id.to_owned(); + let request = ToolApproval { + seat: turn.seat.to_owned(), + turn_id: turn.id.to_owned(), + call_id: id.clone(), + tool: event["tool_name"].as_str().unwrap_or_default().to_owned(), + arguments: event["args"].clone(), + }; + // 0.64.15's `approval_decide` takes no reason, so a denial's is not + // passed on; the model is told only that the call was refused. + let decision = turn.approver.decide(request); + let decision = match tokio::time::timeout(turn.approval_limit, decision).await { + Ok(ToolDecision::Allow) => "approve_once", + Ok(ToolDecision::Deny { .. }) | Err(_) => "deny", + }; + let params = json!({"request_id": id, "decision": decision}); + turn.client + .call("openhuman.approval_decide", params) + .await?; + Ok(()) +} + +/// Deny every approval still pending, which only a turn that is over can +/// have left, as a seat runs one turn at a time; how many there were. +pub(crate) async fn deny_stale(client: &Client) -> Result { + let listed = client + .call("openhuman.approval_list_pending", json!({})) + .await?; + let pending = listed["result"].as_array().cloned().unwrap_or_default(); + let ids: Vec<&str> = pending + .iter() + .filter_map(|row| row["request_id"].as_str()) + .collect(); + for id in &ids { + let params = json!({"request_id": id, "decision": "deny"}); + client.call("openhuman.approval_decide", params).await?; + } + Ok(ids.len()) +} + +/// At most this much of a `chat_error` message is kept. +const MESSAGE: usize = 200; + +/// The harness's own failure text, one bounded line, without what a +/// provider may have put after it. +fn bounded(name: &str, kind: &str, message: &str) -> String { + let kind: String = kind + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '_') + .take(40) + .collect(); + let line = message.lines().next().unwrap_or_default(); + let line: String = line + .chars() + .filter(|c| !c.is_control()) + .take(MESSAGE) + .collect(); + format!("{name} ({kind}): {line}") +} + +/// Cancel `active`, returning once its request has ended. +pub(crate) async fn cancel(client: &Client, active: &Active) -> Result<()> { + let mut events = client.events(&active.client_id).await?; + let mut params = json!({"client_id": active.client_id, "thread_id": active.thread}); + if let Some(request_id) = &active.request_id { + params["request_id"] = json!(request_id); + } + let ack = client.call("openhuman.channel_web_cancel", params).await?; + let Some(cancelled) = ack["result"]["request_id"].as_str() else { + // Nothing was running, so no end follows. + return Ok(()); + }; + while let Some(event) = events.next().await? { + let ends = matches!( + event["event"].as_str(), + Some("chat_error" | "chat_cancelled" | "chat_done") + ); + if ends && event["request_id"] == cancelled { + return Ok(()); + } + } + Err(Error::StreamEnded) +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-openhuman-process/src/turn/test.rs b/crates/tinyhivemind-openhuman-process/src/turn/test.rs new file mode 100644 index 00000000..1f74454c --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/src/turn/test.rs @@ -0,0 +1,321 @@ +//! One turn over `channel_web_chat` and `/events`, against the fake surface. +use super::{Active, Ended, Turn, cancel, run}; +use crate::fixture::Fixture; +use serde_json::{Value, json}; +use std::sync::{Arc, Mutex, PoisonError}; +use tinyhivemind_host::harness::{ + ApprovalFuture, Approver, DenyAll, Event, Observer, Progress, ToolApproval, ToolDecision, + TurnUsage, +}; +use tokio::sync::watch; + +#[derive(Default)] +struct Recorder(Mutex>); + +impl Observer for Recorder { + fn event(&self, _: &str, event: Event) { + self.0 + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(event); + } +} + +impl Recorder { + fn progress(&self) -> Vec { + let events = self.0.lock().unwrap_or_else(PoisonError::into_inner); + let progress = events.iter().filter_map(|event| match event { + Event::Progress { progress, .. } => Some(progress.clone()), + _ => None, + }); + progress.collect() + } +} + +struct AllowAll; + +impl Approver for AllowAll { + fn decide(&self, _: ToolApproval) -> ApprovalFuture { + Box::pin(async { ToolDecision::Allow }) + } +} + +struct Harnessed { + fixture: Fixture, + events: Arc, + active: Arc>>, + closed: watch::Sender, +} + +impl Harnessed { + async fn new(steps: &[Value]) -> Self { + let fixture = Fixture::new().await; + fixture.script(steps); + Self { + fixture, + events: Arc::default(), + active: Arc::default(), + closed: watch::channel(false).0, + } + } + + fn turn<'a>(&'a self, approver: &'a dyn Approver, iterations: usize) -> Turn<'a> { + Turn { + client: &self.fixture.client, + seat: "scout", + thread: "thm-scout", + id: "t1", + client_id: "thm-1".into(), + iterations, + observer: self.events.as_ref(), + approver, + approval_limit: std::time::Duration::from_secs(5), + closed: self.closed.subscribe(), + } + } + + async fn run(&self, iterations: usize) -> super::Result { + run(self.turn(&DenyAll, iterations), "go", &self.active).await + } +} + +#[tokio::test] +async fn a_turn_ends_with_its_reply_and_its_own_usage() { + let harnessed = Harnessed::new(&[json!({"reply": "done", "tokens": 40})]).await; + let ended = harnessed.run(8).await; + let usage = TurnUsage { + input_tokens: 40, + cached_input_tokens: 4, + output_tokens: 2, + reasoning_tokens: 0, + }; + let expected = Ended { + reply: Some("done".into()), + usage: Some(usage), + failure: None, + }; + assert_eq!(ended.ok(), Some(expected)); + // Published before `channel_web_chat` answered, and still seen. + let progress = harnessed.events.progress(); + assert_eq!( + progress.first(), + Some(&Progress::ModelCall { iteration: 1 }) + ); + assert!(progress.contains(&Progress::Text { + delta: "done".into() + })); + assert!(harnessed.active.lock().is_ok_and(|active| active.is_none())); +} + +#[tokio::test] +async fn another_requests_events_are_not_this_turns() { + let step = json!({"reply": "mine", "tokens": 1, "stray": true}); + let harnessed = Harnessed::new(&[step]).await; + let ended = harnessed.run(8).await; + assert_eq!( + ended.ok().and_then(|ended| ended.reply), + Some("mine".into()) + ); +} + +#[tokio::test] +async fn a_chat_error_fails_the_turn() { + let harnessed = Harnessed::new(&[json!({"error": "provider down"})]).await; + let ended = harnessed.run(8).await; + let failure = ended.ok().and_then(|ended| ended.failure); + assert!(failure.is_some_and(|failure| failure.contains("provider down"))); +} + +#[tokio::test] +async fn reaching_the_eight_iteration_cap_is_a_failed_turn_with_its_usage() { + let step = json!({"reply": "checkpoint", "tokens": 9, "iterations": 8}); + let harnessed = Harnessed::new(&[step]).await; + let ended = harnessed.run(8).await.ok(); + let failure = ended.as_ref().and_then(|ended| ended.failure.clone()); + assert!(failure.is_some_and(|failure| failure.contains("cap of 8"))); + let usage = ended.and_then(|ended| ended.usage); + assert_eq!(usage.map(|usage| usage.input_tokens), Some(9)); +} + +#[tokio::test] +async fn a_seat_limit_below_the_cap_fails_the_turn_past_it() { + let step = json!({"reply": "late", "tokens": 1, "iterations": 5}); + let harnessed = Harnessed::new(&[step]).await; + let ended = harnessed.run(3).await.ok(); + let failure = ended.and_then(|ended| ended.failure); + assert!(failure.is_some_and(|failure| failure.contains("limit of 3"))); + let seven = Harnessed::new(&[json!({"reply": "ok", "iterations": 3})]).await; + let ended = seven.run(3).await.ok(); + assert_eq!(ended.and_then(|ended| ended.failure), None); +} + +#[tokio::test] +async fn a_harness_approval_is_decided_by_the_approver() { + let step = json!({"reply": "after", "approval": "shell"}); + let harnessed = Harnessed::new(std::slice::from_ref(&step)).await; + assert!(harnessed.run(8).await.is_ok()); + let allowed = Harnessed::new(&[step]).await; + assert!( + run(allowed.turn(&AllowAll, 8), "go", &allowed.active) + .await + .is_ok() + ); + let decided = |harnessed: &Harnessed| { + let log = harnessed.fixture.log("decisions.jsonl"); + log.iter() + .map(|entry| entry["decision"].clone()) + .collect::>() + }; + assert_eq!(decided(&harnessed), [json!("deny")]); + assert_eq!(decided(&allowed), [json!("approve_once")]); +} + +#[tokio::test] +async fn a_tool_call_and_its_result_are_progress() { + let step = json!({"reply": "ok", "tool": "mcp_hivemind_hivemind_post_000001"}); + let harnessed = Harnessed::new(&[step]).await; + assert!(harnessed.run(8).await.is_ok()); + let progress = harnessed.events.progress(); + let call = Progress::ToolCall { + call_id: "call_1".into(), + tool: "mcp_hivemind_hivemind_post_000001".into(), + }; + let result = Progress::ToolResult { + call_id: "call_1".into(), + failed: true, + }; + assert!( + progress.contains(&call) && progress.contains(&result), + "{progress:?}" + ); +} + +#[tokio::test] +async fn a_cancelled_turn_is_shown_to_have_stopped() { + let harnessed = Arc::new(Harnessed::new(&[Value::Null]).await); + let running = harnessed.clone(); + let task = tokio::spawn(async move { running.run(8).await.is_ok() }); + while harnessed.fixture.calls() != ["open"] { + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + task.abort(); + let active = harnessed + .active + .lock() + .ok() + .and_then(|mut active| active.take()); + let active = active.unwrap_or_else(|| unreachable!("a dropped turn leaves itself")); + assert!(active.request_id.is_some()); + let cancelled = cancel(&harnessed.fixture.client, &active).await; + assert!(cancelled.is_ok(), "{cancelled:?}"); + assert_eq!(harnessed.fixture.calls(), ["aborted"]); + // Nothing is running any more, so a second cancel returns at once. + let again = cancel(&harnessed.fixture.client, &active).await; + assert!(again.is_ok()); +} + +#[tokio::test] +async fn a_closed_turn_ends_without_waiting_for_the_harness() { + let harnessed = Arc::new(Harnessed::new(&[Value::Null]).await); + let running = harnessed.clone(); + let task = tokio::spawn(async move { running.run(8).await.err().map(|e| e.to_string()) }); + while harnessed.fixture.calls() != ["open"] { + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + let _ = harnessed.closed.send(true); + let ended = task.await.ok().flatten(); + assert!(ended.is_some_and(|error| error.contains("closed"))); +} + +#[tokio::test] +async fn a_message_the_instance_does_not_accept_fails_and_agent_chat_is_never_used() { + let fixture = Fixture::with(&[]).await; + let harnessed = Harnessed { + fixture, + events: Arc::default(), + active: Arc::default(), + closed: watch::channel(false).0, + }; + let mut turn = harnessed.turn(&DenyAll, 8); + turn.thread = ""; + let ended = run(turn, "go", &harnessed.active).await; + assert!(ended.is_err()); + let methods = harnessed.fixture.log("methods.jsonl"); + assert!(!methods.contains(&json!("openhuman.inference_agent_chat"))); + assert!(methods.contains(&json!("openhuman.channel_web_chat"))); +} + +/// Never answers. +struct Silent; + +impl Approver for Silent { + fn decide(&self, _: ToolApproval) -> ApprovalFuture { + Box::pin(std::future::pending()) + } +} + +#[tokio::test] +async fn an_approver_that_does_not_answer_in_time_is_a_denial() { + let harnessed = Harnessed::new(&[json!({"reply": "after", "approval": "shell"})]).await; + let mut turn = harnessed.turn(&Silent, 8); + turn.approval_limit = std::time::Duration::from_millis(100); + assert!(run(turn, "go", &harnessed.active).await.is_ok()); + let decided = harnessed.fixture.log("decisions.jsonl"); + assert_eq!( + decided.first().map(|entry| entry["decision"].clone()), + Some(json!("deny")) + ); +} + +#[tokio::test] +async fn an_approval_request_without_an_id_fails_the_turn_clearly() { + let step = json!({"reply": "after", "approval": "shell", "approval_id": ""}); + let harnessed = Harnessed::new(&[step]).await; + let ended = harnessed.run(8).await; + let error = ended.err().map(|error| error.to_string()); + assert!(error.is_some_and(|error| error.contains("approval_request without a request_id"))); +} + +#[tokio::test] +async fn an_approval_left_by_a_dropped_turn_is_denied_before_the_next() { + let harnessed = + Arc::new(Harnessed::new(&[json!({"reply": "late", "approval": "shell"})]).await); + let running = harnessed.clone(); + let task = tokio::spawn(async move { + run(running.turn(&Silent, 8), "go", &running.active) + .await + .is_ok() + }); + let client = harnessed.fixture.client.clone(); + let mut pending = 0; + while pending == 0 { + let listed = client + .call("openhuman.approval_list_pending", json!({})) + .await; + pending = listed + .ok() + .and_then(|listed| listed["result"].as_array().map(Vec::len)) + .unwrap_or(0); + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + task.abort(); + let denied = super::deny_stale(&client).await; + assert_eq!(denied.ok(), Some(1)); + let decided = harnessed.fixture.log("decisions.jsonl"); + assert_eq!( + decided.first().map(|entry| entry["decision"].clone()), + Some(json!("deny")) + ); + assert_eq!(super::deny_stale(&client).await.ok(), Some(0)); +} + +#[tokio::test] +async fn a_chat_error_is_bounded_and_carries_no_payload() { + let payload = format!("upstream said:\n{{\"error\": \"{}\"}}", "x".repeat(5000)); + let harnessed = Harnessed::new(&[json!({"error": payload})]).await; + let failure = harnessed.run(8).await.ok().and_then(|ended| ended.failure); + let failure = failure.unwrap_or_else(|| unreachable!("a failure")); + assert!(failure.len() <= 300, "{} bytes", failure.len()); + assert!(!failure.contains('\n'), "{failure}"); + assert!(failure.starts_with("chat_error (inference)"), "{failure}"); +} diff --git a/crates/tinyhivemind-openhuman-process/tests/README.md b/crates/tinyhivemind-openhuman-process/tests/README.md new file mode 100644 index 00000000..4841cee4 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/README.md @@ -0,0 +1,9 @@ +# Tests + +| Path | Purpose | +| --- | --- | +| `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`). | +| [`fake/`](fake/README.md) | The fake `openhuman-core` surface and child | +| [`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/conformance.rs b/crates/tinyhivemind-openhuman-process/tests/conformance.rs new file mode 100644 index 00000000..9ad5e4f0 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/conformance.rs @@ -0,0 +1,193 @@ +//! The host's conformance suite over this runner and a fake `openhuman-core` +//! child, so that supervision is real; and the seat refusals through the +//! port. Linux only, as the suite escapes a process group on purpose. +#![cfg(target_os = "linux")] + +#[path = "support/seat.rs"] +mod seat_support; +#[path = "fake/subject.rs"] +mod subject; + +use anyhow::Result; +use subject::FakeSubject; +use tinyhivemind_hives::TurnDisposition; +use tinyhivemind_host::harness::conformance::{Case, Subject as _}; +use tinyhivemind_host::harness::{Error, HarnessKind, SeatPlan}; +use tinyhivemind_openhuman_process::capability::Refusal; + +/// One test per case, and a check that no case is left out. +macro_rules! passes { + ($($name:ident => $case:ident),* $(,)?) => { + $( + #[tokio::test(flavor = "multi_thread")] + async fn $name() -> Result<()> { + Case::$case.run(&FakeSubject::new()?).await?; + Ok(()) + } + )* + #[test] + fn every_case_is_run() { + assert_eq!(Case::ALL, [$(Case::$case),*]); + } + }; +} + +passes! { + a_second_turn_continues_the_session => SecondTurnContinues, + a_session_is_resumed_after_a_restart => ResumesAfterRestart, + a_resume_failure_is_an_error => ResumeFailureIsAnError, + a_timeout_stops_the_turn => TimeoutStopsTheTurn, + a_dropped_run_stops_the_turn => DropStopsTheTurn, + a_kill_neither_replays_nor_loses_the_seat => KillNeitherReplaysNorLosesTheSeat, + one_turn_runs_at_a_time => OneTurnAtATime, + no_turn_runs_twice => NoTurnTwice, + usage_is_per_turn => UsageIsPerTurn, + the_tool_list_is_exact => ToolListIsExact, + the_config_is_the_one_written => ConfigIsTheOneWritten, + nothing_is_left_after_stop => NothingLeftAfterStop, +} + +#[tokio::test] +async fn the_harness_is_the_openhuman_kind() -> Result<()> { + let subject = FakeSubject::new()?; + assert_eq!(subject.harness().kind(), HarnessKind::OpenHuman); + Ok(()) +} + +#[tokio::test] +async fn a_seat_it_cannot_honour_is_refused_before_anything_starts() -> Result<()> { + let subject = FakeSubject::new()?; + let mut seat = seat_support::seat("http://127.0.0.1:9/v1"); + seat.integration.limits.iterations = Some(20); + let plan = SeatPlan::new(seat, subject.root_path().join("instance")); + let refused = subject.harness().start(plan, subject.endpoint()).await; + let Err(Error::Refused(refusal)) = refused else { + anyhow::bail!("not refused: {:?}", refused.err()); + }; + let refusal = refusal.downcast_ref::(); + assert_eq!(refusal, Some(&Refusal::Iterations { asked: 20, cap: 8 })); + assert_eq!(subject.processes(), Vec::::new()); + Ok(()) +} + +#[tokio::test] +async fn a_running_seat_is_not_started_twice_and_a_stopped_one_is_already_stopped() -> Result<()> { + let subject = FakeSubject::new()?; + let harness = subject.harness(); + let runner = harness.start(subject.seat(), subject.endpoint()).await?; + let again = harness.start(subject.seat(), subject.endpoint()).await; + assert!(matches!(again, Err(Error::Harness(reason)) if reason.contains("already running"))); + harness.stop("scout").await?; + harness.stop("scout").await?; + assert_eq!(subject.processes(), Vec::::new()); + drop(runner); + Ok(()) +} + +/// A first turn that fails leaves no session behind: the next turn starts +/// the seat's thread afresh instead of failing to resume it forever. +#[tokio::test(flavor = "multi_thread")] +async fn a_failed_first_turn_leaves_the_seat_able_to_start() -> Result<()> { + let subject = FakeSubject::new()?; + let harness = subject.harness(); + let runner = harness.start(subject.seat(), subject.endpoint()).await?; + let steps = subject.control().join("steps"); + std::fs::write(steps.join("a"), r#"{"error": "provider down"}"#)?; + let first = runner.run(seat_support::request("t1", None)).await; + let failed = match &first { + Ok(outcome) => matches!(outcome.disposition, TurnDisposition::Failed(_)), + Err(_) => true, + }; + assert!(failed, "{first:?}"); + std::fs::write(steps.join("b"), r#"{"reply": "works", "tokens": 1}"#)?; + let second = runner.run(seat_support::request("t2", None)).await?; + assert_eq!(second.disposition, TurnDisposition::Completed); + assert_eq!(second.reply.as_deref(), Some("works")); + harness.stop("scout").await?; + Ok(()) +} + +/// Neither the seat's bearer nor the instance's core token is in the +/// harness's `Debug`, running seats included. +#[tokio::test(flavor = "multi_thread")] +async fn debug_of_a_running_harness_shows_no_secret() -> Result<()> { + use std::sync::{Arc, Mutex}; + use tinyhivemind_host::harness::{Event, Harness as _, Observer}; + #[derive(Default)] + struct Pid(Mutex>); + impl Observer for Pid { + fn event(&self, _: &str, event: Event) { + if let Event::Started(started) = event { + *self + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(started.pid); + } + } + } + let subject = FakeSubject::new()?; + let harness = subject.openhuman(); + let pid = Arc::new(Pid::default()); + let mut plan = subject.seat(); + plan.observer = pid.clone(); + let runner = harness.start(plan, subject.endpoint()).await?; + let started = *pid + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let environ = std::fs::read(format!("/proc/{}/environ", started.unwrap_or_default()))?; + let token = String::from_utf8_lossy(&environ) + .split('\0') + .find_map(|entry| { + entry + .strip_prefix("OPENHUMAN_CORE_TOKEN=") + .map(str::to_owned) + }) + .unwrap_or_default(); + assert!(token.len() >= 32, "the child's core token was not found"); + let shown = format!("{harness:?}"); + assert!(!shown.contains(&token), "the core token is in {shown}"); + assert!(!shown.contains("seat-bearer"), "the bearer is in {shown}"); + harness.stop("scout").await?; + drop(runner); + Ok(()) +} + +/// Two starts of one seat at once: one runs, the other is refused. +#[tokio::test(flavor = "multi_thread")] +async fn a_seat_starting_twice_at_once_runs_once() -> Result<()> { + use tinyhivemind_host::harness::Harness as _; + let subject = FakeSubject::new()?; + let harness = subject.openhuman(); + let (one, two) = tokio::join!( + harness.start(subject.seat(), subject.endpoint()), + harness.start(subject.seat(), subject.endpoint()), + ); + let started = [one.is_ok(), two.is_ok()]; + assert_eq!(started.iter().filter(|ok| **ok).count(), 1, "{started:?}"); + let refused = one.err().or(two.err()).map(|error| error.to_string()); + assert!(refused.is_some_and(|reason| reason.contains("already"))); + harness.stop("scout").await?; + assert_eq!(subject.processes(), Vec::::new()); + Ok(()) +} + +/// A stop while the seat starts stops what it starts, and the start fails. +#[tokio::test(flavor = "multi_thread")] +async fn a_stop_during_start_leaves_nothing_running() -> Result<()> { + use tinyhivemind_host::harness::Harness as _; + let subject = FakeSubject::new()?; + let harness = std::sync::Arc::new(subject.openhuman()); + let starting = harness.clone(); + let (seat, endpoint) = (subject.seat(), subject.endpoint()); + let start = tokio::spawn(async move { starting.start(seat, endpoint).await.err() }); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + harness.stop("scout").await?; + let refused = start.await?; + assert!(refused.is_some(), "the start succeeded after its stop"); + assert_eq!(subject.processes(), Vec::::new()); + // The seat may be started again. + harness.start(subject.seat(), subject.endpoint()).await?; + harness.stop("scout").await?; + Ok(()) +} diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/README.md b/crates/tinyhivemind-openhuman-process/tests/fake/README.md new file mode 100644 index 00000000..e5eef41b --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/fake/README.md @@ -0,0 +1,7 @@ +# The fake openhuman-core + +| File | Purpose | +| --- | --- | +| `surface.rs` | The scripted RPC, `/health` and `/events` surface, recorded from 0.64.15; driven by a control directory. Also compiled into the unit tests. | +| `child.rs` | The `tinyhivemind-fake-openhuman` binary: the surface on `--port`, with the runner's environment, and a grandchild that escapes its session on request. | +| `subject.rs` | Both as a conformance `Subject`, launched through a wrapper script that sets `CONTROL`. | diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/child.rs b/crates/tinyhivemind-openhuman-process/tests/fake/child.rs new file mode 100644 index 00000000..dd157eea --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/fake/child.rs @@ -0,0 +1,87 @@ +//! The scripted fake `openhuman-core`: `run --headless-api --host 127.0.0.1 +//! --port ` serves the fake surface from `surface.rs` on that port, with +//! the token and workspace from the environment the runner gives the real +//! one. `CONTROL` names the control directory; a test's wrapper script sets +//! it. Asked through `/escape`, it leaves a grandchild in a session +//! of its own, which reports its pid to `/escapee`. +#[path = "../support/http.rs"] +mod http; +// The in-process unit tests use the parts of the fake this binary does not. +#[allow(dead_code, reason = "shared with the in-process tests")] +#[path = "surface.rs"] +mod surface; + +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::time::Duration; + +fn main() -> ExitCode { + let arguments: Vec = std::env::args().skip(1).collect(); + if let [mode, report] = arguments.as_slice() + && mode == "escapee" + { + return escapee(Path::new(report)); + } + // The real binary is never run with its sandbox off, so neither is this. + if std::env::var_os("OPENHUMAN_SANDBOX").is_some() { + return ExitCode::from(3); + } + let port = arguments + .windows(2) + .find(|pair| pair[0] == "--port") + .and_then(|pair| pair[1].parse::().ok()); + let variable = |name: &str| std::env::var_os(name).map(PathBuf::from); + let (Some(port), Some(workspace), Some(control), Ok(token)) = ( + port, + variable("OPENHUMAN_WORKSPACE"), + variable("CONTROL"), + std::env::var("OPENHUMAN_CORE_TOKEN"), + ) else { + return ExitCode::from(2); + }; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let Ok(runtime) = runtime else { + return ExitCode::FAILURE; + }; + runtime.block_on(async move { + let Ok(listener) = tokio::net::TcpListener::bind(("127.0.0.1", port)).await else { + return ExitCode::FAILURE; + }; + let setup = surface::Setup { + token, + workspace, + control: control.clone(), + pid: std::process::id(), + }; + let _fake = surface::Fake::on(listener, setup, port); + loop { + let request = control.join("escape"); + if std::fs::remove_file(&request).is_ok() + && let Ok(program) = std::env::current_exe() + { + let _ = std::process::Command::new(program) + .arg("escapee") + .arg(control.join("escapee")) + .spawn(); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) +} + +/// Leave the process group, report, and stay two minutes at most. +fn escapee(report: &Path) -> ExitCode { + if rustix::process::setsid().is_err() { + return ExitCode::FAILURE; + } + let partial = report.with_extension("partial"); + let written = std::fs::write(&partial, std::process::id().to_string()) + .and_then(|()| std::fs::rename(&partial, report)); + if written.is_err() { + return ExitCode::FAILURE; + } + std::thread::sleep(Duration::from_secs(120)); + ExitCode::SUCCESS +} diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs b/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs new file mode 100644 index 00000000..e476b985 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/fake/subject.rs @@ -0,0 +1,195 @@ +//! The fake `openhuman-core` as a subject of the host's conformance suite. +//! +//! The runner launches a wrapper script that sets `CONTROL` and execs the +//! fake child, so the runner itself is exactly the one a host uses. +use crate::seat_support::{done, kill_all, processes_in, seat}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; +use std::fs; +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; +use tinyhivemind_host::harness::conformance::{ + CallState, EscapeFuture, ModelCall, ModelStep, Subject, ToolFault, +}; +use tinyhivemind_host::harness::{Harness, SeatPlan, ToolEndpoint}; +use tinyhivemind_host::process::StopPolicy; +use tinyhivemind_openhuman_process::{OpenHumanHarness, Options, Program}; + +/// Fresh durable state and the scripted fake. +pub(crate) struct FakeSubject { + root: tempfile::TempDir, + steps: AtomicUsize, +} + +pub(crate) const TOOLS: [&str; 2] = ["hivemind_post", "hivemind_ask"]; + +impl FakeSubject { + pub(crate) fn new() -> std::io::Result { + let root = tempfile::tempdir()?; + let control = root.path().join("control"); + fs::create_dir_all(control.join("steps"))?; + fs::write(control.join("served"), json!(TOOLS).to_string())?; + let program = env!("CARGO_BIN_EXE_tinyhivemind-fake-openhuman"); + let wrapper = root.path().join("openhuman-core"); + let script = format!( + "#!/bin/sh\nCONTROL='{}' exec '{program}' \"$@\"\n", + control.display() + ); + fs::write(&wrapper, script)?; + fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755))?; + Ok(Self { + root, + steps: AtomicUsize::new(0), + }) + } + + pub(crate) fn control(&self) -> PathBuf { + self.root.path().join("control") + } + + pub(crate) fn root_path(&self) -> &Path { + self.root.path() + } + + fn instance(&self) -> PathBuf { + self.root.path().join("instance") + } + + fn entries(&self) -> Vec { + fs::read_to_string(self.control().join("calls.jsonl")) + .unwrap_or_default() + .lines() + .filter_map(|line| serde_json::from_str(line).ok()) + .collect() + } + + pub(crate) fn options() -> Options { + Options { + ready: Duration::from_secs(20), + warm_up: Duration::from_secs(3), + stop: StopPolicy { + cancel: Duration::from_secs(2), + terminate: Duration::from_secs(2), + kill: Duration::from_secs(10), + }, + approval: Duration::from_secs(5), + } + } +} + +impl FakeSubject { + /// The harness itself, rather than behind the port. + pub(crate) fn openhuman(&self) -> OpenHumanHarness { + let program = Program::new(self.root.path().join("openhuman-core"), "0.64.15"); + OpenHumanHarness::new(program).with_options(Self::options()) + } +} + +impl Subject for FakeSubject { + fn harness(&self) -> Arc { + Arc::new(self.openhuman()) + } + + fn seat(&self) -> SeatPlan { + SeatPlan::new(seat("http://127.0.0.1:9/v1"), self.instance()) + } + + fn endpoint(&self) -> ToolEndpoint { + let tools = TOOLS.map(String::from); + ToolEndpoint::new("hivemind", "http://127.0.0.1:1/mcp", "seat-bearer", tools) + } + + fn script(&self, steps: &[ModelStep]) { + let directory = self.control().join("steps"); + for old in fs::read_dir(&directory).into_iter().flatten().flatten() { + let _ = fs::remove_file(old.path()); + } + for step in steps { + let number = self.steps.fetch_add(1, Ordering::Relaxed); + let step = match step { + ModelStep::Reply { text, usage } => { + json!({"reply": text, "tokens": usage.input_tokens}) + } + ModelStep::Hang => Value::Null, + }; + let path = directory.join(format!("{number:06}")); + done(&fs::write(path, step.to_string())); + } + } + + fn model_calls(&self) -> Vec { + let mut calls = BTreeMap::new(); + for entry in self.entries() { + let state = match entry["state"].as_str() { + Some("answered") => CallState::Answered, + Some("aborted") => CallState::Aborted, + // A model call ends with the process that makes it. + _ if !Path::new(&format!("/proc/{}/cwd", entry["pid"])).exists() => { + CallState::Aborted + } + _ => CallState::Open, + }; + let seen = entry["seen"].as_u64().unwrap_or_default(); + let call = calls.entry(entry["call"].as_u64()).or_insert(ModelCall { + seen: usize::try_from(seen).unwrap_or(usize::MAX), + state, + }); + call.state = state; + } + calls.into_values().collect() + } + + fn lose_sessions(&self) { + let transcripts = self.instance().join("state/ws/workspace/session_raw"); + done(&fs::remove_dir_all(transcripts)); + } + + fn offer(&self, fault: ToolFault) { + let text = match fault { + ToolFault::None => "", + ToolFault::Extra => "extra", + ToolFault::Missing => "missing", + }; + done(&fs::write(self.control().join("tools"), text)); + } + + fn misconfigure(&self) { + done(&fs::write(self.control().join("misconfigured"), "")); + } + + fn escapee(&self) -> EscapeFuture { + let control = self.control(); + Box::pin(async move { + let report = control.join("escapee"); + let _ = fs::remove_file(&report); + done(&fs::write(control.join("escape"), "")); + loop { + if let Ok(pid) = fs::read_to_string(&report) { + return pid.parse().ok(); + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + } + + fn processes(&self) -> Vec { + processes_in(&self.instance()) + } + + fn turn_limit(&self) -> Duration { + Duration::from_secs(5) + } + + fn patience(&self) -> Duration { + Duration::from_secs(60) + } +} + +impl Drop for FakeSubject { + fn drop(&mut self) { + kill_all(self.processes()); + } +} diff --git a/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs new file mode 100644 index 00000000..5856342d --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/fake/surface.rs @@ -0,0 +1,537 @@ +//! A scripted fake of `openhuman-core run --headless-api`: the JSON-RPC, +//! `/health` and `/events` surface the runner uses, with the field names and +//! behaviour recorded from 0.64.15 in the harness spike. +//! +//! What it copies, because the runner must cope with it: +//! +//! - bad or unreadable TOML is not an error: the instance runs on defaults; +//! - MCP tools are listed only after a warm-up, by hashed names +//! `mcp___`; +//! - `channel_web_chat` rejects unknown params, answers with a `request_id`, +//! and may publish events before that answer arrives; +//! - events go to `/events` subscribers of the turn's `client_id`, and an +//! `approval_request` carries the approval's id as its `request_id`; +//! - a new message on a busy thread interrupts the turn on it; +//! - the custom agent ends after eight iterations as if it had finished; +//! - compaction is on unless the config turns it off. +//! +//! It is driven through files in a control directory shared with the test: +//! `steps/` (the scripted model, in name order), `calls.jsonl` (each model +//! call and its end), `served` (the tools the host's server serves), +//! `tools` (`extra` or `missing`), `misconfigured`, `version`, `warm` +//! (available-tools calls before MCP tools appear), and `methods.jsonl` and +//! `decisions.jsonl`, which it writes. +use super::http::{Reply, Request, event, serve}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; +use std::fs; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use tokio::net::TcpListener; +use tokio::sync::{Notify, mpsc, oneshot}; + +/// The version the fake reports unless told otherwise. +pub(crate) const VERSION: &str = "0.64.15"; +/// The released binary's custom-agent iteration cap. +const CAP: u64 = 8; + +/// What the fake is started with. +#[derive(Clone, Debug)] +pub(crate) struct Setup { + /// The bearer every `/rpc` and `/events` request must carry. + pub(crate) token: String, + /// `OPENHUMAN_WORKSPACE`: holds `config.toml` and the transcripts. + pub(crate) workspace: PathBuf, + /// The control directory. + pub(crate) control: PathBuf, + /// The pid `/health` reports. + pub(crate) pid: u32, +} + +/// A running fake. +pub(crate) struct Fake { + /// Where it listens, on 127.0.0.1. + pub(crate) port: u16, + task: tokio::task::JoinHandle<()>, + state: Arc, +} + +impl Fake { + /// Serve `setup` on a free port. + pub(crate) async fn start(setup: Setup) -> std::io::Result { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let port = listener.local_addr()?.port(); + Ok(Self::on(listener, setup, port)) + } + + /// Serve `setup` on `listener`. + pub(crate) fn on(listener: TcpListener, setup: Setup, port: u16) -> Self { + let state = Arc::new(State::new(setup)); + let serving = state.clone(); + let task = tokio::spawn(serve(listener, move |request| { + let state = serving.clone(); + async move { state.handle(&request) } + })); + Self { port, task, state } + } +} + +impl Drop for Fake { + /// Like a process that is gone: nothing answers and every stream ends. + fn drop(&mut self) { + self.task.abort(); + lock(&self.state.subscribers).clear(); + } +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// A turn running on a thread. +struct InFlight { + request_id: String, + cancel: Arc, +} + +struct State { + setup: Setup, + config: Value, + subscribers: Mutex)>>, + in_flight: Mutex>, + approvals: Mutex>>, + listed: AtomicUsize, + next: AtomicU64, +} + +impl State { + fn new(setup: Setup) -> Self { + let config = effective(&setup); + Self { + setup, + config, + subscribers: Mutex::default(), + in_flight: Mutex::default(), + approvals: Mutex::default(), + listed: AtomicUsize::new(0), + next: AtomicU64::new(0), + } + } + + fn control(&self, name: &str) -> PathBuf { + self.setup.control.join(name) + } + + fn read(&self, name: &str) -> Option { + fs::read_to_string(self.control(name)).ok() + } + + fn append(&self, name: &str, entry: &Value) { + let file = fs::File::options() + .create(true) + .append(true) + .open(self.control(name)); + if let Ok(mut file) = file { + let _ = writeln!(file, "{entry}"); + } + } + + fn handle(self: Arc, request: &Request) -> Reply { + if request.method == "GET" && request.path == "/health" { + let health = json!({"pid": self.setup.pid, "healthy": true, "components": {}}); + return Reply::Json(200, health); + } + let bearer = format!("Bearer {}", self.setup.token); + if request.header("authorization") != Some(bearer.as_str()) { + return Reply::Json(401, json!({"ok": false, "error": "unauthorized"})); + } + match (request.method.as_str(), request.path.as_str()) { + ("GET", "/events") => self.subscribe(request), + ("POST", "/rpc") => { + let body = request.json(); + let id = body["id"].clone(); + let method = body["method"].as_str().unwrap_or_default().to_owned(); + self.append("methods.jsonl", &json!(method)); + let params = body["params"].clone(); + let answer = match self.clone().call(&method, ¶ms) { + Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}), + Err(message) => json!({"jsonrpc": "2.0", "id": id, + "error": {"code": -32000, "message": message, "data": null}}), + }; + Reply::Json(200, answer) + } + _ => Reply::Json(404, json!({"ok": false, "error": "not_found"})), + } + } + + fn subscribe(&self, request: &Request) -> Reply { + let (sender, receiver) = mpsc::channel(1024); + let client = request.param("client_id").unwrap_or_default(); + lock(&self.subscribers).push((client, sender)); + Reply::Stream(receiver) + } + + /// Publish `name` to the subscribers of `client`. + fn publish(&self, client: &str, thread: &str, request_id: &str, name: &str, fields: Value) { + let mut data = json!({ + "event": name, "client_id": client, "thread_id": thread, "request_id": request_id, + }); + if let (Some(data), Value::Object(fields)) = (data.as_object_mut(), fields) { + data.extend(fields); + } + let frame = event(name, &data); + let mut subscribers = lock(&self.subscribers); + subscribers.retain(|(_, sender)| !sender.is_closed()); + for (_, sender) in subscribers.iter().filter(|(id, _)| id == client) { + let _ = sender.try_send(frame.clone()); + } + } + + fn call(self: Arc, method: &str, params: &Value) -> Result { + let envelope = |result: Value| json!({"logs": ["fake"], "result": result}); + match method { + "core.version" => { + let version = self.read("version").unwrap_or_else(|| VERSION.into()); + Ok(json!({"version": version.trim()})) + } + "openhuman.config_get" => Ok(envelope(json!({ + "config": self.config, + "workspace_dir": self.setup.workspace.join("workspace"), + }))), + "openhuman.agent_registry_available_tools" => Ok(json!({"tools": self.tools()})), + "openhuman.threads_transcript_get" => { + let thread = params["thread_id"].as_str().unwrap_or_default(); + let exists = self.transcript(thread).exists(); + Ok(json!({"data": {"threadId": thread, "hasTranscript": exists}})) + } + "openhuman.channel_web_chat" => self.chat(params).map(envelope), + "openhuman.channel_web_cancel" => Ok(envelope(self.cancel(params))), + "openhuman.approval_list_pending" => { + let pending = lock(&self.approvals) + .keys() + .map(|id| json!({"request_id": id})) + .collect::>(); + Ok(envelope(json!(pending))) + } + "openhuman.approval_decide" => { + let id = params["request_id"].as_str().unwrap_or_default(); + let decision = params["decision"].as_str().unwrap_or_default().to_owned(); + self.append("decisions.jsonl", &json!({"id": id, "decision": decision})); + let pending = lock(&self.approvals).remove(id); + let sender = pending.ok_or_else(|| format!("no pending approval {id}"))?; + let _ = sender.send(decision); + Ok(envelope(json!({"request_id": id}))) + } + other => Err(format!("unknown method: {other}")), + } + } + + fn tools(&self) -> Vec { + let builtin = ["shell", "mcp_call_tool", "juice_retrieve"]; + let mut tools: Vec = builtin.map(String::from).to_vec(); + let warm: usize = self + .read("warm") + .and_then(|n| n.trim().parse().ok()) + .unwrap_or(2); + if self.listed.fetch_add(1, Ordering::Relaxed) >= warm { + let mut served: Vec = self + .read("served") + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default(); + if self.read("tools").as_deref() == Some("missing") { + served.pop(); + } + let servers = self.config["mcp_client"]["servers"].as_array().cloned(); + for server in servers.unwrap_or_default() { + let name = server["name"].as_str().unwrap_or_default(); + for tool in &served { + tools.push(hashed(name, tool)); + } + } + } + let tools = tools + .into_iter() + .map(|name| json!({"name": name, "description": ""})); + tools.collect() + } + + fn transcript(&self, thread: &str) -> PathBuf { + let safe: String = thread + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' { + c + } else { + '_' + } + }) + .collect(); + self.setup + .workspace + .join("workspace/session_raw") + .join(format!("{safe}.jsonl")) + } + + fn chat(self: Arc, params: &Value) -> Result { + let known = [ + "client_id", + "thread_id", + "message", + "model_override", + "queue_mode", + ]; + for key in params.as_object().into_iter().flatten().map(|(key, _)| key) { + if !known.contains(&key.as_str()) { + return Err(format!("unknown param '{key}' for channel.web_chat")); + } + } + let agent = self.config["agent"]["chat_agent_id"] + .as_str() + .unwrap_or("orchestrator"); + let entries = self.config["agent_registry"]["entries"].as_array().cloned(); + if !entries + .unwrap_or_default() + .iter() + .any(|entry| entry["id"] == agent) + { + return Err(format!( + "chat_agent_id '{agent}' is not a runnable agent definition" + )); + } + let text = |key: &str| { + params[key] + .as_str() + .filter(|text| !text.is_empty()) + .map(str::to_owned) + }; + let (Some(client), Some(thread), Some(message)) = + (text("client_id"), text("thread_id"), text("message")) + else { + return Err("client_id, thread_id and message are required".into()); + }; + let number = self.next.fetch_add(1, Ordering::Relaxed); + let request_id = format!("req-{number}"); + let cancel = Arc::new(Notify::new()); + let flight = InFlight { + request_id: request_id.clone(), + cancel: cancel.clone(), + }; + if let Some(earlier) = lock(&self.in_flight).insert(thread.clone(), flight) { + // A second message interrupts the first, as `queue_mode` does by default. + earlier.cancel.notify_one(); + } + // The first event is out before the answer is. + let first = json!({"message": format!("Iteration 1/{CAP}"), "round": 1}); + self.publish(&client, &thread, &request_id, "iteration_start", first); + let ack = json!({"accepted": true, "client_id": client, "thread_id": thread, + "request_id": request_id}); + let ids = Ids { + client, + thread, + request_id, + }; + tokio::spawn(async move { self.run(ids, message, cancel).await }); + Ok(ack) + } + + fn cancel(&self, params: &Value) -> Value { + let thread = params["thread_id"].as_str().unwrap_or_default(); + let scoped = params["request_id"].as_str(); + let mut in_flight = lock(&self.in_flight); + let target = in_flight + .get(thread) + .is_some_and(|flight| scoped.is_none_or(|id| id == flight.request_id)); + let cancelled = if target { + in_flight.remove(thread) + } else { + None + }; + let request_id = cancelled.as_ref().map(|flight| flight.request_id.clone()); + if let Some(flight) = cancelled { + flight.cancel.notify_one(); + } + json!({"cancelled": request_id.is_some(), "client_id": params["client_id"], + "thread_id": thread, "request_id": request_id, "subagents_cancelled": 0}) + } + + /// The next scripted step; null hangs. + fn step(&self) -> Value { + let mut steps: Vec = fs::read_dir(self.control("steps")) + .into_iter() + .flatten() + .flatten() + .map(|entry| entry.path()) + .collect(); + steps.sort(); + for next in steps { + if let Ok(text) = fs::read_to_string(&next) + && fs::remove_file(&next).is_ok() + { + return serde_json::from_str(&text).unwrap_or(Value::Null); + } + } + Value::Null + } + + async fn run(self: Arc, ids: Ids, message: String, cancel: Arc) { + let step = self.step(); + let say = |name: &str, fields: Value| { + self.publish(&ids.client, &ids.thread, &ids.request_id, name, fields); + }; + if step["stray"].as_bool() == Some(true) { + let stray = json!({"full_response": "not yours", "request_id": "req-stray"}); + self.publish(&ids.client, &ids.thread, "req-stray", "chat_done", stray); + } + if let Some(tool) = step["approval"].as_str() { + let id = match step["approval_id"].as_str() { + Some(id) => id.to_owned(), + None => format!("approval-{}", self.next.fetch_add(1, Ordering::Relaxed)), + }; + let (sender, decided) = oneshot::channel(); + lock(&self.approvals).insert(id.clone(), sender); + // Its `request_id` is the approval's, not the turn's. + let request = json!({"tool_name": tool, "args": {"command": ""}}); + self.publish(&ids.client, &ids.thread, &id, "approval_request", request); + let _ = decided.await; + } + let iterations = step["iterations"].as_u64().unwrap_or(1).min(CAP); + for round in 2..=iterations { + let text = format!("Iteration {round}/{CAP}"); + say("iteration_start", json!({"message": text, "round": round})); + } + if let Some(tool) = step["tool"].as_str() { + let call = json!({"tool_name": tool, "tool_call_id": "call_1", "args": {}}); + say("tool_call", call); + let result = json!({"tool_name": tool, "tool_call_id": "call_1", "success": false}); + say("tool_result", result); + } + // Only a turn that ends is kept in the thread, as 0.64.15 does. + let seen = self.users(&ids.thread) + 1; + let call = self.open(seen); + if step.is_null() { + cancel.notified().await; + self.append("calls.jsonl", &json!({"call": call, "state": "aborted"})); + say( + "chat_error", + json!({"message": "Cancelled", "error_type": "cancelled"}), + ); + return; + } + self.append("calls.jsonl", &json!({"call": call, "state": "answered"})); + self.finish(&ids.thread, &ids.request_id); + if let Some(error) = step["error"].as_str() { + say( + "chat_error", + json!({"message": error, "error_type": "inference"}), + ); + return; + } + let reply = step["reply"].as_str().unwrap_or_default(); + self.remember(&ids.thread, "user", &message); + self.remember(&ids.thread, "assistant", reply); + let tokens = step["tokens"].as_u64().unwrap_or(0); + let usage = json!({"input_tokens": tokens, "output_tokens": 2, + "cached_input_tokens": tokens / 10, "cost_usd": 0.0, "context_window": 0}); + say( + "text_delta", + json!({"delta": reply, "delta_kind": "text", "round": 1}), + ); + say("turn_cost", json!({"usage": usage, "round": 1})); + say("chat_done", json!({"full_response": reply, "usage": usage})); + } + + /// The turn on `thread` ended, unless a newer one replaced it. + fn finish(&self, thread: &str, request_id: &str) { + let mut in_flight = lock(&self.in_flight); + if in_flight + .get(thread) + .is_some_and(|flight| flight.request_id == request_id) + { + in_flight.remove(thread); + } + } + + /// The user messages in the thread's transcript. + fn users(&self, thread: &str) -> usize { + let text = fs::read_to_string(self.transcript(thread)).unwrap_or_default(); + text.lines() + .filter(|line| line.contains("\"user\"")) + .count() + } + + /// Append to the thread's transcript. + fn remember(&self, thread: &str, role: &str, text: &str) { + let path = self.transcript(thread); + if let Some(parent) = path.parent() { + let _ = fs::create_dir_all(parent); + } + let file = fs::File::options().create(true).append(true).open(&path); + if let Ok(mut file) = file { + let _ = writeln!(file, "{}", json!({"role": role, "text": text})); + } + } + + fn open(&self, seen: usize) -> u64 { + let log = self.read("calls.jsonl").unwrap_or_default(); + let count = log.lines().filter(|line| line.contains("\"open\"")).count(); + let call = u64::try_from(count).unwrap_or(u64::MAX); + let entry = json!({"call": call, "state": "open", "seen": seen, + "pid": std::process::id()}); + self.append("calls.jsonl", &entry); + call + } +} + +struct Ids { + client: String, + thread: String, + request_id: String, +} + +/// The model-visible name 0.64.15 gives a direct MCP tool. +pub(crate) fn hashed(server: &str, tool: &str) -> String { + let mut hash: u32 = 0x811c_9dc5; + for byte in format!("{server}/{tool}").bytes() { + hash = (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193); + } + format!("mcp_{server}_{tool}_{:06x}", hash & 0x00ff_ffff) +} + +/// The config the instance runs with: the file, unless it cannot be read, +/// with some of the defaults 0.64.15 adds. +fn effective(setup: &Setup) -> Value { + let control = &setup.control; + let written = fs::read_to_string(setup.workspace.join("config.toml")).ok(); + let parsed = written + .filter(|_| !control.join("misconfigured").exists()) + .and_then(|text| text.parse::().ok()) + .and_then(|table| serde_json::to_value(table).ok()); + let mut config = parsed.unwrap_or_else(|| json!({"schema_version": 13})); + config["embeddings_provider"] = json!("openhuman"); + if config["context"]["compaction_enabled"].is_null() { + config["context"]["compaction_enabled"] = json!(true); + } + if let Some(servers) = config["mcp_client"]["servers"].as_array_mut() { + for server in servers { + server["timeout_secs"] = json!(30); + } + } + if fs::read_to_string(control.join("tools")).is_ok_and(|text| text == "extra") { + let entries = config["agent_registry"]["entries"].as_array_mut(); + for entry in entries.into_iter().flatten() { + if let Some(tools) = entry["tool_allowlist"].as_array_mut() { + tools.push(json!("shell")); + } + } + } + config +} + +/// A control directory for one fake, with its `steps/`. +pub(crate) fn control(root: &Path) -> std::io::Result { + let control = root.join("control"); + fs::create_dir_all(control.join("steps"))?; + Ok(control) +} diff --git a/crates/tinyhivemind-openhuman-process/tests/live.rs b/crates/tinyhivemind-openhuman-process/tests/live.rs new file mode 100644 index 00000000..fa0f7088 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/live.rs @@ -0,0 +1,225 @@ +//! `live_*`: this runner on the pinned `openhuman-core`. +//! +//! Opt in with `THM_OPENHUMAN_CORE=`, fetched and +//! checked by `.github/scripts/fetch-harness.sh`; Node runs the spike +//! fixture, from `THM_NODE` or `PATH`. Without either, each test says why on +//! stderr and passes. The conformance cases run with the scripted model in +//! `live/model.rs` and the fixture's MCP stub; the gate repeats the spike's +//! checks with the fixture as model too. +#![cfg(target_os = "linux")] + +#[path = "live/model.rs"] +mod model; +#[path = "support/seat.rs"] +mod seat_support; +#[path = "live/subject.rs"] +mod subject; + +use anyhow::{Context as _, Result}; +use serde_json::{Value, json}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; +use subject::{Fixture, LiveSubject, PINNED, options, requirements}; +use tinyhivemind_hives::{Destination, Message, TurnDisposition, TurnRequest}; +use tinyhivemind_host::harness::conformance::Case; +use tinyhivemind_host::harness::{Event, Harness as _, Observer, SeatPlan, ToolEndpoint}; +use tinyhivemind_openhuman_process::{OpenHumanHarness, Program}; + +macro_rules! live { + ($($name:ident => $case:ident),* $(,)?) => { + $( + #[tokio::test(flavor = "multi_thread")] + async fn $name() -> Result<()> { + if let Some(subject) = LiveSubject::new().await? { + Case::$case.run(&subject).await?; + } + Ok(()) + } + )* + #[test] + fn every_case_is_run_live() { + assert_eq!(Case::ALL, [$(Case::$case),*]); + } + }; +} + +live! { + live_a_second_turn_continues_the_session => SecondTurnContinues, + live_a_session_is_resumed_after_a_restart => ResumesAfterRestart, + live_a_resume_failure_is_an_error => ResumeFailureIsAnError, + live_a_timeout_stops_the_turn => TimeoutStopsTheTurn, + live_a_dropped_run_stops_the_turn => DropStopsTheTurn, + live_a_kill_neither_replays_nor_loses_the_seat => KillNeitherReplaysNorLosesTheSeat, + live_one_turn_runs_at_a_time => OneTurnAtATime, + live_no_turn_runs_twice => NoTurnTwice, + live_usage_is_per_turn => UsageIsPerTurn, + live_the_tool_list_is_exact => ToolListIsExact, + live_the_config_is_the_one_written => ConfigIsTheOneWritten, + live_nothing_is_left_after_stop => NothingLeftAfterStop, +} + +#[derive(Default)] +struct Recorder(Mutex>); + +impl Observer for Recorder { + fn event(&self, _: &str, event: Event) { + self.0 + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(event); + } +} + +fn request(turn: &str, body: &str, session: Option<&str>) -> TurnRequest { + TurnRequest { + turn_id: turn.into(), + scheduled_job_id: None, + teammates: Vec::new(), + agent_id: "scout".into(), + session_id: session.map(Into::into), + messages: vec![Message { + scheduled_job_id: None, + message_id: format!("message-{turn}"), + sequence: 1, + sender: tinyhivemind_hives::HOST_ID.into(), + destination: Destination::Agent("scout".into()), + body: body.into(), + thread: None, + episode_id: None, + only_for: Vec::new(), + }], + memberships: Vec::new(), + episode: None, + resumption: None, + } +} + +/// The spike's gate through this runner: the hive tool is called as the +/// right seat, the model is offered that tool alone, usage is the turn's, +/// a dropped turn closes its model call, and nothing is left after stop. +#[tokio::test(flavor = "multi_thread")] +async fn live_the_spike_gate_holds_through_the_runner() -> Result<()> { + let (binary, node) = match requirements() { + Ok(found) => found, + Err(reason) => { + eprintln!("skipped: {reason}"); + return Ok(()); + } + }; + let root = tempfile::tempdir()?; + let fixture = Fixture::start(&node, root.path()).await?; + let harness = OpenHumanHarness::new(Program::new(binary, PINNED)).with_options(options()); + let endpoint = format!("http://127.0.0.1:{}/v1", fixture.port); + let events = Arc::new(Recorder::default()); + let mut plan = SeatPlan::new(seat_support::seat(&endpoint), root.path().join("instance")); + plan.observer = events.clone(); + let url = format!("http://127.0.0.1:{}/mcp", fixture.port); + let tools = ToolEndpoint::new("hivea", url, "seat-a-token", ["hivemind_post".to_owned()]); + let runner = harness.start(plan, tools).await?; + + let since = fixture.entries().len(); + let outcome = runner.run(request("t1", "CALLTOOL please", None)).await?; + assert_eq!(outcome.disposition, TurnDisposition::Completed); + assert_eq!(outcome.reply.as_deref(), Some("MOCK_REPLY turns=1")); + let entries: Vec = fixture.entries().split_off(since); + let calls: Vec<&Value> = entries + .iter() + .filter(|entry| entry["rpc"] == "tools/call") + .collect(); + assert_eq!(calls.len(), 1, "{entries:?}"); + assert_eq!(calls[0]["seat"], "a"); + let models: Vec<&Value> = entries + .iter() + .filter(|entry| entry["kind"] == "model") + .collect(); + let started = events + .0 + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .find_map(|event| match event { + Event::Started(started) => Some(started.clone()), + _ => None, + }); + let started = started.context("no started event")?; + assert_eq!(started.version, PINNED); + let offered: Vec = started.tools.iter().map(|tool| json!(tool)).collect(); + assert_eq!(offered.len(), 1); + for model in &models { + assert_eq!(model["tools"], json!(offered), "the model saw other tools"); + } + let usage = events + .0 + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .find_map(|event| match event { + Event::Usage { turn_id, usage } if turn_id == "t1" => Some(*usage), + _ => None, + }); + assert_eq!(usage.map(|usage| usage.input_tokens), Some(200)); + + let session = outcome.session_id; + let slow = tokio::spawn(runner.run(request("t2", "SLOW please", Some(&session)))); + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + while !fixture.entries().iter().any(|entry| entry["key"] == "SLOW") { + anyhow::ensure!( + tokio::time::Instant::now() < deadline, + "the slow turn never reached the model" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + slow.abort(); + while !fixture + .entries() + .iter() + .any(|entry| entry["kind"] == "model-disconnect") + { + anyhow::ensure!( + tokio::time::Instant::now() < deadline, + "the dropped turn kept its model call open" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + let again = runner + .run(request("t3", "PLAIN again", Some(&session))) + .await?; + // The same thread, without the cancelled turn's message: the binary keeps + // only turns that ended, as the spike saw too. + assert_eq!(again.reply.as_deref(), Some("MOCK_REPLY turns=2")); + assert_eq!(again.session_id, session); + + harness.stop("scout").await?; + let left = seat_support::processes_in(&root.path().join("instance")); + assert_eq!(left, Vec::::new()); + Ok(()) +} + +/// A first turn the provider refuses leaves the seat able to start its +/// thread on the next turn. +#[tokio::test(flavor = "multi_thread")] +async fn live_a_failed_first_turn_leaves_the_seat_able_to_start() -> Result<()> { + use tinyhivemind_host::harness::conformance::{ModelStep, Subject as _}; + let Some(subject) = LiveSubject::new().await? else { + return Ok(()); + }; + let harness = subject.harness(); + let runner = harness.start(subject.seat(), subject.endpoint()).await?; + subject.model().fail_next(); + let first = runner.run(seat_support::request("t1", None)).await; + let failed = match &first { + Ok(outcome) => matches!(outcome.disposition, TurnDisposition::Failed(_)), + Err(_) => true, + }; + anyhow::ensure!(failed, "the refused turn did not fail: {first:?}"); + let reply = ModelStep::Reply { + text: "works".into(), + usage: tinyhivemind_host::harness::TurnUsage::default(), + }; + subject.model().script(&[reply]); + let second = runner.run(seat_support::request("t2", None)).await?; + assert_eq!(second.disposition, TurnDisposition::Completed); + assert_eq!(second.reply.as_deref(), Some("works")); + harness.stop("scout").await?; + Ok(()) +} diff --git a/crates/tinyhivemind-openhuman-process/tests/live/README.md b/crates/tinyhivemind-openhuman-process/tests/live/README.md new file mode 100644 index 00000000..c4f2744e --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/live/README.md @@ -0,0 +1,6 @@ +# Live + +| File | Purpose | +| --- | --- | +| `subject.rs` | The pinned binary as a conformance `Subject`, with the spike fixture's MCP stub run by Node, and a wrapper that can corrupt the written config. | +| `model.rs` | A scripted Chat Completions model that plays the suite's steps and sees a hang-up. | diff --git a/crates/tinyhivemind-openhuman-process/tests/live/model.rs b/crates/tinyhivemind-openhuman-process/tests/live/model.rs new file mode 100644 index 00000000..9d7f9b6a --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/live/model.rs @@ -0,0 +1,155 @@ +//! A scripted Chat Completions model on loopback, played by the host's +//! conformance steps: each request takes the next step, and a hanging one +//! notices when the caller hangs up. +#[allow(dead_code, reason = "shared with the fake surface")] +#[path = "../support/http.rs"] +mod http; + +use http::{Reply, Request, serve}; +use serde_json::{Value, json}; +use std::collections::VecDeque; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use tinyhivemind_host::harness::conformance::{CallState, ModelCall, ModelStep}; +use tokio::net::TcpListener; +use tokio::sync::mpsc; + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +#[derive(Default)] +struct State { + /// Requests to refuse with a 400 before the script plays on. + failures: Mutex, + steps: Mutex>, + calls: Mutex>, +} + +/// The model, serving until dropped. +pub(crate) struct ScriptedModel { + pub(crate) port: u16, + state: Arc, + task: tokio::task::JoinHandle<()>, +} + +impl ScriptedModel { + 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 state = Arc::new(State::default()); + let serving = state.clone(); + let task = tokio::spawn(serve(listener, move |request| { + let state = serving.clone(); + async move { answer(&state, &request) } + })); + Ok(Self { port, state, task }) + } + + pub(crate) fn script(&self, steps: &[ModelStep]) { + *lock(&self.state.steps) = steps.iter().cloned().collect(); + } + + /// Refuse the next request, as a provider refuses a bad one. + pub(crate) fn fail_next(&self) { + *lock(&self.state.failures) += 1; + } + + pub(crate) fn calls(&self) -> Vec { + lock(&self.state.calls).clone() + } +} + +impl Drop for ScriptedModel { + fn drop(&mut self) { + self.task.abort(); + } +} + +fn answer(state: &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 mut failures = lock(&state.failures); + if *failures > 0 { + *failures -= 1; + let error = + json!({"error": {"message": "scripted refusal", "type": "invalid_request_error"}}); + return Reply::Json(400, error); + } + } + let body = request.json(); + let messages = body["messages"].as_array().cloned().unwrap_or_default(); + let seen = messages + .iter() + .filter(|message| message["role"] == "user") + .count(); + let index = { + let mut calls = lock(&state.calls); + calls.push(ModelCall { + seen, + state: CallState::Open, + }); + calls.len() - 1 + }; + let step = lock(&state.steps).pop_front().unwrap_or(ModelStep::Hang); + let (sender, receiver) = mpsc::channel(16); + let state = state.clone(); + let stream = body["stream"] == true; + match step { + ModelStep::Hang => { + tokio::spawn(async move { + sender.closed().await; + lock(&state.calls)[index].state = CallState::Aborted; + }); + Reply::Stream(receiver) + } + ModelStep::Reply { text, usage } => { + lock(&state.calls)[index].state = CallState::Answered; + let usage = json!({"prompt_tokens": usage.input_tokens, "completion_tokens": 1, + "total_tokens": usage.input_tokens + 1}); + let base = json!({"id": "c", "created": 1, "model": "mock"}); + if !stream { + let mut reply = base; + 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); + } + let chunk = |choices: Value, usage: Option| { + let mut chunk = base.clone(); + chunk["object"] = json!("chat.completion.chunk"); + chunk["choices"] = choices; + if let Some(usage) = usage { + chunk["usage"] = usage; + } + format!("data: {chunk}\n\n") + }; + let frames = [ + chunk( + json!([{"index": 0, "delta": {"role": "assistant", "content": text}, "finish_reason": null}]), + None, + ), + chunk( + json!([{"index": 0, "delta": {}, "finish_reason": "stop"}]), + None, + ), + chunk(json!([]), Some(usage)), + "data: [DONE]\n\n".to_owned(), + ]; + tokio::spawn(async move { + for frame in frames { + let _ = sender.send(frame).await; + } + }); + Reply::Stream(receiver) + } + } +} diff --git a/crates/tinyhivemind-openhuman-process/tests/live/subject.rs b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs new file mode 100644 index 00000000..74c4fbde --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/live/subject.rs @@ -0,0 +1,225 @@ +//! The pinned `openhuman-core` as a subject of the conformance suite: the +//! scripted model in `model.rs`, and the spike fixture's MCP stub, run by +//! Node, for the host's tools. +use crate::model::ScriptedModel; +use crate::seat_support::{done, kill_all, processes_in, seat}; +use std::fs; +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::time::Duration; +use tinyhivemind_host::harness::conformance::{ + EscapeFuture, ModelCall, ModelStep, Subject, ToolFault, +}; +use tinyhivemind_host::harness::{Harness, SeatPlan, ToolEndpoint}; +use tinyhivemind_host::process::StopPolicy; +use tinyhivemind_openhuman_process::{OpenHumanHarness, Options, Program}; +use tokio::io::{AsyncBufReadExt as _, BufReader}; +use tokio::process::{Child, Command}; + +/// The pinned version, as `harnesses.lock` records it. +pub(crate) const PINNED: &str = "0.64.15"; + +/// What a live test needs, or why it cannot run here. +pub(crate) fn requirements() -> Result<(PathBuf, PathBuf), String> { + let binary = std::env::var_os("THM_OPENHUMAN_CORE") + .map(PathBuf::from) + .ok_or("THM_OPENHUMAN_CORE is not set to the pinned openhuman-core")?; + let node = std::env::var_os("THM_NODE").map(PathBuf::from).or_else(|| { + let path = std::env::var_os("PATH")?; + std::env::split_paths(&path) + .map(|dir| dir.join("node")) + .find(|node| node.is_file()) + }); + let node = node.ok_or("node is neither THM_NODE nor on PATH, and the fixture needs it")?; + Ok((binary, node)) +} + +/// The spike's fixture: a model that ignores its key and an MCP stub that +/// maps `seat-a-token` to seat `a`. +pub(crate) struct Fixture { + pub(crate) port: u16, + pub(crate) log: PathBuf, + _child: Child, +} + +impl Fixture { + pub(crate) async fn start(node: &Path, dir: &Path) -> std::io::Result { + let port = std::net::TcpListener::bind("127.0.0.1:0")? + .local_addr()? + .port(); + let script = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../docs/experiments/2026-11-25-process-harnesses/fixture/server.mjs"); + let log = dir.join("fixture.jsonl"); + let mut child = Command::new(node) + .arg(script) + .arg(port.to_string()) + .arg(&log) + .stdout(std::process::Stdio::piped()) + .kill_on_drop(true) + .spawn()?; + let stdout = child.stdout.take().ok_or(std::io::ErrorKind::BrokenPipe)?; + let mut lines = BufReader::new(stdout).lines(); + while let Some(line) = lines.next_line().await? { + if line.trim() == "ready" { + return Ok(Self { + port, + log, + _child: child, + }); + } + } + Err(std::io::ErrorKind::UnexpectedEof.into()) + } + + pub(crate) fn entries(&self) -> Vec { + fs::read_to_string(&self.log) + .unwrap_or_default() + .lines() + .filter_map(|line| serde_json::from_str(line).ok()) + .collect() + } +} + +/// Generous: the real binary takes up to a second to start. +pub(crate) fn options() -> Options { + Options { + ready: Duration::from_secs(30), + warm_up: Duration::from_secs(20), + stop: StopPolicy::default(), + approval: Duration::from_secs(5), + } +} + +pub(crate) struct LiveSubject { + root: tempfile::TempDir, + model: ScriptedModel, + fixture: Fixture, + fault: AtomicU8, +} + +impl LiveSubject { + pub(crate) async fn new() -> anyhow::Result> { + let (binary, node) = match requirements() { + Ok(found) => found, + Err(reason) => { + eprintln!("skipped: {reason}"); + return Ok(None); + } + }; + let root = tempfile::tempdir()?; + let fixture = Fixture::start(&node, root.path()).await?; + // Corrupts the written config on request, so that the binary falls + // back to its defaults as it does on bad TOML. + let script = format!( + "#!/bin/sh\n[ -e '{}/misconfigured' ] && printf '\\n[[[\\n' >> \"$OPENHUMAN_WORKSPACE/config.toml\"\nexec '{}' \"$@\"\n", + root.path().display(), + binary.display() + ); + let wrapper = root.path().join("openhuman-core"); + fs::write(&wrapper, script)?; + fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755))?; + Ok(Some(Self { + model: ScriptedModel::start().await?, + root, + fixture, + fault: AtomicU8::new(0), + })) + } + + pub(crate) fn model(&self) -> &ScriptedModel { + &self.model + } + + fn instance(&self) -> PathBuf { + self.root.path().join("instance") + } +} + +impl Subject for LiveSubject { + fn harness(&self) -> Arc { + let program = Program::new(self.root.path().join("openhuman-core"), PINNED); + Arc::new(OpenHumanHarness::new(program).with_options(options())) + } + + fn seat(&self) -> SeatPlan { + let endpoint = format!("http://127.0.0.1:{}/v1", self.model.port); + SeatPlan::new(seat(&endpoint), self.instance()) + } + + fn endpoint(&self) -> ToolEndpoint { + let mut tools = vec!["hivemind_post".to_owned()]; + if self.fault.load(Ordering::Relaxed) == 2 { + // The stub serves no such tool, so the instance never lists it. + tools.push("hivemind_absent".to_owned()); + } + let url = format!("http://127.0.0.1:{}/mcp", self.fixture.port); + ToolEndpoint::new("hivea", url, "seat-a-token", tools) + } + + fn script(&self, steps: &[ModelStep]) { + self.model.script(steps); + } + + fn model_calls(&self) -> Vec { + self.model.calls() + } + + fn lose_sessions(&self) { + let workspace = self.instance().join("state/ws/workspace"); + for store in [ + "session_raw", + "sessions", + "session_db", + "memory/conversations", + ] { + let _ = fs::remove_dir_all(workspace.join(store)); + } + } + + /// The binary shows its model only what the exact allowlist names, so an + /// extra tool can only come from another config: that is what `Extra` + /// writes. `Missing` names a tool the stub does not serve. + fn offer(&self, fault: ToolFault) { + let (code, misconfigured) = match fault { + ToolFault::None => (0, false), + ToolFault::Extra => (1, true), + ToolFault::Missing => (2, false), + }; + self.fault.store(code, Ordering::Relaxed); + let marker = self.root.path().join("misconfigured"); + let _ = if misconfigured { + fs::write(marker, "") + } else { + fs::remove_file(marker) + }; + } + + fn misconfigure(&self) { + done(&fs::write(self.root.path().join("misconfigured"), "")); + } + + /// Built-in tools are off, so nothing can make this instance spawn. + fn escapee(&self) -> EscapeFuture { + Box::pin(async { None }) + } + + fn processes(&self) -> Vec { + processes_in(&self.instance()) + } + + fn turn_limit(&self) -> Duration { + Duration::from_secs(20) + } + + fn patience(&self) -> Duration { + Duration::from_secs(90) + } +} + +impl Drop for LiveSubject { + fn drop(&mut self) { + kill_all(self.processes()); + } +} diff --git a/crates/tinyhivemind-openhuman-process/tests/support/README.md b/crates/tinyhivemind-openhuman-process/tests/support/README.md new file mode 100644 index 00000000..1e13b514 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/support/README.md @@ -0,0 +1,6 @@ +# Support + +| File | Purpose | +| --- | --- | +| `http.rs` | A small HTTP/1.1 server: JSON answers, close-delimited streams, hang-up notice. | +| `seat.rs` | The test seat, and the processes of an instance directory. | diff --git a/crates/tinyhivemind-openhuman-process/tests/support/http.rs b/crates/tinyhivemind-openhuman-process/tests/support/http.rs new file mode 100644 index 00000000..7145bb72 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/support/http.rs @@ -0,0 +1,209 @@ +//! A small HTTP/1.1 server for the fakes: one request per connection, a JSON +//! answer or a close-delimited stream, and notice when the client hangs up. +//! +//! Hand-written over Tokio so that the fake child needs no web framework. It +//! reads a request line, headers and a `content-length` body; nothing else of +//! HTTP is needed by the clients it serves. +use serde_json::Value; +use std::future::Future; +use std::sync::Arc; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::mpsc; + +/// Largest request the fakes read. +const LIMIT: usize = 4 * 1024 * 1024; + +/// One request. +#[derive(Clone, Debug, Default)] +pub(crate) struct Request { + pub(crate) method: String, + pub(crate) path: String, + pub(crate) query: String, + pub(crate) headers: Vec<(String, String)>, + pub(crate) body: Vec, +} + +impl Request { + /// The header `name`, case-insensitively. + pub(crate) fn header(&self, name: &str) -> Option<&str> { + let found = self + .headers + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(name)); + found.map(|(_, value)| value.as_str()) + } + + /// The query parameter `name`, percent-decoded. + pub(crate) fn param(&self, name: &str) -> Option { + self.query.split('&').find_map(|pair| { + let (key, value) = pair.split_once('=')?; + (key == name).then(|| decode(value)) + }) + } + + /// The body as JSON, or null. + pub(crate) fn json(&self) -> Value { + serde_json::from_slice(&self.body).unwrap_or(Value::Null) + } +} + +fn decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + let hex = bytes.get(index + 1..index + 3).and_then(|hex| { + let hex = std::str::from_utf8(hex).ok()?; + u8::from_str_radix(hex, 16).ok() + }); + match (bytes[index], hex) { + (b'%', Some(byte)) => { + out.push(byte); + index += 3; + } + (b'+', _) => { + out.push(b' '); + index += 1; + } + (byte, _) => { + out.push(byte); + index += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// An answer. +#[derive(Debug)] +pub(crate) enum Reply { + /// A status and a JSON body. + Json(u16, Value), + /// `text/event-stream`, one chunk per message, until the sender is + /// dropped. Once the client hangs up the receiver is dropped, which the + /// sender sees as `closed()`. + Stream(mpsc::Receiver), +} + +/// Serve `handler` on `listener` until the task is dropped. +pub(crate) async fn serve(listener: TcpListener, handler: H) +where + H: Fn(Request) -> F + Send + Sync + 'static, + F: Future + Send + 'static, +{ + let handler = Arc::new(handler); + while let Ok((stream, _)) = listener.accept().await { + let handler = handler.clone(); + tokio::spawn(async move { + let _ = connection(stream, handler.as_ref()).await; + }); + } +} + +async fn connection(mut stream: TcpStream, handler: &H) -> std::io::Result<()> +where + H: Fn(Request) -> F, + F: Future, +{ + let Some(request) = read(&mut stream).await? else { + return Ok(()); + }; + match handler(request).await { + Reply::Json(status, body) => { + let body = body.to_string(); + let head = format!( + "HTTP/1.1 {status} {}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", + reason(status), + body.len() + ); + stream.write_all(head.as_bytes()).await?; + stream.write_all(body.as_bytes()).await?; + stream.shutdown().await + } + Reply::Stream(mut chunks) => { + let head = "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncache-control: no-cache\r\nconnection: close\r\n\r\n"; + stream.write_all(head.as_bytes()).await?; + stream.flush().await?; + let (mut reader, mut writer) = stream.into_split(); + let mut scratch = [0_u8; 256]; + loop { + tokio::select! { + chunk = chunks.recv() => match chunk { + Some(chunk) => { + writer.write_all(chunk.as_bytes()).await?; + writer.flush().await?; + } + None => return writer.shutdown().await, + }, + read = reader.read(&mut scratch) => { + if matches!(read, Ok(0) | Err(_)) { + // Hung up: dropping `chunks` tells the sender. + return Ok(()); + } + } + } + } + } + } +} + +fn reason(status: u16) -> &'static str { + match status { + 200 => "OK", + 401 => "Unauthorized", + 404 => "Not Found", + _ => "Status", + } +} + +async fn read(stream: &mut TcpStream) -> std::io::Result> { + let mut buffer = Vec::new(); + let mut chunk = [0_u8; 8192]; + let head_end = loop { + if let Some(end) = buffer.windows(4).position(|window| window == b"\r\n\r\n") { + break end; + } + let read = stream.read(&mut chunk).await?; + if read == 0 || buffer.len() > LIMIT { + return Ok(None); + } + buffer.extend_from_slice(&chunk[..read]); + }; + let head = String::from_utf8_lossy(&buffer[..head_end]).into_owned(); + let mut lines = head.split("\r\n"); + let mut first = lines.next().unwrap_or_default().split(' '); + let method = first.next().unwrap_or_default().to_owned(); + let target = first.next().unwrap_or_default(); + let (path, query) = target.split_once('?').unwrap_or((target, "")); + let headers: Vec<(String, String)> = lines + .filter_map(|line| { + let (key, value) = line.split_once(':')?; + Some((key.trim().to_owned(), value.trim().to_owned())) + }) + .collect(); + let mut request = Request { + method, + path: path.to_owned(), + query: query.to_owned(), + headers, + body: buffer[head_end + 4..].to_vec(), + }; + let length: usize = request + .header("content-length") + .and_then(|length| length.parse().ok()) + .unwrap_or(0); + while request.body.len() < length.min(LIMIT) { + let read = stream.read(&mut chunk).await?; + if read == 0 { + return Ok(None); + } + request.body.extend_from_slice(&chunk[..read]); + } + Ok(Some(request)) +} + +/// One SSE message. +pub(crate) fn event(name: &str, data: &Value) -> String { + format!("event: {name}\ndata: {data}\n\n") +} diff --git a/crates/tinyhivemind-openhuman-process/tests/support/seat.rs b/crates/tinyhivemind-openhuman-process/tests/support/seat.rs new file mode 100644 index 00000000..9170ee09 --- /dev/null +++ b/crates/tinyhivemind-openhuman-process/tests/support/seat.rs @@ -0,0 +1,94 @@ +//! What both conformance subjects share: the seat, and the processes of an +//! instance directory. +use rustix::process::{Pid, Signal, kill_process}; +use serde_json::Value; +use std::fmt::Debug; +use std::fs; +use std::path::Path; +use tinyhivemind_lang::{ + LoweredModel, LoweredSeat, LoweredSeatIntegration, Model, Provider, ProviderKind, +}; + +/// The result of something the test itself does, which has to work. +pub(crate) fn done(result: &Result) { + assert!(result.is_ok(), "{result:?}"); +} + +/// A seat on an `openai` endpoint at `endpoint`. +pub(crate) fn seat(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: "scout".into(), + label: "Scout".into(), + template: "seat".into(), + config: Value::Null, + prompt: "You scout.".into(), + memory: None, + integration: LoweredSeatIntegration { + model: Some(LoweredModel { + model, + provider: Some(provider), + }), + ..LoweredSeatIntegration::default() + }, + } +} + +/// Whatever runs in `instance`. +pub(crate) 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() +} + +/// Kill what a faulty run left behind. +pub(crate) fn kill_all(pids: Vec) { + for pid in pids { + if let Some(pid) = Pid::from_raw(pid.cast_signed()) { + let _ = kill_process(pid, Signal::KILL); + } + } +} + +/// A turn of the test seat, from the host. +pub(crate) fn request(turn: &str, session: Option<&str>) -> tinyhivemind_hives::TurnRequest { + use tinyhivemind_hives::{Destination, Message, TurnRequest}; + TurnRequest { + turn_id: turn.into(), + scheduled_job_id: None, + teammates: Vec::new(), + agent_id: "scout".into(), + session_id: session.map(Into::into), + messages: vec![Message { + scheduled_job_id: None, + message_id: format!("message-{turn}"), + sequence: 1, + sender: tinyhivemind_hives::HOST_ID.into(), + destination: Destination::Agent("scout".into()), + body: format!("turn {turn}"), + thread: None, + episode_id: None, + only_for: Vec::new(), + }], + memberships: Vec::new(), + episode: None, + resumption: None, + } +} diff --git a/docs/plans/2026-11-25-process-harnesses.md b/docs/plans/2026-11-25-process-harnesses.md index c13cbe8c..3ef77b45 100644 --- a/docs/plans/2026-11-25-process-harnesses.md +++ b/docs/plans/2026-11-25-process-harnesses.md @@ -72,9 +72,12 @@ cases are diagnosed at their location; a roster-only edit cannot change `harness - **4a. `tinyhivemind-openclaw`:** handshake with Ed25519 device identity, `agent` and its second response, `chat.abort`, generated config, recovery hold. -- **4b. OpenHuman process runner** in `tinyhivemind-openhuman`, beside the linked - path: workspace and config per seat, `web_chat` and `/events`, `web_cancel`, - start-up verification, approvals through `list_pending` and `decide`. +- **4b. OpenHuman process runner** in `tinyhivemind-openhuman-process`, a crate + beside the linked adapter rather than a module of it, so that step 6 deletes + the adapter without touching it: workspace and config per seat, `web_chat` and + `/events`, `web_cancel`, start-up verification, approvals through the + `approval_request` event and `decide`. Done: conformance offline and `live_*` + on 0.64.15. - **4c. `tinyhivemind-codex`:** app-server over stdio, pinned catalog, per-thread MCP. Medulla's `codex_app_server` is the reference for framing; its silent new thread on a failed resume is not copied. diff --git a/docs/specs/harnesses.md b/docs/specs/harnesses.md index a09d1de0..92e8b97c 100644 --- a/docs/specs/harnesses.md +++ b/docs/specs/harnesses.md @@ -5,16 +5,17 @@ Boundary: [ADR 0035](../adr/0035-a-harness-is-a-process.md), [ADR 0036](../adr/0036-hive-tools-are-served-over-loopback-mcp.md). Evidence: [the harness spike](../experiments/2026-11-25-process-harnesses.md). -Implemented so far, by steps 1, 2 and 3 of the plan: the harness-neutral host -crate, the harness port with the seat rules below, start verification, process -supervision on Linux, a conformance suite that a scripted fake harness passes, -the coordinator's per-turn call record, the `tinyhivemind-mcp` server, and the -package schema: the `harnesses` section, `harness` on runtime, profile and seat, -the capability table in `tinyhivemind-lang` and its `check` diagnostics. No -client for a real harness exists yet, and the server does not proxy package MCP -servers. Until the plan's removal phase lands, the linked OpenHuman adapter -remains the way a package is deployed, and it refuses a seat whose harness is -not `openhuman`. +Implemented so far, by steps 1, 2, 3 and 4b of the plan: the harness-neutral +host crate, the harness port with the seat rules below, start verification, +process supervision on Linux, a conformance suite that a scripted fake harness +passes, the coordinator's per-turn call record, the `tinyhivemind-mcp` server, +the package schema (the `harnesses` section, `harness` on runtime, profile and +seat, the capability table in `tinyhivemind-lang` and its `check` diagnostics), +and the `openhuman` client, `crates/tinyhivemind-openhuman-process`, which passes +the conformance suite offline and on the pinned binary. No deployment starts a +process harness yet, and the server does not proxy package MCP servers. Until the +plan's removal phase lands, the linked OpenHuman adapter remains the way a +package is deployed, and it refuses a seat whose harness is not `openhuman`. ## Problem @@ -431,6 +432,46 @@ reports it as a normal end. Until that is configurable, a package asking for mor iterations is rejected for this kind, and a turn that reaches the cap is reported as failed. The runner counts `iteration_start` events to tell. +What implementing it on 0.64.15 settled: + +- No RPC reports the tools a custom agent's turn offers + (`agent_list_definitions` and `agent_get_definition` cover built-in agents; + the offline `openhuman agent dump-prompt --with-tools` CLI reports a + definition's tools but not a session's). So the model-visible list is + computed from the effective config the way `resolved_scope` in + `agent/tinyagents/host/definition_registry.rs` builds it: the chat agent's + allowlist, of the tools the instance has; every deferred tool if the list + names `tool_search`; the session's delegation tools for an agent with + subagents; `juice_retrieve` while compaction or the orchestrator's summary + stage is on; the REPL tools while results are stored behind a handle; and + `extra_tools`. A chat agent other than the written one counts as a + built-in's set. Any of these fails the start. The config turns compaction + off, since it defaults on. The live gate test checks the list at the model. +- A turn that fails before its thread has a transcript reports no session, + as an error, so the next turn starts the thread rather than failing to + resume one that never existed. A failure on a thread with a transcript is a + failed turn in that session. +- The hashed names are known only to a running instance, so a start is two: + one whose allowlist matches nothing, to read them, and the verified one. +- A session is a `thread_id`, the same for a seat's life. A turn that names a + session runs only if `threads_transcript_get` has a transcript for it; + otherwise the turn fails as a resume failure and nothing reaches the model. +- Every turn has its own `client_id`, and its `/events` subscription is open + before `channel_web_chat` is called, since the first events can precede its + answer. Events are taken only for the returned `request_id`, except + `approval_request`, whose `request_id` is the approval's. +- A cancelled or failed turn leaves no message in the thread. +- An approval the harness asks for goes to the seat's approver, which has a + time limit and is a denial past it. `approval_decide` takes no reason, so a + denial's reason is not passed on. Approvals still pending when a turn starts + are left by one that is over, and are denied first. A `chat_error` message is + cut to one line of at most 200 characters before it becomes the failure. +- The top-level `embeddings_provider` is rewritten to the hosted default on + load whatever the file says, so it is neither written nor compared; memory + is off, so nothing embeds. The binary also carries a compiled-in Sentry DSN + that no config or environment entry empties, which is one more reason live + runs block egress. + **OpenClaw.** Tool search and code mode off; `tools.allow` exactly the seat's server; the deny groups recorded in the experiment; agent-to-agent off. After a crash, do not admit a turn for a seat until its recovery is known to be settled. @@ -448,7 +489,8 @@ Login tokens are a host secret and enter only the instance's environment. ## Pins -A lock file records version, target and sha256 for each kind. A script fetches +A lock file records version, target and sha256 for each kind: `harnesses.lock` +at the repository root. A script, `.github/scripts/fetch-harness.sh`, fetches and verifies; the library takes a path. Live tests run against exactly the pin, with outbound network blocked except to the model endpoint under test. diff --git a/harnesses.lock b/harnesses.lock new file mode 100644 index 00000000..45ae7b08 --- /dev/null +++ b/harnesses.lock @@ -0,0 +1,21 @@ +# The harness binaries process runners are tested against, one entry per +# kind and target. Library code never downloads: `.github/scripts/fetch-harness.sh` +# fetches an entry's asset, checks its sha256 (and the binary's, where it is +# recorded), and prints the binary's path for the host to pass in. +# Spec: docs/specs/harnesses.md#pins. + +[[openhuman]] +version = "0.64.15" +target = "x86_64-unknown-linux-gnu" +url = "https://github.com/tinyhumansai/openhuman/releases/download/v0.64.15/openhuman-core-0.64.15-x86_64-unknown-linux-gnu.tar.gz" +sha256 = "f86ae0157b4ed28767c580c443e04027b62fe14e6f3260786f44cd265a242587" +binary = "openhuman-core" +binary_sha256 = "4788efd57d66ee43ae398c99875a2c84e006691e9fbefab60e5a22c0fb7fefce" + +[[openhuman]] +version = "0.64.15" +target = "aarch64-unknown-linux-gnu" +url = "https://github.com/tinyhumansai/openhuman/releases/download/v0.64.15/openhuman-core-0.64.15-aarch64-unknown-linux-gnu.tar.gz" +sha256 = "eabac98af5f1feb711b4ffd48185aa06a233fa6bbcd1bcd4d733397dace03b9b" +binary = "openhuman-core" +binary_sha256 = "17486cc1f85a58f2b4502ee41cad44b6aa11ee8058c3bad63dbc9994578c6634"